@effect-uai/chat-completions 0.11.0 → 0.12.1
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/dist/ChatCompletions.d.mts +10 -7
- package/dist/ChatCompletions.d.mts.map +1 -1
- package/dist/ChatCompletions.mjs +1 -1
- package/dist/ChatCompletions.mjs.map +1 -1
- package/dist/codec.d.mts +5 -8
- package/dist/codec.d.mts.map +1 -1
- package/dist/codec.mjs +1 -1
- package/dist/codec.mjs.map +1 -1
- package/dist/http.d.mts +0 -2
- package/dist/http.d.mts.map +1 -1
- package/dist/http.mjs +1 -1
- package/dist/http.mjs.map +1 -1
- package/package.json +5 -5
- /package/dist/{chunk-CfYAbeIz.mjs → rolldown-runtime-D7D4PA-g.mjs} +0 -0
|
@@ -1,22 +1,25 @@
|
|
|
1
1
|
import { Effect, Layer, Redacted } from "effect";
|
|
2
2
|
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
3
3
|
import { CommonRequest, LanguageModel, LanguageModelService } from "@effect-uai/core/LanguageModel";
|
|
4
|
-
|
|
5
|
-
//#region src/ChatCompletions.d.ts
|
|
6
4
|
declare namespace ChatCompletions_d_exports {
|
|
7
5
|
export { ChatConfig, layer, make };
|
|
8
6
|
}
|
|
9
7
|
type ChatConfig = {
|
|
10
|
-
readonly apiKey: Redacted.Redacted;
|
|
11
|
-
|
|
12
|
-
readonly
|
|
8
|
+
readonly apiKey: Redacted.Redacted;
|
|
9
|
+
/** Provider base URL, e.g. `https://openrouter.ai/api/v1`. No trailing slash. */
|
|
10
|
+
readonly baseUrl: string;
|
|
11
|
+
/** Name used to tag `AiError`s from this provider. */
|
|
12
|
+
readonly provider: string;
|
|
13
|
+
/** Request path appended to `baseUrl`. Defaults to `/chat/completions`. */
|
|
13
14
|
readonly path?: string;
|
|
14
15
|
/**
|
|
15
16
|
* Override the auth header. Defaults to `Authorization: Bearer <apiKey>`.
|
|
16
17
|
* Supply this for gateways that authenticate differently (e.g. Azure `api-key`).
|
|
17
18
|
*/
|
|
18
|
-
readonly authHeader?: (request: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest;
|
|
19
|
-
|
|
19
|
+
readonly authHeader?: (request: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest;
|
|
20
|
+
/** Extra headers merged into every request (e.g. OpenRouter `HTTP-Referer`). */
|
|
21
|
+
readonly extraHeaders?: Record<string, string>;
|
|
22
|
+
/** Provider-specific request-body fields merged into the wire body. */
|
|
20
23
|
readonly extraBody?: (request: CommonRequest) => Record<string, unknown>;
|
|
21
24
|
};
|
|
22
25
|
/** Build a generic chat-completions `LanguageModelService`. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatCompletions.d.mts","names":[],"sources":["../src/ChatCompletions.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ChatCompletions.d.mts","names":[],"sources":["../src/ChatCompletions.ts"],"mappings":";;;;;;KA8BY;WACD,QAAQ,SAAS;;WAEjB;;WAEA;;WAEA;;;;;WAKA,cACP,SAAS,kBAAkB,sBACxB,kBAAkB;;WAEd,eAAe;;WAEf,aAAa,SAAS,kBAAkB;;;cAgGtC,OAAI,KACV,eACJ,OAAO,OAAO,6BAA6B,WAAW;;cAW5C,QAAK,KAAS,eAAa,MAAM,MAAM,sBAAsB,WAAW"}
|
package/dist/ChatCompletions.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as __exportAll } from "./
|
|
1
|
+
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";
|
|
@@ -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 {\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 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":";;;;;;;;;;;;;;;AAuDA,MAAM,oBAAoB,KAAiB,YAAoD;CAC7F,MAAM,QAAQ,UAAU,cAAc,QAAQ,
|
|
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 {\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 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":";;;;;;;;;;;;;;;AAuDA,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,YAAY;EAC5E,GAAI,QAAQ,SAAS,KAAA,KAAa,EAAE,OAAO,QAAQ,KAAK;EACxD,GAAI,QAAQ,oBAAoB,KAAA,KAAa,EAAE,YAAY,QAAQ,gBAAgB;EACnF,GAAI,OAAO,OAAO,KAAK,KAAK,EAAE,OAAO,MAAM,MAAM;EACjD,GAAI,QAAQ,eAAe,KAAA,KAAa,EAAE,aAAa,eAAe,QAAQ,UAAU,EAAE;EAC1F,GAAI,QAAQ,eAA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,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"}
|
package/dist/codec.d.mts
CHANGED
|
@@ -1,12 +1,8 @@
|
|
|
1
1
|
import { Option, Schema } from "effect";
|
|
2
2
|
import { ToolDescriptor } from "@effect-uai/core/Tool";
|
|
3
3
|
import { Turn, TurnEvent } from "@effect-uai/core/Turn";
|
|
4
|
-
import * as _$effect_SchemaAST0 from "effect/SchemaAST";
|
|
5
|
-
import * as _$effect_Effect0 from "effect/Effect";
|
|
6
4
|
import { HistoryItem, Usage } from "@effect-uai/core/Items";
|
|
7
5
|
import { StructuredFormat } from "@effect-uai/core/StructuredFormat";
|
|
8
|
-
|
|
9
|
-
//#region src/codec.d.ts
|
|
10
6
|
declare namespace codec_d_exports {
|
|
11
7
|
export { Accumulator, WireChunk, accumulatorToTurn, applyChunk, decodeChunk, emptyAccumulator, itemsToMessages, responseFormatWire, toolChoiceWire, toolsWire };
|
|
12
8
|
}
|
|
@@ -49,19 +45,19 @@ declare const WireChunk: Schema.Struct<{
|
|
|
49
45
|
}>>>;
|
|
50
46
|
}>;
|
|
51
47
|
type WireChunk = typeof WireChunk.Type;
|
|
52
|
-
declare const decodeChunk: (input: unknown, options?:
|
|
48
|
+
declare const decodeChunk: (input: unknown, options?: import("effect/SchemaAST").ParseOptions) => import("effect/Effect").Effect<{
|
|
53
49
|
readonly choices?: readonly {
|
|
54
50
|
readonly index?: number | undefined;
|
|
55
51
|
readonly delta?: {
|
|
56
52
|
readonly role?: string | null | undefined;
|
|
57
53
|
readonly content?: string | null | undefined;
|
|
58
54
|
readonly tool_calls?: readonly {
|
|
55
|
+
readonly index?: number | undefined;
|
|
56
|
+
readonly id?: string | null | undefined;
|
|
59
57
|
readonly function?: {
|
|
60
58
|
readonly name?: string | null | undefined;
|
|
61
59
|
readonly arguments?: string | null | undefined;
|
|
62
60
|
} | undefined;
|
|
63
|
-
readonly id?: string | null | undefined;
|
|
64
|
-
readonly index?: number | undefined;
|
|
65
61
|
}[] | null | undefined;
|
|
66
62
|
} | undefined;
|
|
67
63
|
readonly finish_reason?: string | null | undefined;
|
|
@@ -78,7 +74,8 @@ type ToolAcc = {
|
|
|
78
74
|
readonly arguments: string;
|
|
79
75
|
};
|
|
80
76
|
type Accumulator = {
|
|
81
|
-
readonly text: string;
|
|
77
|
+
readonly text: string;
|
|
78
|
+
/** Tool calls keyed by their wire `index` (defaults to position when absent). */
|
|
82
79
|
readonly tools: ReadonlyMap<number, ToolAcc>;
|
|
83
80
|
readonly order: ReadonlyArray<number>;
|
|
84
81
|
readonly usage: Usage;
|
package/dist/codec.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;KAwBK;EACH;EACA,kBAAkB,cAAc;EAChC,aAAa,cAAc;EAC3B;;;cAuEW,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
package/dist/codec.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, 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 }),\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 => (b.type === \"input_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) ? content.map(textOfBlock).join(\"\") : content.map(blockToPart)\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,MAA4B,CAAC,KAC1D,MAAM,IAAI,QAAQ,MAAM,EAAE,IAAI,EAC9B,MAAM,IAAI,WAAW,MAAM,QAAQ,EAAE,SAAS,UAAU,EAAE,SAAS,E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G,CAAC,CAAC,CAAC;GAClE,GACF;;;AAIN,MAAa,qBAAqB,QAA2B;CAC3D,MAAM,UACJ,IAAI,KAAK,SAAS,IACd,CAAC;EAAE,MAAM;EAAW,MAAM;EAAa,SAAS,CAAC;GAAE,MAAM;GAAe,MAAM,IAAI;GAAM,CAAC;EAAE,CAAC,GAC5F,EAAE;CACR,MAAM,YAAwC,IAAI,MAAM,SAAS,UAAU;EACzE,MAAM,IAAI,IAAI,MAAM,IAAI,MAAM;AAC9B,SAAO,MAAM,KAAA,IACT,EAAE,GACF,CACE;GACE,MAAM;GACN,SAAS,EAAE;GACX,MAAM,EAAE;GACR,WAAW,EAAE;GACd,CACF;GACL;AACF,QAAO;EACL,OAAO,CAAC,GAAG,SAAS,GAAG,UAAU;EACjC,OAAO,IAAI;EACX,aAAa,aAAa,IAAI;EAC/B"}
|
|
1
|
+
{"version":3,"file":"codec.mjs","names":["Arr"],"sources":["../src/codec.ts"],"sourcesContent":["import { Array as Arr, Encoding, Match, Option, 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 }),\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 => (b.type === \"input_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) ? content.map(textOfBlock).join(\"\") : content.map(blockToPart)\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,KA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,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"}
|
package/dist/http.d.mts
CHANGED
package/dist/http.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.d.mts","names":[],"sources":["../src/http.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"http.d.mts","names":[],"sources":["../src/http.ts"],"mappings":";;;;;cAIa,kBAAe,kBAAoB,gBAAgB,iBAAiB,QAAQ;cA2B5E,mBAAgB,kBAAoB,mBAAmB,QAAQ"}
|
package/dist/http.mjs
CHANGED
package/dist/http.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"http.mjs","names":[],"sources":["../src/http.ts"],"sourcesContent":["import { Match } from \"effect\"\nimport * as AiError from \"@effect-uai/core/AiError\"\n\n/** Map an HTTP status from a chat-completions endpoint to an `AiError` variant. */\nexport const httpStatusError = (provider: string, status: number, body: string): AiError.AiError =>\n Match.value(status).pipe(\n Match.when(429, (): AiError.AiError => new AiError.RateLimited({ provider, raw: body })),\n Match.whenOr(408, 504, (): AiError.AiError => new AiError.Timeout({ provider, raw: body })),\n Match.when(\n 401,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"billing\", raw: body }),\n ),\n Match.when(\n 413,\n (): AiError.AiError => new AiError.ContextLengthExceeded({ provider, raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider, status: n, raw: body }),\n ),\n Match.orElse((): AiError.AiError => new AiError.InvalidRequest({ provider, raw: body })),\n )\n\nexport const transportFailure = (provider: string, cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider, raw: cause })\n"],"mappings":";;;;;;;;;AAIA,MAAa,mBAAmB,UAAkB,QAAgB,SAChE,MAAM,MAAM,
|
|
1
|
+
{"version":3,"file":"http.mjs","names":[],"sources":["../src/http.ts"],"sourcesContent":["import { Match } from \"effect\"\nimport * as AiError from \"@effect-uai/core/AiError\"\n\n/** Map an HTTP status from a chat-completions endpoint to an `AiError` variant. */\nexport const httpStatusError = (provider: string, status: number, body: string): AiError.AiError =>\n Match.value(status).pipe(\n Match.when(429, (): AiError.AiError => new AiError.RateLimited({ provider, raw: body })),\n Match.whenOr(408, 504, (): AiError.AiError => new AiError.Timeout({ provider, raw: body })),\n Match.when(\n 401,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"auth\", raw: body }),\n ),\n Match.when(\n 403,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"permission\", raw: body }),\n ),\n Match.when(\n 402,\n (): AiError.AiError => new AiError.AuthFailed({ provider, subtype: \"billing\", raw: body }),\n ),\n Match.when(\n 413,\n (): AiError.AiError => new AiError.ContextLengthExceeded({ provider, raw: body }),\n ),\n Match.when(\n (n) => n >= 500,\n (n): AiError.AiError => new AiError.Unavailable({ provider, status: n, raw: body }),\n ),\n Match.orElse((): AiError.AiError => new AiError.InvalidRequest({ provider, raw: body })),\n )\n\nexport const transportFailure = (provider: string, cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider, raw: cause })\n"],"mappings":";;;;;;;;;AAIA,MAAa,mBAAmB,UAAkB,QAAgB,SAChE,MAAM,MAAM,MAAM,CAAC,CAAC,KAClB,MAAM,KAAK,WAA4B,IAAI,QAAQ,YAAY;CAAE;CAAU,KAAK;AAAK,CAAC,CAAC,GACvF,MAAM,OAAO,KAAK,WAA4B,IAAI,QAAQ,QAAQ;CAAE;CAAU,KAAK;AAAK,CAAC,CAAC,GAC1F,MAAM,KACJ,WACuB,IAAI,QAAQ,WAAW;CAAE;CAAU,SAAS;CAAQ,KAAK;AAAK,CAAC,CACxF,GACA,MAAM,KACJ,WACuB,IAAI,QAAQ,WAAW;CAAE;CAAU,SAAS;CAAc,KAAK;AAAK,CAAC,CAC9F,GACA,MAAM,KACJ,WACuB,IAAI,QAAQ,WAAW;CAAE;CAAU,SAAS;CAAW,KAAK;AAAK,CAAC,CAC3F,GACA,MAAM,KACJ,WACuB,IAAI,QAAQ,sBAAsB;CAAE;CAAU,KAAK;AAAK,CAAC,CAClF,GACA,MAAM,MACH,MAAM,KAAK,MACX,MAAuB,IAAI,QAAQ,YAAY;CAAE;CAAU,QAAQ;CAAG,KAAK;AAAK,CAAC,CACpF,GACA,MAAM,aAA8B,IAAI,QAAQ,eAAe;CAAE;CAAU,KAAK;AAAK,CAAC,CAAC,CACzF;AAEF,MAAa,oBAAoB,UAAkB,UACjD,IAAI,QAAQ,YAAY;CAAE;CAAU,KAAK;AAAM,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@effect-uai/chat-completions",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.1",
|
|
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-
|
|
57
|
-
"typescript": "^
|
|
58
|
-
"@effect-uai/core": "0.
|
|
56
|
+
"effect": "4.0.0-rc.111",
|
|
57
|
+
"typescript": "^7.0.2",
|
|
58
|
+
"@effect-uai/core": "0.12.1"
|
|
59
59
|
},
|
|
60
60
|
"peerDependencies": {
|
|
61
61
|
"@effect-uai/core": ">=0.2.0 <1",
|
|
62
|
-
"effect": ">=4.0.0-
|
|
62
|
+
"effect": ">=4.0.0-rc.111 <5.0.0"
|
|
63
63
|
},
|
|
64
64
|
"scripts": {
|
|
65
65
|
"build": "tsdown",
|
|
File without changes
|