Tool Calling

Before calling, set your API key and TOKENGRID_BASE_URL environment variables. The base URL includes /v1. See the quick start.

Tool calling lets a model request structured application-side functions or API calls.

How it works

  1. Define tools using JSON Schema.
  2. Send tool definitions and messages to the model.
  3. The model may return a tool name and arguments.
  4. Your application validates the request and executes the tool.
  5. Send the result back to the model for a final response.

Quick example

The weather example shows how to send a tool definition, execute it in the application, and return the result. The model does not execute the external function itself.

Define a tool and send a request

Python
import os
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["TOKENGRID_API_KEY"],
    base_url=os.environ["TOKENGRID_BASE_URL"]
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather at a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {
                    "type": "string",
                    "description": "City"
                }
            },
            "required": ["location"]
        }
    }
}]

response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
    tools=tools,
    temperature=0.1
)

print(response.choices[0].message.tool_calls)

Execute the tool and return its result

Python · Full example
import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["TOKENGRID_API_KEY"],
    base_url=os.environ["TOKENGRID_BASE_URL"]
)

tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get the current weather at a location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City"}
            },
            "required": ["location"]
        }
    }
}]

# 1. Send the initial request
messages = [{"role": "user", "content": "What is the weather in San Francisco?"}]
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=messages,
    tools=tools,
    temperature=0.1
)

# 2. Check for tool calls
assistant_message = response.choices[0].message
if assistant_message.tool_calls:
    tool_call = assistant_message.tool_calls[0]

    # 3. Execute the application tool
    def get_weather(location):
        return {"location": location, "temperature": 22, "condition": "sunny"}

    function_args = json.loads(tool_call.function.arguments)
    function_result = get_weather(**function_args)

    # 4. Append the tool call and result
    messages.append(assistant_message)
    messages.append({
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": json.dumps(function_result, ensure_ascii=False)
    })

    # 5. Ask the model for a final response
    final_response = client.chat.completions.create(
        model="YOUR_MODEL_ID",
        messages=messages,
        tools=tools,
        temperature=0.1
    )

    print(final_response.choices[0].message.content)

Defining tools

Provide each tool's unique name, a clear description, and parameters with required fields in JSON Schema.

Parameter types

Common types include string, number, integer, object, array, boolean and null. Use specific descriptions and enums where appropriate.

Define multiple tools

Python
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get the current weather at a location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {"type": "string", "description": "City or region"},
                    "unit": {
                        "type": "string",
                        "enum": ["celsius", "fahrenheit"],
                        "description": "Temperature unit"
                    }
                },
                "required": ["location"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_restaurants",
            "description": "Search restaurants by cuisine and location",
            "parameters": {
                "type": "object",
                "properties": {
                    "cuisine": {"type": "string", "description": "Cuisine"},
                    "location": {"type": "string", "description": "City or neighborhood"},
                    "price_range": {
                        "type": "string",
                        "enum": ["$", "$", "$$", "$$"]
                    }
                },
                "required": ["cuisine", "location"]
            }
        }
    }
]

Tool choice

Selecting a tool with tool_choice

tool_choice can let the model choose automatically, prohibit tools, require a tool, or select a named function. Parallel calls depend on model support.

Python · Choose a tool
response = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Get the weather in San Francisco"}],
    tools=tools,
    tool_choice={
        "type": "function",
        "function": {"name": "get_weather"}
    }
)

Streaming tool calls

Tool names and arguments may arrive across multiple chunks. Accumulate each call by index and parse arguments after they are complete.

Python
import json

tool_calls = {}

stream = client.chat.completions.create(
    model="YOUR_MODEL_ID",
    messages=[{"role": "user", "content": "Get the weather in San Francisco"}],
    tools=tools,
    stream=True,
    temperature=0.1
)

for chunk in stream:
    delta_calls = chunk.choices[0].delta.tool_calls
    if delta_calls:
        for item in delta_calls:
            index = item.index
            if index not in tool_calls:
                tool_calls[index] = {"id": "", "name": "", "arguments": ""}

            if item.id:
                tool_calls[index]["id"] = item.id
            if item.function and item.function.name:
                tool_calls[index]["name"] = item.function.name
            if item.function and item.function.arguments:
                tool_calls[index]["arguments"] += item.function.arguments

    if chunk.choices[0].finish_reason == "tool_calls":
        for item in tool_calls.values():
            arguments = json.loads(item["arguments"])
            print(item["name"], arguments)
        break

Troubleshooting

The model does not call a tool

Review the tool description, task clarity, tool choice and model support.

Arguments are invalid

Improve descriptions and examples, use enums and validate arguments before execution.

JSON parsing errors

Handle malformed JSON returned by a model before calling the tool.

Python · Parse arguments
import json

try:
    function_args = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as error:
    print(f"Invalid tool arguments: {error}")