openai-chat.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. import { describe, expect } from "bun:test"
  2. import { Effect, Schema, Stream } from "effect"
  3. import { HttpClientRequest } from "effect/unstable/http"
  4. import { LLM, LLMError } from "../../src"
  5. import * as Azure from "../../src/providers/azure"
  6. import * as OpenAI from "../../src/providers/openai"
  7. import * as OpenAIChat from "../../src/protocols/openai-chat"
  8. import { LLMClient } from "../../src/route"
  9. import { it } from "../lib/effect"
  10. import { dynamicResponse, fixedResponse, truncatedStream } from "../lib/http"
  11. import { deltaChunk, usageChunk } from "../lib/openai-chunks"
  12. import { sseEvents } from "../lib/sse"
  13. const TargetJson = Schema.fromJsonString(Schema.Unknown)
  14. const encodeJson = Schema.encodeSync(TargetJson)
  15. const decodeJson = Schema.decodeUnknownSync(TargetJson)
  16. const model = OpenAIChat.model({
  17. id: "gpt-4o-mini",
  18. baseURL: "https://api.openai.test/v1/",
  19. headers: { authorization: "Bearer test" },
  20. })
  21. const request = LLM.request({
  22. id: "req_1",
  23. model,
  24. system: "You are concise.",
  25. prompt: "Say hello.",
  26. generation: { maxTokens: 20, temperature: 0 },
  27. })
  28. describe("OpenAI Chat route", () => {
  29. it.effect("prepares OpenAI Chat payload", () =>
  30. Effect.gen(function* () {
  31. // Pass the OpenAIChat payload type so `prepared.body` is statically
  32. // typed to the route's native shape — the assertions below read field
  33. // names without `unknown` casts.
  34. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(request)
  35. const _typed: { readonly model: string; readonly stream: true } = prepared.body
  36. expect(prepared.body).toEqual({
  37. model: "gpt-4o-mini",
  38. messages: [
  39. { role: "system", content: "You are concise." },
  40. { role: "user", content: "Say hello." },
  41. ],
  42. stream: true,
  43. stream_options: { include_usage: true },
  44. max_tokens: 20,
  45. temperature: 0,
  46. })
  47. }),
  48. )
  49. it.effect("maps OpenAI provider options to Chat options", () =>
  50. Effect.gen(function* () {
  51. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  52. LLM.request({
  53. model: OpenAI.chat("gpt-4o-mini", { baseURL: "https://api.openai.test/v1/" }),
  54. prompt: "think",
  55. providerOptions: { openai: { reasoningEffort: "low" } },
  56. }),
  57. )
  58. expect(prepared.body.store).toBe(false)
  59. expect(prepared.body.reasoning_effort).toBe("low")
  60. }),
  61. )
  62. it.effect("adds native query params to the Chat Completions URL", () =>
  63. LLMClient.generate(
  64. LLM.updateRequest(request, { model: OpenAIChat.model({ ...model, queryParams: { "api-version": "v1" } }) }),
  65. ).pipe(
  66. Effect.provide(
  67. dynamicResponse((input) =>
  68. Effect.gen(function* () {
  69. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  70. expect(web.url).toBe("https://api.openai.test/v1/chat/completions?api-version=v1")
  71. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  72. headers: { "content-type": "text/event-stream" },
  73. })
  74. }),
  75. ),
  76. ),
  77. ),
  78. )
  79. it.effect("uses Azure api-key header for static OpenAI Chat keys", () =>
  80. LLMClient.generate(
  81. LLM.updateRequest(request, {
  82. model: Azure.chat("gpt-4o-mini", {
  83. baseURL: "https://opencode-test.openai.azure.com/openai/v1/",
  84. apiKey: "azure-key",
  85. headers: { authorization: "Bearer stale" },
  86. }),
  87. }),
  88. ).pipe(
  89. Effect.provide(
  90. dynamicResponse((input) =>
  91. Effect.gen(function* () {
  92. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  93. expect(web.headers.get("api-key")).toBe("azure-key")
  94. expect(web.headers.get("authorization")).toBeNull()
  95. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  96. headers: { "content-type": "text/event-stream" },
  97. })
  98. }),
  99. ),
  100. ),
  101. ),
  102. )
  103. it.effect("applies serializable HTTP overlays after payload lowering", () =>
  104. LLMClient.generate(
  105. LLM.updateRequest(request, {
  106. model: OpenAIChat.model({ ...model, apiKey: "fresh-key", headers: { authorization: "Bearer stale" } }),
  107. http: {
  108. body: { metadata: { source: "test" } },
  109. headers: { authorization: "Bearer request", "x-custom": "yes" },
  110. query: { debug: "1" },
  111. },
  112. }),
  113. ).pipe(
  114. Effect.provide(
  115. dynamicResponse((input) =>
  116. Effect.gen(function* () {
  117. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  118. expect(web.url).toBe("https://api.openai.test/v1/chat/completions?debug=1")
  119. expect(web.headers.get("authorization")).toBe("Bearer fresh-key")
  120. expect(web.headers.get("x-custom")).toBe("yes")
  121. expect(decodeJson(input.text)).toMatchObject({
  122. stream: true,
  123. stream_options: { include_usage: true },
  124. metadata: { source: "test" },
  125. })
  126. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  127. headers: { "content-type": "text/event-stream" },
  128. })
  129. }),
  130. ),
  131. ),
  132. ),
  133. )
  134. it.effect("prepares assistant tool-call and tool-result messages", () =>
  135. Effect.gen(function* () {
  136. const prepared = yield* LLMClient.prepare(
  137. LLM.request({
  138. id: "req_tool_result",
  139. model,
  140. messages: [
  141. LLM.user("What is the weather?"),
  142. LLM.assistant([LLM.toolCall({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  143. LLM.toolMessage({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  144. ],
  145. }),
  146. )
  147. expect(prepared.body).toEqual({
  148. model: "gpt-4o-mini",
  149. messages: [
  150. { role: "user", content: "What is the weather?" },
  151. {
  152. role: "assistant",
  153. content: null,
  154. tool_calls: [
  155. {
  156. id: "call_1",
  157. type: "function",
  158. function: { name: "lookup", arguments: encodeJson({ query: "weather" }) },
  159. },
  160. ],
  161. },
  162. { role: "tool", tool_call_id: "call_1", content: encodeJson({ forecast: "sunny" }) },
  163. ],
  164. stream: true,
  165. stream_options: { include_usage: true },
  166. })
  167. }),
  168. )
  169. it.effect("rejects unsupported user media content", () =>
  170. Effect.gen(function* () {
  171. const error = yield* LLMClient.prepare(
  172. LLM.request({
  173. id: "req_media",
  174. model,
  175. messages: [LLM.user({ type: "media", mediaType: "image/png", data: "AAECAw==" })],
  176. }),
  177. ).pipe(Effect.flip)
  178. expect(error.message).toContain("OpenAI Chat user messages only support text content for now")
  179. }),
  180. )
  181. it.effect("rejects unsupported assistant reasoning content", () =>
  182. Effect.gen(function* () {
  183. const error = yield* LLMClient.prepare(
  184. LLM.request({
  185. id: "req_reasoning",
  186. model,
  187. messages: [LLM.assistant({ type: "reasoning", text: "hidden" })],
  188. }),
  189. ).pipe(Effect.flip)
  190. expect(error.message).toContain("OpenAI Chat assistant messages only support text and tool-call content for now")
  191. }),
  192. )
  193. it.effect("parses text and usage stream fixtures", () =>
  194. Effect.gen(function* () {
  195. const body = sseEvents(
  196. deltaChunk({ role: "assistant", content: "Hello" }),
  197. deltaChunk({ content: "!" }),
  198. deltaChunk({}, "stop"),
  199. usageChunk({
  200. prompt_tokens: 5,
  201. completion_tokens: 2,
  202. total_tokens: 7,
  203. prompt_tokens_details: { cached_tokens: 1 },
  204. completion_tokens_details: { reasoning_tokens: 0 },
  205. }),
  206. )
  207. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  208. expect(response.text).toBe("Hello!")
  209. expect(response.events).toEqual([
  210. { type: "text-delta", text: "Hello" },
  211. { type: "text-delta", text: "!" },
  212. {
  213. type: "request-finish",
  214. reason: "stop",
  215. usage: {
  216. inputTokens: 5,
  217. outputTokens: 2,
  218. reasoningTokens: 0,
  219. cacheReadInputTokens: 1,
  220. totalTokens: 7,
  221. native: {
  222. prompt_tokens: 5,
  223. completion_tokens: 2,
  224. total_tokens: 7,
  225. prompt_tokens_details: { cached_tokens: 1 },
  226. completion_tokens_details: { reasoning_tokens: 0 },
  227. },
  228. },
  229. },
  230. ])
  231. }),
  232. )
  233. it.effect("assembles streamed tool call input", () =>
  234. Effect.gen(function* () {
  235. const body = sseEvents(
  236. deltaChunk({
  237. role: "assistant",
  238. tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
  239. }),
  240. deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
  241. deltaChunk({}, "tool_calls"),
  242. )
  243. const response = yield* LLMClient.generate(
  244. LLM.updateRequest(request, {
  245. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  246. }),
  247. ).pipe(Effect.provide(fixedResponse(body)))
  248. expect(response.events).toEqual([
  249. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  250. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  251. { type: "tool-call", id: "call_1", name: "lookup", input: { query: "weather" } },
  252. { type: "request-finish", reason: "tool-calls", usage: undefined },
  253. ])
  254. }),
  255. )
  256. it.effect("does not finalize streamed tool calls without a finish reason", () =>
  257. Effect.gen(function* () {
  258. const body = sseEvents(
  259. deltaChunk({
  260. role: "assistant",
  261. tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
  262. }),
  263. deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
  264. )
  265. const response = yield* LLMClient.generate(
  266. LLM.updateRequest(request, {
  267. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  268. }),
  269. ).pipe(Effect.provide(fixedResponse(body)))
  270. expect(response.events).toEqual([
  271. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  272. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  273. ])
  274. expect(response.toolCalls).toEqual([])
  275. }),
  276. )
  277. it.effect("fails on malformed stream events", () =>
  278. Effect.gen(function* () {
  279. const body = sseEvents(deltaChunk({ content: 123 }))
  280. const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
  281. expect(error.message).toContain("Invalid openai/openai-chat stream event")
  282. }),
  283. )
  284. it.effect("surfaces transport errors that occur mid-stream", () =>
  285. Effect.gen(function* () {
  286. const layer = truncatedStream([
  287. `data: ${JSON.stringify(deltaChunk({ role: "assistant", content: "Hello" }))}\n\n`,
  288. ])
  289. const error = yield* LLMClient.generate(request).pipe(Effect.provide(layer), Effect.flip)
  290. expect(error.message).toContain("Failed to read openai/openai-chat stream")
  291. }),
  292. )
  293. it.effect("fails HTTP provider errors before stream parsing", () =>
  294. Effect.gen(function* () {
  295. const error = yield* LLMClient.generate(request).pipe(
  296. Effect.provide(
  297. fixedResponse('{"error":{"message":"Bad request","type":"invalid_request_error"}}', {
  298. status: 400,
  299. headers: { "content-type": "application/json" },
  300. }),
  301. ),
  302. Effect.flip,
  303. )
  304. expect(error).toBeInstanceOf(LLMError)
  305. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  306. expect(error.message).toContain("HTTP 400")
  307. }),
  308. )
  309. it.effect("short-circuits the upstream stream when the consumer takes a prefix", () =>
  310. Effect.gen(function* () {
  311. // The body has more chunks than we'll consume. If `Stream.take(1)` did
  312. // not interrupt the upstream HTTP body the test would hang waiting for
  313. // the rest of the stream to drain.
  314. const body = sseEvents(
  315. deltaChunk({ role: "assistant", content: "Hello" }),
  316. deltaChunk({ content: " world" }),
  317. deltaChunk({}, "stop"),
  318. )
  319. const events = Array.from(
  320. yield* LLMClient.stream(request).pipe(Stream.take(1), Stream.runCollect, Effect.provide(fixedResponse(body))),
  321. )
  322. expect(events.map((event) => event.type)).toEqual(["text-delta"])
  323. }),
  324. )
  325. })