Custom tools for agents
1. Custom tools for agents
Now that we've created our first agent, let's take a closer a look at tools so we can design our own.2. Tool formats
Tools in LangChain must be formatted in a specific way to be compatible with agents. They must have a name, accessible via the .name attribute. A description, which is used by the LLM to determine when to call the tool. In this case, if the LLM interprets the task as being a math problem, it will likely call this tool based on its description.3. Tool formats
Finally, the return_direct parameter indicates whether the agent should stop after invoking this tool, which it won't in this case. Understanding this required format will help us to understand how to create our own tools.4. Defining a custom function
Let's say we want to define a Python function to generate a financial report for a company. It takes three arguments: the company_name, revenue, and expenses, and outputs a string containing the net_income. We make the use of this function clear in the docstring, defined using triple quotes.5. Calling the function
Here's what the report looks like. Let's convert this function into a tool our agent can call.6. From functions to tools
To do this, we import the @tool decorator and add it before the function definition. Don't worry if you're not familiar with Python decorators; the @tool modifies the function so it's in the correct format to be used by a tool.7. Examining our new tool
Like with the built-in tool we were looking at, we can now examine the various attributes of our tool. These include its name, which is the function name by default, its description, which is the function's docstring, and return_direct, which is set to False by default. We can also print the tools arguments, which lay out the argument names and expected data types. Let's put our tool into action!8. Integrating the custom tool
We'll again use a ReAct agent, combining the chat LLM with a list of tools to use, containing our new custom tool. We invoke the agent with an input containing the required information: a company name, revenue, and expenses.9. Integrating the custom tool
The response from the agent starts with our input, then determines that the financial_report tool should be called, which returns a tool message containing the output from our function, and finally, the output is passed to the LLM, which responds to us. Let's zoom in on this final message.10. Tool outputs
Here's the final output from the LLM. Notice anything? Here's the output from the tool based on the function we defined. Notice that there's slight formatting differences between the two; the LLM received the tool output, and put it's own slight spin on it, which you may need to watch out for.11. Let's practice!
Now it's your turn!Create Your Free Account
or
By continuing, you accept our Terms of Use, our Privacy Policy and that your data is stored in the USA.