llm.test.ts 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. import { describe, expect, test } from "bun:test"
  2. import { CacheHint, LLM, LLMResponse } from "../src"
  3. import * as OpenAIChat from "../src/protocols/openai-chat"
  4. import * as OpenAIResponses from "../src/protocols/openai-responses"
  5. import { LLMRequest, Message, Model, ToolCallPart, ToolChoice, ToolDefinition, ToolResultPart } from "../src/schema"
  6. const chatRoute = OpenAIChat.route
  7. const responsesRoute = OpenAIResponses.route
  8. describe("llm constructors", () => {
  9. test("builds canonical schema classes from ergonomic input", () => {
  10. const request = LLM.request({
  11. id: "req_1",
  12. model: Model.make({ id: "fake-model", provider: "fake", route: chatRoute }),
  13. system: "You are concise.",
  14. prompt: "Say hello.",
  15. })
  16. expect(request).toBeInstanceOf(LLMRequest)
  17. expect(request.model).toBeInstanceOf(Model)
  18. expect(request.messages[0]).toBeInstanceOf(Message)
  19. expect(request.system).toEqual([{ type: "text", text: "You are concise." }])
  20. expect(request.messages[0]?.content).toEqual([{ type: "text", text: "Say hello." }])
  21. expect(request.generation).toBeUndefined()
  22. expect(request.tools).toEqual([])
  23. })
  24. test("updates requests without spreading schema class instances", () => {
  25. const base = LLM.request({
  26. id: "req_1",
  27. model: Model.make({ id: "fake-model", provider: "fake", route: chatRoute }),
  28. prompt: "Say hello.",
  29. })
  30. const updated = LLM.updateRequest(base, {
  31. generation: { maxTokens: 20 },
  32. messages: [...base.messages, Message.assistant("Hi.")],
  33. })
  34. expect(updated).toBeInstanceOf(LLMRequest)
  35. expect(updated.id).toBe("req_1")
  36. expect(updated.model).toEqual(base.model)
  37. expect(updated.generation).toEqual({ maxTokens: 20 })
  38. expect(updated.messages.map((message) => message.role)).toEqual(["user", "assistant"])
  39. })
  40. test("keeps request options separate from route defaults", () => {
  41. const request = LLM.request({
  42. model: Model.make({
  43. id: "fake-model",
  44. provider: "fake",
  45. route: chatRoute.with({
  46. generation: { maxTokens: 100, temperature: 1 },
  47. providerOptions: { openai: { store: false, metadata: { model: true } } },
  48. http: { body: { metadata: { model: true } }, headers: { "x-shared": "model" }, query: { model: "1" } },
  49. }),
  50. }),
  51. prompt: "Say hello.",
  52. generation: { temperature: 0 },
  53. providerOptions: { openai: { store: true, metadata: { request: true } } },
  54. http: { body: { metadata: { request: true } }, headers: { "x-shared": "request" }, query: { request: "1" } },
  55. })
  56. expect(request.generation).toEqual({ temperature: 0 })
  57. expect(request.providerOptions).toEqual({ openai: { store: true, metadata: { request: true } } })
  58. expect(request.http).toEqual({
  59. body: { metadata: { request: true } },
  60. headers: { "x-shared": "request" },
  61. query: { request: "1" },
  62. })
  63. })
  64. test("updates canonical requests from the request datatype", () => {
  65. const base = LLM.request({
  66. id: "req_1",
  67. model: Model.make({ id: "fake-model", provider: "fake", route: chatRoute }),
  68. prompt: "Say hello.",
  69. })
  70. const updated = LLMRequest.update(base, { messages: [...base.messages, Message.assistant("Hi.")] })
  71. expect(updated).toBeInstanceOf(LLMRequest)
  72. expect(updated.id).toBe("req_1")
  73. expect(LLMRequest.input(updated).id).toBe("req_1")
  74. expect(updated.messages.map((message) => message.role)).toEqual(["user", "assistant"])
  75. expect(LLMRequest.update(updated, {})).toBe(updated)
  76. })
  77. test("updates canonical models from the model datatype", () => {
  78. const base = Model.make({
  79. id: "fake-model",
  80. provider: "fake",
  81. route: chatRoute,
  82. })
  83. const updated = Model.update(base, {
  84. route: responsesRoute,
  85. defaults: { generation: { maxTokens: 20 } },
  86. compatibility: { toolSchema: "gemini" },
  87. })
  88. const updatedInput = Model.input(updated)
  89. expect(updated).toBeInstanceOf(Model)
  90. expect(String(updated.id)).toBe("fake-model")
  91. expect(updated.route).toBe(responsesRoute)
  92. expect(updated.defaults?.generation).toEqual({ maxTokens: 20 })
  93. expect(updated.compatibility).toEqual({ toolSchema: "gemini" })
  94. expect(updatedInput.defaults).toBe(updated.defaults)
  95. expect(updatedInput.compatibility).toBe(updated.compatibility)
  96. expect(String(updatedInput.provider)).toBe("fake")
  97. expect(Model.update(updated, {})).toBe(updated)
  98. })
  99. test("carries model defaults and compatibility through route model selection", () => {
  100. const model = chatRoute.model({
  101. id: "kimi-k2",
  102. defaults: {
  103. limits: { context: 128_000, output: 8_192 },
  104. generation: { maxTokens: 1_024, stop: ["END"] },
  105. providerOptions: { openai: { parallelToolCalls: false } },
  106. http: { body: { extra_body: true } },
  107. },
  108. compatibility: { toolSchema: "moonshot" },
  109. })
  110. const request = LLM.request({ model, prompt: "Say hello." })
  111. expect(request.model.defaults?.limits).toEqual({ context: 128_000, output: 8_192 })
  112. expect(request.model.defaults?.generation).toEqual({ maxTokens: 1_024, stop: ["END"] })
  113. expect(request.model.defaults?.providerOptions).toEqual({ openai: { parallelToolCalls: false } })
  114. expect(request.model.defaults?.http).toEqual({ body: { extra_body: true } })
  115. expect(request.model.compatibility).toEqual({ toolSchema: "moonshot" })
  116. expect(request.generation).toBeUndefined()
  117. expect(request.providerOptions).toBeUndefined()
  118. expect(request.http).toBeUndefined()
  119. })
  120. test("builds tool choices from names and tools", () => {
  121. const tool = ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })
  122. expect(tool).toBeInstanceOf(ToolDefinition)
  123. expect(ToolChoice.make("lookup")).toEqual(new ToolChoice({ type: "tool", name: "lookup" }))
  124. expect(ToolChoice.named("required")).toEqual(new ToolChoice({ type: "tool", name: "required" }))
  125. expect(ToolChoice.make(tool)).toEqual(new ToolChoice({ type: "tool", name: "lookup" }))
  126. })
  127. test("builds tool choice modes from reserved strings", () => {
  128. expect(ToolChoice.make("auto")).toEqual(new ToolChoice({ type: "auto" }))
  129. expect(ToolChoice.make("none")).toEqual(new ToolChoice({ type: "none" }))
  130. expect(ToolChoice.make("required")).toEqual(new ToolChoice({ type: "required" }))
  131. expect(
  132. LLM.request({
  133. model: Model.make({
  134. id: "fake-model",
  135. provider: "fake",
  136. route: chatRoute,
  137. }),
  138. prompt: "Use tools if needed.",
  139. toolChoice: "required",
  140. }).toolChoice,
  141. ).toEqual(new ToolChoice({ type: "required" }))
  142. })
  143. test("builds assistant tool calls and tool result messages", () => {
  144. const call = ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })
  145. const result = ToolResultPart.make({ id: "call_1", name: "lookup", result: { temperature: 72 } })
  146. expect(Message.assistant([call]).content).toEqual([call])
  147. expect(Message.tool(result).content).toEqual([
  148. { type: "tool-result", id: "call_1", name: "lookup", result: { type: "json", value: { temperature: 72 } } },
  149. ])
  150. })
  151. test("builds chronological text-only system updates separately from the initial system prompt", () => {
  152. const update = Message.system([
  153. { type: "text", text: "Use parameterized SQL.", cache: new CacheHint({ type: "ephemeral" }) },
  154. ])
  155. const request = LLM.request({
  156. model: Model.make({ id: "fake-model", provider: "fake", route: chatRoute }),
  157. system: "Initial operator prompt.",
  158. messages: [Message.user("Review this."), update],
  159. })
  160. expect(update).toBeInstanceOf(Message)
  161. expect(update).toEqual({
  162. role: "system",
  163. content: [{ type: "text", text: "Use parameterized SQL.", cache: { type: "ephemeral" } }],
  164. })
  165. expect(request.system).toEqual([{ type: "text", text: "Initial operator prompt." }])
  166. expect(request.messages.map((message) => message.role)).toEqual(["user", "system"])
  167. })
  168. test("extracts output text from response events", () => {
  169. expect(
  170. LLMResponse.text({
  171. events: [
  172. { type: "text-delta", id: "text-0", text: "hi" },
  173. { type: "finish", reason: "stop" },
  174. ],
  175. }),
  176. ).toBe("hi")
  177. })
  178. })