Skip to content

feat(ai-openrouter): forward system-prompt cache_control breakpoints#777

Open
lecstor wants to merge 1 commit into
TanStack:mainfrom
lecstor:fix/openrouter-system-prompt-cache-control
Open

feat(ai-openrouter): forward system-prompt cache_control breakpoints#777
lecstor wants to merge 1 commit into
TanStack:mainfrom
lecstor:fix/openrouter-system-prompt-cache-control

Conversation

@lecstor

@lecstor lecstor commented Jun 17, 2026

Copy link
Copy Markdown

🎯 Changes

@tanstack/ai-openrouter's text adapter collapsed systemPrompts to a plain joined string and dropped the object-form metadata, so Anthropic-family prompt caching over OpenRouter was unreachable — a cache_control breakpoint never reached the wire. (OpenAI routes auto-cache prefixes, so only Anthropic-family routes were affected.)

This mirrors what @tanstack/ai-anthropic already does:

  • Declare OpenRouterSystemPromptMetadata ({ cache_control?: ChatContentCacheControl }) and thread it through BaseTextAdapter's TSystemPromptMetadata param, so cache_control is typed and autocompleted at the chat() call site.
  • In mapOptionsToRequest, when any system prompt carries cache_control, emit the system message as a ChatContentText[] content array with cacheControl on the part(s) that declared it. Without cache_control, the system message is sent as the same joined string as before — existing callers are unaffected.
chat({
  adapter: openRouterText('anthropic/claude-sonnet-4.5'),
  systemPrompts: [
    {
      content: 'Large, stable instructions — cache me.',
      metadata: { cache_control: { type: 'ephemeral' } },
    },
    'Volatile per-request instruction.',
  ],
})

Tests cover: a single cached prompt (asserting both the camelCase pre-serialization shape and the snake_case cache_control wire output via ChatRequest$outboundSchema), mixed cached/uncached prompts (breakpoint only on the prompt that declared it), and the unchanged no-cache_control path (foreign metadata still dropped, plain string preserved).

✅ Checklist

  • I have followed the steps in the Contributing guide.
  • I have tested this code locally with pnpm run test:pr.

🚀 Release Impact

  • This change affects published code, and I have generated a changeset.
  • This change is docs/CI/dev-only (no release).

Summary by CodeRabbit

  • New Features

    • System prompts now support optional per-prompt cache control directives that are properly forwarded to OpenRouter. Backwards compatible—prompts without cache control continue to work as before.
  • Tests

    • Expanded test coverage for system prompt cache control handling and validation.

The text adapter collapsed `systemPrompts` to a plain joined string and
dropped the object-form `metadata`, so Anthropic-family prompt caching over
OpenRouter was unreachable — `cache_control` never reached the wire.

Declare `OpenRouterSystemPromptMetadata` (threaded through `BaseTextAdapter`'s
`TSystemPromptMetadata`, so `cache_control` is typed/autocompleted at the
`chat()` call site) and, when any system prompt carries `cache_control`, emit
the system message as a content-array part carrying the directive — mirroring
`@tanstack/ai-anthropic`. Without `cache_control` the system message is still
the same joined string, so existing callers are unaffected.
@coderabbitai

coderabbitai Bot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c90b6419-1403-48d2-a4a7-bee6fc39758e

📥 Commits

Reviewing files that changed from the base of the PR and between eadabbc and e121468.

📒 Files selected for processing (5)
  • .changeset/openrouter-system-prompt-cache-control.md
  • packages/ai-openrouter/src/adapters/text.ts
  • packages/ai-openrouter/src/index.ts
  • packages/ai-openrouter/src/text/text-provider-options.ts
  • packages/ai-openrouter/tests/openrouter-adapter.test.ts

📝 Walkthrough

Walkthrough

Adds per-system-prompt cache_control forwarding in the OpenRouterTextAdapter. A new exported type OpenRouterSystemPromptMetadata with an optional cache_control field is introduced. The adapter's mapOptionsToRequest is updated to emit a structured content array when any system prompt declares cache_control, preserving existing joined-string behavior otherwise.

Changes

OpenRouter system prompt cache_control support

Layer / File(s) Summary
OpenRouterSystemPromptMetadata type and public export
packages/ai-openrouter/src/text/text-provider-options.ts, packages/ai-openrouter/src/index.ts
Adds ChatContentCacheControl import, defines and documents the exported OpenRouterSystemPromptMetadata type with an optional cache_control field, and re-exports it from the package index.
Adapter type wiring and mapOptionsToRequest logic
packages/ai-openrouter/src/adapters/text.ts
Updates OpenRouterTextAdapter's BaseTextAdapter type argument to OpenRouterSystemPromptMetadata, adds ChatContentText import, and branches mapOptionsToRequest to emit a structured content array with per-prompt cacheControl when any prompt declares cache_control, otherwise falls back to the existing joined-string path.
Tests and changeset
packages/ai-openrouter/tests/openrouter-adapter.test.ts, .changeset/openrouter-system-prompt-cache-control.md
Updates the existing mixed-metadata test to use foreign (non-cache_control) metadata with an explicit drop assertion. Adds two new tests: one verifying structured content emission for a single cached prompt (pre- and post-Zod serialization), and one verifying cache_control is applied only to the declaring prompt while others become plain text parts. Records a minor version changeset.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

  • TanStack/ai#575: Introduced the normalized { content, metadata } system prompt shape whose metadata field is now narrowed to OpenRouterSystemPromptMetadata to carry cache_control through to the wire request.

Suggested reviewers

  • AlemTuzlak
  • tombeckenham

Poem

🐇 Hop hop, the cache is set!
No more prompts lost in the net.
cache_control now makes the trip,
Structured content, a tidy ship.
The rabbit cheers with a joyful skip! 🎉

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main change: forwarding system-prompt cache_control breakpoints in the OpenRouter adapter.
Description check ✅ Passed The description fully addresses all required template sections with detailed explanations, code examples, test coverage details, and both checklist items completed.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

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.

1 participant