Anthropic

Anthropic

LiteLLM은 모든 Anthropic 모델을 지원해요.

  • claude-sonnet-5, claude-opus-5
  • claude-opus-4-6 (claude-opus-4-6-20260205), claude-sonnet-4-6
  • claude-sonnet-4-5-20250929, claude-opus-4-5-20251101
  • claude-opus-4-1-20250805
  • claude-4 (claude-opus-4-20250514, claude-sonnet-4-20250514)
  • claude-3.7 (claude-3-7-sonnet-20250219)
  • claude-3.5 (claude-3-5-sonnet-20240620)
  • claude-3 (claude-3-haiku-20240307, claude-3-opus-20240229, claude-3-sonnet-20240229)
  • claude-2, claude-2.1, claude-instant-1.2
속성 세부 내용
설명 Claude는 Anthropic이 만든 고성능·신뢰할 수 있고 지능적인 AI 플랫폼이에요. 언어·추론·분석·코딩 등에 탁월하며 Azure Foundry로도 이용 가능해요.
LiteLLM 프로바이더 라우트 anthropic/ (모델 이름에 이 접두사를 붙여 Anthropic으로 라우팅 - 예: anthropic/claude-3-5-sonnet-20240620). Azure Foundry 배포는 azure_ai/claude-* 사용 (Azure Anthropic 문서 참고)
프로바이더 문서 Anthropic ↗, Azure Foundry Claude ↗
프로바이더 API 엔드포인트 https://api.anthropic.com (또는 Azure Foundry 엔드포인트: https://<resource-name>.services.ai.azure.com/anthropic)
지원 엔드포인트 /chat/completions, /v1/messages (패스스루)

출처: 문서

본문

지원되는 OpenAI 파라미터 (Supported OpenAI Parameters)

코드에서 확인하려면 여기를 참고해 주세요.

"stream",
"stop",
"temperature",
"top_p",
"max_tokens",
"max_completion_tokens",
"tools",
"tool_choice",
"extra_headers",
"parallel_tool_calls",
"response_format",
"user",
"reasoning_effort",

참고:

  • Anthropic API는 max_tokens가 전달되지 않으면 요청에 실패해요. 그래서 litellm은 max_tokens가 없을 때 max_tokens=4096을 전달해요.
  • response_format은 Claude Sonnet 4.5와 Opus 4.1 모델에서 완전히 지원돼요 (Structured Outputs 참고).
  • reasoning_effort는 Claude 4.6 및 Opus 4.5 모델에서 자동으로 output_config={"effort": ...}로 매핑돼요 (Effort 파라미터 참고).

구조화된 출력 (Structured Outputs)

LiteLLM은 Claude Sonnet 4.5와 Opus 4.1 모델에서 Anthropic의 구조화된 출력 기능을 지원해요. 이 모델들에 response_format을 사용하면 LiteLLM이 자동으로:

  • 필요한 structured-outputs-2025-11-13 베타 헤더를 추가
  • OpenAI의 response_format을 Anthropic의 output_format 형식으로 변환

지원 모델

  • sonnet-4-5 또는 sonnet-4.5 (모든 Sonnet 4.5 변형)
  • opus-4-1 또는 opus-4.1 (모든 Opus 4.1 변형)
    • opus-4-5 또는 opus-4.5 (모든 Opus 4.5 변형)

사용 예시

LiteLLM SDK

from litellm import completion

response = completion(
    model="claude-sonnet-5",
    messages=[{"role": "user", "content": "What is the capital of France?"}],
    response_format={
        "type": "json_schema",
        "json_schema": {
            "name": "capital_response",
            "strict": True,
            "schema": {
                "type": "object",
                "properties": {
                    "country": {"type": "string"},
                    "capital": {"type": "string"}
                },
                "required": ["country", "capital"],
                "additionalProperties": False
            }
        }
    }
)

print(response.choices[0].message.content)
# Output: {"country": "France", "capital": "Paris"}

LiteLLM Proxy

  1. config.yaml 설정
model_list:
  - model_name: claude-sonnet-5
    litellm_params:
      model: anthropic/claude-sonnet-5
      api_key: os.environ/ANTHROPIC_API_KEY
  1. 프록시 시작
litellm --config /path/to/config.yaml
  1. 테스트하기
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LITELLM_KEY" \
  -d '{
    "model": "claude-sonnet-5",
    "messages": [{"role": "user", "content": "What is the capital of France?"}],
    "response_format": {
        "type": "json_schema",
        "json_schema": {
            "name": "capital_response",
            "strict": true,
            "schema": {
                "type": "object",
                "properties": {
                    "country": {"type": "string"},
                    "capital": {"type": "string"}
                },
                "required": ["country", "capital"],
                "additionalProperties": false
            }
        }
    }
  }'

참고: 지원 모델에서 구조화된 출력을 사용하면 LiteLLM이 자동으로:

  • OpenAI의 response_format을 Anthropic의 output_schema로 변환
  • anthropic-beta: structured-outputs-2025-11-13 헤더 추가
  • 스키마로 도구를 만들고 모델이 그것을 사용하도록 강제

API 키 (API Keys)

import os

os.environ["ANTHROPIC_API_KEY"] = "your-api-key"
# os.environ["ANTHROPIC_API_BASE"] = "" # [OPTIONAL] or 'ANTHROPIC_BASE_URL'
# os.environ["LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX"] = "true" # [OPTIONAL] Disable automatic URL suffix appending

Azure Foundry 지원

Claude 모델은 Microsoft Azure Foundry를 통해서도 사용할 수 있어요. anthropic/ 대신 azure_ai/ 접두사를 사용하고 Azure 인증을 설정해요. 자세한 내용은 Azure Anthropic 문서를 참고하세요.

예시:

response = completion(
    model="azure_ai/claude-sonnet-5",
    api_base="https://<resource-name>.services.ai.azure.com/anthropic",
    api_key="your-azure-api-key",
    messages=[{"role": "user", "content": "Hello!"}]
)

커스텀 API Base

Anthropic에 커스텀 API base(예: 프록시 또는 커스텀 엔드포인트)를 사용하면, LiteLLM이 자동으로 적절한 접미사(/v1/messages 또는 /v1/complete)를 base URL에 추가해요.

커스텀 엔드포인트가 이미 전체 경로를 포함하거나 표준 URL 구조를 따르지 않는다면, 이 자동 접미사 추가를 비활성화할 수 있어요:

import os

os.environ["ANTHROPIC_API_BASE"] = "https://my-custom-endpoint.com/custom/path"
os.environ["LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX"] = "true"  # Prevents automatic suffix

LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX 없이:

  • Base URL https://my-proxy.comhttps://my-proxy.com/v1/messages
  • Base URL https://my-proxy.com/apihttps://my-proxy.com/api/v1/messages

LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX=true 로:

  • Base URL https://my-proxy.com/custom/pathhttps://my-proxy.com/custom/path (변경 없음)

Azure AI Foundry (대체 방법)

권장 방법: Azure AD 인증을 포함한 전체 Azure 지원을 위해, azure_ai/ 접두사가 있는 전용 Azure Anthropic 프로바이더를 사용해요.

대안으로, Azure가 Claude를 Anthropic 네이티브 API로 노출하므로 anthropic/ 프로바이더를 Azure 엔드포인트와 함께 직접 사용할 수도 있어요.

from litellm import completion

response = completion(
    model="anthropic/claude-sonnet-5",
    api_base="https://<your-resource>.services.ai.azure.com/anthropic",
    api_key="<your-azure-api-key>",
    messages=[{"role": "user", "content": "Hello!"}],
)
print(response)

Azure 엔드포인트 찾기: Azure AI Foundry → 배포(deployment) → 개요(Overview)로 이동하세요. base URL은 https://<resource-name>.services.ai.azure.com/anthropic입니다.

사용법 (Usage)

import os
from litellm import completion

# set env - [OPTIONAL] replace with your anthropic key
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

messages = [{"role": "user", "content": "Hey! how's it going?"}]
response = completion(model="claude-opus-5", messages=messages)
print(response)

사용법 - 스트리밍 (Streaming)

completion 호출 시 stream=True만 설정하면 돼요.

import os
from litellm import completion

# set env
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

messages = [{"role": "user", "content": "Hey! how's it going?"}]
response = completion(model="claude-opus-5", messages=messages, stream=True)
for chunk in response:
    print(chunk["choices"][0]["delta"]["content"])  # same as openai format

LiteLLM 프록시 사용법

LiteLLM Proxy Server로 Anthropic을 호출하는 방법이에요.

1. 환경에 키 저장하기

export ANTHROPIC_API_KEY="your-api-key"

2. 프록시 시작하기

model_list:
  - model_name: claude-4 ### RECEIVED MODEL NAME ###
    litellm_params: # all params accepted by litellm.completion() - https://docs.litellm.ai/docs/completion/input
      model: claude-opus-5 ### MODEL NAME sent to `litellm.completion()` ###
      api_key: "os.environ/ANTHROPIC_API_KEY" # does os.getenv("ANTHROPIC_API_KEY")
litellm --config /path/to/config.yaml

config.yaml에 정의하지 않고 claude-sonnet-5, claude-opus-5로 요청하고 싶다면 와일드카드 설정을 사용해요.

필요 환경 변수

ANTHROPIC_API_KEY=sk-ant****
model_list:
  - model_name: "*"
    litellm_params:
      model: "*"
litellm --config /path/to/config.yaml

이 config.yaml에 대한 예시 요청 (anthropic/ 접두사로 요청을 Anthropic API로 라우팅):

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
      "model": "anthropic/claude-sonnet-5",
      "messages": [
        {
          "role": "user",
          "content": "what llm are you"
        }
      ]
    }
'

CLI로도 시작할 수 있어요:

$ litellm --model claude-opus-5

# Server running on http://0.0.0.0:4000

3. 테스트하기

curl --location 'http://0.0.0.0:4000/chat/completions' \
--header 'Content-Type: application/json' \
--data ' {
      "model": "anthropic/claude-sonnet-5",
      "messages": [
        {
          "role": "user",
          "content": "what llm are you"
        }
      ]
    }
'

OpenAI SDK 사용

import openai
client = openai.OpenAI(
    api_key="anything",
    base_url="http://0.0.0.0:4000"
)

# request sent to model set on litellm proxy, `litellm --model`
response = client.chat.completions.create(model="anthropic/claude-sonnet-5", messages = [
    {
        "role": "user",
        "content": "this is a test request, write a short poem"
    }
])

print(response)

Langchain 사용

from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
    ChatPromptTemplate,
    HumanMessagePromptTemplate,
    SystemMessagePromptTemplate,
)
from langchain.schema import HumanMessage, SystemMessage

chat = ChatOpenAI(
    openai_api_base="http://0.0.0.0:4000", # set openai_api_base to the LiteLLM Proxy
    model = "anthropic/claude-sonnet-5",
    temperature=0.1
)

messages = [
    SystemMessage(
        content="You are a helpful assistant that im using to make a test request to."
    ),
    HumanMessage(
        content="test from litellm. tell me why it's amazing in 1 sentence"
    ),
]
response = chat(messages)

print(response)

지원 모델 (Supported Models)

Model Name 👉 사람이 읽기 좋은 이름. Function Call 👉 LiteLLM에서 모델을 호출하는 방법.

모델 이름 함수 호출
claude-opus-4-6 completion('claude-opus-4-6-20260205', messages)
claude-sonnet-4-5 completion('claude-sonnet-4-5-20250929', messages)
claude-opus-4-5 completion('claude-opus-4-5-20251101', messages)
claude-opus-4-1 completion('claude-opus-4-1-20250805', messages)
claude-opus-4 completion('claude-opus-4-20250514', messages)
claude-sonnet-4 completion('claude-sonnet-4-20250514', messages)
claude-3.7 completion('claude-3-7-sonnet-20250219', messages)
claude-3-5-sonnet completion('claude-3-5-sonnet-20240620', messages)
claude-3-haiku completion('claude-3-haiku-20240307', messages)
claude-3-opus completion('claude-3-opus-20240229', messages)
claude-3-5-sonnet-20240620 completion('claude-3-5-sonnet-20240620', messages)
claude-3-sonnet completion('claude-3-sonnet-20240229', messages)
claude-2.1 completion('claude-2.1', messages)
claude-2 completion('claude-2', messages)
claude-instant-1.2 completion('claude-instant-1.2', messages)
claude-instant-1 completion('claude-instant-1', messages)

프롬프트 캐싱 (Prompt Caching)

Anthropic 프롬프트 캐싱을 사용해요. 관련 Anthropic API 문서를 참고하세요.

LiteLLM이 Anthropic 컨텍스트 캐싱에 보내는 샘플 원본 요청은 다음과 같아요.

POST Request Sent from LiteLLM:
curl -X POST \
https://api.anthropic.com/v1/messages \
-H 'accept: application/json' -H 'anthropic-version: 2023-06-01' -H 'content-type: application/json' -H 'x-api-key: sk-...' \
-d '{'model': 'claude-sonnet-5', [
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What are the key terms and conditions in this agreement?",
          "cache_control": {
            "type": "ephemeral"
          }
        }
      ]
    },
    {
      "role": "assistant",
      "content": [
        {
          "type": "text",
          "text": "Certainly! The key terms and conditions are the following: the contract is 1 year long for $10/mo"
        }
      ]
    }
  ],
  "temperature": 0.2,
  "max_tokens": 10
}'

참고: Anthropic은 더 이상 anthropic-beta: prompt-caching-2024-07-31 헤더를 요구하지 않아요. 이제 프롬프트 캐싱은 메시지에서 cache_control을 사용하면 자동으로 동작해요.

큰 컨텍스트 캐싱

법적 계약 전문을 프리픽스로 캐시하고 사용자 지시는 캐시하지 않는 기본 프롬프트 캐싱 예시예요.

response = await litellm.acompletion(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "system",
            "content": [
                {
                    "type": "text",
                    "text": "You are an AI assistant tasked with analyzing legal documents.",
                },
                {
                    "type": "text",
                    "text": "Here is the full text of a complex legal agreement",
                    "cache_control": {"type": "ephemeral"},
                },
            ],
        },
        {
            "role": "user",
            "content": "what are the key terms and conditions in this agreement?",
        },
    ]
)

도구 정의 캐싱

이 예시는 도구 정의를 캐시하는 방법을 보여 줘요. cache_control 파라미터는 마지막 도구에 위치합니다.

import litellm

response = await litellm.acompletion(
    model="anthropic/claude-sonnet-5",
    messages = [{"role": "user", "content": "What's the weather like in Boston today?"}],
    tools = [
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "Get the current weather in a given location",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                    },
                    "required": ["location"],
                },
                "cache_control": {"type": "ephemeral"}
            },
        }
    ]
)

멀티턴 대화 계속 이어가기

이 예시는 멀티턴 대화에서 프롬프트 캐싱을 사용하는 방법을 보여 줘요. cache_control은 정적 프리픽스의 일부로 지정하기 위해 시스템 메시지에 위치합니다. 대화 기록(이전 메시지)은 메시지 배열에 포함되고, 마지막 턴은 후속 대화에서 계속하기 위해 캐시로 표시됩니다.

import litellm

response = await litellm.acompletion(
    model="anthropic/claude-sonnet-5",
    messages=[
        # System Message
        {
            "role": "system",
            "content": [
                {
                    "type": "text",
                    "text": "Here is the full text of a complex legal agreement"
                    * 400,
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
        # marked for caching with the cache_control parameter, so that this checkpoint can read from the previous cache.
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What are the key terms and conditions in this agreement?",
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
        {
            "role": "assistant",
            "content": "Certainly! the key terms and conditions are the following: the contract is 1 year long for $10/mo",
        },
        # The final turn is marked with cache-control, for continuing in followups.
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What are the key terms and conditions in this agreement?",
                    "cache_control": {"type": "ephemeral"},
                }
            ],
        },
    ]
)

함수/도구 호출 (Function/Tool Calling)

from litellm import completion

# set env
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "Get the current weather in a given location",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "The city and state, e.g. San Francisco, CA",
                    },
                    "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
                },
                "required": ["location"],
            },
        },
    }
]
messages = [{"role": "user", "content": "What's the weather like in Boston today?"}]

response = completion(
    model="anthropic/claude-sonnet-5",
    messages=messages,
    tools=tools,
    tool_choice="auto",
)
# Add any assertions, here to check response args
print(response)
assert isinstance(response.choices[0].message.tool_calls[0].function.name, str)
assert isinstance(
    response.choices[0].message.tool_calls[0].function.arguments, str
)

특정 도구 사용 강제하기 (Forcing Anthropic Tool Use)

Claude가 사용자 질문에 답하기 위해 특정 도구를 사용하도록 하려면, tool_choice 필드에서 도구를 지정하면 돼요:

response = completion(
    model="anthropic/claude-sonnet-5",
    messages=messages,
    tools=tools,
    tool_choice={"type": "tool", "name": "get_weather"},
)

도구 호출 비활성화 (Disable Tool Calling)

tool_choice"none"으로 설정하면 도구 호출을 비활성화할 수 있어요.

SDK

from litellm import completion

response = completion(
    model="anthropic/claude-sonnet-5",
    messages=messages,
    tools=tools,
    tool_choice="none",
)

Proxy

  1. config.yaml 설정
model_list:
  - model_name: anthropic-claude-model
    litellm_params:
        model: anthropic/claude-sonnet-5
        api_key: os.environ/ANTHROPIC_API_KEY
  1. 프록시 시작
litellm --config /path/to/config.yaml
  1. 테스트하기
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer anything" \
  -d '{
    "model": "anthropic-claude-model",
    "messages": [{"role": "user", "content": "Who won the World Cup in 2022?"}],
    "tools": [{"type": "mcp", "server_label": "deepwiki", "server_url": "https://mcp.deepwiki.com/mcp", "require_approval": "never"}],
    "tool_choice": "none"
  }'

MCP 도구 호출 (MCP Tool Calling)

LiteLLM은 OpenAI Responses API 형식으로 Anthropic과 MCP 도구 호출을 지원해요.

LiteLLM SDK

import os
from litellm import completion

os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."

tools=[
    {
        "type": "mcp",
        "server_label": "deepwiki",
        "server_url": "https://mcp.deepwiki.com/mcp",
        "require_approval": "never",
    },
]

response = completion(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Who won the World Cup in 2022?"}],
    tools=tools
)

Anthropic 형식 (URL 기반)

import os
from litellm import completion

os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."

tools = [
    {
        "type": "url",
        "url": "https://mcp.deepwiki.com/mcp",
        "name": "deepwiki-mcp",
    }
]
response = completion(
    model="anthropic/claude-sonnet-5",
    messages=[{"role": "user", "content": "Who won the World Cup in 2022?"}],
    tools=tools
)

print(response)

Proxy

  1. config.yaml 설정
model_list:
  - model_name: claude-4-sonnet
    litellm_params:
        model: anthropic/claude-sonnet-5
        api_key: os.environ/ANTHROPIC_API_KEY
  1. 프록시 시작
litellm --config /path/to/config.yaml
  1. 테스트하기
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $LITELLM_KEY" \
  -d '{
    "model": "claude-4-sonnet",
    "messages": [{"role": "user", "content": "Who won the World Cup in 2022?"}],
    "tools": [...]
  }'

병렬 함수 호출 (Parallel Function Calling)

여러 도구를 병렬로 호출할 수 있어요. 자세한 내용은 원본 문서를 참고하세요.

컨텍스트 관리 (Context Management, Beta)

Anthropic의 컨텍스트 편집(context editing) API로 오래된 도구 결과나 thinking 블록을 자동으로 지울 수 있어요. LiteLLM은 이제 Anthropic 모델 호출 시 네이티브 context_management 페이로드를 전달하고, 필요한 context-management-2025-06-27 베타 헤더를 자동으로 추가해요.

from litellm import completion

response = completion(
    model="anthropic/claude-sonnet-5",
    messages = [{"role": "user", "content": "Summarize the latest tool results"}],
    context_management = {
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                ...

Anthropic 호스티드 도구 (Computer, Text Editor, Web Search, Memory)

Anthropic이 호스팅하는 도구들도 사용할 수 있어요. 자세한 내용은 원본 문서를 참고하세요.

사용법 - 비전 (Vision)

image_path = "../proxy/cached_logo.jpg"
# Getting the base64 string
base64_image = encode_image(image_path)
resp = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "text",
                    "text": "What's in this image?"
                },
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/jpeg;base64,{base64_image}"}
                }
            ]
        }
    ]
)

사용법 - Thinking / reasoning_content

LiteLLM은 OpenAI의 reasoning_effort를 Anthropic의 thinking 파라미터로 번역해요. 구현 코드

특히 LiteLLM은 OpenAI 호환 /chat/completions 라우트의 기본 Anthropic 요청에 다음을 주입해요:

{
  "thinking": {"type": "adaptive"},
  "output_config": {"effort": "<low|medium|high|xhigh|max>"}
}

Anthropic 모델에 thinking 전달하기

response = litellm.completion(
   model="anthropic/claude-sonnet-5",
   messages = [{"role": "user", "content": "What is the capital of France?"}],
   thinking = {"type": "enabled", "budget_tokens": 1024},
)
적응형 사고 (Adaptive Thinking, Claude Opus 4.6)
response = litellm.completion(
   model="anthropic/claude-opus-5",
   messages = [{"role": "user", "content": "What is the optimal strategy for solving this problem?"}],
   thinking = {"type": "adaptive"},
)
예산이 있는 Thinking 비활성화
response = litellm.completion(
   model="anthropic/claude-opus-5",
   messages = [{"role": "user", "content": "What is the capital of France?"}],
   thinking = {"type": "enabled", "budget_tokens": 5000},
)

Anthropic API에 추가 헤더 전달하기 (Passing Extra Headers)

from litellm import completion
messages = [{"role": "user", "content": "What is Anthropic?"}]
response = completion(
    model="claude-3-5-sonnet-20240620",
    messages=messages,
    extra_headers={"anthropic-beta": "some-beta-header"},
)

사용법 - "Assistant Pre-fill"

import os
from litellm import completion

# set env - [OPTIONAL] replace with your anthropic key
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

messages = [
    {"role": "user", "content": "How do you say 'Hello' in German? Return your answer as a JSON object, like this:\n\n{\"Hello\": \"Hallo\"}"},
    {"role": "assistant", "content": "{"},
]
response = completion(model="claude-2.1", messages=messages)
print(response)

사용법 - "System" 메시지

Claude 2.1에서 system 역할 메시지는 올바르게 포맷돼요.

import os
from litellm import completion

# set env - [OPTIONAL] replace with your anthropic key
os.environ["ANTHROPIC_API_KEY"] = "your-api-key"

messages = [
    {"role": "system", "content": "You are a snarky assistant."},
    {"role": "user", "content": "How do I boil water?"},
]
response = completion(model="claude-2.1", messages=messages)

사용법 - PDF

base64 사용

file 콘텐츠 타입과 file_data 필드를 사용해 base64 인코딩 PDF 파일을 Anthropic 모델에 전달해요.

from litellm import completion, supports_pdf_input
import base64
import requests

# URL of the file
url = "https://storage.googleapis.com/cloud-samples-data/generative-ai/pdf/2403.05530.pdf"

# Download the file
response = requests.get(url)
file_data = response.content

encoded_file = base64.b64encode(file_data).decode("utf-8")

## check if model supports pdf input
supports_pdf_input("anthropic/claude-sonnet-5") # True

response = completion(
    model="anthropic/claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "You are a very professional document summarization specialist. Please summarize the given document."},
                {
                    "type": "file",
                    "file": {
                       "file_data": f"data:application/pdf;base64,{encoded_file}", # 👈 PDF
                    }
                },
            ],
        }
    ],
    max_tokens=300,
)

print(response.choices[0])

[BETA] 인용 API (Citations API)

citations: {"enabled": true}를 Anthropic에 전달하면 문서 응답에 인용을 받을 수 있어요. 이 인터페이스는 베타 상태이며, 피드백은 여기로 알려주세요.

from litellm import completion

resp = completion(
    model="claude-sonnet-5",
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "document",
                    "source": {
                        "type": "text",
                        "media_type": "text/plain",
                        "data": "The grass is green. The sky is blue.",
                    },
                    "title": "My Document",
                    "context": "This is a trustworthy document.",
                    "citations": {"enabled": True},
                },
                {
                    "type": "text",
                    "text": "What color is the grass and sky?",
                },
            ],
        }
    ],
)

citations = resp.choices[0].message.provider_specific_fields["citations"]

assert citations is not None

Files API

파일을 한 번 업로드하고 여러 요청에서 file_id로 참조할 수 있어요. 매번 콘텐츠를 다시 업로드할 필요가 없습니다.

참고: Anthropic에서 얻은 file_id는 Anthropic Claude 모델에서만 동작해요. 다른 프로바이더(OpenAI, Bedrock 등)에서는 사용할 수 없어요.

  • 최대 파일 크기: 500 MB | 총 저장 공간: 조직당 100 GB
  • 가격: File API 작업은 무료예요. Messages 요청에서 사용된 파일 콘텐츠는 입력 토큰으로 과금돼요.

파일 유형별 지원 모델:

  • 이미지: 모든 Claude 3+ 모델
  • PDF: 모든 Claude 3.5+ 모델
  • 기타 파일 유형 (코드 실행용): Claude 3.5 Haiku + 모든 Claude 3.7+ 모델

빠른 시작 (Quick Start)

import litellm
import os

os.environ["ANTHROPIC_API_KEY"] = "sk-ant-..."

# 1. Upload a file once
file = litellm.create_file(
    file=open("document.pdf", "rb"),
    purpose="messages",
    custom_llm_provider="anthropic",
)

# 2. Use file_id in messages (no re-upload needed)
response = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "Summarize this document"},
            {"type": "file", "file": {"file_id": file.id, "format": "application/pdf"}}
        ]
    }]
)

파일 작업 (File Operations)

작업 함수
업로드 (Upload) litellm.create_file(file, purpose="messages", custom_llm_provider="anthropic")
목록 (List) litellm.file_list(custom_llm_provider="anthropic")
조회 (Retrieve) litellm.file_retrieve(file_id, custom_llm_provider="anthropic")
삭제 (Delete) litellm.file_delete(file_id, custom_llm_provider="anthropic")
다운로드 (Download) litellm.file_content(file_id, custom_llm_provider="anthropic")

참고: 다운로드는 코드 실행 도구가 만든 파일에서만 동작하며, 업로드한 파일에는 동작하지 않아요.

지원 형식 (Supported Formats)

파일 타입 형식 값
PDF application/pdf
일반 텍스트 text/plain
JPEG image/jpeg
PNG image/png
GIF image/gif
WebP image/webp

이미지 사용하기

# Upload image
image = litellm.create_file(
    file=open("photo.jpg", "rb"),
    purpose="messages",
    custom_llm_provider="anthropic",
)

# Use in message
response = litellm.completion(
    model="anthropic/claude-sonnet-5",
    messages=[{
        "role": "user",
        "content": [
            {"type": "text", "text": "What's in this image?"},
            {"type": "file", "file": {"file_id": image.id, "format": "image/jpeg"}}
        ]
    }]
)

사용법 - user_id를 Anthropic에 전달하기

LiteLLM은 OpenAI의 user 파라미터를 Anthropic의 metadata[user_id] 파라미터로 번역해요.

SDK

response = completion(
    model="claude-sonnet-5",
    messages=messages,
    user="user_123",
)

Proxy

  1. config.yaml 설정
model_list:
    - model_name: claude-sonnet-5
      litellm_params:
        model: anthropic/claude-sonnet-5
        api_key: os.environ/ANTHROPIC_API_KEY
  1. 프록시 시작
litellm --config /path/to/config.yaml
  1. 테스트하기
curl http://0.0.0.0:4000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer <YOUR-LITELLM-KEY>" \
  -d '{
    "model": "claude-sonnet-5",
    "messages": [{"role": "user", "content": "What is Anthropic?"}],
    "user": "user_123"
  }'

사용법 - 에이전트 스킬 (Agent Skills)

LiteLLM은 API로 에이전트 스킬(Agent Skills) 사용을 지원해요.

SDK

response = completion(
    model="claude-sonnet-5",
    messages=messages,
    tools= [
        {
            "type": "code_execution_20250825",
            "name": "code_execution"
        }
    ],
    container= {
        "skills": [
            {
                "type": "anthropic",
                "skill_id": "pptx",
                "version": "latest"
            }
        ]
    }
)

Proxy

  1. config.yaml 설정
model_list:
    - model_name: claude-sonnet-5
      litellm_params:
        model: anthropic/claude-sonnet-5
        api_key: os.environ/ANTHROPIC_API_KEY
  1. 프록시 시작
litellm --config /path/to/config.yaml
  1. 테스트하기
curl --location 'http://localhost:4000/chat/completions' \
--header 'Content-Type: application/json' \
--header 'Authorization: Bearer <YOUR-LITELLM-KEY>' \
--data '{
    "model": "claude-sonnet-5",
    "messages": [
        {
            "role": "user",
            "content": "Hi"
        }
    ],
    "tools": [
        {
            "type": "code_execution_20250825",
            "name": "code_execution"
        }
    ],
    "container": {
        "skills": [
            {
                "type": "anthropic",
                "skill_id": "pptx",
                "version": "latest"
            }
        ]
    }
}'

container와 그 id는 스트리밍/비스트리밍 응답의 provider_specific_fields에 나타나요.

더 알아보기 (Learn more)