request-cache.e2e.ts 4.6 KB

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