본문으로 건너뛰기

© 2026 Molayo

Dev.to헤드라인2026. 05. 07. 23:07

Best AI Gateway to Optimize Claude Code Token Cost

요약

Claude Code를 사용하는 에이전트 워크플로우에서 발생하는 높은 토큰 비용 문제를 해결하기 위해 AI 게이트웨이를 활용하는 방법을 설명합니다. 이 게이트웨이는 응답 캐싱, 저렴한 모델로의 전환(모델 고정), 그리고 특히 MCP 도구 정의 오버헤드를 획기적으로 줄여주는 '코드 모드'를 제공하여 비용 효율성을 극대화합니다. 핵심적으로, 게이트웨이를 통해 Claude Code에 접근하면 API 호출을 중앙 집중식으로 관리할 수 있으며, 이를 통해 반복적인 작업의 중복 계산을 방지하고, 필요한 도구 정의만 컨텍스트에 주입하는 방식으로 토큰 사용량을 크게 절감할 수 있습니다.

핵심 포인트

  • AI 게이트웨이는 Claude Code 워크플로우에서 발생하는 높은 토큰 비용(모델 선택, 반복 작업, 도구 정의 오버헤드)을 해결합니다.
  • 게이트웨이를 통해 API 호출을 중앙 집중화하고, `ANTHROPIC_BASE_URL` 설정을 사용하여 Claude Code가 게이트웨이와 통신하도록 설정할 수 있습니다.
  • 필요에 따라 기본 모델을 Sonnet과 같은 저렴한 모델로 고정(pinning)하여 비용을 절감할 수 있습니다.
  • 의미론적 캐싱(Semantic Caching) 기능을 활성화하여 유사하거나 동일한 질문에 대한 중복 계산 및 토큰 사용을 방지합니다.
  • MCP 서버를 위한 '코드 모드(Code Mode)'는 도구 정의 오버헤드를 획기적으로 줄여주어, 수백 개의 도구가 연결된 경우 토큰 페이로드를 대폭 감소시키는 가장 큰 최적화 방법입니다.

TL;DR: 에이전트 중심 워크플로우에서 Claude Code 토큰 비용은 각 도구 정의가 컨텍스트에 주입됨으로 인해 빠르게 증가합니다. Claude Code 앞에 있는 AI 게이트웨이에서는 응답을 캐싱하고, 더 저렴한 모델로 전환하며, 코드 모드를 사용하여 도구 정의 오버헤드를 줄일 수 있습니다. Bifrost 와 테스트한 설정에서 가장 큰 단일 최적화는 MCP 의 코드 모드로, 도구 정의 토큰을 58% 에서 92.8% 까지 줄입니다. 이 글은 Claude Code, MCP 서버 기본 개념, 그리고 CLI 에이전트에서 ANTHROPIC_BASE_URL 이 하는 일을 알고 있다는 가정하에 작성됩니다.

Claude Code 토큰 비용이 어디서 오나요?

일반적인 Claude Code 워크로드에서 비용을 주도하는 세 가지 요소가 있습니다. 첫째, 모델 자체입니다. 기본 Claude Code 는 대부분의 작업에 Sonnet 을 사용하고 어려운 작업에는 Opus 를 사용합니다. Opus 는 토큰당 Sonnet 보다 수 배 비싸고, Sonnet 은 Haiku 보다 수 배 비쌉니다.

둘째, 반복 작업입니다. Claude Code 는 장기간 세션에서 파일을 다시 읽으며, grep 를 재실행하고 동일한 문제를 다시 생각합니다. 두 개의 인접한 프롬프트가 동일한 코드 경로를 타격하면, 캐싱되지 않는 한 두 번째는 전체 비용이 청구됩니다.

셋째, MCP 도구 카탈로그입니다. 각 연결된 MCP 서버의 모든 도구 정의는 각 요청마다 컨텍스트에 주입됩니다. Anthropic 의 Model Context Protocol 개요는 프로토콜 수준에서 도구 발견이 어떻게 작동하는지 설명합니다. 몇 개의 서버가 연결되면 모델이 결코 호출하지 않을 도구를 설명하기 위해 토큰 수천을 지불할 수 있습니다.

게이트웨이는 세 가지 모두를 해결합니다.

단계 1: Claude Code 를 게이트웨이로 지시
Bifrost 의 경우, Claude Code 가 API 호스트를 발견하도록 읽는 환경 변수를 설정하세요.
export ANTHROPIC_BASE_URL = http://localhost:8080/anthropic
export ANTHROPIC_API_KEY = vk-prod-abc123
claude Bifrost 는 100% 호환되는 Anthropic 엔드포인트를 노출하므로, Claude Code 는 게이트웨이를 대화하고 있다는 것을 알지 못합니다. 완전한 통합 단계는 Bifrost Claude Code 문서에 있습니다.

단계 2: 필요할 때 Claude Code 를 더 저렴한 모델로 고정
Claude Code 는 시작 또는 세션 중 모델 오버라이드를 존중합니다. 게이트웨이에서는 Sonnet 을 기본 작업으로 고정하고, 필요할 때만 Opus 로 전환할 수 있습니다.
claude --model claude-sonnet-4-6
Bedrock 또는 Vertex 를 준수 이유로 라우팅하는 경우, 게이트웨이는 해당 백엔드로 매핑되는 핀ning 문법을 수용합니다:
export ANTHROPIC_DEFAULT_SONNET_MODEL = "bedrock/global.anthropic.claude-sonnet-4-6"
export ANTHROPIC_DEFAULT_OPUS_MODEL = "vertex/claude-opus-4-7"
The Bifrost CLI agents 개요는 동일한 설정에서 Claude Code, Codex CLI, Gemini CLI 를 다룹니다.

단계 3: 의미론적 캐싱 활성화
Claude Code 는 동일한 세션 내에서 유사한 질문을 다시 묻습니다. 이중층 캐싱은 정확한 반복과 의미적으로 유사한 프롬프트를 모두 잡습니다.
semantic_cache : enabled : true
vector_store : weaviate
weaviate_url : ${WEAVIATE_URL}
similarity_threshold : 0.92
conversation_history_threshold : 3
ttl_seconds : 86400
각 요청은 캐싱에 참여하려면 x-bf-cache-key 헤더가 필요합니다. Claude Code 는 기본적으로 이 헤더를 설정하지 않으므로, 가상 키별로 Bifrost 를 주입하거나 CLI 호출을 헤더 설정 프로кси로 감싸야 합니다. 의미론적 캐싱 문서는 메커니즘을 다룹니다.

캐시는 모델과 제공자 격리되어 있으므로 Sonnet 응답은 Opus 요청에 절대 반환되지 않습니다.

단계 4: MCP 서버를 위한 코드 모드 사용
이것은 테스트에서 가장 큰 단일 최적화입니다. 코드 모드는 완전한 도구 정의 주입을 Python 스텝 생성 방식으로 대체합니다. 모든 도구를 보는 대신, 각 서버의 모든 도구를...

rver, the model sees four meta-tools: listToolFiles , readToolFile , getToolDocs , and executeToolCode . The model loads only the tool definitions it actually needs. Bifrost publishes Code Mode benchmarks on its MCP gateway resource page : MCP tools connected Token reduction Pass rate 96 tools 58% 100% 251 tools 84.5% 100% 508 tools 92.8% 100% At ~500 tools, the per-query payload drops from roughly 1.15M tokens to 83K, a 14x reduction. Tool calls execute inside a sandboxed Starlark interpreter so behaviour is bounded and auditable. The same numbers and detail are in the Bifrost benchmarks resource . Configuring Code Mode for Claude Code's MCP setup: mcp : code_mode : enabled : true sandbox : starlark servers : - name : github-mcp type : stdio command : [ " npx" , " -y" , " @modelcontextprotocol/server-github" ] - name : linear-mcp type : http url : ${LINEAR_MCP_URL} The MCP tool execution docs cover the sandbox model in depth. Step 5: Set Per-Session Budget Caps Long Claude Code sessions can run for hours. Per-virtual-key budget caps stop runaway sessions before they hit your finance team. virtual_keys : - key_name : claude-code-dev key : vk-cc-dev rate_limit : token_limit : 5000000 token_limit_duration : " 1d" budget_limit : 50.00 budget_duration : " 1d" allowed_models : [ " claude-sonnet-4-6" , " claude-opus-4-7" ] Reset durations are calendar-aligned ( 1d , 1w , 1M , 1Y in UTC) so caps line up with billing cycles. The four-tier budget hierarchy (Customer, Team, Virtual Key, Provider Config) is documented on the Bifrost governance resource . Comparison: Optimisation Levers Lever Mechanism Best for Model pinning Default to Sonnet, opt into Opus All Claude Code workloads Semantic caching Vector similarity match Sessions with repeated patterns Code Mode (MCP) Stub generation, demand-loaded tools Large MCP catalogs Per-VK budgets Hard caps with calendar resets Long-running sessions Trade-offs and Limitations Bifrost is self-hosted only with no managed cloud. If you do not have ops capacity to run a gateway, this is real overhead. Code Mode requires the model to call meta-tools to load definitions, which adds a small number of extra round trips compared to the upfront-definition approach. On large catalogs that is a clear net win. On a 5-tool setup it is not. Semantic caching introduces freshness questions for code workflows. If your repo state changed but the cached prompt looks identical, you get a stale response. Tight TTLs and per-key cache scoping reduce the risk. OpenRouter is not compatible because of a tool call streaming issue, so if you currently route Claude Code through OpenRouter you cannot keep that path through Bifrost. Bifrost is newer than LiteLLM , so the community and ecosystem of integrations is still building up. Quick Recap Three cost drivers: model choice, repeat work, and MCP tool definition payload Pin Claude Code to Sonnet by default, opt into Opus only when needed Dual-layer semantic caching captures repeat patterns inside long sessions Code Mode for MCP cuts tool definition tokens by 58% to 92.8% depending on catalog size Per-virtual-key budgets put hard caps on runaway sessions GitHub: https://git.new/bifrost | Docs: https://getmax.im/bifrostdocs | Website: https://getmax.im/bifrost-home

AI 자동 생성 콘텐츠

본 콘텐츠는 Dev.to AI tag의 원문을 AI가 자동으로 요약·번역·분석한 것입니다. 원 저작권은 원저작자에게 있으며, 정확한 내용은 반드시 원문을 확인해 주세요.

원문 바로가기
1

댓글

0