Implementing a Multi-Step Agent with Langchain
In this document, we’ll go through the nuts-and-bolts of building a generative-AI agent with Cohere’s multi-step tool use functionality and the Langchain framework.
Building the Langchain ReAct Agent
Multi-step tool use with Cohere can be implemented using the Langchain framework, which conveniently comes with many pre-defined tools. More specifically, we recommend using the ReAct agent abstraction in Langchain, powered by create_cohere_react_agent
. Let’s see how we can easily build an agent, using the multi-step tool use capabilities of Langchain and Cohere.
Jupyter Notebook
The example below is also available in this Jupyter Notebook for convenience.
First, we’ll install the dependencies. (Note: the !
is required for notebooks, but you must omit it if you’re in the command line).
Second, we define some tools to equip your agent. Langchain comes out-of-the-box with more than 50 predefined tools, including web search, a python interpreter, vector stores, and many others.
Below, we’ve included two code snippets, equipping the agent with the Web Search and Python interpreter tools, respectively.
Example: define the Web Search tool
Example: define the Python Interpreter tool
Even better any Python function can easily be transformed into a Langchain tool by using the @tool
decorator. As a best practice, should specify the tool name, definition, and arguments schema.
Example: define a custom tool
Third, create a ReAct agent in Langchain. The model can dynamically pick the right tool(s) for the user query, call them in a sequence, analyze the results, and self-reflect. Note that your ReAct agent can optionally take an input preamble.
Finally, call your agent with a question!
Inspecting the Logs
We can get some insight into what’s going on under the hood by taking a look at the logs (we’ve added #
comments throughout for context):
Some Useful Tools
Beyond the web search tool and the Python interpreter tool shared in the code snippets above, we have found some tools to be particularly useful. Here’s an example of leveraging a vector store for greater functionality:
Multi-turn Conversations and Chat History
So far, we asked one-off questions to the ReAct agent. In many enterprise applications, end users want to have conversations with the ReAct agent.
The ReAct agent can handle multi-turn conversations by using chat_history
.
Can the ReAct Agent Directly Answer a Question?
Yes. The ReAct agent from Cohere comes out of the box with the ability to answer a user question directly. This happens when answering the user’s question doesn’t require using a tool.
For example, let’s look at the following question:
By inspecting the logs, we see that the ReAct agent decided to just respond directly.