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

# 函数调用

> 通过与 OpenAI 兼容的函数调用能力和聊天补全 API，让 Venice 聊天模型调用你应用中的工具。

函数调用允许模型选择结构化的工具调用，由你的应用来执行。模型本身并不会运行函数，它会返回函数名和参数，由你的代码运行该函数，然后再把结果返回给模型。

当模型需要实时数据、执行应用操作、查询数据库或进行确定性计算时，可以使用函数调用。

## 基本工具定义

使用与 OpenAI 兼容的 `tools` 数组来定义工具：

<CodeGroup>
  ```python Python theme={"system"}
  import os
  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ["VENICE_API_KEY"],
      base_url="https://api.venice.ai/api/v1",
  )

  tools = [
      {
          "type": "function",
          "function": {
              "name": "get_weather",
              "description": "Get the current weather in a location",
              "parameters": {
                  "type": "object",
                  "properties": {
                      "location": {
                          "type": "string",
                          "description": "City and state, such as San Francisco, CA",
                      }
                  },
                  "required": ["location"],
              },
          },
      }
  ]

  response = client.chat.completions.create(
      model="zai-org-glm-5",
      messages=[{"role": "user", "content": "What is the weather in San Francisco?"}],
      tools=tools,
  )

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

  ```javascript Node.js theme={"system"}
  import OpenAI from "openai";

  const client = new OpenAI({
    apiKey: process.env.VENICE_API_KEY,
    baseURL: "https://api.venice.ai/api/v1",
  });

  const tools = [
    {
      type: "function",
      function: {
        name: "get_weather",
        description: "Get the current weather in a location",
        parameters: {
          type: "object",
          properties: {
            location: {
              type: "string",
              description: "City and state, such as San Francisco, CA",
            },
          },
          required: ["location"],
        },
      },
    },
  ];

  const response = await client.chat.completions.create({
    model: "zai-org-glm-5",
    messages: [{ role: "user", content: "What is the weather in San Francisco?" }],
    tools,
  });

  console.log(response.choices[0].message.tool_calls);
  ```

  ```bash cURL theme={"system"}
  curl https://api.venice.ai/api/v1/chat/completions \
    -H "Authorization: Bearer $VENICE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "zai-org-glm-5",
      "messages": [
        {"role": "user", "content": "What is the weather in San Francisco?"}
      ],
      "tools": [
        {
          "type": "function",
          "function": {
            "name": "get_weather",
            "description": "Get the current weather in a location",
            "parameters": {
              "type": "object",
              "properties": {
                "location": {
                  "type": "string",
                  "description": "City and state, such as San Francisco, CA"
                }
              },
              "required": ["location"]
            }
          }
        }
      ]
    }'
  ```
</CodeGroup>

## 执行工具

当模型选择了一个工具时，检查 `message.tool_calls`，解析其参数，执行你的应用函数，然后把结果作为 `tool` 消息发回。

```python Python theme={"system"}
import json

message = response.choices[0].message
tool_call = message.tool_calls[0]
arguments = json.loads(tool_call.function.arguments)

weather = get_weather(arguments["location"])

follow_up = client.chat.completions.create(
    model="zai-org-glm-5",
    messages=[
        {"role": "user", "content": "What is the weather in San Francisco?"},
        message.model_dump(),
        {
            "role": "tool",
            "tool_call_id": tool_call.id,
            "content": json.dumps(weather),
        },
    ],
    tools=tools,
)

print(follow_up.choices[0].message.content)
```

## 选择模型

函数调用的支持因模型而异。可在 [文本模型](/models/text) 页面或通过 [Models API](/api-reference/endpoint/models/list) 查找具备 `supportsFunctionCalling` 能力的模型。

<Warning>
  请将工具参数视为不可信输入。在将其用于数据库查询、shell 命令、支付等有副作用的操作之前，务必先进行校验。
</Warning>

## 设计建议

* 让工具名和描述简短、直接。
* 使用 JSON Schema，让模型更容易生成合法的参数。
* 优先使用输入清晰、职责单一的小工具，而不是包含大量可选行为的一个大工具。
* 返回简洁的工具结果，让最终回答有足够的上下文但不会浪费 token。

## 相关资源

* [Chat Completions API](/api-reference/endpoint/chat/completions)
* [文本模型](/models/text)
* [结构化响应指南](/guides/features/structured-responses)
* [LangChain 集成](/guides/integrations/langchain#function-calling-with-agents)
