request-cache.e2e.ts 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { afterEach, describe, expect, it } from 'vitest'
  2. import { Context } from 'cordis'
  3. import LlmService from '@deepseek-ai/dsh-llm'
  4. import SessionStore from '@deepseek-ai/dsh-session'
  5. import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
  6. import ToolRegistry, { defineTool } from '@deepseek-ai/dsh-tools'
  7. import AgentRegistry, { AgentId, type Agent } from '@deepseek-ai/dsh-agent'
  8. import AgentLoop from '@deepseek-ai/dsh-agent-loop'
  9. import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek'
  10. /**
  11. * With-key proof that log-derived requests translate into real provider cache hits: a
  12. * multi-step tool turn (plus a follow-up turn) against the live DeepSeek API must report
  13. * `cacheReadTokens > 0` on every request after the first — the adapter maps the provider's
  14. * `prompt_cache_hit_tokens`, and the per-step usage recorded on `assistant/message` events is
  15. * the production observable for cache behavior (the reconstructability RFC's measurement
  16. * layer: prefix stability is corollary #1).
  17. */
  18. // Long enough that the shared request prefix comfortably spans the provider's
  19. // cache-block granularity (64 tokens) from the very first request.
  20. const SYSTEM = 'You are a terse coding assistant used in an automated cache test. '
  21. + 'Always follow instructions literally and exactly. When the user asks you to look '
  22. + 'something up, call the lookup tool with the requested key and wait for its result '
  23. + 'before answering. Never invent a value the tool has not returned. After the tool '
  24. + 'returns, answer with a single short sentence that repeats the returned value '
  25. + 'verbatim. Do not add explanations, do not use markdown, do not ask follow-up '
  26. + 'questions. If the user asks anything else, answer in one short sentence.'
  27. let ctx: Context | undefined
  28. afterEach(async () => {
  29. await ctx?.fiber.dispose()
  30. ctx = undefined
  31. })
  32. async function loopHarness(): Promise<Context> {
  33. const created = new Context()
  34. await created.plugin(LlmService)
  35. await created.plugin(SessionStore)
  36. await created.plugin(SystemPrompt, { persona: SYSTEM })
  37. await created.plugin(ToolRegistry)
  38. await created.plugin(AgentRegistry)
  39. await created.plugin(AgentLoop, { agents: [] })
  40. await created.plugin(LlmDeepSeek, { models: ['deepseek-v4-flash'] })
  41. created.tools.register(defineTool({
  42. name: 'lookup',
  43. description: 'Look up the stored value for a key.',
  44. parameters: { key: { type: 'string', description: 'The key to look up.' } },
  45. async execute(args) {
  46. return [{ type: 'text', text: `value(${String(args.key)}) = azure-falcon-42` }]
  47. },
  48. }))
  49. return created
  50. }
  51. function waitForIdle(context: Context, agent: Agent): Promise<void> {
  52. return new Promise((resolve) => {
  53. const dispose = context.on('agent/status', (subject, status) => {
  54. if (subject === agent && status === 'idle') {
  55. dispose()
  56. resolve()
  57. }
  58. })
  59. })
  60. }
  61. describe.skipIf(!process.env.DEEPSEEK_API_KEY)('log-derived request cache hits (real API)', () => {
  62. it('every request after the first hits the provider prefix cache', async () => {
  63. ctx = await loopHarness()
  64. const agent = ctx.agentLoop.create(AgentId('cache-e2e'), { model: 'deepseek-v4-flash' })
  65. // Turn 1: forces a tool call → at least two steps (two model requests).
  66. agent.send([{ type: 'text', text: 'Look up the key "deploy-color" with the lookup tool and tell me the value.' }])
  67. await waitForIdle(ctx, agent)
  68. // Turn 2: a follow-up over the same (longer) prefix.
  69. agent.send([{ type: 'text', text: 'Thanks. Repeat that value one more time.' }])
  70. await waitForIdle(ctx, agent)
  71. const usages = [...agent.session.events]
  72. .filter(e => e.type === 'assistant/message')
  73. .map(e => e.data.usage)
  74. expect(usages.length).toBeGreaterThanOrEqual(3) // 2 steps in turn 1 + ≥1 in turn 2
  75. for (const usage of usages) expect(usage).toBeDefined()
  76. // The first request has nothing to hit; every later one shares its
  77. // predecessor as a byte-identical prefix, so the provider must report
  78. // cached prompt tokens (prompt_cache_hit_tokens → cacheReadTokens).
  79. for (const usage of usages.slice(1)) {
  80. expect(usage!.cacheReadTokens ?? 0).toBeGreaterThan(0)
  81. }
  82. // World-verification of the conversation itself: the tool value made it
  83. // through the loop into the final answer.
  84. const finalText = agent.session.deriveMessages().at(-1)!.content
  85. .filter(block => block.type === 'text')
  86. .map(block => block.text)
  87. .join('')
  88. expect(finalText).toContain('azure-falcon-42')
  89. }, 180_000)
  90. })