Implement Prompt Caching for reduced cost and latency
masterThis package supports two methods for OpenRouter prompt caching:
- Top-level caching (Recommended for multi-turn conversations): Set the
cache_controlproperty on theChatDataobject. This applies caching to the entire request. - Explicit cache breakpoint (Fine-grained control): Set the
cache_controlproperty on specificTextContentDataobjects within a message's content array. This is ideal for caching large, static blocks like RAG data or long instructions.
Use CacheControlData::ALLOWED_TYPE (e.g., "ephemeral") and an optional ttl (e.g., '1h').
// Top-level example (automatic caching)
$chatData = new ChatData(
messages: [
new MessageData(
role: RoleType::USER,
content: 'What triggered the collapse?',
),
],
model: 'anthropic/claude-sonnet-4.6',
cache_control: new CacheControlData(
type: CacheControlData::ALLOWED_TYPE, // "ephemeral"
ttl: '1h', // optional
),
);
// Explicit breakpoint example (cache a large text block)
$chatData = new ChatData(
messages: [
new MessageData(
role: RoleType::USER,
content: [
new TextContentData(text: 'Given the book below:'),
new TextContentData(
text: 'HUGE TEXT BODY',
cache_control: new CacheControlData(
type: CacheControlData::ALLOWED_TYPE,
ttl: '1h',
),
),
new TextContentData(text: 'What triggered the collapse?'),
],
),
],
model: 'anthropic/claude-sonnet-4.6',
);