---
title: OpenAI SDK 相容性
url: https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/openai-sdk
description: Anthropic 提供了一個相容層，讓您能夠使用 OpenAI SDK 來測試 Claude API。只需少量程式碼變更，您就可以快速評估 Anthropic 模型的能力。
---

<Note>
  此相容層主要用於測試和比較模型能力，對於大多數使用情境而言，並不被視為長期或可用於正式環境的解決方案。雖然我們打算讓它保持完整功能且不會有破壞性變更，但優先考量的是 [Claude API](https://platform.claude.com/docs/zh-TW/api/overview) 的可靠性與有效性。

  如需了解已知相容性限制的更多資訊，請參閱[重要的 OpenAI 相容性限制](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/libraries/openai-sdk#important-openai-compatibility-limitations)。

  如果您在使用 OpenAI SDK 相容性功能時遇到任何問題，請透過此[相容性回饋表單](https://forms.gle/oQV4McQNiuuNbz9n8)分享您的回饋。
</Note>

<Tip>
  為了獲得最佳體驗並使用 Claude API 的完整功能集（[PDF 處理](https://platform.claude.com/docs/zh-TW/build-with-claude/pdf-support)、[引用](https://platform.claude.com/docs/zh-TW/build-with-claude/citations)、[思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)以及[提示快取](https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-caching)），請使用原生的 [Claude API](https://platform.claude.com/docs/zh-TW/api/overview)。
</Tip>

## 開始使用 OpenAI SDK

要使用 OpenAI SDK 相容性功能，您需要：

1. 使用官方的 OpenAI SDK

2. 變更以下項目

   * 更新您的 base URL，使其指向 Claude API
   * 將您的 API 金鑰替換為 [Claude API 金鑰](https://platform.claude.com/settings/keys)
   * 如果您的金鑰是可存取多個工作區的[個人或服務帳戶金鑰](https://platform.claude.com/docs/zh-TW/manage-claude/authentication#key-types)，請同時在每個請求中傳送 `anthropic-workspace-id` 標頭（例如，Python SDK 中的 `default_headers` 或 TypeScript 中的 `defaultHeaders`）；請參閱[選擇工作區](https://platform.claude.com/docs/zh-TW/manage-claude/authentication#select-a-workspace)
   * 更新您的模型名稱以使用 [Claude 模型](https://platform.claude.com/docs/zh-TW/models/overview)

3. 檢閱以下各節以了解支援哪些功能

### 快速入門範例

<CodeGroup exclude="shell, php">
  ```python Python
  import os

  from openai import OpenAI

  client = OpenAI(
      api_key=os.environ.get("ANTHROPIC_API_KEY"),  # Your Claude API key
      base_url="https://api.anthropic.com/v1/",  # the Claude API endpoint
  )

  response = client.chat.completions.create(
      model="claude-opus-5-5",  # Claude model name
      messages=[
          {"role": "system", "content": "You are a helpful assistant."},
          {"role": "user", "content": "Who are you?"},
      ],
  )

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

  ```typescript TypeScript
  import OpenAI from "openai";

  const openai = new OpenAI({
    apiKey: process.env.ANTHROPIC_API_KEY, // Your Claude API key
    baseURL: "https://api.anthropic.com/v1/" // Claude API endpoint
  });

  const response = await openai.chat.completions.create({
    messages: [
      { role: "system", content: "You are a helpful assistant." },
      { role: "user", content: "Who are you?" }
    ],
    model: "claude-opus-5-5" // Claude model name
  });

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

  ```csharp C#
  using System.ClientModel;
  using OpenAI;
  using OpenAI.Chat;

  ChatClient chatClient = new(
      model: "claude-opus-5-5", // Claude model name
      credential: new ApiKeyCredential(
          Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")), // Your Claude API key
      options: new OpenAIClientOptions()
      {
          Endpoint = new Uri("https://api.anthropic.com/v1/") // the Claude API endpoint
      });

  ChatCompletion completion = chatClient.CompleteChat(
      new SystemChatMessage("You are a helpful assistant."),
      new UserChatMessage("Who are you?"));

  Console.WriteLine(completion.Content[0].Text);
  ```

  ```go Go
  package main

  import (
  	"context"
  	"fmt"
  	"os"

  	"github.com/openai/openai-go/v3"
  	"github.com/openai/openai-go/v3/option"
  )

  func main() {
  	client := openai.NewClient(
  		option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")),   // Your Claude API key
  		option.WithBaseURL("https://api.anthropic.com/v1/"), // the Claude API endpoint
  	)

  	response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{
  		Model: "claude-opus-5-5", // Claude model name
  		Messages: []openai.ChatCompletionMessageParamUnion{
  			openai.SystemMessage("You are a helpful assistant."),
  			openai.UserMessage("Who are you?"),
  		},
  	})
  	if err != nil {
  		panic(err)
  	}

  	fmt.Println(response.Choices[0].Message.Content)
  }
  ```

  ```java Java
  import com.openai.client.OpenAIClient;
  import com.openai.client.okhttp.OpenAIOkHttpClient;
  import com.openai.models.chat.completions.ChatCompletion;
  import com.openai.models.chat.completions.ChatCompletionCreateParams;

  public class QuickStart {
      public static void main(String[] args) {
          OpenAIClient client = OpenAIOkHttpClient.builder()
                  .apiKey(System.getenv("ANTHROPIC_API_KEY")) // Your Claude API key
                  .baseUrl("https://api.anthropic.com/v1/") // the Claude API endpoint
                  .build();

          ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                  .model("claude-opus-5-5") // Claude model name
                  .addSystemMessage("You are a helpful assistant.")
                  .addUserMessage("Who are you?")
                  .build();

          ChatCompletion completion = client.chat().completions().create(params);
          System.out.println(completion.choices().get(0).message().content().orElse(""));
      }
  }
  ```

  <CodeGroupItem language="PHP">
    OpenAI 沒有官方的 PHP SDK。若要從 PHP 使用 Claude，請改用 [Claude SDK for PHP](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/sdks/php)。
  </CodeGroupItem>

  ```ruby Ruby
  require "openai"

  openai = OpenAI::Client.new(
    api_key: ENV["ANTHROPIC_API_KEY"], # Your Claude API key
    base_url: "https://api.anthropic.com/v1/" # the Claude API endpoint
  )

  response = openai.chat.completions.create(
    model: "claude-opus-5-5", # Claude model name
    messages: [
      {role: "system", content: "You are a helpful assistant."},
      {role: "user", content: "Who are you?"}
    ]
  )

  puts response.choices.first.message.content
  ```
</CodeGroup>

## 重要的 OpenAI 相容性限制

### API 行為

以下是與使用 OpenAI 相比最主要的差異：

* 函式呼叫的 `strict` 參數會被忽略，這表示工具使用的 JSON 不保證會遵循所提供的 schema。若需要保證符合 schema，請使用原生的 [Claude API 搭配結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs)。
* 不支援音訊輸入；它會被忽略並從輸入中移除
* 不支援提示快取（prompt caching），但 [Anthropic SDK](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/overview) 中有支援
* 系統／開發者訊息無論出現在對話中的何處，都會被提升並串接到頂層的 `system` 欄位中。若要在對話進行中途加入系統指示，請在原生 Claude API 中使用[對話中途系統訊息](https://platform.claude.com/docs/zh-TW/build-with-claude/mid-conversation-system-messages)。

大多數不支援的欄位會被靜默忽略，而不會產生錯誤。這些都記錄在以下各節中。

### 輸出品質考量

如果您已對提示進行了大量調整，它很可能是專門針對 OpenAI 調校的。請考慮使用[提示最佳實務指南](https://platform.claude.com/docs/zh-TW/build-with-claude/prompt-engineering/claude-prompting-best-practices)為 Claude 重新調整。

### 系統／開發者訊息提升

OpenAI SDK 的大多數輸入都能清楚地直接對應到 Anthropic 的 API 參數，但一個明顯的差異是系統／開發者提示的處理方式。透過 OpenAI，這兩種提示可以放在聊天對話中的任何位置。相容層會取得所有系統／開發者訊息，並以單一換行符號（`\n`）將它們串接在一起。然後，這個完整的字串會作為頂層的 `system` 欄位提供，位於所有訊息之前。

### 思考支援

您可以透過新增 `thinking` 參數來啟用[思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking)。在目前的模型上，思考是自適應的，由 Claude 決定何時思考以及思考的深度，而在 Claude 5 模型上則預設為開啟；手動設定的擴展思考是一種舊版模式。雖然思考能改善 Claude 在複雜任務上的推理能力，但 OpenAI SDK 不會回傳 Claude 的思考內容。若要使用完整的思考功能，包括[摘要思考](https://platform.claude.com/docs/zh-TW/build-with-claude/thinking#summarized-thinking)，請使用原生的 Claude API。

<CodeGroup exclude="shell, php">
  ```python Python
  response = client.chat.completions.create(
      model="claude-sonnet-4-6",
      messages=[{"role": "user", "content": "Who are you?"}],
      extra_body={"thinking": {"type": "enabled", "budget_tokens": 2000}},
  )
  ```

  ```typescript TypeScript
  const response = await openai.chat.completions.create({
    messages: [{ role: "user", content: "Who are you?" }],
    model: "claude-sonnet-4-6",
    // @ts-expect-error
    thinking: { type: "enabled", budget_tokens: 2000 }
  });
  ```

  ```csharp C#
  // .NET SDK 沒有像 Python 那樣的 extra_body 參數，因此本範例
  // 使用 SDK 文件記載的協定方法來傳送 thinking 參數
  // （原始 JSON 請求主體）。
  BinaryData input = BinaryData.FromString("""
      {
        "model": "claude-sonnet-4-6",
        "messages": [{ "role": "user", "content": "Who are you?" }],
        "thinking": { "type": "enabled", "budget_tokens": 2000 }
      }
      """);

  using BinaryContent content = BinaryContent.Create(input);
  ClientResult result = chatClient.CompleteChat(content);
  ```

  ```go Go
  response, err := client.Chat.Completions.New(
  	context.Background(),
  	openai.ChatCompletionNewParams{
  		Model: "claude-sonnet-4-6",
  		Messages: []openai.ChatCompletionMessageParamUnion{
  			openai.UserMessage("Who are you?"),
  		},
  	},
  	option.WithJSONSet("thinking", map[string]any{"type": "enabled", "budget_tokens": 2000}),
  )
  ```

  ```java Java
  ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
          .model("claude-sonnet-4-6")
          .addUserMessage("Who are you?")
          .putAdditionalBodyProperty("thinking",
                  JsonValue.from(Map.of("type", "enabled", "budget_tokens", 2000)))
          .build();

  ChatCompletion completion = client.chat().completions().create(params);
  ```

  <CodeGroupItem language="PHP">
    OpenAI 沒有官方的 PHP SDK。若要從 PHP 使用 Claude，請改用 [Claude SDK for PHP](https://platform.claude.com/docs/zh-TW/cli-sdks-libraries/sdks/php)。
  </CodeGroupItem>

  ```ruby Ruby
  response = openai.chat.completions.create(
    model: "claude-sonnet-4-6",
    messages: [{role: "user", content: "Who are you?"}],
    request_options: {extra_body: {thinking: {type: "enabled", budget_tokens: 2000}}}
  )
  ```
</CodeGroup>

## 速率限制

速率限制（rate limit）遵循 Anthropic 針對 `/v1/messages` 端點的[標準限制](https://platform.claude.com/docs/zh-TW/api/rate-limits)。

## 詳細的 OpenAI 相容 API 支援

### 請求欄位

#### 簡單欄位

| 欄位                      | 支援狀態                                                                                                                                                                                                                                       |
| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `model`                 | 使用 Claude 模型名稱                                                                                                                                                                                                                             |
| `max_tokens`            | 完全支援                                                                                                                                                                                                                                       |
| `max_completion_tokens` | 完全支援                                                                                                                                                                                                                                       |
| `stream`                | 完全支援                                                                                                                                                                                                                                       |
| `stream_options`        | 完全支援                                                                                                                                                                                                                                       |
| `top_p`                 | 會傳遞給模型。Claude 4.7 及更新的模型以及 Claude Mythos Preview 對於預設值 `0.99` 以外的任何值都會回傳 400 錯誤，因此請省略此參數。同時設定 `temperature` 和 `top_p` 的請求也會回傳 400 錯誤。請參閱[使用 Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)。 |
| `parallel_tool_calls`   | 完全支援                                                                                                                                                                                                                                       |
| `stop`                  | 所有非空白的停止序列皆可運作                                                                                                                                                                                                                             |
| `temperature`           | 介於 0 到 1 之間（含）。大於 1 的值會被限制為 1。在 Claude 4.7 及更新的模型以及 Claude Mythos Preview 上，任何低於 1 的值都會回傳 400 錯誤，因此請省略此參數。請參閱[使用 Messages API](https://platform.claude.com/docs/zh-TW/build-with-claude/working-with-messages)。                            |
| `n`                     | 必須恰好為 1                                                                                                                                                                                                                                    |
| `logprobs`              | 忽略                                                                                                                                                                                                                                         |
| `metadata`              | 忽略                                                                                                                                                                                                                                         |
| `response_format`       | 忽略。若需要 JSON 輸出，請搭配原生 Claude API 使用[結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs)                                                                                                                     |
| `prediction`            | 忽略                                                                                                                                                                                                                                         |
| `presence_penalty`      | 忽略                                                                                                                                                                                                                                         |
| `frequency_penalty`     | 忽略                                                                                                                                                                                                                                         |
| `seed`                  | 忽略                                                                                                                                                                                                                                         |
| `service_tier`          | 忽略                                                                                                                                                                                                                                         |
| `audio`                 | 忽略                                                                                                                                                                                                                                         |
| `logit_bias`            | 忽略                                                                                                                                                                                                                                         |
| `store`                 | 忽略                                                                                                                                                                                                                                         |
| `user`                  | 忽略                                                                                                                                                                                                                                         |
| `modalities`            | 忽略                                                                                                                                                                                                                                         |
| `top_logprobs`          | 忽略                                                                                                                                                                                                                                         |
| `reasoning_effort`      | 忽略                                                                                                                                                                                                                                         |

#### `tools` / `functions` 欄位

<Accordion title="顯示欄位">
  <Tabs>
    <Tab title="Tools">
      `tools[n].function` 欄位

      | 欄位            | 支援狀態                                                                                                                        |
      | ------------- | --------------------------------------------------------------------------------------------------------------------------- |
      | `name`        | 完全支援                                                                                                                        |
      | `description` | 完全支援                                                                                                                        |
      | `parameters`  | 完全支援                                                                                                                        |
      | `strict`      | 忽略。若需要嚴格的 schema 驗證，請搭配原生 Claude API 使用[結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs) |
    </Tab>

    <Tab title="Functions">
      `functions[n]` 欄位

      <Info>
        OpenAI 已棄用 `functions` 欄位，並建議改用 `tools`。
      </Info>

      | 欄位            | 支援狀態                                                                                                                        |
      | ------------- | --------------------------------------------------------------------------------------------------------------------------- |
      | `name`        | 完全支援                                                                                                                        |
      | `description` | 完全支援                                                                                                                        |
      | `parameters`  | 完全支援                                                                                                                        |
      | `strict`      | 忽略。若需要嚴格的 schema 驗證，請搭配原生 Claude API 使用[結構化輸出](https://platform.claude.com/docs/zh-TW/build-with-claude/structured-outputs) |
    </Tab>
  </Tabs>
</Accordion>

#### `messages` 陣列欄位

<Accordion title="顯示欄位">
  <Tabs>
    <Tab title="Developer 角色">
      `messages[n].role == "developer"` 的欄位

      <Info>
        開發者訊息會被提升到對話開頭，作為初始系統訊息的一部分
      </Info>

      | 欄位        | 支援狀態       |
      | --------- | ---------- |
      | `content` | 完全支援，但會被提升 |
      | `name`    | 忽略         |
    </Tab>

    <Tab title="System 角色">
      `messages[n].role == "system"` 的欄位

      <Info>
        系統訊息會被提升到對話開頭，作為初始系統訊息的一部分
      </Info>

      | 欄位        | 支援狀態       |
      | --------- | ---------- |
      | `content` | 完全支援，但會被提升 |
      | `name`    | 忽略         |
    </Tab>

    <Tab title="User 角色">
      `messages[n].role == "user"` 的欄位

      | 欄位        | 變體                               | 子欄位      | 支援狀態 |
      | --------- | -------------------------------- | -------- | ---- |
      | `content` | `string`                         |          | 完全支援 |
      |           | `array`, `type == "text"`        |          | 完全支援 |
      |           | `array`, `type == "image_url"`   | `url`    | 完全支援 |
      |           |                                  | `detail` | 忽略   |
      |           | `array`, `type == "input_audio"` |          | 忽略   |
      |           | `array`, `type == "file"`        |          | 忽略   |
      | `name`    |                                  |          | 忽略   |
    </Tab>

    <Tab title="Assistant 角色">
      `messages[n].role == "assistant"` 的欄位

      | 欄位              | 變體                           | 支援狀態 |
      | --------------- | ---------------------------- | ---- |
      | `content`       | `string`                     | 完全支援 |
      |                 | `array`, `type == "text"`    | 完全支援 |
      |                 | `array`, `type == "refusal"` | 忽略   |
      | `tool_calls`    |                              | 完全支援 |
      | `function_call` |                              | 完全支援 |
      | `audio`         |                              | 忽略   |
      | `refusal`       |                              | 忽略   |
    </Tab>

    <Tab title="Tool 角色">
      `messages[n].role == "tool"` 的欄位

      | 欄位             | 變體                        | 支援狀態                                                                                                                                                                                                                                                        |
      | -------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
      | `content`      | `string`                  | 完全支援                                                                                                                                                                                                                                                        |
      |                | `array`, `type == "text"` | 完全支援                                                                                                                                                                                                                                                        |
      | `tool_call_id` |                           | 完全支援                                                                                                                                                                                                                                                        |
      | `tool_choice`  |                           | 支援。`"required"` 和指定函式名稱的值會強制進行工具呼叫；Claude Opus 5.5、Claude Sonnet 5.5、Claude Fable 5.1 和 Claude Mythos 5.1 不支援強制工具使用並會回傳錯誤，因此在這些模型上請使用 `"auto"`。請參閱[強制工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools#forcing-tool-use)。 |
      | `name`         |                           | 忽略                                                                                                                                                                                                                                                          |
    </Tab>

    <Tab title="Function 角色">
      `messages[n].role == "function"` 的欄位

      | 欄位            | 變體                        | 支援狀態                                                                                                                                                                                                                                                        |
      | ------------- | ------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
      | `content`     | `string`                  | 完全支援                                                                                                                                                                                                                                                        |
      |               | `array`, `type == "text"` | 完全支援                                                                                                                                                                                                                                                        |
      | `tool_choice` |                           | 支援。`"required"` 和指定函式名稱的值會強制進行工具呼叫；Claude Opus 5.5、Claude Sonnet 5.5、Claude Fable 5.1 和 Claude Mythos 5.1 不支援強制工具使用並會回傳錯誤，因此在這些模型上請使用 `"auto"`。請參閱[強制工具使用](https://platform.claude.com/docs/zh-TW/agents-and-tools/tool-use/define-tools#forcing-tool-use)。 |
      | `name`        |                           | 忽略                                                                                                                                                                                                                                                          |
    </Tab>
  </Tabs>
</Accordion>

### 回應欄位

| 欄位                                | 支援狀態    |
| --------------------------------- | ------- |
| `id`                              | 完全支援    |
| `choices[]`                       | 長度永遠為 1 |
| `choices[].finish_reason`         | 完全支援    |
| `choices[].index`                 | 完全支援    |
| `choices[].message.role`          | 完全支援    |
| `choices[].message.content`       | 完全支援    |
| `choices[].message.tool_calls`    | 完全支援    |
| `object`                          | 完全支援    |
| `created`                         | 完全支援    |
| `model`                           | 完全支援    |
| `finish_reason`                   | 完全支援    |
| `content`                         | 完全支援    |
| `usage.completion_tokens`         | 完全支援    |
| `usage.prompt_tokens`             | 完全支援    |
| `usage.total_tokens`              | 完全支援    |
| `usage.completion_tokens_details` | 永遠為空    |
| `usage.prompt_tokens_details`     | 永遠為空    |
| `choices[].message.refusal`       | 永遠為空    |
| `choices[].message.audio`         | 永遠為空    |
| `logprobs`                        | 永遠為空    |
| `service_tier`                    | 永遠為空    |
| `system_fingerprint`              | 永遠為空    |

### 錯誤訊息相容性

相容層會維持與 OpenAI API 一致的錯誤格式。然而，詳細的錯誤訊息不會完全相同。請僅將錯誤訊息用於記錄和除錯。

### 標頭相容性

雖然 OpenAI SDK 會自動管理標頭，但以下是 Claude API 所支援的完整標頭清單，供需要直接處理標頭的開發者參考。

| 標頭                               | 支援狀態             |
| -------------------------------- | ---------------- |
| `x-ratelimit-limit-requests`     | 完全支援             |
| `x-ratelimit-limit-tokens`       | 完全支援             |
| `x-ratelimit-remaining-requests` | 完全支援             |
| `x-ratelimit-remaining-tokens`   | 完全支援             |
| `x-ratelimit-reset-requests`     | 完全支援             |
| `x-ratelimit-reset-tokens`       | 完全支援             |
| `retry-after`                    | 完全支援             |
| `request-id`                     | 完全支援             |
| `openai-version`                 | 永遠為 `2020-10-01` |
| `authorization`                  | 完全支援             |
| `openai-processing-ms`           | 永遠為空             |
