Connecting Large Language Model APIs to Web Search: Workflow, Code, and Common Pitfalls

    Learn how to connect an LLM API to real-time web search using tool calling. This guide covers client-side and server-side approaches, request design, response parsing, multi-turn execution loops, error handling, cost monitoring, security, compliance, and a practical pre-launch checklist.

    1. Why Models Need Web Access

    Large language models learn from their training data. Once training is complete, the model has no direct knowledge of events that happen afterward. Information such as current weather, breaking news, and stock prices changes over time and cannot be answered reliably from the model’s parameters alone.

    The standard solution is tool use, also known as function calling. When the model determines that a question requires external information, it first returns a tool call containing the tool name and its arguments, such as a search query. Your application executes the tool, sends the result back to the model, and then lets the model generate a response based on that result.

    Web search and web page extraction are two common tools. A search tool returns a list of candidate results, including titles, snippets, and URLs. A page extraction tool retrieves the main content from a URL, removes advertisements and navigation elements, and returns plain text. Used together, these tools allow the model to locate relevant sources first and then read their detailed content.

    2. Choosing Between the Two Implementation Models

    There are two primary ways to add web access. The right choice depends on your use case.

    Comparison Client-side tool execution Server-side built-in tools
    Who executes the tool Your application calls the search service and sends the result back The provider performs search and extraction on the server
    Search source selection Flexible; you can connect enterprise knowledge bases or other sources Limited to the sources provided by the service
    Development effort You implement the tool functions and execution loop You only declare the tool, so less code is required
    Result format Fully controlled by your application Defined by the provider’s documentation
    Suitable scenarios Custom data sources and strict workflow control Fast deployment and general-purpose Q&A

    The code in this article uses the standard client-side approach, where the tool declaration has type: "function". This format is compatible with many providers that support the OpenAI API protocol.

    If you use server-side built-in tools, the tool type, parameters, and response fields must follow the provider’s official documentation. Do not copy the implementation of one provider directly to another.

    3. Preparation

    Before writing code, complete the following checks.

    1. SDK version: Make sure your openai package version supports the tools parameter. Use pip show openai to check the installed version, and confirm the minimum requirement in your provider’s documentation.
    2. API key permissions: Create a key in the provider’s developer console and verify that it can access chat completions and tool calling. Do not use a master key with administrative privileges.
    3. Environment variables: Store credentials in environment variables instead of source code or logs. For example:
    1. export LLM_API_KEY="your-api-key"
    2. export LLM_BASE_URL="provider-api-endpoint"
    3. export LLM_MODEL="provider-model-name"
    1. Billing: Check whether tool calls are billed separately and review the cost of each search and page extraction request. Before production deployment, run a small number of real requests to verify actual billing.

    4. Designing the Request

    The following example declares a web search tool:

    1. import os
    2. from datetime import datetime, timezone
    3. from openai import OpenAI
    4. client = OpenAI(
    5. api_key=os.environ["LLM_API_KEY"],
    6. base_url=os.environ.get("LLM_BASE_URL", "https://api.example.com/v1"),
    7. )
    8. tools = [
    9. {
    10. "type": "function",
    11. "function": {
    12. "name": "web_search",
    13. "description": "Search the web and return a list of titles, snippets, and URLs.",
    14. "parameters": {
    15. "type": "object",
    16. "properties": {
    17. "query": {"type": "string", "description": "Search keywords"},
    18. "max_results": {
    19. "type": "integer",
    20. "description": "Number of results to return; defaults to 5",
    21. },
    22. },
    23. "required": ["query"],
    24. },
    25. },
    26. }
    27. ]
    28. now = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
    29. messages = [
    30. {
    31. "role": "system",
    32. "content": f"Current time: {now}. The user speaks Chinese. Call web_search when the question requires up-to-date information.",
    33. },
    34. {"role": "user", "content": "What are the most important AI industry news stories today?"},
    35. ]
    36. response = client.chat.completions.create(
    37. model=os.environ.get("LLM_MODEL", "model-name"),
    38. messages=messages,
    39. tools=tools,
    40. )

    This example highlights three important points:

    • Provide the current time: The model does not have a real-time clock. Including the date and time zone in the system message helps it interpret terms such as “this year” and “recently” correctly when generating search queries.
    • Use specific descriptions: The description field influences when the model calls the tool. Clear descriptions reduce both unnecessary calls and missed calls.
    • Enable tools only when needed: Web access adds latency and cost. Pass tools only for questions that depend on current information. General knowledge questions usually do not need it.

    5. Understanding the Response and Extracting Fields

    When the model decides to call a tool, finish_reason is typically tool_calls. message.content is usually empty, while the tool request appears in tool_calls.

    The following example uses standard protocol field names:

    1. {
    2. "id": "chatcmpl-abc123",
    3. "object": "chat.completion",
    4. "model": "model-name",
    5. "choices": [
    6. {
    7. "index": 0,
    8. "message": {
    9. "role": "assistant",
    10. "content": null,
    11. "tool_calls": [
    12. {
    13. "id": "call_001",
    14. "type": "function",
    15. "function": {
    16. "name": "web_search",
    17. "arguments": "{\"query\": \"AI industry news in November 2026\", \"max_results\": 5}"
    18. }
    19. }
    20. ]
    21. },
    22. "finish_reason": "tool_calls"
    23. }
    24. ],
    25. "usage": {
    26. "prompt_tokens": 128,
    27. "completion_tokens": 36,
    28. "total_tokens": 164
    29. }
    30. }

    The key fields are:

    • Final answer: When finish_reason is stop, the answer is available in choices[0].message.content.
    • Tool request: Each item in tool_calls contains an id, the tool name in function.name, and the argument string in function.arguments. The arguments are provided as a JSON string and must be parsed with json.loads. Always handle parsing errors.
    • Usage statistics: Token counts in usage are useful for cost calculations. If the provider returns tool-call counts separately, use the field names defined in its documentation.
    1. import json
    2. choice = response.choices[0]
    3. message = choice.message
    4. if choice.finish_reason == "tool_calls":
    5. for call in message.tool_calls:
    6. try:
    7. args = json.loads(call.function.arguments)
    8. except json.JSONDecodeError:
    9. args = {}
    10. print(call.function.name, args)
    11. else:
    12. print(message.content)

    6. Building the Complete Execution Loop

    The model may need multiple searches or tool calls. Your application should therefore use a loop:

    1. Send a request.
    2. If the model returns a tool call, execute the tool.
    3. Send the result back with the tool role.
    4. Request the model again.
    5. Stop when the model returns a final answer.
    1. import json
    2. def web_search(query: str, max_results: int = 5) -> list[dict]:
    3. # Connect your selected search service here and return a normalized structure:
    4. # [{"title": "...", "snippet": "...", "url": "..."}]
    5. raise NotImplementedError("Implement the search service call first")
    6. TOOL_HANDLERS = {"web_search": web_search}
    7. MAX_ROUNDS = 3
    8. def run_agent(messages: list[dict]) -> str:
    9. for _ in range(MAX_ROUNDS):
    10. resp = client.chat.completions.create(
    11. model=os.environ.get("LLM_MODEL", "model-name"),
    12. messages=messages,
    13. tools=tools,
    14. )
    15. msg = resp.choices[0].message
    16. if not msg.tool_calls:
    17. return msg.content or ""
    18. messages.append(msg.model_dump(exclude_none=True))
    19. for call in msg.tool_calls:
    20. handler = TOOL_HANDLERS.get(call.function.name)
    21. try:
    22. args = json.loads(call.function.arguments)
    23. result = handler(**args) if handler else {"error": "unknown_tool"}
    24. except Exception as exc:
    25. result = {"error": str(exc)}
    26. messages.append({
    27. "role": "tool",
    28. "tool_call_id": call.id,
    29. "content": json.dumps(result, ensure_ascii=False),
    30. })
    31. return "The maximum number of search rounds has been reached. Try rephrasing the question."

    There are three important design considerations:

    • Limit the number of rounds: MAX_ROUNDS prevents repeated tool calls from causing uncontrolled costs.
    • Return errors to the model: If a tool fails, send the error as the tool result. The model can then retry with a different query or explain the limitation to the user. The application should not fail immediately.
    • Preserve tool results exactly: tool_call_id must match the corresponding request id. Otherwise, the server may reject the next request.

    7. Fallbacks and Error Handling

    Search and page extraction can fail. Define behavior for the following situations before going live.

    1. No search results: Ask the model to retry once with a different query. If the second attempt also returns nothing, tell the user that no reliable source was found and suggest narrowing or rephrasing the question.
    2. Page extraction failure: Skip the failed URL and use the search snippet instead. The answer should state that it is based only on the snippet.
    3. Highly time-sensitive information: For live prices, current scores, or similar data, warn that the information may be delayed and include the retrieval time.

    The decision flow can be represented as follows:

    1. if the search returns no results:
    2. retry once with different keywords
    3. if the second attempt is also empty:
    4. tell the user that no reliable source was found
    5. elif page extraction fails:
    6. answer using the snippet and state "based on the snippet only"
    7. elif the information is highly time-sensitive:
    8. add "Data retrieved at: XXXX"
    9. else:
    10. answer normally and include source links

    8. Cost and Monitoring Metrics

    After deployment, continuously monitor the following metrics and use consistent definitions.

    Metric Definition Purpose
    Tool-call rate Requests that trigger a tool / total requests Determine whether web access is being overused
    Searches per request Total search calls / requests that trigger tools Detect excessive loops or unnecessary calls
    Empty-result rate Searches with no results / total searches Evaluate query quality
    Extraction failure rate Failed extractions / total extractions Evaluate source stability
    P95 latency 95th-percentile duration for requests with tool calls Measure user experience
    Cost per 1,000 requests (Model cost + tool cost) / requests × 1,000 Calculate unit economics

    For alert thresholds, use the first week of production data as a baseline, then alert when values exceed the baseline by an appropriate margin. For high-volume use cases, consider daily tool-call or spending limits per user or session.

    9. Security and Compliance

    Web access brings external content into the model context and requires additional safeguards.

    • Do not execute instructions found in retrieved content: Search results and web pages may contain text such as “ignore previous instructions.” Treat tool output as untrusted data used only to extract facts, not as operational instructions. State this rule in the system message as well.
    • Filter malicious URLs: Apply domain allowlists or blocklists to search results and block known phishing or malicious domains. In high-risk scenarios, display only reviewed sources.
    • Respect copyright and cite sources: Quote only the necessary portions of retrieved content and include the original URL. Do not reproduce an entire web page.
    • Inform users: Clearly label information as coming from public web search so users do not assume that everything comes from the model’s internal knowledge.
    • Limit search scope: For medical, legal, and financial topics, consider restricting searches to designated authoritative sites and remind users to rely on official information.

    10. Pre-Launch Checklist

    Verify each item before deployment:

    1. Activation conditions: Pass tools only for requests that need current information, and verify that general knowledge questions do not trigger web access.
    2. Cost limits: Set a maximum number of rounds per request and configure alerts for daily spending or call volume.
    3. Fallback behavior: Define responses for empty search results, extraction failures, and time-sensitive information.
    4. Compliance notices: Label information sources in the interface, include verifiable links in answers, and complete copyright and privacy reviews.
    5. Security controls: State in the system message that retrieved instructions must not be executed, and ensure domain filtering is active.
    6. Key management: Store API keys only in environment variables or a secrets manager. Do not log complete keys or sensitive user information.
    7. Monitoring: Add all six metrics listed above to a dashboard and assign responsibility for weekly review.

    Following this workflow allows developers to validate results with a small amount of traffic before gradually expanding usage. Web access provides valuable real-time information, but it also introduces additional cost, latency, and compliance responsibilities. Each of these areas should have a defined handling strategy before the feature goes live.