Haven't gotten to all of them, but this:
- Updates some of the tools notebooks to actually instantiate a tool
(many just show a 'utility' rather than a tool. More changes to come in
separate PR)
- Move the `Tool` and decorator definitions to `langchain/tools/base.py`
(but still export from `langchain.agents`)
- Add scene explain to the load_tools() function
- Add unit tests for public apis for the langchain.tools and langchain.agents modules
"- name (str), is required and must be unique within a set of tools provided to an agent\n",
"- description (str), is optional but recommended, as it is used by an agent to determine tool use\n",
"- return_direct (bool), defaults to False\n",
"- args_schema (Pydantic BaseModel), is optional but recommended, can be used to provide more information or validation for expected parameters.\n",
"- args_schema (Pydantic BaseModel), is optional but recommended, can be used to provide more information (e.g., few-shot examples) or validation for expected parameters.\n",
"\n",
"The function that should be called when the tool is selected should return a single string.\n",
"\n",
"There are two ways to define a tool, we will cover both in the example below."
"There are two main ways to define a tool, we will cover both in the example below."
"First, we show how to create completely new tools from scratch.\n",
"## Completely New Tools - String Input and Output\n",
"\n",
"The simplest tools accept a single query string and return a string output. If your tool function requires multiple arguments, you might want to skip down to the `StructuredTool` section below.\n",
"\n",
"There are two ways to do this: either by using the Tool dataclass, or by subclassing the BaseTool class."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "b63fcc3b",
"metadata": {},
"source": [
"### Tool dataclass"
"### Tool dataclass\n",
"\n",
"The 'Tool' dataclass wraps functions that accept a single string input and returns a string output."
]
},
{
@ -81,19 +86,46 @@
"metadata": {
"tags": []
},
"outputs": [],
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"/Users/wfh/code/lc/lckg/langchain/chains/llm_math/base.py:50: UserWarning: Directly instantiating an LLMMathChain with an llm is deprecated. Please instantiate with llm_chain argument or using the from_llm class method.\n",
" description=\"useful for when you need to answer questions about current events\"\n",
" # coroutine= ... <- you can specify an async method if desired as well\n",
" ),\n",
"]\n",
"# You can also define an args_schema to provide more information about inputs\n",
"]"
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "e9b560f7",
"metadata": {},
"source": [
"You can also define a custom `args_schema`` to provide more information about inputs."
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "631361e7",
"metadata": {},
"outputs": [],
"source": [
"from pydantic import BaseModel, Field\n",
"\n",
"class CalculatorInput(BaseModel):\n",
@ -101,18 +133,19 @@
" \n",
"\n",
"tools.append(\n",
" Tool(\n",
" name=\"Calculator\",\n",
" Tool.from_function(\n",
" func=llm_math_chain.run,\n",
" name=\"Calculator\",\n",
" description=\"useful for when you need to answer questions about math\",\n",
" args_schema=CalculatorInput\n",
" # coroutine= ... <- you can specify an async method if desired as well\n",
" )\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 5,
"id": "5b93047d",
"metadata": {
"tags": []
@ -126,7 +159,7 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 6,
"id": "6f96a891",
"metadata": {
"tags": []
@ -141,7 +174,17 @@
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age\n",
"Action: Search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\u001b[36;1m\u001b[1;3mDiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years.\u001b[0m\u001b[32;1m\u001b[1;3mI need to find out Camila Morrone's current age\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI still need to find out his current girlfriend's name and age\n",
"Action: Search\n",
"Action Input: \"Leo DiCaprio current girlfriend\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mJust Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date!\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow that I know his girlfriend's name is Camila Morrone, I need to find her current age\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer\n",
"Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99.\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@ -162,10 +207,10 @@
{
"data": {
"text/plain": [
"'3.991298452658078'"
"\"Camila Morrone's current age raised to the 0.43 power is approximately 3.99.\""
]
},
"execution_count": 5,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@ -175,71 +220,65 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "6f12eaf0",
"metadata": {},
"source": [
"### Subclassing the BaseTool class"
"### Subclassing the BaseTool class\n",
"\n",
"You can also directly subclass `BaseTool`. This is useful if you want more control over the instance variables or if you want to propagate callbacks to nested chains or other tools."
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age\n",
"Action: Search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\u001b[36;1m\u001b[1;3mDiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years.\u001b[0m\u001b[32;1m\u001b[1;3mI need to find out Camila Morrone's current age\n",
"\u001b[32;1m\u001b[1;3mI need to use custom_search to find out who Leo DiCaprio's girlfriend is, and then use the Calculator to raise her age to the 0.43 power.\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to find out the current age of Eden Polani.\n",
"Action: custom_search\n",
"Action Input: \"Eden Polani age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3m19 years old\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mNow I can use the Calculator to raise her age to the 0.43 power.\n",
"Action: Calculator\n",
"Action Input: 25^(0.43)\u001b[0m\n",
"Action Input: 19 ^ 0.43\u001b[0m\n",
"\n",
"\u001b[1m> Entering new LLMMathChain chain...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI now know the final answer.\n",
"Final Answer: 3.547023357958959\u001b[0m\n",
"\n",
"\u001b[1m> Finished chain.\u001b[0m\n"
]
@ -281,7 +328,7 @@
{
"data": {
"text/plain": [
"'3.991298452658078'"
"'3.547023357958959'"
]
},
"execution_count": 9,
@ -312,34 +359,13 @@
},
"outputs": [],
"source": [
"from langchain.agents import tool\n",
"from langchain.tools import tool\n",
"\n",
"@tool\n",
"def search_api(query: str) -> str:\n",
" \"\"\"Searches the API for the query.\"\"\"\n",
" return f\"Results for query {query}\""
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "0a23b91b",
"metadata": {
"tags": []
},
"outputs": [
{
"data": {
"text/plain": [
"Tool(name='search_api', description='search_api(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd664c0>, coroutine=None)"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
" return f\"Results for query {query}\"\n",
"\n",
"search_api"
]
},
@ -433,18 +459,149 @@
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "61d2e80b",
"metadata": {},
"source": [
"## Custom Structured Tools\n",
"\n",
"If your functions require more structured arguments, you can use the `StructuredTool` class directly, or still subclass the `BaseTool` class."
]
},
{
"attachments": {},
"cell_type": "markdown",
"id": "5be41722",
"metadata": {},
"source": [
"### StructuredTool dataclass\n",
"\n",
"To dynamically generate a structured tool from a given function, the fastest way to get started is with `StructuredTool.from_function()`."
"Now, we show how to load existing tools and just modify them. In the example below, we do something really simple and change the Search tool to have the name `Google Search`."
"Now, we show how to load existing tools and modify them directly. In the example below, we do something really simple and change the Search tool to have the name `Google Search`."
]
},
{
"cell_type": "code",
"execution_count": 14,
"execution_count": 13,
"id": "79213f40",
"metadata": {},
"outputs": [],
@ -454,7 +611,7 @@
},
{
"cell_type": "code",
"execution_count": 15,
"execution_count": 14,
"id": "e1067dcb",
"metadata": {},
"outputs": [],
@ -464,7 +621,7 @@
},
{
"cell_type": "code",
"execution_count": 16,
"execution_count": 15,
"id": "6c66ffe8",
"metadata": {},
"outputs": [],
@ -474,7 +631,7 @@
},
{
"cell_type": "code",
"execution_count": 17,
"execution_count": 16,
"id": "f45b5bc3",
"metadata": {},
"outputs": [],
@ -484,7 +641,7 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 17,
"id": "565e2b9b",
"metadata": {},
"outputs": [
@ -497,10 +654,18 @@
"\u001b[1m> Entering new AgentExecutor chain...\u001b[0m\n",
"\u001b[32;1m\u001b[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age.\n",
"Action: Google Search\n",
"Action Input: \"Leo DiCaprio girlfriend\"\u001b[0m\u001b[36;1m\u001b[1;3mI draw the lime at going to get a Mohawk, though.\" DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid.\u001b[0m\u001b[32;1m\u001b[1;3mNow I need to find out Camila Morrone's current age.\n",
"Observation: \u001b[36;1m\u001b[1;3mAfter rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his \"age bracket\" has moved up. This follows his rumoured relationship with mere 19-year-old Eden Polani.\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI still need to find out his current girlfriend's name and her age.\n",
"Action: Google Search\n",
"Action Input: \"Leo DiCaprio current girlfriend age\"\u001b[0m\n",
"Observation: \u001b[36;1m\u001b[1;3mLeonardo DiCaprio has been linked with 19-year-old model Eden Polani, continuing the rumour that he doesn't date any women over the age of ...\u001b[0m\n",
"Thought:\u001b[32;1m\u001b[1;3mI need to find out the age of Eden Polani.\n",
"Action: Calculator\n",
"Action Input: 25^0.43\u001b[0m\u001b[33;1m\u001b[1;3mAnswer: 3.991298452658078\u001b[0m\u001b[32;1m\u001b[1;3mI now know the final answer.\n",
"Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99.\u001b[0m\n",
" description=\"Search Google for recent results.\",\n",
" func=search.run\n",
")"
]
},
{
@ -41,30 +50,20 @@
"execution_count": 3,
"id": "84b8f773",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "068991a6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'1 Child\\'s First Name. 2. 6. 7d. Street Address. 71. (Type or print). BARACK. Sex. 3. This Birth. 4. If Twin or Triplet,. Was Child Born. Barack Hussein Obama II is an American retired politician who served as the 44th president of the United States from 2009 to 2017. His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Feb 9, 2015 ... Michael Jordan misspelled Barack Obama\\'s first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama\\'s first name. Miller knew that every answer had to end\\xa0... First Lady Michelle LaVaughn Robinson Obama is a lawyer, writer, and the wife of the 44th President, Barack Obama. She is the first African-American First\\xa0... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and the first\\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Feb 27, 2020 ... President Barack Obama was born Barack Hussein Obama, II, as shown here on his birth certificate here . As reported by Reuters here , his\\xa0... Jan 16, 2007 ... 4, 1961, in Honolulu. His first name means \"one who is blessed\" in Swahili. While Obama\\'s father, Barack Hussein Obama Sr., was from Kenya, his\\xa0...'"
"\"STATE OF HAWAII. 1 Child's First Name. (Type or print). 2. Sex. BARACK. 3. This Birth. CERTIFICATE OF LIVE BIRTH. FILE. NUMBER 151 le. lb. Middle Name. Barack Hussein Obama II is an American former politician who served as the 44th president of the United States from 2009 to 2017. A member of the Democratic\\xa0... When Barack Obama was elected president in 2008, he became the first African American to hold ... The Middle East remained a key foreign policy challenge. Jan 19, 2017 ... Jordan Barack Treasure, New York City, born in 2008 ... Jordan Barack Treasure made national news when he was the focus of a New York newspaper\\xa0... Portrait of George Washington, the 1st President of the United States ... Portrait of Barack Obama, the 44th President of the United States\\xa0... His full name is Barack Hussein Obama II. Since the “II” is simply because he was named for his father, his last name is Obama. Mar 22, 2008 ... Barry Obama decided that he didn't like his nickname. A few of his friends at Occidental College had already begun to call him Barack (his\\xa0... Aug 18, 2017 ... It took him several seconds and multiple clues to remember former President Barack Obama's first name. Miller knew that every answer had to\\xa0... Feb 9, 2015 ... Michael Jordan misspelled Barack Obama's first name on 50th-birthday gift ... Knowing Obama is a Chicagoan and huge basketball fan,\\xa0... 4 days ago ... Barack Obama, in full Barack Hussein Obama II, (born August 4, 1961, Honolulu, Hawaii, U.S.), 44th president of the United States (2009–17) and\\xa0...\""
]
},
"execution_count": 4,
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.run(\"Obama's first name?\")"
"tool.run(\"Obama's first name?\")"
]
},
{
@ -78,17 +77,23 @@
},
{
"cell_type": "code",
"execution_count": 5,
"execution_count": 4,
"id": "5083fbdd",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper(k=1)"
"search = GoogleSearchAPIWrapper(k=1)\n",
"\n",
"tool = Tool(\n",
" name = \"I'm Feeling Lucky\",\n",
" description=\"Search Google and return the first result.\",\n",
" func=search.run\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 6,
"execution_count": 5,
"id": "77aaa857",
"metadata": {},
"outputs": [
@ -98,13 +103,13 @@
"'The official home of the Python Programming Language.'"
]
},
"execution_count": 6,
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"search.run(\"python\")"
"tool.run(\"python\")"
]
},
{
@ -137,48 +142,30 @@
},
{
"cell_type": "code",
"execution_count": 7,
"execution_count": 6,
"id": "028f4cba",
"metadata": {},
"outputs": [],
"source": [
"search = GoogleSearchAPIWrapper()"
"search = GoogleSearchAPIWrapper()\n",
"\n",
"def top5_results(query):\n",
" return search.results(query, 5)\n",
"\n",
"tool = Tool(\n",
" name = \"Google Search Snippets\",\n",
" description=\"Search Google for recent results.\",\n",
" func=top5_results\n",
")"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "4d8f734f",
"execution_count": null,
"id": "4d7f92e1",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[{'snippet': 'Discover the innovative world of Apple and shop everything iPhone, iPad, Apple Watch, Mac, and Apple TV, plus explore accessories, entertainment,\\xa0...',\n",
" 'title': 'Apple',\n",
" 'link': 'https://www.apple.com/'},\n",
" {'snippet': \"Jul 10, 2022 ... Whether or not you're up on your apple trivia, no doubt you know how delicious this popular fruit is, and how nutritious. Apples are rich in\\xa0...\",\n",
" 'title': '25 Types of Apples and What to Make With Them - Parade ...',\n",
" {'snippet': 'An apple is an edible fruit produced by an apple tree (Malus domestica). Apple trees are cultivated worldwide and are the most widely grown species in the\\xa0...',\n",
" {'snippet': 'Apples are a popular fruit. They contain antioxidants, vitamins, dietary fiber, and a range of other nutrients. Due to their varied nutrient content,\\xa0...',\n",
" 'title': 'Apples: Benefits, nutrition, and tips',\n",
" {'snippet': \"An apple is a crunchy, bright-colored fruit, one of the most popular in the United States. You've probably heard the age-old saying, “An apple a day keeps\\xa0...\",\n",
" 'title': 'Apples: Nutrition & Health Benefits',\n",