How to Build a Chatbot With Tool Calling: A Step-by-Step Guide

Tool calling lets a chatbot look up data and take actions. This step-by-step guide covers the loop, code examples, parallel calls and production hardening.

By Galactic News Editorial · Published 2026-11-22T01:53:35+00:00 · Updated 2026-11-22T01:53:35+00:00

How to build a chatbot with tool calling step by step guide

How to Build a Chatbot With Tool Calling: A Step-by-Step Guide

Tool calling lets a chatbot do more than chat. It lets the model ask your code to look up data, run a calculation or take an action. The model never runs your code itself. It returns a structured request. Your code runs the function and sends the result back. This guide walks through how to build a chatbot with tool calling, step by step, using the OpenAI and Anthropic docs as the reference.

How Tool Calling Works

Tool calling is a five-step loop. First, you send the model a message plus a list of tools it may call. Each tool has a name, a description and a JSON schema for its arguments. Second, the model replies with a tool call instead of plain text. Third, your code runs the named function with the supplied arguments. Fourth, you send the result back to the model. Fifth, the model gives a final answer, or calls another tool.

OpenAI calls this function calling. Anthropic calls it tool use. The shape is the same. The model decides when a tool is needed. Your code does the work. In the OpenAI Responses API, a tool call arrives as a function_call item with a call_id. In the Anthropic Messages API, it arrives as a tool_use block with an id and a stop_reason of tool_use. You must echo that id back with the result so the API can match them.

Step 1: Define Your Tools

Start with one or two tools. A weather lookup and an order lookup are good first examples. Each tool needs a clear name, a plain description and a JSON schema. The description is the model's guide. It tells the model when to call the tool and how to fill each field. Name tools with verbs, such as get_weather or search_orders. Keep the schema tight. Every required field should be truly required. Optional fields should have defaults.

Here is a tool definition in the OpenAI style:

tools = [
    {
        "type": "function",
        "name": "get_weather",
        "description": "Get the current weather for a city.",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name, e.g. Lahore"}
            },
            "required": ["location"]
        }
    }
]

In the Anthropic style, the same tool uses name, description and input_schema. The fields map one to one. Pick one provider first. Learn the loop there. Then port it.

Step 2: Send the First Request

Call the API with the user's message and your tools list. Use the provider's SDK. In the OpenAI Python SDK, the call looks like this:

from openai import OpenAI
client = OpenAI()
response = client.responses.create(
    model="gpt-4o",
    input=[{"role": "user", "content": "What is the weather in Lahore?"}],
    tools=tools,
)

Do not expect the model to call a tool for every question. With the default tool_choice of auto, the model calls a tool only when the answer is not already in context. For greetings and general questions, it answers directly. That is correct behaviour.

Step 3: Detect the Tool Call

Inspect the response. In the OpenAI Responses API, look through response.output for a function_call item. It carries the tool name, the arguments as a JSON string, and a call_id. In the Chat Completions API, the finish_reason is tool_calls and the message carries a tool_calls list. In the Anthropic API, check stop_reason for tool_use and read the tool_use blocks from response.content. Each block has a name, an input dict and an id.

Parse the arguments with json.loads. Validate them before running anything. If a required argument is missing or the wrong type, return an error to the model instead of crashing. The model can often fix its own call on the next turn.

Step 4: Run the Function and Return the Result

Run the real function in your code. Call the weather API, query the database, or read the file. Keep the result small and structured. A JSON object is best. Then send it back to the model with the matching call id. In the OpenAI Responses API, the result goes in a function_call_output item tied to the call_id. In the Anthropic API, it goes in a tool_result block tied to the tool_use id.

Then call the model again with the full conversation so far. The model now has the data it lacked. It composes a natural-language answer. For example: "It is 28 degrees in Lahore, with clear skies."

Step 5: Loop Until the Answer Is Done

One turn is rarely enough. A complex question may need several tool calls in sequence. Wrap the loop in a function with a step limit, such as five or ten steps. Each iteration checks the response. If it contains a tool call, run it and continue. If it contains text, return it as the answer. If the step limit is hit, stop and tell the user the task needs more steps.

Some questions need parallel calls. Asking for the weather in two cities needs two independent lookups. Both OpenAI and Anthropic support parallel tool calls. The model emits several tool calls in one response. Run them all, then send all the results back together. If your tools have ordering dependencies, force serial calls. OpenAI offers parallel_tool_calls: false for that case.

Step 6: Harden the Chatbot for Production

Four things separate a demo from a production chatbot. First, strict schemas. Set strict: true on OpenAI tools so the model output must conform to your schema. That cuts malformed arguments. Second, timeouts and retries. Every external call can fail. Give each tool a timeout. Return the error to the model so it can retry or explain.

Third, guardrails on actions. Read-only tools are safe to run freely. Tools that send email, charge a card or delete data need confirmation. Ask the user before running them, or require an explicit approval step. Fourth, logging. Log every tool call, its arguments and its result. That log is your debugging tool and your audit trail.

Common Mistakes to Avoid

The most common mistake is letting the model see too many tools. A long tool list confuses the model and wastes context. Keep the list short. Load extra tools only when the conversation needs them. OpenAI supports tool search for deferring rarely used tools.

The second mistake is vague descriptions. If the description does not say when to call the tool, the model guesses. Write the description like documentation for a new team member. State the purpose, the inputs and the limits.

The third mistake is trusting tool arguments blindly. Validate types and ranges. Never pass model output into a shell command or a raw SQL string. Treat arguments as untrusted input from a user.

OpenAI or Anthropic: Which to Start With

FeatureOpenAIAnthropic
Feature nameFunction callingTool use
Main APIResponses API and Chat CompletionsMessages API
Tool call itemfunction_call with call_idtool_use block with id
Result itemfunction_call_outputtool_result block
Strict schemasstrict: trueJSON Schema via input_schema
Built-in toolsWeb search, code execution, MCPWeb search, web fetch, code execution

Both providers also offer built-in tools and SDK helpers that run the loop for you. The OpenAI Agents SDK derives tool schemas from Python functions with a decorator. Anthropic offers a tool runner in its SDKs. Use those once you understand the manual loop. They hide the plumbing, but the plumbing is what you debug when things break.

Bottom Line

Tool calling is a simple loop. Define tools with clear schemas. Send them with the user's message. Run the function the model requests. Send the result back. Repeat until the answer is done. Start with one read-only tool and a strict schema. Add action tools only with confirmation and logging. The chatbot that calls tools well is the chatbot that answers with real data instead of guesses.