Files
langchain/docs/modules/agents/examples/custom_tools.ipynb
T
2023-01-28 18:26:24 -08:00

15 KiB

Defining Custom Tools

When constructing your own agent, you will need to provide it with a list of Tools that it can use. A Tool is defined as below.

@dataclass 
class Tool:
    """Interface for tools."""

    name: str
    func: Callable[[str], str]
    description: Optional[str] = None
    return_direct: bool = True

The two required components of a Tool are the name and then the tool itself. A tool description is optional, as it is needed for some agents but not all. You can create these tools directly, but we also provide a decorator to easily convert any function into a tool.

In [1]:
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
from langchain import LLMMathChain, SerpAPIWrapper

Initialize the LLM to use for the agent.

In [2]:
llm = OpenAI(temperature=0)

Completely New Tools

First, we show how to create completely new tools from scratch.

In [3]:
# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
    Tool(
        name = "Search",
        func=search.run,
        description="useful for when you need to answer questions about current events"
    ),
    Tool(
        name="Calculator",
        func=llm_math_chain.run,
        description="useful for when you need to answer questions about math"
    )
]
In [6]:
# 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="zero-shot-react-description", verbose=True)
In [7]:
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
Out [7]:

> Entering new AgentExecutor chain...
 I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.
Action: Search
Action Input: Olivia Wilde's boyfriend
Observation: Harry Styles
Thought: I need to calculate Harry Styles' age raised to the 0.23 power.
Action: Calculator
Action Input: 23^0.23

> Entering new LLMMathChain chain...
23^0.23
```python
import math
print(math.pow(23, 0.23))
```

Answer: 2.0568252837687546

> Finished LLMMathChain chain.

Observation: Answer: 2.0568252837687546

Thought: I now know the final answer.
Final Answer: Harry Styles' age raised to the 0.23 power is 2.0568252837687546.
> Finished AgentExecutor chain.
"Harry Styles' age raised to the 0.23 power is 2.0568252837687546."

Using the tool decorator

To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a string as the first argument. Additionally, the decorator will use the function's docstring as the tool's description.

In [1]:
from langchain.agents import tool

@tool
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
In [2]:
search_api
Out [2]:
Tool(name='search_api', func=<function search_api at 0x10dad7d90>, description='search_api(query: str) -> str - Searches the API for the query.', return_direct=False)

You can also provide arguments like the tool name and whether to return directly.

In [3]:
@tool("search", return_direct=True)
def search_api(query: str) -> str:
    """Searches the API for the query."""
    return "Results"
In [4]:
search_api
Out [4]:
Tool(name='search', func=<function search_api at 0x112301bd0>, description='search(query: str) -> str - Searches the API for the query.', return_direct=True)

Modify existing tools

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.

In [8]:
from langchain.agents import load_tools
In [9]:
tools = load_tools(["serpapi", "llm-math"], llm=llm)
In [10]:
tools[0].name = "Google Search"
In [11]:
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
In [12]:
agent.run("Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?")
Out [12]:

> Entering new AgentExecutor chain...
 I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.
Action: Google Search
Action Input: "Olivia Wilde boyfriend"
Observation: Harry Styles
Thought: I need to find out Harry Styles' age
Action: Google Search
Action Input: "Harry Styles age"
Observation: 28 years
Thought: I need to calculate 28 raised to the 0.23 power
Action: Calculator
Action Input: 28^0.23
Observation: Answer: 2.1520202182226886

Thought: I now know the final answer
Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.1520202182226886.
> Finished AgentExecutor chain.
"Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.1520202182226886."

Defining the priorities among Tools

When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools.

For example, you made a custom tool, which gets information on music from your database. When a user wants information on songs, You want the Agent to use the custom tool more than the normal Search tool. But the Agent might prioritize a normal Search tool.

This can be accomplished by adding a statement such as 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?' to the description.

An example is below.

In [7]:
# Import things that are needed generically
from langchain.agents import initialize_agent, Tool
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="zero-shot-react-description", verbose=True)
In [8]:
agent.run("what is the most famous song of christmas")
Out [8]:

> Entering new AgentExecutor chain...
 I should use a music search engine to find the answer
Action: Music Search
Action Input: most famous song of christmas
Observation: 'All I Want For Christmas Is You' by Mariah Carey.
Thought: I now know the final answer
Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.

> Finished chain.
"'All I Want For Christmas Is You' by Mariah Carey."

Using tools to return directly

Often, it can be desirable to have a tool output returned directly to the user, if it’s called. You can do this easily with LangChain by setting the return_direct flag for a tool to be True.

In [3]:
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 [4]:
llm = OpenAI(temperature=0)
agent = initialize_agent(tools, llm, agent="zero-shot-react-description", verbose=True)
In [5]:
agent.run("whats 2**.12")
Out [5]:

> Entering new AgentExecutor chain...
 I need to calculate this
Action: Calculator
Action Input: 2**.12
Observation: Answer: 1.2599210498948732


> Finished chain.
'Answer: 1.2599210498948732'
In [ ]: