src/context/turn-context.ts
1 KB - 查看原始文件
// Per-turn context: facts that change every turn, such as the current time.
//
// They must NOT go in the system prompt: the system prompt is the start of every request, and
// changing one byte there invalidates the prompt cache for the whole conversation. Instead, each
// user message gets a short context block in front of the owner's text. That block becomes part
// of the history like any other message, so earlier requests stay byte-for-byte the same.
import type { BetaContentBlockParam } from '@anthropic-ai/sdk/resources/beta/messages/messages';
export interface TurnContextInput {
now: Date;
timezone: string;
channel: string;
}
export function turnContextBlock({ now, timezone, channel }: TurnContextInput): string {
const local = new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
dateStyle: 'full',
timeStyle: 'short',
}).format(now);
return `<turn-context>\nlocal time: ${local} (${timezone})\nchannel: ${channel}\n</turn-context>`;
}
/** The user message content: the context block first, then what the owner wrote. */
export function userContent(text: string, context?: string): string | BetaContentBlockParam[] {
if (!context) return text;
return [
{ type: 'text', text: context },
{ type: 'text', text },
];
}