---
title: "服务器端工具（OpenAI 聊天补全 API）"
description: "了解如何使用 OpenAI 聊天补全 API 调用服务器端工具。"
canonical_url: "https://tiptap.zhcndoc.com/content-ai/capabilities/agent/custom-llms/server-side-tools/openai-chat-completions"
---

# 服务器端工具（OpenAI 聊天补全 API）

了解如何使用 OpenAI 聊天补全 API 调用服务器端工具。

本指南介绍如何使用 OpenAI 聊天补全 API 调用服务器端工具。示例中展示了一个返回指定地点天气的工具。

> **提供代码示例:**
>
> 本指南包含代码示例，帮助你快速入门。详见 [GitHub 仓库](https://github.com/ueberdosis/ai-agent-custom-llm-demos)。

首先，在 [OpenAI 聊天补全 API 工具格式](https://platform.openai.com/docs/guides/function-calling)中定义该工具：

```ts
const weatherTool = {
  type: 'function',
  function: {
    name: 'get_weather',
    description: '返回指定地点的天气',
    parameters: {
      type: 'object',
      properties: {
        location: {
          type: 'string',
          description: '需要查询天气的地点',
        },
      },
      required: ['location'],
    },
  },
}
```

接着，调用 OpenAI API 时，在 `tools` 数组中包含该工具。

```ts
import {
  AiAgentToolkit,
  openaiChatCompletionsAdapter,
  ChatMessagesFormatter,
} from '@tiptap-pro/extension-ai-agent-server'
import OpenAI from 'openai'

const { chatMessages, schemaAwarenessData } = request

const toolkit = new AiAgentToolkit({
  adapter: openaiChatCompletionsAdapter,
  schemaAwarenessData,
})

const formatter = new ChatMessagesFormatter({
  initialMessages: chatMessages,
  adapter: openaiChatCompletionsAdapter,
})

// 初始化 OpenAI 客户端
const openai = new OpenAI()

// 调用 OpenAI 聊天补全 API
const response = await openai.chat.completions.create({
  model: 'gpt-4.1',
  messages: [
    {
      role: 'system',
      content: `
<你的系统提示>
${toolkit.getSystemPrompt()}
`,
    },
    ...formatter.format(),
  ],
  // 在 AiAgentToolkit 提供的工具列表外，额外包含天气工具
  tools: [...toolkit.format(), weatherTool],
})
```

首先，将响应添加到 formatter 中，以便纳入对话。

```ts
formatter.addAiResponse(response)
```

然后，检查响应中是否包含类似天气工具的服务器端工具调用，如果有，则调用该工具并将结果添加到 formatter 中。之后，再次调用 OpenAI API。

重复此过程，直到响应中不再包含服务器端工具调用。

```ts
const isGetWeatherToolCall = (toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall) =>
  toolCall.function.name === 'get_weather'

let response: OpenAI.Chat.Completions.ChatCompletion | null = null

while (!response || response.choices[0].message.tool_calls?.some(isGetWeatherToolCall)) {
  // 调用 OpenAI 聊天补全 API
  response = await openai.chat.completions.create({
    model: 'gpt-4.1',
    messages: [
      {
        role: 'system',
        content: `${systemPrompt}\n${toolkit.getSystemPrompt()}`,
      },
      ...formatter.format(),
    ],
    // 在 AiAgentToolkit 其他工具旁包含天气工具
    tools: [...toolkit.format(), weatherTool],
  })

  // 将响应转换为 AI Agent 扩展所需的格式
  formatter.addAiResponse(response)

  // 处理天气工具调用
  for (const toolCall of response.choices[0].message.tool_calls || []) {
    if (isGetWeatherToolCall(toolCall)) {
      const args = locationSchema.parse(JSON.parse(toolCall.function.arguments))
      const weatherResult = await getWeather(args.location)

      // 将工具调用结果添加到 formatter
      formatter.addChatMessage({
        type: 'toolCallResult',
        toolName: 'get_weather',
        toolCallId: toolCall.id,
        result: weatherResult,
        isError: false,
      })
    }
  }
}
```

最后，当没有更多服务器端工具调用时，使用 `formatter` 将响应转换为 AI Agent 扩展所需的格式。

```ts
const response = formatter.getResolverResponse()
```

`formatter.getResolverResponse()` 返回的值应作为你的 API 端点响应以及解析器函数的返回值。
