Skip to content

feat(fireworks_ai): map litellm session id to x-session-affinity header for prompt caching - #33717

Merged
krrish-berri-2 merged 12 commits into
litellm_internal_stagingfrom
devin/1784306658-fireworks-session-affinity
Jul 18, 2026
Merged

krrish-berri-2 merged 12 commits into
litellm_internal_stagingfrom
devin/1784306658-fireworks-session-affinity

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to 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 it

Claude Code session id (from ~/.claude/projects/.../da93f8f5-b637-41eb-975a-90403981b2c6.jsonl):

da93f8f5-b637-41eb-975a-90403981b2c6

Outbound headers LiteLLM sent to Fireworks for every request in that session:

=== OUTBOUND to Fireworks: POST /inference/v1/chat/completions ===
{
  "User-Agent": "litellm/1.94.0",
  "Authorization": "Bearer ***",
  "x-session-affinity": "da93f8f5-b637-41eb-975a-90403981b2c6",
  ...
}

The same x-session-affinity value was sent on all requests of the session, so Fireworks routes them to the same replica for prompt-cache hits. A plain curl /v1/messages with x-claude-code-session-id: test-session-abc12345 likewise produced x-session-affinity: test-session-abc12345, and requests without any session id carry no affinity header

Cache 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 returned cached_tokens: 3013 of 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 and additional_usage_values.cache_read_input_tokens: 3013 in Metadata; the uncached first request shows no Cache Read Tokens. Full recording and screenshots are in the PR comments below

Type

🆕 New Feature

Changes

Fireworks AI recommends a stable x-session-affinity header 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's x-claude-code-session-id becomes litellm_session_id / metadata.session_id); this PR forwards it to Fireworks

litellm/llms/fireworks_ai/common_utils.py adds get_fireworks_session_id(litellm_params), resolving litellm_session_id -> session_id -> metadata.session_id -> litellm_trace_id and returning None if absent (no synthetic id is generated). FireworksAIMixin.validate_environment() sets x-session-affinity: <session_id> when a session id resolves, unless the caller already supplied that header (case-insensitive check). FireworksAIConfig (chat) now inherits FireworksAIMixin so chat completions, including the Claude Code /v1/messages -> adapter -> litellm.acompletion() path, get the header alongside text completions which already used the mixin

Spend 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 report usage.prompt_tokens_details.cached_tokens instead. get_logging_payload() now aliases a positive cached_tokens into additional_usage_values.cache_read_input_tokens when 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 untouched

Tests: tests/test_litellm/llms/fireworks_ai/chat/test_fireworks_ai_chat_transformation.py covers the affinity header (from litellm_session_id, from metadata.session_id, absent without a session id, explicit-header preservation); tests/test_litellm/proxy/spend_tracking/test_spend_tracking_utils.py covers the spend-log alias (OpenAI-style mapping, Anthropic precedence, zero/absent cached tokens add nothing)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/2ce9237f40c949f98fd71c87bb1b9e1d
Requested by: @krrish-berri-2

yuneng-berri and others added 6 commits July 11, 2026 17:42
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>
@krrish-berri-2 krrish-berri-2 self-assigned this Jul 17, 2026
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

CLAassistant commented Jul 17, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
2 out of 3 committers have signed the CLA.

✅ yuneng-berri
✅ mateo-berri
❌ krrish-berri
You have signed the CLA already but the status is still pending? Let us recheck it.

@devin-ai-integration
devin-ai-integration Bot changed the base branch from litellm_internal_staging to main July 17, 2026 16:53
@greptile-apps

greptile-apps Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds Fireworks AI prompt-cache optimisation by forwarding a stable x-session-affinity header derived from litellm's session identifiers. It introduces get_fireworks_session_id in common_utils.py, wires it into FireworksAIMixin.validate_environment, and adds FireworksAIMixin to FireworksAIConfig's inheritance chain so chat completions benefit alongside the already-covered text-completion path.

  • get_fireworks_session_id resolves session identity in priority order (litellm_session_id → session_id → metadata.session_id → litellm_trace_id), mirroring the existing get_chatgpt_session_id pattern; the litellm_trace_id fallback is untested and the PR description incorrectly states no synthetic ID is ever used.
  • Adding FireworksAIMixin before OpenAIGPTConfig in the MRO silently removes the Content-Type: application/json injection that OpenAIGPTConfig.validate_environment previously provided for chat completions (harmless in practice because httpx sets it, but worth noting).
  • Four new mock-only unit tests cover the main scenarios correctly, but leave the litellm_trace_id fallback branch completely untested.

Confidence Score: 4/5

Safe 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.

Important Files Changed

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

Comment on lines +26 to +29
value = params.get("litellm_trace_id")
if value:
return str(value)
return None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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.

Comment on lines +66 to +79
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


Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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

codecov Bot commented Jul 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing devin/1784306658-fireworks-session-affinity (b1e07a8) with litellm_internal_staging (f759c75)

Open in CodSpeed

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

E2E test: real Claude Code session + Fireworks prompt caching

Ran the proxy from this branch (Postgres + admin UI) with kimi-k2 → fireworks_ai/accounts/fireworks/models/kimi-k2p6, behind a header-logging passthrough to the real Fireworks API, and drove a real interactive Claude Code session (v2.1.197, ANTHROPIC_BASE_URL=http://localhost:4000). Devin session

  • passed — multi-turn Claude Code session on Fireworks via LiteLLM (session id 3ed1ed6f-f3b4-4dba-9e2a-a83924042532)
  • passed — every upstream request carried x-session-affinity: 3ed1ed6f-f3b4-4dba-9e2a-a83924042532 (matches Claude Code session id exactly)
  • passed — LiteLLM UI Logs show a later turn with cached_tokens: 23159 of 23,557 prompt tokens and Cache Read Cost: $0.00370544
  • control — first request of a fresh session: cached_tokens: 0; identical second same-session request: cached_tokens: 43208/43209

Cached tokens in UI logs (usage object) and cache read cost:

cached tokens

x-session-affinity header on every Fireworks request

headers

Cache Read Cost in Cost Breakdown

cache cost

Claude Code session + /status showing session id

turn2
status

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 cache_read_input_tokens, which Fireworks doesn't populate — the cached count is in prompt_tokens_details.cached_tokens.

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>
@devin-ai-integration
devin-ai-integration Bot changed the base branch from main to litellm_internal_staging July 17, 2026 19:01
krrish-berri and others added 4 commits July 18, 2026 02:57
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>
@krrish-berri-2
krrish-berri-2 merged commit b3d05bd into litellm_internal_staging Jul 18, 2026
77 of 79 checks passed
@krrish-berri-2
krrish-berri-2 deleted the devin/1784306658-fireworks-session-affinity branch July 18, 2026 04:33
@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

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 litellm_internal_staging at commit 3829fa3014 and reproduced the identical failure sets there. For proxy-server, the 8 failures in tests/test_litellm/proxy/proxy_server/test_team_model_name_translation.py all raise ValueError: not enough values to unpack (expected 2, got 0) inside create_model_info_response() at the llm_router.get_configured_token_limits(model_id) call in litellm/proxy/utils.py. For proxy-endpoints, the failures are test_get_model_info_with_id_propagates_blocked_true (pydantic validation error on created_by/updated_by from a MagicMock) and two ModuleNotFoundError: No module named 'detect_secrets' failures in the secret detection tests. All reproduce on base with the same commands the CI shards run

This PR only touches the Fireworks transformation/session affinity code and the spend-log usage normalization, none of the files involved in those failures

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants