|
|
LangChain Tool Calling with Multiple Tools and Error Handling
Author: Venkata Sudhakar
ShopMax India's order management agent needs to call multiple backend tools - checking order status, looking up product availability, and triggering refunds - all from a single natural language request. LangChain's tool calling with bind_tools lets you attach multiple Python functions to an LLM, which then decides which tools to call and with what arguments based on the user query.
You define tools as Python functions decorated with @tool, then bind them to the LLM using llm.bind_tools(). When the LLM returns a tool call, you execute the tool and pass the result back to the LLM for a final response. The agent loop continues until the LLM returns a plain text response with no more tool calls. Error handling is critical - wrap tool execution in try/except and return error messages as tool results so the LLM can report them gracefully.
The example below shows a ShopMax India order assistant that uses three tools - get_order_status, check_stock, and process_refund - and handles tool errors gracefully.
It gives the following output,
Order ORD-1001 is currently Shipped and expected to arrive by May 10. Sony WH-1000XM5 headphones are in stock with 24 units available at the ShopMax India warehouse.
In production, limit the number of tool call iterations with a max_iterations counter to prevent infinite loops if the LLM keeps calling tools. Log every tool invocation with arguments and results for audit trails. For sensitive operations like refunds, add a confirmation step before executing. Use parallel tool calling (supported by GPT-4o) to run independent tool calls simultaneously and reduce total response time for ShopMax customer queries.
|
|