| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299 |
- import { describe, expect } from "bun:test"
- import { Effect, Ref, Schema, Stream } from "effect"
- import { HttpClientRequest } from "effect/unstable/http"
- import {
- HttpOptions,
- LLM,
- AIError,
- LLMEvent,
- LLMRequest,
- Message,
- LanguageModel,
- ToolCallPart,
- ToolDefinition,
- Usage,
- } from "../../src/index.js"
- import * as Azure from "../../src/providers/azure.js"
- import * as OpenAI from "../../src/providers/openai.js"
- import * as OpenAICompatible from "../../src/providers/openai-compatible.js"
- import * as XAI from "../../src/providers/xai.js"
- import * as OpenAIChat from "../../src/protocols/openai-chat.js"
- import { ProviderShared } from "../../src/protocols/shared.js"
- import { Auth, LLMClient } from "../../src/route.js"
- import { compileRequest } from "../../src/route/client.js"
- import { it } from "../lib/effect.js"
- import { dynamicResponse, fixedResponse, systemError, truncatedStream } from "../lib/http.js"
- import { deltaChunk, usageChunk } from "../lib/openai-chunks.js"
- import { sseEvents } from "../lib/sse.js"
- const TargetJson = Schema.fromJsonString(Schema.Unknown)
- const encodeJson = Schema.encodeSync(TargetJson)
- const decodeJson = Schema.decodeUnknownSync(TargetJson)
- const model = OpenAIChat.route
- .with({ endpoint: { baseURL: "https://api.openai.test/v1/" }, auth: Auth.bearer("test") })
- .model({ id: "gpt-4o-mini" })
- const request = LLM.request({
- id: "req_1",
- model,
- system: "You are concise.",
- prompt: "Say hello.",
- generation: { maxTokens: 20, temperature: 0 },
- })
- describe("OpenAI Chat route", () => {
- it.effect("prepares OpenAI Chat payload", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(request)
- expect(prepared.body).toEqual({
- model: "gpt-4o-mini",
- messages: [
- { role: "system", content: "You are concise." },
- { role: "user", content: "Say hello." },
- ],
- stream: true,
- stream_options: { include_usage: true },
- max_tokens: 20,
- temperature: 0,
- })
- }),
- )
- it.effect("lowers chronological system updates to escaped user wrappers in order", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.user("Before."),
- Message.system("Treat <admin> & data literally."),
- Message.assistant("After."),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- {
- role: "user",
- content: "Before.\n<system-update>\nTreat <admin> & data literally.\n</system-update>",
- },
- { role: "assistant", content: "After." },
- ])
- }),
- )
- it.effect("replays canonical reasoning as OpenAI-compatible reasoning_content", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([
- { type: "reasoning", text: "thinking" },
- { type: "text", text: "Hello" },
- ]),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_content: "thinking" }])
- }),
- )
- it.effect("concatenates assistant text parts without adding separators", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([
- { type: "text", text: "Hello" },
- { type: "text", text: " world" },
- ]),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([{ role: "assistant", content: "Hello world" }])
- }),
- )
- it.effect("writes reasoning to a configured custom field on every assistant message", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model: LanguageModel.update(model, { compatibility: { reasoningField: "vendor_reasoning" } }),
- messages: [
- Message.assistant([
- {
- type: "reasoning",
- text: "thinking",
- providerMetadata: { openai: { reasoningField: "reasoning" } },
- },
- { type: "text", text: "Hello" },
- ]),
- Message.assistant("Done"),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- { role: "assistant", content: "Hello", vendor_reasoning: "thinking" },
- { role: "assistant", content: "Done", vendor_reasoning: "" },
- ])
- }),
- )
- it.effect("rejects reasoning fields that conflict with assistant message fields", () =>
- Effect.gen(function* () {
- const error = yield* compileRequest(
- LLM.request({
- model: LanguageModel.update(model, { compatibility: { reasoningField: "content" } }),
- messages: [Message.assistant([{ type: "reasoning", text: "thinking" }])],
- }),
- ).pipe(Effect.flip)
- expect(error.message).toContain("reserved field content")
- }),
- )
- it.effect("maps OpenAI provider options to Chat options", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model: OpenAI.configure({ baseURL: "https://api.openai.test/v1/", apiKey: "test" }).chat("gpt-4o-mini"),
- prompt: "think",
- providerOptions: { openai: { reasoningEffort: "max" } },
- }),
- )
- expect(prepared.body.store).toBe(false)
- expect(prepared.body.reasoning_effort).toBe("max")
- }),
- )
- it.effect("maps the request prompt cache key", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model: OpenAICompatible.configure({
- baseURL: "https://api.compatible.test/v1",
- apiKey: "test",
- }).model("compatible-model"),
- prompt: "Hello",
- promptCacheKey: "session_123",
- }),
- )
- expect(prepared.body.prompt_cache_key).toBe("session_123")
- }),
- )
- it.effect("maps the xAI Chat prompt cache key to conversation affinity", () =>
- LLMClient.generate(
- LLM.request({
- model: XAI.configure({ apiKey: "test", baseURL: "https://api.x.ai/v1" }).chat("grok-4.5"),
- prompt: "Hello",
- promptCacheKey: "session_123",
- }),
- ).pipe(
- Effect.provide(
- dynamicResponse((input) =>
- Effect.gen(function* () {
- const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
- expect(web.headers.get("x-grok-conv-id")).toBe("session_123")
- const body = decodeJson(yield* Effect.promise(() => web.text()))
- expect(ProviderShared.isRecord(body) ? body.prompt_cache_key : undefined).toBe("session_123")
- return input.respond(sseEvents(deltaChunk({}, "stop")), {
- headers: { "content-type": "text/event-stream" },
- })
- }),
- ),
- ),
- ),
- )
- it.effect("passes through custom OpenAI-compatible reasoning effort strings", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- prompt: "think",
- providerOptions: { openai: { reasoningEffort: "experimental" } },
- }),
- )
- expect(prepared.body.reasoning_effort).toBe("experimental")
- }),
- )
- it.effect("adds native query params to the Chat Completions URL", () =>
- LLMClient.generate(
- LLMRequest.update(request, {
- model: LanguageModel.update(model, {
- route: model.route.with({ endpoint: { query: { "api-version": "v1" } } }),
- }),
- }),
- ).pipe(
- Effect.provide(
- dynamicResponse((input) =>
- Effect.gen(function* () {
- const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
- expect(web.url).toBe("https://api.openai.test/v1/chat/completions?api-version=v1")
- return input.respond(sseEvents(deltaChunk({}, "stop")), {
- headers: { "content-type": "text/event-stream" },
- })
- }),
- ),
- ),
- ),
- )
- it.effect("uses Azure api-key header for static OpenAI Chat keys", () =>
- LLMClient.generate(
- LLMRequest.update(request, {
- model: Azure.configure({
- baseURL: "https://opencode-test.openai.azure.com/openai/v1/",
- apiKey: "azure-key",
- headers: { authorization: "Bearer stale" },
- }).chat("gpt-4o-mini"),
- }),
- ).pipe(
- Effect.provide(
- dynamicResponse((input) =>
- Effect.gen(function* () {
- const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
- expect(web.url).toBe("https://opencode-test.openai.azure.com/openai/v1/chat/completions?api-version=v1")
- expect(web.headers.get("api-key")).toBe("azure-key")
- expect(web.headers.get("authorization")).toBeNull()
- return input.respond(sseEvents(deltaChunk({}, "stop")), {
- headers: { "content-type": "text/event-stream" },
- })
- }),
- ),
- ),
- ),
- )
- it.effect("applies serializable HTTP overlays after payload lowering", () =>
- LLMClient.generate(
- LLMRequest.update(request, {
- model: model.route
- .with({ auth: Auth.bearer("fresh-key"), headers: { authorization: "Bearer stale" } })
- .model({ id: model.id }),
- http: HttpOptions.make({
- body: { metadata: { source: "test" } },
- headers: { authorization: "Bearer request", "x-custom": "yes" },
- query: { debug: "1" },
- }),
- }),
- ).pipe(
- Effect.provide(
- dynamicResponse((input) =>
- Effect.gen(function* () {
- const web = yield* HttpClientRequest.toWeb(input.request).pipe(Effect.orDie)
- expect(web.url).toBe("https://api.openai.test/v1/chat/completions?debug=1")
- expect(web.headers.get("authorization")).toBe("Bearer fresh-key")
- expect(web.headers.get("x-custom")).toBe("yes")
- expect(decodeJson(input.text)).toMatchObject({
- stream: true,
- stream_options: { include_usage: true },
- metadata: { source: "test" },
- })
- return input.respond(sseEvents(deltaChunk({}, "stop")), {
- headers: { "content-type": "text/event-stream" },
- })
- }),
- ),
- ),
- ),
- )
- it.effect("prepares assistant tool-call and tool-result messages", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- id: "req_tool_result",
- model,
- messages: [
- Message.user("What is the weather?"),
- Message.assistant([ToolCallPart.make({ id: "call_1", name: "lookup", input: { query: "weather" } })]),
- Message.tool({ id: "call_1", name: "lookup", result: { forecast: "sunny" } }),
- ],
- }),
- )
- expect(prepared.body).toEqual({
- model: "gpt-4o-mini",
- messages: [
- { role: "user", content: "What is the weather?" },
- {
- role: "assistant",
- content: null,
- tool_calls: [
- {
- id: "call_1",
- type: "function",
- function: { name: "lookup", arguments: encodeJson({ query: "weather" }) },
- },
- ],
- },
- { role: "tool", tool_call_id: "call_1", content: encodeJson({ forecast: "sunny" }) },
- ],
- stream: true,
- stream_options: { include_usage: true },
- })
- }),
- )
- it.effect("preserves structured tool errors for the model", () =>
- Effect.gen(function* () {
- const error = { error: { type: "unknown", message: "Tool execution interrupted" } }
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([ToolCallPart.make({ id: "call_1", name: "bash", input: {} })]),
- Message.tool({ id: "call_1", name: "bash", resultType: "error", result: error }),
- ],
- }),
- )
- expect(prepared.body.messages.at(-1)).toEqual({
- role: "tool",
- tool_call_id: "call_1",
- content: ProviderShared.encodeJson(error),
- })
- }),
- )
- it.effect("continues image tool results as vision input without base64 text", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([ToolCallPart.make({ id: "call_image", name: "read", input: { path: "pixel.png" } })]),
- Message.tool({
- id: "call_image",
- name: "read",
- result: {
- type: "content",
- value: [
- { type: "text", text: "Image read successfully" },
- { type: "file", uri: "data:image/png;base64,AAECAw==", mime: "image/png", name: "pixel.png" },
- ],
- },
- }),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- {
- role: "assistant",
- content: null,
- tool_calls: [
- {
- id: "call_image",
- type: "function",
- function: { name: "read", arguments: encodeJson({ path: "pixel.png" }) },
- },
- ],
- },
- { role: "tool", tool_call_id: "call_image", content: "Image read successfully" },
- {
- role: "user",
- content: [{ type: "image_url", image_url: { url: "data:image/png;base64,AAECAw==" } }],
- },
- ])
- expect(JSON.stringify(prepared.body.messages)).not.toContain('"content":"AAECAw=="')
- }),
- )
- it.effect("orders parallel tool responses before one aggregated vision message", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([
- ToolCallPart.make({ id: "call_1", name: "read", input: {} }),
- ToolCallPart.make({ id: "call_2", name: "read", input: {} }),
- ]),
- Message.make({
- role: "tool",
- content: [
- {
- type: "tool-result",
- id: "call_1",
- name: "read",
- result: {
- type: "content",
- value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
- },
- },
- {
- type: "tool-result",
- id: "call_2",
- name: "read",
- result: {
- type: "content",
- value: [{ type: "file", uri: "data:image/jpeg;base64,/9j/", mime: "image/jpeg" }],
- },
- },
- ],
- }),
- ],
- }),
- )
- expect(prepared.body.messages.slice(1)).toEqual([
- { role: "tool", tool_call_id: "call_1", content: "" },
- { role: "tool", tool_call_id: "call_2", content: "" },
- {
- role: "user",
- content: [
- { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
- { type: "image_url", image_url: { url: "data:image/jpeg;base64,/9j/" } },
- ],
- },
- ])
- }),
- )
- it.effect("aggregates consecutive tool images with a following system update", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.tool({
- id: "call_1",
- name: "read",
- result: {
- type: "content",
- value: [{ type: "file", uri: "data:image/png;base64,AAEC", mime: "image/png" }],
- },
- }),
- Message.tool({
- id: "call_2",
- name: "read",
- result: {
- type: "content",
- value: [{ type: "file", uri: "data:image/webp;base64,UklG", mime: "image/webp" }],
- },
- }),
- Message.system("Inspect both images."),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- { role: "tool", tool_call_id: "call_1", content: "" },
- { role: "tool", tool_call_id: "call_2", content: "" },
- {
- role: "user",
- content: [
- { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
- { type: "image_url", image_url: { url: "data:image/webp;base64,UklG" } },
- { type: "text", text: "<system-update>\nInspect both images.\n</system-update>" },
- ],
- },
- ])
- }),
- )
- it.effect("appends system updates without replacing multipart user content", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.user({ type: "media", mediaType: "image/png", data: "AAEC" }),
- Message.system("Keep the image."),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- {
- role: "user",
- content: [
- { type: "image_url", image_url: { url: "data:image/png;base64,AAEC" } },
- { type: "text", text: "<system-update>\nKeep the image.\n</system-update>" },
- ],
- },
- ])
- }),
- )
- for (const [name, media] of [
- ["mismatched data URL MIME", { mediaType: "image/png", data: "data:image/jpeg;base64,/9j/" }],
- ["malformed base64", { mediaType: "image/png", data: "not-base64" }],
- ["unsupported SVG", { mediaType: "image/svg+xml", data: "PHN2Zz4=" }],
- ] as const)
- it.effect(`rejects ${name}`, () =>
- Effect.gen(function* () {
- const error = yield* compileRequest(
- LLM.request({ model, messages: [Message.user({ type: "media", ...media })] }),
- ).pipe(Effect.flip)
- expect(error.message).toMatch(/does not support|does not match|valid base64/)
- }),
- )
- it.effect("rejects oversized image input", () =>
- Effect.gen(function* () {
- const error = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.user({
- type: "media",
- mediaType: "image/png",
- data: "A".repeat(ProviderShared.MAX_MEDIA_ENCODED_BYTES + 4),
- }),
- ],
- }),
- ).pipe(Effect.flip)
- expect(error.message).toContain("encoded limit")
- }),
- )
- it.effect("prepares raw and data URL image media as vision input", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- id: "req_media",
- model,
- messages: [
- Message.user([
- { type: "media", mediaType: "image/png", data: "AAECAw==" },
- { type: "media", mediaType: "image/jpeg", data: "data:image/jpeg;base64,/9j/" },
- ]),
- ],
- }),
- )
- expect(prepared.body.messages).toEqual([
- {
- role: "user",
- content: [
- { type: "image_url", image_url: { url: "data:image/png;base64,AAECAw==" } },
- { type: "image_url", image_url: { url: "data:image/jpeg;base64,/9j/" } },
- ],
- },
- ])
- }),
- )
- it.effect("lowers reasoning-only assistant history", () =>
- Effect.gen(function* () {
- const prepared = yield* compileRequest(
- LLM.request({
- id: "req_reasoning",
- model,
- messages: [Message.assistant({ type: "reasoning", text: "hidden" })],
- }),
- )
- expect(prepared.body.messages).toEqual([{ role: "assistant", content: "", reasoning_content: "hidden" }])
- }),
- )
- it.effect("parses text and usage stream fixtures", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({ role: "assistant", content: "Hello" }),
- deltaChunk({ content: "!" }),
- deltaChunk({}, "stop"),
- usageChunk({
- prompt_tokens: 5,
- completion_tokens: 2,
- total_tokens: 7,
- prompt_tokens_details: { cached_tokens: 1, cache_write_tokens: 2 },
- completion_tokens_details: { reasoning_tokens: 0 },
- }),
- )
- const response = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)))
- const usage = new Usage({
- inputTokens: 5,
- outputTokens: 2,
- nonCachedInputTokens: 2,
- cacheReadInputTokens: 1,
- cacheWriteInputTokens: 2,
- reasoningTokens: 0,
- totalTokens: 7,
- providerMetadata: {
- openai: {
- prompt_tokens: 5,
- completion_tokens: 2,
- total_tokens: 7,
- prompt_tokens_details: { cached_tokens: 1, cache_write_tokens: 2 },
- completion_tokens_details: { reasoning_tokens: 0 },
- },
- },
- })
- expect(response.text).toBe("Hello!")
- expect(response.events).toEqual([
- { type: "step-start", index: 0 },
- { type: "text-start", id: "text-0" },
- { type: "text-delta", id: "text-0", text: "Hello" },
- { type: "text-delta", id: "text-0", text: "!" },
- { type: "text-end", id: "text-0" },
- {
- type: "step-finish",
- index: 0,
- reason: { normalized: "stop", raw: "stop" },
- usage,
- providerMetadata: undefined,
- },
- {
- type: "finish",
- reason: { normalized: "stop", raw: "stop" },
- usage,
- },
- ])
- }),
- )
- it.effect("parses and replays OpenAI-compatible reasoning fields", () =>
- Effect.gen(function* () {
- const fields = ["reasoning_content", "reasoning", "reasoning_text"] as const
- for (const field of fields) {
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { [field]: "thinking" } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.text).toBe("Hello")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: field },
- })
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", [field]: "thinking" }])
- }
- }),
- )
- it.effect("parses and replays a configured custom reasoning field", () =>
- Effect.gen(function* () {
- const custom = LanguageModel.update(model, { compatibility: { reasoningField: "vendor_reasoning" } })
- const response = yield* LLMClient.generate(LLMRequest.update(request, { model: custom })).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { vendor_reasoning: "thinking" } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "vendor_reasoning" },
- })
- const replay = yield* compileRequest(LLM.request({ model: custom, messages: [response.message] }))
- expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", vendor_reasoning: "thinking" }])
- }),
- )
- it.effect("preserves and replays reasoning details alongside scalar reasoning", () =>
- Effect.gen(function* () {
- const details = [
- { type: "reasoning.text", text: "thinking", format: "anthropic-claude-v1", index: 0 },
- { type: "reasoning.encrypted", data: "opaque", format: "anthropic-claude-v1", index: 1 },
- ]
- const response = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- }),
- ).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning: "thinking", reasoning_details: [details[0]] } }] },
- { choices: [{ delta: { reasoning_details: [details[1]] } }] },
- {
- choices: [
- {
- delta: {
- tool_calls: [
- { index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query":"weather"}' } },
- ],
- },
- finish_reason: "tool_calls",
- },
- ],
- },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: details },
- })
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([
- {
- role: "assistant",
- content: null,
- reasoning: "thinking",
- reasoning_details: details,
- tool_calls: [
- {
- id: "call_1",
- type: "function",
- function: { name: "lookup", arguments: '{"query":"weather"}' },
- },
- ],
- },
- ])
- }),
- )
- it.effect("uses reasoning details as display fallback without inventing a scalar replay field", () =>
- Effect.gen(function* () {
- const details = [
- { type: "reasoning.summary", summary: "thinking", format: "openai-responses-v1", index: 0 },
- { type: "reasoning.encrypted", data: "opaque", format: "openai-responses-v1", index: 1 },
- ]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning_details: [details[0]] } }] },
- { choices: [{ delta: { reasoning_details: [details[1]] } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningDetails: details },
- })
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_details: details }])
- }),
- )
- it.effect("preserves unknown reasoning details while using scalar display text", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.future", format: "provider-v2", state: { opaque: true } }]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning: "thinking", reasoning_details: details } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: details },
- })
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([
- { role: "assistant", content: "Hello", reasoning: "thinking", reasoning_details: details },
- ])
- }),
- )
- it.effect("uses scalar display text for signature-only reasoning details", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.text", signature: "signed", format: "provider-v2", index: 0 }]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning: "thinking", reasoning_details: details } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: details },
- })
- }),
- )
- it.effect("preserves scalar reasoning after content starts", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.text", text: "detail", format: "unknown", index: 0 }]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning_details: details } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: { reasoning: "scalar" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("detailscalar")
- expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(2)
- expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(2)
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: details },
- })
- }),
- )
- it.effect("preserves an explicitly empty reasoning details array", () =>
- Effect.gen(function* () {
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning_details: [] } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("")
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningDetails: [] },
- })
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([{ role: "assistant", content: "Hello", reasoning_details: [] }])
- }),
- )
- it.effect("attaches signature-only details that arrive after content", () =>
- Effect.gen(function* () {
- const details = [
- { type: "reasoning.text", text: "thinking", format: "anthropic-claude-v1", index: 0 },
- { type: "reasoning.text", signature: "signed", format: "anthropic-claude-v1", index: 0 },
- ]
- const merged = [
- {
- type: "reasoning.text",
- text: "thinking",
- signature: "signed",
- format: "anthropic-claude-v1",
- index: 0,
- },
- ]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning: "thinking", reasoning_details: [details[0]] } }] },
- { choices: [{ delta: { content: "Hello" } }] },
- { choices: [{ delta: { reasoning_details: [details[1]] } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("thinking")
- expect(response.message.content.filter((part) => part.type === "reasoning")).toHaveLength(1)
- expect(response.message.content.find((part) => part.type === "reasoning")?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: merged },
- })
- expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
- expect(response.events.filter(LLMEvent.is.reasoningDelta)).toHaveLength(1)
- expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
- expect(response.events.filter(LLMEvent.is.reasoningEnd).at(-1)?.providerMetadata).toEqual({
- openai: { reasoningField: "reasoning", reasoningDetails: merged },
- })
- expect(response.events.findIndex(LLMEvent.is.reasoningEnd)).toBeLessThan(
- response.events.findIndex(LLMEvent.is.textStart),
- )
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([
- { role: "assistant", content: "Hello", reasoning: "thinking", reasoning_details: merged },
- ])
- }),
- )
- it.effect("preserves metadata-only reasoning when the stream ends", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.encrypted", data: "opaque", format: "openai-responses-v1", index: 0 }]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning_details: details } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.message.content).toEqual([
- { type: "reasoning", text: "", providerMetadata: { openai: { reasoningDetails: details } } },
- ])
- expect(response.events.filter(LLMEvent.is.reasoningStart)).toHaveLength(1)
- expect(response.events.filter(LLMEvent.is.reasoningEnd)).toHaveLength(1)
- const replay = yield* compileRequest(LLM.request({ model, messages: [response.message] }))
- expect(replay.body.messages).toEqual([{ role: "assistant", content: "", reasoning_details: details }])
- }),
- )
- it.effect("flushes details-only display reasoning when the stream ends", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.summary", summary: "summary", format: "openai-responses-v1", index: 0 }]
- const response = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse(
- sseEvents(
- { choices: [{ delta: { reasoning_details: details } }] },
- { choices: [{ delta: {}, finish_reason: "stop" }] },
- ),
- ),
- ),
- )
- expect(response.reasoning).toBe("summary")
- expect(response.message.content).toEqual([
- { type: "reasoning", text: "summary", providerMetadata: { openai: { reasoningDetails: details } } },
- ])
- }),
- )
- it.effect("replays details from multiple reasoning parts in order", () =>
- Effect.gen(function* () {
- const first = { type: "reasoning.text", text: "first", signature: "signed-0", index: 0 }
- const second = { type: "reasoning.text", text: "second", signature: "signed-1", index: 1 }
- const replay = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([
- {
- type: "reasoning",
- text: "first",
- providerMetadata: { openai: { reasoningDetails: [first] } },
- },
- {
- type: "reasoning",
- text: "second",
- providerMetadata: { openai: { reasoningField: "reasoning", reasoningDetails: [second] } },
- },
- ]),
- ],
- }),
- )
- expect(replay.body.messages).toEqual([
- { role: "assistant", content: "", reasoning: "firstsecond", reasoning_details: [first, second] },
- ])
- }),
- )
- it.effect("retains scalar replay for mixed structured reasoning parts", () =>
- Effect.gen(function* () {
- const detail = { type: "reasoning.encrypted", data: "opaque", index: 0 }
- const replay = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.assistant([
- {
- type: "reasoning",
- text: "A",
- providerMetadata: { openai: { reasoningDetails: [detail] } },
- },
- { type: "reasoning", text: "B" },
- ]),
- ],
- }),
- )
- expect(replay.body.messages).toEqual([
- { role: "assistant", content: "", reasoning_content: "AB", reasoning_details: [detail] },
- ])
- }),
- )
- it.effect("replays native scalar reasoning alongside native details", () =>
- Effect.gen(function* () {
- const details = [{ type: "reasoning.encrypted", data: "opaque", index: 0 }]
- const replay = yield* compileRequest(
- LLM.request({
- model,
- messages: [
- Message.make({
- role: "assistant",
- content: [{ type: "reasoning", text: "thinking" }],
- native: { openaiCompatible: { reasoning_content: "thinking", reasoning_details: details } },
- }),
- ],
- }),
- )
- expect(replay.body.messages).toEqual([
- { role: "assistant", content: "", reasoning_content: "thinking", reasoning_details: details },
- ])
- }),
- )
- it.effect("assembles streamed tool call input", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({
- role: "assistant",
- tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
- }),
- deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
- deltaChunk({}, "tool_calls"),
- )
- const response = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- }),
- ).pipe(Effect.provide(fixedResponse(body)))
- expect(response.events).toEqual([
- { type: "step-start", index: 0 },
- { type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
- { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
- { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
- { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
- {
- type: "tool-call",
- id: "call_1",
- name: "lookup",
- input: { query: "weather" },
- providerExecuted: undefined,
- providerMetadata: undefined,
- },
- {
- type: "step-finish",
- index: 0,
- reason: { normalized: "tool-calls", raw: "tool_calls" },
- usage: undefined,
- providerMetadata: undefined,
- },
- { type: "finish", reason: { normalized: "tool-calls", raw: "tool_calls" }, usage: undefined },
- ])
- }),
- )
- it.effect("ignores empty identity fields on later tool call deltas", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({
- tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: "{" } }],
- }),
- deltaChunk({
- tool_calls: [{ index: 0, id: "", function: { name: "", arguments: '\"query\":\"weather\"}' } }],
- }),
- deltaChunk({}, "tool_calls"),
- )
- const response = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- }),
- ).pipe(Effect.provide(fixedResponse(body)))
- expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
- }),
- )
- it.effect("buffers tool call deltas until the function name arrives", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({
- tool_calls: [{ index: 0, id: "call_1", function: { arguments: "{" } }],
- }),
- deltaChunk({
- tool_calls: [{ index: 0, function: { name: "lookup", arguments: '\"query\":' } }],
- }),
- deltaChunk({ tool_calls: [{ index: 0, function: { arguments: '\"weather\"}' } }] }),
- deltaChunk({}, "tool_calls"),
- )
- const response = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- }),
- ).pipe(Effect.provide(fixedResponse(body)))
- expect(response.toolCalls).toMatchObject([{ id: "call_1", name: "lookup", input: { query: "weather" } }])
- }),
- )
- it.effect("fails when a buffered tool call never receives a function name", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({
- tool_calls: [{ index: 0, id: "call_1", function: { arguments: "{}" } }],
- }),
- deltaChunk({}, "tool_calls"),
- )
- const error = yield* LLMClient.generate(
- LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- }),
- ).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
- expect(error.message).toContain("OpenAI Chat tool call delta is missing id or name")
- }),
- )
- it.effect("finalizes a streamed tool call when the provider ends without a finish reason", () =>
- Effect.gen(function* () {
- const body = sseEvents(
- deltaChunk({
- role: "assistant",
- tool_calls: [{ index: 0, id: "call_1", function: { name: "lookup", arguments: '{"query"' } }],
- }),
- deltaChunk({ tool_calls: [{ index: 0, function: { arguments: ':"weather"}' } }] }),
- )
- const input = LLMRequest.update(request, {
- tools: [ToolDefinition.make({ name: "lookup", description: "Lookup data", inputSchema: { type: "object" } })],
- })
- const response = yield* LLMClient.generate(input).pipe(Effect.provide(fixedResponse(body)))
- expect(response.events).toEqual([
- { type: "step-start", index: 0 },
- { type: "tool-input-start", id: "call_1", name: "lookup", providerMetadata: undefined },
- { type: "tool-input-delta", id: "call_1", name: "lookup", text: '{"query"' },
- { type: "tool-input-delta", id: "call_1", name: "lookup", text: ':"weather"}' },
- { type: "tool-input-end", id: "call_1", name: "lookup", providerMetadata: undefined },
- {
- type: "tool-call",
- id: "call_1",
- name: "lookup",
- input: { query: "weather" },
- providerExecuted: undefined,
- providerMetadata: undefined,
- },
- {
- type: "step-finish",
- index: 0,
- reason: { normalized: "tool-calls" },
- usage: undefined,
- providerMetadata: undefined,
- },
- { type: "finish", reason: { normalized: "tool-calls" }, usage: undefined },
- ])
- }),
- )
- it.effect("fails on malformed stream events", () =>
- Effect.gen(function* () {
- const body = sseEvents(deltaChunk({ content: 123 }))
- const error = yield* LLMClient.generate(request).pipe(Effect.provide(fixedResponse(body)), Effect.flip)
- expect(error.message).toContain("Invalid openai/openai-chat stream event")
- }),
- )
- it.effect("surfaces transport errors that occur mid-stream", () =>
- Effect.gen(function* () {
- const layer = truncatedStream(
- [`data: ${JSON.stringify(deltaChunk({ role: "assistant", content: "Hello" }))}\n\n`],
- systemError("ECONNRESET", "socket closed unexpectedly"),
- )
- const events = yield* Ref.make<ReadonlyArray<LLMEvent>>([])
- const error = yield* LLMClient.stream(request).pipe(
- Stream.tap((event) => Ref.update(events, (current) => [...current, event])),
- Stream.runDrain,
- Effect.provide(layer),
- Effect.flip,
- )
- expect((yield* Ref.get(events)).some((event) => event.type === "text-delta")).toBeTrue()
- expect(error.reason).toMatchObject({
- _tag: "Transport",
- message: "ECONNRESET: socket closed unexpectedly",
- transport: "http",
- operation: "read",
- code: "ECONNRESET",
- url: "https://api.openai.test/v1/chat/completions",
- })
- }),
- )
- it.effect("surfaces transport errors before the first stream frame", () =>
- Effect.gen(function* () {
- const error = yield* LLMClient.generate(request).pipe(
- Effect.provide(truncatedStream([], systemError("ECONNRESET", "socket closed before output"))),
- Effect.flip,
- )
- expect(error.reason).toMatchObject({
- _tag: "Transport",
- message: "ECONNRESET: socket closed before output",
- transport: "http",
- operation: "read",
- code: "ECONNRESET",
- })
- }),
- )
- it.effect("fails HTTP provider errors before stream parsing", () =>
- Effect.gen(function* () {
- const error = yield* LLMClient.generate(request).pipe(
- Effect.provide(
- fixedResponse('{"error":{"message":"Bad request","type":"invalid_request_error"}}', {
- status: 400,
- headers: { "content-type": "application/json" },
- }),
- ),
- Effect.flip,
- )
- expect(error).toBeInstanceOf(AIError)
- expect(error.reason).toMatchObject({ _tag: "InvalidRequest", message: "Bad request" })
- }),
- )
- it.effect("short-circuits the upstream stream when the consumer takes a prefix", () =>
- Effect.gen(function* () {
- // The body has more chunks than we'll consume. If `Stream.take(1)` did
- // not interrupt the upstream HTTP body the test would hang waiting for
- // the rest of the stream to drain.
- const body = sseEvents(
- deltaChunk({ role: "assistant", content: "Hello" }),
- deltaChunk({ content: " world" }),
- deltaChunk({}, "stop"),
- )
- const events = Array.from(
- yield* LLMClient.stream(request).pipe(Stream.take(1), Stream.runCollect, Effect.provide(fixedResponse(body))),
- )
- expect(events.map((event) => event.type)).toEqual(["step-start"])
- }),
- )
- })
|