OpenAI 호환 인터페이스 업그레이드: Claude 심층 지원

AIHubMix가 Claude용 OpenAI 호환 API를 업그레이드했습니다. 추가 매개변수 없이 인터리브드 사고(interleaved thinking)를 사용할 수 있고, 프롬프트 캐싱과 Anthropic 베타 기능 지원도 추가되었습니다.

AIHubMix8분 분량
OpenAI 호환 인터페이스 업그레이드: Claude 심층 지원

Claude 시리즈 모델에 맞춰 OpenAI 호환 인터페이스를 더 깊이 최적화했습니다. 이제 사고(thinking)와 캐싱을 더 정밀하고 편리하게 제어할 수 있습니다. 다중 턴 대화에서의 인터리브드 사고도 더 쓰기 쉬워져, 추가 매개변수 없이 매끄럽게 통합할 수 있습니다. Anthropic이 제공하는 베타 기능을 활성화하는 것도 지원합니다.

1. 모델 사고 (Extended Thinking)

1.1 인터리브드 사고의 장점

인터리브드 사고가 활성화되지 않은 경우, 모델은 어시스턴트 턴의 시작 부분에서 한 번만 사고를 수행합니다. 이후 응답은 도구 결과를 받은 뒤 새로운 사고 블록을 만들지 않고 바로 생성됩니다:

User → [Thinking] → Tool Call → Tool Result → Response

인터리브드 사고가 활성화되면, 모델은 도구 결과를 받을 때마다 새로운 사고 블록을 삽입해 추론의 연쇄를 형성합니다:

User → [Thinking] → Tool Call → Tool Result → [Thinking] → Response
                                                ↑ Interleaved Thinking

이를 통해 모델은 다음을 할 수 있습니다:

  • 도구 결과를 바탕으로 2차 추론을 수행하며, 출력을 단순히 이어 붙이지 않습니다.
  • 여러 도구 호출 사이에서 추론을 연결하여, 각 결정이 이전 단계의 분석에 근거하도록 합니다.
참고: Anthropic 인터리브드 사고

1.2 사고 활성화

다음 네 가지 방법 중 하나를 선택해 사고를 활성화할 수 있습니다:

방법 예시 설명
reasoning_effort "reasoning_effort": "low" OpenAI 표준 매개변수로, 요청 본문의 최상위 레벨에 둡니다
reasoning.effort "reasoning": {"effort": "low"} 이전 방법과 동일하며, reasoning 객체 안에 둡니다
reasoning.max_tokens "reasoning": {"max_tokens": 1024} 사고에 사용할 최대 토큰 수를 정밀하게 제어합니다
모델 이름에 -think을 붙입니다 "model": "claude-sonnet-4-5-think" 가장 간단한 방법으로, 추가 매개변수가 필요 없습니다
우선순위(여러 방법을 함께 사용할 때): reasoning_effort > reasoning.max_tokens > reasoning.effort > -think 접미사

effort 가능한 값: minimal / low / medium / high / xhigh

1.3 사고 내용 반환

응답 메시지에 두 개의 새 필드가 포함됩니다:

  • reasoning_content: 사고 내용(문자열)이며, 쉽게 표시할 수 있도록 제공됩니다.
  • reasoning_details: 사고에 관한 완전한 구조화 정보로, 다중 턴 대화에서 수정 없이 그대로 다시 반환해야 합니다. 내부 구조는 제공자마다 다를 수 있습니다.

비스트리밍 응답 예시(관련 없는 필드 생략):

{
  "choices": [{
    "message": {
      "role": "assistant",
      "content": "Hello! How can I help you today?",
      "reasoning_content": "The user is just saying hello...",
      "reasoning_details": {
        "type": "thinking",
        "thinking": "The user is just saying hello...",
        "signature": "Er8CCkYI..."
      }
    }
  }]
}

스트리밍 응답에서는 사고 내용이 delta.reasoning_content와 delta.reasoning_details를 통해 청크 단위로 전송됩니다. 전체 스트리밍 연결 로직은 아래의 전체 예시를 참고하세요.

1.4 다중 턴 대화에서 사고 유지 (인터리브드 사고는 기본 내장되어 있으며, 추가 매개변수가 필요 없습니다)

다중 턴 대화에서도 모델이 추론 능력을 이어갈 수 있도록, 이전에 반환된 reasoning_details를 수정 없이 그대로 다음 라운드의 어시스턴트 메시지에 넣으면 됩니다:

messages = [
    {"role": "user", "content": "What's the weather like in Boston?"},
    {
        "role": "assistant",
        "content": response.choices[0].message.content,
        "tool_calls": response.choices[0].message.tool_calls,
        "reasoning_details": response.choices[0].message.reasoning_details,
    },
    {
        "role": "tool",
        "tool_call_id": "toolu_xxx",
        "content": '{"temperature": 45, "condition": "rainy"}',
    }
]

AIHubMix는 요청에 과거 사고 정보가 포함된 것을 감지하면 인터리브드 사고를 자동으로 활성화합니다. 이를 통해 추가 매개변수 없이도 모델이 도구 호출 결과를 받은 뒤에도 깊은 추론을 이어갈 수 있습니다.

1.5 전체 예시

아래 두 예시는 다중 턴 도구 호출과 인터리브드 사고의 전체 과정을 보여줍니다: 사용자 질문 → 모델이 사고하고 도구를 호출 → 도구 결과 주입(reasoning_details 보존) → 모델이 인터리브드 사고를 거쳐 최종 응답을 생성.

비스트리밍 · 인터리브드 사고

import os
import json
from openai import OpenAI

client = OpenAI(
    base_url="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)

# ── Tool definition ───────────────────────────────────────────
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "City name"}},
            "required": ["location"]
        }
    }
}]

# ── Mock tool execution ───────────────────────────────────────
WEATHER_DB = {
    "boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
    "tokyo":  {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}

def execute_tool(name: str, args: dict) -> str:
    if name == "get_weather":
        key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
        return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
    return "{}"

# ── Multi-turn conversation loop ─────────────────────────────
messages = [
    {"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]

turn = 0
while True:
    turn += 1
    print(f"\n── Turn {turn} ──")

    response = client.chat.completions.create(
        model="claude-sonnet-4-5",
        messages=messages,
        tools=tools,
        extra_body={"reasoning": {"max_tokens": 2000}},
    )
    msg = response.choices[0].message

    # Print thinking process
    if msg.reasoning_content:
        label = "Interleaved Thinking" if turn > 1 else "Thinking"
        print(f"[{label}] {msg.reasoning_content}")

    # Print response content
    if msg.content:
        print(f"[Response] {msg.content}")

    # Print tool calls
    if msg.tool_calls:
        for tc in msg.tool_calls:
            print(f"[Tool Call: {tc.function.name}] {tc.function.arguments}")

    # Build assistant message, preserve reasoning_details (critical!)
    assistant_msg = {"role": "assistant", "content": msg.content}
    if msg.tool_calls:
        assistant_msg["tool_calls"] = msg.tool_calls
    if msg.reasoning_details:
        assistant_msg["reasoning_details"] = msg.reasoning_details  # pass back unmodified
    messages.append(assistant_msg)

    # No tool_calls means conversation is done
    if not msg.tool_calls:
        break

    # Execute tools and append results to messages
    for tc in msg.tool_calls:
        args = json.loads(tc.function.arguments)
        result = execute_tool(tc.function.name, args)
        print(f"[Tool Result: {tc.function.name}] {result}")
        messages.append({"role": "tool", "tool_call_id": tc.id, "content": result})

스트리밍 · 인터리브드 사고

import os
import sys
import json
from openai import OpenAI

client = OpenAI(
    base_url="https://aihubmix.com/v1",
    api_key=os.environ.get("AIHUBMIX_API_KEY", "sk-***"),
)

# ── Tool definition & mock execution ─────────────────────────
tools = [{
    "type": "function",
    "function": {
        "name": "get_weather",
        "description": "Get current weather for a location",
        "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "City name"}},
            "required": ["location"]
        }
    }
}]

WEATHER_DB = {
    "boston": {"temperature": "45°F (7°C)", "condition": "rainy", "humidity": "85%", "wind": "15 mph NE"},
    "tokyo":  {"temperature": "72°F (22°C)", "condition": "sunny", "humidity": "45%", "wind": "5 mph S"},
}

def execute_tool(name: str, args: dict) -> str:
    if name == "get_weather":
        key = next((k for k in WEATHER_DB if k in args.get("location", "").lower()), None)
        return json.dumps(WEATHER_DB.get(key, {"temperature": "65°F", "condition": "clear"}))
    return "{}"

# ── Stream response collector ────────────────────────────────
def stream_and_collect(turn: int, **kwargs):
    """Stream response, print thinking/content in real-time, accumulate reasoning_details/tool_calls."""
    rd = {}            # accumulated reasoning_details
    content = ""       # accumulated response text
    tc_map = {}        # accumulated tool_calls (by index)
    cur = "none"       # current output section: none / thinking / content

    stream = client.chat.completions.create(stream=True, **kwargs)
    for chunk in stream:
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta

        # ── Handle thinking ──
        rd_delta = getattr(delta, "reasoning_details", None)
        if rd_delta and isinstance(rd_delta, dict):
            for k, v in rd_delta.items():
                if k == "type":
                    rd[k] = v
                elif isinstance(v, str):
                    rd[k] = rd.get(k, "") + v
                elif v is not None:
                    rd[k] = v
            # Print thinking chunks in real-time
            thinking_chunk = rd_delta.get("thinking", "")
            if thinking_chunk:
                if cur != "thinking":
                    cur = "thinking"
                    label = "Interleaved Thinking" if turn > 1 else "Thinking"
                    sys.stdout.write(f"\n[{label}] ")
                sys.stdout.write(thinking_chunk)
                sys.stdout.flush()

        # ── Handle content ──
        if delta.content:
            if cur != "content":
                if cur == "thinking":
                    sys.stdout.write("\n")
                cur = "content"
                sys.stdout.write("\n[Response] ")
            sys.stdout.write(delta.content)
            sys.stdout.flush()
            content += delta.content

        # ── Handle tool_calls ──
        for tc in delta.tool_calls or []:
            i = tc.index
            if i not in tc_map:
                tc_map[i] = {"id": "", "type": "function",
                             "function": {"name": "", "arguments": ""}}
            if tc.id:
                tc_map[i]["id"] = tc.id
            if tc.function:
                tc_map[i]["function"]["name"] += tc.function.name or ""
                tc_map[i]["function"]["arguments"] += tc.function.arguments or ""

    # End current output section
    if cur in ("thinking", "content"):
        sys.stdout.write("\n")

    tool_calls = [tc_map[i] for i in sorted(tc_map)] if tc_map else None
    return {
        "content": content or None,
        "reasoning_details": rd or None,
        "tool_calls": tool_calls,
    }

# ── Multi-turn conversation loop ─────────────────────────────
messages = [
    {"role": "user", "content": "What's the weather like in Boston? Then recommend what to wear."}
]

turn = 0
while True:
    turn += 1
    print(f"\n── Turn {turn} ──")

    result = stream_and_collect(
        turn,
        model="claude-sonnet-4-5",
        messages=messages,
        tools=tools,
        extra_body={"reasoning": {"max_tokens": 2000}},
    )

    # Print tool calls
    if result["tool_calls"]:
        for tc in result["tool_calls"]:
            print(f"[Tool Call: {tc['function']['name']}] {tc['function']['arguments']}")

    # Build assistant message, preserve reasoning_details (critical!)
    assistant_msg = {"role": "assistant", "content": result["content"]}
    if result["tool_calls"]:
        assistant_msg["tool_calls"] = result["tool_calls"]
    if result["reasoning_details"]:
        assistant_msg["reasoning_details"] = result["reasoning_details"]  # pass back unmodified
    messages.append(assistant_msg)

    # No tool_calls means conversation is done
    if not result["tool_calls"]:
        break

    # Execute tools and append results to messages
    for tc in result["tool_calls"]:
        args = json.loads(tc["function"]["arguments"])
        tool_result = execute_tool(tc["function"]["name"], args)
        print(f"[Tool Result: {tc['function']['name']}] {tool_result}")
        messages.append({"role": "tool", "tool_call_id": tc["id"], "content": tool_result})

1.6 사고 강도 매핑 규칙

Effort 모드:

  • Opus 4.6 / Sonnet 4.6 이상: Anthropic 네이티브 Adaptive Thinking의 effort 수준에 매핑됩니다.
  • 그 밖의 모델: budget_tokens 계산 공식을 사용해 산출합니다:
budget_tokens = max(min(max_tokens × effort_ratio, 128000), 1024)
effort effort_ratio
xhigh 0.95
high 0.80
medium 0.50
low 0.20
minimal 0.10

Adaptive Thinking Effort 매핑:

입력 Effort Opus 4.6 Sonnet 4.6
xhigh max high
high high high
medium medium medium
low low low
minimal low low

max_tokens 모드: Anthropic의 budget_tokens로 그대로 할당됩니다.

-think 접미사: Opus/Sonnet 4.6 이상은 adaptive thinking(effort=medium)을 사용하며, 다른 모델은 budget_tokens = min(10240, max_tokens - 1)로 설정하고, 기본 max_tokens는 4096입니다.


2. 프롬프트 캐싱

Chat 인터페이스로 Claude 모델에 요청할 때 프롬프트 캐싱을 사용할 수 있습니다. 메시지에 cache_control 브레이크포인트를 설정하면 역할 카드, RAG 데이터, 책의 장 등 큰 텍스트 블록을 캐시해 재사용할 수 있으며, 이후 요청이 캐시에 바로 적중해 비용을 크게 줄일 수 있습니다.

Claude 공식 문서: 프롬프트 캐싱

2.1 캐싱 비용

작업 가격 배수(원래 입력 가격 대비)
캐시 쓰기(5분 TTL) 1.25x
캐시 쓰기(1시간 TTL) 2x
캐시 읽기 0.1x

2.2 지원 모델 및 최소 캐시 길이

모델 최소 캐시 토큰 수
Claude Opus 4.8 1024
Claude Opus 4.7 2048
Claude Opus 4.6 / Opus 4.5 4096
Claude Sonnet 4.6 / Sonnet 4.5 / Opus 4.1 / Opus 4 / Sonnet 4 / Sonnet 3.7 (지원 종료) 1024
Claude Haiku 4.5 4096
Claude Haiku 3.5 (지원 종료) / Haiku 3 2048
브레이크포인트 개수 제한: 요청당 최대 4개의 cache_control 브레이크포인트를 설정할 수 있습니다.

2.3 캐시 TTL

TTL 구문 적용 시나리오
5분(기본값) "cache_control": {"type": "ephemeral"} 짧은 세션, 일상적인 요청
1시간 "cache_control": {"type": "ephemeral", "ttl": "1h"} 긴 세션, 반복적인 캐시 쓰기를 피하고 싶을 때

1시간 TTL의 쓰기 비용은 더 높지만, 긴 세션에서 반복 쓰기를 줄여 전체 비용을 절감할 수 있습니다. 모든 제공자(Anthropic, Amazon Bedrock, Google Vertex AI 포함)의 Claude 4.5 이후 모델은 모두 1시간 TTL을 지원합니다.

2.4 사용법

system, user(이미지 포함), tools의 cache_control 필드로 캐시 브레이크포인트를 설정할 수 있습니다. 아래 예시는 핵심 구조만 보여 주며, 긴 텍스트 블록은 생략했습니다.

시스템 메시지 캐싱(기본 5분 TTL):

{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [
        {"type": "text", "text": "You are an AI assistant"},
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {
      "role": "user",
      "content": [{"type": "text", "text": "Hello"}]
    }
  ]
}

사용자 메시지 캐싱(1시간 TTL):

{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [{"type": "text", "text": "You are an AI assistant"}]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral", "ttl": "1h"}
        },
        {"type": "text", "text": "Hello"}
      ]
    }
  ]
}

이미지 메시지 캐싱:

{
  "role": "user",
  "content": [
    {
      "type": "image_url",
      "image_url": {"detail": "auto", "url": "data:image/jpeg;base64,/9j/4AAQ..."},
      "cache_control": {"type": "ephemeral"}
    },
    {"type": "text", "text": "What's this?"}
  ]
}

도구 정의 캐싱:

cache_control은 도구 객체의 최상위 레벨에 둡니다(type 및 function과 같은 위치):

{
  "tools": [{
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get current weather for a location",
      "parameters": {
        "type": "object",
        "properties": {"city": {"type": "string"}},
        "required": ["city"]
      }
    },
    "cache_control": {"type": "ephemeral", "ttl": "1h"}
  }]
}

2.5 캐시 상태 확인

응답의 usage에는 캐시 상세 정보를 기록하는 claude_cache_tokens_details가 포함됩니다:

첫 번째 요청(캐시 생성):

{
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 890,
    "total_tokens": 912,
    "claude_cache_tokens_details": {
      "cache_creation_input_tokens": 6266,
      "cache_read_input_tokens": 0,
      "cache_write_5_minutes_input_tokens": 6266,
      "cache_write_1_hour_input_tokens": 0
    }
  }
}

이후 요청(캐시 적중):

{
  "usage": {
    "prompt_tokens": 22,
    "completion_tokens": 810,
    "total_tokens": 832,
    "prompt_tokens_details": {
      "cached_tokens": 6266
    },
    "claude_cache_tokens_details": {
      "cache_creation_input_tokens": 0,
      "cache_read_input_tokens": 6266,
      "cache_write_5_minutes_input_tokens": 0,
      "cache_write_1_hour_input_tokens": 0
    }
  }
}
필드 의미
cache_creation_input_tokens 이번 요청에서 캐시에 기록된 토큰 수
cache_read_input_tokens 이번 요청에서 캐시에서 읽은 토큰 수
cache_write_5_minutes_input_tokens 5분 TTL 캐시에 기록된 토큰 수
cache_write_1_hour_input_tokens 1시간 TTL 캐시에 기록된 토큰 수
prompt_tokens_details.cached_tokens 캐시 적중 시 캐시된 토큰 수이며, OpenAI 형식과 호환됩니다

3. anthropic-beta 요청 헤더

HTTP 헤더 anthropic-beta를 통해 Claude 모델의 베타 기능을 활성화할 수 있으며, AIHubMix는 이를 Anthropic API로 그대로 전달합니다.

사용법

요청 헤더에 anthropic-beta를 추가하고, 값으로 해당 베타 기능 식별자를 넣습니다:

curl "https://aihubmix.com/v1/chat/completions" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $AIHUBMIX_API_KEY" \
  -H "anthropic-beta: context-1m-2025-08-07" \
  -d '{
  "model": "claude-opus-4-5",
  "messages": [
    {
      "role": "system",
      "content": [
        {"type": "text", "text": "You are an AI assistant"},
        {
          "type": "text",
          "text": "(long context)",
          "cache_control": {"type": "ephemeral"}
        }
      ]
    },
    {"role": "user", "content": [{"type": "text", "text": "hello"}]}
  ]
}'
사용 가능한 베타 식별자는 Anthropic API 문서를 참고하세요.

최종 업데이트: 2026-06-01

여러 AI 제공업체를 하나의 게이트웨이로. 프로덕션 환경을 위해 설계했습니다.

AIHubMix 웹사이트 방문