@effect-uai/responses 0.11.0 → 0.12.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/dist/Responses.d.mts +20 -0
- package/dist/Responses.d.mts.map +1 -1
- package/dist/Responses.mjs +5 -3
- package/dist/Responses.mjs.map +1 -1
- package/dist/codec.d.mts.map +1 -1
- package/dist/codec.mjs +30 -8
- package/dist/codec.mjs.map +1 -1
- package/dist/codec.test.d.mts +1 -0
- package/dist/codec.test.mjs +93 -0
- package/dist/codec.test.mjs.map +1 -0
- package/package.json +6 -2
- package/src/Responses.ts +24 -1
- package/src/codec.test.ts +87 -0
- package/src/codec.ts +33 -13
package/dist/Responses.d.mts
CHANGED
|
@@ -30,6 +30,20 @@ type ResponsesRequest = Omit<CommonRequest, "model"> & {
|
|
|
30
30
|
readonly safetyIdentifier?: string;
|
|
31
31
|
readonly promptCacheKey?: string;
|
|
32
32
|
readonly truncation?: "auto" | "disabled";
|
|
33
|
+
/**
|
|
34
|
+
* Vendor-specific body fields merged into the request as-is.
|
|
35
|
+
*
|
|
36
|
+
* The Responses dialect is spoken by gateways as well as by OpenAI, and a
|
|
37
|
+
* gateway carries its own parameters — Requesty's `{ requesty: { auto_cache:
|
|
38
|
+
* true } }`, for example. Modelling each one would tie this provider to a
|
|
39
|
+
* catalogue of gateways it cannot see; passing them through keeps the typed
|
|
40
|
+
* surface OpenAI's and the untyped surface open.
|
|
41
|
+
*
|
|
42
|
+
* Merged over the built body, so a field named here wins over the one this
|
|
43
|
+
* provider would have sent. Per-request keys win over the layer's
|
|
44
|
+
* {@link Config.extraBody}.
|
|
45
|
+
*/
|
|
46
|
+
readonly extraBody?: Readonly<Record<string, unknown>>;
|
|
33
47
|
/**
|
|
34
48
|
* Free-form JSON output: model emits valid JSON without schema
|
|
35
49
|
* constraints. Mutually exclusive with `structured` (schema wins if
|
|
@@ -81,6 +95,12 @@ type Config = {
|
|
|
81
95
|
readonly apiKey: Redacted.Redacted;
|
|
82
96
|
readonly baseUrl?: string;
|
|
83
97
|
readonly region?: OpenAiRegion;
|
|
98
|
+
/**
|
|
99
|
+
* Vendor-specific body fields sent on every request from this layer — the
|
|
100
|
+
* place for a gateway's standing configuration, so call sites do not repeat
|
|
101
|
+
* it. Overridden per request by {@link ResponsesRequest.extraBody}.
|
|
102
|
+
*/
|
|
103
|
+
readonly extraBody?: Readonly<Record<string, unknown>>;
|
|
84
104
|
};
|
|
85
105
|
declare const httpStatusError: (status: number, body: string) => AiError.AiError;
|
|
86
106
|
/**
|
package/dist/Responses.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Responses.d.mts","names":[],"sources":["../src/Responses.ts"],"mappings":";;;;;;;;;;;;;;KAqCY,gBAAA,GAAmB,IAAA,CAAK,aAAA;;;;;WAKzB,KAAA,EAAO,WAAA;EAAA,SACP,SAAA;IAAA,SAAuB,MAAA;EAAA;EAAA,SACvB,KAAA;EAAA,SACA,kBAAA;EAAA,SACA,YAAA;EAAA,SACA,iBAAA;EAAA,SACA,QAAA,GAAW,QAAA,CAAS,MAAA;EAAA,SACpB,IAAA;EAAA,SACA,gBAAA;EAAA,SACA,cAAA;EAAA,SACA,UAAA;;;AAfX
|
|
1
|
+
{"version":3,"file":"Responses.d.mts","names":[],"sources":["../src/Responses.ts"],"mappings":";;;;;;;;;;;;;;KAqCY,gBAAA,GAAmB,IAAA,CAAK,aAAA;;;;;WAKzB,KAAA,EAAO,WAAA;EAAA,SACP,SAAA;IAAA,SAAuB,MAAA;EAAA;EAAA,SACvB,KAAA;EAAA,SACA,kBAAA;EAAA,SACA,YAAA;EAAA,SACA,iBAAA;EAAA,SACA,QAAA,GAAW,QAAA,CAAS,MAAA;EAAA,SACpB,IAAA;EAAA,SACA,gBAAA;EAAA,SACA,cAAA;EAAA,SACA,UAAA;;;AAfX;;;;;;;;;;;WA6BW,SAAA,GAAY,QAAA,CAAS,MAAA;EA7BD;;;;;EAAA,SAmCp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CAAO,MAAA,CAAO,gBAAA,SAAyB,UAAA,CAAW,UAAA;;;;;;;;cAqBxE,KAAA,GACX,GAAA,EAAK,MAAA,KACJ,KAAA,CAAM,KAAA,CAAM,SAAA,GAAY,aAAA,SAAsB,UAAA,CAAW,UAAA"}
|
package/dist/Responses.mjs
CHANGED
|
@@ -42,7 +42,7 @@ const buildText = (request) => {
|
|
|
42
42
|
if (request.verbosity !== void 0) text.verbosity = request.verbosity;
|
|
43
43
|
return Object.keys(text).length === 0 ? void 0 : text;
|
|
44
44
|
};
|
|
45
|
-
const buildBody = (request, providerToolWire) => {
|
|
45
|
+
const buildBody = (request, providerToolWire, cfg) => {
|
|
46
46
|
const text = buildText(request);
|
|
47
47
|
const tools = [...descriptorsOf(request.tools).map((t) => ({
|
|
48
48
|
type: "function",
|
|
@@ -70,7 +70,9 @@ const buildBody = (request, providerToolWire) => {
|
|
|
70
70
|
...request.safetyIdentifier !== void 0 && { safety_identifier: request.safetyIdentifier },
|
|
71
71
|
...request.promptCacheKey !== void 0 && { prompt_cache_key: request.promptCacheKey },
|
|
72
72
|
...request.truncation !== void 0 && { truncation: request.truncation },
|
|
73
|
-
...text !== void 0 && { text }
|
|
73
|
+
...text !== void 0 && { text },
|
|
74
|
+
...cfg.extraBody,
|
|
75
|
+
...request.extraBody
|
|
74
76
|
};
|
|
75
77
|
};
|
|
76
78
|
const decodeKnown = Schema.decodeUnknownEffect(KnownProviderEvent);
|
|
@@ -185,7 +187,7 @@ const buildNativeStream = (cfg) => {
|
|
|
185
187
|
})),
|
|
186
188
|
onSuccess: (wire) => Effect.succeed(wire)
|
|
187
189
|
});
|
|
188
|
-
const httpRequest = HttpClientRequest.post(url).pipe(HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire)), HttpClientRequest.accept("text/event-stream"));
|
|
190
|
+
const httpRequest = HttpClientRequest.post(url).pipe(HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire, cfg)), HttpClientRequest.accept("text/event-stream"));
|
|
189
191
|
return providerEventsOfResponse(yield* client.execute(httpRequest).pipe(Effect.mapError((cause) => new AiError.Unavailable({
|
|
190
192
|
provider: "responses",
|
|
191
193
|
raw: cause
|
package/dist/Responses.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Responses.mjs","names":[],"sources":["../src/Responses.ts"],"sourcesContent":["import { Context, Effect, Layer, Match, Option, Redacted, Result, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as StructuredFormat from \"@effect-uai/core/StructuredFormat\"\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, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport type { Turn, TurnEvent } from \"@effect-uai/core/Turn\"\nimport { itemsToInput } from \"./codec.js\"\nimport { renderProviderTools } from \"./ResponsesTools.js\"\n\nexport {\n codeInterpreterTool,\n fileSearchTool,\n webSearchTool,\n type WebSearchOptions,\n type WebSearchFilters,\n type UserLocation,\n} from \"./ResponsesTools.js\"\nimport type { OpenAIModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\nimport {\n KnownProviderEvent,\n ProviderEvent,\n eventToDeltas,\n makeCallIdLookup,\n} from \"./streamEvents.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type ResponsesRequest = Omit<CommonRequest, \"model\"> & {\n /**\n * Narrows `CommonRequest.model` (`string`) to the typed `OpenAIModel`\n * literal union for autocomplete.\n */\n readonly model: OpenAIModel\n readonly reasoning?: { readonly effort: \"low\" | \"medium\" | \"high\" }\n readonly store?: boolean\n readonly previousResponseId?: string\n readonly instructions?: string\n readonly parallelToolCalls?: boolean\n readonly metadata?: Readonly<Record<string, string>>\n readonly user?: string\n readonly safetyIdentifier?: string\n readonly promptCacheKey?: string\n readonly truncation?: \"auto\" | \"disabled\"\n /**\n * Free-form JSON output: model emits valid JSON without schema\n * constraints. Mutually exclusive with `structured` (schema wins if\n * both are set).\n */\n readonly responseFormat?: { readonly type: \"json_object\" }\n /**\n * Answer length / level-of-detail hint. GPT-5+ models honour it;\n * earlier models ignore.\n */\n readonly verbosity?: \"low\" | \"medium\" | \"high\"\n}\n\nexport type ResponsesService = {\n /**\n * Stream the provider's native event vocabulary (post-SSE-decode).\n * Use this when you need full vendor fidelity. For provider-portable\n * code, use `streamTurn` instead.\n */\n readonly streamNative: (\n request: ResponsesRequest,\n ) => Stream.Stream<ProviderEvent, AiError.AiError>\n /**\n * Stream canonical `TurnEvent`s. Implemented as\n * `streamNative |> toCanonical`.\n */\n readonly streamTurn: (request: ResponsesRequest) => Stream.Stream<TurnEvent, AiError.AiError>\n /**\n * Drain a single turn and return the assembled `Turn`. Derived from\n * `streamTurn` — Responses doesn't expose a native non-streaming\n * complete endpoint we'd want to take advantage of.\n */\n readonly turn: (request: ResponsesRequest) => Effect.Effect<Turn, AiError.AiError>\n /**\n * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n * Exposed for cases where consumers want to compose with `streamNative`\n * directly (e.g. tap into natives + still get canonical downstream).\n */\n readonly toCanonical: <E, R>(\n s: Stream.Stream<ProviderEvent, E, R>,\n ) => Stream.Stream<TurnEvent, E, R>\n}\n\n/**\n * Provider-typed service tag. Yield this when you want Responses-specific\n * options (`reasoning.effort`, `store`, `previousResponseId`) at the call\n * site. Yield the generic `LanguageModel` tag for provider-portable code -\n * both are registered by `layer`.\n */\nexport class Responses extends Context.Service<Responses, ResponsesService>()(\n \"@betalyra/effect-uai/providers/responses/Responses\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Request body\n// ---------------------------------------------------------------------------\n\nconst jsonSchemaFormat = (\n format: StructuredFormat.StructuredFormat<unknown>,\n): Record<string, unknown> => ({\n type: \"json_schema\",\n name: format.name,\n schema: format.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n ...(format.description !== undefined && { description: format.description }),\n ...(format.strict !== undefined && { strict: format.strict }),\n})\n\nconst buildText = (request: ResponsesRequest): Record<string, unknown> | undefined => {\n const format =\n request.structured !== undefined ? jsonSchemaFormat(request.structured) : request.responseFormat\n const text: Record<string, unknown> = {}\n if (format !== undefined) text.format = format\n if (request.verbosity !== undefined) text.verbosity = request.verbosity\n return Object.keys(text).length === 0 ? undefined : text\n}\n\nconst buildBody = (\n request: ResponsesRequest,\n providerToolWire: ReadonlyArray<Record<string, unknown>>,\n): Record<string, unknown> => {\n const text = buildText(request)\n const functionTools = descriptorsOf(request.tools).map((t) => ({\n type: \"function\",\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict !== undefined && { strict: t.strict }),\n }))\n const tools = [...functionTools, ...providerToolWire]\n return {\n model: request.model,\n input: itemsToInput(request.history),\n stream: true,\n ...(tools.length > 0 && { tools }),\n ...(request.toolChoice !== undefined && { tool_choice: request.toolChoice }),\n ...(request.temperature !== undefined && { temperature: request.temperature }),\n ...(request.maxOutputTokens !== undefined && {\n max_output_tokens: request.maxOutputTokens,\n }),\n ...(request.reasoning !== undefined && { reasoning: request.reasoning }),\n ...(request.store !== undefined && { store: request.store }),\n ...(request.previousResponseId !== undefined && {\n previous_response_id: request.previousResponseId,\n }),\n ...(request.instructions !== undefined && { instructions: request.instructions }),\n ...(request.topP !== undefined && { top_p: request.topP }),\n ...(request.parallelToolCalls !== undefined && {\n parallel_tool_calls: request.parallelToolCalls,\n }),\n ...(request.metadata !== undefined && { metadata: request.metadata }),\n ...(request.user !== undefined && { user: request.user }),\n ...(request.safetyIdentifier !== undefined && {\n safety_identifier: request.safetyIdentifier,\n }),\n ...(request.promptCacheKey !== undefined && {\n prompt_cache_key: request.promptCacheKey,\n }),\n ...(request.truncation !== undefined && { truncation: request.truncation }),\n ...(text !== undefined && { text }),\n }\n}\n\n// ---------------------------------------------------------------------------\n// SSE event → provider event\n// ---------------------------------------------------------------------------\n\nconst decodeKnown = Schema.decodeUnknownEffect(KnownProviderEvent)\n\nconst makeUnknown = (raw: unknown): ProviderEvent => ({ type: \"_unknown\", raw })\n\n/**\n * Lift events that carry a terminal failure signal (`error`,\n * `response.failed`) to a typed `AiError`. Other events are not failures\n * and produce `Option.none`.\n */\nconst eventToError = Match.type<ProviderEvent>().pipe(\n Match.discriminators(\"type\")({\n error: (e): AiError.AiError => {\n const detail = e.error\n const message = detail?.message ?? e.message\n const code = detail?.code ?? e.code\n const param = detail?.param\n // A top-level SSE `error` is usually a request rejection (bad model,\n // missing access, malformed body): non-retryable, so `InvalidRequest`.\n return detail?.type === \"invalid_request_error\"\n ? new AiError.InvalidRequest({\n provider: \"responses\",\n ...(param != null && { param }),\n raw: e,\n })\n : new AiError.GenerationFailed({\n provider: \"responses\",\n ...(code != null && { code }),\n ...(message != null && { message }),\n raw: e,\n })\n },\n \"response.failed\": (e): AiError.AiError => {\n const code = e.response.error?.code\n const message = e.response.error?.message\n return new AiError.GenerationFailed({\n provider: \"responses\",\n ...(code !== undefined && code !== null && { code }),\n ...(message !== undefined && message !== null && { message }),\n raw: e,\n })\n },\n }),\n Match.option,\n)\n\nconst parseJsonUnknown = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))\n\nconst sseEventToProviderEvent = (ev: SSE.Event): Effect.Effect<ProviderEvent> =>\n parseJsonUnknown(ev.data).pipe(\n Effect.flatMap((parsed) =>\n decodeKnown(parsed).pipe(Effect.orElseSucceed(() => makeUnknown(parsed))),\n ),\n Effect.orElseSucceed(() => makeUnknown(ev.data)),\n )\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nexport const httpStatusError = (status: number, body: string): AiError.AiError => {\n const provider = \"responses\"\n const raw = body\n if (status === 429) return new AiError.RateLimited({ provider, raw })\n if (status === 408 || status === 504) return new AiError.Timeout({ provider, raw })\n if (status === 401) return new AiError.AuthFailed({ provider, subtype: \"auth\", raw })\n if (status === 403) return new AiError.AuthFailed({ provider, subtype: \"permission\", raw })\n if (status === 402) return new AiError.AuthFailed({ provider, subtype: \"billing\", raw })\n if (status === 413) return new AiError.ContextLengthExceeded({ provider, raw })\n if (status >= 500) return new AiError.Unavailable({ provider, status, raw })\n return new AiError.InvalidRequest({ provider, raw })\n}\n\n/**\n * Decode an already-executed `/responses` HTTP response into the native\n * `ProviderEvent` stream: fail on a >=400 status, else SSE-decode the body and\n * lift terminal `error` / `response.failed` events to a typed `AiError`. Shared\n * by the streaming turn path (POST) and the deep-research resume stream (GET\n * `?stream=true`).\n */\nexport const providerEventsOfResponse = (\n response: HttpClientResponse.HttpClientResponse,\n): Stream.Stream<ProviderEvent, AiError.AiError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n if (response.status >= 400) {\n const body = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return Stream.fail(httpStatusError(response.status, body))\n }\n return response.stream.pipe(\n Stream.mapError((cause) => new AiError.Unavailable({ provider: \"responses\", raw: cause })),\n SSE.fromBytes,\n Stream.mapEffect(sseEventToProviderEvent),\n Stream.flatMap((event) =>\n Option.match(eventToError(event), {\n onNone: () => Stream.succeed(event),\n onSome: Stream.fail,\n }),\n ),\n )\n }),\n )\n\nconst buildNativeStream = (cfg: Config) => {\n const url = `${resolveHost(cfg)}/responses`\n return (\n request: ResponsesRequest,\n ): Stream.Stream<ProviderEvent, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const providerToolWire = yield* Result.match(\n renderProviderTools(providerToolsOf(request.tools)),\n {\n onFailure: (e) =>\n Effect.fail(\n new AiError.Unsupported({\n provider: \"responses\",\n capability: e.capability,\n reason: e.reason,\n }),\n ),\n onSuccess: (wire) => Effect.succeed(wire),\n },\n )\n const httpRequest = HttpClientRequest.post(url).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire)),\n HttpClientRequest.accept(\"text/event-stream\"),\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(\n Effect.mapError(\n (cause) => new AiError.Unavailable({ provider: \"responses\", raw: cause }),\n ),\n )\n return providerEventsOfResponse(response)\n }),\n )\n}\n\n/**\n * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n * Threads a fresh `CallIdLookup` per stream so `function_call_arguments.delta`\n * can be tagged with the right `call_id`.\n */\nexport const toCanonical = <E, R>(\n s: Stream.Stream<ProviderEvent, E, R>,\n): Stream.Stream<TurnEvent, E, R> =>\n Stream.unwrap(\n Effect.sync(() => {\n const lookup = makeCallIdLookup()\n return s.pipe(Stream.flatMap((event) => Stream.fromIterable(eventToDeltas(event, lookup))))\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Build a `ResponsesService` value. For Layer-based setup, prefer `layer`.\n */\nexport const make = (cfg: Config): Effect.Effect<ResponsesService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => {\n const streamNative: ResponsesService[\"streamNative\"] = (request) =>\n buildNativeStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client))\n const streamTurn: ResponsesService[\"streamTurn\"] = (request) =>\n toCanonical(streamNative(request))\n return {\n streamNative,\n streamTurn,\n turn: turnFromStream(streamTurn),\n toCanonical,\n }\n })\n\n/**\n * Layer that registers both the provider-specific `Responses` tag and the\n * generic `LanguageModel` tag, sharing one underlying implementation.\n *\n * The generic tag accepts `CommonRequest`; the typed tag accepts the full\n * `ResponsesRequest` surface.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<Responses | LanguageModel, never, HttpClient.HttpClient> => {\n const typed = Layer.effect(Responses, make(cfg))\n const generic = Layer.effect(\n LanguageModel,\n Effect.map(\n make(cfg),\n (s): LanguageModelService => ({\n streamTurn: (request) => s.streamTurn(request as ResponsesRequest),\n turn: (request) => s.turn(request as ResponsesRequest),\n }),\n ),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGA,IAAa,YAAb,cAA+B,QAAQ,SAAsC,CAC3E,qDACD,CAAC;AAYF,MAAM,oBACJ,YAC6B;CAC7B,MAAM;CACN,MAAM,OAAO;CACb,QAAQ,OAAO,OAAO,aAAa,WAAW,MAAM,EAAE,QAAQ,iBAAiB,CAAC;CAChF,GAAI,OAAO,gBAAgB,KAAA,KAAa,EAAE,aAAa,OAAO,aAAa;CAC3E,GAAI,OAAO,WAAW,KAAA,KAAa,EAAE,QAAQ,OAAO,QAAQ;CAC7D;AAED,MAAM,aAAa,YAAmE;CACpF,MAAM,SACJ,QAAQ,eAAe,KAAA,IAAY,iBAAiB,QAAQ,WAAW,GAAG,QAAQ;CACpF,MAAM,OAAgC,EAAE;AACxC,KAAI,WAAW,KAAA,EAAW,MAAK,SAAS;AACxC,KAAI,QAAQ,cAAc,KAAA,EAAW,MAAK,YAAY,QAAQ;AAC9D,QAAO,OAAO,KAAK,KAAK,CAAC,WAAW,IAAI,KAAA,IAAY;;AAGtD,MAAM,aACJ,SACA,qBAC4B;CAC5B,MAAM,OAAO,UAAU,QAAQ;CAQ/B,MAAM,QAAQ,CAAC,GAPO,cAAc,QAAQ,MAAM,CAAC,KAAK,OAAO;EAC7D,MAAM;EACN,MAAM,EAAE;EACR,aAAa,EAAE;EACf,YAAY,EAAE;EACd,GAAI,EAAE,WAAW,KAAA,KAAa,EAAE,QAAQ,EAAE,QAAQ;EACnD,EAC8B,EAAE,GAAG,iBAAiB;AACrD,QAAO;EACL,OAAO,QAAQ;EACf,OAAO,aAAa,QAAQ,QAAQ;EACpC,QAAQ;EACR,GAAI,MA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AAY,SAAS,OAAO,QAAQ,KAAK;GAC1C,CACF;EACD,MAAM,cAAc,kBAAkB,KAAK,IAAI,CAAC,KAC9C,kBAAkB,YAAY,IAAI,OAAO,EACzC,kBAAkB,eAAe,UAAU,SAAS,iBAAiB,CAAC,EACtE,kBAAkB,OAAO,oBAAoB,CAC9C;AAQD,SAAO,yBAAyB,OAPR,OACrB,QAAQ,YAAY,CACpB,KACC,OAAO,UACJ,UAAU,IAAI,QAAQ,YAAY;GAAE,UAAU;GAAa,KAAK;GAAO,CAAC,CAC1E,CACF,CACsC;GACzC,CACH;;;;;;;AAQL,MAAa,eACX,MAEA,OAAO,OACL,OAAO,WAAW;CAChB,MAAM,SAAS,kBAAkB;AACjC,QAAO,EAAE,KAAK,OAAO,SAAS,UAAU,OAAO,aAAa,cAAc,OAAO,OAAO,CAAC,CAAC,CAAC;EAC3F,CACH;;;;AASH,MAAa,QAAQ,QACnB,OAAO,IAAI,WAAW,aAAa,WAAW;CAC5C,MAAM,gBAAkD,YACtD,kBAAkB,IAAI,CAAC,QAAQ,CAAC,KAAK,OAAO,eAAe,WAAW,YAAY,OAAO,CAAC;CAC5F,MAAM,cAA8C,YAClD,YAAY,aAAa,QAAQ,CAAC;AACpC,QAAO;EACL;EACA;EACA,MAAM,eAAe,WAAW;EAChC;EACD;EACD;;;;;;;;AASJ,MAAa,SACX,QACyE;CACzE,MAAM,QAAQ,MAAM,OAAO,WAAW,KAAK,IAAI,CAAC;CAChD,MAAM,UAAU,MAAM,OACpB,eACA,OAAO,IACL,KAAK,IAAI,GACR,OAA6B;EAC5B,aAAa,YAAY,EAAE,WAAW,QAA4B;EAClE,OAAO,YAAY,EAAE,KAAK,QAA4B;EACvD,EACF,CACF;AACD,QAAO,MAAM,MAAM,OAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"Responses.mjs","names":[],"sources":["../src/Responses.ts"],"sourcesContent":["import { Context, Effect, Layer, Match, Option, Redacted, Result, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as StructuredFormat from \"@effect-uai/core/StructuredFormat\"\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, providerToolsOf } from \"@effect-uai/core/Tool\"\nimport type { Turn, TurnEvent } from \"@effect-uai/core/Turn\"\nimport { itemsToInput } from \"./codec.js\"\nimport { renderProviderTools } from \"./ResponsesTools.js\"\n\nexport {\n codeInterpreterTool,\n fileSearchTool,\n webSearchTool,\n type WebSearchOptions,\n type WebSearchFilters,\n type UserLocation,\n} from \"./ResponsesTools.js\"\nimport type { OpenAIModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\nimport {\n KnownProviderEvent,\n ProviderEvent,\n eventToDeltas,\n makeCallIdLookup,\n} from \"./streamEvents.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\nexport type ResponsesRequest = Omit<CommonRequest, \"model\"> & {\n /**\n * Narrows `CommonRequest.model` (`string`) to the typed `OpenAIModel`\n * literal union for autocomplete.\n */\n readonly model: OpenAIModel\n readonly reasoning?: { readonly effort: \"low\" | \"medium\" | \"high\" }\n readonly store?: boolean\n readonly previousResponseId?: string\n readonly instructions?: string\n readonly parallelToolCalls?: boolean\n readonly metadata?: Readonly<Record<string, string>>\n readonly user?: string\n readonly safetyIdentifier?: string\n readonly promptCacheKey?: string\n readonly truncation?: \"auto\" | \"disabled\"\n /**\n * Vendor-specific body fields merged into the request as-is.\n *\n * The Responses dialect is spoken by gateways as well as by OpenAI, and a\n * gateway carries its own parameters — Requesty's `{ requesty: { auto_cache:\n * true } }`, for example. Modelling each one would tie this provider to a\n * catalogue of gateways it cannot see; passing them through keeps the typed\n * surface OpenAI's and the untyped surface open.\n *\n * Merged over the built body, so a field named here wins over the one this\n * provider would have sent. Per-request keys win over the layer's\n * {@link Config.extraBody}.\n */\n readonly extraBody?: Readonly<Record<string, unknown>>\n /**\n * Free-form JSON output: model emits valid JSON without schema\n * constraints. Mutually exclusive with `structured` (schema wins if\n * both are set).\n */\n readonly responseFormat?: { readonly type: \"json_object\" }\n /**\n * Answer length / level-of-detail hint. GPT-5+ models honour it;\n * earlier models ignore.\n */\n readonly verbosity?: \"low\" | \"medium\" | \"high\"\n}\n\nexport type ResponsesService = {\n /**\n * Stream the provider's native event vocabulary (post-SSE-decode).\n * Use this when you need full vendor fidelity. For provider-portable\n * code, use `streamTurn` instead.\n */\n readonly streamNative: (\n request: ResponsesRequest,\n ) => Stream.Stream<ProviderEvent, AiError.AiError>\n /**\n * Stream canonical `TurnEvent`s. Implemented as\n * `streamNative |> toCanonical`.\n */\n readonly streamTurn: (request: ResponsesRequest) => Stream.Stream<TurnEvent, AiError.AiError>\n /**\n * Drain a single turn and return the assembled `Turn`. Derived from\n * `streamTurn` — Responses doesn't expose a native non-streaming\n * complete endpoint we'd want to take advantage of.\n */\n readonly turn: (request: ResponsesRequest) => Effect.Effect<Turn, AiError.AiError>\n /**\n * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n * Exposed for cases where consumers want to compose with `streamNative`\n * directly (e.g. tap into natives + still get canonical downstream).\n */\n readonly toCanonical: <E, R>(\n s: Stream.Stream<ProviderEvent, E, R>,\n ) => Stream.Stream<TurnEvent, E, R>\n}\n\n/**\n * Provider-typed service tag. Yield this when you want Responses-specific\n * options (`reasoning.effort`, `store`, `previousResponseId`) at the call\n * site. Yield the generic `LanguageModel` tag for provider-portable code -\n * both are registered by `layer`.\n */\nexport class Responses extends Context.Service<Responses, ResponsesService>()(\n \"@betalyra/effect-uai/providers/responses/Responses\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n readonly region?: OpenAiRegion\n /**\n * Vendor-specific body fields sent on every request from this layer — the\n * place for a gateway's standing configuration, so call sites do not repeat\n * it. Overridden per request by {@link ResponsesRequest.extraBody}.\n */\n readonly extraBody?: Readonly<Record<string, unknown>>\n}\n\n// ---------------------------------------------------------------------------\n// Request body\n// ---------------------------------------------------------------------------\n\nconst jsonSchemaFormat = (\n format: StructuredFormat.StructuredFormat<unknown>,\n): Record<string, unknown> => ({\n type: \"json_schema\",\n name: format.name,\n schema: format.schema[\"~standard\"].jsonSchema.input({ target: \"draft-2020-12\" }),\n ...(format.description !== undefined && { description: format.description }),\n ...(format.strict !== undefined && { strict: format.strict }),\n})\n\nconst buildText = (request: ResponsesRequest): Record<string, unknown> | undefined => {\n const format =\n request.structured !== undefined ? jsonSchemaFormat(request.structured) : request.responseFormat\n const text: Record<string, unknown> = {}\n if (format !== undefined) text.format = format\n if (request.verbosity !== undefined) text.verbosity = request.verbosity\n return Object.keys(text).length === 0 ? undefined : text\n}\n\nconst buildBody = (\n request: ResponsesRequest,\n providerToolWire: ReadonlyArray<Record<string, unknown>>,\n cfg: Config,\n): Record<string, unknown> => {\n const text = buildText(request)\n const functionTools = descriptorsOf(request.tools).map((t) => ({\n type: \"function\",\n name: t.name,\n description: t.description,\n parameters: t.inputSchema,\n ...(t.strict !== undefined && { strict: t.strict }),\n }))\n const tools = [...functionTools, ...providerToolWire]\n return {\n model: request.model,\n input: itemsToInput(request.history),\n stream: true,\n ...(tools.length > 0 && { tools }),\n ...(request.toolChoice !== undefined && { tool_choice: request.toolChoice }),\n ...(request.temperature !== undefined && { temperature: request.temperature }),\n ...(request.maxOutputTokens !== undefined && {\n max_output_tokens: request.maxOutputTokens,\n }),\n ...(request.reasoning !== undefined && { reasoning: request.reasoning }),\n ...(request.store !== undefined && { store: request.store }),\n ...(request.previousResponseId !== undefined && {\n previous_response_id: request.previousResponseId,\n }),\n ...(request.instructions !== undefined && { instructions: request.instructions }),\n ...(request.topP !== undefined && { top_p: request.topP }),\n ...(request.parallelToolCalls !== undefined && {\n parallel_tool_calls: request.parallelToolCalls,\n }),\n ...(request.metadata !== undefined && { metadata: request.metadata }),\n ...(request.user !== undefined && { user: request.user }),\n ...(request.safetyIdentifier !== undefined && {\n safety_identifier: request.safetyIdentifier,\n }),\n ...(request.promptCacheKey !== undefined && {\n prompt_cache_key: request.promptCacheKey,\n }),\n ...(request.truncation !== undefined && { truncation: request.truncation }),\n ...(text !== undefined && { text }),\n ...cfg.extraBody,\n ...request.extraBody,\n }\n}\n\n// ---------------------------------------------------------------------------\n// SSE event → provider event\n// ---------------------------------------------------------------------------\n\nconst decodeKnown = Schema.decodeUnknownEffect(KnownProviderEvent)\n\nconst makeUnknown = (raw: unknown): ProviderEvent => ({ type: \"_unknown\", raw })\n\n/**\n * Lift events that carry a terminal failure signal (`error`,\n * `response.failed`) to a typed `AiError`. Other events are not failures\n * and produce `Option.none`.\n */\nconst eventToError = Match.type<ProviderEvent>().pipe(\n Match.discriminators(\"type\")({\n error: (e): AiError.AiError => {\n const detail = e.error\n const message = detail?.message ?? e.message\n const code = detail?.code ?? e.code\n const param = detail?.param\n // A top-level SSE `error` is usually a request rejection (bad model,\n // missing access, malformed body): non-retryable, so `InvalidRequest`.\n return detail?.type === \"invalid_request_error\"\n ? new AiError.InvalidRequest({\n provider: \"responses\",\n ...(param != null && { param }),\n raw: e,\n })\n : new AiError.GenerationFailed({\n provider: \"responses\",\n ...(code != null && { code }),\n ...(message != null && { message }),\n raw: e,\n })\n },\n \"response.failed\": (e): AiError.AiError => {\n const code = e.response.error?.code\n const message = e.response.error?.message\n return new AiError.GenerationFailed({\n provider: \"responses\",\n ...(code !== undefined && code !== null && { code }),\n ...(message !== undefined && message !== null && { message }),\n raw: e,\n })\n },\n }),\n Match.option,\n)\n\nconst parseJsonUnknown = Schema.decodeUnknownEffect(Schema.fromJsonString(Schema.Unknown))\n\nconst sseEventToProviderEvent = (ev: SSE.Event): Effect.Effect<ProviderEvent> =>\n parseJsonUnknown(ev.data).pipe(\n Effect.flatMap((parsed) =>\n decodeKnown(parsed).pipe(Effect.orElseSucceed(() => makeUnknown(parsed))),\n ),\n Effect.orElseSucceed(() => makeUnknown(ev.data)),\n )\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nexport const httpStatusError = (status: number, body: string): AiError.AiError => {\n const provider = \"responses\"\n const raw = body\n if (status === 429) return new AiError.RateLimited({ provider, raw })\n if (status === 408 || status === 504) return new AiError.Timeout({ provider, raw })\n if (status === 401) return new AiError.AuthFailed({ provider, subtype: \"auth\", raw })\n if (status === 403) return new AiError.AuthFailed({ provider, subtype: \"permission\", raw })\n if (status === 402) return new AiError.AuthFailed({ provider, subtype: \"billing\", raw })\n if (status === 413) return new AiError.ContextLengthExceeded({ provider, raw })\n if (status >= 500) return new AiError.Unavailable({ provider, status, raw })\n return new AiError.InvalidRequest({ provider, raw })\n}\n\n/**\n * Decode an already-executed `/responses` HTTP response into the native\n * `ProviderEvent` stream: fail on a >=400 status, else SSE-decode the body and\n * lift terminal `error` / `response.failed` events to a typed `AiError`. Shared\n * by the streaming turn path (POST) and the deep-research resume stream (GET\n * `?stream=true`).\n */\nexport const providerEventsOfResponse = (\n response: HttpClientResponse.HttpClientResponse,\n): Stream.Stream<ProviderEvent, AiError.AiError> =>\n Stream.unwrap(\n Effect.gen(function* () {\n if (response.status >= 400) {\n const body = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return Stream.fail(httpStatusError(response.status, body))\n }\n return response.stream.pipe(\n Stream.mapError((cause) => new AiError.Unavailable({ provider: \"responses\", raw: cause })),\n SSE.fromBytes,\n Stream.mapEffect(sseEventToProviderEvent),\n Stream.flatMap((event) =>\n Option.match(eventToError(event), {\n onNone: () => Stream.succeed(event),\n onSome: Stream.fail,\n }),\n ),\n )\n }),\n )\n\nconst buildNativeStream = (cfg: Config) => {\n const url = `${resolveHost(cfg)}/responses`\n return (\n request: ResponsesRequest,\n ): Stream.Stream<ProviderEvent, AiError.AiError, HttpClient.HttpClient> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const providerToolWire = yield* Result.match(\n renderProviderTools(providerToolsOf(request.tools)),\n {\n onFailure: (e) =>\n Effect.fail(\n new AiError.Unsupported({\n provider: \"responses\",\n capability: e.capability,\n reason: e.reason,\n }),\n ),\n onSuccess: (wire) => Effect.succeed(wire),\n },\n )\n const httpRequest = HttpClientRequest.post(url).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire, cfg)),\n HttpClientRequest.accept(\"text/event-stream\"),\n )\n const response = yield* client\n .execute(httpRequest)\n .pipe(\n Effect.mapError(\n (cause) => new AiError.Unavailable({ provider: \"responses\", raw: cause }),\n ),\n )\n return providerEventsOfResponse(response)\n }),\n )\n}\n\n/**\n * Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.\n * Threads a fresh `CallIdLookup` per stream so `function_call_arguments.delta`\n * can be tagged with the right `call_id`.\n */\nexport const toCanonical = <E, R>(\n s: Stream.Stream<ProviderEvent, E, R>,\n): Stream.Stream<TurnEvent, E, R> =>\n Stream.unwrap(\n Effect.sync(() => {\n const lookup = makeCallIdLookup()\n return s.pipe(Stream.flatMap((event) => Stream.fromIterable(eventToDeltas(event, lookup))))\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Build a `ResponsesService` value. For Layer-based setup, prefer `layer`.\n */\nexport const make = (cfg: Config): Effect.Effect<ResponsesService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => {\n const streamNative: ResponsesService[\"streamNative\"] = (request) =>\n buildNativeStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client))\n const streamTurn: ResponsesService[\"streamTurn\"] = (request) =>\n toCanonical(streamNative(request))\n return {\n streamNative,\n streamTurn,\n turn: turnFromStream(streamTurn),\n toCanonical,\n }\n })\n\n/**\n * Layer that registers both the provider-specific `Responses` tag and the\n * generic `LanguageModel` tag, sharing one underlying implementation.\n *\n * The generic tag accepts `CommonRequest`; the typed tag accepts the full\n * `ResponsesRequest` surface.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<Responses | LanguageModel, never, HttpClient.HttpClient> => {\n const typed = Layer.effect(Responses, make(cfg))\n const generic = Layer.effect(\n LanguageModel,\n Effect.map(\n make(cfg),\n (s): LanguageModelService => ({\n streamTurn: (request) => s.streamTurn(request as ResponsesRequest),\n turn: (request) => s.turn(request as ResponsesRequest),\n }),\n ),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoHA,IAAa,YAAb,cAA+B,QAAQ,SAAsC,CAC3E,qDACD,CAAC;AAkBF,MAAM,oBACJ,YAC6B;CAC7B,MAAM;CACN,MAAM,OAAO;CACb,QAAQ,OAAO,OAAO,aAAa,WAAW,MAAM,EAAE,QAAQ,iBAAiB,CAAC;CAChF,GAAI,OAAO,gBAAgB,KAAA,KAAa,EAAE,aAAa,OAAO,aAAa;CAC3E,GAAI,OAAO,WAAW,KAAA,KAAa,EAAE,QAAQ,OAAO,QAAQ;CAC7D;AAED,MAAM,aAAa,YAAmE;CACpF,MAAM,SACJ,QAAQ,eAAe,KAAA,IAAY,iBAAiB,QAAQ,WAAW,GAAG,QAAQ;CACpF,MAAM,OAAgC,EAAE;AACxC,KAAI,WAAW,KAAA,EAAW,MAAK,SAAS;AACxC,KAAI,QAAQ,cAAc,KAAA,EAAW,MAAK,YAAY,QAAQ;AAC9D,QAAO,OAAO,KAAK,KAAK,CAAC,WAAW,IAAI,KAAA,IAAY;;AAGtD,MAAM,aACJ,SACA,kBACA,QAC4B;CAC5B,MAAM,OAAO,UAAU,QAAQ;CAQ/B,MAAM,QAAQ,CAAC,GAPO,cAAc,QAAQ,MAAM,CAAC,KAAK,OAAO;EAC7D,MAAM;EACN,MAAM,EAAE;EACR,aAAa,EAAE;EACf,YAAY,EAAE;EACd,GAAI,EAAE,WAAW,KAAA,KAAa,EAAE,Q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EACvD,EACF,CACF;AACD,QAAO,MAAM,MAAM,OAAO,QAAQ"}
|
package/dist/codec.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;cAqCa,cAAA,EAAc,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;cAkEd,cAAA,EAAc,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAQf,cAAA,UAAwB,cAAA,CAAe,IAAA;AAAA,cA6BtC,qBAAA,EAAqB,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KActB,qBAAA,UAA+B,qBAAA,CAAsB,IAAA;;
|
|
1
|
+
{"version":3,"file":"codec.d.mts","names":[],"sources":["../src/codec.ts"],"mappings":";;;;;;;;cAqCa,cAAA,EAAc,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;cAkEd,cAAA,EAAc,MAAA,CAAA,KAAA,WAAA,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAQf,cAAA,UAAwB,cAAA,CAAe,IAAA;AAAA,cA6BtC,qBAAA,EAAqB,MAAA,CAAA,MAAA;EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KActB,qBAAA,UAA+B,qBAAA,CAAsB,IAAA;;cA8FpD,YAAA,GACX,KAAA,EAAO,aAAA,CAAc,WAAA,MACpB,aAAA,CAAc,MAAA;AAAA,cAiBJ,cAAA,GAAkB,IAAA,EAAM,cAAA,KAAiB,aAAA,CAAc,WAAA;AAAA,cAwEvD,iBAAA,GAAqB,OAAA,EAAS,qBAAA,KAAwB,IAAA"}
|
package/dist/codec.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
|
|
2
|
-
import { Encoding, Match, Option, Schema } from "effect";
|
|
2
|
+
import { Encoding, Match, Option, Result, Schema, pipe } from "effect";
|
|
3
3
|
//#region src/codec.ts
|
|
4
4
|
var codec_exports = /* @__PURE__ */ __exportAll({
|
|
5
5
|
WireAnnotation: () => WireAnnotation,
|
|
@@ -114,11 +114,33 @@ const WireResponseCompleted = Schema.Struct({
|
|
|
114
114
|
error: Schema.optional(Schema.NullOr(WireResponseError))
|
|
115
115
|
});
|
|
116
116
|
/**
|
|
117
|
-
*
|
|
118
|
-
*
|
|
119
|
-
*
|
|
117
|
+
* The item shapes we stash for round-tripping. Narrower than
|
|
118
|
+
* `WireOutputItem`: the provider-hosted call variants are dropped from the
|
|
119
|
+
* turn, so they are never stored. Composed from the internal `Wire*` structs,
|
|
120
|
+
* which keeps the wire model out of the package's public surface.
|
|
120
121
|
*/
|
|
121
|
-
const
|
|
122
|
+
const StoredItem = Schema.Union([
|
|
123
|
+
WireMessage,
|
|
124
|
+
WireFunctionCall,
|
|
125
|
+
WireReasoning
|
|
126
|
+
]);
|
|
127
|
+
const ProviderDataResponses = Schema.Struct({ responses: StoredItem });
|
|
128
|
+
const decodeResponsesData = Schema.decodeUnknownResult(ProviderDataResponses);
|
|
129
|
+
/**
|
|
130
|
+
* If an item carries `providerData.responses` from a prior turn on this API,
|
|
131
|
+
* re-emit it verbatim - preserves `encrypted_content` and item ids, which a
|
|
132
|
+
* fresh encode from our `HistoryItem` shape cannot reconstruct.
|
|
133
|
+
*
|
|
134
|
+
* Namespaced because `providerData` is a shared slot: an item routed through
|
|
135
|
+
* another provider first (dynamic fallback) carries that provider's key, and
|
|
136
|
+
* re-emitting the whole object would send that provider's data as the wire
|
|
137
|
+
* item and drop the real content. Anything that fails to decode is not ours,
|
|
138
|
+
* so we fall back to encoding the item normally.
|
|
139
|
+
*/
|
|
140
|
+
const passthrough = (item) => pipe(decodeResponsesData(item.providerData), Result.match({
|
|
141
|
+
onSuccess: (data) => data.responses,
|
|
142
|
+
onFailure: () => void 0
|
|
143
|
+
}));
|
|
122
144
|
/**
|
|
123
145
|
* OpenAI's `input_image` content block carries a single `image_url` field;
|
|
124
146
|
* inline bytes get encoded as a `data:` URI. Either form (URL or data URI)
|
|
@@ -188,21 +210,21 @@ const wireItemToItem = (wire) => Match.value(wire).pipe(Match.discriminatorsExha
|
|
|
188
210
|
type: "message",
|
|
189
211
|
role: m.role,
|
|
190
212
|
content: m.content.map(wireMessageContentToBlock),
|
|
191
|
-
providerData: m
|
|
213
|
+
providerData: { responses: m }
|
|
192
214
|
}],
|
|
193
215
|
function_call: (f) => [{
|
|
194
216
|
type: "function_call",
|
|
195
217
|
call_id: f.call_id,
|
|
196
218
|
name: f.name,
|
|
197
219
|
arguments: f.arguments,
|
|
198
|
-
providerData: f
|
|
220
|
+
providerData: { responses: f }
|
|
199
221
|
}],
|
|
200
222
|
reasoning: (r) => [{
|
|
201
223
|
type: "reasoning",
|
|
202
224
|
...r.id !== void 0 && { id: r.id },
|
|
203
225
|
...r.summary !== void 0 && { summary: r.summary.map((s) => s.text).join("\n") },
|
|
204
226
|
...r.encrypted_content !== void 0 && { signature: r.encrypted_content },
|
|
205
|
-
providerData: r
|
|
227
|
+
providerData: { responses: r }
|
|
206
228
|
}],
|
|
207
229
|
web_search_call: () => [],
|
|
208
230
|
code_interpreter_call: () => [],
|
package/dist/codec.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"codec.mjs","names":[],"sources":["../src/codec.ts"],"sourcesContent":["import { Encoding, Match, Option, Schema } from \"effect\"\nimport type { ContentBlock, InputImage, HistoryItem } from \"@effect-uai/core/Items\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - minimal subset of the Responses API output we consume.\n// Reference: https://www.openresponses.org/specification\n// ---------------------------------------------------------------------------\n\nconst WireUrlCitation = Schema.Struct({\n type: Schema.Literal(\"url_citation\"),\n url: Schema.String,\n start_index: Schema.Number,\n end_index: Schema.Number,\n title: Schema.String,\n})\n\nconst WireFileCitation = Schema.Struct({\n type: Schema.Literal(\"file_citation\"),\n file_id: Schema.String,\n index: Schema.Number,\n})\n\nconst WireContainerFileCitation = Schema.Struct({\n type: Schema.Literal(\"container_file_citation\"),\n container_id: Schema.String,\n file_id: Schema.String,\n start_index: Schema.Number,\n end_index: Schema.Number,\n})\n\nconst WireFilePath = Schema.Struct({\n type: Schema.Literal(\"file_path\"),\n file_id: Schema.String,\n index: Schema.Number,\n})\n\nexport const WireAnnotation = Schema.Union([\n WireUrlCitation,\n WireFileCitation,\n WireContainerFileCitation,\n WireFilePath,\n])\n\nconst WireOutputTextContent = Schema.Struct({\n type: Schema.Literal(\"output_text\"),\n text: Schema.String,\n annotations: Schema.optional(Schema.NullOr(Schema.Array(WireAnnotation))),\n})\n\nconst WireRefusalContent = Schema.Struct({\n type: Schema.Literal(\"refusal\"),\n refusal: Schema.String,\n})\n\nconst WireMessageContent = Schema.Union([WireOutputTextContent, WireRefusalContent])\n\nconst WireSummaryText = Schema.Struct({\n type: Schema.Literal(\"summary_text\"),\n text: Schema.String,\n})\n\nconst WireMessage = Schema.Struct({\n type: Schema.Literal(\"message\"),\n id: Schema.optional(Schema.String),\n role: Schema.Literal(\"assistant\"),\n content: Schema.Array(WireMessageContent),\n})\n\nconst WireFunctionCall = Schema.Struct({\n type: Schema.Literal(\"function_call\"),\n id: Schema.optional(Schema.String),\n call_id: Schema.String,\n name: Schema.String,\n arguments: Schema.String,\n})\n\nconst WireReasoning = Schema.Struct({\n type: Schema.Literal(\"reasoning\"),\n id: Schema.optional(Schema.String),\n summary: Schema.optional(Schema.Array(WireSummaryText)),\n encrypted_content: Schema.optional(Schema.String),\n})\n\n// Provider-hosted tool call items (web search, code interpreter, file search).\n// The provider executes them, not us — we model them only so a grounded\n// `response.completed` still decodes and assembles a Turn; they are dropped\n// from the turn's items in Phase 1. Surfacing them is a follow-up.\nconst WireWebSearchCall = Schema.Struct({\n type: Schema.Literal(\"web_search_call\"),\n id: Schema.optional(Schema.String),\n})\n\nconst WireCodeInterpreterCall = Schema.Struct({\n type: Schema.Literal(\"code_interpreter_call\"),\n id: Schema.optional(Schema.String),\n})\n\nconst WireFileSearchCall = Schema.Struct({\n type: Schema.Literal(\"file_search_call\"),\n id: Schema.optional(Schema.String),\n})\n\nexport const WireOutputItem = Schema.Union([\n WireMessage,\n WireFunctionCall,\n WireReasoning,\n WireWebSearchCall,\n WireCodeInterpreterCall,\n WireFileSearchCall,\n])\nexport type WireOutputItem = typeof WireOutputItem.Type\n\nconst WireInputTokensDetails = Schema.Struct({\n cached_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n})\n\nconst WireOutputTokensDetails = Schema.Struct({\n reasoning_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n})\n\nconst WireUsage = Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n input_tokens_details: Schema.optional(Schema.NullOr(WireInputTokensDetails)),\n output_tokens_details: Schema.optional(Schema.NullOr(WireOutputTokensDetails)),\n})\n\nconst WireResponseError = Schema.Struct({\n code: Schema.optional(Schema.NullOr(Schema.String)),\n message: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\n// Many Responses-API fields are emitted as explicit `null` rather than\n// missing - `Schema.optional` alone (T | undefined) doesn't cover that, so\n// we lift each through `NullOr` first. Used by `response.completed`,\n// `response.incomplete`, and `response.failed` events; not every field is\n// populated on every event (e.g. `error` only on failed, `incomplete_details`\n// only on incomplete).\nexport const WireResponseCompleted = Schema.Struct({\n id: Schema.optional(Schema.NullOr(Schema.String)),\n status: Schema.optional(Schema.NullOr(Schema.String)),\n output: Schema.optional(Schema.NullOr(Schema.Array(WireOutputItem))),\n usage: Schema.optional(Schema.NullOr(WireUsage)),\n incomplete_details: Schema.optional(\n Schema.NullOr(\n Schema.Struct({\n reason: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ),\n ),\n error: Schema.optional(Schema.NullOr(WireResponseError)),\n})\nexport type WireResponseCompleted = typeof WireResponseCompleted.Type\n\n// ---------------------------------------------------------------------------\n// History → request body input\n// ---------------------------------------------------------------------------\n\n/**\n * If an item carries `providerData` from a prior OpenAI turn, re-emit it\n * verbatim - preserves `encrypted_content`, item ids, and any field this\n * codec doesn't model.\n */\nconst passthrough = (item: HistoryItem): Record<string, unknown> | undefined =>\n item.providerData !== undefined &&\n typeof item.providerData === \"object\" &&\n item.providerData !== null\n ? (item.providerData as Record<string, unknown>)\n : undefined\n\n/**\n * OpenAI's `input_image` content block carries a single `image_url` field;\n * inline bytes get encoded as a `data:` URI. Either form (URL or data URI)\n * is fine - the model just dereferences `image_url`.\n */\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 contentBlockToInput = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"input_text\", text: b.text }),\n input_image: (b) => ({\n type: \"input_image\",\n image_url: imageSourceToUrl(b.source),\n }),\n output_text: (b) => ({ type: \"output_text\", text: b.text }),\n refusal: (b) => ({ type: \"refusal\", refusal: b.text }),\n }),\n)\n\nconst itemToInput = (item: HistoryItem): Record<string, unknown> =>\n passthrough(item) ??\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => ({\n type: \"message\",\n role: m.role,\n content: m.content.map(contentBlockToInput),\n }),\n function_call: (f) => ({\n type: \"function_call\",\n call_id: f.call_id,\n name: f.name,\n arguments: f.arguments,\n }),\n function_call_output: (o) => ({\n type: \"function_call_output\",\n call_id: o.call_id,\n output: o.output,\n }),\n reasoning: (r) => ({\n type: \"reasoning\",\n ...(r.id !== undefined && { id: r.id }),\n ...(r.summary !== undefined && {\n summary: [{ type: \"summary_text\", text: r.summary }],\n }),\n ...(r.signature !== undefined && { encrypted_content: r.signature }),\n }),\n }),\n )\n\n/** Convert our `HistoryItem[]` history into the Responses API `input` array. */\nexport const itemsToInput = (\n items: ReadonlyArray<HistoryItem>,\n): ReadonlyArray<Record<string, unknown>> => items.map(itemToInput)\n\n// ---------------------------------------------------------------------------\n// Wire output items → our Items\n// ---------------------------------------------------------------------------\n\nconst wireMessageContentToBlock = Match.type<typeof WireMessageContent.Type>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n output_text: (c): ContentBlock => ({\n type: \"output_text\",\n text: c.text,\n ...(c.annotations !== undefined && c.annotations !== null && { annotations: c.annotations }),\n }),\n refusal: (c): ContentBlock => ({ type: \"refusal\", text: c.refusal }),\n }),\n)\n\nexport const wireItemToItem = (wire: WireOutputItem): ReadonlyArray<HistoryItem> =>\n Match.value(wire).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m): ReadonlyArray<HistoryItem> => [\n {\n type: \"message\" as const,\n role: m.role,\n content: m.content.map(wireMessageContentToBlock),\n providerData: m,\n },\n ],\n function_call: (f): ReadonlyArray<HistoryItem> => [\n {\n type: \"function_call\" as const,\n call_id: f.call_id,\n name: f.name,\n arguments: f.arguments,\n providerData: f,\n },\n ],\n reasoning: (r): ReadonlyArray<HistoryItem> => [\n {\n type: \"reasoning\" as const,\n ...(r.id !== undefined && { id: r.id }),\n ...(r.summary !== undefined && {\n summary: r.summary.map((s) => s.text).join(\"\\n\"),\n }),\n ...(r.encrypted_content !== undefined && { signature: r.encrypted_content }),\n providerData: r,\n },\n ],\n // Hosted-tool calls are provider-executed; drop from the turn (Phase 1).\n web_search_call: (): ReadonlyArray<HistoryItem> => [],\n code_interpreter_call: (): ReadonlyArray<HistoryItem> => [],\n file_search_call: (): ReadonlyArray<HistoryItem> => [],\n }),\n )\n\n// ---------------------------------------------------------------------------\n// response.completed → Turn\n// ---------------------------------------------------------------------------\n\nconst reasonToStop = Match.type<string>().pipe(\n Match.when(\"max_output_tokens\", () => \"max_tokens\" as const),\n Match.when(\"refusal\", () => \"refusal\" as const),\n Match.when(\"content_filter\", () => \"content_filter\" as const),\n Match.when(\"max_tool_calls\", () => \"max_tool_calls\" as const),\n Match.option,\n)\n\nconst hasRefusalContent = (payload: WireResponseCompleted): boolean =>\n (payload.output ?? []).some(\n (i) => i.type === \"message\" && i.content.some((c) => c.type === \"refusal\"),\n )\n\nconst stopReasonFromCompleted = (payload: WireResponseCompleted): Turn[\"stop_reason\"] =>\n Option.match(reasonToStop(payload.incomplete_details?.reason ?? \"\"), {\n onSome: (s) => s,\n onNone: () =>\n hasRefusalContent(payload)\n ? (\"refusal\" as const)\n : (payload.output ?? []).some((i) => i.type === \"function_call\")\n ? (\"tool_calls\" as const)\n : (\"stop\" as const),\n })\n\nconst cachedTokens = (payload: WireResponseCompleted): number | undefined =>\n payload.usage?.input_tokens_details?.cached_tokens ?? undefined\n\nconst reasoningTokens = (payload: WireResponseCompleted): number | undefined =>\n payload.usage?.output_tokens_details?.reasoning_tokens ?? undefined\n\nexport const turnFromCompleted = (payload: WireResponseCompleted): Turn => {\n const cached = cachedTokens(payload)\n const reasoning = reasoningTokens(payload)\n return {\n items: (payload.output ?? []).flatMap(wireItemToItem),\n usage: {\n ...(payload.usage?.input_tokens !== undefined && {\n input_tokens: payload.usage.input_tokens,\n }),\n ...(payload.usage?.output_tokens !== undefined && {\n output_tokens: payload.usage.output_tokens,\n }),\n ...(payload.usage?.total_tokens !== undefined && {\n total_tokens: payload.usage.total_tokens,\n }),\n ...(cached !== undefined && {\n input_tokens_details: { cached_tokens: cached },\n }),\n ...(reasoning !== undefined && {\n output_tokens_details: { reasoning_tokens: reasoning },\n }),\n },\n stop_reason: stopReasonFromCompleted(payload),\n }\n}\n"],"mappings":";;;;;;;;;;;AASA,MAAM,kBAAkB,OAAO,OAAO;CACpC,MAAM,OAAO,QAAQ,eAAe;CACpC,KAAK,OAAO;CACZ,aAAa,OAAO;CACpB,WAAW,OAAO;CAClB,OAAO,OAAO;CACf,CAAC;AAEF,MAAM,mBAAmB,OAAO,OAAO;CACrC,MAAM,OAAO,QAAQ,gBAAgB;CACrC,SAAS,OAAO;CAChB,OAAO,OAAO;CACf,CAAC;AAEF,MAAM,4BAA4B,OAAO,OAAO;CAC9C,MAAM,OAAO,QAAQ,0BAA0B;CAC/C,cAAc,OAAO;CACrB,SAAS,OAAO;CAChB,aAAa,OAAO;CACpB,WAAW,OAAO;CACnB,CAAC;AAEF,MAAM,eAAe,OAAO,OAAO;CACjC,MAAM,OAAO,QAAQ,YAAY;CACjC,SAAS,OAAO;CAChB,OAAO,OAAO;CACf,CAAC;AAEF,MAAa,iBAAiB,OAAO,MAAM;CACzC;CACA;CACA;CACA;CACD,CAAC;AAEF,MAAM,wBAAwB,OAAO,OAAO;CAC1C,MAAM,OAAO,QAAQ,cAAc;CACnC,MAAM,OAAO;CACb,aAAa,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,eAAe,CAAC,CAAC;CAC1E,CAAC;AAEF,MAAM,qBAAqB,OAAO,OAAO;CACvC,MAAM,OAAO,QAAQ,UAAU;CAC/B,SAAS,OAAO;CACjB,CAAC;AAEF,MAAM,qBAAqB,OAAO,MAAM,CAAC,uBAAuB,mBAAmB,CAAC;AAEpF,MAAM,kBAAkB,OAAO,OAAO;CACpC,MAAM,OAAO,QAAQ,eAAe;CACpC,MAAM,OAAO;CACd,CAAC;AAEF,MAAM,cAAc,OAAO,OAAO;CAChC,MAAM,OAAO,QAAQ,UAAU;CAC/B,IAAI,OAAO,SAAS,OAAO,OAAO;CAClC,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,qBAAqB,YAAyC;CACzE,MAAM,SAAS,aAAa,QAAQ;CACpC,MAAM,YAAY,gBAAgB,QAAQ;AAC1C,QAAO;EACL,QAAQ,QAAQ,UAAU,EAAE,EAAE,QAAQ,eAAe;EACrD,OAAO;GACL,GAAI,QAAQ,OAAO,iBAAiB,KAAA,KAAa,EAC/C,cAAc,QAAQ,MAAM,cAC7B;GACD,GAAI,QAAQ,OAAO,kBAAkB,KAAA,KAAa,EAChD,eAAe,QAAQ,MAAM,eAC9B;GACD,GAAI,QAAQ,OAAO,iBAAiB,KAAA,KAAa,EAC/C,cAAc,QAAQ,MAAM,cAC7B;GACD,GAAI,WAAW,KAAA,KAAa,EAC1B,sBAAsB,EAAE,eAAe,QAAQ,EAChD;GACD,GAAI,cAAc,KAAA,KAAa,EAC7B,uBAAuB,EAAE,kBAAkB,WAAW,EACvD;GACF;EACD,aAAa,wBAAwB,QAAQ;EAC9C"}
|
|
1
|
+
{"version":3,"file":"codec.mjs","names":[],"sources":["../src/codec.ts"],"sourcesContent":["import { Encoding, Match, Option, Result, Schema, pipe } from \"effect\"\nimport type { ContentBlock, InputImage, HistoryItem } from \"@effect-uai/core/Items\"\nimport type { Turn } from \"@effect-uai/core/Turn\"\n\n// ---------------------------------------------------------------------------\n// Wire schemas - minimal subset of the Responses API output we consume.\n// Reference: https://www.openresponses.org/specification\n// ---------------------------------------------------------------------------\n\nconst WireUrlCitation = Schema.Struct({\n type: Schema.Literal(\"url_citation\"),\n url: Schema.String,\n start_index: Schema.Number,\n end_index: Schema.Number,\n title: Schema.String,\n})\n\nconst WireFileCitation = Schema.Struct({\n type: Schema.Literal(\"file_citation\"),\n file_id: Schema.String,\n index: Schema.Number,\n})\n\nconst WireContainerFileCitation = Schema.Struct({\n type: Schema.Literal(\"container_file_citation\"),\n container_id: Schema.String,\n file_id: Schema.String,\n start_index: Schema.Number,\n end_index: Schema.Number,\n})\n\nconst WireFilePath = Schema.Struct({\n type: Schema.Literal(\"file_path\"),\n file_id: Schema.String,\n index: Schema.Number,\n})\n\nexport const WireAnnotation = Schema.Union([\n WireUrlCitation,\n WireFileCitation,\n WireContainerFileCitation,\n WireFilePath,\n])\n\nconst WireOutputTextContent = Schema.Struct({\n type: Schema.Literal(\"output_text\"),\n text: Schema.String,\n annotations: Schema.optional(Schema.NullOr(Schema.Array(WireAnnotation))),\n})\n\nconst WireRefusalContent = Schema.Struct({\n type: Schema.Literal(\"refusal\"),\n refusal: Schema.String,\n})\n\nconst WireMessageContent = Schema.Union([WireOutputTextContent, WireRefusalContent])\n\nconst WireSummaryText = Schema.Struct({\n type: Schema.Literal(\"summary_text\"),\n text: Schema.String,\n})\n\nconst WireMessage = Schema.Struct({\n type: Schema.Literal(\"message\"),\n id: Schema.optional(Schema.String),\n role: Schema.Literal(\"assistant\"),\n content: Schema.Array(WireMessageContent),\n})\n\nconst WireFunctionCall = Schema.Struct({\n type: Schema.Literal(\"function_call\"),\n id: Schema.optional(Schema.String),\n call_id: Schema.String,\n name: Schema.String,\n arguments: Schema.String,\n})\n\nconst WireReasoning = Schema.Struct({\n type: Schema.Literal(\"reasoning\"),\n id: Schema.optional(Schema.String),\n summary: Schema.optional(Schema.Array(WireSummaryText)),\n encrypted_content: Schema.optional(Schema.String),\n})\n\n// Provider-hosted tool call items (web search, code interpreter, file search).\n// The provider executes them, not us — we model them only so a grounded\n// `response.completed` still decodes and assembles a Turn; they are dropped\n// from the turn's items in Phase 1. Surfacing them is a follow-up.\nconst WireWebSearchCall = Schema.Struct({\n type: Schema.Literal(\"web_search_call\"),\n id: Schema.optional(Schema.String),\n})\n\nconst WireCodeInterpreterCall = Schema.Struct({\n type: Schema.Literal(\"code_interpreter_call\"),\n id: Schema.optional(Schema.String),\n})\n\nconst WireFileSearchCall = Schema.Struct({\n type: Schema.Literal(\"file_search_call\"),\n id: Schema.optional(Schema.String),\n})\n\nexport const WireOutputItem = Schema.Union([\n WireMessage,\n WireFunctionCall,\n WireReasoning,\n WireWebSearchCall,\n WireCodeInterpreterCall,\n WireFileSearchCall,\n])\nexport type WireOutputItem = typeof WireOutputItem.Type\n\nconst WireInputTokensDetails = Schema.Struct({\n cached_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n})\n\nconst WireOutputTokensDetails = Schema.Struct({\n reasoning_tokens: Schema.optional(Schema.NullOr(Schema.Number)),\n})\n\nconst WireUsage = Schema.Struct({\n input_tokens: Schema.optional(Schema.Number),\n output_tokens: Schema.optional(Schema.Number),\n total_tokens: Schema.optional(Schema.Number),\n input_tokens_details: Schema.optional(Schema.NullOr(WireInputTokensDetails)),\n output_tokens_details: Schema.optional(Schema.NullOr(WireOutputTokensDetails)),\n})\n\nconst WireResponseError = Schema.Struct({\n code: Schema.optional(Schema.NullOr(Schema.String)),\n message: Schema.optional(Schema.NullOr(Schema.String)),\n})\n\n// Many Responses-API fields are emitted as explicit `null` rather than\n// missing - `Schema.optional` alone (T | undefined) doesn't cover that, so\n// we lift each through `NullOr` first. Used by `response.completed`,\n// `response.incomplete`, and `response.failed` events; not every field is\n// populated on every event (e.g. `error` only on failed, `incomplete_details`\n// only on incomplete).\nexport const WireResponseCompleted = Schema.Struct({\n id: Schema.optional(Schema.NullOr(Schema.String)),\n status: Schema.optional(Schema.NullOr(Schema.String)),\n output: Schema.optional(Schema.NullOr(Schema.Array(WireOutputItem))),\n usage: Schema.optional(Schema.NullOr(WireUsage)),\n incomplete_details: Schema.optional(\n Schema.NullOr(\n Schema.Struct({\n reason: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n ),\n ),\n error: Schema.optional(Schema.NullOr(WireResponseError)),\n})\nexport type WireResponseCompleted = typeof WireResponseCompleted.Type\n\n// ---------------------------------------------------------------------------\n// History → request body input\n// ---------------------------------------------------------------------------\n\n/**\n * The item shapes we stash for round-tripping. Narrower than\n * `WireOutputItem`: the provider-hosted call variants are dropped from the\n * turn, so they are never stored. Composed from the internal `Wire*` structs,\n * which keeps the wire model out of the package's public surface.\n */\nconst StoredItem = Schema.Union([WireMessage, WireFunctionCall, WireReasoning])\ntype StoredItem = typeof StoredItem.Type\n\nconst ProviderDataResponses = Schema.Struct({ responses: StoredItem })\nconst decodeResponsesData = Schema.decodeUnknownResult(ProviderDataResponses)\n\n/**\n * If an item carries `providerData.responses` from a prior turn on this API,\n * re-emit it verbatim - preserves `encrypted_content` and item ids, which a\n * fresh encode from our `HistoryItem` shape cannot reconstruct.\n *\n * Namespaced because `providerData` is a shared slot: an item routed through\n * another provider first (dynamic fallback) carries that provider's key, and\n * re-emitting the whole object would send that provider's data as the wire\n * item and drop the real content. Anything that fails to decode is not ours,\n * so we fall back to encoding the item normally.\n */\nconst passthrough = (item: HistoryItem): StoredItem | undefined =>\n pipe(\n decodeResponsesData(item.providerData),\n Result.match({\n onSuccess: (data) => data.responses,\n onFailure: (): StoredItem | undefined => undefined,\n }),\n )\n\n/**\n * OpenAI's `input_image` content block carries a single `image_url` field;\n * inline bytes get encoded as a `data:` URI. Either form (URL or data URI)\n * is fine - the model just dereferences `image_url`.\n */\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 contentBlockToInput = Match.type<ContentBlock>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n input_text: (b) => ({ type: \"input_text\", text: b.text }),\n input_image: (b) => ({\n type: \"input_image\",\n image_url: imageSourceToUrl(b.source),\n }),\n output_text: (b) => ({ type: \"output_text\", text: b.text }),\n refusal: (b) => ({ type: \"refusal\", refusal: b.text }),\n }),\n)\n\nconst itemToInput = (item: HistoryItem): Record<string, unknown> =>\n passthrough(item) ??\n Match.value(item).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m) => ({\n type: \"message\",\n role: m.role,\n content: m.content.map(contentBlockToInput),\n }),\n function_call: (f) => ({\n type: \"function_call\",\n call_id: f.call_id,\n name: f.name,\n arguments: f.arguments,\n }),\n function_call_output: (o) => ({\n type: \"function_call_output\",\n call_id: o.call_id,\n output: o.output,\n }),\n reasoning: (r) => ({\n type: \"reasoning\",\n ...(r.id !== undefined && { id: r.id }),\n ...(r.summary !== undefined && {\n summary: [{ type: \"summary_text\", text: r.summary }],\n }),\n ...(r.signature !== undefined && { encrypted_content: r.signature }),\n }),\n }),\n )\n\n/** Convert our `HistoryItem[]` history into the Responses API `input` array. */\nexport const itemsToInput = (\n items: ReadonlyArray<HistoryItem>,\n): ReadonlyArray<Record<string, unknown>> => items.map(itemToInput)\n\n// ---------------------------------------------------------------------------\n// Wire output items → our Items\n// ---------------------------------------------------------------------------\n\nconst wireMessageContentToBlock = Match.type<typeof WireMessageContent.Type>().pipe(\n Match.discriminatorsExhaustive(\"type\")({\n output_text: (c): ContentBlock => ({\n type: \"output_text\",\n text: c.text,\n ...(c.annotations !== undefined && c.annotations !== null && { annotations: c.annotations }),\n }),\n refusal: (c): ContentBlock => ({ type: \"refusal\", text: c.refusal }),\n }),\n)\n\nexport const wireItemToItem = (wire: WireOutputItem): ReadonlyArray<HistoryItem> =>\n Match.value(wire).pipe(\n Match.discriminatorsExhaustive(\"type\")({\n message: (m): ReadonlyArray<HistoryItem> => [\n {\n type: \"message\" as const,\n role: m.role,\n content: m.content.map(wireMessageContentToBlock),\n providerData: { responses: m },\n },\n ],\n function_call: (f): ReadonlyArray<HistoryItem> => [\n {\n type: \"function_call\" as const,\n call_id: f.call_id,\n name: f.name,\n arguments: f.arguments,\n providerData: { responses: f },\n },\n ],\n reasoning: (r): ReadonlyArray<HistoryItem> => [\n {\n type: \"reasoning\" as const,\n ...(r.id !== undefined && { id: r.id }),\n ...(r.summary !== undefined && {\n summary: r.summary.map((s) => s.text).join(\"\\n\"),\n }),\n ...(r.encrypted_content !== undefined && { signature: r.encrypted_content }),\n providerData: { responses: r },\n },\n ],\n // Hosted-tool calls are provider-executed; drop from the turn (Phase 1).\n web_search_call: (): ReadonlyArray<HistoryItem> => [],\n code_interpreter_call: (): ReadonlyArray<HistoryItem> => [],\n file_search_call: (): ReadonlyArray<HistoryItem> => [],\n }),\n )\n\n// ---------------------------------------------------------------------------\n// response.completed → Turn\n// ---------------------------------------------------------------------------\n\nconst reasonToStop = Match.type<string>().pipe(\n Match.when(\"max_output_tokens\", () => \"max_tokens\" as const),\n Match.when(\"refusal\", () => \"refusal\" as const),\n Match.when(\"content_filter\", () => \"content_filter\" as const),\n Match.when(\"max_tool_calls\", () => \"max_tool_calls\" as const),\n Match.option,\n)\n\nconst hasRefusalContent = (payload: WireResponseCompleted): boolean =>\n (payload.output ?? []).some(\n (i) => i.type === \"message\" && i.content.some((c) => c.type === \"refusal\"),\n )\n\nconst stopReasonFromCompleted = (payload: WireResponseCompleted): Turn[\"stop_reason\"] =>\n Option.match(reasonToStop(payload.incomplete_details?.reason ?? \"\"), {\n onSome: (s) => s,\n onNone: () =>\n hasRefusalContent(payload)\n ? (\"refusal\" as const)\n : (payload.output ?? []).some((i) => i.type === \"function_call\")\n ? (\"tool_calls\" as const)\n : (\"stop\" as const),\n })\n\nconst cachedTokens = (payload: WireResponseCompleted): number | undefined =>\n payload.usage?.input_tokens_details?.cached_tokens ?? undefined\n\nconst reasoningTokens = (payload: WireResponseCompleted): number | undefined =>\n payload.usage?.output_tokens_details?.reasoning_tokens ?? undefined\n\nexport const turnFromCompleted = (payload: WireResponseCompleted): Turn => {\n const cached = cachedTokens(payload)\n const reasoning = reasoningTokens(payload)\n return {\n items: (payload.output ?? []).flatMap(wireItemToItem),\n usage: {\n ...(payload.usage?.input_tokens !== undefined && {\n input_tokens: payload.usage.input_tokens,\n }),\n ...(payload.usage?.output_tokens !== undefined && {\n output_tokens: payload.usage.output_tokens,\n }),\n ...(payload.usage?.total_tokens !== undefined && {\n total_tokens: payload.usage.total_tokens,\n }),\n ...(cached !== undefined && {\n input_tokens_details: { cached_tokens: cached },\n }),\n ...(reasoning !== undefined && {\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QAAQ,UAAU,EAAE,EAAE,MAAM,MAAM,EAAE,SAAS,gBAAgB,GAC3D,eACA;CACV,CAAC;AAEJ,MAAM,gBAAgB,YACpB,QAAQ,OAAO,sBAAsB,iBAAiB,KAAA;AAExD,MAAM,mBAAmB,YACvB,QAAQ,OAAO,uBAAuB,oBAAoB,KAAA;AAE5D,MAAa,qBAAqB,YAAyC;CACzE,MAAM,SAAS,aAAa,QAAQ;CACpC,MAAM,YAAY,gBAAgB,QAAQ;AAC1C,QAAO;EACL,QAAQ,QAAQ,UAAU,EAAE,EAAE,QAAQ,eAAe;EACrD,OAAO;GACL,GAAI,QAAQ,OAAO,iBAAiB,KAAA,KAAa,EAC/C,cAAc,QAAQ,MAAM,cAC7B;GACD,GAAI,QAAQ,OAAO,kBAAkB,KAAA,KAAa,EAChD,eAAe,QAAQ,MAAM,eAC9B;GACD,GAAI,QAAQ,OAAO,iBAAiB,KAAA,KAAa,EAC/C,cAAc,QAAQ,MAAM,cAC7B;GACD,GAAI,WAAW,KAAA,KAAa,EAC1B,sBAAsB,EAAE,eAAe,QAAQ,EAChD;GACD,GAAI,cAAc,KAAA,KAAa,EAC7B,uBAAuB,EAAE,kBAAkB,WAAW,EACvD;GACF;EACD,aAAa,wBAAwB,QAAQ;EAC9C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { itemsToInput, wireItemToItem } from "./codec.mjs";
|
|
2
|
+
import { n as describe, r as it, t as globalExpect } from "./test.DNmyFkvJ-CPKukVWS.mjs";
|
|
3
|
+
//#region src/codec.test.ts
|
|
4
|
+
describe("providerData round-trip", () => {
|
|
5
|
+
it("re-emits a stashed item verbatim, preserving fields our shape drops", () => {
|
|
6
|
+
globalExpect(itemsToInput(wireItemToItem({
|
|
7
|
+
type: "reasoning",
|
|
8
|
+
id: "rs_1",
|
|
9
|
+
encrypted_content: "opaque-state"
|
|
10
|
+
}))).toEqual([{
|
|
11
|
+
type: "reasoning",
|
|
12
|
+
id: "rs_1",
|
|
13
|
+
encrypted_content: "opaque-state"
|
|
14
|
+
}]);
|
|
15
|
+
});
|
|
16
|
+
});
|
|
17
|
+
describe("providerData is a shared slot", () => {
|
|
18
|
+
it("ignores another provider's data and encodes the item normally", () => {
|
|
19
|
+
globalExpect(itemsToInput([{
|
|
20
|
+
type: "message",
|
|
21
|
+
role: "user",
|
|
22
|
+
content: [{
|
|
23
|
+
type: "input_text",
|
|
24
|
+
text: "hello world"
|
|
25
|
+
}],
|
|
26
|
+
providerData: { gemini: { thoughtSignature: "sig-abc" } }
|
|
27
|
+
}])).toEqual([{
|
|
28
|
+
type: "message",
|
|
29
|
+
role: "user",
|
|
30
|
+
content: [{
|
|
31
|
+
type: "input_text",
|
|
32
|
+
text: "hello world"
|
|
33
|
+
}]
|
|
34
|
+
}]);
|
|
35
|
+
});
|
|
36
|
+
it("does not send a foreign function_call as junk", () => {
|
|
37
|
+
globalExpect(itemsToInput([{
|
|
38
|
+
type: "function_call",
|
|
39
|
+
call_id: "c1",
|
|
40
|
+
name: "get_weather",
|
|
41
|
+
arguments: "{\"city\":\"Lisbon\"}",
|
|
42
|
+
providerData: { gemini: {
|
|
43
|
+
id: "g1",
|
|
44
|
+
thoughtSignature: "sig-abc"
|
|
45
|
+
} }
|
|
46
|
+
}])).toEqual([{
|
|
47
|
+
type: "function_call",
|
|
48
|
+
call_id: "c1",
|
|
49
|
+
name: "get_weather",
|
|
50
|
+
arguments: "{\"city\":\"Lisbon\"}"
|
|
51
|
+
}]);
|
|
52
|
+
});
|
|
53
|
+
it("re-emits only our key when an item carries several providers' data", () => {
|
|
54
|
+
globalExpect(itemsToInput([{
|
|
55
|
+
type: "reasoning",
|
|
56
|
+
signature: "opaque-state",
|
|
57
|
+
providerData: {
|
|
58
|
+
responses: {
|
|
59
|
+
type: "reasoning",
|
|
60
|
+
id: "rs_1",
|
|
61
|
+
encrypted_content: "opaque-state"
|
|
62
|
+
},
|
|
63
|
+
gemini: { thoughtSignature: "sig-abc" }
|
|
64
|
+
}
|
|
65
|
+
}])).toEqual([{
|
|
66
|
+
type: "reasoning",
|
|
67
|
+
id: "rs_1",
|
|
68
|
+
encrypted_content: "opaque-state"
|
|
69
|
+
}]);
|
|
70
|
+
});
|
|
71
|
+
it("falls back to a normal encode when the stashed value is not one of ours", () => {
|
|
72
|
+
globalExpect(itemsToInput([{
|
|
73
|
+
type: "message",
|
|
74
|
+
role: "user",
|
|
75
|
+
content: [{
|
|
76
|
+
type: "input_text",
|
|
77
|
+
text: "hi"
|
|
78
|
+
}],
|
|
79
|
+
providerData: { responses: { type: "not_an_item_we_model" } }
|
|
80
|
+
}])).toEqual([{
|
|
81
|
+
type: "message",
|
|
82
|
+
role: "user",
|
|
83
|
+
content: [{
|
|
84
|
+
type: "input_text",
|
|
85
|
+
text: "hi"
|
|
86
|
+
}]
|
|
87
|
+
}]);
|
|
88
|
+
});
|
|
89
|
+
});
|
|
90
|
+
//#endregion
|
|
91
|
+
export {};
|
|
92
|
+
|
|
93
|
+
//# sourceMappingURL=codec.test.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codec.test.mjs","names":[],"sources":["../src/codec.test.ts"],"sourcesContent":["import type { HistoryItem } from \"@effect-uai/core/Items\"\nimport { describe, expect, it } from \"vitest\"\nimport { itemsToInput, wireItemToItem } from \"./codec.js\"\n\ndescribe(\"providerData round-trip\", () => {\n it(\"re-emits a stashed item verbatim, preserving fields our shape drops\", () => {\n // `id` and `encrypted_content` cannot be reconstructed from a Reasoning\n // item, so the round-trip has to go through the stash.\n const items = wireItemToItem({\n type: \"reasoning\",\n id: \"rs_1\",\n encrypted_content: \"opaque-state\",\n })\n expect(itemsToInput(items)).toEqual([\n { type: \"reasoning\", id: \"rs_1\", encrypted_content: \"opaque-state\" },\n ])\n })\n})\n\ndescribe(\"providerData is a shared slot\", () => {\n // Regression: the passthrough used to re-emit the whole `providerData`\n // object as the wire item. An item that had been through another provider\n // first was sent as that provider's data, losing the real content.\n it(\"ignores another provider's data and encodes the item normally\", () => {\n const history: ReadonlyArray<HistoryItem> = [\n {\n type: \"message\",\n role: \"user\",\n content: [{ type: \"input_text\", text: \"hello world\" }],\n providerData: { gemini: { thoughtSignature: \"sig-abc\" } },\n },\n ]\n expect(itemsToInput(history)).toEqual([\n { type: \"message\", role: \"user\", content: [{ type: \"input_text\", text: \"hello world\" }] },\n ])\n })\n\n it(\"does not send a foreign function_call as junk\", () => {\n const history: ReadonlyArray<HistoryItem> = [\n {\n type: \"function_call\",\n call_id: \"c1\",\n name: \"get_weather\",\n arguments: '{\"city\":\"Lisbon\"}',\n providerData: { gemini: { id: \"g1\", thoughtSignature: \"sig-abc\" } },\n },\n ]\n expect(itemsToInput(history)).toEqual([\n {\n type: \"function_call\",\n call_id: \"c1\",\n name: \"get_weather\",\n arguments: '{\"city\":\"Lisbon\"}',\n },\n ])\n })\n\n it(\"re-emits only our key when an item carries several providers' data\", () => {\n const history: ReadonlyArray<HistoryItem> = [\n {\n type: \"reasoning\",\n signature: \"opaque-state\",\n providerData: {\n responses: { type: \"reasoning\", id: \"rs_1\", encrypted_content: \"opaque-state\" },\n gemini: { thoughtSignature: \"sig-abc\" },\n },\n },\n ]\n expect(itemsToInput(history)).toEqual([\n { type: \"reasoning\", id: \"rs_1\", encrypted_content: \"opaque-state\" },\n ])\n })\n\n it(\"falls back to a normal encode when the stashed value is not one of ours\", () => {\n const history: ReadonlyArray<HistoryItem> = [\n {\n type: \"message\",\n role: \"user\",\n content: [{ type: \"input_text\", text: \"hi\" }],\n providerData: { responses: { type: \"not_an_item_we_model\" } },\n },\n ]\n expect(itemsToInput(history)).toEqual([\n { type: \"message\", role: \"user\", content: [{ type: \"input_text\", text: \"hi\" }] },\n ])\n })\n})\n"],"mappings":";;;AAIA,SAAS,iCAAiC;AACxC,IAAG,6EAA6E;AAQ9E,eAAO,aALO,eAAe;GAC3B,MAAM;GACN,IAAI;GACJ,mBAAmB;GACpB,CACw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;GAAQ,SAAS,CAAC;IAAE,MAAM;IAAc,MAAM;IAAM,CAAC;GAAE,CACjF,CAAC;GACF;EACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@effect-uai/responses",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "OpenAI Responses API provider for @effect-uai/core.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ai",
|
|
@@ -38,6 +38,10 @@
|
|
|
38
38
|
"types": "./dist/Responses.d.mts",
|
|
39
39
|
"import": "./dist/Responses.mjs"
|
|
40
40
|
},
|
|
41
|
+
"./ResponsesTools": {
|
|
42
|
+
"types": "./dist/ResponsesTools.d.mts",
|
|
43
|
+
"import": "./dist/ResponsesTools.mjs"
|
|
44
|
+
},
|
|
41
45
|
"./OpenAIDeepResearch": {
|
|
42
46
|
"types": "./dist/OpenAIDeepResearch.d.mts",
|
|
43
47
|
"import": "./dist/OpenAIDeepResearch.mjs"
|
|
@@ -53,7 +57,7 @@
|
|
|
53
57
|
"devDependencies": {
|
|
54
58
|
"effect": "4.0.0-beta.94",
|
|
55
59
|
"typescript": "^6.0.3",
|
|
56
|
-
"@effect-uai/core": "0.
|
|
60
|
+
"@effect-uai/core": "0.12.0"
|
|
57
61
|
},
|
|
58
62
|
"peerDependencies": {
|
|
59
63
|
"@effect-uai/core": ">=0.2.0 <1",
|
package/src/Responses.ts
CHANGED
|
@@ -51,6 +51,20 @@ export type ResponsesRequest = Omit<CommonRequest, "model"> & {
|
|
|
51
51
|
readonly safetyIdentifier?: string
|
|
52
52
|
readonly promptCacheKey?: string
|
|
53
53
|
readonly truncation?: "auto" | "disabled"
|
|
54
|
+
/**
|
|
55
|
+
* Vendor-specific body fields merged into the request as-is.
|
|
56
|
+
*
|
|
57
|
+
* The Responses dialect is spoken by gateways as well as by OpenAI, and a
|
|
58
|
+
* gateway carries its own parameters — Requesty's `{ requesty: { auto_cache:
|
|
59
|
+
* true } }`, for example. Modelling each one would tie this provider to a
|
|
60
|
+
* catalogue of gateways it cannot see; passing them through keeps the typed
|
|
61
|
+
* surface OpenAI's and the untyped surface open.
|
|
62
|
+
*
|
|
63
|
+
* Merged over the built body, so a field named here wins over the one this
|
|
64
|
+
* provider would have sent. Per-request keys win over the layer's
|
|
65
|
+
* {@link Config.extraBody}.
|
|
66
|
+
*/
|
|
67
|
+
readonly extraBody?: Readonly<Record<string, unknown>>
|
|
54
68
|
/**
|
|
55
69
|
* Free-form JSON output: model emits valid JSON without schema
|
|
56
70
|
* constraints. Mutually exclusive with `structured` (schema wins if
|
|
@@ -108,6 +122,12 @@ export type Config = {
|
|
|
108
122
|
readonly apiKey: Redacted.Redacted
|
|
109
123
|
readonly baseUrl?: string
|
|
110
124
|
readonly region?: OpenAiRegion
|
|
125
|
+
/**
|
|
126
|
+
* Vendor-specific body fields sent on every request from this layer — the
|
|
127
|
+
* place for a gateway's standing configuration, so call sites do not repeat
|
|
128
|
+
* it. Overridden per request by {@link ResponsesRequest.extraBody}.
|
|
129
|
+
*/
|
|
130
|
+
readonly extraBody?: Readonly<Record<string, unknown>>
|
|
111
131
|
}
|
|
112
132
|
|
|
113
133
|
// ---------------------------------------------------------------------------
|
|
@@ -136,6 +156,7 @@ const buildText = (request: ResponsesRequest): Record<string, unknown> | undefin
|
|
|
136
156
|
const buildBody = (
|
|
137
157
|
request: ResponsesRequest,
|
|
138
158
|
providerToolWire: ReadonlyArray<Record<string, unknown>>,
|
|
159
|
+
cfg: Config,
|
|
139
160
|
): Record<string, unknown> => {
|
|
140
161
|
const text = buildText(request)
|
|
141
162
|
const functionTools = descriptorsOf(request.tools).map((t) => ({
|
|
@@ -176,6 +197,8 @@ const buildBody = (
|
|
|
176
197
|
}),
|
|
177
198
|
...(request.truncation !== undefined && { truncation: request.truncation }),
|
|
178
199
|
...(text !== undefined && { text }),
|
|
200
|
+
...cfg.extraBody,
|
|
201
|
+
...request.extraBody,
|
|
179
202
|
}
|
|
180
203
|
}
|
|
181
204
|
|
|
@@ -309,7 +332,7 @@ const buildNativeStream = (cfg: Config) => {
|
|
|
309
332
|
)
|
|
310
333
|
const httpRequest = HttpClientRequest.post(url).pipe(
|
|
311
334
|
HttpClientRequest.bearerToken(cfg.apiKey),
|
|
312
|
-
HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire)),
|
|
335
|
+
HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire, cfg)),
|
|
313
336
|
HttpClientRequest.accept("text/event-stream"),
|
|
314
337
|
)
|
|
315
338
|
const response = yield* client
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { HistoryItem } from "@effect-uai/core/Items"
|
|
2
|
+
import { describe, expect, it } from "vitest"
|
|
3
|
+
import { itemsToInput, wireItemToItem } from "./codec.js"
|
|
4
|
+
|
|
5
|
+
describe("providerData round-trip", () => {
|
|
6
|
+
it("re-emits a stashed item verbatim, preserving fields our shape drops", () => {
|
|
7
|
+
// `id` and `encrypted_content` cannot be reconstructed from a Reasoning
|
|
8
|
+
// item, so the round-trip has to go through the stash.
|
|
9
|
+
const items = wireItemToItem({
|
|
10
|
+
type: "reasoning",
|
|
11
|
+
id: "rs_1",
|
|
12
|
+
encrypted_content: "opaque-state",
|
|
13
|
+
})
|
|
14
|
+
expect(itemsToInput(items)).toEqual([
|
|
15
|
+
{ type: "reasoning", id: "rs_1", encrypted_content: "opaque-state" },
|
|
16
|
+
])
|
|
17
|
+
})
|
|
18
|
+
})
|
|
19
|
+
|
|
20
|
+
describe("providerData is a shared slot", () => {
|
|
21
|
+
// Regression: the passthrough used to re-emit the whole `providerData`
|
|
22
|
+
// object as the wire item. An item that had been through another provider
|
|
23
|
+
// first was sent as that provider's data, losing the real content.
|
|
24
|
+
it("ignores another provider's data and encodes the item normally", () => {
|
|
25
|
+
const history: ReadonlyArray<HistoryItem> = [
|
|
26
|
+
{
|
|
27
|
+
type: "message",
|
|
28
|
+
role: "user",
|
|
29
|
+
content: [{ type: "input_text", text: "hello world" }],
|
|
30
|
+
providerData: { gemini: { thoughtSignature: "sig-abc" } },
|
|
31
|
+
},
|
|
32
|
+
]
|
|
33
|
+
expect(itemsToInput(history)).toEqual([
|
|
34
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: "hello world" }] },
|
|
35
|
+
])
|
|
36
|
+
})
|
|
37
|
+
|
|
38
|
+
it("does not send a foreign function_call as junk", () => {
|
|
39
|
+
const history: ReadonlyArray<HistoryItem> = [
|
|
40
|
+
{
|
|
41
|
+
type: "function_call",
|
|
42
|
+
call_id: "c1",
|
|
43
|
+
name: "get_weather",
|
|
44
|
+
arguments: '{"city":"Lisbon"}',
|
|
45
|
+
providerData: { gemini: { id: "g1", thoughtSignature: "sig-abc" } },
|
|
46
|
+
},
|
|
47
|
+
]
|
|
48
|
+
expect(itemsToInput(history)).toEqual([
|
|
49
|
+
{
|
|
50
|
+
type: "function_call",
|
|
51
|
+
call_id: "c1",
|
|
52
|
+
name: "get_weather",
|
|
53
|
+
arguments: '{"city":"Lisbon"}',
|
|
54
|
+
},
|
|
55
|
+
])
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it("re-emits only our key when an item carries several providers' data", () => {
|
|
59
|
+
const history: ReadonlyArray<HistoryItem> = [
|
|
60
|
+
{
|
|
61
|
+
type: "reasoning",
|
|
62
|
+
signature: "opaque-state",
|
|
63
|
+
providerData: {
|
|
64
|
+
responses: { type: "reasoning", id: "rs_1", encrypted_content: "opaque-state" },
|
|
65
|
+
gemini: { thoughtSignature: "sig-abc" },
|
|
66
|
+
},
|
|
67
|
+
},
|
|
68
|
+
]
|
|
69
|
+
expect(itemsToInput(history)).toEqual([
|
|
70
|
+
{ type: "reasoning", id: "rs_1", encrypted_content: "opaque-state" },
|
|
71
|
+
])
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
it("falls back to a normal encode when the stashed value is not one of ours", () => {
|
|
75
|
+
const history: ReadonlyArray<HistoryItem> = [
|
|
76
|
+
{
|
|
77
|
+
type: "message",
|
|
78
|
+
role: "user",
|
|
79
|
+
content: [{ type: "input_text", text: "hi" }],
|
|
80
|
+
providerData: { responses: { type: "not_an_item_we_model" } },
|
|
81
|
+
},
|
|
82
|
+
]
|
|
83
|
+
expect(itemsToInput(history)).toEqual([
|
|
84
|
+
{ type: "message", role: "user", content: [{ type: "input_text", text: "hi" }] },
|
|
85
|
+
])
|
|
86
|
+
})
|
|
87
|
+
})
|
package/src/codec.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Encoding, Match, Option, Schema } from "effect"
|
|
1
|
+
import { Encoding, Match, Option, Result, Schema, pipe } from "effect"
|
|
2
2
|
import type { ContentBlock, InputImage, HistoryItem } from "@effect-uai/core/Items"
|
|
3
3
|
import type { Turn } from "@effect-uai/core/Turn"
|
|
4
4
|
|
|
@@ -159,16 +159,36 @@ export type WireResponseCompleted = typeof WireResponseCompleted.Type
|
|
|
159
159
|
// ---------------------------------------------------------------------------
|
|
160
160
|
|
|
161
161
|
/**
|
|
162
|
-
*
|
|
163
|
-
*
|
|
164
|
-
*
|
|
162
|
+
* The item shapes we stash for round-tripping. Narrower than
|
|
163
|
+
* `WireOutputItem`: the provider-hosted call variants are dropped from the
|
|
164
|
+
* turn, so they are never stored. Composed from the internal `Wire*` structs,
|
|
165
|
+
* which keeps the wire model out of the package's public surface.
|
|
165
166
|
*/
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
167
|
+
const StoredItem = Schema.Union([WireMessage, WireFunctionCall, WireReasoning])
|
|
168
|
+
type StoredItem = typeof StoredItem.Type
|
|
169
|
+
|
|
170
|
+
const ProviderDataResponses = Schema.Struct({ responses: StoredItem })
|
|
171
|
+
const decodeResponsesData = Schema.decodeUnknownResult(ProviderDataResponses)
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* If an item carries `providerData.responses` from a prior turn on this API,
|
|
175
|
+
* re-emit it verbatim - preserves `encrypted_content` and item ids, which a
|
|
176
|
+
* fresh encode from our `HistoryItem` shape cannot reconstruct.
|
|
177
|
+
*
|
|
178
|
+
* Namespaced because `providerData` is a shared slot: an item routed through
|
|
179
|
+
* another provider first (dynamic fallback) carries that provider's key, and
|
|
180
|
+
* re-emitting the whole object would send that provider's data as the wire
|
|
181
|
+
* item and drop the real content. Anything that fails to decode is not ours,
|
|
182
|
+
* so we fall back to encoding the item normally.
|
|
183
|
+
*/
|
|
184
|
+
const passthrough = (item: HistoryItem): StoredItem | undefined =>
|
|
185
|
+
pipe(
|
|
186
|
+
decodeResponsesData(item.providerData),
|
|
187
|
+
Result.match({
|
|
188
|
+
onSuccess: (data) => data.responses,
|
|
189
|
+
onFailure: (): StoredItem | undefined => undefined,
|
|
190
|
+
}),
|
|
191
|
+
)
|
|
172
192
|
|
|
173
193
|
/**
|
|
174
194
|
* OpenAI's `input_image` content block carries a single `image_url` field;
|
|
@@ -253,7 +273,7 @@ export const wireItemToItem = (wire: WireOutputItem): ReadonlyArray<HistoryItem>
|
|
|
253
273
|
type: "message" as const,
|
|
254
274
|
role: m.role,
|
|
255
275
|
content: m.content.map(wireMessageContentToBlock),
|
|
256
|
-
providerData: m,
|
|
276
|
+
providerData: { responses: m },
|
|
257
277
|
},
|
|
258
278
|
],
|
|
259
279
|
function_call: (f): ReadonlyArray<HistoryItem> => [
|
|
@@ -262,7 +282,7 @@ export const wireItemToItem = (wire: WireOutputItem): ReadonlyArray<HistoryItem>
|
|
|
262
282
|
call_id: f.call_id,
|
|
263
283
|
name: f.name,
|
|
264
284
|
arguments: f.arguments,
|
|
265
|
-
providerData: f,
|
|
285
|
+
providerData: { responses: f },
|
|
266
286
|
},
|
|
267
287
|
],
|
|
268
288
|
reasoning: (r): ReadonlyArray<HistoryItem> => [
|
|
@@ -273,7 +293,7 @@ export const wireItemToItem = (wire: WireOutputItem): ReadonlyArray<HistoryItem>
|
|
|
273
293
|
summary: r.summary.map((s) => s.text).join("\n"),
|
|
274
294
|
}),
|
|
275
295
|
...(r.encrypted_content !== undefined && { signature: r.encrypted_content }),
|
|
276
|
-
providerData: r,
|
|
296
|
+
providerData: { responses: r },
|
|
277
297
|
},
|
|
278
298
|
],
|
|
279
299
|
// Hosted-tool calls are provider-executed; drop from the turn (Phase 1).
|