@effect-uai/chat-completions 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,18 +18,18 @@ Groq, Together, or a self-hosted gateway.
18
18
  pnpm add @effect-uai/chat-completions @effect-uai/core effect
19
19
  ```
20
20
 
21
- ESM-only. Requires `effect@4.x` and `@effect-uai/core` as peers.
21
+ ESM-only. Requires `effect@>=4.0.1` and `@effect-uai/core` as peers.
22
22
 
23
23
  ## Usage
24
24
 
25
25
  ```ts
26
26
  import { Config, Effect, Layer } from "effect"
27
- import { FetchHttpClient } from "effect/unstable/http"
27
+ import { FetchHttpClient } from "effect/http"
28
28
  import { layer as chatLayer } from "@effect-uai/chat-completions/ChatCompletions"
29
29
 
30
30
  const provider = Layer.unwrap(
31
31
  Effect.gen(function* () {
32
- const apiKey = yield* Config.redacted("LLM_API_KEY")
32
+ const apiKey = yield* Config.Redacted("LLM_API_KEY")
33
33
  return chatLayer({
34
34
  apiKey,
35
35
  baseUrl: "https://openrouter.ai/api/v1",
@@ -1,5 +1,5 @@
1
1
  import { Effect, Layer, Redacted } from "effect";
2
- import { HttpClient, HttpClientRequest } from "effect/unstable/http";
2
+ import { HttpClient, HttpClientRequest } from "effect/http";
3
3
  import { CommonRequest, LanguageModel, LanguageModelService } from "@effect-uai/core/LanguageModel";
4
4
  declare namespace ChatCompletions_d_exports {
5
5
  export { ChatConfig, layer, make };
@@ -2,7 +2,7 @@ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
2
  import { accumulatorToTurn, applyChunk, decodeChunk, emptyAccumulator, itemsToMessages, responseFormatWire, toolChoiceWire, toolsWire } from "./codec.mjs";
3
3
  import { httpStatusError, transportFailure } from "./http.mjs";
4
4
  import { Effect, Layer, Option, Result, Schema, Stream } from "effect";
5
- import { HttpClient, HttpClientRequest } from "effect/unstable/http";
5
+ import { HttpClient, HttpClientRequest } from "effect/http";
6
6
  import * as AiError from "@effect-uai/core/AiError";
7
7
  import * as Capabilities from "@effect-uai/core/Capabilities";
8
8
  import { LanguageModel, turnFromStream } from "@effect-uai/core/LanguageModel";
@@ -1 +1 @@
1
- {"version":3,"file":"ChatCompletions.mjs","names":[],"sources":["../src/ChatCompletions.ts"],"sourcesContent":["import { Effect, Layer, Option, Redacted, Result, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport {\n type CommonRequest,\n LanguageModel,\n type LanguageModelService,\n turnFromStream,\n} from \"@effect-uai/core/LanguageModel\"\nimport * as SSE from \"@effect-uai/core/SSE\"\nimport { descriptorsOf } from \"@effect-uai/core/Tool\"\nimport { TurnEvent } from \"@effect-uai/core/Turn\"\nimport {\n type Accumulator,\n type WireChunk,\n accumulatorToTurn,\n applyChunk,\n decodeChunk,\n emptyAccumulator,\n itemsToMessages,\n responseFormatWire,\n toolChoiceWire,\n toolsWire,\n} from \"./codec.js\"\nimport { httpStatusError, transportFailure } from \"./http.js\"\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport type ChatConfig = {\n readonly apiKey: Redacted.Redacted\n /** Provider base URL, e.g. `https://openrouter.ai/api/v1`. No trailing slash. */\n readonly baseUrl: string\n /** Name used to tag `AiError`s from this provider. */\n readonly provider: string\n /** Request path appended to `baseUrl`. Defaults to `/chat/completions`. */\n readonly path?: string\n /**\n * Override the auth header. Defaults to `Authorization: Bearer <apiKey>`.\n * Supply this for gateways that authenticate differently (e.g. Azure `api-key`).\n */\n readonly authHeader?: (\n request: HttpClientRequest.HttpClientRequest,\n ) => HttpClientRequest.HttpClientRequest\n /** Extra headers merged into every request (e.g. OpenRouter `HTTP-Referer`). */\n readonly extraHeaders?: Record<string, string>\n /** Provider-specific request-body fields merged into the wire body. */\n readonly extraBody?: (request: CommonRequest) => Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Request body\n// ---------------------------------------------------------------------------\n\nconst buildRequestBody = (cfg: ChatConfig, request: CommonRequest): Record<string, unknown> => {\n const tools = toolsWire(descriptorsOf(request.tools))\n return {\n model: request.model,\n stream: true,\n messages: itemsToMessages(request.history),\n ...(request.temperature !== undefined && { temperature: request.temperature }),\n ...(request.topP !== undefined && { top_p: request.topP }),\n ...(request.maxOutputTokens !== undefined && { max_tokens: request.maxOutputTokens }),\n ...(Option.isSome(tools) && { tools: tools.value }),\n ...(request.toolChoice !== undefined && { tool_choice: toolChoiceWire(request.toolChoice) }),\n ...(request.structured !== undefined && {\n response_format: responseFormatWire(request.structured),\n }),\n ...(cfg.extraBody?.(request) ?? {}),\n }\n}\n\n// ---------------------------------------------------------------------------\n// SSE → WireChunk\n// ---------------------------------------------------------------------------\n\nconst parseJsonUnknown = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))\n\n/**\n * Decode one SSE event's `data` payload into a `WireChunk`. Returns `None` for\n * the `[DONE]` sentinel and for any payload that isn't a chunk we model, so a\n * stray keep-alive never aborts the turn.\n */\nconst decodeEvent = (data: string): Effect.Effect<Option.Option<WireChunk>> =>\n data.trim() === \"[DONE]\"\n ? Effect.succeedNone\n : parseJsonUnknown(data).pipe(Effect.flatMap(decodeChunk), Effect.option)\n\n// ---------------------------------------------------------------------------\n// Stream\n// ---------------------------------------------------------------------------\n\nconst buildStream = (cfg: ChatConfig) => {\n const url = `${cfg.baseUrl}${cfg.path ?? \"/chat/completions\"}`\n const auth = cfg.authHeader ?? HttpClientRequest.bearerToken(cfg.apiKey)\n return (\n request: CommonRequest,\n ): Stream.Stream<TurnEvent, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n yield* Capabilities.warnDroppedBlocks(request.history, \"output_image\", {\n provider: cfg.provider,\n capability: \"output_image\",\n reason:\n \"Assistant messages carry no image on this wire. Use `Turn.imagesAsInput` to resend it as user content.\",\n })\n const httpRequest = HttpClientRequest.post(url).pipe(\n auth,\n HttpClientRequest.setHeaders(cfg.extraHeaders ?? {}),\n HttpClientRequest.bodyJsonUnsafe(buildRequestBody(cfg, request)),\n HttpClientRequest.accept(\"text/event-stream\"),\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError((cause) => transportFailure(cfg.provider, cause)))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return Stream.fail(httpStatusError(cfg.provider, response.status, text))\n }\n\n return response.stream.pipe(\n Stream.mapError(\n (cause): AiError.AiError =>\n new AiError.Unavailable({ provider: cfg.provider, raw: cause }),\n ),\n SSE.fromBytes,\n Stream.mapEffect((ev) => decodeEvent(ev.data)),\n Stream.filterMap((chunk) =>\n Option.isSome(chunk) ? Result.succeed(chunk.value) : Result.failVoid,\n ),\n Stream.mapAccum((): Accumulator => emptyAccumulator, applyChunk, {\n // `onHalt` also fires on upstream failure and truncated streams, so\n // only emit `TurnComplete` once a `finish_reason` was observed.\n onHalt: (acc) =>\n Option.isSome(acc.finishReason)\n ? [TurnEvent.TurnComplete({ turn: accumulatorToTurn(acc) })]\n : [],\n }),\n )\n }),\n )\n}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/** Build a generic chat-completions `LanguageModelService`. */\nexport const make = (\n cfg: ChatConfig,\n): Effect.Effect<LanguageModelService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => {\n const streamTurn: LanguageModelService[\"streamTurn\"] = (request) =>\n buildStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client))\n return {\n streamTurn,\n turn: turnFromStream(streamTurn),\n }\n })\n\n/** Layer registering the generic `LanguageModel` tag for a compatible gateway. */\nexport const layer = (cfg: ChatConfig): Layer.Layer<LanguageModel, never, HttpClient.HttpClient> =>\n Layer.effect(LanguageModel, make(cfg))\n"],"mappings":";;;;;;;;;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,CAAC,CAAC,GACnD,kBAAkB,eAAe,iBAAiB,KAAK,OAAO,CAAC,GAC/D,kBAAkB,OAAO,mBAAmB,CAC9C;EACA,MAAM,WAAW,OAAO,OACrB,QAAQ,WAAW,CAAC,CACpB,KAAK,OAAO,UAAU,UAAU,iBAAiB,IAAI,UAAU,KAAK,CAAC,CAAC;EACzE,IAAI,SAAS,UAAU,KAAK;GAC1B,MAAM,OAAO,OAAO,SAAS,KAAK,KAAK,OAAO,oBAAoB,EAAE,CAAC;GACrE,OAAO,OAAO,KAAK,gBAAgB,IAAI,UAAU,SAAS,QAAQ,IAAI,CAAC;EACzE;EAEA,OAAO,SAAS,OAAO,KACrB,OAAO,UACJ,UACC,IAAI,QAAQ,YAAY;GAAE,UAAU,IAAI;GAAU,KAAK;EAAM,CAAC,CAClE,GACA,IAAI,WACJ,OAAO,WAAW,OAAO,YAAY,GAAG,IAAI,CAAC,GAC7C,OAAO,WAAW,UAChB,OAAO,OAAO,KAAK,IAAI,OAAO,QAAQ,MAAM,KAAK,IAAI,OAAO,QAC9D,GACA,OAAO,eAA4B,kBAAkB,YAAY,EAG/D,SAAS,QACP,OAAO,OAAO,IAAI,YAAY,IAC1B,CAAC,UAAU,aAAa,EAAE,MAAM,kBAAkB,GAAG,EAAE,CAAC,CAAC,IACzD,CAAC,EACT,CAAC,CACH;CACF,CAAC,CACH;AACJ;;AAOA,MAAa,QACX,QAEA,OAAO,IAAI,WAAW,aAAa,WAAW;CAC5C,MAAM,cAAkD,YACtD,YAAY,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,KAAK,OAAO,eAAe,WAAW,YAAY,MAAM,CAAC;CACrF,OAAO;EACL;EACA,MAAM,eAAe,UAAU;CACjC;AACF,CAAC;;AAGH,MAAa,SAAS,QACpB,MAAM,OAAO,eAAe,KAAK,GAAG,CAAC"}
1
+ {"version":3,"file":"ChatCompletions.mjs","names":[],"sources":["../src/ChatCompletions.ts"],"sourcesContent":["import { Effect, Layer, Option, Redacted, Result, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport {\n type CommonRequest,\n LanguageModel,\n type LanguageModelService,\n turnFromStream,\n} from \"@effect-uai/core/LanguageModel\"\nimport * as SSE from \"@effect-uai/core/SSE\"\nimport { descriptorsOf } from \"@effect-uai/core/Tool\"\nimport { TurnEvent } from \"@effect-uai/core/Turn\"\nimport {\n type Accumulator,\n type WireChunk,\n accumulatorToTurn,\n applyChunk,\n decodeChunk,\n emptyAccumulator,\n itemsToMessages,\n responseFormatWire,\n toolChoiceWire,\n toolsWire,\n} from \"./codec.js\"\nimport { httpStatusError, transportFailure } from \"./http.js\"\n\n// ---------------------------------------------------------------------------\n// Config\n// ---------------------------------------------------------------------------\n\nexport type ChatConfig = {\n readonly apiKey: Redacted.Redacted\n /** Provider base URL, e.g. `https://openrouter.ai/api/v1`. No trailing slash. */\n readonly baseUrl: string\n /** Name used to tag `AiError`s from this provider. */\n readonly provider: string\n /** Request path appended to `baseUrl`. Defaults to `/chat/completions`. */\n readonly path?: string\n /**\n * Override the auth header. Defaults to `Authorization: Bearer <apiKey>`.\n * Supply this for gateways that authenticate differently (e.g. Azure `api-key`).\n */\n readonly authHeader?: (\n request: HttpClientRequest.HttpClientRequest,\n ) => HttpClientRequest.HttpClientRequest\n /** Extra headers merged into every request (e.g. OpenRouter `HTTP-Referer`). */\n readonly extraHeaders?: Record<string, string>\n /** Provider-specific request-body fields merged into the wire body. */\n readonly extraBody?: (request: CommonRequest) => Record<string, unknown>\n}\n\n// ---------------------------------------------------------------------------\n// Request body\n// ---------------------------------------------------------------------------\n\nconst buildRequestBody = (cfg: ChatConfig, request: CommonRequest): Record<string, unknown> => {\n const tools = toolsWire(descriptorsOf(request.tools))\n return {\n model: request.model,\n stream: true,\n messages: itemsToMessages(request.history),\n ...(request.temperature !== undefined && { temperature: request.temperature }),\n ...(request.topP !== undefined && { top_p: request.topP }),\n ...(request.maxOutputTokens !== undefined && { max_tokens: request.maxOutputTokens }),\n ...(Option.isSome(tools) && { tools: tools.value }),\n ...(request.toolChoice !== undefined && { tool_choice: toolChoiceWire(request.toolChoice) }),\n ...(request.structured !== undefined && {\n response_format: responseFormatWire(request.structured),\n }),\n ...(cfg.extraBody?.(request) ?? {}),\n }\n}\n\n// ---------------------------------------------------------------------------\n// SSE → WireChunk\n// ---------------------------------------------------------------------------\n\nconst parseJsonUnknown = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))\n\n/**\n * Decode one SSE event's `data` payload into a `WireChunk`. Returns `None` for\n * the `[DONE]` sentinel and for any payload that isn't a chunk we model, so a\n * stray keep-alive never aborts the turn.\n */\nconst decodeEvent = (data: string): Effect.Effect<Option.Option<WireChunk>> =>\n data.trim() === \"[DONE]\"\n ? Effect.succeedNone\n : parseJsonUnknown(data).pipe(Effect.flatMap(decodeChunk), Effect.option)\n\n// ---------------------------------------------------------------------------\n// Stream\n// ---------------------------------------------------------------------------\n\nconst buildStream = (cfg: ChatConfig) => {\n const url = `${cfg.baseUrl}${cfg.path ?? \"/chat/completions\"}`\n const auth = cfg.authHeader ?? HttpClientRequest.bearerToken(cfg.apiKey)\n return (\n request: CommonRequest,\n ): Stream.Stream<TurnEvent, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n yield* Capabilities.warnDroppedBlocks(request.history, \"output_image\", {\n provider: cfg.provider,\n capability: \"output_image\",\n reason:\n \"Assistant messages carry no image on this wire. Use `Turn.imagesAsInput` to resend it as user content.\",\n })\n const httpRequest = HttpClientRequest.post(url).pipe(\n auth,\n HttpClientRequest.setHeaders(cfg.extraHeaders ?? {}),\n HttpClientRequest.bodyJsonUnsafe(buildRequestBody(cfg, request)),\n HttpClientRequest.accept(\"text/event-stream\"),\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(Effect.mapError((cause) => transportFailure(cfg.provider, cause)))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return Stream.fail(httpStatusError(cfg.provider, response.status, text))\n }\n\n return response.stream.pipe(\n Stream.mapError(\n (cause): AiError.AiError =>\n new AiError.Unavailable({ provider: cfg.provider, raw: cause }),\n ),\n SSE.fromBytes,\n Stream.mapEffect((ev) => decodeEvent(ev.data)),\n Stream.filterMap((chunk) =>\n Option.isSome(chunk) ? Result.succeed(chunk.value) : Result.failVoid,\n ),\n Stream.mapAccum((): Accumulator => emptyAccumulator, applyChunk, {\n // `onHalt` also fires on upstream failure and truncated streams, so\n // only emit `TurnComplete` once a `finish_reason` was observed.\n onHalt: (acc) =>\n Option.isSome(acc.finishReason)\n ? [TurnEvent.TurnComplete({ turn: accumulatorToTurn(acc) })]\n : [],\n }),\n )\n }),\n )\n}\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/** Build a generic chat-completions `LanguageModelService`. */\nexport const make = (\n cfg: ChatConfig,\n): Effect.Effect<LanguageModelService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => {\n const streamTurn: LanguageModelService[\"streamTurn\"] = (request) =>\n buildStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client))\n return {\n streamTurn,\n turn: turnFromStream(streamTurn),\n }\n })\n\n/** Layer registering the generic `LanguageModel` tag for a compatible gateway. */\nexport const layer = (cfg: ChatConfig): Layer.Layer<LanguageModel, never, HttpClient.HttpClient> =>\n Layer.effect(LanguageModel, make(cfg))\n"],"mappings":";;;;;;;;;;;;;;;;AAwDA,MAAM,oBAAoB,KAAiB,YAAoD;CAC7F,MAAM,QAAQ,UAAU,cAAc,QAAQ,KAAK,CAAC;CACpD,OAAO;EACL,OAAO,QAAQ;EACf,QAAQ;EACR,UAAU,gBAAgB,QAAQ,OAAO;EACzC,GAAI,QAAQ,gBAAgB,KAAA,KAAa,EAAE,aAAa,QAAQ,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;;;;;;;;;;;;;;;;;;;;;KAIV,mBAAmB,UAAU;cAE5B,cAAW,gBAAA,qCAAA,yCAAA;;;;;;;;;;;;;;;;;;;;;;GAAwC,OAAA;KAM3D;WACM;WACA;WACA;;KAGC;WACD;;WAEA,OAAO,oBAAoB;WAC3B,OAAO;WACP,OAAO;WACP,cAAc,OAAO;;cAGnB,kBAAkB;;KAS1B,iBAAiB,aAAa,cAAc;;;;;cAqFpC,aAAU,KAAS,aAAW,OAAS,cAAY;;cAYnD,oBAAiB,KAAS,gBAAc"}
1
+ {"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;KAyBK;EACH;EACA,kBAAkB,cAAc;EAChC,aAAa,cAAc;EAC3B;;;cAgFW,kBAAe,OAAW,cAAc,iBAAe,cAAc;cAOrE,YAAS,aACP,cAAc,oBAC1B,OAAO,OAAO,cAAc;KAe1B;WAIU;WAA2B;;cAE7B,iBAAc,QAAY,wBAAsB;cAQhD,qBAAkB,YACjB,8BACX;cA0CU,WAAS,OAAA;;;;;;;;;;;;;;;;;;;;;;;KAIV,mBAAmB,UAAU;cAE5B,cAAW,gBAAA,qCAAA,yCAAA;;;;;;;;;;;;;;;;;;;;;;GAAwC,OAAA;KAM3D;WACM;WACA;WACA;;KAGC;WACD;;WAEA,OAAO,oBAAoB;WAC3B,OAAO;WACP,OAAO;WACP,cAAc,OAAO;;cAGnB,kBAAkB;;KAS1B,iBAAiB,aAAa,cAAc;;;;;cAqFpC,aAAU,KAAS,aAAW,OAAS,cAAY;;cAYnD,oBAAiB,KAAS,gBAAc"}
package/dist/codec.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
2
- import { Array, Encoding, Match, Option, Result, Schema } from "effect";
2
+ import { Array, Match, Option, Result, Schema } from "effect";
3
3
  import { TurnEvent } from "@effect-uai/core/Turn";
4
+ import { Base64 } from "effect/encoding";
4
5
  //#region src/codec.ts
5
6
  var codec_exports = /* @__PURE__ */ __exportAll({
6
7
  WireChunk: () => WireChunk,
@@ -14,7 +15,7 @@ var codec_exports = /* @__PURE__ */ __exportAll({
14
15
  toolsWire: () => toolsWire
15
16
  });
16
17
  /** A `data:` URI for inline image bytes; URLs pass through untouched. */
17
- const imageSourceToUrl = Match.type().pipe(Match.tag("url", (s) => s.url), Match.tag("base64", (s) => `data:${s.mimeType};base64,${s.base64}`), Match.tag("bytes", (s) => `data:${s.mimeType};base64,${Encoding.encodeBase64(s.bytes)}`), Match.exhaustive);
18
+ const imageSourceToUrl = Match.type().pipe(Match.tag("url", (s) => s.url), Match.tag("base64", (s) => `data:${s.mimeType};base64,${s.base64}`), Match.tag("bytes", (s) => `data:${s.mimeType};base64,${Base64.encode(s.bytes)}`), Match.exhaustive);
18
19
  const blockToPart = Match.type().pipe(Match.discriminatorsExhaustive("type")({
19
20
  input_text: (b) => ({
20
21
  type: "text",
@@ -1 +1 @@
1
- {"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, Result, Schema } from \"effect\"\nimport type {\n ContentBlock,\n HistoryItem,\n InputImage,\n StopReason,\n Usage,\n} from \"@effect-uai/core/Items\"\nimport type { StructuredFormat } from \"@effect-uai/core/StructuredFormat\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport { TurnEvent } from \"@effect-uai/core/Turn\"\n\n// ---------------------------------------------------------------------------\n// History → chat `messages`\n//\n// The OpenAI Chat Completions dialect: a flat list of `{ role, content, ... }`\n// objects where an assistant turn's tool calls live on the assistant message\n// (`tool_calls`) and each tool result is its own\n// `{ role: \"tool\", tool_call_id, content }` message. Our history is a flatter\n// item list (assistant message, then separate `function_call` items), so we\n// fold consecutive `function_call`s onto the preceding assistant message.\n// ---------------------------------------------------------------------------\n\ntype WireMessage = {\n role: string\n content: string | ReadonlyArray<Record<string, unknown>>\n tool_calls?: ReadonlyArray<Record<string, unknown>>\n tool_call_id?: string\n}\n\n/** A `data:` URI for inline image bytes; URLs pass through untouched. */\nconst imageSourceToUrl = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (s) => s.url),\n Match.tag(\"base64\", (s) => `data:${s.mimeType};base64,${s.base64}`),\n Match.tag(\"bytes\", (s) => `data:${s.mimeType};base64,${Encoding.encodeBase64(s.bytes)}`),\n Match.exhaustive,\n)\n\nconst blockToPart = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"text\", text: b.text }),\n output_text: (b) => ({ type: \"text\", text: b.text }),\n refusal: (b) => ({ type: \"text\", text: b.text }),\n input_image: (b) => ({ type: \"image_url\", image_url: { url: imageSourceToUrl(b.source) } }),\n // No assistant-image part here. Dropped rather than relocated onto a\n // user message, which is the caller's call: `Turn.imagesAsInput`.\n output_image: () => undefined,\n }),\n)\n\nconst isTextBlock = (b: ContentBlock): boolean =>\n b.type === \"input_text\" || b.type === \"output_text\" || b.type === \"refusal\"\n\nconst textOfBlock = (b: ContentBlock): string =>\n b.type === \"input_image\" || b.type === \"output_image\" ? \"\" : b.text\n\n/**\n * Collapse a message's content to a plain string when it is text-only (the\n * common case), otherwise emit the multimodal parts array.\n */\nconst encodeContent = (\n content: ReadonlyArray<ContentBlock>,\n): string | ReadonlyArray<Record<string, unknown>> =>\n Arr.every(content, isTextBlock)\n ? content.map(textOfBlock).join(\"\")\n : Arr.filterMap(content, (b) => {\n const part = blockToPart(b)\n return part === undefined ? Result.failVoid : Result.succeed(part)\n })\n\nconst toolCallWire = (call_id: string, name: string, args: string): Record<string, unknown> => ({\n id: call_id,\n type: \"function\",\n function: { name, arguments: args },\n})\n\nconst appendToolCall = (\n acc: ReadonlyArray<WireMessage>,\n call_id: string,\n name: string,\n args: string,\n): ReadonlyArray<WireMessage> => {\n const last = acc[acc.length - 1]\n const wire = toolCallWire(call_id, name, args)\n // Attach to the immediately-preceding assistant message (not a tool result),\n // matching the shape where tool calls ride the assistant turn.\n if (last !== undefined && last.role === \"assistant\" && last.tool_call_id === undefined) {\n return [...acc.slice(0, -1), { ...last, tool_calls: [...(last.tool_calls ?? []), wire] }]\n }\n return [...acc, { role: \"assistant\", content: \"\", tool_calls: [wire] }]\n}\n\nconst foldItem = (acc: ReadonlyArray<WireMessage>, item: HistoryItem): ReadonlyArray<WireMessage> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => [...acc, { role: m.role, content: encodeContent(m.content) }],\n function_call: (f) => appendToolCall(acc, f.call_id, f.name, f.arguments),\n function_call_output: (o) => [\n ...acc,\n { role: \"tool\", tool_call_id: o.call_id, content: o.output },\n ],\n // Reasoning items are not replayed to the chat-completions endpoint.\n reasoning: () => acc,\n }),\n )\n\n/** Convert our `HistoryItem[]` history into chat `messages`. */\nexport const itemsToMessages = (items: ReadonlyArray<HistoryItem>): ReadonlyArray<WireMessage> =>\n Arr.reduce(items, [] as ReadonlyArray<WireMessage>, foldItem)\n\n// ---------------------------------------------------------------------------\n// tools / tool_choice / response_format\n// ---------------------------------------------------------------------------\n\nexport const toolsWire = (\n descriptors: ReadonlyArray<ToolDescriptor>,\n): Option.Option<ReadonlyArray<Record<string, unknown>>> =>\n descriptors.length > 0\n ? Option.some(\n descriptors.map((t) => ({\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict !== undefined && { strict: t.strict }),\n },\n })),\n )\n : Option.none()\n\ntype ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | { readonly type: \"function\"; readonly name: string }\n\nexport const toolChoiceWire = (choice: ToolChoice): string | Record<string, unknown> =>\n Match.value(choice).pipe(\n Match.when(\"auto\", () => \"auto\" as const),\n Match.when(\"required\", () => \"required\" as const),\n Match.when(\"none\", () => \"none\" as const),\n Match.orElse((c) => ({ type: \"function\", function: { name: c.name } })),\n )\n\nexport const responseFormatWire = (\n structured: StructuredFormat<unknown>,\n): Record<string, unknown> => ({\n type: \"json_schema\",\n json_schema: {\n name: structured.name,\n schema: structured.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n ...(structured.strict !== undefined && { strict: structured.strict }),\n },\n})\n\n// ---------------------------------------------------------------------------\n// Streaming decode: chat.completion.chunk → TurnEvent\n// ---------------------------------------------------------------------------\n\nconst WireFunction = Schema.Struct({\n name: Schema.optional(Schema.NullOr(Schema.String)),\n arguments: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireToolCall = Schema.Struct({\n index: Schema.optional(Schema.Number),\n id: Schema.optional(Schema.NullOr(Schema.String)),\n function: Schema.optional(WireFunction),\n})\n\nconst WireDelta = Schema.Struct({\n role: Schema.optional(Schema.NullOr(Schema.String)),\n content: Schema.optional(Schema.NullOr(Schema.String)),\n tool_calls: Schema.optional(Schema.NullOr(Schema.Array(WireToolCall))),\n})\n\nconst WireChoice = Schema.Struct({\n index: Schema.optional(Schema.Number),\n delta: Schema.optional(WireDelta),\n finish_reason: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireUsage = Schema.Struct({\n prompt_tokens: Schema.optional(Schema.Number),\n completion_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n choices: Schema.optional(Schema.Array(WireChoice)),\n usage: Schema.optional(Schema.NullOr(WireUsage)),\n})\nexport type WireChunk = typeof WireChunk.Type\n\nexport const decodeChunk = Schema.decodeUnknownEffect(WireChunk)\n\n// ---------------------------------------------------------------------------\n// Accumulator\n// ---------------------------------------------------------------------------\n\ntype ToolAcc = {\n readonly call_id: string\n readonly name: string\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n /** Tool calls keyed by their wire `index` (defaults to position when absent). */\n readonly tools: ReadonlyMap<number, ToolAcc>\n readonly order: ReadonlyArray<number>\n readonly usage: Usage\n readonly finishReason: Option.Option<string>\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n tools: new Map(),\n order: [],\n usage: {},\n finishReason: Option.none(),\n}\n\n/** State threaded through the fold plus the events the step produced. */\ntype Step = readonly [Accumulator, ReadonlyArray<TurnEvent>]\n\nconst usageFrom = (wire: typeof WireUsage.Type): Usage => ({\n ...(wire.prompt_tokens !== undefined && { input_tokens: wire.prompt_tokens }),\n ...(wire.completion_tokens !== undefined && { output_tokens: wire.completion_tokens }),\n ...(wire.total_tokens !== undefined && { total_tokens: wire.total_tokens }),\n})\n\nconst reasonToStop = Match.type<string>().pipe(\n Match.when(\"stop\", () => \"stop\" as const),\n Match.when(\"length\", () => \"max_tokens\" as const),\n Match.when(\"tool_calls\", () => \"tool_calls\" as const),\n Match.when(\"content_filter\", () => \"content_filter\" as const),\n Match.orElse(() => \"stop\" as const),\n)\n\nconst stopReasonOf = (acc: Accumulator): StopReason =>\n Option.match(acc.finishReason, {\n onNone: () => (acc.tools.size > 0 ? \"tool_calls\" : \"stop\"),\n onSome: reasonToStop,\n })\n\nconst withTool = (acc: Accumulator, index: number, tool: ToolAcc, isNew: boolean): Accumulator => ({\n ...acc,\n tools: new Map(acc.tools).set(index, tool),\n order: isNew ? [...acc.order, index] : acc.order,\n})\n\nconst applyContent = (acc: Accumulator, delta: typeof WireDelta.Type | undefined): Step => {\n const content = delta?.content\n return content !== undefined && content !== null && content.length > 0\n ? [{ ...acc, text: acc.text + content }, [TurnEvent.TextDelta({ text: content })]]\n : [acc, []]\n}\n\nconst applyToolCall = (acc: Accumulator, tc: typeof WireToolCall.Type, position: number): Step => {\n const index = tc.index ?? position\n const argsDelta = tc.function?.arguments ?? \"\"\n const existing = acc.tools.get(index)\n if (existing === undefined) {\n // Only `index` is guaranteed on a streaming tool-call chunk, so the id may\n // be absent. The synthesised fallback is 9-char alphanumeric: valid on every\n // chat-completions wire (Mistral additionally requires `^[a-zA-Z0-9]{9}$`),\n // and it is replayed on the next turn.\n const call_id = tc.id ?? String(index).padStart(9, \"0\")\n const name = tc.function?.name ?? \"\"\n return [\n withTool(acc, index, { call_id, name, arguments: argsDelta }, true),\n [\n TurnEvent.ToolCallStart({ call_id, name }),\n ...(argsDelta.length > 0\n ? [TurnEvent.ToolCallArgsDelta({ call_id, delta: argsDelta })]\n : []),\n ],\n ]\n }\n return argsDelta.length > 0\n ? [\n withTool(acc, index, { ...existing, arguments: existing.arguments + argsDelta }, false),\n [TurnEvent.ToolCallArgsDelta({ call_id: existing.call_id, delta: argsDelta })],\n ]\n : [acc, []]\n}\n\nconst chain = (step: Step, next: (acc: Accumulator) => Step): Step => {\n const [acc, events] = step\n const [acc2, more] = next(acc)\n return [acc2, [...events, ...more]]\n}\n\nconst applyChoice = (step: Step, choice: typeof WireChoice.Type): Step => {\n const withContent = chain(step, (acc) => applyContent(acc, choice.delta))\n const withTools = Arr.reduce(choice.delta?.tool_calls ?? [], withContent, (s: Step, tc, i) =>\n chain(s, (acc) => applyToolCall(acc, tc, i)),\n )\n const reason = choice.finish_reason\n return reason !== undefined && reason !== null\n ? [{ ...withTools[0], finishReason: Option.some(reason) }, withTools[1]]\n : withTools\n}\n\n/**\n * Fold one decoded chunk into the accumulator, returning the next state and the\n * `TurnEvent`s the chunk produced.\n */\nexport const applyChunk = (acc: Accumulator, chunk: WireChunk): Step => {\n const afterChoices = Arr.reduce(chunk.choices ?? [], [acc, []] as Step, applyChoice)\n const usage = chunk.usage\n return usage !== undefined && usage !== null\n ? chain(afterChoices, (a) => {\n const u = usageFrom(usage)\n return [{ ...a, usage: u }, [TurnEvent.UsageUpdate({ usage: u })]]\n })\n : afterChoices\n}\n\n/** Assemble the terminal `Turn` from the accumulated state. */\nexport const accumulatorToTurn = (acc: Accumulator): Turn => {\n const message: ReadonlyArray<HistoryItem> =\n acc.text.length > 0\n ? [{ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: acc.text }] }]\n : []\n const toolCalls: ReadonlyArray<HistoryItem> = acc.order.flatMap((index) => {\n const t = acc.tools.get(index)\n return t === undefined\n ? []\n : [\n {\n type: \"function_call\" as const,\n call_id: t.call_id,\n name: t.name,\n arguments: t.arguments,\n },\n ]\n })\n return {\n items: [...message, ...toolCalls],\n usage: acc.usage,\n stop_reason: stopReasonOf(acc),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,mBAAmB,MAAM,KAA2B,CAAC,CAAC,KAC1D,MAAM,IAAI,QAAQ,MAAM,EAAE,GAAG,GAC7B,MAAM,IAAI,WAAW,MAAM,QAAQ,EAAE,SAAS,UAAU,EAAE,QAAQ,GAClE,MAAM,IAAI,UAAU,MAAM,QAAQ,EAAE,SAAS,UAAU,SAAS,aAAa,EAAE,KAAK,GAAG,GACvF,MAAM,UACR;AAEA,MAAM,cAAc,MAAM,KAAmB,CAAC,CAAC,KAC7C,MAAM,yBAAyB,MAAM,CAAC,CAAC;CACrC,aAAa,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CACjD,cAAc,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CAClD,UAAU,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CAC9C,cAAc,OAAO;EAAE,MAAM;EAAa,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,EAAE;CAAE;CAGzF,oBAAoB,KAAA;AACtB,CAAC,CACH;AAEA,MAAM,eAAe,MACnB,EAAE,SAAS,gBAAgB,EAAE,SAAS,iBAAiB,EAAE,SAAS;AAEpE,MAAM,eAAe,MACnB,EAAE,SAAS,iBAAiB,EAAE,SAAS,iBAAiB,KAAK,EAAE;;;;;AAMjE,MAAM,iBACJ,YAEAA,MAAI,MAAM,SAAS,WAAW,IAC1B,QAAQ,IAAI,WAAW,CAAC,CAAC,KAAK,EAAE,IAChCA,MAAI,UAAU,UAAU,MAAM;CAC5B,MAAM,OAAO,YAAY,CAAC;CAC1B,OAAO,SAAS,KAAA,IAAY,OAAO,WAAW,OAAO,QAAQ,IAAI;AACnE,CAAC;AAEP,MAAM,gBAAgB,SAAiB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IAAI,MACtF,MAAM,IAAI,QAAQ,cAAc,KAAK,IAAI,CAAC,CAAC,CAC7C;CACA,MAAM,SAAS,OAAO;CACtB,OAAO,WAAW,KAAA,KAAa,WAAW,OACtC,CAAC;EAAE,GAAG,UAAU;EAAI,cAAc,OAAO,KAAK,MAAM;CAAE,GAAG,UAAU,EAAE,IACrE;AACN;;;;;AAMA,MAAa,cAAc,KAAkB,UAA2B;CACtE,MAAM,eAAeA,MAAI,OAAO,MAAM,WAAW,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC,GAAW,WAAW;CACnF,MAAM,QAAQ,MAAM;CACpB,OAAO,UAAU,KAAA,KAAa,UAAU,OACpC,MAAM,eAAe,MAAM;EACzB,MAAM,IAAI,UAAU,KAAK;EACzB,OAAO,CAAC;GAAE,GAAG;GAAG,OAAO;EAAE,GAAG,CAAC,UAAU,YAAY,EAAE,OAAO,EAAE,CAAC,CAAC,CAAC;CACnE,CAAC,IACD;AACN;;AAGA,MAAa,qBAAqB,QAA2B;CAC3D,MAAM,UACJ,IAAI,KAAK,SAAS,IACd,CAAC;EAAE,MAAM;EAAW,MAAM;EAAa,SAAS,CAAC;GAAE,MAAM;GAAe,MAAM,IAAI;EAAK,CAAC;CAAE,CAAC,IAC3F,CAAC;CACP,MAAM,YAAwC,IAAI,MAAM,SAAS,UAAU;EACzE,MAAM,IAAI,IAAI,MAAM,IAAI,KAAK;EAC7B,OAAO,MAAM,KAAA,IACT,CAAC,IACD,CACE;GACE,MAAM;GACN,SAAS,EAAE;GACX,MAAM,EAAE;GACR,WAAW,EAAE;EACf,CACF;CACN,CAAC;CACD,OAAO;EACL,OAAO,CAAC,GAAG,SAAS,GAAG,SAAS;EAChC,OAAO,IAAI;EACX,aAAa,aAAa,GAAG;CAC/B;AACF"}
1
+ {"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Match, Option, Result, Schema } from \"effect\"\nimport { Base64 } from \"effect/encoding\"\nimport type {\n ContentBlock,\n HistoryItem,\n InputImage,\n StopReason,\n Usage,\n} from \"@effect-uai/core/Items\"\nimport type { StructuredFormat } from \"@effect-uai/core/StructuredFormat\"\nimport type { ToolDescriptor } from \"@effect-uai/core/Tool\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\nimport { TurnEvent } from \"@effect-uai/core/Turn\"\n\n// ---------------------------------------------------------------------------\n// History → chat `messages`\n//\n// The OpenAI Chat Completions dialect: a flat list of `{ role, content, ... }`\n// objects where an assistant turn's tool calls live on the assistant message\n// (`tool_calls`) and each tool result is its own\n// `{ role: \"tool\", tool_call_id, content }` message. Our history is a flatter\n// item list (assistant message, then separate `function_call` items), so we\n// fold consecutive `function_call`s onto the preceding assistant message.\n// ---------------------------------------------------------------------------\n\ntype WireMessage = {\n role: string\n content: string | ReadonlyArray<Record<string, unknown>>\n tool_calls?: ReadonlyArray<Record<string, unknown>>\n tool_call_id?: string\n}\n\n/** A `data:` URI for inline image bytes; URLs pass through untouched. */\nconst imageSourceToUrl = Match.type<InputImage[\"source\"]>().pipe(\n Match.tag(\"url\", (s) => s.url),\n Match.tag(\"base64\", (s) => `data:${s.mimeType};base64,${s.base64}`),\n Match.tag(\"bytes\", (s) => `data:${s.mimeType};base64,${Base64.encode(s.bytes)}`),\n Match.exhaustive,\n)\n\nconst blockToPart = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"text\", text: b.text }),\n output_text: (b) => ({ type: \"text\", text: b.text }),\n refusal: (b) => ({ type: \"text\", text: b.text }),\n input_image: (b) => ({ type: \"image_url\", image_url: { url: imageSourceToUrl(b.source) } }),\n // No assistant-image part here. Dropped rather than relocated onto a\n // user message, which is the caller's call: `Turn.imagesAsInput`.\n output_image: () => undefined,\n }),\n)\n\nconst isTextBlock = (b: ContentBlock): boolean =>\n b.type === \"input_text\" || b.type === \"output_text\" || b.type === \"refusal\"\n\nconst textOfBlock = (b: ContentBlock): string =>\n b.type === \"input_image\" || b.type === \"output_image\" ? \"\" : b.text\n\n/**\n * Collapse a message's content to a plain string when it is text-only (the\n * common case), otherwise emit the multimodal parts array.\n */\nconst encodeContent = (\n content: ReadonlyArray<ContentBlock>,\n): string | ReadonlyArray<Record<string, unknown>> =>\n Arr.every(content, isTextBlock)\n ? content.map(textOfBlock).join(\"\")\n : Arr.filterMap(content, (b) => {\n const part = blockToPart(b)\n return part === undefined ? Result.failVoid : Result.succeed(part)\n })\n\nconst toolCallWire = (call_id: string, name: string, args: string): Record<string, unknown> => ({\n id: call_id,\n type: \"function\",\n function: { name, arguments: args },\n})\n\nconst appendToolCall = (\n acc: ReadonlyArray<WireMessage>,\n call_id: string,\n name: string,\n args: string,\n): ReadonlyArray<WireMessage> => {\n const last = acc[acc.length - 1]\n const wire = toolCallWire(call_id, name, args)\n // Attach to the immediately-preceding assistant message (not a tool result),\n // matching the shape where tool calls ride the assistant turn.\n if (last !== undefined && last.role === \"assistant\" && last.tool_call_id === undefined) {\n return [...acc.slice(0, -1), { ...last, tool_calls: [...(last.tool_calls ?? []), wire] }]\n }\n return [...acc, { role: \"assistant\", content: \"\", tool_calls: [wire] }]\n}\n\nconst foldItem = (acc: ReadonlyArray<WireMessage>, item: HistoryItem): ReadonlyArray<WireMessage> =>\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => [...acc, { role: m.role, content: encodeContent(m.content) }],\n function_call: (f) => appendToolCall(acc, f.call_id, f.name, f.arguments),\n function_call_output: (o) => [\n ...acc,\n { role: \"tool\", tool_call_id: o.call_id, content: o.output },\n ],\n // Reasoning items are not replayed to the chat-completions endpoint.\n reasoning: () => acc,\n }),\n )\n\n/** Convert our `HistoryItem[]` history into chat `messages`. */\nexport const itemsToMessages = (items: ReadonlyArray<HistoryItem>): ReadonlyArray<WireMessage> =>\n Arr.reduce(items, [] as ReadonlyArray<WireMessage>, foldItem)\n\n// ---------------------------------------------------------------------------\n// tools / tool_choice / response_format\n// ---------------------------------------------------------------------------\n\nexport const toolsWire = (\n descriptors: ReadonlyArray<ToolDescriptor>,\n): Option.Option<ReadonlyArray<Record<string, unknown>>> =>\n descriptors.length > 0\n ? Option.some(\n descriptors.map((t) => ({\n type: \"function\",\n function: {\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict !== undefined && { strict: t.strict }),\n },\n })),\n )\n : Option.none()\n\ntype ToolChoice =\n | \"auto\"\n | \"required\"\n | \"none\"\n | { readonly type: \"function\"; readonly name: string }\n\nexport const toolChoiceWire = (choice: ToolChoice): string | Record<string, unknown> =>\n Match.value(choice).pipe(\n Match.when(\"auto\", () => \"auto\" as const),\n Match.when(\"required\", () => \"required\" as const),\n Match.when(\"none\", () => \"none\" as const),\n Match.orElse((c) => ({ type: \"function\", function: { name: c.name } })),\n )\n\nexport const responseFormatWire = (\n structured: StructuredFormat<unknown>,\n): Record<string, unknown> => ({\n type: \"json_schema\",\n json_schema: {\n name: structured.name,\n schema: structured.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n ...(structured.strict !== undefined && { strict: structured.strict }),\n },\n})\n\n// ---------------------------------------------------------------------------\n// Streaming decode: chat.completion.chunk → TurnEvent\n// ---------------------------------------------------------------------------\n\nconst WireFunction = Schema.Struct({\n name: Schema.optional(Schema.NullOr(Schema.String)),\n arguments: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireToolCall = Schema.Struct({\n index: Schema.optional(Schema.Number),\n id: Schema.optional(Schema.NullOr(Schema.String)),\n function: Schema.optional(WireFunction),\n})\n\nconst WireDelta = Schema.Struct({\n role: Schema.optional(Schema.NullOr(Schema.String)),\n content: Schema.optional(Schema.NullOr(Schema.String)),\n tool_calls: Schema.optional(Schema.NullOr(Schema.Array(WireToolCall))),\n})\n\nconst WireChoice = Schema.Struct({\n index: Schema.optional(Schema.Number),\n delta: Schema.optional(WireDelta),\n finish_reason: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\nconst WireUsage = Schema.Struct({\n prompt_tokens: Schema.optional(Schema.Number),\n completion_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n})\n\nexport const WireChunk = Schema.Struct({\n choices: Schema.optional(Schema.Array(WireChoice)),\n usage: Schema.optional(Schema.NullOr(WireUsage)),\n})\nexport type WireChunk = typeof WireChunk.Type\n\nexport const decodeChunk = Schema.decodeUnknownEffect(WireChunk)\n\n// ---------------------------------------------------------------------------\n// Accumulator\n// ---------------------------------------------------------------------------\n\ntype ToolAcc = {\n readonly call_id: string\n readonly name: string\n readonly arguments: string\n}\n\nexport type Accumulator = {\n readonly text: string\n /** Tool calls keyed by their wire `index` (defaults to position when absent). */\n readonly tools: ReadonlyMap<number, ToolAcc>\n readonly order: ReadonlyArray<number>\n readonly usage: Usage\n readonly finishReason: Option.Option<string>\n}\n\nexport const emptyAccumulator: Accumulator = {\n text: \"\",\n tools: new Map(),\n order: [],\n usage: {},\n finishReason: Option.none(),\n}\n\n/** State threaded through the fold plus the events the step produced. */\ntype Step = readonly [Accumulator, ReadonlyArray<TurnEvent>]\n\nconst usageFrom = (wire: typeof WireUsage.Type): Usage => ({\n ...(wire.prompt_tokens !== undefined && { input_tokens: wire.prompt_tokens }),\n ...(wire.completion_tokens !== undefined && { output_tokens: wire.completion_tokens }),\n ...(wire.total_tokens !== undefined && { total_tokens: wire.total_tokens }),\n})\n\nconst reasonToStop = Match.type<string>().pipe(\n Match.when(\"stop\", () => \"stop\" as const),\n Match.when(\"length\", () => \"max_tokens\" as const),\n Match.when(\"tool_calls\", () => \"tool_calls\" as const),\n Match.when(\"content_filter\", () => \"content_filter\" as const),\n Match.orElse(() => \"stop\" as const),\n)\n\nconst stopReasonOf = (acc: Accumulator): StopReason =>\n Option.match(acc.finishReason, {\n onNone: () => (acc.tools.size > 0 ? \"tool_calls\" : \"stop\"),\n onSome: reasonToStop,\n })\n\nconst withTool = (acc: Accumulator, index: number, tool: ToolAcc, isNew: boolean): Accumulator => ({\n ...acc,\n tools: new Map(acc.tools).set(index, tool),\n order: isNew ? [...acc.order, index] : acc.order,\n})\n\nconst applyContent = (acc: Accumulator, delta: typeof WireDelta.Type | undefined): Step => {\n const content = delta?.content\n return content !== undefined && content !== null && content.length > 0\n ? [{ ...acc, text: acc.text + content }, [TurnEvent.TextDelta({ text: content })]]\n : [acc, []]\n}\n\nconst applyToolCall = (acc: Accumulator, tc: typeof WireToolCall.Type, position: number): Step => {\n const index = tc.index ?? position\n const argsDelta = tc.function?.arguments ?? \"\"\n const existing = acc.tools.get(index)\n if (existing === undefined) {\n // Only `index` is guaranteed on a streaming tool-call chunk, so the id may\n // be absent. The synthesised fallback is 9-char alphanumeric: valid on every\n // chat-completions wire (Mistral additionally requires `^[a-zA-Z0-9]{9}$`),\n // and it is replayed on the next turn.\n const call_id = tc.id ?? String(index).padStart(9, \"0\")\n const name = tc.function?.name ?? \"\"\n return [\n withTool(acc, index, { call_id, name, arguments: argsDelta }, true),\n [\n TurnEvent.ToolCallStart({ call_id, name }),\n ...(argsDelta.length > 0\n ? [TurnEvent.ToolCallArgsDelta({ call_id, delta: argsDelta })]\n : []),\n ],\n ]\n }\n return argsDelta.length > 0\n ? [\n withTool(acc, index, { ...existing, arguments: existing.arguments + argsDelta }, false),\n [TurnEvent.ToolCallArgsDelta({ call_id: existing.call_id, delta: argsDelta })],\n ]\n : [acc, []]\n}\n\nconst chain = (step: Step, next: (acc: Accumulator) => Step): Step => {\n const [acc, events] = step\n const [acc2, more] = next(acc)\n return [acc2, [...events, ...more]]\n}\n\nconst applyChoice = (step: Step, choice: typeof WireChoice.Type): Step => {\n const withContent = chain(step, (acc) => applyContent(acc, choice.delta))\n const withTools = Arr.reduce(choice.delta?.tool_calls ?? [], withContent, (s: Step, tc, i) =>\n chain(s, (acc) => applyToolCall(acc, tc, i)),\n )\n const reason = choice.finish_reason\n return reason !== undefined && reason !== null\n ? [{ ...withTools[0], finishReason: Option.some(reason) }, withTools[1]]\n : withTools\n}\n\n/**\n * Fold one decoded chunk into the accumulator, returning the next state and the\n * `TurnEvent`s the chunk produced.\n */\nexport const applyChunk = (acc: Accumulator, chunk: WireChunk): Step => {\n const afterChoices = Arr.reduce(chunk.choices ?? [], [acc, []] as Step, applyChoice)\n const usage = chunk.usage\n return usage !== undefined && usage !== null\n ? chain(afterChoices, (a) => {\n const u = usageFrom(usage)\n return [{ ...a, usage: u }, [TurnEvent.UsageUpdate({ usage: u })]]\n })\n : afterChoices\n}\n\n/** Assemble the terminal `Turn` from the accumulated state. */\nexport const accumulatorToTurn = (acc: Accumulator): Turn => {\n const message: ReadonlyArray<HistoryItem> =\n acc.text.length > 0\n ? [{ type: \"message\", role: \"assistant\", content: [{ type: \"output_text\", text: acc.text }] }]\n : []\n const toolCalls: ReadonlyArray<HistoryItem> = acc.order.flatMap((index) => {\n const t = acc.tools.get(index)\n return t === undefined\n ? []\n : [\n {\n type: \"function_call\" as const,\n call_id: t.call_id,\n name: t.name,\n arguments: t.arguments,\n },\n ]\n })\n return {\n items: [...message, ...toolCalls],\n usage: acc.usage,\n stop_reason: stopReasonOf(acc),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAiCA,MAAM,mBAAmB,MAAM,KAA2B,CAAC,CAAC,KAC1D,MAAM,IAAI,QAAQ,MAAM,EAAE,GAAG,GAC7B,MAAM,IAAI,WAAW,MAAM,QAAQ,EAAE,SAAS,UAAU,EAAE,QAAQ,GAClE,MAAM,IAAI,UAAU,MAAM,QAAQ,EAAE,SAAS,UAAU,OAAO,OAAO,EAAE,KAAK,GAAG,GAC/E,MAAM,UACR;AAEA,MAAM,cAAc,MAAM,KAAmB,CAAC,CAAC,KAC7C,MAAM,yBAAyB,MAAM,CAAC,CAAC;CACrC,aAAa,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CACjD,cAAc,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CAClD,UAAU,OAAO;EAAE,MAAM;EAAQ,MAAM,EAAE;CAAK;CAC9C,cAAc,OAAO;EAAE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SAAS,CAAC;GAAE,MAAM;GAAe,MAAM,IAAI;EAAK,CAAC;CAAE,CAAC,IAC3F,CAAC;CACP,MAAM,YAAwC,IAAI,MAAM,SAAS,UAAU;EACzE,MAAM,IAAI,IAAI,MAAM,IAAI,KAAK;EAC7B,OAAO,MAAM,KAAA,IACT,CAAC,IACD,CACE;GACE,MAAM;GACN,SAAS,EAAE;GACX,MAAM,EAAE;GACR,WAAW,EAAE;EACf,CACF;CACN,CAAC;CACD,OAAO;EACL,OAAO,CAAC,GAAG,SAAS,GAAG,SAAS;EAChC,OAAO,IAAI;EACX,aAAa,aAAa,GAAG;CAC/B;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@effect-uai/chat-completions",
3
- "version": "0.17.0",
3
+ "version": "0.18.0",
4
4
  "description": "Reusable OpenAI Chat Completions (`/chat/completions`) LanguageModel base for @effect-uai/core. Point it at any compatible gateway (OpenRouter, Groq, Together, self-hosted).",
5
5
  "keywords": [
6
6
  "ai",
@@ -53,13 +53,13 @@
53
53
  "access": "public"
54
54
  },
55
55
  "devDependencies": {
56
- "effect": "4.0.0-rc.111",
56
+ "effect": "4.0.1",
57
57
  "typescript": "^7.0.2",
58
- "@effect-uai/core": "0.17.0"
58
+ "@effect-uai/core": "0.18.0"
59
59
  },
60
60
  "peerDependencies": {
61
61
  "@effect-uai/core": ">=0.2.0 <1",
62
- "effect": ">=4.0.0-rc.111 <5.0.0"
62
+ "effect": ">=4.0.1 <5.0.0"
63
63
  },
64
64
  "scripts": {
65
65
  "build": "tsdown",
@@ -1,5 +1,5 @@
1
1
  import { Effect, Layer, Option, Redacted, Result, Schema, Stream } from "effect"
2
- import { HttpClient, HttpClientRequest } from "effect/unstable/http"
2
+ import { HttpClient, HttpClientRequest } from "effect/http"
3
3
  import * as AiError from "@effect-uai/core/AiError"
4
4
  import * as Capabilities from "@effect-uai/core/Capabilities"
5
5
  import {
package/src/codec.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { Array as Arr, Encoding, Match, Option, Result, Schema } from "effect"
1
+ import { Array as Arr, Match, Option, Result, Schema } from "effect"
2
+ import { Base64 } from "effect/encoding"
2
3
  import type {
3
4
  ContentBlock,
4
5
  HistoryItem,
@@ -33,7 +34,7 @@ type WireMessage = {
33
34
  const imageSourceToUrl = Match.type<InputImage["source"]>().pipe(
34
35
  Match.tag("url", (s) => s.url),
35
36
  Match.tag("base64", (s) => `data:${s.mimeType};base64,${s.base64}`),
36
- Match.tag("bytes", (s) => `data:${s.mimeType};base64,${Encoding.encodeBase64(s.bytes)}`),
37
+ Match.tag("bytes", (s) => `data:${s.mimeType};base64,${Base64.encode(s.bytes)}`),
37
38
  Match.exhaustive,
38
39
  )
39
40