response.test.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { describe, expect, test } from "bun:test"
  2. import { LLMEvent, LLMResponse } from "../src"
  3. const reduce = (events: ReadonlyArray<LLMEvent>) => events.reduce(LLMResponse.reduce, LLMResponse.empty())
  4. describe("LLMResponse reducer", () => {
  5. test("assembles interleaved reasoning and text with end metadata", () => {
  6. const response = LLMResponse.fromEvents([
  7. LLMEvent.reasoningStart({ id: "r1" }),
  8. LLMEvent.reasoningDelta({ id: "r1", text: "I should " }),
  9. LLMEvent.textStart({ id: "t1" }),
  10. LLMEvent.reasoningDelta({ id: "r1", text: "compare..." }),
  11. LLMEvent.reasoningEnd({ id: "r1", providerMetadata: { anthropic: { signature: "sig" } } }),
  12. LLMEvent.textDelta({ id: "t1", text: "Answer" }),
  13. LLMEvent.textEnd({ id: "t1" }),
  14. LLMEvent.finish({ reason: "stop", usage: { outputTokens: 5 } }),
  15. ])
  16. expect(response?.finishReason).toBe("stop")
  17. expect(response?.usage).toMatchObject({ outputTokens: 5 })
  18. expect(response?.message.content).toEqual([
  19. {
  20. type: "reasoning",
  21. text: "I should compare...",
  22. providerMetadata: { anthropic: { signature: "sig" } },
  23. },
  24. { type: "text", text: "Answer" },
  25. ])
  26. expect(response?.events).toHaveLength(8)
  27. })
  28. test("preserves partial content without completing a failed stream", () => {
  29. const state = reduce([LLMEvent.textStart({ id: "t1" }), LLMEvent.textDelta({ id: "t1", text: "partial" })])
  30. expect(LLMResponse.complete(state)).toBeUndefined()
  31. expect(state.message.content).toEqual([{ type: "text", text: "partial" }])
  32. })
  33. test("assembles tool-call content only after the completed tool call event", () => {
  34. const pending = reduce([
  35. LLMEvent.toolInputStart({ id: "call_1", name: "lookup" }),
  36. LLMEvent.toolInputDelta({ id: "call_1", name: "lookup", text: '{"query"' }),
  37. ])
  38. expect(pending.message.content).toEqual([])
  39. expect(pending.toolInputs.call_1?.text).toBe('{"query"')
  40. const response = LLMResponse.fromEvents([
  41. ...pending.events,
  42. LLMEvent.toolInputDelta({ id: "call_1", name: "lookup", text: ':"weather"}' }),
  43. LLMEvent.toolInputEnd({ id: "call_1", name: "lookup" }),
  44. LLMEvent.toolCall({ id: "call_1", name: "lookup", input: { query: "weather" } }),
  45. LLMEvent.finish({ reason: "tool-calls" }),
  46. ])
  47. expect(response?.message.content).toEqual([
  48. { type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
  49. ])
  50. })
  51. })