OpenAI's function calling (the tools parameter in Chat Completions and Assistants API) provides the most reliable way to connect models like gpt-4o and gpt-4o-mini to live external data. Instead of stuffing raw HTML into system prompts or managing heavyweight agent frameworks, native function calling gives models a structured schema to trigger web searches only when fresh factual context is required.

This guide demonstrates production-grade implementations in both TypeScript (Node.js) and Python, walking through schema definition, multi-turn agent execution loops with Serqo, and token optimization techniques that keep overhead under 300 tokens per search.

Why Native Function Calling Over Browser Scraping

Feature Browser Automation (Puppeteer) Serqo Function Calling
Latency 4,000 – 10,000 ms 400 – 800 ms
Context Overhead 20,000 – 50,000 tokens (HTML boilerplate) 150 – 300 tokens (Structured JSON)
Reliability Frequent CAPTCHA blocks & IP bans Managed residential IP rotation
Cost per Search High proxy & headless browser server costs From $0.002 / search (Starter plan)

Tool Definition Schema

Below is the standard JSON Schema compatible with OpenAI's tools: [{ type: "function", function: ... }]:

{
  "type": "function",
  "function": {
    "name": "web_search",
    "description": "Search Google or Bing for real-time news, current events, recent software documentation, and factual verifications.",
    "parameters": {
      "type": "object",
      "properties": {
        "query": {
          "type": "string",
          "description": "The search query keywords (e.g., 'Node.js 22 LTS changes')"
        },
        "engine": {
          "type": "string",
          "enum": ["google", "bing"],
          "default": "google",
          "description": "Search engine provider to query."
        }
      },
      "required": ["query"]
    }
  }
}

Node.js / TypeScript Implementation

Using the official openai npm package, this script runs an end-to-end agent loop that automatically executes tool calls and formats the final answer:

import OpenAI from "openai";

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const SERP_API_KEY = process.env.SERP_API_KEY;

// 1. Tool execution helper calling Serqo
async function executeWebSearch(query: string, engine: "google" | "bing" = "google"): Promise<string> {
  if (!SERP_API_KEY) {
    throw new Error("SERP_API_KEY is not configured.");
  }

  const res = await fetch("https://serqo.io/v1/search", {
    method: "POST",
    headers: {
      "x-api-key": SERP_API_KEY,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      engine,
      q: query,
      gl: "us",
      hl: "en",
    }),
  });

  if (!res.ok) {
    const errorBody = await res.text();
    return `Search API failed with status ${res.status}: ${errorBody}`;
  }

  const payload = await res.json();
  const results = (payload?.data?.results || []).slice(0, 5);

  if (results.length === 0) {
    return `No search results found for query: "${query}".`;
  }

  // Slice results into a concise text summary to preserve LLM context tokens
  return results
    .map((item: any, idx: number) => `[${idx + 1}] ${item.title}\nURL: ${item.url}\nSummary: ${item.snippet}`)
    .join("\n\n");
}

// 2. OpenAI Tool Definition
const tools: OpenAI.ChatCompletionTool[] = [
  {
    type: "function",
    function: {
      name: "web_search",
      description: "Search Google or Bing for real-time information, recent events, and technical documentation.",
      parameters: {
        type: "object",
        properties: {
          query: {
            type: "string",
            description: "Search keywords or question",
          },
          engine: {
            type: "string",
            enum: ["google", "bing"],
            default: "google",
          },
        },
        required: ["query"],
      },
    },
  },
];

// 3. Multi-turn Agent Execution Loop
async function runSearchAgent(prompt: string) {
  const messages: OpenAI.ChatCompletionMessageParam[] = [
    {
      role: "system",
      content: "You are a helpful assistant with access to real-time Google and Bing search. Always cite URLs when using search results.",
    },
    { role: "user", content: prompt },
  ];

  const response = await openai.chat.completions.create({
    model: "gpt-4o-mini",
    messages,
    tools,
    tool_choice: "auto",
  });

  const responseMessage = response.choices[0].message;
  messages.push(responseMessage);

  if (responseMessage.tool_calls && responseMessage.tool_calls.length > 0) {
    for (const toolCall of responseMessage.tool_calls) {
      if (toolCall.function.name === "web_search") {
        const args = JSON.parse(toolCall.function.arguments);
        const searchResult = await executeWebSearch(args.query, args.engine);

        messages.push({
          role: "tool",
          tool_call_id: toolCall.id,
          content: searchResult,
        });
      }
    }

    const finalResponse = await openai.chat.completions.create({
      model: "gpt-4o-mini",
      messages,
    });

    console.log("\n[Final Answer]:\n", finalResponse.choices[0].message.content);
  } else {
    console.log("\n[Direct Answer without Search]:\n", responseMessage.content);
  }
}

runSearchAgent("What are the key new features introduced in PostgreSQL 17?");

Python Implementation

The equivalent implementation in Python 3.10+ using requests and openai:

import os
import json
import requests
from openai import OpenAI

client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
SERP_API_KEY = os.environ.get("SERP_API_KEY")

def execute_web_search(query: str, engine: str = "google") -> str:
    """Executes a real-time web search via Serqo API."""
    if not SERP_API_KEY:
        return "Error: SERP_API_KEY environment variable is missing."

    try:
        response = requests.post(
            "https://serqo.io/v1/search",
            headers={
                "x-api-key": SERP_API_KEY,
                "Content-Type": "application/json",
            },
            json={
                "engine": engine,
                "q": query,
                "gl": "us",
                "hl": "en",
            },
            timeout=10,
        )
        response.raise_for_status()
        payload = response.json()
        results = payload.get("data", {}).get("results", [])[:5]

        if not results:
            return f"No results found for query: '{query}'."

        formatted = []
        for idx, item in enumerate(results, start=1):
            title = item.get("title", "")
            url = item.get("url", "")
            snippet = item.get("snippet", "")
            formatted.append(f"[{idx}] {title}\nURL: {url}\nSummary: {snippet}")

        return "\n\n".join(formatted)

    except Exception as exc:
        return f"Search execution failed: {str(exc)}"

tools = [
    {
        "type": "function",
        "function": {
            "name": "web_search",
            "description": "Retrieve up-to-date search results from Google or Bing.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "Keywords to search for",
                    },
                    "engine": {
                        "type": "string",
                        "enum": ["google", "bing"],
                        "default": "google",
                    },
                },
                "required": ["query"],
            },
        },
    }
]

def run_agent(prompt: str):
    messages = [
        {"role": "system", "content": "You are an AI research assistant. Ground answers in search results with URLs."},
        {"role": "user", "content": prompt},
    ]

    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=messages,
        tools=tools,
        tool_choice="auto",
    )

    msg = response.choices[0].message
    messages.append(msg)

    if msg.tool_calls:
        for tool_call in msg.tool_calls:
            if tool_call.function.name == "web_search":
                args = json.loads(tool_call.function.arguments)
                result = execute_web_search(args.get("query"), args.get("engine", "google"))

                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result,
                })

        final = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
        )
        print("[Final Answer]:\n", final.choices[0].message.content)
    else:
        print("[Direct Answer]:\n", msg.content)

if __name__ == "__main__":
    run_agent("What are the major performance benchmarks of Python 3.13 free-threaded mode?")

Production Boundaries & Error Handling

Continue reading