@effect-uai/responses 0.10.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/OpenAIDeepResearch.d.mts +54 -0
- package/dist/OpenAIDeepResearch.d.mts.map +1 -0
- package/dist/OpenAIDeepResearch.mjs +121 -0
- package/dist/OpenAIDeepResearch.mjs.map +1 -0
- package/dist/OpenAIEmbedding.mjs +1 -1
- package/dist/OpenAIEmbedding.mjs.map +1 -1
- package/dist/Responses.d.mts +33 -3
- package/dist/Responses.d.mts.map +1 -1
- package/dist/Responses.mjs +71 -34
- package/dist/Responses.mjs.map +1 -1
- package/dist/ResponsesTools.d.mts +85 -0
- package/dist/ResponsesTools.d.mts.map +1 -0
- package/dist/ResponsesTools.mjs +126 -0
- package/dist/ResponsesTools.mjs.map +1 -0
- package/dist/codec.d.mts +42 -3
- package/dist/codec.d.mts.map +1 -1
- package/dist/codec.mjs +58 -17
- 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/dist/index.d.mts +5 -3
- package/dist/index.mjs +5 -3
- package/dist/{magic-string.es-PAZgLX4h.mjs → magic-string.es-CaWgF-3p.mjs} +1 -1
- package/dist/{magic-string.es-PAZgLX4h.mjs.map → magic-string.es-CaWgF-3p.mjs.map} +1 -1
- package/dist/models.d.mts +10 -1
- package/dist/models.d.mts.map +1 -1
- package/dist/region.test.mjs +1 -13630
- package/dist/region.test.mjs.map +1 -1
- package/dist/responsesTools.test.d.mts +1 -0
- package/dist/responsesTools.test.mjs +138 -0
- package/dist/responsesTools.test.mjs.map +1 -0
- package/dist/streamEvents.d.mts +142 -0
- package/dist/streamEvents.d.mts.map +1 -1
- package/dist/streamEvents.mjs +27 -2
- package/dist/streamEvents.mjs.map +1 -1
- package/dist/test.DNmyFkvJ-CPKukVWS.mjs +13633 -0
- package/dist/test.DNmyFkvJ-CPKukVWS.mjs.map +1 -0
- package/package.json +12 -4
- package/src/OpenAIDeepResearch.ts +266 -0
- package/src/OpenAIEmbedding.ts +1 -1
- package/src/Responses.ts +117 -36
- package/src/ResponsesTools.ts +158 -0
- package/src/codec.test.ts +87 -0
- package/src/codec.ts +92 -36
- package/src/index.ts +2 -0
- package/src/models.ts +14 -0
- package/src/responsesTools.test.ts +146 -0
- package/src/streamEvents.ts +58 -1
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { WireResponseCompleted } from "./codec.mjs";
|
|
2
|
+
import { OpenAIDeepResearchModel } from "./models.mjs";
|
|
3
|
+
import { OpenAiRegion } from "./region.mjs";
|
|
4
|
+
import { Context, Effect, Layer, Redacted } from "effect";
|
|
5
|
+
import { HttpClient } from "effect/unstable/http";
|
|
6
|
+
import { DeepResearch, DeepResearchServiceShape } from "@effect-uai/core/DeepResearch";
|
|
7
|
+
import * as Job from "@effect-uai/core/Job";
|
|
8
|
+
import { ResearchRequest, ResearchState } from "@effect-uai/core/Research";
|
|
9
|
+
|
|
10
|
+
//#region src/OpenAIDeepResearch.d.ts
|
|
11
|
+
declare namespace OpenAIDeepResearch_d_exports {
|
|
12
|
+
export { Config, OpenAIDeepResearch, OpenAIDeepResearchService, OpenAIResearchRequest, jobStateOf, layer, make };
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* OpenAI-typed research request. Narrows `model` to the deep-research ids and
|
|
16
|
+
* adds `maxSearches` (mapped to `max_tool_calls`) and a `reasoning` hint.
|
|
17
|
+
* Provider-portable code uses the generic `DeepResearch` tag instead.
|
|
18
|
+
*/
|
|
19
|
+
type OpenAIResearchRequest = Omit<ResearchRequest, "model"> & {
|
|
20
|
+
readonly model?: OpenAIDeepResearchModel; /** Cost/latency cap on the agent's tool calls. Maps to `max_tool_calls`. */
|
|
21
|
+
readonly maxSearches?: number; /** Reasoning-effort hint; `summary: "auto"` streams reasoning summaries. */
|
|
22
|
+
readonly reasoning?: {
|
|
23
|
+
readonly effort?: "low" | "medium" | "high";
|
|
24
|
+
readonly summary?: "auto" | "concise" | "detailed";
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
type OpenAIDeepResearchService = DeepResearchServiceShape<OpenAIResearchRequest>;
|
|
28
|
+
declare const OpenAIDeepResearch_base: Context.ServiceClass<OpenAIDeepResearch, "@betalyra/effect-uai/providers/responses/OpenAIDeepResearch", OpenAIDeepResearchService>;
|
|
29
|
+
/**
|
|
30
|
+
* Provider-typed tag. Yield this for the OpenAI model / `maxSearches` knobs;
|
|
31
|
+
* yield the generic `DeepResearch` tag for provider-portable code. The
|
|
32
|
+
* background job is detachable and streams live over the resumable Responses
|
|
33
|
+
* SSE, so `streamFrom` is a real event stream (not the synthesized fallback) and
|
|
34
|
+
* a persisted ref survives a restart.
|
|
35
|
+
*/
|
|
36
|
+
declare class OpenAIDeepResearch extends OpenAIDeepResearch_base {}
|
|
37
|
+
type Config = {
|
|
38
|
+
readonly apiKey: Redacted.Redacted;
|
|
39
|
+
readonly baseUrl?: string;
|
|
40
|
+
readonly region?: OpenAiRegion; /** Poll cadence / overall timeout for the derived poll loops. */
|
|
41
|
+
readonly job?: Job.JobConfig;
|
|
42
|
+
};
|
|
43
|
+
declare const jobStateOf: (wire: WireResponseCompleted) => ResearchState;
|
|
44
|
+
/** Build an `OpenAIDeepResearchService`. For Layer setup, prefer {@link layer}. */
|
|
45
|
+
declare const make: (cfg: Config) => Effect.Effect<OpenAIDeepResearchService, never, HttpClient.HttpClient>;
|
|
46
|
+
/**
|
|
47
|
+
* Layer registering the provider-typed `OpenAIDeepResearch` tag and the generic
|
|
48
|
+
* `DeepResearch` tag. No capability markers: the whole surface (detach, live
|
|
49
|
+
* stream, cancel) is universal.
|
|
50
|
+
*/
|
|
51
|
+
declare const layer: (cfg: Config) => Layer.Layer<OpenAIDeepResearch | DeepResearch, never, HttpClient.HttpClient>;
|
|
52
|
+
//#endregion
|
|
53
|
+
export { Config, OpenAIDeepResearch, OpenAIDeepResearchService, OpenAIResearchRequest, jobStateOf, layer, make, OpenAIDeepResearch_d_exports as t };
|
|
54
|
+
//# sourceMappingURL=OpenAIDeepResearch.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OpenAIDeepResearch.d.mts","names":[],"sources":["../src/OpenAIDeepResearch.ts"],"mappings":";;;;;;;;;;;;;;;;;;KA4BY,qBAAA,GAAwB,IAAA,CAAK,eAAA;EAAA,SAC9B,KAAA,GAAQ,uBAAA;WAER,WAAA;WAEA,SAAA;IAAA,SACE,MAAA;IAAA,SACA,OAAA;EAAA;AAAA;AAAA,KAID,yBAAA,GAA4B,wBAAA,CAAyB,qBAAA;AAAA,cAAsB,uBAAA;;;;;;;;cAS1E,kBAAA,SAA2B,uBAAA;AAAA,KAK5B,MAAA;EAAA,SACD,MAAA,EAAQ,QAAA,CAAS,QAAA;EAAA,SACjB,OAAA;EAAA,SACA,MAAA,GAAS,YAAA,EAjBR;EAAA,SAmBD,GAAA,GAAM,GAAA,CAAI,SAAA;AAAA;AAAA,cA2BR,UAAA,GAAc,IAAA,EAAM,qBAAA,KAAwB,aAAA;;cA2J5C,IAAA,GACX,GAAA,EAAK,MAAA,KACJ,MAAA,CAAO,MAAA,CAAO,yBAAA,SAAkC,UAAA,CAAW,UAAA;;;;;;cAQjD,KAAA,GACX,GAAA,EAAK,MAAA,KACJ,KAAA,CAAM,KAAA,CAAM,kBAAA,GAAqB,YAAA,SAAqB,UAAA,CAAW,UAAA"}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
|
|
2
|
+
import { WireResponseCompleted, itemsToInput, turnFromCompleted } from "./codec.mjs";
|
|
3
|
+
import { resolveHost } from "./region.mjs";
|
|
4
|
+
import { httpStatusError, providerEventsOfResponse, toCanonical } from "./Responses.mjs";
|
|
5
|
+
import { Context, Effect, Layer, Match, Option, Schema, Stream } from "effect";
|
|
6
|
+
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
7
|
+
import * as AiError from "@effect-uai/core/AiError";
|
|
8
|
+
import { DeepResearch, fromJob } from "@effect-uai/core/DeepResearch";
|
|
9
|
+
import * as Job from "@effect-uai/core/Job";
|
|
10
|
+
//#region src/OpenAIDeepResearch.ts
|
|
11
|
+
var OpenAIDeepResearch_exports = /* @__PURE__ */ __exportAll({
|
|
12
|
+
OpenAIDeepResearch: () => OpenAIDeepResearch,
|
|
13
|
+
jobStateOf: () => jobStateOf,
|
|
14
|
+
layer: () => layer,
|
|
15
|
+
make: () => make
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* Provider-typed tag. Yield this for the OpenAI model / `maxSearches` knobs;
|
|
19
|
+
* yield the generic `DeepResearch` tag for provider-portable code. The
|
|
20
|
+
* background job is detachable and streams live over the resumable Responses
|
|
21
|
+
* SSE, so `streamFrom` is a real event stream (not the synthesized fallback) and
|
|
22
|
+
* a persisted ref survives a restart.
|
|
23
|
+
*/
|
|
24
|
+
var OpenAIDeepResearch = class extends Context.Service()("@betalyra/effect-uai/providers/responses/OpenAIDeepResearch") {};
|
|
25
|
+
const decodeResponse = Schema.decodeUnknownEffect(WireResponseCompleted);
|
|
26
|
+
const WireCreated = Schema.Struct({ response: Schema.Struct({ id: Schema.String }) });
|
|
27
|
+
const decodeCreated = Schema.decodeUnknownEffect(WireCreated);
|
|
28
|
+
const responseIdOf = (event) => event.type === "_unknown" ? decodeCreated(event.raw).pipe(Effect.map((wire) => Option.some(wire.response.id)), Effect.orElseSucceed(() => Option.none())) : Effect.succeedNone;
|
|
29
|
+
const jobStateOf = (wire) => Match.value(wire.status ?? "").pipe(Match.when("queued", () => ({ _tag: "Pending" })), Match.when("in_progress", () => ({ _tag: "Running" })), Match.whenOr("completed", "incomplete", () => ({
|
|
30
|
+
_tag: "Succeeded",
|
|
31
|
+
result: turnFromCompleted(wire)
|
|
32
|
+
})), Match.whenOr("failed", "cancelled", () => ({
|
|
33
|
+
_tag: "Failed",
|
|
34
|
+
...wire.error?.message != null && { reason: wire.error.message },
|
|
35
|
+
raw: wire
|
|
36
|
+
})), Match.orElse(() => ({ _tag: "Running" })));
|
|
37
|
+
const transportFailure = (cause) => new AiError.Unavailable({
|
|
38
|
+
provider: "responses",
|
|
39
|
+
raw: cause
|
|
40
|
+
});
|
|
41
|
+
const submitBody = (request) => ({
|
|
42
|
+
model: request.model ?? "o3-deep-research",
|
|
43
|
+
input: itemsToInput(request.history),
|
|
44
|
+
background: true,
|
|
45
|
+
store: true,
|
|
46
|
+
tools: [{ type: "web_search_preview" }],
|
|
47
|
+
...request.maxSearches !== void 0 && { max_tool_calls: request.maxSearches },
|
|
48
|
+
...request.reasoning !== void 0 && { reasoning: request.reasoning }
|
|
49
|
+
});
|
|
50
|
+
const submitJob = (cfg, request) => Effect.gen(function* () {
|
|
51
|
+
const client = yield* HttpClient.HttpClient;
|
|
52
|
+
const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/responses`).pipe(HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.accept("text/event-stream"), HttpClientRequest.bodyJsonUnsafe({
|
|
53
|
+
...submitBody(request),
|
|
54
|
+
stream: true
|
|
55
|
+
}));
|
|
56
|
+
const id = yield* providerEventsOfResponse(yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))).pipe(Stream.mapEffect(responseIdOf), Stream.filter(Option.isSome), Stream.map((some) => some.value), Stream.runHead);
|
|
57
|
+
return yield* Option.match(id, {
|
|
58
|
+
onNone: () => Effect.fail(new AiError.GenerationFailed({
|
|
59
|
+
provider: "responses",
|
|
60
|
+
message: "streaming create ended without a response id",
|
|
61
|
+
raw: submitBody(request)
|
|
62
|
+
})),
|
|
63
|
+
onSome: (value) => Effect.succeed(Job.jobRef("responses", value))
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
const pollJob = (cfg, ref) => Effect.gen(function* () {
|
|
67
|
+
const client = yield* HttpClient.HttpClient;
|
|
68
|
+
const httpRequest = HttpClientRequest.get(`${resolveHost(cfg)}/responses/${ref.id}`).pipe(HttpClientRequest.bearerToken(cfg.apiKey));
|
|
69
|
+
const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure));
|
|
70
|
+
if (response.status >= 400) {
|
|
71
|
+
const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
|
|
72
|
+
return yield* httpStatusError(response.status, text);
|
|
73
|
+
}
|
|
74
|
+
return jobStateOf(yield* decodeResponse(yield* response.json.pipe(Effect.mapError(transportFailure))).pipe(Effect.mapError(transportFailure)));
|
|
75
|
+
});
|
|
76
|
+
const cancelJob = (cfg, ref) => Effect.gen(function* () {
|
|
77
|
+
const client = yield* HttpClient.HttpClient;
|
|
78
|
+
const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/responses/${ref.id}/cancel`).pipe(HttpClientRequest.bearerToken(cfg.apiKey));
|
|
79
|
+
const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure));
|
|
80
|
+
if (response.status >= 400) {
|
|
81
|
+
const text = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
|
|
82
|
+
return yield* httpStatusError(response.status, text);
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
const streamFromRef = (cfg, ref) => Stream.unwrap(Effect.gen(function* () {
|
|
86
|
+
const client = yield* HttpClient.HttpClient;
|
|
87
|
+
const httpRequest = HttpClientRequest.get(`${resolveHost(cfg)}/responses/${ref.id}?stream=true`).pipe(HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.accept("text/event-stream"));
|
|
88
|
+
return toCanonical(providerEventsOfResponse(yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))));
|
|
89
|
+
}));
|
|
90
|
+
const jobOps = (cfg, client) => {
|
|
91
|
+
const withClient = (e) => Effect.provideService(e, HttpClient.HttpClient, client);
|
|
92
|
+
const withClientStream = (s) => Stream.provideService(s, HttpClient.HttpClient, client);
|
|
93
|
+
return {
|
|
94
|
+
submit: (request) => withClient(submitJob(cfg, request)),
|
|
95
|
+
poll: (ref) => withClient(pollJob(cfg, ref)),
|
|
96
|
+
cancel: (ref) => withClient(cancelJob(cfg, ref)),
|
|
97
|
+
streamFrom: (ref) => withClientStream(streamFromRef(cfg, ref))
|
|
98
|
+
};
|
|
99
|
+
};
|
|
100
|
+
/** Build an `OpenAIDeepResearchService`. For Layer setup, prefer {@link layer}. */
|
|
101
|
+
const make = (cfg) => Effect.map(HttpClient.HttpClient, (client) => fromJob(jobOps(cfg, client), cfg.job));
|
|
102
|
+
/**
|
|
103
|
+
* Layer registering the provider-typed `OpenAIDeepResearch` tag and the generic
|
|
104
|
+
* `DeepResearch` tag. No capability markers: the whole surface (detach, live
|
|
105
|
+
* stream, cancel) is universal.
|
|
106
|
+
*/
|
|
107
|
+
const layer = (cfg) => {
|
|
108
|
+
const typed = Layer.effect(OpenAIDeepResearch, make(cfg));
|
|
109
|
+
const generic = Layer.effect(DeepResearch, Effect.map(HttpClient.HttpClient, (client) => {
|
|
110
|
+
const ops = jobOps(cfg, client);
|
|
111
|
+
return fromJob({
|
|
112
|
+
...ops,
|
|
113
|
+
submit: (request) => ops.submit(request)
|
|
114
|
+
}, cfg.job);
|
|
115
|
+
}));
|
|
116
|
+
return Layer.merge(typed, generic);
|
|
117
|
+
};
|
|
118
|
+
//#endregion
|
|
119
|
+
export { OpenAIDeepResearch, jobStateOf, layer, make, OpenAIDeepResearch_exports as t };
|
|
120
|
+
|
|
121
|
+
//# sourceMappingURL=OpenAIDeepResearch.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"OpenAIDeepResearch.mjs","names":[],"sources":["../src/OpenAIDeepResearch.ts"],"sourcesContent":["import { Context, Effect, Layer, Match, Option, Redacted, Schema, Stream } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport {\n DeepResearch,\n type DeepResearchService,\n type DeepResearchServiceShape,\n fromJob,\n type ResearchJobOps,\n} from \"@effect-uai/core/DeepResearch\"\nimport * as Job from \"@effect-uai/core/Job\"\nimport type { ResearchJobRef, ResearchRequest, ResearchState } from \"@effect-uai/core/Research\"\nimport type { Turn, TurnEvent } from \"@effect-uai/core/Turn\"\nimport { WireResponseCompleted, turnFromCompleted, itemsToInput } from \"./codec.js\"\nimport type { OpenAIDeepResearchModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\nimport { httpStatusError, providerEventsOfResponse, toCanonical } from \"./Responses.js\"\nimport type { ProviderEvent } from \"./streamEvents.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI-typed research request. Narrows `model` to the deep-research ids and\n * adds `maxSearches` (mapped to `max_tool_calls`) and a `reasoning` hint.\n * Provider-portable code uses the generic `DeepResearch` tag instead.\n */\nexport type OpenAIResearchRequest = Omit<ResearchRequest, \"model\"> & {\n readonly model?: OpenAIDeepResearchModel\n /** Cost/latency cap on the agent's tool calls. Maps to `max_tool_calls`. */\n readonly maxSearches?: number\n /** Reasoning-effort hint; `summary: \"auto\"` streams reasoning summaries. */\n readonly reasoning?: {\n readonly effort?: \"low\" | \"medium\" | \"high\"\n readonly summary?: \"auto\" | \"concise\" | \"detailed\"\n }\n}\n\nexport type OpenAIDeepResearchService = DeepResearchServiceShape<OpenAIResearchRequest>\n\n/**\n * Provider-typed tag. Yield this for the OpenAI model / `maxSearches` knobs;\n * yield the generic `DeepResearch` tag for provider-portable code. The\n * background job is detachable and streams live over the resumable Responses\n * SSE, so `streamFrom` is a real event stream (not the synthesized fallback) and\n * a persisted ref survives a restart.\n */\nexport class OpenAIDeepResearch extends Context.Service<\n OpenAIDeepResearch,\n OpenAIDeepResearchService\n>()(\"@betalyra/effect-uai/providers/responses/OpenAIDeepResearch\") {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n readonly region?: OpenAiRegion\n /** Poll cadence / overall timeout for the derived poll loops. */\n readonly job?: Job.JobConfig\n}\n\n// ---------------------------------------------------------------------------\n// Wire codec\n// ---------------------------------------------------------------------------\n\nconst decodeResponse = Schema.decodeUnknownEffect(WireResponseCompleted)\n\n// Any early lifecycle event (`response.created` / `response.queued` / ...)\n// carries the response object; only its id matters here. These events are not\n// in the modeled `ProviderEvent` union, so they arrive as `_unknown`.\nconst WireCreated = Schema.Struct({ response: Schema.Struct({ id: Schema.String }) })\nconst decodeCreated = Schema.decodeUnknownEffect(WireCreated)\n\nconst responseIdOf = (event: ProviderEvent): Effect.Effect<Option.Option<string>> =>\n event.type === \"_unknown\"\n ? decodeCreated(event.raw).pipe(\n Effect.map((wire) => Option.some(wire.response.id)),\n Effect.orElseSucceed(() => Option.none<string>()),\n )\n : Effect.succeedNone\n\n// Map a Responses object's `status` onto the generic `JobState`. `completed`\n// and `incomplete` both carry a usable turn (incomplete = stopped early with a\n// partial answer, same shape); `failed` / `cancelled` are terminal failures.\n// An unknown / absent status keeps the loop polling (bounded by the timeout).\nexport const jobStateOf = (wire: WireResponseCompleted): ResearchState =>\n Match.value(wire.status ?? \"\").pipe(\n Match.when(\"queued\", (): ResearchState => ({ _tag: \"Pending\" })),\n Match.when(\"in_progress\", (): ResearchState => ({ _tag: \"Running\" })),\n Match.whenOr(\n \"completed\",\n \"incomplete\",\n (): ResearchState => ({ _tag: \"Succeeded\", result: turnFromCompleted(wire) }),\n ),\n Match.whenOr(\n \"failed\",\n \"cancelled\",\n (): ResearchState => ({\n _tag: \"Failed\",\n ...(wire.error?.message != null && { reason: wire.error.message }),\n raw: wire,\n }),\n ),\n Match.orElse((): ResearchState => ({ _tag: \"Running\" })),\n )\n\n// ---------------------------------------------------------------------------\n// HTTP\n// ---------------------------------------------------------------------------\n\nconst transportFailure = (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider: \"responses\", raw: cause })\n\n// Deep research requires at least one data-source tool; default to web search.\nconst submitBody = (request: OpenAIResearchRequest): Record<string, unknown> => ({\n model: request.model ?? \"o3-deep-research\",\n input: itemsToInput(request.history),\n background: true,\n store: true,\n tools: [{ type: \"web_search_preview\" }],\n ...(request.maxSearches !== undefined && { max_tool_calls: request.maxSearches }),\n ...(request.reasoning !== undefined && { reasoning: request.reasoning }),\n})\n\n// The job is created with `stream: true` on top of `background: true`: OpenAI\n// only exposes a resumable event feed on responses *created* streaming, so this\n// keeps every submitted ref attachable via `streamFrom`. Only the first SSE\n// event is read (for the response id); the connection is then dropped and the\n// background job keeps running server-side.\nconst submitJob = (\n cfg: Config,\n request: OpenAIResearchRequest,\n): Effect.Effect<ResearchJobRef, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/responses`).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.accept(\"text/event-stream\"),\n HttpClientRequest.bodyJsonUnsafe({ ...submitBody(request), stream: true }),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n const id = yield* providerEventsOfResponse(response).pipe(\n Stream.mapEffect(responseIdOf),\n Stream.filter(Option.isSome),\n Stream.map((some) => some.value),\n Stream.runHead,\n )\n return yield* Option.match(id, {\n onNone: () =>\n Effect.fail(\n new AiError.GenerationFailed({\n provider: \"responses\",\n message: \"streaming create ended without a response id\",\n raw: submitBody(request),\n }),\n ),\n onSome: (value) => Effect.succeed(Job.jobRef<Turn>(\"responses\", value)),\n })\n })\n\nconst pollJob = (\n cfg: Config,\n ref: ResearchJobRef,\n): Effect.Effect<ResearchState, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = HttpClientRequest.get(`${resolveHost(cfg)}/responses/${ref.id}`).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n const wire = yield* decodeResponse(json).pipe(Effect.mapError(transportFailure))\n return jobStateOf(wire)\n })\n\nconst cancelJob = (\n cfg: Config,\n ref: ResearchJobRef,\n): Effect.Effect<void, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = HttpClientRequest.post(\n `${resolveHost(cfg)}/responses/${ref.id}/cancel`,\n ).pipe(HttpClientRequest.bearerToken(cfg.apiKey))\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n })\n\n// Attach a live event stream to a detached job via the resumable Responses SSE,\n// reusing the shared decode pipeline and the canonical `TurnEvent` projection.\nconst streamFromRef = (\n cfg: Config,\n ref: ResearchJobRef,\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.get(\n `${resolveHost(cfg)}/responses/${ref.id}?stream=true`,\n ).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.accept(\"text/event-stream\"),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n return toCanonical(providerEventsOfResponse(response))\n }),\n )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n// The job ops. OpenAI streams live over the resumable Responses SSE, so it\n// supplies a real `streamFrom` (not the synthesized fallback). Since `submit`\n// creates the job streaming, `fromJob`'s default `researchStream`\n// (submit-then-attach) streams real events too.\nconst jobOps = (\n cfg: Config,\n client: HttpClient.HttpClient,\n): ResearchJobOps<OpenAIResearchRequest> => {\n const withClient = <A>(e: Effect.Effect<A, AiError.AiError, HttpClient.HttpClient>) =>\n Effect.provideService(e, HttpClient.HttpClient, client)\n const withClientStream = <A>(s: Stream.Stream<A, AiError.AiError, HttpClient.HttpClient>) =>\n Stream.provideService(s, HttpClient.HttpClient, client)\n return {\n submit: (request) => withClient(submitJob(cfg, request)),\n poll: (ref) => withClient(pollJob(cfg, ref)),\n cancel: (ref) => withClient(cancelJob(cfg, ref)),\n streamFrom: (ref) => withClientStream(streamFromRef(cfg, ref)),\n }\n}\n\n/** Build an `OpenAIDeepResearchService`. For Layer setup, prefer {@link layer}. */\nexport const make = (\n cfg: Config,\n): Effect.Effect<OpenAIDeepResearchService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => fromJob(jobOps(cfg, client), cfg.job))\n\n/**\n * Layer registering the provider-typed `OpenAIDeepResearch` tag and the generic\n * `DeepResearch` tag. No capability markers: the whole surface (detach, live\n * stream, cancel) is universal.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<OpenAIDeepResearch | DeepResearch, never, HttpClient.HttpClient> => {\n const typed = Layer.effect(OpenAIDeepResearch, make(cfg))\n const generic = Layer.effect(\n DeepResearch,\n Effect.map(HttpClient.HttpClient, (client): DeepResearchService => {\n const ops = jobOps(cfg, client)\n return fromJob<ResearchRequest>(\n { ...ops, submit: (request) => ops.submit(request as OpenAIResearchRequest) },\n cfg.job,\n )\n }),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,qBAAb,cAAwC,QAAQ,SAG7C,CAAC,8DAA8D,CAAC;AAcnE,MAAM,iBAAiB,OAAO,oBAAoB,sBAAsB;AAKxE,MAAM,cAAc,OAAO,OAAO,EAAE,UAAU,OAAO,OAAO,EAAE,IAAI,OAAO,QAAQ,CAAC,EAAE,CAAC;AACrF,MAAM,gBAAgB,OAAO,oBAAoB,YAAY;AAE7D,MAAM,gBAAgB,UACpB,MAAM,SAAS,aACX,cAAc,MAAM,IAAI,CAAC,KACvB,OAAO,KAAK,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AAI,OAAO,QAAiC;GAAE,EAC7E,IAAI,IACL;GACD,CACH;AACD,QAAO,MAAM,MAAM,OAAO,QAAQ"}
|
package/dist/OpenAIEmbedding.mjs
CHANGED
|
@@ -140,7 +140,7 @@ const embedManyImpl = (cfg) => (request) => buildBatchBody(request).pipe(Effect.
|
|
|
140
140
|
* Build an `OpenAIEmbeddingService` value. For Layer-based setup, prefer
|
|
141
141
|
* `layer`.
|
|
142
142
|
*/
|
|
143
|
-
const make = (cfg) => Effect.map(HttpClient.HttpClient
|
|
143
|
+
const make = (cfg) => Effect.map(HttpClient.HttpClient, (client) => ({
|
|
144
144
|
embed: (request) => embedImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),
|
|
145
145
|
embedMany: (request) => embedManyImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client))
|
|
146
146
|
}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenAIEmbedding.mjs","names":[],"sources":["../src/OpenAIEmbedding.ts"],"sourcesContent":["import { Context, Effect, Layer, Redacted, Schema } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type {\n EmbedContentPart,\n EmbedInput,\n Float32Embedding,\n Usage,\n} from \"@effect-uai/core/Embedding\"\nimport {\n assertEncoding,\n type CommonEmbedManyRequest,\n type CommonEmbedRequest,\n type EmbedEncoding,\n EmbeddingModel,\n type EmbeddingModelService,\n type EmbedManyResponse,\n type EmbedResponse,\n} from \"@effect-uai/core/EmbeddingModel\"\nimport type { OpenAIEmbeddingModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI's embedding API has no task-type semantics, so `task` is omitted\n * from the request type intentionally - passing it would be a compile\n * error. The generic `EmbeddingModel` registration accepts and silently\n * ignores `task` from `CommonEmbedRequest`.\n */\nexport type OpenAIEmbedRequest = Omit<CommonEmbedRequest, \"model\" | \"task\" | \"encoding\"> & {\n /** Narrows `CommonEmbedRequest.model` to the typed OpenAI union. */\n readonly model: OpenAIEmbeddingModel\n}\n\nexport type OpenAIEmbedManyRequest = Omit<OpenAIEmbedRequest, \"input\"> & {\n readonly inputs: ReadonlyArray<EmbedInput>\n}\n\nexport type OpenAIEmbeddingService = {\n readonly embed: (request: OpenAIEmbedRequest) => Effect.Effect<EmbedResponse, AiError.AiError>\n readonly embedMany: (\n request: OpenAIEmbedManyRequest,\n ) => Effect.Effect<EmbedManyResponse, AiError.AiError>\n}\n\n/**\n * Provider-typed service tag. Yield this for OpenAI-typed embedding\n * requests; yield the generic `EmbeddingModel` tag for provider-portable\n * code. Both are registered by `layer`.\n */\nexport class OpenAIEmbedding extends Context.Service<OpenAIEmbedding, OpenAIEmbeddingService>()(\n \"@betalyra/effect-uai/providers/responses/OpenAIEmbedding\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Codec - input flattening to the single string OpenAI expects\n// ---------------------------------------------------------------------------\n\n// Image input on a text-only embedder is bucket 1: a silently dropped image\n// yields a vector that represents the wrong thing. Reject with `Unsupported`\n// (capability gap), not `InvalidRequest` (which is for wire-shape mismatches).\n// OpenAI's embeddings API remains text-only as of June 2026.\nconst imageRejected: AiError.AiError = new AiError.Unsupported({\n provider: \"openai\",\n capability: \"imageEmbedding\",\n reason: \"OpenAI embeddings are text-only; pass a string or { text }.\",\n})\n\nconst partToText = (part: EmbedContentPart): Effect.Effect<string, AiError.AiError> =>\n \"text\" in part ? Effect.succeed(part.text) : Effect.fail(imageRejected)\n\n/**\n * OpenAI accepts a single string per input. Pure-text `content[]` is\n * concatenated with newlines (treats them as paragraphs of one document);\n * any image part fails with `Unsupported`.\n */\nconst inputToString = (input: EmbedInput): Effect.Effect<string, AiError.AiError> => {\n if (typeof input === \"string\") return Effect.succeed(input)\n if (\"text\" in input) return Effect.succeed(input.text)\n if (\"image\" in input) return Effect.fail(imageRejected)\n return Effect.forEach(input.content, partToText).pipe(Effect.map((texts) => texts.join(\"\\n\")))\n}\n\n// ---------------------------------------------------------------------------\n// Codec - request body\n// ---------------------------------------------------------------------------\n\ntype WireBody = {\n readonly model: string\n readonly input: string | ReadonlyArray<string>\n readonly dimensions?: number\n readonly encoding_format?: \"float\" | \"base64\"\n}\n\nconst buildSingleBody = (request: OpenAIEmbedRequest): Effect.Effect<WireBody, AiError.AiError> =>\n inputToString(request.input).pipe(\n Effect.map((input) => ({\n model: request.model,\n input,\n ...(request.dimensions !== undefined && { dimensions: request.dimensions }),\n })),\n )\n\nconst buildBatchBody = (\n request: OpenAIEmbedManyRequest,\n): Effect.Effect<WireBody, AiError.AiError> =>\n Effect.forEach(request.inputs, inputToString).pipe(\n Effect.map((inputs) => ({\n model: request.model,\n input: inputs,\n ...(request.dimensions !== undefined && { dimensions: request.dimensions }),\n })),\n )\n\n// ---------------------------------------------------------------------------\n// Codec - response\n// ---------------------------------------------------------------------------\n\nconst WireEmbeddingItem = Schema.Struct({\n embedding: Schema.Array(Schema.Number),\n index: Schema.Number,\n})\n\nconst WireUsage = Schema.Struct({\n prompt_tokens: Schema.Number,\n total_tokens: Schema.Number,\n})\n\nconst WireResponse = Schema.Struct({\n data: Schema.Array(WireEmbeddingItem),\n model: Schema.String,\n usage: WireUsage,\n})\n\nconst valuesToEmbedding = (values: ReadonlyArray<number>): Float32Embedding => ({\n _tag: \"float32\",\n vector: Float32Array.from(values),\n})\n\n// OpenAI returns `data[]` unsorted in theory; sort by `index` so caller\n// gets results in the order they passed inputs.\nconst orderedEmbeddings = (\n data: ReadonlyArray<{ readonly embedding: ReadonlyArray<number>; readonly index: number }>,\n): ReadonlyArray<Float32Embedding> =>\n [...data].sort((a, b) => a.index - b.index).map((item) => valuesToEmbedding(item.embedding))\n\n// ---------------------------------------------------------------------------\n// HTTP errors\n// ---------------------------------------------------------------------------\n\nconst httpStatusError = (status: number, body: string): AiError.AiError => {\n const provider = \"openai\"\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\nconst transportFailure = (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider: \"openai\", raw: cause })\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\nconst postEmbed = (\n cfg: Config,\n body: WireBody,\n): Effect.Effect<typeof WireResponse.Type, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/embeddings`).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.bodyJsonUnsafe(body),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n return yield* Schema.decodeUnknownEffect(WireResponse)(json).pipe(\n Effect.mapError(transportFailure),\n )\n })\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nconst usageOf = (u: typeof WireUsage.Type): Usage => ({ inputTokens: u.prompt_tokens })\n\n// `task` is dropped on the generic path (OpenAI has no task parameter on any\n// model, so this is a per-Layer gap, not per-model). Bucket 2: warn, don't fail.\nconst warnTaskDropped = (task: CommonEmbedRequest[\"task\"]): Effect.Effect<void> =>\n Capabilities.warnDroppedWhen(task, {\n provider: \"openai\",\n capability: \"task\",\n field: \"task\",\n reason: \"OpenAI embeddings have no task-type parameter.\",\n })\n\nconst embedImpl =\n (cfg: Config) =>\n (\n request: OpenAIEmbedRequest,\n ): Effect.Effect<EmbedResponse, AiError.AiError, HttpClient.HttpClient> =>\n buildSingleBody(request).pipe(\n Effect.flatMap((body) => postEmbed(cfg, body)),\n Effect.flatMap((decoded) => {\n const first = decoded.data[0]\n if (first === undefined) {\n return Effect.fail(transportFailure(\"OpenAI returned empty `data` array\"))\n }\n return Effect.succeed<EmbedResponse>({\n embedding: valuesToEmbedding(first.embedding),\n usage: usageOf(decoded.usage),\n })\n }),\n )\n\nconst embedManyImpl =\n (cfg: Config) =>\n (\n request: OpenAIEmbedManyRequest,\n ): Effect.Effect<EmbedManyResponse, AiError.AiError, HttpClient.HttpClient> =>\n buildBatchBody(request).pipe(\n Effect.flatMap((body) => postEmbed(cfg, body)),\n Effect.map(\n (decoded): EmbedManyResponse => ({\n embeddings: orderedEmbeddings(decoded.data),\n usage: usageOf(decoded.usage),\n }),\n ),\n )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Build an `OpenAIEmbeddingService` value. For Layer-based setup, prefer\n * `layer`.\n */\nexport const make = (\n cfg: Config,\n): Effect.Effect<OpenAIEmbeddingService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient.asEffect(), (client) => ({\n embed: (request) =>\n embedImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n embedMany: (request) =>\n embedManyImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n }))\n\n/**\n * Layer that registers both the provider-specific `OpenAIEmbedding` tag\n * and the generic `EmbeddingModel` tag, sharing one underlying\n * implementation. The generic registration trusts the caller; invalid\n * encodings produce an `InvalidRequest` from OpenAI's API.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<OpenAIEmbedding | EmbeddingModel, never, HttpClient.HttpClient> => {\n const typed = Layer.effect(OpenAIEmbedding, make(cfg))\n const generic = Layer.effect(\n EmbeddingModel,\n Effect.map(\n make(cfg),\n (s): EmbeddingModelService => ({\n // OpenAI emits float32 only and has no task parameter. Reject a\n // non-float32 `encoding` (bucket 1, else a float32 vector comes back\n // mislabeled as the requested type) and warn on a dropped `task`\n // (bucket 2).\n embed: <E extends EmbedEncoding | undefined = undefined>(\n req: Omit<CommonEmbedRequest, \"encoding\"> & { readonly encoding?: E },\n ) =>\n assertEncoding(req.encoding, [\"float32\"], \"openai\").pipe(\n Effect.andThen(warnTaskDropped(req.task)),\n Effect.andThen(s.embed(req as OpenAIEmbedRequest)),\n ) as Effect.Effect<EmbedResponse<E>, AiError.AiError>,\n embedMany: <E extends EmbedEncoding | undefined = undefined>(\n req: Omit<CommonEmbedManyRequest, \"encoding\"> & { readonly encoding?: E },\n ) =>\n assertEncoding(req.encoding, [\"float32\"], \"openai\").pipe(\n Effect.andThen(warnTaskDropped(req.task)),\n Effect.andThen(s.embedMany(req as OpenAIEmbedManyRequest)),\n ) as Effect.Effect<EmbedManyResponse<E>, AiError.AiError>,\n }),\n ),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAa,kBAAb,cAAqC,QAAQ,SAAkD,CAC7F,2DACD,CAAC;AAgBF,MAAM,gBAAiC,IAAI,QAAQ,YAAY;CAC7D,UAAU;CACV,YAAY;CACZ,QAAQ;CACT,CAAC;AAEF,MAAM,cAAc,SAClB,UAAU,OAAO,OAAO,QAAQ,KAAK,KAAK,GAAG,OAAO,KAAK,cAAc;;;;;;AAOzE,MAAM,iBAAiB,UAA8D;AACnF,KAAI,OAAO,UAAU,SAAU,QAAO,OAAO,QAAQ,MAAM;AAC3D,KAAI,UAAU,MAAO,QAAO,OAAO,QAAQ,MAAM,KAAK;A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M,IAA0B,CAAC,CACnD;EACH,YACE,QAEA,eAAe,IAAI,UAAU,CAAC,UAAU,EAAE,SAAS,CAAC,KAClD,OAAO,QAAQ,gBAAgB,IAAI,KAAK,CAAC,EACzC,OAAO,QAAQ,EAAE,UAAU,IAA8B,CAAC,CAC3D;EACJ,EACF,CACF;AACD,QAAO,MAAM,MAAM,OAAO,QAAQ"}
|
|
1
|
+
{"version":3,"file":"OpenAIEmbedding.mjs","names":[],"sources":["../src/OpenAIEmbedding.ts"],"sourcesContent":["import { Context, Effect, Layer, Redacted, Schema } from \"effect\"\nimport { HttpClient, HttpClientRequest } from \"effect/unstable/http\"\nimport * as AiError from \"@effect-uai/core/AiError\"\nimport * as Capabilities from \"@effect-uai/core/Capabilities\"\nimport type {\n EmbedContentPart,\n EmbedInput,\n Float32Embedding,\n Usage,\n} from \"@effect-uai/core/Embedding\"\nimport {\n assertEncoding,\n type CommonEmbedManyRequest,\n type CommonEmbedRequest,\n type EmbedEncoding,\n EmbeddingModel,\n type EmbeddingModelService,\n type EmbedManyResponse,\n type EmbedResponse,\n} from \"@effect-uai/core/EmbeddingModel\"\nimport type { OpenAIEmbeddingModel } from \"./models.js\"\nimport { type OpenAiRegion, resolveHost } from \"./region.js\"\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * OpenAI's embedding API has no task-type semantics, so `task` is omitted\n * from the request type intentionally - passing it would be a compile\n * error. The generic `EmbeddingModel` registration accepts and silently\n * ignores `task` from `CommonEmbedRequest`.\n */\nexport type OpenAIEmbedRequest = Omit<CommonEmbedRequest, \"model\" | \"task\" | \"encoding\"> & {\n /** Narrows `CommonEmbedRequest.model` to the typed OpenAI union. */\n readonly model: OpenAIEmbeddingModel\n}\n\nexport type OpenAIEmbedManyRequest = Omit<OpenAIEmbedRequest, \"input\"> & {\n readonly inputs: ReadonlyArray<EmbedInput>\n}\n\nexport type OpenAIEmbeddingService = {\n readonly embed: (request: OpenAIEmbedRequest) => Effect.Effect<EmbedResponse, AiError.AiError>\n readonly embedMany: (\n request: OpenAIEmbedManyRequest,\n ) => Effect.Effect<EmbedManyResponse, AiError.AiError>\n}\n\n/**\n * Provider-typed service tag. Yield this for OpenAI-typed embedding\n * requests; yield the generic `EmbeddingModel` tag for provider-portable\n * code. Both are registered by `layer`.\n */\nexport class OpenAIEmbedding extends Context.Service<OpenAIEmbedding, OpenAIEmbeddingService>()(\n \"@betalyra/effect-uai/providers/responses/OpenAIEmbedding\",\n) {}\n\nexport type Config = {\n readonly apiKey: Redacted.Redacted\n readonly baseUrl?: string\n readonly region?: OpenAiRegion\n}\n\n// ---------------------------------------------------------------------------\n// Codec - input flattening to the single string OpenAI expects\n// ---------------------------------------------------------------------------\n\n// Image input on a text-only embedder is bucket 1: a silently dropped image\n// yields a vector that represents the wrong thing. Reject with `Unsupported`\n// (capability gap), not `InvalidRequest` (which is for wire-shape mismatches).\n// OpenAI's embeddings API remains text-only as of June 2026.\nconst imageRejected: AiError.AiError = new AiError.Unsupported({\n provider: \"openai\",\n capability: \"imageEmbedding\",\n reason: \"OpenAI embeddings are text-only; pass a string or { text }.\",\n})\n\nconst partToText = (part: EmbedContentPart): Effect.Effect<string, AiError.AiError> =>\n \"text\" in part ? Effect.succeed(part.text) : Effect.fail(imageRejected)\n\n/**\n * OpenAI accepts a single string per input. Pure-text `content[]` is\n * concatenated with newlines (treats them as paragraphs of one document);\n * any image part fails with `Unsupported`.\n */\nconst inputToString = (input: EmbedInput): Effect.Effect<string, AiError.AiError> => {\n if (typeof input === \"string\") return Effect.succeed(input)\n if (\"text\" in input) return Effect.succeed(input.text)\n if (\"image\" in input) return Effect.fail(imageRejected)\n return Effect.forEach(input.content, partToText).pipe(Effect.map((texts) => texts.join(\"\\n\")))\n}\n\n// ---------------------------------------------------------------------------\n// Codec - request body\n// ---------------------------------------------------------------------------\n\ntype WireBody = {\n readonly model: string\n readonly input: string | ReadonlyArray<string>\n readonly dimensions?: number\n readonly encoding_format?: \"float\" | \"base64\"\n}\n\nconst buildSingleBody = (request: OpenAIEmbedRequest): Effect.Effect<WireBody, AiError.AiError> =>\n inputToString(request.input).pipe(\n Effect.map((input) => ({\n model: request.model,\n input,\n ...(request.dimensions !== undefined && { dimensions: request.dimensions }),\n })),\n )\n\nconst buildBatchBody = (\n request: OpenAIEmbedManyRequest,\n): Effect.Effect<WireBody, AiError.AiError> =>\n Effect.forEach(request.inputs, inputToString).pipe(\n Effect.map((inputs) => ({\n model: request.model,\n input: inputs,\n ...(request.dimensions !== undefined && { dimensions: request.dimensions }),\n })),\n )\n\n// ---------------------------------------------------------------------------\n// Codec - response\n// ---------------------------------------------------------------------------\n\nconst WireEmbeddingItem = Schema.Struct({\n embedding: Schema.Array(Schema.Number),\n index: Schema.Number,\n})\n\nconst WireUsage = Schema.Struct({\n prompt_tokens: Schema.Number,\n total_tokens: Schema.Number,\n})\n\nconst WireResponse = Schema.Struct({\n data: Schema.Array(WireEmbeddingItem),\n model: Schema.String,\n usage: WireUsage,\n})\n\nconst valuesToEmbedding = (values: ReadonlyArray<number>): Float32Embedding => ({\n _tag: \"float32\",\n vector: Float32Array.from(values),\n})\n\n// OpenAI returns `data[]` unsorted in theory; sort by `index` so caller\n// gets results in the order they passed inputs.\nconst orderedEmbeddings = (\n data: ReadonlyArray<{ readonly embedding: ReadonlyArray<number>; readonly index: number }>,\n): ReadonlyArray<Float32Embedding> =>\n [...data].sort((a, b) => a.index - b.index).map((item) => valuesToEmbedding(item.embedding))\n\n// ---------------------------------------------------------------------------\n// HTTP errors\n// ---------------------------------------------------------------------------\n\nconst httpStatusError = (status: number, body: string): AiError.AiError => {\n const provider = \"openai\"\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\nconst transportFailure = (cause: unknown): AiError.AiError =>\n new AiError.Unavailable({ provider: \"openai\", raw: cause })\n\n// ---------------------------------------------------------------------------\n// HTTP plumbing\n// ---------------------------------------------------------------------------\n\nconst postEmbed = (\n cfg: Config,\n body: WireBody,\n): Effect.Effect<typeof WireResponse.Type, AiError.AiError, HttpClient.HttpClient> =>\n Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient\n const httpRequest = HttpClientRequest.post(`${resolveHost(cfg)}/embeddings`).pipe(\n HttpClientRequest.bearerToken(cfg.apiKey),\n HttpClientRequest.bodyJsonUnsafe(body),\n )\n const response = yield* client.execute(httpRequest).pipe(Effect.mapError(transportFailure))\n if (response.status >= 400) {\n const text = yield* response.text.pipe(Effect.orElseSucceed(() => \"\"))\n return yield* httpStatusError(response.status, text)\n }\n const json = yield* response.json.pipe(Effect.mapError(transportFailure))\n return yield* Schema.decodeUnknownEffect(WireResponse)(json).pipe(\n Effect.mapError(transportFailure),\n )\n })\n\n// ---------------------------------------------------------------------------\n// Service implementation\n// ---------------------------------------------------------------------------\n\nconst usageOf = (u: typeof WireUsage.Type): Usage => ({ inputTokens: u.prompt_tokens })\n\n// `task` is dropped on the generic path (OpenAI has no task parameter on any\n// model, so this is a per-Layer gap, not per-model). Bucket 2: warn, don't fail.\nconst warnTaskDropped = (task: CommonEmbedRequest[\"task\"]): Effect.Effect<void> =>\n Capabilities.warnDroppedWhen(task, {\n provider: \"openai\",\n capability: \"task\",\n field: \"task\",\n reason: \"OpenAI embeddings have no task-type parameter.\",\n })\n\nconst embedImpl =\n (cfg: Config) =>\n (\n request: OpenAIEmbedRequest,\n ): Effect.Effect<EmbedResponse, AiError.AiError, HttpClient.HttpClient> =>\n buildSingleBody(request).pipe(\n Effect.flatMap((body) => postEmbed(cfg, body)),\n Effect.flatMap((decoded) => {\n const first = decoded.data[0]\n if (first === undefined) {\n return Effect.fail(transportFailure(\"OpenAI returned empty `data` array\"))\n }\n return Effect.succeed<EmbedResponse>({\n embedding: valuesToEmbedding(first.embedding),\n usage: usageOf(decoded.usage),\n })\n }),\n )\n\nconst embedManyImpl =\n (cfg: Config) =>\n (\n request: OpenAIEmbedManyRequest,\n ): Effect.Effect<EmbedManyResponse, AiError.AiError, HttpClient.HttpClient> =>\n buildBatchBody(request).pipe(\n Effect.flatMap((body) => postEmbed(cfg, body)),\n Effect.map(\n (decoded): EmbedManyResponse => ({\n embeddings: orderedEmbeddings(decoded.data),\n usage: usageOf(decoded.usage),\n }),\n ),\n )\n\n// ---------------------------------------------------------------------------\n// Constructors\n// ---------------------------------------------------------------------------\n\n/**\n * Build an `OpenAIEmbeddingService` value. For Layer-based setup, prefer\n * `layer`.\n */\nexport const make = (\n cfg: Config,\n): Effect.Effect<OpenAIEmbeddingService, never, HttpClient.HttpClient> =>\n Effect.map(HttpClient.HttpClient, (client) => ({\n embed: (request) =>\n embedImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n embedMany: (request) =>\n embedManyImpl(cfg)(request).pipe(Effect.provideService(HttpClient.HttpClient, client)),\n }))\n\n/**\n * Layer that registers both the provider-specific `OpenAIEmbedding` tag\n * and the generic `EmbeddingModel` tag, sharing one underlying\n * implementation. The generic registration trusts the caller; invalid\n * encodings produce an `InvalidRequest` from OpenAI's API.\n */\nexport const layer = (\n cfg: Config,\n): Layer.Layer<OpenAIEmbedding | EmbeddingModel, never, HttpClient.HttpClient> => {\n const typed = Layer.effect(OpenAIEmbedding, make(cfg))\n const generic = Layer.effect(\n EmbeddingModel,\n Effect.map(\n make(cfg),\n (s): EmbeddingModelService => ({\n // OpenAI emits float32 only and has no task parameter. Reject a\n // non-float32 `encoding` (bucket 1, else a float32 vector comes back\n // mislabeled as the requested type) and warn on a dropped `task`\n // (bucket 2).\n embed: <E extends EmbedEncoding | undefined = undefined>(\n req: Omit<CommonEmbedRequest, \"encoding\"> & { readonly encoding?: E },\n ) =>\n assertEncoding(req.encoding, [\"float32\"], \"openai\").pipe(\n Effect.andThen(warnTaskDropped(req.task)),\n Effect.andThen(s.embed(req as OpenAIEmbedRequest)),\n ) as Effect.Effect<EmbedResponse<E>, AiError.AiError>,\n embedMany: <E extends EmbedEncoding | undefined = undefined>(\n req: Omit<CommonEmbedManyRequest, \"encoding\"> & { readonly encoding?: E },\n ) =>\n assertEncoding(req.encoding, [\"float32\"], \"openai\").pipe(\n Effect.andThen(warnTaskDropped(req.task)),\n Effect.andThen(s.embedMany(req as OpenAIEmbedManyRequest)),\n ) as Effect.Effect<EmbedManyResponse<E>, AiError.AiError>,\n }),\n ),\n )\n return Layer.merge(typed, generic)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAsDA,IAAa,kBAAb,cAAqC,QAAQ,SAAkD,CAC7F,2DACD,CAAC;AAgBF,MAAM,gBAAiC,IAAI,QAAQ,YAAY;CAC7D,UAAU;CACV,YAAY;CACZ,QAAQ;CACT,CAAC;AAEF,MAAM,cAAc,SAClB,UAAU,OAAO,OAAO,QAAQ,KAAK,KAAK,GAAG,OAAO,KAAK,cAAc;;;;;;AAOzE,MAAM,iBAAiB,UAA8D;AACnF,KAAI,OAAO,UAAU,SAAU,QAAO,OAAO,QAAQ,MAAM;AAC3D,KAAI,UAAU,MAAO,QAAO,OAAO,QAAQ,MAAM,KAAK;AACtD,KAAI,WAAW,MAAO,QAAO,OAAO,KAAK,cAAc;AACvD,QAAO,OAAO,QAAQ,MAAM,SAAS,WAAW,CAAC,KAAK,OAAO,KAAK,UAAU,MAAM,KAAK,KAAK,CAAC,CAAC;;AAchG,MAAM,mBAAmB,YACvB,cAAc,QAAQ,MAAM,CAAC,KAC3B,OAAO,KAAK,WAAW;CACrB,OAAO,QAAQ;CACf;CACA,GAAI,QAAQ,eAAe,KAAA,KAAa,EAAE,YAAY,QAAQ,YAAY;CAC3E,EAAE,CAC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enAiRegion } from "./region.mjs";
|
|
3
|
+
import { UserLocation, WebSearchFilters, WebSearchOptions, codeInterpreterTool, fileSearchTool, webSearchTool } from "./ResponsesTools.mjs";
|
|
3
4
|
import { ProviderEvent } from "./streamEvents.mjs";
|
|
4
5
|
import { Context, Effect, Layer, Redacted, Stream } from "effect";
|
|
5
|
-
import { HttpClient } from "effect/unstable/http";
|
|
6
|
+
import { HttpClient, HttpClientResponse } from "effect/unstable/http";
|
|
6
7
|
import * as AiError from "@effect-uai/core/AiError";
|
|
7
8
|
import { CommonRequest, LanguageModel } from "@effect-uai/core/LanguageModel";
|
|
8
9
|
import { Turn, TurnEvent } from "@effect-uai/core/Turn";
|
|
9
10
|
|
|
10
11
|
//#region src/Responses.d.ts
|
|
11
12
|
declare namespace Responses_d_exports {
|
|
12
|
-
export { Config, Responses, ResponsesRequest, ResponsesService, layer, make, toCanonical };
|
|
13
|
+
export { Config, Responses, ResponsesRequest, ResponsesService, UserLocation, WebSearchFilters, WebSearchOptions, codeInterpreterTool, fileSearchTool, httpStatusError, layer, make, providerEventsOfResponse, toCanonical, webSearchTool };
|
|
13
14
|
}
|
|
14
15
|
type ResponsesRequest = Omit<CommonRequest, "model"> & {
|
|
15
16
|
/**
|
|
@@ -29,6 +30,20 @@ type ResponsesRequest = Omit<CommonRequest, "model"> & {
|
|
|
29
30
|
readonly safetyIdentifier?: string;
|
|
30
31
|
readonly promptCacheKey?: string;
|
|
31
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>>;
|
|
32
47
|
/**
|
|
33
48
|
* Free-form JSON output: model emits valid JSON without schema
|
|
34
49
|
* constraints. Mutually exclusive with `structured` (schema wins if
|
|
@@ -80,7 +95,22 @@ type Config = {
|
|
|
80
95
|
readonly apiKey: Redacted.Redacted;
|
|
81
96
|
readonly baseUrl?: string;
|
|
82
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>>;
|
|
83
104
|
};
|
|
105
|
+
declare const httpStatusError: (status: number, body: string) => AiError.AiError;
|
|
106
|
+
/**
|
|
107
|
+
* Decode an already-executed `/responses` HTTP response into the native
|
|
108
|
+
* `ProviderEvent` stream: fail on a >=400 status, else SSE-decode the body and
|
|
109
|
+
* lift terminal `error` / `response.failed` events to a typed `AiError`. Shared
|
|
110
|
+
* by the streaming turn path (POST) and the deep-research resume stream (GET
|
|
111
|
+
* `?stream=true`).
|
|
112
|
+
*/
|
|
113
|
+
declare const providerEventsOfResponse: (response: HttpClientResponse.HttpClientResponse) => Stream.Stream<ProviderEvent, AiError.AiError>;
|
|
84
114
|
/**
|
|
85
115
|
* Project a stream of native `ProviderEvent`s into canonical `TurnEvent`s.
|
|
86
116
|
* Threads a fresh `CallIdLookup` per stream so `function_call_arguments.delta`
|
|
@@ -100,5 +130,5 @@ declare const make: (cfg: Config) => Effect.Effect<ResponsesService, never, Http
|
|
|
100
130
|
*/
|
|
101
131
|
declare const layer: (cfg: Config) => Layer.Layer<Responses | LanguageModel, never, HttpClient.HttpClient>;
|
|
102
132
|
//#endregion
|
|
103
|
-
export { Config, Responses, ResponsesRequest, ResponsesService, layer, make, Responses_d_exports as t, toCanonical };
|
|
133
|
+
export { Config, Responses, ResponsesRequest, ResponsesService, type UserLocation, type WebSearchFilters, type WebSearchOptions, codeInterpreterTool, fileSearchTool, httpStatusError, layer, make, providerEventsOfResponse, Responses_d_exports as t, toCanonical, webSearchTool };
|
|
104
134
|
//# sourceMappingURL=Responses.d.mts.map
|
package/dist/Responses.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Responses.d.mts","names":[],"sources":["../src/Responses.ts"],"mappings":"
|
|
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,SAmCpB,cAAA;IAAA,SAA4B,IAAA;EAAA;EA1B5B;;;;EAAA,SA+BA,SAAA;AAAA;AAAA,KAGC,gBAAA;EA7BD;;;;;EAAA,SAmCA,YAAA,GACP,OAAA,EAAS,gBAAA,KACN,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,OAAA,CAAQ,OAAA;EAhBL;;;;EAAA,SAqB5B,UAAA,GAAa,OAAA,EAAS,gBAAA,KAAqB,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,OAAA,CAAQ,OAAA;EAb3D;;;;;EAAA,SAmBjB,IAAA,GAAO,OAAA,EAAS,gBAAA,KAAqB,MAAA,CAAO,MAAA,CAAO,IAAA,EAAM,OAAA,CAAQ,OAAA;EAN3C;;;;;EAAA,SAYtB,WAAA,SACP,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,CAAA,EAAG,CAAA,MAChC,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,CAAA,EAAG,CAAA;AAAA;AAAA,cAClC,cAAA;;;;;;;cAQY,SAAA,SAAkB,cAAA;AAAA,KAInB,MAAA;EAAA,SACD,MAAA,EAAQ,QAAA,CAAS,QAAA;EAAA,SACjB,OAAA;EAAA,SACA,MAAA,GAAS,YAAA;EApChB;;;;;EAAA,SA0CO,SAAA,GAAY,QAAA,CAAS,MAAA;AAAA;AAAA,cA0InB,eAAA,GAAmB,MAAA,UAAgB,IAAA,aAAe,OAAA,CAAQ,OAAA;;;;;;;;cAoB1D,wBAAA,GACX,QAAA,EAAU,kBAAA,CAAmB,kBAAA,KAC5B,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,OAAA,CAAQ,OAAA;;;;;;cAiE3B,WAAA,SACX,CAAA,EAAG,MAAA,CAAO,MAAA,CAAO,aAAA,EAAe,CAAA,EAAG,CAAA,MAClC,MAAA,CAAO,MAAA,CAAO,SAAA,EAAW,CAAA,EAAG,CAAA;;;;cAelB,IAAA,GAAQ,GAAA,EAAK,MAAA,KAAS,MAAA,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
|
@@ -1,19 +1,25 @@
|
|
|
1
1
|
import { t as __exportAll } from "./chunk-CfYAbeIz.mjs";
|
|
2
|
-
import { resolveHost } from "./region.mjs";
|
|
3
2
|
import { itemsToInput } from "./codec.mjs";
|
|
3
|
+
import { resolveHost } from "./region.mjs";
|
|
4
|
+
import { codeInterpreterTool, fileSearchTool, renderProviderTools, webSearchTool } from "./ResponsesTools.mjs";
|
|
4
5
|
import { KnownProviderEvent, eventToDeltas, makeCallIdLookup } from "./streamEvents.mjs";
|
|
5
|
-
import { Context, Effect, Layer, Match, Option, Schema, Stream } from "effect";
|
|
6
|
+
import { Context, Effect, Layer, Match, Option, Result, Schema, Stream } from "effect";
|
|
6
7
|
import { HttpClient, HttpClientRequest } from "effect/unstable/http";
|
|
7
8
|
import * as AiError from "@effect-uai/core/AiError";
|
|
8
9
|
import { LanguageModel, turnFromStream } from "@effect-uai/core/LanguageModel";
|
|
9
10
|
import * as SSE from "@effect-uai/core/SSE";
|
|
10
|
-
import { descriptorsOf } from "@effect-uai/core/Tool";
|
|
11
|
+
import { descriptorsOf, providerToolsOf } from "@effect-uai/core/Tool";
|
|
11
12
|
//#region src/Responses.ts
|
|
12
13
|
var Responses_exports = /* @__PURE__ */ __exportAll({
|
|
13
14
|
Responses: () => Responses,
|
|
15
|
+
codeInterpreterTool: () => codeInterpreterTool,
|
|
16
|
+
fileSearchTool: () => fileSearchTool,
|
|
17
|
+
httpStatusError: () => httpStatusError,
|
|
14
18
|
layer: () => layer,
|
|
15
19
|
make: () => make,
|
|
16
|
-
|
|
20
|
+
providerEventsOfResponse: () => providerEventsOfResponse,
|
|
21
|
+
toCanonical: () => toCanonical,
|
|
22
|
+
webSearchTool: () => webSearchTool
|
|
17
23
|
});
|
|
18
24
|
/**
|
|
19
25
|
* Provider-typed service tag. Yield this when you want Responses-specific
|
|
@@ -36,20 +42,20 @@ const buildText = (request) => {
|
|
|
36
42
|
if (request.verbosity !== void 0) text.verbosity = request.verbosity;
|
|
37
43
|
return Object.keys(text).length === 0 ? void 0 : text;
|
|
38
44
|
};
|
|
39
|
-
const buildBody = (request) => {
|
|
45
|
+
const buildBody = (request, providerToolWire, cfg) => {
|
|
40
46
|
const text = buildText(request);
|
|
41
|
-
const tools = descriptorsOf(request.tools)
|
|
47
|
+
const tools = [...descriptorsOf(request.tools).map((t) => ({
|
|
48
|
+
type: "function",
|
|
49
|
+
name: t.name,
|
|
50
|
+
description: t.description,
|
|
51
|
+
parameters: t.inputSchema,
|
|
52
|
+
...t.strict !== void 0 && { strict: t.strict }
|
|
53
|
+
})), ...providerToolWire];
|
|
42
54
|
return {
|
|
43
55
|
model: request.model,
|
|
44
56
|
input: itemsToInput(request.history),
|
|
45
57
|
stream: true,
|
|
46
|
-
...tools.length > 0 && { tools
|
|
47
|
-
type: "function",
|
|
48
|
-
name: t.name,
|
|
49
|
-
description: t.description,
|
|
50
|
-
parameters: t.inputSchema,
|
|
51
|
-
...t.strict !== void 0 && { strict: t.strict }
|
|
52
|
-
})) },
|
|
58
|
+
...tools.length > 0 && { tools },
|
|
53
59
|
...request.toolChoice !== void 0 && { tool_choice: request.toolChoice },
|
|
54
60
|
...request.temperature !== void 0 && { temperature: request.temperature },
|
|
55
61
|
...request.maxOutputTokens !== void 0 && { max_output_tokens: request.maxOutputTokens },
|
|
@@ -64,7 +70,9 @@ const buildBody = (request) => {
|
|
|
64
70
|
...request.safetyIdentifier !== void 0 && { safety_identifier: request.safetyIdentifier },
|
|
65
71
|
...request.promptCacheKey !== void 0 && { prompt_cache_key: request.promptCacheKey },
|
|
66
72
|
...request.truncation !== void 0 && { truncation: request.truncation },
|
|
67
|
-
...text !== void 0 && { text }
|
|
73
|
+
...text !== void 0 && { text },
|
|
74
|
+
...cfg.extraBody,
|
|
75
|
+
...request.extraBody
|
|
68
76
|
};
|
|
69
77
|
};
|
|
70
78
|
const decodeKnown = Schema.decodeUnknownEffect(KnownProviderEvent);
|
|
@@ -78,10 +86,22 @@ const makeUnknown = (raw) => ({
|
|
|
78
86
|
* and produce `Option.none`.
|
|
79
87
|
*/
|
|
80
88
|
const eventToError = Match.type().pipe(Match.discriminators("type")({
|
|
81
|
-
error: (e) =>
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
error: (e) => {
|
|
90
|
+
const detail = e.error;
|
|
91
|
+
const message = detail?.message ?? e.message;
|
|
92
|
+
const code = detail?.code ?? e.code;
|
|
93
|
+
const param = detail?.param;
|
|
94
|
+
return detail?.type === "invalid_request_error" ? new AiError.InvalidRequest({
|
|
95
|
+
provider: "responses",
|
|
96
|
+
...param != null && { param },
|
|
97
|
+
raw: e
|
|
98
|
+
}) : new AiError.GenerationFailed({
|
|
99
|
+
provider: "responses",
|
|
100
|
+
...code != null && { code },
|
|
101
|
+
...message != null && { message },
|
|
102
|
+
raw: e
|
|
103
|
+
});
|
|
104
|
+
},
|
|
85
105
|
"response.failed": (e) => {
|
|
86
106
|
const code = e.response.error?.code;
|
|
87
107
|
const message = e.response.error?.message;
|
|
@@ -135,26 +155,43 @@ const httpStatusError = (status, body) => {
|
|
|
135
155
|
raw
|
|
136
156
|
});
|
|
137
157
|
};
|
|
158
|
+
/**
|
|
159
|
+
* Decode an already-executed `/responses` HTTP response into the native
|
|
160
|
+
* `ProviderEvent` stream: fail on a >=400 status, else SSE-decode the body and
|
|
161
|
+
* lift terminal `error` / `response.failed` events to a typed `AiError`. Shared
|
|
162
|
+
* by the streaming turn path (POST) and the deep-research resume stream (GET
|
|
163
|
+
* `?stream=true`).
|
|
164
|
+
*/
|
|
165
|
+
const providerEventsOfResponse = (response) => Stream.unwrap(Effect.gen(function* () {
|
|
166
|
+
if (response.status >= 400) {
|
|
167
|
+
const body = yield* response.text.pipe(Effect.orElseSucceed(() => ""));
|
|
168
|
+
return Stream.fail(httpStatusError(response.status, body));
|
|
169
|
+
}
|
|
170
|
+
return response.stream.pipe(Stream.mapError((cause) => new AiError.Unavailable({
|
|
171
|
+
provider: "responses",
|
|
172
|
+
raw: cause
|
|
173
|
+
})), SSE.fromBytes, Stream.mapEffect(sseEventToProviderEvent), Stream.flatMap((event) => Option.match(eventToError(event), {
|
|
174
|
+
onNone: () => Stream.succeed(event),
|
|
175
|
+
onSome: Stream.fail
|
|
176
|
+
})));
|
|
177
|
+
}));
|
|
138
178
|
const buildNativeStream = (cfg) => {
|
|
139
179
|
const url = `${resolveHost(cfg)}/responses`;
|
|
140
180
|
return (request) => Stream.unwrap(Effect.gen(function* () {
|
|
141
181
|
const client = yield* HttpClient.HttpClient;
|
|
142
|
-
const
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
return
|
|
182
|
+
const providerToolWire = yield* Result.match(renderProviderTools(providerToolsOf(request.tools)), {
|
|
183
|
+
onFailure: (e) => Effect.fail(new AiError.Unsupported({
|
|
184
|
+
provider: "responses",
|
|
185
|
+
capability: e.capability,
|
|
186
|
+
reason: e.reason
|
|
187
|
+
})),
|
|
188
|
+
onSuccess: (wire) => Effect.succeed(wire)
|
|
189
|
+
});
|
|
190
|
+
const httpRequest = HttpClientRequest.post(url).pipe(HttpClientRequest.bearerToken(cfg.apiKey), HttpClientRequest.bodyJsonUnsafe(buildBody(request, providerToolWire, cfg)), HttpClientRequest.accept("text/event-stream"));
|
|
191
|
+
return providerEventsOfResponse(yield* client.execute(httpRequest).pipe(Effect.mapError((cause) => new AiError.Unavailable({
|
|
152
192
|
provider: "responses",
|
|
153
193
|
raw: cause
|
|
154
|
-
}))
|
|
155
|
-
onNone: () => Stream.succeed(event),
|
|
156
|
-
onSome: Stream.fail
|
|
157
|
-
})));
|
|
194
|
+
}))));
|
|
158
195
|
}));
|
|
159
196
|
};
|
|
160
197
|
/**
|
|
@@ -169,7 +206,7 @@ const toCanonical = (s) => Stream.unwrap(Effect.sync(() => {
|
|
|
169
206
|
/**
|
|
170
207
|
* Build a `ResponsesService` value. For Layer-based setup, prefer `layer`.
|
|
171
208
|
*/
|
|
172
|
-
const make = (cfg) => Effect.map(HttpClient.HttpClient
|
|
209
|
+
const make = (cfg) => Effect.map(HttpClient.HttpClient, (client) => {
|
|
173
210
|
const streamNative = (request) => buildNativeStream(cfg)(request).pipe(Stream.provideService(HttpClient.HttpClient, client));
|
|
174
211
|
const streamTurn = (request) => toCanonical(streamNative(request));
|
|
175
212
|
return {
|
|
@@ -195,6 +232,6 @@ const layer = (cfg) => {
|
|
|
195
232
|
return Layer.merge(typed, generic);
|
|
196
233
|
};
|
|
197
234
|
//#endregion
|
|
198
|
-
export { Responses, layer, make, Responses_exports as t, toCanonical };
|
|
235
|
+
export { Responses, codeInterpreterTool, fileSearchTool, httpStatusError, layer, make, providerEventsOfResponse, Responses_exports as t, toCanonical, webSearchTool };
|
|
199
236
|
|
|
200
237
|
//# sourceMappingURL=Responses.mjs.map
|