docs: update toolkit guides (#24992)

This commit is contained in:
ccurme 2024-08-02 15:51:05 -04:00 committed by GitHub
parent 22c1a4041b
commit acba38a18e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 97 additions and 230 deletions

View File

@ -122,7 +122,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 5, "execution_count": 2,
"metadata": { "metadata": {
"tags": [] "tags": []
}, },
@ -130,14 +130,14 @@
{ {
"data": { "data": {
"text/plain": [ "text/plain": [
"[GmailCreateDraft(name='create_gmail_draft', description='Use this tool to create a draft email with the provided message fields.', args_schema=<class 'langchain_community.tools.gmail.create_draft.CreateDraftSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n", "[GmailCreateDraft(api_resource=<googleapiclient.discovery.Resource object at 0x1094509d0>),\n",
" GmailSendMessage(name='send_gmail_message', description='Use this tool to send email messages. The input is the message, recipents', args_schema=None, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n", " GmailSendMessage(api_resource=<googleapiclient.discovery.Resource object at 0x1094509d0>),\n",
" GmailSearch(name='search_gmail', description=('Use this tool to search for email messages or threads. The input must be a valid Gmail query. The output is a JSON list of the requested resource.',), args_schema=<class 'langchain_community.tools.gmail.search.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n", " GmailSearch(api_resource=<googleapiclient.discovery.Resource object at 0x1094509d0>),\n",
" GmailGetMessage(name='get_gmail_message', description='Use this tool to fetch an email by message ID. Returns the thread ID, snipet, body, subject, and sender.', args_schema=<class 'langchain_community.tools.gmail.get_message.SearchArgsSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>),\n", " GmailGetMessage(api_resource=<googleapiclient.discovery.Resource object at 0x1094509d0>),\n",
" GmailGetThread(name='get_gmail_thread', description=('Use this tool to search for email messages. The input must be a valid Gmail query. The output is a JSON list of messages.',), args_schema=<class 'langchain_community.tools.gmail.get_thread.GetThreadSchema'>, return_direct=False, verbose=False, callbacks=None, callback_manager=None, api_resource=<googleapiclient.discovery.Resource object at 0x10e5c6d10>)]" " GmailGetThread(api_resource=<googleapiclient.discovery.Resource object at 0x1094509d0>)]"
] ]
}, },
"execution_count": 5, "execution_count": 2,
"metadata": {}, "metadata": {},
"output_type": "execute_result" "output_type": "execute_result"
} }
@ -164,142 +164,96 @@
"source": [ "source": [
"## Use within an agent\n", "## Use within an agent\n",
"\n", "\n",
"We show here how to use it as part of an [agent](/docs/tutorials/agents). We use the OpenAI Functions Agent, so we will need to setup and install the required dependencies for that. We will also use [LangSmith Hub](https://smith.langchain.com/hub) to pull the prompt from, so we will need to install that.\n", "Below we show how to incorporate the toolkit into an [agent](/docs/tutorials/agents).\n",
"\n", "\n",
"```bash\n", "We will need a LLM or chat model:\n",
"pip install -U langchain-openai langchainhub\n", "\n",
"```{=mdx}\n",
"import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
"\n",
"<ChatModelTabs customVarName=\"llm\" />\n",
"```" "```"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": null, "execution_count": 3,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"import getpass\n", "# | output: false\n",
"import os\n", "# | echo: false\n",
"\n", "\n",
"os.environ[\"OPENAI_API_KEY\"] = getpass.getpass()" "from langchain_openai import ChatOpenAI\n",
"\n",
"llm = ChatOpenAI(model=\"gpt-3.5-turbo-0125\", temperature=0)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 1, "execution_count": 4,
"metadata": {
"tags": []
},
"outputs": [],
"source": [
"from langchain import hub\n",
"from langchain.agents import AgentExecutor, create_openai_functions_agent\n",
"from langchain_openai import ChatOpenAI"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
"instructions = \"\"\"You are an assistant.\"\"\"\n", "from langgraph.prebuilt import create_react_agent\n",
"base_prompt = hub.pull(\"langchain-ai/openai-functions-template\")\n", "\n",
"prompt = base_prompt.partial(instructions=instructions)" "agent_executor = create_react_agent(llm, tools)"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 9, "execution_count": 5,
"metadata": {}, "metadata": {},
"outputs": [],
"source": [
"llm = ChatOpenAI(temperature=0)"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"agent = create_openai_functions_agent(llm, toolkit.get_tools(), prompt)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [],
"source": [
"agent_executor = AgentExecutor(\n",
" agent=agent,\n",
" tools=toolkit.get_tools(),\n",
" # This is set to False to prevent information about my email showing up on the screen\n",
" # Normally, it is helpful to have it set to True however.\n",
" verbose=False,\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {
"tags": []
},
"outputs": [ "outputs": [
{ {
"data": { "name": "stdout",
"text/plain": [ "output_type": "stream",
"{'input': 'Create a gmail draft for me to edit of a letter from the perspective of a sentient parrot who is looking to collaborate on some research with her estranged friend, a cat. Under no circumstances may you send the message, however.',\n", "text": [
" 'output': 'I have created a draft email for you to edit. Please find the draft in your Gmail drafts folder. Remember, under no circumstances should you send the message.'}" "================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Draft an email to fake@fake.com thanking them for coffee.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" create_gmail_draft (call_slGkYKZKA6h3Mf1CraUBzs6M)\n",
" Call ID: call_slGkYKZKA6h3Mf1CraUBzs6M\n",
" Args:\n",
" message: Dear Fake,\n",
"\n",
"I wanted to take a moment to thank you for the coffee yesterday. It was a pleasure catching up with you. Let's do it again soon!\n",
"\n",
"Best regards,\n",
"[Your Name]\n",
" to: ['fake@fake.com']\n",
" subject: Thank You for the Coffee\n",
"=================================\u001b[1m Tool Message \u001b[0m=================================\n",
"Name: create_gmail_draft\n",
"\n",
"Draft created. Draft Id: r-7233782721440261513\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"I have drafted an email to fake@fake.com thanking them for the coffee. You can review and send it from your email draft with the subject \"Thank You for the Coffee\".\n"
] ]
},
"execution_count": 19,
"metadata": {},
"output_type": "execute_result"
} }
], ],
"source": [ "source": [
"agent_executor.invoke(\n", "example_query = \"Draft an email to fake@fake.com thanking them for coffee.\"\n",
" {\n", "\n",
" \"input\": \"Create a gmail draft for me to edit of a letter from the perspective of a sentient parrot\"\n", "events = agent_executor.stream(\n",
" \" who is looking to collaborate on some research with her\"\n", " {\"messages\": [(\"user\", example_query)]},\n",
" \" estranged friend, a cat. Under no circumstances may you send the message, however.\"\n", " stream_mode=\"values\",\n",
" }\n", ")\n",
")" "for event in events:\n",
" event[\"messages\"][-1].pretty_print()"
] ]
}, },
{ {
"cell_type": "code", "cell_type": "markdown",
"execution_count": 20,
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"{'input': 'Could you search in my drafts for the latest email? what is the title?',\n",
" 'output': 'The latest email in your drafts is titled \"Collaborative Research Proposal\".'}"
]
},
"execution_count": 20,
"metadata": {}, "metadata": {},
"output_type": "execute_result"
}
],
"source": [ "source": [
"agent_executor.invoke(\n", "## API reference\n",
" {\"input\": \"Could you search in my drafts for the latest email? what is the title?\"}\n", "\n",
")" "For detailed documentation of all `GmailToolkit` features and configurations head to the [API reference](https://api.python.langchain.com/en/latest/agent_toolkits/langchain_community.agent_toolkits.slack.toolkit.SlackToolkit.html)."
] ]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
} }
], ],
"metadata": { "metadata": {

View File

@ -123,10 +123,10 @@
{ {
"data": { "data": {
"text/plain": [ "text/plain": [
"[SlackGetChannel(client=<slack_sdk.web.client.WebClient object at 0x10ce3a4d0>),\n", "[SlackGetChannel(client=<slack_sdk.web.client.WebClient object at 0x113caa8c0>),\n",
" SlackGetMessage(client=<slack_sdk.web.client.WebClient object at 0x10ce3a0e0>),\n", " SlackGetMessage(client=<slack_sdk.web.client.WebClient object at 0x113caa4d0>),\n",
" SlackScheduleMessage(client=<slack_sdk.web.client.WebClient object at 0x10ce3a050>),\n", " SlackScheduleMessage(client=<slack_sdk.web.client.WebClient object at 0x113caa440>),\n",
" SlackSendMessage(client=<slack_sdk.web.client.WebClient object at 0x10ce3a020>)]" " SlackSendMessage(client=<slack_sdk.web.client.WebClient object at 0x113caa410>)]"
] ]
}, },
"execution_count": 3, "execution_count": 3,
@ -163,7 +163,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 4, "execution_count": 7,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [],
"source": [ "source": [
@ -177,7 +177,7 @@
}, },
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 6, "execution_count": 5,
"metadata": {}, "metadata": {},
"outputs": [ "outputs": [
{ {
@ -189,12 +189,12 @@
"When was the #general channel created?\n", "When was the #general channel created?\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n", "Tool Calls:\n",
" get_channelid_name_dict (call_mINmB55OWDIkXykGXZXaL5Ar)\n", " get_channelid_name_dict (call_NXDkALjoOx97uF1v0CoZTqtJ)\n",
" Call ID: call_mINmB55OWDIkXykGXZXaL5Ar\n", " Call ID: call_NXDkALjoOx97uF1v0CoZTqtJ\n",
" Args:\n", " Args:\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n", "\n",
"The #general channel was created on Unix timestamp 1671043305, which corresponds to \"Mon, 12 Dec 2022 18:41:45 GMT\" in human-readable format.\n" "The #general channel was created on timestamp 1671043305.\n"
] ]
} }
], ],
@ -211,129 +211,42 @@
" event[\"messages\"][-1].pretty_print()" " event[\"messages\"][-1].pretty_print()"
] ]
}, },
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Example with AgentExecutor:"
]
},
{ {
"cell_type": "code", "cell_type": "code",
"execution_count": 11, "execution_count": 13,
"metadata": {}, "metadata": {},
"outputs": [], "outputs": [
"source": [
"from langchain import hub\n",
"from langchain.agents import AgentExecutor, create_openai_tools_agent\n",
"from langchain_openai import ChatOpenAI"
]
},
{ {
"cell_type": "code", "name": "stdout",
"execution_count": 12, "output_type": "stream",
"metadata": {}, "text": [
"outputs": [], "================================\u001b[1m Human Message \u001b[0m=================================\n",
"\n",
"Send a friendly greeting to channel C072Q1LP4QM.\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"Tool Calls:\n",
" send_message (call_xQxpv4wFeAZNZgSBJRIuaizi)\n",
" Call ID: call_xQxpv4wFeAZNZgSBJRIuaizi\n",
" Args:\n",
" message: Hello! Have a great day!\n",
" channel: C072Q1LP4QM\n",
"==================================\u001b[1m Ai Message \u001b[0m==================================\n",
"\n",
"I have sent a friendly greeting to the channel C072Q1LP4QM.\n"
]
}
],
"source": [ "source": [
"llm = ChatOpenAI(temperature=0, model=\"gpt-4\")\n", "example_query = \"Send a friendly greeting to channel C072Q1LP4QM.\"\n",
"prompt = hub.pull(\"hwchase17/openai-tools-agent\")\n", "\n",
"agent = create_openai_tools_agent(\n", "events = agent_executor.stream(\n",
" tools=toolkit.get_tools(),\n", " {\"messages\": [(\"user\", example_query)]},\n",
" llm=llm,\n", " stream_mode=\"values\",\n",
" prompt=prompt,\n",
")\n", ")\n",
"agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)" "for event in events:\n",
] " message = event[\"messages\"][-1]\n",
}, " if message.type != \"tool\": # mask sensitive information\n",
{ " event[\"messages\"][-1].pretty_print()"
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"agent_executor.invoke(\n",
" {\n",
" \"input\": \"Send a greeting to my coworkers in the #general channel. Note use `channel` as key of channel id, and `message` as key of content to sent in the channel.\"\n",
" }\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI need to get the list of channels in the workspace.\n",
"Action: get_channelid_name_dict\n",
"Action Input: {}\u001b[0m\u001b[36;1m\u001b[1;3m[{\"id\": \"C052SCUP4UD\", \"name\": \"general\", \"created\": 1681297313, \"num_members\": 1}, {\"id\": \"C052VBBU4M8\", \"name\": \"test-bots\", \"created\": 1681297343, \"num_members\": 2}, {\"id\": \"C053805TNUR\", \"name\": \"random\", \"created\": 1681297313, \"num_members\": 2}]\u001b[0m\u001b[32;1m\u001b[1;3mI now have the list of channels and their names.\n",
"Final Answer: There are 3 channels in the workspace. Their names are \"general\", \"test-bots\", and \"random\".\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"{'input': 'How many channels are in the workspace? Please list out their names.',\n",
" 'output': 'There are 3 channels in the workspace. Their names are \"general\", \"test-bots\", and \"random\".'}"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.invoke(\n",
" {\"input\": \"How many channels are in the workspace? Please list out their names.\"}\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mFirst, I need to identify the channel ID for the #introductions channel.\n",
"Action: get_channelid_name_dict\n",
"Action Input: None\u001b[0m\u001b[36;1m\u001b[1;3m[{\"id\": \"C052SCUP4UD\", \"name\": \"general\", \"created\": 1681297313, \"num_members\": 1}, {\"id\": \"C052VBBU4M8\", \"name\": \"test-bots\", \"created\": 1681297343, \"num_members\": 2}, {\"id\": \"C053805TNUR\", \"name\": \"random\", \"created\": 1681297313, \"num_members\": 2}]\u001b[0m\u001b[32;1m\u001b[1;3mThe #introductions channel is not listed in the observed channels. I need to inform the user that the #introductions channel does not exist or is not accessible.\n",
"Final Answer: The #introductions channel does not exist or is not accessible.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
},
{
"data": {
"text/plain": [
"{'input': 'Tell me the number of messages sent in the #introductions channel from the past month.',\n",
" 'output': 'The #introductions channel does not exist or is not accessible.'}"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"agent_executor.invoke(\n",
" {\n",
" \"input\": \"Tell me the number of messages sent in the #introductions channel from the past month.\"\n",
" }\n",
")"
] ]
}, },
{ {
@ -342,7 +255,7 @@
"source": [ "source": [
"## API reference\n", "## API reference\n",
"\n", "\n",
"For detailed documentation of all __ModuleName__Toolkit features and configurations head to the [API reference](https://api.python.langchain.com/en/latest/agent_toolkits/langchain_community.agent_toolkits.slack.toolkit.SlackToolkit.html)." "For detailed documentation of all `SlackToolkit` features and configurations head to the [API reference](https://api.python.langchain.com/en/latest/agent_toolkits/langchain_community.agent_toolkits.slack.toolkit.SlackToolkit.html)."
] ]
} }
], ],