Example
Let's start with a simple code example.
from langchain.agents import create_tool_calling_agent
agent = create_tool_calling_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
In this example, you can see that the create_tool_calling_agent method creates an agent and takes three arguments:
- llm: the large language model we're using
- tools: the tools that can be used, which you can also think of as functions
- prompt: the prompt—nothing more to add here
The tools passed in also go by another name: function_calls.
That raises a question: what is a tool?
Tool
Let's look at the official explanation:
Tools are interfaces that an agent, chain, or LLM can use to interact with the world. They combine a few things:
- The name of the tool
- A description of what the tool is
- JSON schema of what the inputs to the tool are
- The function to call
- Whether the result of a tool should be returned directly to the user
It's actually a lot like what we normally think of as a function: you need to describe the tool's name, what it does, its inputs, and outputs.
You can think of a tool as essentially a callback: when the AI decides it needs to use this method, it calls into it.
Creating a Tool
@tool
def search(query: str) -> str:
"""Look up things online."""
return "LangChain"
Now that we've explained what a Tool is, it's easy to understand what an agent is.
Agent
An agent is like a reasoning task hub. When you ask it a question, it reasons about whether the question requires some tool to answer; if it does, it calls that Tool.
The simplest example is search, which gets around the LLM's knowledge-base limitations.
from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_community.tools.tavily_search import TavilySearchResults
from langchain_core.prompts import ChatPromptTemplate
tools = [TavilySearchResults(max_results=1)]
prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a helpful assistant. Make sure to use the tavily_search_results_json tool for information.",
),
("placeholder", "{chat_history}"),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
]
)
# Construct the Tools agent
agent = create_tool_calling_agent(llm, tools, prompt)
# Create an agent executor by passing in the agent and tools
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
agent_executor.invoke({"input": "what is LangChain?"})