Modern autonomous AI agents (built on frameworks such as LangChain, LlamaIndex, CrewAI, or OpenAI Swarm) rely on external tools to interact with real-time reality. When an LLM agent encounters a question about breaking news, stock prices, or competitive products, it must trigger a web search tool to retrieve factual context.
Using Serqo as an AI agent search tool provides two decisive advantages over traditional web scrapers: sub-second JSON retrieval without browser rendering overhead, and lean, structured payloads that protect your LLM context window.
Why Agents Need a Clean SERP API
- Overcoming Knowledge Cutoffs: Foundation models cannot answer queries about events occurring after their training date. Live SERP grounding provides immediate facts.
- Context Window Optimization: Raw web pages or full DOM scrapers dump tens of thousands of tokens per query. Serqo's clean JSON extracts organic titles, URLs, snippets, and knowledge answer boxes directly, minimizing token cost and reducing LLM attention degradation.
- Deterministic Latency: Autonomous loops (such as ReAct or Plan-and-Solve) execute multiple tool calls in sequence. A 4-second delay per search makes agents feel sluggish; Serqo returns structured results in hundreds of milliseconds.
Building a LangChain Search Tool with Python
Below is a production-ready Python example demonstrating how to wrap Serqo into a standard LangChain BaseTool. The tool extracts the search query, calls the Serqo endpoint, and formats the top organic results and answer box into a concise string for the agent.
import os
import requests
from typing import Optional, Type
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
class SearchInput(BaseModel):
query: str = Field(description="The search query to look up on Google")
class SerqoSearchTool(BaseTool):
name: str = "google_search"
description: str = "Search Google for current events, technical documentation, and real-time facts."
args_schema: Type[BaseModel] = SearchInput
def _run(self, query: str) -> str:
api_key = os.environ.get("SERP_API_KEY")
if not api_key:
return "Error: SERP_API_KEY environment variable is not configured."
try:
res = requests.post(
"https://api.serqo.io/v1/search",
headers={"x-api-key": api_key, "Content-Type": "application/json"},
json={"engine": "google", "q": query, "gl": "us", "hl": "en"},
timeout=15
)
if not res.ok:
return f"Search failed with status {res.status_code}"
data = res.json().get("data", {})
snippets = []
# 1. Include answer box if present
features = data.get("features", {})
if "answerBox" in features:
snippets.append(f"Answer: {features['answerBox'].get('answer')}")
# 2. Extract top 4 organic results
for item in data.get("results", [])[:4]:
title = item.get("title", "")
snippet = item.get("snippet", "")
url = item.get("url", "")
snippets.append(f"- {title}: {snippet} ({url})")
return "\n".join(snippets) if snippets else "No relevant search results found."
except Exception as e:
return f"Search error: {str(e)}"
# Example usage in an agentic workflow:
# tool = SerqoSearchTool()
# print(tool.run("latest developments in fusion energy")) TypeScript & AI SDK Tool Calling Example
For modern full-stack TypeScript applications using Vercel AI SDK or Node.js agent loops, you can define Serqo as a typed tool using zod:
import { z } from "zod";
export const googleSearchTool = {
description: "Search Google for live facts, current news, and technical references.",
parameters: z.object({
query: z.string().describe("The search query"),
}),
execute: async ({ query }: { query: string }) => {
const res = await fetch("https://api.serqo.io/v1/search", {
method: "POST",
headers: {
"x-api-key": process.env.SERP_API_KEY || "",
"Content-Type": "application/json",
},
body: JSON.stringify({
engine: "google",
q: query,
gl: "us",
hl: "en",
}),
});
if (!res.ok) return { error: `Failed to search: HTTP ${res.status}` };
const { data } = await res.json();
return {
results: (data.results || []).slice(0, 3).map((r: any) => ({
title: r.title,
snippet: r.snippet,
url: r.url,
})),
};
},
}; Best Practices for Agentic Web Search
- Filter Irrelevant Data Upstream: Never pass full raw HTML into an LLM context. Always extract only the
title,snippet, andurlof the top 3–5 items. - Leverage the Answer Box: When Google displays a direct answer or knowledge panel, pass that field first. In many cases, the agent can resolve the query without reading further organic links.
- Set Deterministic Timeouts: Configure a 10–15s timeout in your HTTP client to prevent hanging agent loops when upstream network conditions vary.
Start Building with 100 Free Searches
Sign up on Serqo to generate your API key with 100 free requests. Test live query outputs across Google and Bing in the interactive playground or explore our API documentation.