Tool Calling in LLM APIs: A Practical Guide to Building a Chat Assistant with Web Search

    This guide explains how to build a chat application that calls external tools, such as web search and web page reading, through large language model APIs. It walks through the tool-calling loop, how to declare tools in Python, and engineering practices for timeouts, content sanitization, caching, logging, and fallback handling. It also covers what is needed to move from a demo to a production app.

    1. Introduction: Why LLMs Need Tools

    Text-only large language models have a built-in limitation: a knowledge cutoff. No matter how many parameters a model has, its training data ends at some point. It cannot answer questions about today’s weather, news published recently, or the latest content of a specific web page. A model also cannot access external systems on its own. Every answer relies on knowledge stored in its parameters, which can be outdated or even fabricated.

    The widely accepted solution is tool calling, also known as function calling. The application declares a set of external capabilities that the model can invoke. During inference, the model decides for itself whether it needs a tool and which arguments to pass. The application then runs the tool and returns the result to the model, which writes the final answer based on real data. Major model providers now offer complete API suites that include chat, reasoning, and web search. As a result, building a chat assistant similar to popular AI apps has become much easier for developers.

    This article uses two typical tools, web search and web page reading, as examples. It walks through a working engineering implementation step by step.

    2. Architecture: The Call Loop Behind a Single Conversation

    A chat application with tool support is built around a loop of “request, decide, execute, return, request again,” not a single API call:

    1. User question: The application sends the user’s message along with the tool declarations to the model.
    2. Model decision: The model decides whether it needs a tool. If it does, it returns a structured tool call request (tool name and arguments) instead of a final text response.
    3. Application execution: The application routes the request to the matching implementation based on the tool name. For example, it calls a search API or fetches web page content.
    4. Result return: The application appends the tool result to the message history with a specific role, usually the tool role, and then sends the history back to the model.
    5. Answer generation: The model combines the tool results into a natural language answer, and the loop ends.

    Some model services also provide hosted tools. In this case, search and web page reading run on the service side, and the developer only needs to enable them without implementing the execution logic. Each approach has trade-offs. Hosted tools are faster to integrate. Self-implemented tools offer more control and make it easier to connect private data sources.

    3. Quick Start: Declaring and Enabling Tools

    The following example uses the Python client. First, install the dependency:

    1. pip install openai

    Add the tools parameter to the request body to declare two tools: web search and link reading. Naming for built-in tools varies between services. The example below is illustrative:

    1. from openai import OpenAI
    2. client = OpenAI(
    3. api_key="YOUR_API_KEY",
    4. base_url="https://your-model-endpoint.example.com/v1",
    5. )
    6. tools = [
    7. {"type": "builtin", "name": "web_search"}, # Web search
    8. {"type": "builtin", "name": "read_url"}, # Read the content of a link
    9. ]
    10. resp = client.chat.completions.create(
    11. model="your-model-name",
    12. messages=[{"role": "user", "content": "What are the notable tech news items today?"}],
    13. tools=tools,
    14. )
    15. print(resp.choices[0].message.content)

    If you implement standard function tools yourself, declare them using the general schema:

    1. tools = [
    2. {
    3. "type": "function",
    4. "function": {
    5. "name": "web_search",
    6. "description": "Search the internet for up-to-date information related to a query",
    7. "parameters": {
    8. "type": "object",
    9. "properties": {
    10. "query": {"type": "string", "description": "Search keywords"}
    11. },
    12. "required": ["query"],
    13. },
    14. },
    15. },
    16. {
    17. "type": "function",
    18. "function": {
    19. "name": "read_url",
    20. "description": "Fetch and read the main text content of a specified web page",
    21. "parameters": {
    22. "type": "object",
    23. "properties": {
    24. "url": {"type": "string", "description": "Target web page URL"}
    25. },
    26. "required": ["url"],
    27. },
    28. },
    29. },
    30. ]

    Key point: The quality of a tool’s description directly affects the model’s decision to call it. A good description explains when to use the tool and what each parameter means. Avoid vague wording. For example, do not just write “search tool.” Instead, write “Use when the question involves real-time information, recent events, or knowledge beyond the training data.”

    4. Core Implementation: A Complete Tool-Call Loop

    When the model returns a tool call request, the application must parse it, execute it, and return the result. Otherwise, the conversation stops. A typical loop looks like this:

    1. def run_tool(name: str, args: dict) -> str:
    2. if name == "web_search":
    3. return do_search(args["query"]) # Call the search service
    4. if name == "read_url":
    5. return fetch_page(args["url"]) # Fetch the page body text
    6. return "unknown tool"
    7. def chat(user_input: str) -> str:
    8. messages = [{"role": "user", "content": user_input}]
    9. for _ in range(5): # Limit the number of rounds to prevent infinite loops
    10. resp = client.chat.completions.create(
    11. model="your-model-name",
    12. messages=messages,
    13. tools=tools,
    14. )
    15. msg = resp.choices[0].message
    16. messages.append(msg)
    17. if not getattr(msg, "tool_calls", None):
    18. return msg.content # The model returned the final answer
    19. for call in msg.tool_calls:
    20. import json
    21. result = run_tool(call.function.name,
    22. json.loads(call.function.arguments))
    23. messages.append({
    24. "role": "tool",
    25. "tool_call_id": call.id,
    26. "content": result,
    27. })
    28. raise RuntimeError("Exceeded the maximum number of tool-call rounds")

    This code illustrates three key engineering decisions:

    • Complete message history: Append the model’s tool_calls message to the history exactly as returned, then append the matching tool result. Without this, the model cannot link each call to its result.
    • Round limit: With web access, the model may search several times in a row. Set a limit to prevent runaway token usage.
    • Result truncation: A web page can contain tens of thousands of characters. Extract the key passages before returning them to avoid context overflow and sharp cost increases.

    5. Engineering Best Practices

    1. Timeouts and Retries

    Search and web page fetching are external network calls, and their latency varies widely. Set a separate timeout for each tool execution, such as 5 to 10 seconds. When a call fails, return a structured error to the model, such as "error": "fetch timeout". The model can then retry with different keywords or answer directly. Do not let the exception propagate and fail the entire request.

    2. Content Cleaning and Security

    Fetched web pages may contain scripts, ads, tracking parameters, or even prompt injection text, such as a page that says “ignore previous instructions.” Recommendations:

    • Extract only the body text, and strip HTML tags and scripts.
    • Truncate external content to a set length before sending it to the model.
    • State in the system prompt that tool output is data, not instructions. This reduces the risk of prompt injection.

    3. Cost Control and Caching

    Each web tool call adds token usage and external request overhead. You can add a result cache so that identical queries or identical URLs return cached results within a short period, such as 10 minutes. This significantly reduces repeated overhead. You can implement this caching with general-purpose cache or object storage services, without being tied to any specific vendor’s solution.

    4. Observability

    Log every tool call, including the tool name, arguments, duration, result length, and whether it succeeded. Combined with general-purpose logging and monitoring services, these logs help you identify problems such as the model calling tools too often, or a high failure rate for certain pages. You can then refine tool descriptions and implementations.

    5. Graceful Degradation

    When the search service is unavailable, the application should degrade gracefully. Tell the model that the search failed, and let it answer from its own knowledge, noting that the information may not be up to date. This provides a better user experience than returning a raw error.

    6. From Demo to Product: What Else a Chat Assistant Needs

    A working tool call is only the first step. To turn the example code into a usable chat application, you also need:

    • Multi-turn session management: Store session IDs and message history persistently, and trim the context to stay within length limits.
    • Streaming output: Use a streaming interface to return text word by word, which reduces perceived latency. In streaming mode, tool_calls arrive as incremental fragments that must be assembled correctly.
    • Source citations: Attach the source links from search results at the end of the answer to improve credibility.
    • Frontend states: Show distinct states such as “Thinking,” “Searching,” and “Reading web page.” This is a hallmark of popular AI assistant apps.
    • Concurrency and rate limiting: For a public service, add per-user rate limiting and request queuing to prevent resource abuse.

    7. Conclusion

    The shift toward API suites that bundle models and tools gives developers standardized access to combined model and tool capabilities. The core approach is to declare tools, run the call loop, and return results. Add engineering measures such as timeouts, retries, content cleaning, caching, and monitoring. With these, building a chat application that can access real-time information is no longer limited to a few specialized teams. Start with a minimal working example that has two tools, then add the product features step by step.