> ## Documentation Index
> Fetch the complete documentation index at: https://docs.scitix.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Function Calling（Tool Calling）

Function Calling allows a model to call the tools you define when appropriate and return a structured call request that specifies which tool to call and what arguments to pass. Your application is responsible for executing the corresponding tool and returning the result to the model, and the model then uses those results to generate the final answer.

Function Calling is commonly used to build agents, retrieval systems, and integrations with external systems such as weather services, databases, and internal APIs.

This capability is provided through an OpenAI-compatible calling pattern. You can pass a `tools` array in the request, read `tool_calls` from the response, and send tool execution results back as `role: "tool"` messages.

## Use Cases

* **Real-time data**: Look up weather, prices, inventory, or other real-time information.
* **Actions**: Create tickets, send messages, or trigger workflows from natural language.
* **Retrieval / RAG**: Let the model decide when to query a knowledge base or search API.
* **Agents**: Chain multiple tool calls to complete multi-step tasks.

## Supported Models

Most chat models on the platform support this capability. For details, refer to [Models](https://console.scitix.ai/model-inference/models).

## How It Works

The complete Function Calling flow usually includes two model calls:

1. Send the user message together with the `tools` definitions to the model. Each tool definition includes the tool name, description, and parameter JSON Schema.
2. If the model decides to call a tool, the response returns `finish_reason: "tool_calls"` and provides call information in `message.tool_calls`.
3. Your application executes the corresponding function, then appends the assistant message and a `role: "tool"` message with the matching `tool_call_id` to the conversation.
4. Call the API again, and the model uses the tool execution result to generate the final answer.

<Warning>
  The model only generates tool call requests. It does not execute functions on behalf of your application. Your application runs the function and sends the result back to the model.
</Warning>

## Key Parameters

* `tools`: An array of tool definitions that tells the model which tools are available.
* `tool_calls`: Tool call requests returned by the model, including tool names and arguments.
* `tool_call_id`: The tool call ID. When returning tool results, use this ID to match the result with the original call request.
* `role: "tool"`: The message role used to send tool execution results back to the model.
* `tool_choice`: Controls tool calling behavior. Use `"auto"` to let the model decide, `"none"` to disable tool calls, or force the model to call a specific tool.

## Best Practices

* **Describe tools clearly**: Use clear `name`, `description`, and `parameters` JSON Schema fields for each tool. Clearer definitions make model calls more stable.
* **Validate arguments**: The model generates the arguments, so validate them before executing any real action.
* **Handle multiple tool calls**: `tool_calls` in a single response may contain multiple calls. Execute each one, and add the corresponding `role: "tool"` message for each call before calling the API again.
* **Preserve call relationships**: When returning tool results, you must use the matching `tool_call_id`; otherwise, the model cannot reliably associate tool results with call requests.
* **Reserve token budget**: Set `max_completion_tokens` appropriately and leave enough room. For reasoning-capable models, the reasoning process itself also consumes budget.

## Examples

The examples read the API key from an environment variable to avoid writing secrets into code.

```bash theme={null}
export API_KEY="YOUR_API_KEY"
```

The example demonstrates the standard Function Calling interaction flow:

1. The model independently decides during the conversation whether to request an external tool call, such as querying the weather.

2. The client executes the tool locally and returns the result to the model.

3. The model combines the tool result with the conversation and generates a natural-language reply.

```python theme={null}
import os
import json
from openai import OpenAI

client = OpenAI(
    api_key=os.environ["API_KEY"],
    base_url="https://api.scitix.ai/model-api",
)

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


def get_weather(city: str) -> dict:
    # Replace with a real API call.
    return {"city": city, "temp_c": 21, "condition": "Sunny"}


messages = [
    {"role": "user", "content": "What's the weather like in Paris today?"}
]

# 1. First call: the model decides whether to use the tool.
resp = client.chat.completions.create(
    model="Qwen/Qwen3-32B",
    messages=messages,
    tools=tools,
    tool_choice="auto",
    max_completion_tokens=1024,
)

msg = resp.choices[0].message

if msg.tool_calls:
    messages.append(msg)

    for call in msg.tool_calls:
        args = json.loads(call.function.arguments)
        result = get_weather(**args)

        # 2. Return the tool result, linked by tool_call_id.
        messages.append(
            {
                "role": "tool",
                "tool_call_id": call.id,
                "content": json.dumps(result),
            }
        )

    # 3. Second call: the model writes the final answer.
    final = client.chat.completions.create(
        model="Qwen/Qwen3-32B",
        messages=messages,
        max_completion_tokens=1024,
    )

    print(final.choices[0].message.content)
else:
    print(msg.content)
```
