Repository navigation
feat(fireworks_ai): map litellm session id to x-session-affinity header for prompt caching - #33717
Conversation
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
chore(ci): promote internal staging to main
…er for prompt caching Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
🤖 Devin AI EngineerI'll be helping with this pull request! Here's what you should know: ✅ I will automatically:
Note: I can only respond to comments from users who have write access to this repository. ⚙️ Control Options:
|
|
|
Greptile SummaryThis PR adds Fireworks AI prompt-cache optimisation by forwarding a stable
Confidence Score: 4/5Safe to merge; the change is additive and the x-session-affinity header is only injected when a session identifier resolves, with an explicit guard against overwriting a caller-supplied value. The core logic is a straightforward header injection, consistent with the analogous ChatGPT pattern already in the codebase. The three flagged items are non-blocking: the litellm_trace_id fallback is untested and contradicts the PR description (though it mirrors existing code), the MRO change that drops Content-Type from the validate_environment return value is compensated by httpx, and the test gap around the trace-id branch leaves a small blind spot in the suite. litellm/llms/fireworks_ai/common_utils.py — the litellm_trace_id fallback in get_fireworks_session_id deserves a clarifying comment or an additional test to confirm the intended behaviour when only a trace ID is present.
|
| Filename | Overview |
|---|---|
| litellm/llms/fireworks_ai/common_utils.py | Adds get_fireworks_session_id helper and wires x-session-affinity header into FireworksAIMixin.validate_environment; logic mirrors the existing chatgpt equivalent but the litellm_trace_id fallback contradicts the PR description and is untested |
| litellm/llms/fireworks_ai/chat/transformation.py | Adds FireworksAIMixin to FireworksAIConfig's inheritance chain so chat completions get the session-affinity header; the MRO change silently drops Content-Type: application/json that OpenAIGPTConfig.validate_environment previously set, though httpx sets it automatically |
| tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py | Four new unit tests covering main session-affinity scenarios; all mock-only and correct; missing a test for the litellm_trace_id fallback branch introduced in get_fireworks_session_id |
Reviews (1): Last reviewed commit: "feat(fireworks_ai): map litellm session ..." | Re-trigger Greptile
| value = params.get("litellm_trace_id") | ||
| if value: | ||
| return str(value) | ||
| return None |
There was a problem hiding this comment.
litellm_trace_id fallback contradicts stated behaviour
The PR description explicitly states "no synthetic id is generated" when no user-supplied session id is present, but the code falls back to litellm_trace_id before returning None. litellm_trace_id is typically a per-request unique value generated by litellm itself — if it changes on every request within the same conversation, the x-session-affinity header will carry a different value each time, preventing prompt-cache hits on the same Fireworks replica. The existing get_chatgpt_session_id in litellm/llms/chatgpt/common_utils.py uses the same pattern (and also falls back to litellm_call_id), so this may be intentional, but there is no test covering this branch and the PR description is misleading if it is.
| config = FireworksAIConfig() | ||
|
|
||
| headers = config.validate_environment( | ||
| headers={}, | ||
| model="accounts/fireworks/models/test-model", | ||
| messages=[], | ||
| optional_params={}, | ||
| litellm_params={}, | ||
| api_key="test-key", | ||
| ) | ||
|
|
||
| assert "x-session-affinity" not in headers | ||
|
|
||
|
|
There was a problem hiding this comment.
litellm_trace_id branch is completely untested
get_fireworks_session_id has a fourth resolution step: falling back to litellm_trace_id. The "no session id" test (test_validate_environment_does_not_set_session_affinity_without_session_id) passes litellm_params={}, which means the trace-id branch is never exercised. In production the proxy often populates litellm_params["litellm_trace_id"], so the actual behaviour under that condition — whether the header is set or absent — is unverified by the test suite.
|
|
||
|
|
||
| class FireworksAIConfig(OpenAIGPTConfig): | ||
| class FireworksAIConfig(FireworksAIMixin, OpenAIGPTConfig): |
There was a problem hiding this comment.
MRO change silently drops
Content-Type: application/json from the validate-environment path
Before this PR FireworksAIConfig resolved validate_environment through OpenAIGPTConfig, which explicitly sets Content-Type: application/json when the header is absent. Now FireworksAIMixin.validate_environment is resolved first in the MRO and does not call super().validate_environment(), so the Content-Type header is no longer added by this path. In practice httpx injects it automatically when a JSON body is provided, so this is unlikely to cause a real failure, but it is a silent behavioural delta worth being aware of — especially for code paths that inspect the returned headers dictionary directly.
Codecov Report✅ All modified and coverable lines are covered by tests. 📢 Thoughts on this report? Let us know! |
E2E test: real Claude Code session + Fireworks prompt cachingRan the proxy from this branch (Postgres + admin UI) with
Cached tokens in UI logs (usage object) and cache read cost: Note: the UI "Cache Hit: False" badge reflects LiteLLM's own response cache, not provider prompt caching; and the "Cache Read Tokens" metric reads Anthropic-style |
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
b3d05bd
into
litellm_internal_staging
|
Clarifying the two failing CI checks (proxy-server / Run tests and proxy-endpoints / Run tests): both are preexisting on the base branch and unrelated to this PR I checked out This PR only touches the Fireworks transformation/session affinity code and the spend-log usage normalization, none of the files involved in those failures |
Relevant issues
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito re-request a review after pushing changes)Screenshots / Proof of Fix
Live e2e run against the proxy from this branch with a real Fireworks model (
fireworks_ai/accounts/fireworks/models/kimi-k2p6), fronted by a header-logging passthrough to the real Fireworks API so outbound request headers are visible. A real Claude Code session (v2.1.197,ANTHROPIC_BASE_URL=http://localhost:4000) was run against itClaude Code session id (from
~/.claude/projects/.../da93f8f5-b637-41eb-975a-90403981b2c6.jsonl):Outbound headers LiteLLM sent to Fireworks for every request in that session:
The same
x-session-affinityvalue was sent on all requests of the session, so Fireworks routes them to the same replica for prompt-cache hits. A plaincurl /v1/messageswithx-claude-code-session-id: test-session-abc12345likewise producedx-session-affinity: test-session-abc12345, and requests without any session id carry no affinity headerCache proof (same setup, two identical curl requests in one session): the first request returned
prompt_tokens_details.cached_tokens: 0; the identical second request in the same session returnedcached_tokens: 3013of 3,014 prompt tokens. With the spend-log normalization, the LiteLLM UI Logs request detail (http://localhost:4000/ui/logs, open the session, second request) shows Cache Read Tokens: 3,013 in the Metrics panel andadditional_usage_values.cache_read_input_tokens: 3013in Metadata; the uncached first request shows no Cache Read Tokens. Full recording and screenshots are in the PR comments belowType
🆕 New Feature
Changes
Fireworks AI recommends a stable
x-session-affinityheader value per conversation so requests land on the same replica and hit the prompt cache. LiteLLM already derives a session id from client headers (e.g. Claude Code'sx-claude-code-session-idbecomeslitellm_session_id/metadata.session_id); this PR forwards it to Fireworkslitellm/llms/fireworks_ai/common_utils.pyaddsget_fireworks_session_id(litellm_params), resolvinglitellm_session_id->session_id->metadata.session_id->litellm_trace_idand returningNoneif absent (no synthetic id is generated).FireworksAIMixin.validate_environment()setsx-session-affinity: <session_id>when a session id resolves, unless the caller already supplied that header (case-insensitive check).FireworksAIConfig(chat) now inheritsFireworksAIMixinso chat completions, including the Claude Code/v1/messages-> adapter ->litellm.acompletion()path, get the header alongside text completions which already used the mixinSpend logs: the Admin UI "Cache Read Tokens" metric reads
metadata.additional_usage_values.cache_read_input_tokens(Anthropic-style), which OpenAI-compatible providers like Fireworks don't emit; they reportusage.prompt_tokens_details.cached_tokensinstead.get_logging_payload()now aliases a positivecached_tokensintoadditional_usage_values.cache_read_input_tokenswhen no explicit value exists, so the metric renders for these providers. The client-facing response usage is unchanged (OpenAI-style only, no duplicated field), explicit Anthropic-style values take precedence, and cost calculation is untouchedTests:
tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.pycovers the affinity header (fromlitellm_session_id, frommetadata.session_id, absent without a session id, explicit-header preservation);tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.pycovers the spend-log alias (OpenAI-style mapping, Anthropic precedence, zero/absent cached tokens add nothing)Final Attestation
Link to Devin session: https://app.devin.ai/sessions/2ce9237f40c949f98fd71c87bb1b9e1d
Requested by: @krrish-berri-2