openai-responses.test.ts 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472
  1. import { describe, expect } from "bun:test"
  2. import { ConfigProvider, Effect, Layer, Stream } from "effect"
  3. import { Headers, HttpClientRequest } from "effect/unstable/http"
  4. import { LLM, LLMError, Message, Model, ToolCallPart, Usage } from "../../src"
  5. import { Auth, LLMClient, RequestExecutor, WebSocketExecutor } from "../../src/route"
  6. import * as Azure from "../../src/providers/azure"
  7. import * as OpenAI from "../../src/providers/openai"
  8. import * as OpenAIResponses from "../../src/protocols/openai-responses"
  9. import * as ProviderShared from "../../src/protocols/shared"
  10. import { continuationRequest, nativeOpenAIResponsesContinuation } from "../continuation-scenarios"
  11. import { it } from "../lib/effect"
  12. import { dynamicResponse, fixedResponse } from "../lib/http"
  13. import { sseEvents } from "../lib/sse"
  14. const model = OpenAIResponses.route
  15. .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") })
  16. .model({ id: "gpt-4.1-mini" })
  17. const request = LLM.request({
  18. id: "req_1",
  19. model,
  20. system: "You are concise.",
  21. prompt: "Say hello.",
  22. generation: { maxTokens: 20, temperature: 0 },
  23. })
  24. const configEnv = (env: Record<string, string>) => Effect.provide(ConfigProvider.layer(ConfigProvider.fromEnv({ env })))
  25. type OpenAIToolOutput = Extract<
  26. OpenAIResponses.OpenAIResponsesBody["input"][number],
  27. { readonly type: "function_call_output" }
  28. >
  29. const expectToolOutput = (body: OpenAIResponses.OpenAIResponsesBody): OpenAIToolOutput => {
  30. const output = body.input.find(
  31. (item): item is OpenAIToolOutput => "type" in item && item.type === "function_call_output",
  32. )
  33. expect(output).toBeDefined()
  34. return output!
  35. }
  36. describe("OpenAI Responses route", () => {
  37. it.effect("prepares OpenAI Responses target", () =>
  38. Effect.gen(function* () {
  39. const prepared = yield* LLMClient.prepare(request)
  40. expect(prepared.body).toEqual({
  41. model: "gpt-4.1-mini",
  42. input: [
  43. { role: "system", content: "You are concise." },
  44. { role: "user", content: [{ type: "input_text", text: "Say hello." }] },
  45. ],
  46. store: false,
  47. stream: true,
  48. max_output_tokens: 20,
  49. temperature: 0,
  50. })
  51. }),
  52. )
  53. it.effect("lowers semantic service tier options", () =>
  54. Effect.gen(function* () {
  55. const input = LLM.updateRequest(request, { providerOptions: { openai: { serviceTier: "priority" } } })
  56. expect(input.providerOptions).toEqual({ openai: { serviceTier: "priority" } })
  57. const prepared = yield* LLMClient.prepare(input)
  58. expect(prepared.body).toMatchObject({ service_tier: "priority" })
  59. expect(prepared.body).not.toHaveProperty("serviceTier")
  60. }),
  61. )
  62. it.effect("omits unsupported semantic service tiers", () =>
  63. Effect.gen(function* () {
  64. const prepared = yield* LLMClient.prepare(
  65. LLM.updateRequest(request, { providerOptions: { openai: { serviceTier: "unsupported" } } }),
  66. )
  67. expect(prepared.body).not.toHaveProperty("service_tier")
  68. }),
  69. )
  70. it.effect("flattens top-level object unions in function schemas", () =>
  71. Effect.gen(function* () {
  72. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  73. LLM.updateRequest(request, {
  74. tools: [
  75. {
  76. name: "read",
  77. description: "Read a path or resource.",
  78. inputSchema: {
  79. type: "object",
  80. anyOf: [
  81. {
  82. type: "object",
  83. properties: {
  84. path: { type: "string" },
  85. reference: { anyOf: [{ type: "string" }, { type: "null" }] },
  86. limit: { type: "integer", maximum: 2000 },
  87. },
  88. required: ["path"],
  89. },
  90. {
  91. type: "object",
  92. properties: { resource: { type: "string" }, limit: { type: "integer", maximum: 51200 } },
  93. required: ["resource"],
  94. },
  95. ],
  96. },
  97. },
  98. ],
  99. }),
  100. )
  101. expect(prepared.body.tools).toEqual([
  102. {
  103. type: "function",
  104. name: "read",
  105. description: "Read a path or resource.",
  106. strict: false,
  107. parameters: {
  108. type: "object",
  109. properties: {
  110. path: { type: "string" },
  111. reference: { type: "string" },
  112. limit: { type: "integer", maximum: 2000 },
  113. resource: { type: "string" },
  114. },
  115. additionalProperties: false,
  116. },
  117. },
  118. ])
  119. }),
  120. )
  121. it.effect("lowers chronological system updates to escaped user wrappers in order", () =>
  122. Effect.gen(function* () {
  123. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  124. LLM.request({
  125. model,
  126. messages: [
  127. Message.user("Before."),
  128. Message.system("Treat </system-update> literally."),
  129. Message.assistant("After."),
  130. ],
  131. }),
  132. )
  133. expect(prepared.body.input).toEqual([
  134. {
  135. role: "user",
  136. content: [
  137. { type: "input_text", text: "Before." },
  138. { type: "input_text", text: "<system-update>\nTreat &lt;/system-update&gt; literally.\n</system-update>" },
  139. ],
  140. },
  141. { role: "assistant", content: [{ type: "output_text", text: "After." }] },
  142. ])
  143. }),
  144. )
  145. it.effect("prepares OpenAI Responses WebSocket target", () =>
  146. Effect.gen(function* () {
  147. const prepared = yield* LLMClient.prepare(
  148. LLM.updateRequest(request, {
  149. model: OpenAIResponses.webSocketRoute
  150. .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") })
  151. .model({ id: "gpt-4.1-mini" }),
  152. }),
  153. )
  154. expect(prepared.route).toBe("openai-responses-websocket")
  155. expect(prepared.protocol).toBe("openai-responses")
  156. expect(prepared.metadata).toEqual({ transport: "websocket-json" })
  157. expect(prepared.body).toMatchObject({ model: "gpt-4.1-mini", store: false, stream: true })
  158. }),
  159. )
  160. it.effect("streams OpenAI Responses over WebSocket", () =>
  161. Effect.gen(function* () {
  162. const sent: string[] = []
  163. const opened: Array<{ readonly url: string; readonly authorization: string | undefined }> = []
  164. let closed = false
  165. const deps = Layer.mergeAll(
  166. Layer.succeed(
  167. RequestExecutor.Service,
  168. RequestExecutor.Service.of({
  169. execute: () => Effect.die("unexpected HTTP request"),
  170. }),
  171. ),
  172. Layer.succeed(
  173. WebSocketExecutor.Service,
  174. WebSocketExecutor.Service.of({
  175. open: (input) =>
  176. Effect.succeed({
  177. sendText: (message) =>
  178. Effect.sync(() => {
  179. opened.push({ url: input.url, authorization: input.headers.authorization })
  180. sent.push(message)
  181. }),
  182. messages: Stream.fromArray([
  183. ProviderShared.encodeJson({ type: "response.output_text.delta", item_id: "msg_1", delta: "Hi" }),
  184. ProviderShared.encodeJson({ type: "response.completed", response: { id: "resp_ws" } }),
  185. ]),
  186. close: Effect.sync(() => {
  187. closed = true
  188. }),
  189. }),
  190. }),
  191. ),
  192. )
  193. const response = yield* LLMClient.generate(
  194. LLM.request({
  195. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).responsesWebSocket(
  196. "gpt-4.1-mini",
  197. ),
  198. prompt: "Say hello.",
  199. }),
  200. ).pipe(Effect.provide(LLMClient.layer.pipe(Layer.provide(deps))))
  201. expect(response.text).toBe("Hi")
  202. expect(opened).toEqual([{ url: "wss://api.openai.test/v1/responses", authorization: "Bearer test" }])
  203. expect(closed).toBe(true)
  204. expect(sent).toHaveLength(1)
  205. expect(JSON.parse(sent[0])).toEqual({
  206. type: "response.create",
  207. model: "gpt-4.1-mini",
  208. input: [{ role: "user", content: [{ type: "input_text", text: "Say hello." }] }],
  209. store: false,
  210. })
  211. }),
  212. )
  213. it.effect("fails immediately when WebSocket is already closed", () =>
  214. Effect.gen(function* () {
  215. const error = yield* WebSocketExecutor.fromWebSocket(
  216. // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- fromWebSocket reads readyState before touching WebSocket methods on this branch.
  217. { readyState: globalThis.WebSocket.CLOSED } as globalThis.WebSocket,
  218. { url: "wss://api.openai.test/v1/responses", headers: Headers.empty },
  219. ).pipe(Effect.flip)
  220. expect(error.message).toContain("closed before opening")
  221. }),
  222. )
  223. it.effect("adds native query params to the Responses URL", () =>
  224. Effect.gen(function* () {
  225. yield* LLMClient.generate(
  226. LLM.updateRequest(request, {
  227. model: Model.update(model, { route: model.route.with({ endpoint: { query: { "api-version": "v1" } } }) }),
  228. }),
  229. ).pipe(
  230. Effect.provide(
  231. dynamicResponse((input) =>
  232. Effect.gen(function* () {
  233. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  234. expect(web.url).toBe("https://api.openai.test/v1/responses?api-version=v1")
  235. return input.respond(sseEvents({ type: "response.completed", response: {} }), {
  236. headers: { "content-type": "text/event-stream" },
  237. })
  238. }),
  239. ),
  240. ),
  241. )
  242. }),
  243. )
  244. it.effect("uses Azure api-key header for static OpenAI Responses keys", () =>
  245. Effect.gen(function* () {
  246. yield* LLMClient.generate(
  247. LLM.updateRequest(request, {
  248. model: Azure.configure({
  249. baseURL: "https://opencode-test.openai.azure.com/openai/v1/",
  250. apiKey: "azure-key",
  251. headers: { authorization: "Bearer stale" },
  252. }).responses("gpt-4.1-mini"),
  253. }),
  254. ).pipe(
  255. Effect.provide(
  256. dynamicResponse((input) =>
  257. Effect.gen(function* () {
  258. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  259. expect(web.url).toBe("https://opencode-test.openai.azure.com/openai/v1/responses?api-version=v1")
  260. expect(web.headers.get("api-key")).toBe("azure-key")
  261. expect(web.headers.get("authorization")).toBeNull()
  262. return input.respond(sseEvents({ type: "response.completed", response: {} }), {
  263. headers: { "content-type": "text/event-stream" },
  264. })
  265. }),
  266. ),
  267. ),
  268. )
  269. }),
  270. )
  271. it.effect("loads OpenAI default auth from Effect Config", () =>
  272. LLMClient.generate(
  273. LLM.updateRequest(request, {
  274. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/" }).responses("gpt-4.1-mini"),
  275. }),
  276. ).pipe(
  277. configEnv({ OPENAI_API_KEY: "env-key" }),
  278. Effect.provide(
  279. dynamicResponse((input) =>
  280. Effect.gen(function* () {
  281. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  282. expect(web.headers.get("authorization")).toBe("Bearer env-key")
  283. return input.respond(sseEvents({ type: "response.completed", response: {} }), {
  284. headers: { "content-type": "text/event-stream" },
  285. })
  286. }),
  287. ),
  288. ),
  289. ),
  290. )
  291. it.effect("lets explicit auth override OpenAI default API key auth", () =>
  292. LLMClient.generate(
  293. LLM.updateRequest(request, {
  294. model: OpenAI.configure({
  295. baseURL: "https://api.openai.test/v1/",
  296. auth: Auth.bearer("oauth-token"),
  297. }).responses("gpt-4.1-mini"),
  298. }),
  299. ).pipe(
  300. Effect.provide(
  301. dynamicResponse((input) =>
  302. Effect.gen(function* () {
  303. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  304. expect(web.headers.get("authorization")).toBe("Bearer oauth-token")
  305. return input.respond(sseEvents({ type: "response.completed", response: {} }), {
  306. headers: { "content-type": "text/event-stream" },
  307. })
  308. }),
  309. ),
  310. ),
  311. ),
  312. )
  313. it.effect("prepares function call and function output input items", () =>
  314. Effect.gen(function* () {
  315. const prepared = yield* LLMClient.prepare(
  316. LLM.request({
  317. id: "req_tool_result",
  318. model,
  319. messages: [
  320. Message.user("What is the weather?"),
  321. Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
  322. Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
  323. ],
  324. }),
  325. )
  326. expect(prepared.body).toEqual({
  327. model: "gpt-4.1-mini",
  328. input: [
  329. { role: "user", content: [{ type: "input_text", text: "What is the weather?" }] },
  330. { type: "function_call", call_id: "call_1", name: "lookup", arguments: '{"query":"weather"}' },
  331. { type: "function_call_output", call_id: "call_1", output: '{"forecast":"sunny"}' },
  332. ],
  333. store: false,
  334. stream: true,
  335. max_output_tokens: undefined,
  336. temperature: undefined,
  337. tool_choice: undefined,
  338. tools: undefined,
  339. top_p: undefined,
  340. })
  341. }),
  342. )
  343. it.effect("preserves structured tool errors for the model", () =>
  344. Effect.gen(function* () {
  345. const error = {
  346. error: { type: "unknown", message: "Tool execution interrupted" },
  347. content: [],
  348. structured: {},
  349. }
  350. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  351. LLM.request({
  352. model,
  353. messages: [
  354. Message.assistant([ToolCallPart.make({ id: "call_1", name: "bash", input: { command: "sleep 10" } })]),
  355. Message.tool({
  356. id: "call_1",
  357. name: "bash",
  358. resultType: "error",
  359. result: error,
  360. }),
  361. ],
  362. }),
  363. )
  364. expect(expectToolOutput(prepared.body).output).toBe(ProviderShared.encodeJson(error))
  365. }),
  366. )
  367. it.effect("keeps primitive tool errors as plain text", () =>
  368. Effect.gen(function* () {
  369. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  370. LLM.request({
  371. model,
  372. messages: [
  373. Message.assistant([ToolCallPart.make({ id: "call_1", name: "bash", input: {} })]),
  374. Message.tool({ id: "call_1", name: "bash", resultType: "error", result: 503 }),
  375. ],
  376. }),
  377. )
  378. expect(expectToolOutput(prepared.body).output).toBe("503")
  379. }),
  380. )
  381. it.effect("keeps non-JSON tool errors as plain text", () =>
  382. Effect.gen(function* () {
  383. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  384. LLM.request({
  385. model,
  386. messages: [
  387. Message.assistant([ToolCallPart.make({ id: "call_1", name: "bash", input: {} })]),
  388. Message.tool({ id: "call_1", name: "bash", resultType: "error", result: new Error("boom") }),
  389. ],
  390. }),
  391. )
  392. expect(expectToolOutput(prepared.body).output).toBe("Error: boom")
  393. }),
  394. )
  395. // Regression: screenshot/read tool results must stay structured so base64
  396. // image data is not JSON-stringified into `function_call_output.output`.
  397. it.effect("lowers image tool-result content as structured input_image items", () =>
  398. Effect.gen(function* () {
  399. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  400. LLM.request({
  401. id: "req_tool_result_image",
  402. model,
  403. messages: [
  404. Message.user("Show me the screenshot."),
  405. Message.assistant([ToolCallPart.make({ id: "call_1", name: "read", input: { filePath: "shot.png" } })]),
  406. Message.tool({
  407. id: "call_1",
  408. name: "read",
  409. resultType: "content",
  410. result: [
  411. { type: "text", text: "Image read successfully" },
  412. { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png" },
  413. ],
  414. }),
  415. ],
  416. }),
  417. )
  418. expect(expectToolOutput(prepared.body).output).toEqual([
  419. { type: "input_text", text: "Image read successfully" },
  420. { type: "input_image", image_url: "data:image/png;base64,AAECAw==" },
  421. ])
  422. }),
  423. )
  424. it.effect("lowers single-image tool-result content as structured input_image array", () =>
  425. Effect.gen(function* () {
  426. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  427. LLM.request({
  428. id: "req_tool_result_image_only",
  429. model,
  430. messages: [
  431. Message.assistant([ToolCallPart.make({ id: "call_1", name: "screenshot", input: {} })]),
  432. Message.tool({
  433. id: "call_1",
  434. name: "screenshot",
  435. resultType: "content",
  436. result: [{ type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png" }],
  437. }),
  438. ],
  439. }),
  440. )
  441. expect(expectToolOutput(prepared.body).output).toEqual([
  442. { type: "input_image", image_url: "data:image/png;base64,AAECAw==" },
  443. ])
  444. }),
  445. )
  446. it.effect("rejects non-image media in tool-result content with a clear error", () =>
  447. Effect.gen(function* () {
  448. const error = yield* LLMClient.prepare(
  449. LLM.request({
  450. id: "req_tool_result_unsupported_media",
  451. model,
  452. messages: [
  453. Message.assistant([ToolCallPart.make({ id: "call_1", name: "fetch", input: {} })]),
  454. Message.tool({
  455. id: "call_1",
  456. name: "fetch",
  457. resultType: "content",
  458. result: [{ type: "file", uri: "data:audio/mpeg;base64,AAECAw==", mime: "audio/mpeg" }],
  459. }),
  460. ],
  461. }),
  462. ).pipe(Effect.flip)
  463. expect(error.message).toContain("OpenAI Responses")
  464. expect(error.message).toContain("audio/mpeg")
  465. }),
  466. )
  467. it.effect("prepares the composed native continuation request", () =>
  468. Effect.gen(function* () {
  469. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  470. continuationRequest({
  471. id: "req_native_continuation_openai",
  472. model,
  473. features: nativeOpenAIResponsesContinuation,
  474. }),
  475. )
  476. expect(prepared.body).toMatchObject({
  477. input: [
  478. { role: "system", content: "You are concise. Continue from the provided history." },
  479. {
  480. role: "user",
  481. content: [
  482. { type: "input_text", text: "What is shown here?" },
  483. { type: "input_image", image_url: "data:image/png;base64,AAECAw==" },
  484. ],
  485. },
  486. {
  487. type: "reasoning",
  488. encrypted_content: "encrypted-continuation-state",
  489. summary: [{ type: "summary_text", text: "I inspected the previous turn." }],
  490. },
  491. { role: "assistant", content: [{ type: "output_text", text: "It shows a small test image." }] },
  492. { role: "user", content: [{ type: "input_text", text: "Check the weather in Paris before continuing." }] },
  493. { type: "function_call", call_id: "call_weather_1", name: "get_weather", arguments: '{"city":"Paris"}' },
  494. { type: "function_call_output", call_id: "call_weather_1", output: '{"temperature":22}' },
  495. { role: "assistant", content: [{ type: "output_text", text: "Paris is 22 degrees." }] },
  496. {
  497. role: "user",
  498. content: [{ type: "input_text", text: "Continue from this conversation in one short sentence." }],
  499. },
  500. ],
  501. include: ["reasoning.encrypted_content"],
  502. store: false,
  503. })
  504. expect(prepared.body.tools).toEqual([expect.objectContaining({ type: "function", name: "get_weather" })])
  505. }),
  506. )
  507. it.effect("maps OpenAI provider options to Responses options", () =>
  508. Effect.gen(function* () {
  509. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  510. LLM.request({
  511. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).model("gpt-5.2"),
  512. prompt: "think",
  513. providerOptions: {
  514. openai: {
  515. promptCacheKey: "session_123",
  516. reasoningEffort: "high",
  517. reasoningSummary: "auto",
  518. include: ["reasoning.encrypted_content"],
  519. },
  520. },
  521. }),
  522. )
  523. expect(prepared.body.store).toBe(false)
  524. expect(prepared.body.prompt_cache_key).toBe("session_123")
  525. expect(prepared.body.include).toEqual(["reasoning.encrypted_content"])
  526. expect(prepared.body.reasoning).toEqual({ effort: "high", summary: "auto" })
  527. expect(prepared.body.text).toEqual({ verbosity: "low" })
  528. }),
  529. )
  530. it.effect("accepts the full ResponseIncludable union", () =>
  531. Effect.gen(function* () {
  532. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  533. LLM.request({
  534. model,
  535. prompt: "hi",
  536. providerOptions: {
  537. openai: {
  538. include: ["reasoning.encrypted_content", "code_interpreter_call.outputs", "web_search_call.results"],
  539. },
  540. },
  541. }),
  542. )
  543. expect(prepared.body.include).toEqual([
  544. "reasoning.encrypted_content",
  545. "code_interpreter_call.outputs",
  546. "web_search_call.results",
  547. ])
  548. }),
  549. )
  550. it.effect("filters unknown includable values out of the include array", () =>
  551. Effect.gen(function* () {
  552. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  553. LLM.request({
  554. model,
  555. prompt: "hi",
  556. // The user passed one invalid entry alongside a valid one. Keep the
  557. // valid one so the request still succeeds rather than failing on a
  558. // typo from upstream config.
  559. providerOptions: { openai: { include: ["reasoning.encrypted_content", "bogus.thing"] } },
  560. }),
  561. )
  562. expect(prepared.body.include).toEqual(["reasoning.encrypted_content"])
  563. }),
  564. )
  565. it.effect("treats an explicit empty include as no include at all", () =>
  566. Effect.gen(function* () {
  567. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  568. LLM.request({ model, prompt: "hi", providerOptions: { openai: { include: [] } } }),
  569. )
  570. expect(prepared.body.include).toBeUndefined()
  571. }),
  572. )
  573. it.effect("treats an all-invalid include as no include at all", () =>
  574. Effect.gen(function* () {
  575. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  576. LLM.request({ model, prompt: "hi", providerOptions: { openai: { include: ["bogus.thing"] } } }),
  577. )
  578. expect(prepared.body.include).toBeUndefined()
  579. }),
  580. )
  581. it.effect("omits include when no include is set", () =>
  582. Effect.gen(function* () {
  583. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  584. LLM.request({ model, prompt: "hi", providerOptions: { openai: { store: false } } }),
  585. )
  586. expect(prepared.body.include).toBeUndefined()
  587. }),
  588. )
  589. it.effect("requests encrypted reasoning by default for GPT-5 reasoning models", () =>
  590. Effect.gen(function* () {
  591. // The native OpenAI facade configures GPT-5 stateless (store: false) with
  592. // reasoningSummary: "auto" by default. Without `include`, a follow-up
  593. // turn cannot replay reasoning state, so the facade also opts into
  594. // `reasoning.encrypted_content` automatically.
  595. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  596. LLM.request({
  597. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).responses("gpt-5.2"),
  598. prompt: "hi",
  599. }),
  600. )
  601. expect(prepared.body.store).toBe(false)
  602. expect(prepared.body.include).toEqual(["reasoning.encrypted_content"])
  603. expect(prepared.body.reasoning).toEqual({ effort: "medium", summary: "auto" })
  604. }),
  605. )
  606. it.effect("lets callers opt out of the GPT-5 default include", () =>
  607. Effect.gen(function* () {
  608. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  609. LLM.request({
  610. model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).responses("gpt-5.2"),
  611. prompt: "hi",
  612. providerOptions: { openai: { include: [] } },
  613. }),
  614. )
  615. expect(prepared.body.include).toBeUndefined()
  616. }),
  617. )
  618. it.effect("request OpenAI provider options override route defaults", () =>
  619. Effect.gen(function* () {
  620. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  621. LLM.request({
  622. model: OpenAI.configure({
  623. baseURL: "https://api.openai.test/v1/",
  624. apiKey: "test",
  625. providerOptions: { openai: { promptCacheKey: "model_cache" } },
  626. }).model("gpt-4.1-mini"),
  627. prompt: "no cache",
  628. providerOptions: { openai: { promptCacheKey: "request_cache" } },
  629. }),
  630. )
  631. expect(prepared.body.prompt_cache_key).toBe("request_cache")
  632. }),
  633. )
  634. it.effect("parses text and usage stream fixtures", () =>
  635. Effect.gen(function* () {
  636. const body = sseEvents(
  637. { type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
  638. { type: "response.output_text.delta", item_id: "msg_1", delta: "!" },
  639. {
  640. type: "response.completed",
  641. response: {
  642. id: "resp_1",
  643. service_tier: "default",
  644. usage: {
  645. input_tokens: 5,
  646. output_tokens: 2,
  647. total_tokens: 7,
  648. input_tokens_details: { cached_tokens: 1 },
  649. output_tokens_details: { reasoning_tokens: 0 },
  650. },
  651. },
  652. },
  653. )
  654. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  655. const usage = new Usage({
  656. inputTokens: 5,
  657. outputTokens: 2,
  658. nonCachedInputTokens: 4,
  659. cacheReadInputTokens: 1,
  660. reasoningTokens: 0,
  661. totalTokens: 7,
  662. providerMetadata: {
  663. openai: {
  664. input_tokens: 5,
  665. output_tokens: 2,
  666. total_tokens: 7,
  667. input_tokens_details: { cached_tokens: 1 },
  668. output_tokens_details: { reasoning_tokens: 0 },
  669. },
  670. },
  671. })
  672. expect(response.text).toBe("Hello!")
  673. expect(response.events).toEqual([
  674. { type: "step-start", index: 0 },
  675. { type: "text-start", id: "msg_1" },
  676. { type: "text-delta", id: "msg_1", text: "Hello" },
  677. { type: "text-delta", id: "msg_1", text: "!" },
  678. { type: "text-end", id: "msg_1" },
  679. {
  680. type: "step-finish",
  681. index: 0,
  682. reason: "stop",
  683. providerMetadata: { openai: { responseId: "resp_1", serviceTier: "default" } },
  684. usage,
  685. },
  686. {
  687. type: "finish",
  688. reason: "stop",
  689. providerMetadata: { openai: { responseId: "resp_1", serviceTier: "default" } },
  690. usage,
  691. },
  692. ])
  693. }),
  694. )
  695. it.effect("parses reasoning summary stream fixtures", () =>
  696. Effect.gen(function* () {
  697. const body = sseEvents(
  698. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", delta: "thinking" },
  699. { type: "response.output_text.delta", item_id: "msg_1", delta: "Hello" },
  700. { type: "response.reasoning_summary_text.done", item_id: "rs_1" },
  701. { type: "response.completed", response: { id: "resp_1" } },
  702. )
  703. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  704. expect(response.reasoning).toBe("thinking")
  705. expect(response.text).toBe("Hello")
  706. expect(response.events).toMatchObject([
  707. { type: "step-start", index: 0 },
  708. { type: "reasoning-start", id: "rs_1" },
  709. { type: "reasoning-delta", id: "rs_1", text: "thinking" },
  710. { type: "text-start", id: "msg_1" },
  711. { type: "text-delta", id: "msg_1", text: "Hello" },
  712. { type: "reasoning-end", id: "rs_1" },
  713. { type: "text-end", id: "msg_1" },
  714. { type: "step-finish", index: 0, reason: "stop" },
  715. { type: "finish", reason: "stop" },
  716. ])
  717. expect(response.events.filter((event) => event.type === "finish")).toHaveLength(1)
  718. expect(response.message.content).toEqual([
  719. { type: "reasoning", text: "thinking" },
  720. { type: "text", text: "Hello" },
  721. ])
  722. }),
  723. )
  724. it.effect("preserves encrypted reasoning metadata for continuation", () =>
  725. Effect.gen(function* () {
  726. const response = yield* LLMClient.generate(request).pipe(
  727. Effect.provide(
  728. fixedResponse(
  729. sseEvents(
  730. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", delta: "thinking" },
  731. {
  732. type: "response.output_item.done",
  733. item: {
  734. type: "reasoning",
  735. id: "rs_1",
  736. encrypted_content: "encrypted-state",
  737. summary: [{ type: "summary_text", text: "thinking" }],
  738. },
  739. },
  740. { type: "response.completed", response: { id: "resp_1" } },
  741. ),
  742. ),
  743. ),
  744. )
  745. expect(response.events).toContainEqual(
  746. expect.objectContaining({
  747. type: "reasoning-end",
  748. id: "rs_1",
  749. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
  750. }),
  751. )
  752. }),
  753. )
  754. it.effect("streams each reasoning summary part as a separate block", () =>
  755. Effect.gen(function* () {
  756. const response = yield* LLMClient.generate(
  757. LLM.updateRequest(request, { providerOptions: { openai: { store: false } } }),
  758. ).pipe(
  759. Effect.provide(
  760. fixedResponse(
  761. sseEvents(
  762. {
  763. type: "response.output_item.added",
  764. item: { type: "reasoning", id: "rs_1", encrypted_content: null },
  765. },
  766. { type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 0 },
  767. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: "First" },
  768. { type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 0 },
  769. { type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
  770. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 1, delta: "Second" },
  771. { type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 1 },
  772. {
  773. type: "response.output_item.done",
  774. item: { type: "reasoning", id: "rs_1", encrypted_content: "encrypted-state" },
  775. },
  776. { type: "response.completed", response: { id: "resp_1" } },
  777. ),
  778. ),
  779. ),
  780. )
  781. expect(response.reasoning).toBe("FirstSecond")
  782. expect(response.events).toMatchObject([
  783. { type: "step-start", index: 0 },
  784. {
  785. type: "reasoning-start",
  786. id: "rs_1:0",
  787. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: null } },
  788. },
  789. { type: "reasoning-delta", id: "rs_1:0", text: "First" },
  790. { type: "reasoning-end", id: "rs_1:0", providerMetadata: { openai: { itemId: "rs_1" } } },
  791. {
  792. type: "reasoning-start",
  793. id: "rs_1:1",
  794. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: null } },
  795. },
  796. { type: "reasoning-delta", id: "rs_1:1", text: "Second" },
  797. {
  798. type: "reasoning-end",
  799. id: "rs_1:1",
  800. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
  801. },
  802. { type: "step-finish", index: 0, reason: "stop" },
  803. { type: "finish", reason: "stop" },
  804. ])
  805. }),
  806. )
  807. it.effect("closes reasoning summary parts when storage is not disabled", () =>
  808. Effect.gen(function* () {
  809. const response = yield* LLMClient.generate(
  810. LLM.updateRequest(request, { providerOptions: { openai: { store: true } } }),
  811. ).pipe(
  812. Effect.provide(
  813. fixedResponse(
  814. sseEvents(
  815. {
  816. type: "response.output_item.added",
  817. item: { type: "reasoning", id: "rs_1", encrypted_content: null },
  818. },
  819. { type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 0 },
  820. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 0, delta: "First" },
  821. { type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 0 },
  822. { type: "response.reasoning_summary_part.added", item_id: "rs_1", summary_index: 1 },
  823. { type: "response.reasoning_summary_text.delta", item_id: "rs_1", summary_index: 1, delta: "Second" },
  824. { type: "response.reasoning_summary_part.done", item_id: "rs_1", summary_index: 1 },
  825. {
  826. type: "response.output_item.done",
  827. item: { type: "reasoning", id: "rs_1", encrypted_content: null },
  828. },
  829. { type: "response.completed", response: { id: "resp_1" } },
  830. ),
  831. ),
  832. ),
  833. )
  834. expect(response.events.filter((event) => event.type === "reasoning-end")).toEqual([
  835. { type: "reasoning-end", id: "rs_1:0", providerMetadata: { openai: { itemId: "rs_1" } } },
  836. { type: "reasoning-end", id: "rs_1:1", providerMetadata: { openai: { itemId: "rs_1" } } },
  837. ])
  838. }),
  839. )
  840. it.effect("continues a stateless reasoning conversation", () =>
  841. Effect.gen(function* () {
  842. const response = yield* LLMClient.generate(
  843. LLM.request({
  844. id: "req_reasoning_continue",
  845. model,
  846. messages: [
  847. Message.user("What changed?"),
  848. Message.assistant([
  849. {
  850. type: "reasoning",
  851. text: "Checked the previous diff.",
  852. providerMetadata: {
  853. openai: {
  854. itemId: "rs_1",
  855. reasoningEncryptedContent: "encrypted-state",
  856. },
  857. },
  858. },
  859. { type: "text", text: "The parser changed." },
  860. ]),
  861. Message.user("Summarize it."),
  862. ],
  863. providerOptions: { openai: { store: false } },
  864. }),
  865. ).pipe(
  866. Effect.provide(
  867. dynamicResponse((input) =>
  868. Effect.gen(function* () {
  869. const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
  870. const body = yield* Effect.promise(() => web.json())
  871. expect(body).toMatchObject({
  872. input: [
  873. { role: "user", content: [{ type: "input_text", text: "What changed?" }] },
  874. {
  875. type: "reasoning",
  876. encrypted_content: "encrypted-state",
  877. summary: [{ type: "summary_text", text: "Checked the previous diff." }],
  878. },
  879. { role: "assistant", content: [{ type: "output_text", text: "The parser changed." }] },
  880. { role: "user", content: [{ type: "input_text", text: "Summarize it." }] },
  881. ],
  882. })
  883. expect(body.input[1]).not.toHaveProperty("id")
  884. return input.respond(
  885. sseEvents(
  886. { type: "response.output_text.delta", item_id: "msg_1", delta: "Parser now round-trips reasoning." },
  887. { type: "response.completed", response: { id: "resp_1" } },
  888. ),
  889. { headers: { "content-type": "text/event-stream" } },
  890. )
  891. }),
  892. ),
  893. ),
  894. )
  895. expect(response.text).toBe("Parser now round-trips reasoning.")
  896. }),
  897. )
  898. it.effect("preserves assistant content order around reasoning items", () =>
  899. Effect.gen(function* () {
  900. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  901. LLM.request({
  902. id: "req_reasoning_order",
  903. model,
  904. messages: [
  905. Message.assistant([
  906. { type: "text", text: "Before." },
  907. {
  908. type: "reasoning",
  909. text: "Checked order.",
  910. providerMetadata: {
  911. openai: {
  912. itemId: "rs_1",
  913. reasoningEncryptedContent: "encrypted-state",
  914. },
  915. },
  916. },
  917. { type: "text", text: "After." },
  918. ]),
  919. ],
  920. providerOptions: { openai: { store: false } },
  921. }),
  922. )
  923. expect(prepared.body.input).toEqual([
  924. { role: "assistant", content: [{ type: "output_text", text: "Before." }] },
  925. {
  926. type: "reasoning",
  927. encrypted_content: "encrypted-state",
  928. summary: [{ type: "summary_text", text: "Checked order." }],
  929. },
  930. { role: "assistant", content: [{ type: "output_text", text: "After." }] },
  931. ])
  932. }),
  933. )
  934. it.effect("references stored reasoning items by id", () =>
  935. Effect.gen(function* () {
  936. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  937. LLM.request({
  938. model,
  939. messages: [
  940. Message.assistant([
  941. {
  942. type: "reasoning",
  943. text: "Checked the previous diff.",
  944. providerMetadata: { openai: { itemId: "rs_1" } },
  945. },
  946. ]),
  947. ],
  948. providerOptions: { openai: { store: true } },
  949. }),
  950. )
  951. expect(prepared.body.input).toEqual([{ type: "item_reference", id: "rs_1" }])
  952. }),
  953. )
  954. it.effect("references stored provider-executed hosted tool results by id", () =>
  955. Effect.gen(function* () {
  956. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  957. LLM.request({
  958. model,
  959. messages: [
  960. Message.assistant([
  961. ToolCallPart.make({
  962. id: "ws_1",
  963. name: "web_search",
  964. input: { query: "effect 4" },
  965. providerExecuted: true,
  966. providerMetadata: { openai: { itemId: "ws_1" } },
  967. }),
  968. {
  969. type: "tool-result",
  970. id: "ws_1",
  971. name: "web_search",
  972. result: { type: "json", value: { type: "web_search_call", id: "ws_1", status: "completed" } },
  973. providerExecuted: true,
  974. providerMetadata: { openai: { itemId: "ws_1" } },
  975. },
  976. ]),
  977. Message.user("Continue."),
  978. ],
  979. providerOptions: { openai: { store: true } },
  980. }),
  981. )
  982. expect(prepared.body.input).toEqual([
  983. { type: "item_reference", id: "ws_1" },
  984. { role: "user", content: [{ type: "input_text", text: "Continue." }] },
  985. ])
  986. }),
  987. )
  988. it.effect("joins streamed summary blocks into one continuation reasoning item", () =>
  989. Effect.gen(function* () {
  990. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  991. LLM.request({
  992. id: "req_multi_summary_continuation",
  993. model,
  994. messages: [
  995. Message.assistant([
  996. {
  997. type: "reasoning",
  998. text: "First",
  999. providerMetadata: { openai: { itemId: "rs_1" } },
  1000. },
  1001. {
  1002. type: "reasoning",
  1003. text: "Second",
  1004. providerMetadata: { openai: { itemId: "rs_1", reasoningEncryptedContent: "encrypted-state" } },
  1005. },
  1006. ]),
  1007. ],
  1008. providerOptions: { openai: { store: false } },
  1009. }),
  1010. )
  1011. expect(prepared.body.input).toEqual([
  1012. {
  1013. type: "reasoning",
  1014. encrypted_content: "encrypted-state",
  1015. summary: [
  1016. { type: "summary_text", text: "First" },
  1017. { type: "summary_text", text: "Second" },
  1018. ],
  1019. },
  1020. ])
  1021. }),
  1022. )
  1023. it.effect("skips non-persisted reasoning ids without encrypted state", () =>
  1024. Effect.gen(function* () {
  1025. const prepared = yield* LLMClient.prepare(
  1026. LLM.request({
  1027. id: "req_reasoning_without_encrypted_state",
  1028. model,
  1029. messages: [
  1030. Message.user("What changed?"),
  1031. Message.assistant([
  1032. {
  1033. type: "reasoning",
  1034. text: "Checked the previous diff.",
  1035. providerMetadata: {
  1036. openai: {
  1037. itemId: "rs_1",
  1038. reasoningEncryptedContent: null,
  1039. },
  1040. },
  1041. },
  1042. { type: "text", text: "The parser changed." },
  1043. ]),
  1044. Message.user("Summarize it."),
  1045. ],
  1046. providerOptions: { openai: { store: false } },
  1047. }),
  1048. )
  1049. expect(prepared.body).toMatchObject({
  1050. input: [
  1051. { role: "user", content: [{ type: "input_text", text: "What changed?" }] },
  1052. { role: "assistant", content: [{ type: "output_text", text: "The parser changed." }] },
  1053. { role: "user", content: [{ type: "input_text", text: "Summarize it." }] },
  1054. ],
  1055. store: false,
  1056. })
  1057. }),
  1058. )
  1059. it.effect("assembles streamed function call input", () =>
  1060. Effect.gen(function* () {
  1061. const body = sseEvents(
  1062. {
  1063. type: "response.output_item.added",
  1064. item: { type: "function_call", id: "item_1", call_id: "call_1", name: "lookup", arguments: "" },
  1065. },
  1066. { type: "response.function_call_arguments.delta", item_id: "item_1", delta: '{"query"' },
  1067. { type: "response.function_call_arguments.delta", item_id: "item_1", delta: ':"weather"}' },
  1068. {
  1069. type: "response.output_item.done",
  1070. item: {
  1071. type: "function_call",
  1072. id: "item_1",
  1073. call_id: "call_1",
  1074. name: "lookup",
  1075. arguments: '{"query":"weather"}',
  1076. },
  1077. },
  1078. { type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
  1079. )
  1080. const response = yield* LLMClient.generate(
  1081. LLM.updateRequest(request, {
  1082. tools: [{ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } }],
  1083. }),
  1084. ).pipe(Effect.provide(fixedResponse(body)))
  1085. const usage = new Usage({
  1086. inputTokens: 5,
  1087. outputTokens: 1,
  1088. nonCachedInputTokens: 5,
  1089. cacheReadInputTokens: undefined,
  1090. reasoningTokens: undefined,
  1091. totalTokens: 6,
  1092. providerMetadata: { openai: { input_tokens: 5, output_tokens: 1 } },
  1093. })
  1094. expect(response.events).toEqual([
  1095. { type: "step-start", index: 0 },
  1096. {
  1097. type: "tool-input-start",
  1098. id: "call_1",
  1099. name: "lookup",
  1100. providerMetadata: { openai: { itemId: "item_1" } },
  1101. },
  1102. {
  1103. type: "tool-input-delta",
  1104. id: "call_1",
  1105. name: "lookup",
  1106. text: '{"query"',
  1107. },
  1108. {
  1109. type: "tool-input-delta",
  1110. id: "call_1",
  1111. name: "lookup",
  1112. text: ':"weather"}',
  1113. },
  1114. {
  1115. type: "tool-input-end",
  1116. id: "call_1",
  1117. name: "lookup",
  1118. providerMetadata: { openai: { itemId: "item_1" } },
  1119. },
  1120. {
  1121. type: "tool-call",
  1122. id: "call_1",
  1123. name: "lookup",
  1124. input: { query: "weather" },
  1125. providerExecuted: undefined,
  1126. providerMetadata: { openai: { itemId: "item_1" } },
  1127. },
  1128. { type: "step-finish", index: 0, reason: "tool-calls", usage, providerMetadata: undefined },
  1129. {
  1130. type: "finish",
  1131. reason: "tool-calls",
  1132. providerMetadata: undefined,
  1133. usage,
  1134. },
  1135. ])
  1136. }),
  1137. )
  1138. it.effect("decodes web_search_call as provider-executed tool-call + tool-result", () =>
  1139. Effect.gen(function* () {
  1140. const item = {
  1141. type: "web_search_call",
  1142. id: "ws_1",
  1143. status: "completed",
  1144. action: { type: "search", query: "effect 4" },
  1145. }
  1146. const body = sseEvents(
  1147. { type: "response.output_item.added", item },
  1148. { type: "response.output_item.done", item },
  1149. { type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
  1150. )
  1151. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  1152. const callsAndResults = response.events.filter(
  1153. (event) => event.type === "tool-call" || event.type === "tool-result",
  1154. )
  1155. expect(callsAndResults).toEqual([
  1156. {
  1157. type: "tool-call",
  1158. id: "ws_1",
  1159. name: "web_search",
  1160. input: { type: "search", query: "effect 4" },
  1161. providerExecuted: true,
  1162. providerMetadata: { openai: { itemId: "ws_1" } },
  1163. },
  1164. {
  1165. type: "tool-result",
  1166. id: "ws_1",
  1167. name: "web_search",
  1168. result: { type: "json", value: item },
  1169. providerExecuted: true,
  1170. providerMetadata: { openai: { itemId: "ws_1" } },
  1171. },
  1172. ])
  1173. }),
  1174. )
  1175. it.effect("decodes code_interpreter_call as provider-executed events with code input", () =>
  1176. Effect.gen(function* () {
  1177. const item = {
  1178. type: "code_interpreter_call",
  1179. id: "ci_1",
  1180. status: "completed",
  1181. code: "print(1+1)",
  1182. container_id: "cnt_xyz",
  1183. outputs: [{ type: "logs", logs: "2\n" }],
  1184. }
  1185. const body = sseEvents(
  1186. { type: "response.output_item.done", item },
  1187. { type: "response.completed", response: { usage: { input_tokens: 5, output_tokens: 1 } } },
  1188. )
  1189. const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
  1190. const toolCall = response.events.find((event) => event.type === "tool-call")
  1191. expect(toolCall).toEqual({
  1192. type: "tool-call",
  1193. id: "ci_1",
  1194. name: "code_interpreter",
  1195. input: { code: "print(1+1)", container_id: "cnt_xyz" },
  1196. providerExecuted: true,
  1197. providerMetadata: { openai: { itemId: "ci_1" } },
  1198. })
  1199. const toolResult = response.events.find((event) => event.type === "tool-result")
  1200. expect(toolResult).toEqual({
  1201. type: "tool-result",
  1202. id: "ci_1",
  1203. name: "code_interpreter",
  1204. result: { type: "json", value: item },
  1205. providerExecuted: true,
  1206. providerMetadata: { openai: { itemId: "ci_1" } },
  1207. })
  1208. }),
  1209. )
  1210. it.effect("lowers user image content", () =>
  1211. Effect.gen(function* () {
  1212. const prepared = yield* LLMClient.prepare<OpenAIResponses.OpenAIResponsesBody>(
  1213. LLM.request({
  1214. id: "req_media",
  1215. model,
  1216. messages: [Message.user({ type: "media", mediaType: "image/png", data: "AAECAw==" })],
  1217. }),
  1218. )
  1219. expect(prepared.body.input).toEqual([
  1220. {
  1221. role: "user",
  1222. content: [{ type: "input_image", image_url: "data:image/png;base64,AAECAw==" }],
  1223. },
  1224. ])
  1225. }),
  1226. )
  1227. it.effect("rejects unsupported user media content", () =>
  1228. Effect.gen(function* () {
  1229. const error = yield* LLMClient.prepare(
  1230. LLM.request({
  1231. id: "req_media",
  1232. model,
  1233. messages: [Message.user({ type: "media", mediaType: "application/pdf", data: "AAECAw==" })],
  1234. }),
  1235. ).pipe(Effect.flip)
  1236. expect(error.message).toContain("OpenAI Responses does not support media type application/pdf")
  1237. }),
  1238. )
  1239. it.effect("emits provider-error events for mid-stream provider errors", () =>
  1240. Effect.gen(function* () {
  1241. const response = yield* LLMClient.generate(request).pipe(
  1242. Effect.provide(fixedResponse(sseEvents({ type: "error", code: "rate_limit_exceeded", message: "Slow down" }))),
  1243. )
  1244. // Prefix the code so consumers see the failure mode, not just the
  1245. // sometimes-generic provider message. The bare message alone meant
  1246. // production errors like rate limits were indistinguishable from
  1247. // unrelated stream failures.
  1248. expect(response.events).toEqual([{ type: "provider-error", message: "rate_limit_exceeded: Slow down" }])
  1249. }),
  1250. )
  1251. it.effect("falls back to error code when no message is present", () =>
  1252. Effect.gen(function* () {
  1253. const response = yield* LLMClient.generate(request).pipe(
  1254. Effect.provide(fixedResponse(sseEvents({ type: "error", code: "internal_error" }))),
  1255. )
  1256. expect(response.events).toEqual([{ type: "provider-error", message: "internal_error" }])
  1257. }),
  1258. )
  1259. it.effect("falls back to error code when message is empty", () =>
  1260. Effect.gen(function* () {
  1261. const response = yield* LLMClient.generate(request).pipe(
  1262. Effect.provide(fixedResponse(sseEvents({ type: "error", code: "internal_error", message: "" }))),
  1263. )
  1264. expect(response.events).toEqual([{ type: "provider-error", message: "internal_error" }])
  1265. }),
  1266. )
  1267. // Regression: `response.failed` carries the failure details under
  1268. // `response.error`, not at the top level. The previous handler only
  1269. // checked top-level `message`/`code` and so always emitted the bare
  1270. // "OpenAI Responses response failed" string, hiding the real cause.
  1271. it.effect("surfaces response.failed details from response.error", () =>
  1272. Effect.gen(function* () {
  1273. const response = yield* LLMClient.generate(request).pipe(
  1274. Effect.provide(
  1275. fixedResponse(
  1276. sseEvents({
  1277. type: "response.failed",
  1278. response: {
  1279. id: "resp_failed_1",
  1280. error: { code: "server_error", message: "Upstream model unavailable" },
  1281. },
  1282. }),
  1283. ),
  1284. ),
  1285. )
  1286. expect(response.events).toEqual([{ type: "provider-error", message: "server_error: Upstream model unavailable" }])
  1287. }),
  1288. )
  1289. it.effect("surfaces response.failed code when no nested message is present", () =>
  1290. Effect.gen(function* () {
  1291. const response = yield* LLMClient.generate(request).pipe(
  1292. Effect.provide(
  1293. fixedResponse(
  1294. sseEvents({
  1295. type: "response.failed",
  1296. response: { id: "resp_failed_2", error: { code: "invalid_prompt" } },
  1297. }),
  1298. ),
  1299. ),
  1300. )
  1301. expect(response.events).toEqual([{ type: "provider-error", message: "invalid_prompt" }])
  1302. }),
  1303. )
  1304. it.effect("surfaces error event details even when they arrive nested under response.error", () =>
  1305. Effect.gen(function* () {
  1306. // Some OpenAI-compatible proxies and older SDK versions wrap the
  1307. // top-level error fields into a nested `response.error` payload
  1308. // when they bubble up an HTTP error as an SSE `error` event. Honour
  1309. // both shapes so the user still sees the underlying cause instead
  1310. // of the catch-all string.
  1311. const response = yield* LLMClient.generate(request).pipe(
  1312. Effect.provide(
  1313. fixedResponse(
  1314. sseEvents({
  1315. type: "error",
  1316. response: { error: { code: "context_length_exceeded", message: "prompt too long" } },
  1317. }),
  1318. ),
  1319. ),
  1320. )
  1321. expect(response.events).toEqual([
  1322. {
  1323. type: "provider-error",
  1324. message: "context_length_exceeded: prompt too long",
  1325. classification: "context-overflow",
  1326. },
  1327. ])
  1328. }),
  1329. )
  1330. it.effect("falls back to a stable default when both error and response are absent", () =>
  1331. Effect.gen(function* () {
  1332. const response = yield* LLMClient.generate(request).pipe(
  1333. Effect.provide(fixedResponse(sseEvents({ type: "error" }))),
  1334. )
  1335. expect(response.events).toEqual([{ type: "provider-error", message: "OpenAI Responses stream error" }])
  1336. }),
  1337. )
  1338. it.effect("falls back to a stable default when response.failed has no error payload", () =>
  1339. Effect.gen(function* () {
  1340. const response = yield* LLMClient.generate(request).pipe(
  1341. Effect.provide(fixedResponse(sseEvents({ type: "response.failed", response: { id: "resp_failed_3" } }))),
  1342. )
  1343. expect(response.events).toEqual([{ type: "provider-error", message: "OpenAI Responses response failed" }])
  1344. }),
  1345. )
  1346. it.effect("fails HTTP provider errors before stream parsing", () =>
  1347. Effect.gen(function* () {
  1348. const error = yield* LLMClient.generate(request).pipe(
  1349. Effect.provide(
  1350. fixedResponse('{"error":{"type":"invalid_request_error","message":"Bad request"}}', {
  1351. status: 400,
  1352. headers: { "content-type": "application/json" },
  1353. }),
  1354. ),
  1355. Effect.flip,
  1356. )
  1357. expect(error).toBeInstanceOf(LLMError)
  1358. expect(error.reason).toMatchObject({ _tag: "InvalidRequest" })
  1359. expect(error.message).toContain("HTTP 400")
  1360. }),
  1361. )
  1362. })