mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-07 18:35:22 +03:00
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
29 KiB
29 KiB
In [1]:
# Import things that are needed generically
from langchain import LLMMathChain, SerpAPIWrapper
from langchain.agents import AgentType, initialize_agent
from langchain.chat_models import ChatOpenAI
from langchain.tools import BaseTool, StructuredTool, Tool, toolIn [2]:
llm = ChatOpenAI(temperature=0)In [3]:
# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
Tool.from_function(
func=search.run,
name = "Search",
description="useful for when you need to answer questions about current events"
# coroutine= ... <- you can specify an async method if desired as well
),
]/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. warnings.warn(
In [4]:
from pydantic import BaseModel, Field
class CalculatorInput(BaseModel):
question: str = Field()
tools.append(
Tool.from_function(
func=llm_math_chain.run,
name="Calculator",
description="useful for when you need to answer questions about math",
args_schema=CalculatorInput
# coroutine= ... <- you can specify an async method if desired as well
)
)In [5]:
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)In [6]:
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")Out [6]:
[1m> Entering new AgentExecutor chain...[0m
[32;1m[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search
Action Input: "Leo DiCaprio girlfriend"[0m
Observation: [36;1m[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.[0m
Thought:[32;1m[1;3mI still need to find out his current girlfriend's name and age
Action: Search
Action Input: "Leo DiCaprio current girlfriend"[0m
Observation: [36;1m[1;3mJust Jared on Instagram: “Leonardo DiCaprio & girlfriend Camila Morrone couple up for a lunch date![0m
Thought:[32;1m[1;3mNow that I know his girlfriend's name is Camila Morrone, I need to find her current age
Action: Search
Action Input: "Camila Morrone age"[0m
Observation: [36;1m[1;3m25 years[0m
Thought:[32;1m[1;3mNow that I have her age, I need to calculate her age raised to the 0.43 power
Action: Calculator
Action Input: 25^(0.43)[0m
[1m> Entering new LLMMathChain chain...[0m
25^(0.43)[32;1m[1;3m```text
25**(0.43)
```
...numexpr.evaluate("25**(0.43)")...
[0m
Answer: [33;1m[1;3m3.991298452658078[0m
[1m> Finished chain.[0m
Observation: [33;1m[1;3mAnswer: 3.991298452658078[0m
Thought:[32;1m[1;3mI now know the final answer
Final Answer: Camila Morrone's current age raised to the 0.43 power is approximately 3.99.[0m
[1m> Finished chain.[0m
"Camila Morrone's current age raised to the 0.43 power is approximately 3.99."
In [7]:
from typing import Optional, Type
from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
class CustomSearchTool(BaseTool):
name = "custom_search"
description = "useful for when you need to answer questions about current events"
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
"""Use the tool."""
return search.run(query)
async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("custom_search does not support async")
class CustomCalculatorTool(BaseTool):
name = "Calculator"
description = "useful for when you need to answer questions about math"
args_schema: Type[BaseModel] = CalculatorInput
def _run(self, query: str, run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
"""Use the tool."""
return llm_math_chain.run(query)
async def _arun(self, query: str, run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("Calculator does not support async")In [8]:
tools = [CustomSearchTool(), CustomCalculatorTool()]
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)In [9]:
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")Out [9]:
[1m> Entering new AgentExecutor chain...[0m
[32;1m[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.
Action: custom_search
Action Input: "Leo DiCaprio girlfriend"[0m
Observation: [36;1m[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.[0m
Thought:[32;1m[1;3mI need to find out the current age of Eden Polani.
Action: custom_search
Action Input: "Eden Polani age"[0m
Observation: [36;1m[1;3m19 years old[0m
Thought:[32;1m[1;3mNow I can use the Calculator to raise her age to the 0.43 power.
Action: Calculator
Action Input: 19 ^ 0.43[0m
[1m> Entering new LLMMathChain chain...[0m
19 ^ 0.43[32;1m[1;3m```text
19 ** 0.43
```
...numexpr.evaluate("19 ** 0.43")...
[0m
Answer: [33;1m[1;3m3.547023357958959[0m
[1m> Finished chain.[0m
Observation: [33;1m[1;3mAnswer: 3.547023357958959[0m
Thought:[32;1m[1;3mI now know the final answer.
Final Answer: 3.547023357958959[0m
[1m> Finished chain.[0m
'3.547023357958959'
In [10]:
from langchain.tools import tool
@tool
def search_api(query: str) -> str:
"""Searches the API for the query."""
return f"Results for query {query}"
search_apiIn [12]:
@tool("search", return_direct=True)
def search_api(query: str) -> str:
"""Searches the API for the query."""
return "Results"In [13]:
search_apiOut [13]:
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class 'pydantic.main.SearchApi'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bd66310>, coroutine=None)
In [14]:
class SearchInput(BaseModel):
query: str = Field(description="should be a search query")
@tool("search", return_direct=True, args_schema=SearchInput)
def search_api(query: str) -> str:
"""Searches the API for the query."""
return "Results"In [15]:
search_apiOut [15]:
Tool(name='search', description='search(query: str) -> str - Searches the API for the query.', args_schema=<class '__main__.SearchInput'>, return_direct=True, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x12748c4c0>, func=<function search_api at 0x16bcf0ee0>, coroutine=None)
In [10]:
import requests
from langchain.tools import StructuredTool
def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str:
"""Sends a POST request to the given url with the given body and parameters."""
result = requests.post(url, json=body, params=parameters)
return f"Status: {result.status_code} - {result.text}"
tool = StructuredTool.from_function(post_message)In [11]:
from typing import Optional, Type
from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
class CustomSearchTool(BaseTool):
name = "custom_search"
description = "useful for when you need to answer questions about current events"
def _run(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
"""Use the tool."""
search_wrapper = SerpAPIWrapper(params={"engine": engine, "gl": gl, "hl": hl})
return search_wrapper.run(query)
async def _arun(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("custom_search does not support async")
# You can provide a custom args schema to add descriptions or custom validation
class SearchSchema(BaseModel):
query: str = Field(description="should be a search query")
engine: str = Field(description="should be a search engine")
gl: str = Field(description="should be a country code")
hl: str = Field(description="should be a language code")
class CustomSearchTool(BaseTool):
name = "custom_search"
description = "useful for when you need to answer questions about current events"
args_schema: Type[SearchSchema] = SearchSchema
def _run(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[CallbackManagerForToolRun] = None) -> str:
"""Use the tool."""
search_wrapper = SerpAPIWrapper(params={"engine": engine, "gl": gl, "hl": hl})
return search_wrapper.run(query)
async def _arun(self, query: str, engine: str = "google", gl: str = "us", hl: str = "en", run_manager: Optional[AsyncCallbackManagerForToolRun] = None) -> str:
"""Use the tool asynchronously."""
raise NotImplementedError("custom_search does not support async")
In [12]:
import requests
from langchain.tools import tool
@tool
def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str:
"""Sends a POST request to the given url with the given body and parameters."""
result = requests.post(url, json=body, params=parameters)
return f"Status: {result.status_code} - {result.text}"In [13]:
from langchain.agents import load_toolsIn [14]:
tools = load_tools(["serpapi", "llm-math"], llm=llm)In [15]:
tools[0].name = "Google Search"In [16]:
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)In [17]:
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")Out [17]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3mI need to find out Leo DiCaprio's girlfriend's name and her age. Action: Google Search Action Input: "Leo DiCaprio girlfriend"[0m Observation: [36;1m[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.[0m Thought:[32;1m[1;3mI still need to find out his current girlfriend's name and her age. Action: Google Search Action Input: "Leo DiCaprio current girlfriend age"[0m Observation: [36;1m[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 ...[0m Thought:[32;1m[1;3mI need to find out the age of Eden Polani. Action: Calculator Action Input: 19^(0.43)[0m Observation: [33;1m[1;3mAnswer: 3.547023357958959[0m Thought:[32;1m[1;3mI now know the final answer. Final Answer: The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55.[0m [1m> Finished chain.[0m
"The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55."
In [18]:
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper
search = SerpAPIWrapper()
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
),
Tool(
name="Music Search",
func=lambda x: "'All I Want For Christmas Is You' by Mariah Carey.", #Mock Function
description="A Music search engine. Use this more than the normal search if the question is about Music, like 'who is the singer of yesterday?' or 'what is the most popular song in 2022?'",
)
]
agent = initialize_agent(tools, OpenAI(temperature=0), agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)In [20]:
agent.run("what is the most famous song of christmas")Out [20]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m I should use a music search engine to find the answer Action: Music Search Action Input: most famous song of christmas[0m[33;1m[1;3m'All I Want For Christmas Is You' by Mariah Carey.[0m[32;1m[1;3m I now know the final answer Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.[0m [1m> Finished chain.[0m
"'All I Want For Christmas Is You' by Mariah Carey."
In [21]:
llm_math_chain = LLMMathChain(llm=llm)
tools = [
Tool(
name="Calculator",
func=llm_math_chain.run,
description="useful for when you need to answer questions about math",
return_direct=True
)
]In [22]:
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)In [23]:
agent.run("whats 2**.12")Out [23]:
[1m> Entering new AgentExecutor chain...[0m [32;1m[1;3m I need to calculate this Action: Calculator Action Input: 2**.12[0m[36;1m[1;3mAnswer: 1.086734862526058[0m[32;1m[1;3m[0m [1m> Finished chain.[0m
'Answer: 1.086734862526058'