OpenAI SDK 호환성
OpenAI SDK 호환성
Anthropic은 OpenAI SDK를 그대로 써서 Claude API를 테스트할 수 있게 해 주는 호환성 레이어를 제공해요. 코드 몇 줄만 바꾸면 Anthropic 모델의 능력을 빠르게 평가해 볼 수 있죠.
참고: 이 호환성 레이어는 주로 모델 능력을 테스트하고 비교하기 위한 거예요. 대부분의 사용 사례에서 장기적이거나 프로덕션 준비가 된 해결책으로 간주되지 않아요. 완전히 동작하고 비호환(breaking) 변경이 없도록 유지하는 게 목표지만, 우선순위는 Claude API의 신뢰성과 효과성이에요.
알려진 호환성 제한에 대한 자세한 내용은 중요한 OpenAI 호환성 제한을 참고해 주세요.
OpenAI SDK 호환 기능에 문제가 생기면 이 호환성 피드백 양식으로 피드백을 남겨 주세요.
팁: 가장 좋은 경험과 Claude API의 전체 기능 세트(PDF 처리, 인용(citations), thinking, 프롬프트 캐싱)를 쓰려면 기본 Claude API를 사용하세요.
출처: 문서
본문
OpenAI SDK 시작하기
OpenAI SDK 호환 기능을 쓰려면 다음을 해야 해요.
- 공식 OpenAI SDK를 사용한다
- 다음을 바꾼다
- base URL을 Claude API로 업데이트
- API 키를 Claude API 키로 교체
- 키가 여러 워크스페이스에 접근 가능한 개인 또는 서비스 계정 키라면, 모든 요청에
anthropic-workspace-id헤더도 보낸다(Python SDK의default_headers, TypeScript의defaultHeaders등). 워크스페이스 선택 참고 - 모델 이름을 Claude 모델로 업데이트
- 어떤 기능이 지원되는지 아래 섹션을 검토한다
빠른 시작 예제
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)
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: proces...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);
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);
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)
}
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(""));
}
}
<?php
// There is no official OpenAI PHP SDK, so no example is shown here.
// To use Claude from PHP, use the native Claude API instead:
// https://platform.claude.com/docs/en/cli-sdks-libraries/overview
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
중요한 OpenAI 호환성 제한
API 동작
OpenAI를 쓸 때와 가장 큰 차이점들이에요.
- 함수 호출을 위한
strict파라미터는 무시돼요. 즉 도구 사용 JSON이 주어진 스키마를 따른다는 보장이 없어요. 스키마 준수를 보장하려면 Structured Outputs를 쓰는 기본 Claude API를 사용하세요. - 오디오 입력은 지원하지 않아요. 입력에서 무시되고 제거돼요.
- 프롬프트 캐싱은 지원하지 않아요. 단 Anthropic SDK에서는 지원돼요.
- System/developer 메시지는 대화 맨 앞으로 끌어올려(hoist) 연결돼요. Anthropic이 단일 초기 system 메시지만 지원하기 때문이에요.
대부분의 미지원 필드는 오류를 내지 않고 조용히 무시돼요. 이건 모두 아래 섹션에 문서화돼 있어요.
출력 품질 고려 사항
프롬프트를 많이 튜닝했다면 그 프롬프트는 OpenAI에 특화돼 있을 가능성이 높아요. 프롬프팅 모범 사례 가이드를 참고해 Claude용으로 다시 다듬는 걸 고려해 보세요.
System / developer 메시지 끌어올리기
OpenAI SDK 입력 대부분은 Anthropic API 파라미터에 직접 매핑돼요. 하지만 system/developer 프롬프트 처리가 한 가지 뚜렷한 차이예요. 이 두 프롬프트는 OpenAI에선 채팅 대화 곳곳에 넣을 수 있어요. Anthropic은 초기 system 메시지만 지원하므로, API는 모든 system/developer 메시지를 가져와 사이에 개행(\n) 하나씩 넣어 연결해요. 그 전체 문자열이 messages 맨 앞에 단일 system 메시지로 제공돼요.
Thinking 지원
thinking 파라미터를 추가하면 thinking을 켤 수 있어요. 현재 모델에서 thinking은 적응형이라 Claude가 언제, 얼마나 깊이 생각할지 결정해요. Claude 5 모델에서는 기본으로 켜져 있고, 수동으로 구성한 extended thinking은 레거시 모드예요. thinking은 복잡한 작업에서 Claude의 추론을 개선하지만, OpenAI SDK는 Claude의 상세한 사고 과정을 반환하지 않아요. 단계별 reasoning 출력에 접근하는 것을 포함한 전체 thinking 기능은 기본 Claude API를 쓰세요.
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}},
)
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 }
});
// The .NET SDK has no extra_body parameter like Python's, so this example
// sends the thinking parameter with the SDK's documented protocol method
// (a raw JSON request body).
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);
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}),
)
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);
<?php
// There is no official OpenAI PHP SDK, so no example is shown here.
// To use Claude from PHP, use the native Claude API instead:
// https://platform.claude.com/docs/en/cli-sdks-libraries/overview
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}}}
)
속도 제한 (Rate limits)
속도 제한은 /v1/messages 엔드포인트에 대한 Anthropic의 표준 제한을 따릅니다.
상세 OpenAI 호환 API 지원
요청 필드
단순 필드
| 필드 | 지원 상태 |
|---|---|
model |
Claude 모델 이름 사용 |
max_tokens |
완전 지원 |
max_completion_tokens |
완전 지원 |
stream |
완전 지원 |
stream_options |
완전 지원 |
top_p |
완전 지원 |
parallel_tool_calls |
완전 지원 |
stop |
모든 비공백 stop 시퀀스 동작 |
temperature |
0과 1 사이(포함). 1보다 큰 값은 1로 제한됨 |
n |
정확히 1이어야 함 |
logprobs |
무시됨 |
metadata |
무시됨 |
response_format |
무시됨. JSON 출력은 기본 Claude API의 Structured Outputs 사용 |
prediction |
무시됨 |
presence_penalty |
무시됨 |
frequency_penalty |
무시됨 |
seed |
무시됨 |
service_tier |
무시됨 |
audio |
무시됨 |
logit_bias |
무시됨 |
store |
무시됨 |
user |
무시됨 |
modalities |
무시됨 |
top_logprobs |
무시됨 |
reasoning_effort |
무시됨 |
tools / functions 필드
Tools — tools[n].function 필드
| 필드 | 지원 상태 |
|---|---|
name |
완전 지원 |
description |
완전 지원 |
parameters |
완전 지원 |
strict |
무시됨. 엄격한 스키마 검증은 기본 Claude API의 Structured Outputs 사용 |
Functions — functions[n] 필드
참고: OpenAI는
functions필드를 deprecated 처리하고tools사용을 권장해요.
| 필드 | 지원 상태 |
|---|---|
name |
완전 지원 |
description |
완전 지원 |
parameters |
완전 지원 |
strict |
무시됨. 엄격한 스키마 검증은 기본 Claude API의 Structured Outputs 사용 |
messages 배열 필드
Developer role — messages[n].role == "developer" 필드
참고: Developer 메시지는 초기 system 메시지의 일부로 대화 맨 앞으로 끌어올려져요.
| 필드 | 지원 상태 |
|---|---|
content |
완전 지원 (단, 끌어올려짐) |
name |
무시됨 |
System role — messages[n].role == "system" 필드
참고: System 메시지는 초기 system 메시지의 일부로 대화 맨 앞으로 끌어올려져요.
| 필드 | 지원 상태 |
|---|---|
content |
완전 지원 (단, 끌어올려짐) |
name |
무시됨 |
User role — messages[n].role == "user" 필드
| 필드 | 변형 | 하위 필드 | 지원 상태 |
|---|---|---|---|
content |
string |
완전 지원 | |
array, type == "text" |
완전 지원 | ||
array, type == "image_url" |
url |
완전 지원 | |
detail |
무시됨 | ||
array, type == "input_audio" |
무시됨 | ||
array, type == "file" |
무시됨 | ||
name |
무시됨 |
Assistant role — messages[n].role == "assistant" 필드
| 필드 | 변형 | 지원 상태 |
|---|---|---|
content |
string |
완전 지원 |
array, type == "text" |
완전 지원 | |
array, type == "refusal" |
무시됨 | |
tool_calls |
완전 지원 | |
function_call |
완전 지원 | |
audio |
무시됨 | |
refusal |
무시됨 |
Tool role — messages[n].role == "tool" 필드
| 필드 | 변형 | 지원 상태 |
|---|---|---|
content |
string |
완전 지원 |
array, type == "text" |
완전 지원 | |
tool_call_id |
완전 지원 | |
tool_choice |
완전 지원 | |
name |
무시됨 |
Function role — messages[n].role == "function" 필드
| 필드 | 변형 | 지원 상태 |
|---|---|---|
content |
string |
완전 지원 |
array, type == "text" |
완전 지원 | |
tool_choice |
완전 지원 | |
name |
무시됨 |
응답 필드
| 필드 | 지원 상태 |
|---|---|
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 |
항상 비어 있음 |