openai-chat.test.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671
  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, Message, Model, ToolCallPart, Usage } 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 { ProviderShared } from "../../src/protocols/shared"
  9. import { Auth, LLMClient } from "../../src/route"
  10. import { it } from "../lib/effect"
  11. import { dynamicResponse, fixedResponse, truncatedStream } from "../lib/http"
  12. import { deltaChunk, usageChunk } from "../lib/openai-chunks"
  13. import { sseEvents } from "../lib/sse"
  14. const TargetJson = Schema.fromJsonString(Schema.Unknown)
  15. const encodeJson = Schema.encodeSync(TargetJson)
  16. const decodeJson = Schema.decodeUnknownSync(TargetJson)
  17. const model = OpenAIChat.route
  18. .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") })
  19. .model({ id: "gpt-4o-mini" })
  20. const request = LLM.request({
  21. id: "req_1",
  22. model,
  23. system: "You are concise.",
  24. prompt: "Say hello.",
  25. generation: { maxTokens: 20, temperature: 0 },
  26. })
  27. describe("OpenAI Chat route", () => {
  28. it.effect("prepares OpenAI Chat payload", () =>
  29. Effect.gen(function* () {
  30. // Pass the OpenAIChat payload type so `prepared.body` is statically
  31. // typed to the route's native shape — the assertions below read field
  32. // names without `unknown` casts.
  33. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(request)
  34. const _typed: { readonly model: string; readonly stream: true } = prepared.body
  35. expect(prepared.body).toEqual({
  36. model: "gpt-4o-mini",
  37. messages: [
  38. { role: "system", content: "You are concise." },
  39. { role: "user", content: "Say hello." },
  40. ],
  41. stream: true,
  42. stream_options: { include_usage: true },
  43. max_tokens: 20,
  44. temperature: 0,
  45. })
  46. }),
  47. )
  48. it.effect("lowers chronological system updates to escaped user wrappers in order", () =>
  49. Effect.gen(function* () {
  50. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  51. LLM.request({
  52. model,
  53. messages: [
  54. Message.user("Before."),
  55. Message.system("Treat <admin> & data literally."),
  56. Message.assistant("After."),
  57. ],
  58. }),
  59. )
  60. expect(prepared.body.messages).toEqual([
  61. {
  62. role: "user",
  63. content: "Before.\n<system-update>\nTreat &lt;admin&gt; &amp; data literally.\n</system-update>",
  64. },
  65. { role: "assistant", content: "After." },
  66. ])
  67. }),
  68. )
  69. it.effect("replays canonical reasoning as OpenAI-compatible reasoning_content", () =>
  70. Effect.gen(function* () {
  71. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  72. LLM.request({
  73. model,
  74. messages: [
  75. Message.assistant([
  76. { type: "reasoning", text: "thinking" },
  77. { type: "text", text: "Hello" },
  78. ]),
  79. ],
  80. }),
  81. )
  82. expect(prepared.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_content: "thinking" }])
  83. }),
  84. )
  85. it.effect("maps OpenAI provider options to Chat options", () =>
  86. Effect.gen(function* () {
  87. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  88. LLM.request({
  89. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).chat("gpt-4o-mini"),
  90. prompt: "think",
  91. providerOptions: { openai: { reasoningEffort: "low" } },
  92. }),
  93. )
  94. expect(prepared.body.store).toBe(false)
  95. expect(prepared.body.reasoning_effort).toBe("low")
  96. }),
  97. )
  98. it.effect("adds native query params to the Chat Completions URL", () =>
  99. LLMClient.generate(
  100. LLM.updateRequest(request, {
  101. model: Model.update(model, { route: model.route.with({ endpoint: { query: { "api-version": "v1" } } }) }),
  102. }),
  103. ).pipe(
  104. Effect.provide(
  105. dynamicResponse((input) =>
  106. Effect.gen(function* () {
  107. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  108. expect(web.url).toBe("https://api.openai.test/v1/chat/completions?api-version=v1")
  109. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  110. headers: { "content-type": "text/event-stream" },
  111. })
  112. }),
  113. ),
  114. ),
  115. ),
  116. )
  117. it.effect("uses Azure api-key header for static OpenAI Chat keys", () =>
  118. LLMClient.generate(
  119. LLM.updateRequest(request, {
  120. model: Azure.configure({
  121. baseURL: "https://opencode-test.openai.azure.com/openai/v1/",
  122. apiKey: "azure-key",
  123. headers: { authorization: "Bearer stale" },
  124. }).chat("gpt-4o-mini"),
  125. }),
  126. ).pipe(
  127. Effect.provide(
  128. dynamicResponse((input) =>
  129. Effect.gen(function* () {
  130. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  131. expect(web.url).toBe("https://opencode-test.openai.azure.com/openai/v1/chat/completions?api-version=v1")
  132. expect(web.headers.get("api-key")).toBe("azure-key")
  133. expect(web.headers.get("authorization")).toBeNull()
  134. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  135. headers: { "content-type": "text/event-stream" },
  136. })
  137. }),
  138. ),
  139. ),
  140. ),
  141. )
  142. it.effect("applies serializable HTTP overlays after payload lowering", () =>
  143. LLMClient.generate(
  144. LLM.updateRequest(request, {
  145. model: model.route
  146. .with({ auth: Auth.bearer("fresh-key"), headers: { authorization: "Bearer stale" } })
  147. .model({ id: model.id }),
  148. http: {
  149. body: { metadata: { source: "test" } },
  150. headers: { authorization: "Bearer request", "x-custom": "yes" },
  151. query: { debug: "1" },
  152. },
  153. }),
  154. ).pipe(
  155. Effect.provide(
  156. dynamicResponse((input) =>
  157. Effect.gen(function* () {
  158. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  159. expect(web.url).toBe("https://api.openai.test/v1/chat/completions?debug=1")
  160. expect(web.headers.get("authorization")).toBe("Bearer fresh-key")
  161. expect(web.headers.get("x-custom")).toBe("yes")
  162. expect(decodeJson(input.text)).toMatchObject({
  163. stream: true,
  164. stream_options: { include_usage: true },
  165. metadata: { source: "test" },
  166. })
  167. return input.respond(sseEvents(deltaChunk({}, "stop")), {
  168. headers: { "content-type": "text/event-stream" },
  169. })
  170. }),
  171. ),
  172. ),
  173. ),
  174. )
  175. it.effect("prepares assistant tool-call and tool-result messages", () =>
  176. Effect.gen(function* () {
  177. const prepared = yield* LLMClient.prepare(
  178. LLM.request({
  179. id: "req_tool_result",
  180. model,
  181. messages: [
  182. Message.user("What is the weather?"),
  183. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  184. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  185. ],
  186. }),
  187. )
  188. expect(prepared.body).toEqual({
  189. model: "gpt-4o-mini",
  190. messages: [
  191. { role: "user", content: "What is the weather?" },
  192. {
  193. role: "assistant",
  194. content: null,
  195. tool_calls: [
  196. {
  197. id: "call_1",
  198. type: "function",
  199. function: { name: "lookup", arguments: encodeJson({ query: "weather" }) },
  200. },
  201. ],
  202. },
  203. { role: "tool", tool_call_id: "call_1", content: encodeJson({ forecast: "sunny" }) },
  204. ],
  205. stream: true,
  206. stream_options: { include_usage: true },
  207. })
  208. }),
  209. )
  210. it.effect("preserves structured tool errors for the model", () =>
  211. Effect.gen(function* () {
  212. const error = { error: { type: "unknown", message: "Tool execution interrupted" } }
  213. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  214. LLM.request({
  215. model,
  216. messages: [
  217. Message.assistant([ToolCallPart.make({ id: "call_1", name: "bash", input: {} })]),
  218. Message.tool({ id: "call_1", name: "bash", resultType: "error", result: error }),
  219. ],
  220. }),
  221. )
  222. expect(prepared.body.messages.at(-1)).toEqual({
  223. role: "tool",
  224. tool_call_id: "call_1",
  225. content: ProviderShared.encodeJson(error),
  226. })
  227. }),
  228. )
  229. it.effect("continues image tool results as vision input without base64 text", () =>
  230. Effect.gen(function* () {
  231. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  232. LLM.request({
  233. model,
  234. messages: [
  235. Message.assistant([ToolCallPart.make({ id: "call_image", name: "read", input: { path: "pixel.png" } })]),
  236. Message.tool({
  237. id: "call_image",
  238. name: "read",
  239. result: {
  240. type: "content",
  241. value: [
  242. { type: "text", text: "Image read successfully" },
  243. { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png", name: "pixel.png" },
  244. ],
  245. },
  246. }),
  247. ],
  248. }),
  249. )
  250. expect(prepared.body.messages).toEqual([
  251. {
  252. role: "assistant",
  253. content: null,
  254. tool_calls: [
  255. {
  256. id: "call_image",
  257. type: "function",
  258. function: { name: "read", arguments: encodeJson({ path: "pixel.png" }) },
  259. },
  260. ],
  261. },
  262. { role: "tool", tool_call_id: "call_image", content: "Image read successfully" },
  263. {
  264. role: "user",
  265. content: [{ type: "image_url", image_url: { url: "data:image/png;base64,AAECAw==" } }],
  266. },
  267. ])
  268. expect(JSON.stringify(prepared.body.messages)).not.toContain('"content":"AAECAw=="')
  269. }),
  270. )
  271. it.effect("orders parallel tool responses before one aggregated vision message", () =>
  272. Effect.gen(function* () {
  273. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  274. LLM.request({
  275. model,
  276. messages: [
  277. Message.assistant([
  278. ToolCallPart.make({ id: "call_1", name: "read", input: {} }),
  279. ToolCallPart.make({ id: "call_2", name: "read", input: {} }),
  280. ]),
  281. Message.make({
  282. role: "tool",
  283. content: [
  284. {
  285. type: "tool-result",
  286. id: "call_1",
  287. name: "read",
  288. result: {
  289. type: "content",
  290. value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
  291. },
  292. },
  293. {
  294. type: "tool-result",
  295. id: "call_2",
  296. name: "read",
  297. result: {
  298. type: "content",
  299. value: [{ type: "file", uri: "data:image/jpeg;base64,/9j/", mime: "image/jpeg" }],
  300. },
  301. },
  302. ],
  303. }),
  304. ],
  305. }),
  306. )
  307. expect(prepared.body.messages.slice(1)).toEqual([
  308. { role: "tool", tool_call_id: "call_1", content: "" },
  309. { role: "tool", tool_call_id: "call_2", content: "" },
  310. {
  311. role: "user",
  312. content: [
  313. { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
  314. { type: "image_url", image_url: { url: "data:image/jpeg;base64,/9j/" } },
  315. ],
  316. },
  317. ])
  318. }),
  319. )
  320. it.effect("aggregates consecutive tool images with a following system update", () =>
  321. Effect.gen(function* () {
  322. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  323. LLM.request({
  324. model,
  325. messages: [
  326. Message.tool({
  327. id: "call_1",
  328. name: "read",
  329. result: {
  330. type: "content",
  331. value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
  332. },
  333. }),
  334. Message.tool({
  335. id: "call_2",
  336. name: "read",
  337. result: {
  338. type: "content",
  339. value: [{ type: "file", uri: "data:image/webp;base64,UklG", mime: "image/webp" }],
  340. },
  341. }),
  342. Message.system("Inspect both images."),
  343. ],
  344. }),
  345. )
  346. expect(prepared.body.messages).toEqual([
  347. { role: "tool", tool_call_id: "call_1", content: "" },
  348. { role: "tool", tool_call_id: "call_2", content: "" },
  349. {
  350. role: "user",
  351. content: [
  352. { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
  353. { type: "image_url", image_url: { url: "data:image/webp;base64,UklG" } },
  354. { type: "text", text: "<system-update>\nInspect both images.\n</system-update>" },
  355. ],
  356. },
  357. ])
  358. }),
  359. )
  360. it.effect("appends system updates without replacing multipart user content", () =>
  361. Effect.gen(function* () {
  362. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  363. LLM.request({
  364. model,
  365. messages: [
  366. Message.user({ type: "media", mediaType: "image/png", data: "AAEC" }),
  367. Message.system("Keep the image."),
  368. ],
  369. }),
  370. )
  371. expect(prepared.body.messages).toEqual([
  372. {
  373. role: "user",
  374. content: [
  375. { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
  376. { type: "text", text: "<system-update>\nKeep the image.\n</system-update>" },
  377. ],
  378. },
  379. ])
  380. }),
  381. )
  382. for (const [name, media] of [
  383. ["mismatched data URL MIME", { mediaType: "image/png", data: "data:image/jpeg;base64,/9j/" }],
  384. ["malformed base64", { mediaType: "image/png", data: "not-base64" }],
  385. ["unsupported SVG", { mediaType: "image/svg+xml", data: "PHN2Zz4=" }],
  386. ] as const)
  387. it.effect(`rejects ${name}`, () =>
  388. Effect.gen(function* () {
  389. const error = yield* LLMClient.prepare(
  390. LLM.request({ model, messages: [Message.user({ type: "media", ...media })] }),
  391. ).pipe(Effect.flip)
  392. expect(error.message).toMatch(/does not support|does not match|valid base64/)
  393. }),
  394. )
  395. it.effect("rejects oversized image input", () =>
  396. Effect.gen(function* () {
  397. const error = yield* LLMClient.prepare(
  398. LLM.request({
  399. model,
  400. messages: [
  401. Message.user({
  402. type: "media",
  403. mediaType: "image/png",
  404. data: "A".repeat(ProviderShared.MAX_MEDIA_ENCODED_BYTES + 4),
  405. }),
  406. ],
  407. }),
  408. ).pipe(Effect.flip)
  409. expect(error.message).toContain("encoded limit")
  410. }),
  411. )
  412. it.effect("prepares raw and data URL image media as vision input", () =>
  413. Effect.gen(function* () {
  414. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  415. LLM.request({
  416. id: "req_media",
  417. model,
  418. messages: [
  419. Message.user([
  420. { type: "media", mediaType: "image/png", data: "AAECAw==" },
  421. { type: "media", mediaType: "image/jpeg", data: "data:image/jpeg;base64,/9j/" },
  422. ]),
  423. ],
  424. }),
  425. )
  426. expect(prepared.body.messages).toEqual([
  427. {
  428. role: "user",
  429. content: [
  430. { type: "image_url", image_url: { url: "data:image/png;base64,AAECAw==" } },
  431. { type: "image_url", image_url: { url: "data:image/jpeg;base64,/9j/" } },
  432. ],
  433. },
  434. ])
  435. }),
  436. )
  437. it.effect("lowers reasoning-only assistant history", () =>
  438. Effect.gen(function* () {
  439. const prepared = yield* LLMClient.prepare<OpenAIChat.OpenAIChatBody>(
  440. LLM.request({
  441. id: "req_reasoning",
  442. model,
  443. messages: [Message.assistant({ type: "reasoning", text: "hidden" })],
  444. }),
  445. )
  446. expect(prepared.body.messages).toEqual([{ role: "assistant", content: null, reasoning_content: "hidden" }])
  447. }),
  448. )
  449. it.effect("parses text and usage stream fixtures", () =>
  450. Effect.gen(function* () {
  451. const body = sseEvents(
  452. deltaChunk({ role: "assistant", content: "Hello" }),
  453. deltaChunk({ content: "!" }),
  454. deltaChunk({}, "stop"),
  455. usageChunk({
  456. prompt_tokens: 5,
  457. completion_tokens: 2,
  458. total_tokens: 7,
  459. prompt_tokens_details: { cached_tokens: 1 },
  460. completion_tokens_details: { reasoning_tokens: 0 },
  461. }),
  462. )
  463. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  464. const usage = new Usage({
  465. inputTokens: 5,
  466. outputTokens: 2,
  467. nonCachedInputTokens: 4,
  468. cacheReadInputTokens: 1,
  469. reasoningTokens: 0,
  470. totalTokens: 7,
  471. providerMetadata: {
  472. openai: {
  473. prompt_tokens: 5,
  474. completion_tokens: 2,
  475. total_tokens: 7,
  476. prompt_tokens_details: { cached_tokens: 1 },
  477. completion_tokens_details: { reasoning_tokens: 0 },
  478. },
  479. },
  480. })
  481. expect(response.text).toBe("Hello!")
  482. expect(response.events).toEqual([
  483. { type: "step-start", index: 0 },
  484. { type: "text-start", id: "text-0" },
  485. { type: "text-delta", id: "text-0", text: "Hello" },
  486. { type: "text-delta", id: "text-0", text: "!" },
  487. { type: "text-end", id: "text-0" },
  488. { type: "step-finish", index: 0, reason: "stop", usage, providerMetadata: undefined },
  489. {
  490. type: "finish",
  491. reason: "stop",
  492. usage,
  493. },
  494. ])
  495. }),
  496. )
  497. it.effect("parses OpenAI-compatible reasoning content deltas", () =>
  498. Effect.gen(function* () {
  499. const body = sseEvents(
  500. { choices: [{ delta: { reasoning_content: "thinking" } }] },
  501. { choices: [{ delta: { content: "Hello" } }] },
  502. { choices: [{ delta: {}, finish_reason: "stop" }] },
  503. )
  504. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  505. expect(response.reasoning).toBe("thinking")
  506. expect(response.text).toBe("Hello")
  507. expect(response.events).toMatchObject([
  508. { type: "step-start", index: 0 },
  509. { type: "reasoning-start", id: "reasoning-0" },
  510. { type: "reasoning-delta", id: "reasoning-0", text: "thinking" },
  511. { type: "text-start", id: "text-0" },
  512. { type: "text-delta", id: "text-0", text: "Hello" },
  513. { type: "reasoning-end", id: "reasoning-0" },
  514. { type: "text-end", id: "text-0" },
  515. { type: "step-finish", index: 0, reason: "stop" },
  516. { type: "finish", reason: "stop" },
  517. ])
  518. }),
  519. )
  520. it.effect("assembles streamed tool call input", () =>
  521. Effect.gen(function* () {
  522. const body = sseEvents(
  523. deltaChunk({
  524. role: "assistant",
  525. tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
  526. }),
  527. deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
  528. deltaChunk({}, "tool_calls"),
  529. )
  530. const response = yield* LLMClient.generate(
  531. LLM.updateRequest(request, {
  532. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  533. }),
  534. ).pipe(Effect.provide(fixedResponse(body)))
  535. expect(response.events).toEqual([
  536. { type: "step-start", index: 0 },
  537. { type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
  538. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  539. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  540. { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
  541. {
  542. type: "tool-call",
  543. id: "call_1",
  544. name: "lookup",
  545. input: { query: "weather" },
  546. providerExecuted: undefined,
  547. providerMetadata: undefined,
  548. },
  549. { type: "step-finish", index: 0, reason: "tool-calls", usage: undefined, providerMetadata: undefined },
  550. { type: "finish", reason: "tool-calls", usage: undefined },
  551. ])
  552. }),
  553. )
  554. it.effect("does not finalize streamed tool calls without a finish reason", () =>
  555. Effect.gen(function* () {
  556. const body = sseEvents(
  557. deltaChunk({
  558. role: "assistant",
  559. tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
  560. }),
  561. deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
  562. )
  563. const response = yield* LLMClient.generate(
  564. LLM.updateRequest(request, {
  565. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  566. }),
  567. ).pipe(Effect.provide(fixedResponse(body)))
  568. expect(response.events).toEqual([
  569. { type: "step-start", index: 0 },
  570. { type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
  571. { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
  572. { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
  573. ])
  574. expect(response.toolCalls).toEqual([])
  575. }),
  576. )
  577. it.effect("fails on malformed stream events", () =>
  578. Effect.gen(function* () {
  579. const body = sseEvents(deltaChunk({ content: 123 }))
  580. const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
  581. expect(error.message).toContain("Invalid openai/openai-chat stream event")
  582. }),
  583. )
  584. it.effect("surfaces transport errors that occur mid-stream", () =>
  585. Effect.gen(function* () {
  586. const layer = truncatedStream([
  587. `data: ${JSON.stringify(deltaChunk({ role: "assistant", content: "Hello" }))}\n\n`,
  588. ])
  589. const error = yield* LLMClient.generate(request).pipe(Effect.provide(layer), Effect.flip)
  590. expect(error.message).toContain("Failed to read openai/openai-chat stream")
  591. }),
  592. )
  593. it.effect("fails HTTP provider errors before stream parsing", () =>
  594. Effect.gen(function* () {
  595. const error = yield* LLMClient.generate(request).pipe(
  596. Effect.provide(
  597. fixedResponse('{"error":{"message":"Bad request","type":"invalid_request_error"}}', {
  598. status: 400,
  599. headers: { "content-type": "application/json" },
  600. }),
  601. ),
  602. Effect.flip,
  603. )
  604. expect(error).toBeInstanceOf(LLMError)
  605. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  606. expect(error.message).toContain("HTTP 400")
  607. }),
  608. )
  609. it.effect("short-circuits the upstream stream when the consumer takes a prefix", () =>
  610. Effect.gen(function* () {
  611. // The body has more chunks than we'll consume. If `Stream.take(1)` did
  612. // not interrupt the upstream HTTP body the test would hang waiting for
  613. // the rest of the stream to drain.
  614. const body = sseEvents(
  615. deltaChunk({ role: "assistant", content: "Hello" }),
  616. deltaChunk({ content: " world" }),
  617. deltaChunk({}, "stop"),
  618. )
  619. const events = Array.from(
  620. yield* LLMClient.stream(request).pipe(Stream.take(1), Stream.runCollect, Effect.provide(fixedResponse(body))),
  621. )
  622. expect(events.map((event) => event.type)).toEqual(["step-start"])
  623. }),
  624. )
  625. })