프롬프트 압축
프롬프트 압축 (Prompt Compression, compress())
이 기능은 베타입니다. API와 동작은 정식 출시 전에 바뀔 수 있습니다.
completion() 을 호출하기 전에 긴 대화 히스토리를 줄이려면 litellm.compress() 를 사용하세요.
이 함수는 관련성 높은 최근 컨텍스트를 유지하고, 낮은 관련성 콘텐츠를 가벼운 스텁으로 대체하며, 모델이 필요할 때만 전체 콘텐츠를 요청할 수 있도록 검색(retrieval) 도구를 반환합니다.
암호화(서버 측)가 외부 서비스에 의해 처리되길 원하는 프록시 사용자는 Headroom 을 참고하세요.
빠른 시작
import litellm
from litellm.types.utils import CallTypes
messages = [
{"role": "system", "content": "You are a coding assistant."},
{"role": "user", "content": "# auth.py\n" + "def authenticate():\n pass\n" * 2000},
{"role": "user", "content": "# utils.py\n" + "def helper():\n pass\n" * 2000},
{"role": "user", "content": "Fix the bug in auth.py"},
]
compressed = litellm.compress(
messages=messages,
model="gpt-5.6-terra",
call_type=CallTypes.completion,
compression_trigger=1000,
compression_target=500,
)
response = litellm.completion(
model="gpt-5.6-terra",
messages=compressed["messages"],
tools=compressed["tools"],
)
반환 내용
compress() 는 다음을 포함한 사전을 반환합니다:
messages: 압축된 대화 메시지original_tokens: 압축 전 토큰 수compressed_tokens: 압축 후 토큰 수compression_ratio: 제거된 토큰의 비율cache: 스텁 키 → 원래 전체 콘텐츠의 키-값 매핑tools: 주문형 복원을 위한 검색 도구 정의 (litellm_content_retrieve)
출처: 문서
본문
파라미터
messages( List[dict] , 필수): 입력 대화 메시지model( str , 필수): 토큰 카운팅에 사용되는 모델 이름call_type( CallTypes , 기본CallTypes.completion): 이 메시지들이 따르는 LiteLLM 호출 타입. 지원 값:CallTypes.completion/CallTypes.acompletion(OpenAI chat-completions 형태) 및CallTypes.anthropic_messages(Anthropic Messages 형태)compression_trigger( int , 기본 200000): 입력 토큰 수가 이를 초과할 때만 압축compression_target( Optional[int] , 기본compression_trigger의 70%): 압축 후 원하는 토큰 예산embedding_model( Optional[str] ): 설정하면 BM25 + 임베딩 관련성 점수를 결합embedding_model_params( Optional[dict] ):litellm.embedding()에 전달되는 추가 kwargscompression_cache( Optional[DualCache] ): 임베딩 점수에 사용되는 선택 캐시
동작 참고
compression_trigger보다 작은 메시지는 변경 없이 통과합니다.- 시스템 메시지, 마지막 user 메시지, 마지막 assistant 메시지는 항상 보존됩니다.
- 관련 메시지가 남은 예산에 완전히 맞지 않으면
compress()는 잘린 버전을 유지할 수 있어요. - 압축된 콘텐츠는 절대 손실되지 않으며, cache에 저장되고
litellm_content_retrieve로 주소 지정할 수 있습니다.
검색 도구 호출 처리
모델이 litellm_content_retrieve 를 호출하면 compressed["cache"] 에서 요청된 키를 찾아 그 값을 도구 출력으로 반환하세요.
import json
tool_call = response.choices[0].message.tool_calls[0]
args = json.loads(tool_call.function.arguments)
full_content = compressed["cache"][args["key"]]
서버 측 콜백 루프 (/v1/messages)
Anthropic Messages 호출에 대해 검색 루프를 투명하게 만들기 위해 콜백 기반 압축 가로채기를 활성화할 수 있어요:
litellm_settings:
callbacks: ["compression_interception"]
compression_interception_params:
enabled: true
compression_trigger: 10000
compression_target: 7000
활성화되면 LiteLLM이 다음 서버 측 흐름을 실행합니다:
- 첫 프로바이더 호출 전에 인바운드 메시지 압축
litellm_content_retrieve도구 주입- 모델 응답에서 검색
tool_use블록 감지 - 압축 캐시에서 검색 키 해석
- 에이전틱 루프로 모델 재실행 후 최종 답변 반환
성능
SWE-bench Lite(문제당 ~27k 토큰의 BM25 검색 저장소 컨텍스트를 가진 실제 GitHub 이슈)에서 벤치마크됨.
Claude Opus: 문제 5개, trigger=10k
| 지표 | 기준선 | 압축 | 델타 |
|---|---|---|---|
| 파일 오버랩 | 1.000 | 1.000 | +0.000 |
| 정확한 파일 일치 | 100% | 100% | +0.0% |
| Hunk 오버랩 | 0.582 | 0.361 | -0.221 |
| 콘텐츠 유사도 | 0.367 | 0.373 | +0.006 |
| 평균 프롬프트 토큰 | 30,828 | 6,890 | -77.7% |
| 문제당 평균 비용 | $0.488 | $0.136 | -72.0% |
핵심 요점:
- 파일 수준 타게팅이 완전히 보존됨 — 모델은 압축 유무와 관계없이 같은 파일을 편집합니다.
- 콘텐츠 유사도가 기준선과 일치 — 실제 변경된 줄은 비슷합니다.
- Hunk 오버랩은 약간 하락(-0.221). 모델은 올바른 파일을 대상으로 하지만 주변 컨텍스트가 적어 약간 다른 줄 범위를 편집할 수 있어요.
- 72% 비용 절감, 78% 토큰 감소.
지표 설명
| 지표 | 무엇을 측정하는지 |
|---|---|
| File overlap | 금(gold) 패치 파일이 생성된 패치에 존재하는 비율 |
| Exact file match | 생성된 패치가 정확히 같은 파일 세트를 건드리는지 여부 |
| Hunk overlap | 금 hunk 줄 범위가 생성된 hunk로 덮이는 비율 |
| Content similarity | 금과 생성된 패치 사이 변경된 줄(추가/제거)의 Jaccard 유사도 |
SWE-bench 평가 실행
# 5-problem quick check
python tests/eval_swe_bench.py --model claude-opus-5 --problems 5
# Custom trigger/target
python tests/eval_swe_bench.py --model gpt-5.6-terra --problems 20 \
--compression-trigger 15000 --compression-target 10000
# With embedding scoring
python tests/eval_swe_bench.py --model gpt-5.6-terra --problems 10 \
--embedding-model text-embedding-3-small
HumanEval 스타일 평가 실행
python scripts/eval_compression.py --model gpt-5.6-terra --problems 5