---
title: OpenAI SDKとの互換性
url: https://platform.claude.com/docs/ja/cli-sdks-libraries/libraries/openai-sdk
description: Anthropicは、OpenAI SDKを使用してClaude APIをテストできる互換性レイヤーを提供しています。わずかなコード変更で、Anthropicモデルの機能をすばやく評価できます。
---

<Note>
  この互換性レイヤーは、主にモデルの機能をテストおよび比較することを目的としており、ほとんどのユースケースにおいて長期的または本番環境向けのソリューションとは見なされていません。完全に機能し続け、破壊的な変更が行われないことを意図していますが、優先されるのは[Claude API](https://platform.claude.com/docs/ja/api/overview)の信頼性と有効性です。

  既知の互換性の制限事項の詳細については、[OpenAI互換性に関する重要な制限事項](https://platform.claude.com/docs/ja/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/ja/build-with-claude/pdf-support)、[引用](https://platform.claude.com/docs/ja/build-with-claude/citations)、[思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)、[プロンプトキャッシング](https://platform.claude.com/docs/ja/build-with-claude/prompt-caching)）へのアクセスのためには、ネイティブの[Claude API](https://platform.claude.com/docs/ja/api/overview)を使用してください。
</Tip>

## OpenAI SDKを使い始める

OpenAI SDK互換機能を使用するには、次の手順が必要です。

1. 公式のOpenAI SDKを使用する

2. 以下を変更する

   * ベースURLをClaude APIを指すように更新する
   * APIキーを[Claude APIキー](https://platform.claude.com/settings/keys)に置き換える
   * キーが複数のワークスペースにアクセスできる[個人キーまたはサービスアカウントキー](https://platform.claude.com/docs/ja/manage-claude/authentication#key-types)である場合は、すべてのリクエストで`anthropic-workspace-id`ヘッダーも送信する（たとえば、Python SDKでは`default_headers`、TypeScriptでは`defaultHeaders`）。[ワークスペースの選択](https://platform.claude.com/docs/ja/manage-claude/authentication#select-a-workspace)を参照してください
   * モデル名を[Claudeモデル](https://platform.claude.com/docs/ja/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を使用するには、代わりに[PHP用Claude SDK](https://platform.claude.com/docs/ja/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`パラメータは無視されます。つまり、「tool use」（ツール使用）のJSONが指定されたスキーマに従うことは保証されません。スキーマへの準拠を保証するには、ネイティブの[Claude APIの構造化出力](https://platform.claude.com/docs/ja/build-with-claude/structured-outputs)を使用してください。
* 音声入力はサポートされていません。無視され、入力から削除されます
* プロンプトキャッシングはサポートされていませんが、[Anthropic SDK](https://platform.claude.com/docs/ja/cli-sdks-libraries/overview)ではサポートされています
* システム/開発者メッセージは、会話内のどこに出現しても、引き上げられてトップレベルの`system`フィールドに連結されます。会話の途中でシステム指示を追加するには、ネイティブのClaude APIで[会話途中のシステムメッセージ](https://platform.claude.com/docs/ja/build-with-claude/mid-conversation-system-messages)を使用してください。

サポートされていないフィールドのほとんどは、エラーを発生させるのではなく、暗黙的に無視されます。これらはすべて以下のセクションに記載されています。

### 出力品質に関する考慮事項

プロンプトに多くの調整を加えてきた場合、それはOpenAIに特化して最適化されている可能性が高いです。[プロンプトのベストプラクティスガイド](https://platform.claude.com/docs/ja/build-with-claude/prompt-engineering/claude-prompting-best-practices)を使用して、Claude向けに作り直すことを検討してください。

### システム/開発者メッセージの引き上げ

OpenAI SDKへの入力のほとんどはAnthropicのAPIパラメータに明確かつ直接対応していますが、明確な違いの1つはシステム/開発者プロンプトの扱いです。OpenAIでは、これら2つのプロンプトをチャット会話全体のどこにでも配置できます。互換性レイヤーは、すべてのシステム/開発者メッセージを取得し、それらの間に単一の改行（`\n`）を挟んで連結します。この完全な文字列は、すべてのメッセージの前に、トップレベルの`system`フィールドとして提供されます。

### 思考のサポート

`thinking`パラメータを追加することで、[思考](https://platform.claude.com/docs/ja/build-with-claude/thinking)を有効にできます。現在のモデルでは思考は適応型であり、Claudeがいつ、どの程度深く思考するかを判断します。また、Claude 5モデルではデフォルトで有効になっています。手動で設定する拡張思考はレガシーモードです。思考は複雑なタスクにおけるClaudeの推論を向上させますが、OpenAI SDKはClaudeの思考を返しません。[要約された思考](https://platform.claude.com/docs/ja/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パラメータがないため、この例では
  // .NET SDKのドキュメント化されたプロトコルメソッド（生のJSONリクエストボディ）を使用して
  // thinkingパラメータを送信します。
  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を使用するには、代わりに[PHP用Claude SDK](https://platform.claude.com/docs/ja/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」（レート制限）は、`/v1/messages`エンドポイントに対するAnthropicの[標準の制限](https://platform.claude.com/docs/ja/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/ja/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/ja/build-with-claude/working-with-messages)を参照してください。                                             |
| `n`                     | 正確に1である必要があります                                                                                                                                                                                                                                                   |
| `logprobs`              | 無視                                                                                                                                                                                                                                                               |
| `metadata`              | 無視                                                                                                                                                                                                                                                               |
| `response_format`       | 無視。JSON出力には、ネイティブのClaude APIで[構造化出力](https://platform.claude.com/docs/ja/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`      | 無視。厳密なスキーマ検証には、ネイティブのClaude APIで[構造化出力](https://platform.claude.com/docs/ja/build-with-claude/structured-outputs)を使用してください |
    </Tab>

    <Tab title="Functions">
      `functions[n]`フィールド

      <Info>
        OpenAIは`functions`フィールドを非推奨とし、代わりに`tools`を使用することを推奨しています。
      </Info>

      | フィールド         | サポート状況                                                                                                                     |
      | ------------- | -------------------------------------------------------------------------------------------------------------------------- |
      | `name`        | 完全にサポート                                                                                                                    |
      | `description` | 完全にサポート                                                                                                                    |
      | `parameters`  | 完全にサポート                                                                                                                    |
      | `strict`      | 無視。厳密なスキーマ検証には、ネイティブのClaude APIで[構造化出力](https://platform.claude.com/docs/ja/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/ja/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/ja/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`           | 常に空            |
