LangChain Search Tool Integration Patterns
Common ways to register a search API as a LangChain tool and keep outputs agent-friendly.
How it works
LangChain wraps external APIs as `Tool` objects with a name, description, and a callable that returns a string (or structured output in newer versions). A search API integration usually means writing a thin wrapper function that calls the provider's REST endpoint, parses the JSON response, and formats it into a compact string (or a list of structured result objects) that gets appended to the agent's scratchpad before the next reasoning step.
Example
A typical wrapper: def search_tool(query: str) -> str: results = api.search(query); return "\n".join(f"{r['title']}: {r['snippet']} ({r['url']})" for r in results[:5]). Registered as a Tool(name="search", func=search_tool, description="Search the web for current information"), this slots directly into a LangChain agent executor's tool list.
Pitfalls
- Returning raw JSON instead of a formatted string wastes tokens and makes it harder for the model to extract the relevant fields when the agent framework expects string tool output.
- Not truncating snippet length before formatting can silently blow past the agent's context window on agents that call search multiple times per task.
- LangChain's default agent executors don't automatically retry a failed tool call, so an unhandled API timeout inside the wrapper can crash the whole agent run rather than degrading gracefully.