Repository Public
1---2title: OpenAI SDK compatibility3url: https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk4description: Anthropic provides a compatibility layer that enables you to use the OpenAI SDK to test the Claude API. With a few code changes, you can quickly evaluate Anthropic model capabilities.5---67<Note>8 This compatibility layer is primarily intended to test and compare model capabilities, and is not considered a long-term or production-ready solution for most use cases. While it is intended to remain fully functional and not have breaking changes, the priority is the reliability and effectiveness of the [Claude API](https://platform.claude.com/docs/en/api/overview).910 For more information on known compatibility limitations, see [Important OpenAI compatibility limitations](https://platform.claude.com/docs/en/cli-sdks-libraries/libraries/openai-sdk#important-openai-compatibility-limitations).1112 If you encounter any issues with the OpenAI SDK compatibility feature, please share your feedback via this [compatibility feedback form](https://forms.gle/oQV4McQNiuuNbz9n8).13</Note>1415<Tip>16 For the best experience and access to Claude API full feature set ([PDF processing](https://platform.claude.com/docs/en/build-with-claude/pdf-support), [citations](https://platform.claude.com/docs/en/build-with-claude/citations), [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking), and [prompt caching](https://platform.claude.com/docs/en/build-with-claude/prompt-caching)), use the native [Claude API](https://platform.claude.com/docs/en/api/overview).17</Tip>1819## Getting started with the OpenAI SDK2021To use the OpenAI SDK compatibility feature, you'll need to:22231. Use an official OpenAI SDK24252. Change the following2627 * Update your base URL to point to the Claude API28 * Replace your API key with a [Claude API key](https://platform.claude.com/settings/keys)29 * If your key is a [personal or service account key](https://platform.claude.com/docs/en/manage-claude/authentication#key-types) with access to multiple workspaces, also send the `anthropic-workspace-id` header on every request (for example, `default_headers` in the Python SDK or `defaultHeaders` in TypeScript); see [Select a workspace](https://platform.claude.com/docs/en/manage-claude/authentication#select-a-workspace)30 * Update your model name to use a [Claude model](https://platform.claude.com/docs/en/models/overview)31323. Review the following sections for what features are supported3334### Quick start example3536<CodeGroup exclude="shell">37 ```python Python38 import os3940 from openai import OpenAI4142 client = OpenAI(43 api_key=os.environ.get("ANTHROPIC_API_KEY"), # Your Claude API key44 base_url="https://api.anthropic.com/v1/", # the Claude API endpoint45 )4647 response = client.chat.completions.create(48 model="claude-opus-5", # Claude model name49 messages=[50 {"role": "system", "content": "You are a helpful assistant."},51 {"role": "user", "content": "Who are you?"},52 ],53 )5455 print(response.choices[0].message.content)56 ```5758 ```typescript TypeScript59 import OpenAI from "openai";6061 const openai = new OpenAI({62 apiKey: process.env.ANTHROPIC_API_KEY, // Your Claude API key63 baseURL: "https://api.anthropic.com/v1/" // Claude API endpoint64 });6566 const response = await openai.chat.completions.create({67 messages: [68 { role: "system", content: "You are a helpful assistant." },69 { role: "user", content: "Who are you?" }70 ],71 model: "claude-opus-5" // Claude model name72 });7374 console.log(response.choices[0].message.content);75 ```7677 ```csharp C#78 using System.ClientModel;79 using OpenAI;80 using OpenAI.Chat;8182 ChatClient chatClient = new(83 model: "claude-opus-5", // Claude model name84 credential: new ApiKeyCredential(85 Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")), // Your Claude API key86 options: new OpenAIClientOptions()87 {88 Endpoint = new Uri("https://api.anthropic.com/v1/") // the Claude API endpoint89 });9091 ChatCompletion completion = chatClient.CompleteChat(92 new SystemChatMessage("You are a helpful assistant."),93 new UserChatMessage("Who are you?"));9495 Console.WriteLine(completion.Content[0].Text);96 ```9798 ```go Go99 package main100101 import (102 "context"103 "fmt"104 "os"105106 "github.com/openai/openai-go/v3"107 "github.com/openai/openai-go/v3/option"108 )109110 func main() {111 client := openai.NewClient(112 option.WithAPIKey(os.Getenv("ANTHROPIC_API_KEY")), // Your Claude API key113 option.WithBaseURL("https://api.anthropic.com/v1/"), // the Claude API endpoint114 )115116 response, err := client.Chat.Completions.New(context.Background(), openai.ChatCompletionNewParams{117 Model: "claude-opus-5", // Claude model name118 Messages: []openai.ChatCompletionMessageParamUnion{119 openai.SystemMessage("You are a helpful assistant."),120 openai.UserMessage("Who are you?"),121 },122 })123 if err != nil {124 panic(err)125 }126127 fmt.Println(response.Choices[0].Message.Content)128 }129 ```130131 ```java Java132 import com.openai.client.OpenAIClient;133 import com.openai.client.okhttp.OpenAIOkHttpClient;134 import com.openai.models.chat.completions.ChatCompletion;135 import com.openai.models.chat.completions.ChatCompletionCreateParams;136137 public class QuickStart {138 public static void main(String[] args) {139 OpenAIClient client = OpenAIOkHttpClient.builder()140 .apiKey(System.getenv("ANTHROPIC_API_KEY")) // Your Claude API key141 .baseUrl("https://api.anthropic.com/v1/") // the Claude API endpoint142 .build();143144 ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()145 .model("claude-opus-5") // Claude model name146 .addSystemMessage("You are a helpful assistant.")147 .addUserMessage("Who are you?")148 .build();149150 ChatCompletion completion = client.chat().completions().create(params);151 System.out.println(completion.choices().get(0).message().content().orElse(""));152 }153 }154 ```155156 ```php PHP157 <?php158 // There is no official OpenAI PHP SDK, so no example is shown here.159 // To use Claude from PHP, use the native Claude API instead:160 // https://platform.claude.com/docs/en/cli-sdks-libraries/overview161 ```162163 ```ruby Ruby164 require "openai"165166 openai = OpenAI::Client.new(167 api_key: ENV["ANTHROPIC_API_KEY"], # Your Claude API key168 base_url: "https://api.anthropic.com/v1/" # the Claude API endpoint169 )170171 response = openai.chat.completions.create(172 model: "claude-opus-5", # Claude model name173 messages: [174 {role: "system", content: "You are a helpful assistant."},175 {role: "user", content: "Who are you?"}176 ]177 )178179 puts response.choices.first.message.content180 ```181</CodeGroup>182183## Important OpenAI compatibility limitations184185### API behavior186187Here are the most substantial differences from using OpenAI:188189* The `strict` parameter for function calling is ignored, which means the tool use JSON is not guaranteed to follow the supplied schema. For guaranteed schema conformance, use the native [Claude API with Structured Outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs).190* Audio input is not supported; it will be ignored and stripped from input191* Prompt caching is not supported, but it is supported in the [Anthropic SDKs](https://platform.claude.com/docs/en/cli-sdks-libraries/overview)192* System/developer messages are hoisted and concatenated to the beginning of the conversation, as Anthropic only supports a single initial system message.193194Most unsupported fields are silently ignored rather than producing errors. These are all documented in the following sections.195196### Output quality considerations197198If you’ve done lots of tweaking to your prompt, it’s likely to be well-tuned to OpenAI specifically. Consider reworking it for Claude using the [prompting best practices guide](https://platform.claude.com/docs/en/build-with-claude/prompt-engineering/claude-prompting-best-practices).199200### System / developer message hoisting201202Most of the inputs to the OpenAI SDK clearly map directly to Anthropic’s API parameters, but one distinct difference is the handling of system / developer prompts. These two prompts can be put throughout a chat conversation via OpenAI. Since Anthropic only supports an initial system message, the API takes all system/developer messages and concatenates them together with a single newline (`\n`) in between them. This full string is then supplied as a single system message at the start of the messages.203204### Thinking support205206You can enable [thinking](https://platform.claude.com/docs/en/build-with-claude/thinking) by adding the `thinking` parameter. On current models thinking is adaptive, with Claude deciding when and how deeply to think, and on Claude 5 models it is on by default; manually configured extended thinking is a legacy mode. Although thinking improves Claude's reasoning for complex tasks, the OpenAI SDK doesn't return Claude's detailed thought process. For full thinking features, including access to Claude's step-by-step reasoning output, use the native Claude API.207208<CodeGroup exclude="shell">209 ```python Python210 response = client.chat.completions.create(211 model="claude-sonnet-4-6",212 messages=[{"role": "user", "content": "Who are you?"}],213 extra_body={"thinking": {"type": "enabled", "budget_tokens": 2000}},214 )215 ```216217 ```typescript TypeScript218 const response = await openai.chat.completions.create({219 messages: [{ role: "user", content: "Who are you?" }],220 model: "claude-sonnet-4-6",221 // @ts-expect-error222 thinking: { type: "enabled", budget_tokens: 2000 }223 });224 ```225226 ```csharp C#227 // The .NET SDK has no extra_body parameter like Python's, so this example228 // sends the thinking parameter with the SDK's documented protocol method229 // (a raw JSON request body).230 BinaryData input = BinaryData.FromString("""231 {232 "model": "claude-sonnet-4-6",233 "messages": [{ "role": "user", "content": "Who are you?" }],234 "thinking": { "type": "enabled", "budget_tokens": 2000 }235 }236 """);237238 using BinaryContent content = BinaryContent.Create(input);239 ClientResult result = chatClient.CompleteChat(content);240 ```241242 ```go Go243 response, err := client.Chat.Completions.New(244 context.Background(),245 openai.ChatCompletionNewParams{246 Model: "claude-sonnet-4-6",247 Messages: []openai.ChatCompletionMessageParamUnion{248 openai.UserMessage("Who are you?"),249 },250 },251 option.WithJSONSet("thinking", map[string]any{"type": "enabled", "budget_tokens": 2000}),252 )253 ```254255 ```java Java256 ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()257 .model("claude-sonnet-4-6")258 .addUserMessage("Who are you?")259 .putAdditionalBodyProperty("thinking",260 JsonValue.from(Map.of("type", "enabled", "budget_tokens", 2000)))261 .build();262263 ChatCompletion completion = client.chat().completions().create(params);264 ```265266 ```php PHP267 <?php268 // There is no official OpenAI PHP SDK, so no example is shown here.269 // To use Claude from PHP, use the native Claude API instead:270 // https://platform.claude.com/docs/en/cli-sdks-libraries/overview271 ```272273 ```ruby Ruby274 response = openai.chat.completions.create(275 model: "claude-sonnet-4-6",276 messages: [{role: "user", content: "Who are you?"}],277 request_options: {extra_body: {thinking: {type: "enabled", budget_tokens: 2000}}}278 )279 ```280</CodeGroup>281282## Rate limits283284Rate limits follow Anthropic's [standard limits](https://platform.claude.com/docs/en/api/rate-limits) for the `/v1/messages` endpoint.285286## Detailed OpenAI compatible API support287288### Request fields289290#### Simple fields291292| Field | Support status |293| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |294| `model` | Use Claude model names |295| `max_tokens` | Fully supported |296| `max_completion_tokens` | Fully supported |297| `stream` | Fully supported |298| `stream_options` | Fully supported |299| `top_p` | Fully supported |300| `parallel_tool_calls` | Fully supported |301| `stop` | All non-whitespace stop sequences work |302| `temperature` | Between 0 and 1 (inclusive). Values greater than 1 are capped at 1. |303| `n` | Must be exactly 1 |304| `logprobs` | Ignored |305| `metadata` | Ignored |306| `response_format` | Ignored. For JSON output, use [Structured Outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) with the native Claude API |307| `prediction` | Ignored |308| `presence_penalty` | Ignored |309| `frequency_penalty` | Ignored |310| `seed` | Ignored |311| `service_tier` | Ignored |312| `audio` | Ignored |313| `logit_bias` | Ignored |314| `store` | Ignored |315| `user` | Ignored |316| `modalities` | Ignored |317| `top_logprobs` | Ignored |318| `reasoning_effort` | Ignored |319320#### `tools` / `functions` fields321322<Accordion title="Show fields">323 <Tabs>324 <Tab title="Tools">325 `tools[n].function` fields326327 | Field | Support status |328 | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |329 | `name` | Fully supported |330 | `description` | Fully supported |331 | `parameters` | Fully supported |332 | `strict` | Ignored. Use [Structured Outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) with native Claude API for strict schema validation |333 </Tab>334335 <Tab title="Functions">336 `functions[n]` fields337338 <Info>339 OpenAI has deprecated the `functions` field and suggests using `tools` instead.340 </Info>341342 | Field | Support status |343 | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |344 | `name` | Fully supported |345 | `description` | Fully supported |346 | `parameters` | Fully supported |347 | `strict` | Ignored. Use [Structured Outputs](https://platform.claude.com/docs/en/build-with-claude/structured-outputs) with native Claude API for strict schema validation |348 </Tab>349 </Tabs>350</Accordion>351352#### `messages` array fields353354<Accordion title="Show fields">355 <Tabs>356 <Tab title="Developer role">357 Fields for `messages[n].role == "developer"`358359 <Info>360 Developer messages are hoisted to beginning of conversation as part of the initial system message361 </Info>362363 | Field | Support status |364 | --------- | ---------------------------- |365 | `content` | Fully supported, but hoisted |366 | `name` | Ignored |367 </Tab>368369 <Tab title="System role">370 Fields for `messages[n].role == "system"`371372 <Info>373 System messages are hoisted to beginning of conversation as part of the initial system message374 </Info>375376 | Field | Support status |377 | --------- | ---------------------------- |378 | `content` | Fully supported, but hoisted |379 | `name` | Ignored |380 </Tab>381382 <Tab title="User role">383 Fields for `messages[n].role == "user"`384385 | Field | Variant | Sub-field | Support status |386 | --------- | -------------------------------- | --------- | --------------- |387 | `content` | `string` | | Fully supported |388 | | `array`, `type == "text"` | | Fully supported |389 | | `array`, `type == "image_url"` | `url` | Fully supported |390 | | | `detail` | Ignored |391 | | `array`, `type == "input_audio"` | | Ignored |392 | | `array`, `type == "file"` | | Ignored |393 | `name` | | | Ignored |394 </Tab>395396 <Tab title="Assistant role">397 Fields for `messages[n].role == "assistant"`398399 | Field | Variant | Support status |400 | --------------- | ---------------------------- | --------------- |401 | `content` | `string` | Fully supported |402 | | `array`, `type == "text"` | Fully supported |403 | | `array`, `type == "refusal"` | Ignored |404 | `tool_calls` | | Fully supported |405 | `function_call` | | Fully supported |406 | `audio` | | Ignored |407 | `refusal` | | Ignored |408 </Tab>409410 <Tab title="Tool role">411 Fields for `messages[n].role == "tool"`412413 | Field | Variant | Support status |414 | -------------- | ------------------------- | --------------- |415 | `content` | `string` | Fully supported |416 | | `array`, `type == "text"` | Fully supported |417 | `tool_call_id` | | Fully supported |418 | `tool_choice` | | Fully supported |419 | `name` | | Ignored |420 </Tab>421422 <Tab title="Function role">423 Fields for `messages[n].role == "function"`424425 | Field | Variant | Support status |426 | ------------- | ------------------------- | --------------- |427 | `content` | `string` | Fully supported |428 | | `array`, `type == "text"` | Fully supported |429 | `tool_choice` | | Fully supported |430 | `name` | | Ignored |431 </Tab>432 </Tabs>433</Accordion>434435### Response fields436437| Field | Support status |438| --------------------------------- | ------------------------------ |439| `id` | Fully supported |440| `choices[]` | Will always have a length of 1 |441| `choices[].finish_reason` | Fully supported |442| `choices[].index` | Fully supported |443| `choices[].message.role` | Fully supported |444| `choices[].message.content` | Fully supported |445| `choices[].message.tool_calls` | Fully supported |446| `object` | Fully supported |447| `created` | Fully supported |448| `model` | Fully supported |449| `finish_reason` | Fully supported |450| `content` | Fully supported |451| `usage.completion_tokens` | Fully supported |452| `usage.prompt_tokens` | Fully supported |453| `usage.total_tokens` | Fully supported |454| `usage.completion_tokens_details` | Always empty |455| `usage.prompt_tokens_details` | Always empty |456| `choices[].message.refusal` | Always empty |457| `choices[].message.audio` | Always empty |458| `logprobs` | Always empty |459| `service_tier` | Always empty |460| `system_fingerprint` | Always empty |461462### Error message compatibility463464The compatibility layer maintains consistent error formats with the OpenAI API. However, the detailed error messages will not be equivalent. Only use the error messages for logging and debugging.465466### Header compatibility467468While the OpenAI SDK automatically manages headers, here is the complete list of headers supported by the Claude API for developers who need to work with them directly.469470| Header | Support Status |471| -------------------------------- | ------------------- |472| `x-ratelimit-limit-requests` | Fully supported |473| `x-ratelimit-limit-tokens` | Fully supported |474| `x-ratelimit-remaining-requests` | Fully supported |475| `x-ratelimit-remaining-tokens` | Fully supported |476| `x-ratelimit-reset-requests` | Fully supported |477| `x-ratelimit-reset-tokens` | Fully supported |478| `retry-after` | Fully supported |479| `request-id` | Fully supported |480| `openai-version` | Always `2020-10-01` |481| `authorization` | Fully supported |482| `openai-processing-ms` | Always empty |483