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

# 函数调用

> 让模型调用外部工具和 API

EzTokens 对话 API 支持工具调用能力，使模型能够调用函数、并行执行工具、处理复杂的多步骤工作流。

## 基础示例

<Tabs>
  <Tab title="cURL">
    ```bash theme={null}
    curl https://api.eztokens.ai/v1/chat/completions \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer $EZTOKENS_API_KEY" \
      -d '{
        "model": "gpt-4.1",
        "messages": [{"role": "user", "content": "What is the weather like in Paris today?"}],
        "tools": [{
          "type": "function",
          "function": {
            "name": "get_weather",
            "description": "Get current temperature for a given location.",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {"type": "string", "description": "City and country e.g. Bogotá, Colombia"}
              },
              "required": ["location"]
            }
          }
        }]
      }'
    ```
  </Tab>

  <Tab title="Python">
    ```python theme={null}
    from openai import OpenAI

    client = OpenAI(
        api_key="EZTOKENS_API_KEY",
        base_url="https://api.eztokens.ai/v1"
    )

    tools = [{
        "type": "function",
        "function": {
            "name": "get_weather",
            "description": "Get current temperature for a given location.",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "City and country e.g. Bogotá, Colombia"
                    }
                },
                "required": ["location"],
                "additionalProperties": False
            }
        }
    }]

    response = client.chat.completions.create(
        model="gpt-4.1",
        messages=[{"role": "user", "content": "What is the weather like in Paris today?"}],
        tools=tools
    )

    print(response.choices[0].message.tool_calls)
    ```
  </Tab>

  <Tab title="Node.js">
    ```javascript theme={null}
    import OpenAI from "openai";

    const client = new OpenAI({
      apiKey: "EZTOKENS_API_KEY",
      baseURL: "https://api.eztokens.ai/v1",
    });

    const tools = [{
      type: "function",
      function: {
        name: "get_weather",
        description: "Get current temperature for a given location.",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "City and country e.g. Bogotá, Colombia"
            }
          },
          required: ["location"],
        }
      }
    }];

    const response = await client.chat.completions.create({
      model: "gpt-4.1",
      messages: [{ role: "user", content: "What is the weather like in Paris today?" }],
      tools,
    });

    console.log(response.choices[0].message.tool_calls);
    ```
  </Tab>
</Tabs>

## `tool_choice` 选项

| 值                                                           | 说明               |
| ----------------------------------------------------------- | ---------------- |
| `auto`                                                      | 模型自行决定是否调用工具（默认） |
| `none`                                                      | 模型不调用任何工具        |
| `required`                                                  | 模型必须调用一个或多个工具    |
| `{"type": "function", "function": {"name": "my_function"}}` | 强制调用指定工具         |

## 并行工具调用

```python theme={null}
response = client.chat.completions.create(
    model="gpt-4.1",
    messages=[
        {"role": "user", "content": "What's the weather in Paris and London?"}
    ],
    tools=tools
)

for tool_call in response.choices[0].message.tool_calls:
    print(tool_call.function.name)
    print(tool_call.function.arguments)
```

## 处理函数调用结果

```python theme={null}
import json

# 模拟调用外部天气 API
def get_weather(location):
    return f"24°C, sunny in {location}"

available_functions = {"get_weather": get_weather}

messages = [{"role": "user", "content": "What's the weather in Paris?"}]
response = client.chat.completions.create(
    model="gpt-4.1",
    messages=messages,
    tools=tools
)

tool_call = response.choices[0].message.tool_calls[0]
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
function_response = available_functions[function_name](**function_args)

messages.append(response.choices[0].message)
messages.append({
    "role": "tool",
    "tool_call_id": tool_call.id,
    "content": function_response
})

final_response = client.chat.completions.create(
    model="gpt-4.1",
    messages=messages
)
print(final_response.choices[0].message.content)
```
