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

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

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.

Continue reading