Skip to content

Tools and structured output

Let the model call your functions with tools, and make it answer in a JSON Schema with response_format. Includes a complete round-trip example.

Both features are parameters of the Chat Completions endpoint:

  • Function calling: describe your functions in tools. When the model needs one, it returns tool_calls (which function to call and with what arguments). You run the function, send the result back in a role: tool message, and the model gives its final answer.
  • Structured output: use response_format to make the model output only JSON, or JSON that matches a JSON Schema you specify.

Whether they work depends on the model itself: check the model's description in Model Square first, and if you're not sure, send one real request with a simple function to confirm. The models you can use also depend on your key's group.

POST https://codaapi.com/v1/chat/completions

Request headers

Name Required Description
Authorization Yes Bearer sk-…, your API key
Content-Type Yes application/json

Request body

The table lists only the parameters these two features use. For the rest, see Chat Completions.

Parameter Type Required Description
tools array No The functions the model may call
tools[].type string Yes Always function
tools[].function.name string Yes Function name
tools[].function.description string No What the function does; the model uses it to decide when to call it
tools[].function.parameters object No JSON Schema of the arguments
tools[].function.strict boolean No When true, the model must follow the schema strictly when generating arguments; support depends on the model
tool_choice string or object No auto (default, the model decides), none (no calls), required (must call one), or {"type": "function", "function": {"name": "…"}} to name a function
parallel_tool_calls boolean No Whether the model may return several function calls at once
messages[].tool_calls array No When sending results back, include the tool_calls from the model's previous reply (role: assistant) unchanged
messages[].tool_call_id string No The call ID that a result (role: tool) answers
response_format object No Structured output: {"type": "json_object"} or {"type": "json_schema", "json_schema": {…}}
response_format.json_schema.name string Yes Name of the schema
response_format.json_schema.schema object Yes The JSON Schema
response_format.json_schema.strict boolean No When true, the output follows the schema strictly

How this differs by upstream:

  • OpenAI, Grok: the fields above are passed to the upstream as is.
  • Claude: tools, tool_choice, tool_calls and role: tool results are all converted to Claude's format. response_format isn't converted, so it doesn't constrain Claude models. For structured output, ask for JSON in the prompt, or receive the structured result as the arguments of a function.
  • Gemini: function calling is converted, and the json_object and json_schema types of response_format are converted to Gemini's JSON output settings.

Whether a parameter takes effect in the end depends on the model and the upstream.

Request examples

Here is a complete round trip: the user asks about the weather, the model calls get_current_weather, you run the function and send back the result, and the model answers.

Step 1: send the request with tools

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [{"role": "user", "content": "What is the weather like in Beijing today?"}],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "City name, such as Beijing"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    }]
  }'

parameters is a JSON Schema: the model always provides the arguments listed in required and may leave out the others, and enum limits the allowed values, so unit here can only be celsius or fahrenheit.

Step 2: the model returns tool_calls, with finish_reason set to tool_calls and an empty content. arguments is a JSON string that you parse yourself:

{
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": null,
        "tool_calls": [
          {
            "id": "call_abc123",
            "type": "function",
            "function": { "name": "get_current_weather", "arguments": "{\"location\":\"Beijing\",\"unit\":\"celsius\"}" }
          }
        ]
      },
      "finish_reason": "tool_calls"
    }
  ]
}

Step 3: run the function, send the result back and request again. Put these in messages, in order: the original user message, the model's previous reply (with tool_calls), and the result of each call (role: tool, with tool_call_id matching the ID). Keep sending tools:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [
      {"role": "user", "content": "What is the weather like in Beijing today?"},
      {"role": "assistant", "content": null, "tool_calls": [
        {"id": "call_abc123", "type": "function", "function": {"name": "get_current_weather", "arguments": "{\"location\":\"Beijing\",\"unit\":\"celsius\"}"}}
      ]},
      {"role": "tool", "tool_call_id": "call_abc123", "content": "{\"location\": \"Beijing\", \"weather\": \"sunny\", \"temperature\": 18, \"unit\": \"celsius\"}"}
    ],
    "tools": [{
      "type": "function",
      "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
          "type": "object",
          "properties": {
            "location": {"type": "string", "description": "City name, such as Beijing"},
            "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}
          },
          "required": ["location"]
        }
      }
    }]
  }'

This time the model returns an ordinary text answer, such as "It's sunny in Beijing today, 18 °C", with finish_reason set to stop. The model may also return several tool_calls at once, or call another function after getting a result, so code usually runs this as a loop.

Python (pip install openai)

import json
from openai import OpenAI

client = OpenAI()  # reads OPENAI_BASE_URL and OPENAI_API_KEY

tools = [{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "Get the current weather in a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name, such as Beijing"},
                "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
            },
            "required": ["location"],
        },
    },
}]

def get_current_weather(location, unit="celsius"):
    return {"location": location, "weather": "sunny", "temperature": 18, "unit": unit}  # replace with your own implementation

messages = [{"role": "user", "content": "What is the weather like in Beijing today?"}]

while True:
    response = client.chat.completions.create(model="gpt-5.4-mini", messages=messages, tools=tools)
    message = response.choices[0].message
    if not message.tool_calls:
        break
    messages.append(message)  # add the model's reply (with tool_calls) back to the conversation as is
    for call in message.tool_calls:
        result = get_current_weather(**json.loads(call.function.arguments))
        messages.append({
            "role": "tool",
            "tool_call_id": call.id,
            "content": json.dumps(result),
        })

print(message.content)

Node.js (npm install openai)

import OpenAI from 'openai';

const client = new OpenAI(); // reads OPENAI_BASE_URL and OPENAI_API_KEY

const tools = [{
  type: 'function',
  function: {
    name: 'get_current_weather',
    description: 'Get the current weather in a given location',
    parameters: {
      type: 'object',
      properties: {
        location: { type: 'string', description: 'City name, such as Beijing' },
        unit: { type: 'string', enum: ['celsius', 'fahrenheit'] },
      },
      required: ['location'],
    },
  },
}];

function getCurrentWeather({ location, unit = 'celsius' }) {
  return { location, weather: 'sunny', temperature: 18, unit }; // replace with your own implementation
}

const messages = [{ role: 'user', content: 'What is the weather like in Beijing today?' }];

let message;
while (true) {
  const completion = await client.chat.completions.create({ model: 'gpt-5.4-mini', messages, tools });
  message = completion.choices[0].message;
  if (!message.tool_calls?.length) break;
  messages.push(message); // add the model's reply (with tool_calls) back to the conversation as is
  for (const call of message.tool_calls) {
    const result = getCurrentWeather(JSON.parse(call.function.arguments));
    messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
  }
}

console.log(message.content);

Structured output

Use json_schema to make the model output JSON that matches a schema. Here the model solves an equation step by step, writing each step as an item of steps and the answer in final_answer:

curl https://codaapi.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [
      {"role": "system", "content": "You are a helpful math tutor. Explain the solution step by step."},
      {"role": "user", "content": "Solve 8x + 31 = 2"}
    ],
    "response_format": {
      "type": "json_schema",
      "json_schema": {
        "name": "math_response",
        "strict": true,
        "schema": {
          "type": "object",
          "properties": {
            "steps": {
              "type": "array",
              "items": {
                "type": "object",
                "properties": {"explanation": {"type": "string"}, "output": {"type": "string"}},
                "required": ["explanation", "output"],
                "additionalProperties": false
              }
            },
            "final_answer": {"type": "string"}
          },
          "required": ["steps", "final_answer"],
          "additionalProperties": false
        }
      }
    }
  }'

The returned message.content is a JSON string that matches the schema, which you parse yourself. For example:

{"steps": [{"explanation": "Subtract 31 from both sides", "output": "8x = -29"}, {"explanation": "Divide both sides by 8", "output": "x = -29/8"}], "final_answer": "x = -29/8"}

With strict set to true, OpenAI requires "additionalProperties": false on every object and every property listed in required, as in the schema above.

response = client.chat.completions.create(
    model="gpt-5.4-mini",
    messages=[
        {"role": "system", "content": "You are a helpful math tutor. Explain the solution step by step."},
        {"role": "user", "content": "Solve 8x + 31 = 2"},
    ],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "math_response",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "steps": {
                        "type": "array",
                        "items": {
                            "type": "object",
                            "properties": {"explanation": {"type": "string"}, "output": {"type": "string"}},
                            "required": ["explanation", "output"],
                            "additionalProperties": False,
                        },
                    },
                    "final_answer": {"type": "string"},
                },
                "required": ["steps", "final_answer"],
                "additionalProperties": False,
            },
        },
    },
)
data = json.loads(response.choices[0].message.content)
for step in data["steps"]:
    print(step["explanation"], "→", step["output"])
print(data["final_answer"])  # x = -29/8

When you only need valid JSON without a fixed structure, use {"type": "json_object"}. OpenAI then requires the messages to ask for JSON explicitly (for example, "Answer in JSON"), or the request fails.

Response

The response format is the same as Chat Completions. The relevant fields:

Field Description
choices[].message.tool_calls[].id ID of this call; put it in tool_call_id when sending the result back
choices[].message.tool_calls[].function.name The function to call
choices[].message.tool_calls[].function.arguments The arguments, as a JSON string
choices[].finish_reason tool_calls when the model wants to call a function
choices[].message.content A JSON string for structured output

When streaming, function calls arrive in pieces in choices[0].delta.tool_calls: the pieces of one call carry the same index, and you join their arguments in order.

In the Responses API

The Responses endpoint supports both features too, with a different format:

Item Chat Completions Responses
Defining a function {"type": "function", "function": {"name": …, "parameters": …}} {"type": "function", "name": …, "parameters": …} (not nested in function)
The model calls a function message.tool_calls[], matched by id Items in output[] whose type is function_call, matched by call_id
Sending the result back {"role": "tool", "tool_call_id": …, "content": …} In input, first include the function_call item the model returned, then add {"type": "function_call_output", "call_id": …, "output": …}
Structured output response_format text.format, such as {"type": "json_schema", "name": …, "schema": …}

Errors

Errors come back with a 4xx or 5xx status code and an OpenAI-style error body, {"error": {"message": "…", "type": "…", "code": "…"}}, where message ends with the ID of the request (the request id). For common status codes and what to do about them, see Error codes.

Billing

Billing is by tokens: the tools definitions and the function results you send back count as input tokens, and the call arguments the model generates count as output tokens. A round trip is two requests, each billed separately. For each model's price, see Model Square and the price list; for the rules, see Pricing and multipliers.

Updated