@tinyweb_dev/agent-framework-llm 0.2.0 → 0.3.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/cache-policy.d.ts +3 -0
- package/dist/cache-policy.d.ts.map +1 -0
- package/dist/index.cjs +2956 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2831 -0
- package/dist/index.js.map +1 -0
- package/dist/llm.cjs +1718 -0
- package/dist/llm.cjs.map +1 -0
- package/dist/llm.d.ts +284 -0
- package/dist/llm.d.ts.map +1 -0
- package/dist/llm.js +1692 -0
- package/dist/llm.js.map +1 -0
- package/dist/protocols/openai-chat.cjs +2443 -0
- package/dist/protocols/openai-chat.cjs.map +1 -0
- package/dist/protocols/openai-chat.d.ts +357 -0
- package/dist/protocols/openai-chat.d.ts.map +1 -0
- package/dist/protocols/openai-chat.js +2414 -0
- package/dist/protocols/openai-chat.js.map +1 -0
- package/dist/protocols/openai-compatible-chat.cjs +2443 -0
- package/dist/protocols/openai-compatible-chat.cjs.map +1 -0
- package/dist/protocols/openai-compatible-chat.d.ts +77 -0
- package/dist/protocols/openai-compatible-chat.d.ts.map +1 -0
- package/dist/protocols/openai-compatible-chat.js +2419 -0
- package/dist/protocols/openai-compatible-chat.js.map +1 -0
- package/dist/protocols/shared.cjs +904 -0
- package/dist/protocols/shared.cjs.map +1 -0
- package/dist/protocols/shared.d.ts +51 -0
- package/dist/protocols/shared.d.ts.map +1 -0
- package/dist/protocols/shared.js +857 -0
- package/dist/protocols/shared.js.map +1 -0
- package/dist/protocols/utils/openai-options.d.ts +15 -0
- package/dist/protocols/utils/openai-options.d.ts.map +1 -0
- package/dist/protocols/utils/tool-stream.d.ts +78 -0
- package/dist/protocols/utils/tool-stream.d.ts.map +1 -0
- package/dist/provider.cjs +20 -0
- package/dist/provider.cjs.map +1 -0
- package/dist/provider.d.ts +19 -0
- package/dist/provider.d.ts.map +1 -0
- package/dist/provider.js +17 -0
- package/dist/provider.js.map +1 -0
- package/{src/providers/openai-compatible-profile.ts → dist/providers/openai-compatible-profile.cjs} +12 -12
- package/dist/providers/openai-compatible-profile.cjs.map +1 -0
- package/dist/providers/openai-compatible-profile.d.ts +52 -0
- package/dist/providers/openai-compatible-profile.d.ts.map +1 -0
- package/dist/providers/openai-compatible-profile.js +21 -0
- package/dist/providers/openai-compatible-profile.js.map +1 -0
- package/dist/providers/openai-compatible.cjs +2533 -0
- package/dist/providers/openai-compatible.cjs.map +1 -0
- package/dist/providers/openai-compatible.d.ts +128 -0
- package/dist/providers/openai-compatible.d.ts.map +1 -0
- package/dist/providers/openai-compatible.js +2495 -0
- package/dist/providers/openai-compatible.js.map +1 -0
- package/dist/providers/openai-options.cjs +797 -0
- package/dist/providers/openai-options.cjs.map +1 -0
- package/dist/providers/openai-options.d.ts +29 -0
- package/dist/providers/openai-options.d.ts.map +1 -0
- package/dist/providers/openai-options.js +792 -0
- package/dist/providers/openai-options.js.map +1 -0
- package/dist/providers/openai.cjs +2517 -0
- package/dist/providers/openai.cjs.map +1 -0
- package/dist/providers/openai.d.ts +87 -0
- package/dist/providers/openai.d.ts.map +1 -0
- package/dist/providers/openai.js +2489 -0
- package/dist/providers/openai.js.map +1 -0
- package/dist/route/auth-options.cjs +855 -0
- package/dist/route/auth-options.cjs.map +1 -0
- package/dist/route/auth-options.d.ts +25 -0
- package/dist/route/auth-options.d.ts.map +1 -0
- package/dist/route/auth-options.js +852 -0
- package/dist/route/auth-options.js.map +1 -0
- package/dist/route/auth.cjs +855 -0
- package/dist/route/auth.cjs.map +1 -0
- package/dist/route/auth.d.ts +51 -0
- package/dist/route/auth.d.ts.map +1 -0
- package/dist/route/auth.js +836 -0
- package/dist/route/auth.js.map +1 -0
- package/dist/route/client.cjs +1844 -0
- package/dist/route/client.cjs.map +1 -0
- package/dist/route/client.d.ts +268 -0
- package/dist/route/client.d.ts.map +1 -0
- package/dist/route/client.js +1830 -0
- package/dist/route/client.js.map +1 -0
- package/dist/route/endpoint.cjs +756 -0
- package/dist/route/endpoint.cjs.map +1 -0
- package/dist/route/endpoint.d.ts +13 -0
- package/dist/route/endpoint.d.ts.map +1 -0
- package/dist/route/endpoint.js +752 -0
- package/dist/route/endpoint.js.map +1 -0
- package/dist/route/executor.cjs +1077 -0
- package/dist/route/executor.cjs.map +1 -0
- package/dist/route/executor.d.ts +13 -0
- package/dist/route/executor.d.ts.map +1 -0
- package/dist/route/executor.js +1072 -0
- package/dist/route/executor.js.map +1 -0
- package/dist/route/framing.cjs +773 -0
- package/dist/route/framing.cjs.map +1 -0
- package/dist/route/framing.d.ts +9 -0
- package/dist/route/framing.d.ts.map +1 -0
- package/dist/route/framing.js +750 -0
- package/dist/route/framing.js.map +1 -0
- package/dist/route/overflow-detect.d.ts +18 -0
- package/dist/route/overflow-detect.d.ts.map +1 -0
- package/dist/route/protocol.cjs +25 -0
- package/dist/route/protocol.cjs.map +1 -0
- package/dist/route/protocol.d.ts +40 -0
- package/dist/route/protocol.d.ts.map +1 -0
- package/dist/route/protocol.js +21 -0
- package/dist/route/protocol.js.map +1 -0
- package/dist/route/transport/http.d.ts +48 -0
- package/dist/route/transport/http.d.ts.map +1 -0
- package/dist/route/transport/index.cjs +969 -0
- package/dist/route/transport/index.cjs.map +1 -0
- package/dist/route/transport/index.d.ts +13 -0
- package/dist/route/transport/index.d.ts.map +1 -0
- package/dist/route/transport/index.js +967 -0
- package/dist/route/transport/index.js.map +1 -0
- package/dist/schema/errors.d.ts +181 -0
- package/dist/schema/errors.d.ts.map +1 -0
- package/dist/schema/events.d.ts +3224 -0
- package/dist/schema/events.d.ts.map +1 -0
- package/dist/schema/ids.d.ts +31 -0
- package/dist/schema/ids.d.ts.map +1 -0
- package/dist/schema/index.cjs +847 -0
- package/dist/schema/index.cjs.map +1 -0
- package/dist/schema/index.d.ts +6 -0
- package/dist/schema/index.d.ts.map +1 -0
- package/dist/schema/index.js +777 -0
- package/dist/schema/index.js.map +1 -0
- package/dist/schema/messages.d.ts +292 -0
- package/dist/schema/messages.d.ts.map +1 -0
- package/dist/schema/options.d.ts +123 -0
- package/dist/schema/options.d.ts.map +1 -0
- package/dist/tool-runtime.cjs +907 -0
- package/dist/tool-runtime.cjs.map +1 -0
- package/dist/tool-runtime.d.ts +50 -0
- package/dist/tool-runtime.d.ts.map +1 -0
- package/dist/tool-runtime.js +901 -0
- package/dist/tool-runtime.js.map +1 -0
- package/dist/tool.cjs +802 -0
- package/dist/tool.cjs.map +1 -0
- package/dist/tool.d.ts +111 -0
- package/dist/tool.d.ts.map +1 -0
- package/dist/tool.js +796 -0
- package/dist/tool.js.map +1 -0
- package/package.json +112 -29
- package/src/cache-policy.ts +0 -92
- package/src/index.ts +0 -62
- package/src/llm.ts +0 -210
- package/src/protocols/openai-chat.ts +0 -464
- package/src/protocols/openai-compatible-chat.ts +0 -29
- package/src/protocols/shared.ts +0 -204
- package/src/protocols/utils/openai-options.ts +0 -56
- package/src/protocols/utils/tool-stream.ts +0 -135
- package/src/provider.ts +0 -32
- package/src/providers/openai-compatible.ts +0 -69
- package/src/providers/openai-options.ts +0 -71
- package/src/providers/openai.ts +0 -39
- package/src/route/auth-options.ts +0 -48
- package/src/route/auth.ts +0 -198
- package/src/route/client.ts +0 -459
- package/src/route/endpoint.ts +0 -28
- package/src/route/executor.ts +0 -396
- package/src/route/framing.ts +0 -13
- package/src/route/overflow-detect.ts +0 -74
- package/src/route/protocol.ts +0 -48
- package/src/route/transport/http.ts +0 -123
- package/src/route/transport/index.ts +0 -21
- package/src/schema/errors.ts +0 -225
- package/src/schema/events.ts +0 -335
- package/src/schema/ids.ts +0 -44
- package/src/schema/index.ts +0 -6
- package/src/schema/messages.ts +0 -250
- package/src/schema/options.ts +0 -231
- package/src/tool-runtime.ts +0 -301
- package/src/tool.ts +0 -212
package/dist/index.js
ADDED
|
@@ -0,0 +1,2831 @@
|
|
|
1
|
+
import { Schema, Context, Layer, Effect, Array as Array$1, Stream, Random, Cause, Config, Redacted } from 'effect';
|
|
2
|
+
import { Buffer } from 'buffer';
|
|
3
|
+
import * as Sse from 'effect/unstable/encoding/Sse';
|
|
4
|
+
import { HttpClient, FetchHttpClient, Headers, HttpClientError, HttpClientRequest } from 'effect/unstable/http';
|
|
5
|
+
|
|
6
|
+
var __defProp = Object.defineProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var ProtocolID = Schema.String;
|
|
12
|
+
var RouteID = Schema.String;
|
|
13
|
+
var ModelID = Schema.String.pipe(Schema.brand("LLM.ModelID"));
|
|
14
|
+
var ProviderID = Schema.String.pipe(Schema.brand("LLM.ProviderID"));
|
|
15
|
+
var ResponseID = Schema.String;
|
|
16
|
+
var ContentBlockID = Schema.String;
|
|
17
|
+
var ToolCallID = Schema.String;
|
|
18
|
+
var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
19
|
+
var ReasoningEffort = Schema.Literals(ReasoningEfforts);
|
|
20
|
+
var TextVerbosity = Schema.Literals(["low", "medium", "high"]);
|
|
21
|
+
var MessageRole = Schema.Literals(["user", "assistant", "tool"]);
|
|
22
|
+
var FinishReason = Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
|
|
23
|
+
var JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
|
|
24
|
+
var ProviderMetadata = Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown));
|
|
25
|
+
var isRecord = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
26
|
+
var mergeJsonRecords = (...items) => {
|
|
27
|
+
const defined = items.filter((item) => item !== void 0);
|
|
28
|
+
if (defined.length === 0) return void 0;
|
|
29
|
+
if (defined.length === 1 && Object.values(defined[0]).every((value2) => value2 !== void 0)) return defined[0];
|
|
30
|
+
const result = {};
|
|
31
|
+
for (const item of defined) {
|
|
32
|
+
for (const [key, value2] of Object.entries(item)) {
|
|
33
|
+
if (value2 === void 0) continue;
|
|
34
|
+
result[key] = isRecord(result[key]) && isRecord(value2) ? mergeJsonRecords(result[key], value2) : value2;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
38
|
+
};
|
|
39
|
+
var mergeStringRecords = (...items) => {
|
|
40
|
+
const defined = items.filter((item) => item !== void 0);
|
|
41
|
+
if (defined.length === 0) return void 0;
|
|
42
|
+
if (defined.length === 1) return defined[0];
|
|
43
|
+
const result = Object.fromEntries(
|
|
44
|
+
defined.flatMap(
|
|
45
|
+
(item) => Object.entries(item).filter((entry) => entry[1] !== void 0)
|
|
46
|
+
)
|
|
47
|
+
);
|
|
48
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
49
|
+
};
|
|
50
|
+
var ProviderOptions = Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown));
|
|
51
|
+
var mergeProviderOptions = (...items) => {
|
|
52
|
+
const result = {};
|
|
53
|
+
for (const item of items) {
|
|
54
|
+
if (!item) continue;
|
|
55
|
+
for (const [provider3, options2] of Object.entries(item)) {
|
|
56
|
+
const merged = mergeJsonRecords(result[provider3], options2);
|
|
57
|
+
if (merged) result[provider3] = merged;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
61
|
+
};
|
|
62
|
+
var HttpOptions = class extends Schema.Class("LLM.HttpOptions")({
|
|
63
|
+
body: Schema.optional(JsonSchema),
|
|
64
|
+
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
65
|
+
query: Schema.optional(Schema.Record(Schema.String, Schema.String))
|
|
66
|
+
}) {
|
|
67
|
+
};
|
|
68
|
+
((HttpOptions2) => {
|
|
69
|
+
HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
|
|
70
|
+
})(HttpOptions || (HttpOptions = {}));
|
|
71
|
+
var mergeHttpOptions = (...items) => {
|
|
72
|
+
const body = mergeJsonRecords(...items.map((item) => item?.body));
|
|
73
|
+
const headers2 = mergeStringRecords(...items.map((item) => item?.headers));
|
|
74
|
+
const query = mergeStringRecords(...items.map((item) => item?.query));
|
|
75
|
+
if (!body && !headers2 && !query) return void 0;
|
|
76
|
+
return new HttpOptions({ body, headers: headers2, query });
|
|
77
|
+
};
|
|
78
|
+
var GenerationOptions = class extends Schema.Class("LLM.GenerationOptions")({
|
|
79
|
+
maxTokens: Schema.optional(Schema.Number),
|
|
80
|
+
temperature: Schema.optional(Schema.Number),
|
|
81
|
+
topP: Schema.optional(Schema.Number),
|
|
82
|
+
topK: Schema.optional(Schema.Number),
|
|
83
|
+
frequencyPenalty: Schema.optional(Schema.Number),
|
|
84
|
+
presencePenalty: Schema.optional(Schema.Number),
|
|
85
|
+
seed: Schema.optional(Schema.Number),
|
|
86
|
+
stop: Schema.optional(Schema.Array(Schema.String))
|
|
87
|
+
}) {
|
|
88
|
+
};
|
|
89
|
+
((GenerationOptions2) => {
|
|
90
|
+
GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
|
|
91
|
+
})(GenerationOptions || (GenerationOptions = {}));
|
|
92
|
+
var latestGeneration = (items, key) => items.findLast((item) => item?.[key] !== void 0)?.[key];
|
|
93
|
+
var mergeGenerationOptions = (...items) => {
|
|
94
|
+
const result = new GenerationOptions({
|
|
95
|
+
maxTokens: latestGeneration(items, "maxTokens"),
|
|
96
|
+
temperature: latestGeneration(items, "temperature"),
|
|
97
|
+
topP: latestGeneration(items, "topP"),
|
|
98
|
+
topK: latestGeneration(items, "topK"),
|
|
99
|
+
frequencyPenalty: latestGeneration(items, "frequencyPenalty"),
|
|
100
|
+
presencePenalty: latestGeneration(items, "presencePenalty"),
|
|
101
|
+
seed: latestGeneration(items, "seed"),
|
|
102
|
+
stop: latestGeneration(items, "stop")
|
|
103
|
+
});
|
|
104
|
+
return Object.values(result).some((value2) => value2 !== void 0) ? result : void 0;
|
|
105
|
+
};
|
|
106
|
+
var ModelLimits = class extends Schema.Class("LLM.ModelLimits")({
|
|
107
|
+
context: Schema.optional(Schema.Number),
|
|
108
|
+
output: Schema.optional(Schema.Number)
|
|
109
|
+
}) {
|
|
110
|
+
};
|
|
111
|
+
((ModelLimits2) => {
|
|
112
|
+
ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
|
|
113
|
+
})(ModelLimits || (ModelLimits = {}));
|
|
114
|
+
var ModelRef = class extends Schema.Class("LLM.ModelRef")({
|
|
115
|
+
id: ModelID,
|
|
116
|
+
provider: ProviderID,
|
|
117
|
+
route: RouteID,
|
|
118
|
+
baseURL: Schema.String,
|
|
119
|
+
/** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
|
|
120
|
+
apiKey: Schema.optional(Schema.String),
|
|
121
|
+
/** Optional transport auth policy. Opaque because it may contain functions. */
|
|
122
|
+
auth: Schema.optional(Schema.Any),
|
|
123
|
+
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
124
|
+
/**
|
|
125
|
+
* Query params appended to the request URL by `Endpoint.baseURL`. Used for
|
|
126
|
+
* deployment-level URL-scoped settings such as Azure's `api-version` or any
|
|
127
|
+
* provider that requires a per-request key in the URL. Generic concern, so
|
|
128
|
+
* lives as a typed first-class field instead of `native`.
|
|
129
|
+
*/
|
|
130
|
+
queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
131
|
+
limits: ModelLimits,
|
|
132
|
+
/** Provider-neutral generation defaults. Request-level values override them. */
|
|
133
|
+
generation: Schema.optional(GenerationOptions),
|
|
134
|
+
/** Provider-owned typed-at-the-facade options for non-portable knobs. */
|
|
135
|
+
providerOptions: Schema.optional(ProviderOptions),
|
|
136
|
+
/** Serializable raw HTTP overlays applied to the final outgoing request. */
|
|
137
|
+
http: Schema.optional(HttpOptions),
|
|
138
|
+
/**
|
|
139
|
+
* Provider-specific opaque options. Reach for this only when the value is
|
|
140
|
+
* genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
|
|
141
|
+
* `aws_credentials` / `aws_region` for SigV4). Anything used by more than
|
|
142
|
+
* one route should grow into a typed field instead.
|
|
143
|
+
*/
|
|
144
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
145
|
+
}) {
|
|
146
|
+
};
|
|
147
|
+
((ModelRef2) => {
|
|
148
|
+
ModelRef2.input = (model7) => ({
|
|
149
|
+
id: model7.id,
|
|
150
|
+
provider: model7.provider,
|
|
151
|
+
route: model7.route,
|
|
152
|
+
baseURL: model7.baseURL,
|
|
153
|
+
apiKey: model7.apiKey,
|
|
154
|
+
auth: model7.auth,
|
|
155
|
+
headers: model7.headers,
|
|
156
|
+
queryParams: model7.queryParams,
|
|
157
|
+
limits: model7.limits,
|
|
158
|
+
generation: model7.generation,
|
|
159
|
+
providerOptions: model7.providerOptions,
|
|
160
|
+
http: model7.http,
|
|
161
|
+
native: model7.native
|
|
162
|
+
});
|
|
163
|
+
ModelRef2.update = (model7, patch) => {
|
|
164
|
+
if (Object.keys(patch).length === 0) return model7;
|
|
165
|
+
return new ModelRef2({
|
|
166
|
+
...(0, ModelRef2.input)(model7),
|
|
167
|
+
...patch
|
|
168
|
+
});
|
|
169
|
+
};
|
|
170
|
+
})(ModelRef || (ModelRef = {}));
|
|
171
|
+
var CacheHint = class extends Schema.Class("LLM.CacheHint")({
|
|
172
|
+
type: Schema.Literals(["ephemeral", "persistent"]),
|
|
173
|
+
ttlSeconds: Schema.optional(Schema.Number)
|
|
174
|
+
}) {
|
|
175
|
+
};
|
|
176
|
+
var CachePolicyObject = Schema.Struct({
|
|
177
|
+
tools: Schema.optional(Schema.Boolean),
|
|
178
|
+
system: Schema.optional(Schema.Boolean),
|
|
179
|
+
messages: Schema.optional(
|
|
180
|
+
Schema.Union([
|
|
181
|
+
Schema.Literal("latest-user-message"),
|
|
182
|
+
Schema.Literal("latest-assistant"),
|
|
183
|
+
Schema.Struct({ tail: Schema.Number })
|
|
184
|
+
])
|
|
185
|
+
),
|
|
186
|
+
ttlSeconds: Schema.optional(Schema.Number)
|
|
187
|
+
});
|
|
188
|
+
var CachePolicy = Schema.Union([Schema.Literal("auto"), Schema.Literal("none"), CachePolicyObject]);
|
|
189
|
+
var isRecord2 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
190
|
+
var systemPartSchema = Schema.Struct({
|
|
191
|
+
type: Schema.Literal("text"),
|
|
192
|
+
text: Schema.String,
|
|
193
|
+
cache: Schema.optional(CacheHint),
|
|
194
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
195
|
+
}).annotate({ identifier: "LLM.SystemPart" });
|
|
196
|
+
var makeSystemPart = (text2) => ({ type: "text", text: text2 });
|
|
197
|
+
var SystemPart = Object.assign(systemPartSchema, {
|
|
198
|
+
make: makeSystemPart,
|
|
199
|
+
content: (input) => {
|
|
200
|
+
if (input === void 0) return [];
|
|
201
|
+
return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
|
|
202
|
+
}
|
|
203
|
+
});
|
|
204
|
+
var TextPart = Schema.Struct({
|
|
205
|
+
type: Schema.Literal("text"),
|
|
206
|
+
text: Schema.String,
|
|
207
|
+
cache: Schema.optional(CacheHint),
|
|
208
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
209
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
210
|
+
}).annotate({ identifier: "LLM.Content.Text" });
|
|
211
|
+
var MediaPart = Schema.Struct({
|
|
212
|
+
type: Schema.Literal("media"),
|
|
213
|
+
mediaType: Schema.String,
|
|
214
|
+
data: Schema.Union([Schema.String, Schema.Uint8Array]),
|
|
215
|
+
filename: Schema.optional(Schema.String),
|
|
216
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
217
|
+
}).annotate({ identifier: "LLM.Content.Media" });
|
|
218
|
+
var isToolResultValue = (value2) => isRecord2(value2) && (value2.type === "text" || value2.type === "json" || value2.type === "error") && "value" in value2;
|
|
219
|
+
var ToolResultValue = Object.assign(
|
|
220
|
+
Schema.Struct({
|
|
221
|
+
type: Schema.Literals(["json", "text", "error"]),
|
|
222
|
+
value: Schema.Unknown,
|
|
223
|
+
/** Optional structured payload (e.g. tool-interrupt metadata). */
|
|
224
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
225
|
+
}).annotate({ identifier: "LLM.ToolResult" }),
|
|
226
|
+
{
|
|
227
|
+
make: (value2, type = "json", metadata) => {
|
|
228
|
+
if (isToolResultValue(value2)) {
|
|
229
|
+
return metadata ? { ...value2, metadata: { ...value2.metadata ?? {}, ...metadata } } : value2;
|
|
230
|
+
}
|
|
231
|
+
return metadata ? { type, value: value2, metadata } : { type, value: value2 };
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
);
|
|
235
|
+
var ToolCallPart = Object.assign(
|
|
236
|
+
Schema.Struct({
|
|
237
|
+
type: Schema.Literal("tool-call"),
|
|
238
|
+
id: Schema.String,
|
|
239
|
+
name: Schema.String,
|
|
240
|
+
input: Schema.Unknown,
|
|
241
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
242
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
243
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
244
|
+
}).annotate({ identifier: "LLM.Content.ToolCall" }),
|
|
245
|
+
{
|
|
246
|
+
make: (input) => ({ type: "tool-call", ...input })
|
|
247
|
+
}
|
|
248
|
+
);
|
|
249
|
+
var ToolResultPart = Object.assign(
|
|
250
|
+
Schema.Struct({
|
|
251
|
+
type: Schema.Literal("tool-result"),
|
|
252
|
+
id: Schema.String,
|
|
253
|
+
name: Schema.String,
|
|
254
|
+
result: ToolResultValue,
|
|
255
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
256
|
+
cache: Schema.optional(CacheHint),
|
|
257
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
258
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
259
|
+
}).annotate({ identifier: "LLM.Content.ToolResult" }),
|
|
260
|
+
{
|
|
261
|
+
make: (input) => ({
|
|
262
|
+
type: "tool-result",
|
|
263
|
+
id: input.id,
|
|
264
|
+
name: input.name,
|
|
265
|
+
result: ToolResultValue.make(input.result, input.resultType),
|
|
266
|
+
providerExecuted: input.providerExecuted,
|
|
267
|
+
cache: input.cache,
|
|
268
|
+
metadata: input.metadata,
|
|
269
|
+
providerMetadata: input.providerMetadata
|
|
270
|
+
})
|
|
271
|
+
}
|
|
272
|
+
);
|
|
273
|
+
var ReasoningPart = Schema.Struct({
|
|
274
|
+
type: Schema.Literal("reasoning"),
|
|
275
|
+
text: Schema.String,
|
|
276
|
+
encrypted: Schema.optional(Schema.String),
|
|
277
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
278
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
279
|
+
}).annotate({ identifier: "LLM.Content.Reasoning" });
|
|
280
|
+
var ContentPart = Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
|
|
281
|
+
Schema.toTaggedUnion("type")
|
|
282
|
+
);
|
|
283
|
+
var Message = class extends Schema.Class("LLM.Message")({
|
|
284
|
+
id: Schema.optional(Schema.String),
|
|
285
|
+
role: MessageRole,
|
|
286
|
+
content: Schema.Array(ContentPart),
|
|
287
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
288
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
289
|
+
}) {
|
|
290
|
+
};
|
|
291
|
+
((Message2) => {
|
|
292
|
+
Message2.text = (value2) => ({ type: "text", text: value2 });
|
|
293
|
+
Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
|
|
294
|
+
Message2.make = (input) => {
|
|
295
|
+
if (input instanceof Message2) return input;
|
|
296
|
+
return new Message2({ ...input, content: (0, Message2.content)(input.content) });
|
|
297
|
+
};
|
|
298
|
+
Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
|
|
299
|
+
Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
|
|
300
|
+
Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
|
|
301
|
+
})(Message || (Message = {}));
|
|
302
|
+
var ToolDefinition = class extends Schema.Class("LLM.ToolDefinition")({
|
|
303
|
+
name: Schema.String,
|
|
304
|
+
description: Schema.String,
|
|
305
|
+
inputSchema: JsonSchema,
|
|
306
|
+
cache: Schema.optional(CacheHint),
|
|
307
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
308
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
309
|
+
}) {
|
|
310
|
+
};
|
|
311
|
+
((ToolDefinition2) => {
|
|
312
|
+
ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
|
|
313
|
+
})(ToolDefinition || (ToolDefinition = {}));
|
|
314
|
+
var ToolChoice = class extends Schema.Class("LLM.ToolChoice")({
|
|
315
|
+
type: Schema.Literals(["auto", "none", "required", "tool"]),
|
|
316
|
+
name: Schema.optional(Schema.String)
|
|
317
|
+
}) {
|
|
318
|
+
};
|
|
319
|
+
((ToolChoice2) => {
|
|
320
|
+
const isMode = (value2) => value2 === "auto" || value2 === "none" || value2 === "required";
|
|
321
|
+
ToolChoice2.named = (value2) => new ToolChoice2({ type: "tool", name: value2 });
|
|
322
|
+
ToolChoice2.make = (input) => {
|
|
323
|
+
if (input instanceof ToolChoice2) return input;
|
|
324
|
+
if (input instanceof ToolDefinition) return (0, ToolChoice2.named)(input.name);
|
|
325
|
+
if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
|
|
326
|
+
return new ToolChoice2(input);
|
|
327
|
+
};
|
|
328
|
+
})(ToolChoice || (ToolChoice = {}));
|
|
329
|
+
var ResponseFormat = Schema.Union([
|
|
330
|
+
Schema.Struct({ type: Schema.Literal("text") }),
|
|
331
|
+
Schema.Struct({ type: Schema.Literal("json"), schema: JsonSchema }),
|
|
332
|
+
Schema.Struct({ type: Schema.Literal("tool"), tool: ToolDefinition })
|
|
333
|
+
]).pipe(Schema.toTaggedUnion("type"));
|
|
334
|
+
var LLMRequest = class extends Schema.Class("LLM.Request")({
|
|
335
|
+
id: Schema.optional(Schema.String),
|
|
336
|
+
model: ModelRef,
|
|
337
|
+
system: Schema.Array(SystemPart),
|
|
338
|
+
messages: Schema.Array(Message),
|
|
339
|
+
tools: Schema.Array(ToolDefinition),
|
|
340
|
+
toolChoice: Schema.optional(ToolChoice),
|
|
341
|
+
generation: Schema.optional(GenerationOptions),
|
|
342
|
+
providerOptions: Schema.optional(ProviderOptions),
|
|
343
|
+
http: Schema.optional(HttpOptions),
|
|
344
|
+
responseFormat: Schema.optional(ResponseFormat),
|
|
345
|
+
cache: Schema.optional(CachePolicy),
|
|
346
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
347
|
+
}) {
|
|
348
|
+
};
|
|
349
|
+
((LLMRequest2) => {
|
|
350
|
+
LLMRequest2.input = (request2) => ({
|
|
351
|
+
id: request2.id,
|
|
352
|
+
model: request2.model,
|
|
353
|
+
system: request2.system,
|
|
354
|
+
messages: request2.messages,
|
|
355
|
+
tools: request2.tools,
|
|
356
|
+
toolChoice: request2.toolChoice,
|
|
357
|
+
generation: request2.generation,
|
|
358
|
+
providerOptions: request2.providerOptions,
|
|
359
|
+
http: request2.http,
|
|
360
|
+
responseFormat: request2.responseFormat,
|
|
361
|
+
cache: request2.cache,
|
|
362
|
+
metadata: request2.metadata
|
|
363
|
+
});
|
|
364
|
+
LLMRequest2.update = (request2, patch) => {
|
|
365
|
+
if (Object.keys(patch).length === 0) return request2;
|
|
366
|
+
return new LLMRequest2({
|
|
367
|
+
...(0, LLMRequest2.input)(request2),
|
|
368
|
+
...patch,
|
|
369
|
+
model: patch.model ?? request2.model
|
|
370
|
+
});
|
|
371
|
+
};
|
|
372
|
+
})(LLMRequest || (LLMRequest = {}));
|
|
373
|
+
var Usage = class extends Schema.Class("LLM.Usage")({
|
|
374
|
+
inputTokens: Schema.optional(Schema.Number),
|
|
375
|
+
outputTokens: Schema.optional(Schema.Number),
|
|
376
|
+
nonCachedInputTokens: Schema.optional(Schema.Number),
|
|
377
|
+
cacheReadInputTokens: Schema.optional(Schema.Number),
|
|
378
|
+
cacheWriteInputTokens: Schema.optional(Schema.Number),
|
|
379
|
+
reasoningTokens: Schema.optional(Schema.Number),
|
|
380
|
+
totalTokens: Schema.optional(Schema.Number),
|
|
381
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
382
|
+
}) {
|
|
383
|
+
/**
|
|
384
|
+
* Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
|
|
385
|
+
* to zero. The one place subtraction happens in this contract; the clamp
|
|
386
|
+
* means a provider reporting `reasoningTokens > outputTokens` produces a
|
|
387
|
+
* harmless zero rather than a negative that crashes downstream schemas.
|
|
388
|
+
*/
|
|
389
|
+
get visibleOutputTokens() {
|
|
390
|
+
return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
|
|
391
|
+
}
|
|
392
|
+
};
|
|
393
|
+
var RequestStart = Schema.Struct({
|
|
394
|
+
type: Schema.tag("request-start"),
|
|
395
|
+
id: ResponseID,
|
|
396
|
+
model: ModelRef
|
|
397
|
+
}).annotate({ identifier: "LLM.Event.RequestStart" });
|
|
398
|
+
var StepStart = Schema.Struct({
|
|
399
|
+
type: Schema.tag("step-start"),
|
|
400
|
+
index: Schema.Number
|
|
401
|
+
}).annotate({ identifier: "LLM.Event.StepStart" });
|
|
402
|
+
var TextStart = Schema.Struct({
|
|
403
|
+
type: Schema.tag("text-start"),
|
|
404
|
+
id: ContentBlockID,
|
|
405
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
406
|
+
}).annotate({ identifier: "LLM.Event.TextStart" });
|
|
407
|
+
var TextDelta = Schema.Struct({
|
|
408
|
+
type: Schema.tag("text-delta"),
|
|
409
|
+
id: ContentBlockID,
|
|
410
|
+
text: Schema.String
|
|
411
|
+
}).annotate({ identifier: "LLM.Event.TextDelta" });
|
|
412
|
+
var TextEnd = Schema.Struct({
|
|
413
|
+
type: Schema.tag("text-end"),
|
|
414
|
+
id: ContentBlockID,
|
|
415
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
416
|
+
}).annotate({ identifier: "LLM.Event.TextEnd" });
|
|
417
|
+
var ReasoningStart = Schema.Struct({
|
|
418
|
+
type: Schema.tag("reasoning-start"),
|
|
419
|
+
id: ContentBlockID,
|
|
420
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
421
|
+
}).annotate({ identifier: "LLM.Event.ReasoningStart" });
|
|
422
|
+
var ReasoningDelta = Schema.Struct({
|
|
423
|
+
type: Schema.tag("reasoning-delta"),
|
|
424
|
+
id: ContentBlockID,
|
|
425
|
+
text: Schema.String
|
|
426
|
+
}).annotate({ identifier: "LLM.Event.ReasoningDelta" });
|
|
427
|
+
var ReasoningEnd = Schema.Struct({
|
|
428
|
+
type: Schema.tag("reasoning-end"),
|
|
429
|
+
id: ContentBlockID,
|
|
430
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
431
|
+
}).annotate({ identifier: "LLM.Event.ReasoningEnd" });
|
|
432
|
+
var ToolInputStart = Schema.Struct({
|
|
433
|
+
type: Schema.tag("tool-input-start"),
|
|
434
|
+
id: ToolCallID,
|
|
435
|
+
name: Schema.String,
|
|
436
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
437
|
+
}).annotate({ identifier: "LLM.Event.ToolInputStart" });
|
|
438
|
+
var ToolInputDelta = Schema.Struct({
|
|
439
|
+
type: Schema.tag("tool-input-delta"),
|
|
440
|
+
id: ToolCallID,
|
|
441
|
+
name: Schema.String,
|
|
442
|
+
text: Schema.String
|
|
443
|
+
}).annotate({ identifier: "LLM.Event.ToolInputDelta" });
|
|
444
|
+
var ToolInputEnd = Schema.Struct({
|
|
445
|
+
type: Schema.tag("tool-input-end"),
|
|
446
|
+
id: ToolCallID,
|
|
447
|
+
name: Schema.String,
|
|
448
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
449
|
+
}).annotate({ identifier: "LLM.Event.ToolInputEnd" });
|
|
450
|
+
var ToolCall = Schema.Struct({
|
|
451
|
+
type: Schema.tag("tool-call"),
|
|
452
|
+
id: ToolCallID,
|
|
453
|
+
name: Schema.String,
|
|
454
|
+
input: Schema.Unknown,
|
|
455
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
456
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
457
|
+
}).annotate({ identifier: "LLM.Event.ToolCall" });
|
|
458
|
+
var ToolResult = Schema.Struct({
|
|
459
|
+
type: Schema.tag("tool-result"),
|
|
460
|
+
id: ToolCallID,
|
|
461
|
+
name: Schema.String,
|
|
462
|
+
result: ToolResultValue,
|
|
463
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
464
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
465
|
+
}).annotate({ identifier: "LLM.Event.ToolResult" });
|
|
466
|
+
var ToolError = Schema.Struct({
|
|
467
|
+
type: Schema.tag("tool-error"),
|
|
468
|
+
id: ToolCallID,
|
|
469
|
+
name: Schema.String,
|
|
470
|
+
message: Schema.String,
|
|
471
|
+
/** Optional structured payload (e.g. tool-interrupt metadata for approval). */
|
|
472
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
473
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
474
|
+
}).annotate({ identifier: "LLM.Event.ToolError" });
|
|
475
|
+
var StepFinish = Schema.Struct({
|
|
476
|
+
type: Schema.tag("step-finish"),
|
|
477
|
+
index: Schema.Number,
|
|
478
|
+
reason: FinishReason,
|
|
479
|
+
usage: Schema.optional(Usage),
|
|
480
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
481
|
+
}).annotate({ identifier: "LLM.Event.StepFinish" });
|
|
482
|
+
var RequestFinish = Schema.Struct({
|
|
483
|
+
type: Schema.tag("request-finish"),
|
|
484
|
+
reason: FinishReason,
|
|
485
|
+
usage: Schema.optional(Usage),
|
|
486
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
487
|
+
}).annotate({ identifier: "LLM.Event.RequestFinish" });
|
|
488
|
+
var ProviderErrorEvent = Schema.Struct({
|
|
489
|
+
type: Schema.tag("provider-error"),
|
|
490
|
+
message: Schema.String,
|
|
491
|
+
retryable: Schema.optional(Schema.Boolean),
|
|
492
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
493
|
+
}).annotate({ identifier: "LLM.Event.ProviderError" });
|
|
494
|
+
var llmEventTagged = Schema.Union([
|
|
495
|
+
RequestStart,
|
|
496
|
+
StepStart,
|
|
497
|
+
TextStart,
|
|
498
|
+
TextDelta,
|
|
499
|
+
TextEnd,
|
|
500
|
+
ReasoningStart,
|
|
501
|
+
ReasoningDelta,
|
|
502
|
+
ReasoningEnd,
|
|
503
|
+
ToolInputStart,
|
|
504
|
+
ToolInputDelta,
|
|
505
|
+
ToolInputEnd,
|
|
506
|
+
ToolCall,
|
|
507
|
+
ToolResult,
|
|
508
|
+
ToolError,
|
|
509
|
+
StepFinish,
|
|
510
|
+
RequestFinish,
|
|
511
|
+
ProviderErrorEvent
|
|
512
|
+
]).pipe(Schema.toTaggedUnion("type"));
|
|
513
|
+
var responseID = (value2) => ResponseID.make(value2);
|
|
514
|
+
var contentBlockID = (value2) => ContentBlockID.make(value2);
|
|
515
|
+
var toolCallID = (value2) => ToolCallID.make(value2);
|
|
516
|
+
var LLMEvent = Object.assign(llmEventTagged, {
|
|
517
|
+
requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
|
|
518
|
+
stepStart: StepStart.make,
|
|
519
|
+
textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
520
|
+
textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
521
|
+
textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
522
|
+
reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
523
|
+
reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
524
|
+
reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
525
|
+
toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
|
|
526
|
+
toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
|
|
527
|
+
toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
|
|
528
|
+
toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
|
|
529
|
+
toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
|
|
530
|
+
toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
|
|
531
|
+
stepFinish: StepFinish.make,
|
|
532
|
+
requestFinish: RequestFinish.make,
|
|
533
|
+
providerError: ProviderErrorEvent.make,
|
|
534
|
+
is: {
|
|
535
|
+
requestStart: llmEventTagged.guards["request-start"],
|
|
536
|
+
stepStart: llmEventTagged.guards["step-start"],
|
|
537
|
+
textStart: llmEventTagged.guards["text-start"],
|
|
538
|
+
textDelta: llmEventTagged.guards["text-delta"],
|
|
539
|
+
textEnd: llmEventTagged.guards["text-end"],
|
|
540
|
+
reasoningStart: llmEventTagged.guards["reasoning-start"],
|
|
541
|
+
reasoningDelta: llmEventTagged.guards["reasoning-delta"],
|
|
542
|
+
reasoningEnd: llmEventTagged.guards["reasoning-end"],
|
|
543
|
+
toolInputStart: llmEventTagged.guards["tool-input-start"],
|
|
544
|
+
toolInputDelta: llmEventTagged.guards["tool-input-delta"],
|
|
545
|
+
toolInputEnd: llmEventTagged.guards["tool-input-end"],
|
|
546
|
+
toolCall: llmEventTagged.guards["tool-call"],
|
|
547
|
+
toolResult: llmEventTagged.guards["tool-result"],
|
|
548
|
+
toolError: llmEventTagged.guards["tool-error"],
|
|
549
|
+
stepFinish: llmEventTagged.guards["step-finish"],
|
|
550
|
+
requestFinish: llmEventTagged.guards["request-finish"],
|
|
551
|
+
providerError: llmEventTagged.guards["provider-error"]
|
|
552
|
+
}
|
|
553
|
+
});
|
|
554
|
+
var PreparedRequest = class extends Schema.Class("LLM.PreparedRequest")({
|
|
555
|
+
id: Schema.String,
|
|
556
|
+
route: RouteID,
|
|
557
|
+
protocol: ProtocolID,
|
|
558
|
+
model: ModelRef,
|
|
559
|
+
body: Schema.Unknown,
|
|
560
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
561
|
+
}) {
|
|
562
|
+
};
|
|
563
|
+
var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
|
|
564
|
+
var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
|
|
565
|
+
var responseUsage = (events) => events.reduce(
|
|
566
|
+
(usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
|
|
567
|
+
void 0
|
|
568
|
+
);
|
|
569
|
+
var LLMResponse = class extends Schema.Class("LLM.Response")({
|
|
570
|
+
events: Schema.Array(LLMEvent),
|
|
571
|
+
usage: Schema.optional(Usage)
|
|
572
|
+
}) {
|
|
573
|
+
/** Concatenated assistant text assembled from streamed `text-delta` events. */
|
|
574
|
+
get text() {
|
|
575
|
+
return responseText(this.events);
|
|
576
|
+
}
|
|
577
|
+
/** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
|
|
578
|
+
get reasoning() {
|
|
579
|
+
return responseReasoning(this.events);
|
|
580
|
+
}
|
|
581
|
+
/** Completed tool calls emitted by the provider. */
|
|
582
|
+
get toolCalls() {
|
|
583
|
+
return this.events.filter(LLMEvent.is.toolCall);
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
((LLMResponse3) => {
|
|
587
|
+
LLMResponse3.text = (response) => responseText(response.events);
|
|
588
|
+
LLMResponse3.usage = (response) => response.usage ?? responseUsage(response.events);
|
|
589
|
+
LLMResponse3.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
|
|
590
|
+
LLMResponse3.reasoning = (response) => responseReasoning(response.events);
|
|
591
|
+
})(LLMResponse || (LLMResponse = {}));
|
|
592
|
+
var HttpRequestDetails = class extends Schema.Class("LLM.HttpRequestDetails")({
|
|
593
|
+
method: Schema.String,
|
|
594
|
+
url: Schema.String,
|
|
595
|
+
headers: Schema.Record(Schema.String, Schema.String)
|
|
596
|
+
}) {
|
|
597
|
+
};
|
|
598
|
+
var HttpResponseDetails = class extends Schema.Class("LLM.HttpResponseDetails")({
|
|
599
|
+
status: Schema.Number,
|
|
600
|
+
headers: Schema.Record(Schema.String, Schema.String)
|
|
601
|
+
}) {
|
|
602
|
+
};
|
|
603
|
+
var HttpRateLimitDetails = class extends Schema.Class("LLM.HttpRateLimitDetails")({
|
|
604
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
605
|
+
limit: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
606
|
+
remaining: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
607
|
+
reset: Schema.optional(Schema.Record(Schema.String, Schema.String))
|
|
608
|
+
}) {
|
|
609
|
+
};
|
|
610
|
+
var HttpContext = class extends Schema.Class("LLM.HttpContext")({
|
|
611
|
+
request: HttpRequestDetails,
|
|
612
|
+
response: Schema.optional(HttpResponseDetails),
|
|
613
|
+
body: Schema.optional(Schema.String),
|
|
614
|
+
bodyTruncated: Schema.optional(Schema.Boolean),
|
|
615
|
+
requestId: Schema.optional(Schema.String),
|
|
616
|
+
rateLimit: Schema.optional(HttpRateLimitDetails)
|
|
617
|
+
}) {
|
|
618
|
+
};
|
|
619
|
+
var InvalidRequestReason = class extends Schema.Class("LLM.Error.InvalidRequest")({
|
|
620
|
+
_tag: Schema.tag("InvalidRequest"),
|
|
621
|
+
message: Schema.String,
|
|
622
|
+
parameter: Schema.optional(Schema.String),
|
|
623
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
624
|
+
http: Schema.optional(HttpContext)
|
|
625
|
+
}) {
|
|
626
|
+
get retryable() {
|
|
627
|
+
return false;
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
var ContextOverflowReason = class extends Schema.Class("LLM.Error.ContextOverflow")({
|
|
631
|
+
_tag: Schema.tag("ContextOverflow"),
|
|
632
|
+
message: Schema.String,
|
|
633
|
+
/** Provider-reported prompt token count when present in the error body. */
|
|
634
|
+
promptTokens: Schema.optional(Schema.Number),
|
|
635
|
+
/** Provider-reported context window size when present in the error body. */
|
|
636
|
+
contextWindow: Schema.optional(Schema.Number),
|
|
637
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
638
|
+
http: Schema.optional(HttpContext)
|
|
639
|
+
}) {
|
|
640
|
+
get retryable() {
|
|
641
|
+
return false;
|
|
642
|
+
}
|
|
643
|
+
};
|
|
644
|
+
var NoRouteReason = class extends Schema.Class("LLM.Error.NoRoute")({
|
|
645
|
+
_tag: Schema.tag("NoRoute"),
|
|
646
|
+
route: RouteID,
|
|
647
|
+
provider: ProviderID,
|
|
648
|
+
model: ModelID
|
|
649
|
+
}) {
|
|
650
|
+
get retryable() {
|
|
651
|
+
return false;
|
|
652
|
+
}
|
|
653
|
+
get message() {
|
|
654
|
+
return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
|
|
655
|
+
}
|
|
656
|
+
};
|
|
657
|
+
var AuthenticationReason = class extends Schema.Class("LLM.Error.Authentication")({
|
|
658
|
+
_tag: Schema.tag("Authentication"),
|
|
659
|
+
message: Schema.String,
|
|
660
|
+
kind: Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
|
|
661
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
662
|
+
http: Schema.optional(HttpContext)
|
|
663
|
+
}) {
|
|
664
|
+
get retryable() {
|
|
665
|
+
return false;
|
|
666
|
+
}
|
|
667
|
+
};
|
|
668
|
+
var RateLimitReason = class extends Schema.Class("LLM.Error.RateLimit")({
|
|
669
|
+
_tag: Schema.tag("RateLimit"),
|
|
670
|
+
message: Schema.String,
|
|
671
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
672
|
+
rateLimit: Schema.optional(HttpRateLimitDetails),
|
|
673
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
674
|
+
http: Schema.optional(HttpContext)
|
|
675
|
+
}) {
|
|
676
|
+
get retryable() {
|
|
677
|
+
return true;
|
|
678
|
+
}
|
|
679
|
+
};
|
|
680
|
+
var QuotaExceededReason = class extends Schema.Class("LLM.Error.QuotaExceeded")({
|
|
681
|
+
_tag: Schema.tag("QuotaExceeded"),
|
|
682
|
+
message: Schema.String,
|
|
683
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
684
|
+
http: Schema.optional(HttpContext)
|
|
685
|
+
}) {
|
|
686
|
+
get retryable() {
|
|
687
|
+
return false;
|
|
688
|
+
}
|
|
689
|
+
};
|
|
690
|
+
var ContentPolicyReason = class extends Schema.Class("LLM.Error.ContentPolicy")({
|
|
691
|
+
_tag: Schema.tag("ContentPolicy"),
|
|
692
|
+
message: Schema.String,
|
|
693
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
694
|
+
http: Schema.optional(HttpContext)
|
|
695
|
+
}) {
|
|
696
|
+
get retryable() {
|
|
697
|
+
return false;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
var ProviderInternalReason = class extends Schema.Class("LLM.Error.ProviderInternal")({
|
|
701
|
+
_tag: Schema.tag("ProviderInternal"),
|
|
702
|
+
message: Schema.String,
|
|
703
|
+
status: Schema.Number,
|
|
704
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
705
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
706
|
+
http: Schema.optional(HttpContext)
|
|
707
|
+
}) {
|
|
708
|
+
get retryable() {
|
|
709
|
+
return true;
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
var TransportReason = class extends Schema.Class("LLM.Error.Transport")({
|
|
713
|
+
_tag: Schema.tag("Transport"),
|
|
714
|
+
message: Schema.String,
|
|
715
|
+
kind: Schema.optional(Schema.String),
|
|
716
|
+
url: Schema.optional(Schema.String),
|
|
717
|
+
http: Schema.optional(HttpContext)
|
|
718
|
+
}) {
|
|
719
|
+
get retryable() {
|
|
720
|
+
return false;
|
|
721
|
+
}
|
|
722
|
+
};
|
|
723
|
+
var InvalidProviderOutputReason = class extends Schema.Class(
|
|
724
|
+
"LLM.Error.InvalidProviderOutput"
|
|
725
|
+
)({
|
|
726
|
+
_tag: Schema.tag("InvalidProviderOutput"),
|
|
727
|
+
message: Schema.String,
|
|
728
|
+
route: Schema.optional(Schema.String),
|
|
729
|
+
raw: Schema.optional(Schema.String),
|
|
730
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
731
|
+
}) {
|
|
732
|
+
get retryable() {
|
|
733
|
+
return false;
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
var UnknownProviderReason = class extends Schema.Class("LLM.Error.UnknownProvider")({
|
|
737
|
+
_tag: Schema.tag("UnknownProvider"),
|
|
738
|
+
message: Schema.String,
|
|
739
|
+
status: Schema.optional(Schema.Number),
|
|
740
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
741
|
+
http: Schema.optional(HttpContext)
|
|
742
|
+
}) {
|
|
743
|
+
get retryable() {
|
|
744
|
+
return false;
|
|
745
|
+
}
|
|
746
|
+
};
|
|
747
|
+
var LLMErrorReason = Schema.Union([
|
|
748
|
+
InvalidRequestReason,
|
|
749
|
+
ContextOverflowReason,
|
|
750
|
+
NoRouteReason,
|
|
751
|
+
AuthenticationReason,
|
|
752
|
+
RateLimitReason,
|
|
753
|
+
QuotaExceededReason,
|
|
754
|
+
ContentPolicyReason,
|
|
755
|
+
ProviderInternalReason,
|
|
756
|
+
TransportReason,
|
|
757
|
+
InvalidProviderOutputReason,
|
|
758
|
+
UnknownProviderReason
|
|
759
|
+
]).pipe(Schema.toTaggedUnion("_tag"));
|
|
760
|
+
var LLMError = class extends Schema.TaggedErrorClass()("LLM.Error", {
|
|
761
|
+
module: Schema.String,
|
|
762
|
+
method: Schema.String,
|
|
763
|
+
reason: LLMErrorReason
|
|
764
|
+
}) {
|
|
765
|
+
cause = this.reason;
|
|
766
|
+
get retryable() {
|
|
767
|
+
return this.reason.retryable;
|
|
768
|
+
}
|
|
769
|
+
get retryAfterMs() {
|
|
770
|
+
return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
|
|
771
|
+
}
|
|
772
|
+
get message() {
|
|
773
|
+
return `${this.module}.${this.method}: ${this.reason.message}`;
|
|
774
|
+
}
|
|
775
|
+
};
|
|
776
|
+
var ToolFailure = class extends Schema.TaggedErrorClass()("LLM.ToolFailure", {
|
|
777
|
+
message: Schema.String,
|
|
778
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
779
|
+
}) {
|
|
780
|
+
};
|
|
781
|
+
|
|
782
|
+
// src/tool.ts
|
|
783
|
+
var tool_exports = {};
|
|
784
|
+
__export(tool_exports, {
|
|
785
|
+
Tool: () => tool_exports,
|
|
786
|
+
ToolFailure: () => ToolFailure,
|
|
787
|
+
make: () => make,
|
|
788
|
+
toDefinitions: () => toDefinitions,
|
|
789
|
+
tool: () => tool
|
|
790
|
+
});
|
|
791
|
+
function make(config2) {
|
|
792
|
+
if ("jsonSchema" in config2) {
|
|
793
|
+
return {
|
|
794
|
+
description: config2.description,
|
|
795
|
+
parameters: Schema.Unknown,
|
|
796
|
+
success: Schema.Unknown,
|
|
797
|
+
execute: config2.execute,
|
|
798
|
+
_decode: Effect.succeed,
|
|
799
|
+
_encode: Effect.succeed,
|
|
800
|
+
_definition: new ToolDefinition({
|
|
801
|
+
name: "",
|
|
802
|
+
description: config2.description,
|
|
803
|
+
inputSchema: config2.jsonSchema
|
|
804
|
+
})
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
return {
|
|
808
|
+
description: config2.description,
|
|
809
|
+
parameters: config2.parameters,
|
|
810
|
+
success: config2.success,
|
|
811
|
+
execute: config2.execute,
|
|
812
|
+
_decode: Schema.decodeUnknownEffect(config2.parameters),
|
|
813
|
+
_encode: Schema.encodeEffect(config2.success),
|
|
814
|
+
_definition: new ToolDefinition({
|
|
815
|
+
name: "",
|
|
816
|
+
description: config2.description,
|
|
817
|
+
inputSchema: toJsonSchema(config2.parameters)
|
|
818
|
+
})
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
var tool = make;
|
|
822
|
+
var toDefinitions = (tools) => Object.entries(tools).map(
|
|
823
|
+
([name, item]) => new ToolDefinition({
|
|
824
|
+
name,
|
|
825
|
+
description: item._definition.description,
|
|
826
|
+
inputSchema: item._definition.inputSchema
|
|
827
|
+
})
|
|
828
|
+
);
|
|
829
|
+
var toJsonSchema = (schema) => {
|
|
830
|
+
const document = Schema.toJsonSchemaDocument(schema);
|
|
831
|
+
const base = Object.keys(document.definitions).length === 0 ? document.schema : { ...document.schema, $defs: document.definitions };
|
|
832
|
+
return normalizeTopLevel(base);
|
|
833
|
+
};
|
|
834
|
+
var normalizeTopLevel = (s) => {
|
|
835
|
+
if (!s || typeof s !== "object") {
|
|
836
|
+
return { type: "object", properties: {}, additionalProperties: false };
|
|
837
|
+
}
|
|
838
|
+
const obj = s;
|
|
839
|
+
if (obj.type === "object") return s;
|
|
840
|
+
if (Array.isArray(obj.anyOf)) {
|
|
841
|
+
const objectVariant = obj.anyOf.find(
|
|
842
|
+
(v) => v != null && typeof v === "object" && v.type === "object"
|
|
843
|
+
);
|
|
844
|
+
if (objectVariant) {
|
|
845
|
+
const { anyOf: _omit, ...rest } = obj;
|
|
846
|
+
return { ...rest, ...objectVariant };
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
return { type: "object", properties: {}, additionalProperties: false };
|
|
850
|
+
};
|
|
851
|
+
var hasToolCall = (name) => (state) => state.toolCalls.some((call) => call.name === name);
|
|
852
|
+
var stopWhenAny = (...conditions) => (state) => conditions.some((condition) => condition(state));
|
|
853
|
+
var stepCountIs = (count) => (state) => state.step + 1 >= count;
|
|
854
|
+
var stream = (options2) => {
|
|
855
|
+
const concurrency = options2.concurrency ?? 10;
|
|
856
|
+
const tools = options2.tools;
|
|
857
|
+
const runtimeTools = toDefinitions(tools);
|
|
858
|
+
const runtimeToolNames = new Set(runtimeTools.map((tool2) => tool2.name));
|
|
859
|
+
const initialRequest = runtimeTools.length === 0 ? options2.request : LLMRequest.update(options2.request, {
|
|
860
|
+
tools: [...options2.request.tools.filter((tool2) => !runtimeToolNames.has(tool2.name)), ...runtimeTools]
|
|
861
|
+
});
|
|
862
|
+
const loop = (request2, step2) => Stream.unwrap(
|
|
863
|
+
Effect.gen(function* () {
|
|
864
|
+
const state = { assistantContent: [], toolCalls: [], finishReason: void 0 };
|
|
865
|
+
const modelStream = options2.stream(request2).pipe(Stream.tap((event) => Effect.sync(() => accumulate(state, event))));
|
|
866
|
+
const continuation = Stream.unwrap(
|
|
867
|
+
Effect.gen(function* () {
|
|
868
|
+
if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return Stream.empty;
|
|
869
|
+
if (options2.toolExecution === "none") return Stream.empty;
|
|
870
|
+
const dispatched = yield* Effect.forEach(
|
|
871
|
+
state.toolCalls,
|
|
872
|
+
(call) => dispatch(tools, call).pipe(Effect.map((result) => [call, result])),
|
|
873
|
+
{ concurrency }
|
|
874
|
+
);
|
|
875
|
+
const resultStream = Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)));
|
|
876
|
+
if (dispatched.some(([, result]) => isInterruptResult(result))) return resultStream;
|
|
877
|
+
if (!options2.stopWhen) return resultStream;
|
|
878
|
+
if (options2.stopWhen({ step: step2, request: request2, toolCalls: state.toolCalls })) return resultStream;
|
|
879
|
+
const followUp = dispatched.filter(([, result]) => !isInterruptResult(result));
|
|
880
|
+
if (followUp.length === 0) return resultStream;
|
|
881
|
+
return resultStream.pipe(Stream.concat(loop(followUpRequest(request2, state, followUp), step2 + 1)));
|
|
882
|
+
})
|
|
883
|
+
);
|
|
884
|
+
return modelStream.pipe(Stream.concat(continuation));
|
|
885
|
+
})
|
|
886
|
+
);
|
|
887
|
+
return loop(initialRequest, 0);
|
|
888
|
+
};
|
|
889
|
+
var accumulate = (state, event) => {
|
|
890
|
+
if (event.type === "text-delta") {
|
|
891
|
+
appendStreamingText(state, "text", event.text, void 0);
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
894
|
+
if (event.type === "reasoning-delta") {
|
|
895
|
+
appendStreamingText(state, "reasoning", event.text, void 0);
|
|
896
|
+
return;
|
|
897
|
+
}
|
|
898
|
+
if (event.type === "reasoning-end") {
|
|
899
|
+
appendStreamingText(state, "reasoning", "", event.providerMetadata);
|
|
900
|
+
return;
|
|
901
|
+
}
|
|
902
|
+
if (event.type === "text-end") {
|
|
903
|
+
appendStreamingText(state, "text", "", event.providerMetadata);
|
|
904
|
+
return;
|
|
905
|
+
}
|
|
906
|
+
if (event.type === "tool-call") {
|
|
907
|
+
const part = ToolCallPart.make({
|
|
908
|
+
id: event.id,
|
|
909
|
+
name: event.name,
|
|
910
|
+
input: event.input,
|
|
911
|
+
providerExecuted: event.providerExecuted,
|
|
912
|
+
providerMetadata: event.providerMetadata
|
|
913
|
+
});
|
|
914
|
+
state.assistantContent.push(part);
|
|
915
|
+
if (!event.providerExecuted) state.toolCalls.push(part);
|
|
916
|
+
return;
|
|
917
|
+
}
|
|
918
|
+
if (event.type === "tool-result" && event.providerExecuted) {
|
|
919
|
+
state.assistantContent.push(
|
|
920
|
+
ToolResultPart.make({
|
|
921
|
+
id: event.id,
|
|
922
|
+
name: event.name,
|
|
923
|
+
result: event.result,
|
|
924
|
+
providerExecuted: true,
|
|
925
|
+
providerMetadata: event.providerMetadata
|
|
926
|
+
})
|
|
927
|
+
);
|
|
928
|
+
return;
|
|
929
|
+
}
|
|
930
|
+
if (event.type === "request-finish") {
|
|
931
|
+
state.finishReason = event.reason;
|
|
932
|
+
}
|
|
933
|
+
};
|
|
934
|
+
var sameProviderMetadata = (left, right) => left === right || JSON.stringify(left) === JSON.stringify(right);
|
|
935
|
+
var mergeProviderMetadata = (left, right) => {
|
|
936
|
+
if (!left) return right;
|
|
937
|
+
if (!right) return left;
|
|
938
|
+
return Object.fromEntries(
|
|
939
|
+
Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).map((provider3) => [
|
|
940
|
+
provider3,
|
|
941
|
+
{ ...left[provider3], ...right[provider3] }
|
|
942
|
+
])
|
|
943
|
+
);
|
|
944
|
+
};
|
|
945
|
+
var appendStreamingText = (state, type, text2, providerMetadata) => {
|
|
946
|
+
const last = state.assistantContent.at(-1);
|
|
947
|
+
if (last?.type === type && text2.length === 0) {
|
|
948
|
+
state.assistantContent[state.assistantContent.length - 1] = {
|
|
949
|
+
...last,
|
|
950
|
+
providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata)
|
|
951
|
+
};
|
|
952
|
+
return;
|
|
953
|
+
}
|
|
954
|
+
if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
|
|
955
|
+
state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text2}` };
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
state.assistantContent.push({ type, text: text2, providerMetadata });
|
|
959
|
+
};
|
|
960
|
+
var isInterruptResult = (result) => result.type === "error" && typeof result.metadata === "object" && result.metadata !== null && result.metadata.kind === "tool-interrupt";
|
|
961
|
+
var dispatch = (tools, call) => {
|
|
962
|
+
const tool2 = tools[call.name];
|
|
963
|
+
if (!tool2) return Effect.succeed({ type: "error", value: `Unknown tool: ${call.name}` });
|
|
964
|
+
if (!tool2.execute)
|
|
965
|
+
return Effect.succeed({ type: "error", value: `Tool has no execute handler: ${call.name}` });
|
|
966
|
+
return decodeAndExecute(tool2, call.input).pipe(
|
|
967
|
+
Effect.catchTag(
|
|
968
|
+
"LLM.ToolFailure",
|
|
969
|
+
(failure) => Effect.succeed({
|
|
970
|
+
type: "error",
|
|
971
|
+
value: failure.message,
|
|
972
|
+
...failure.metadata ? { metadata: failure.metadata } : {}
|
|
973
|
+
})
|
|
974
|
+
)
|
|
975
|
+
);
|
|
976
|
+
};
|
|
977
|
+
var decodeAndExecute = (tool2, input) => tool2._decode(input).pipe(
|
|
978
|
+
Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
|
|
979
|
+
Effect.flatMap((decoded) => tool2.execute(decoded)),
|
|
980
|
+
Effect.flatMap(
|
|
981
|
+
(value2) => tool2._encode(value2).pipe(
|
|
982
|
+
Effect.mapError(
|
|
983
|
+
(error) => new ToolFailure({
|
|
984
|
+
message: `Tool returned an invalid value for its success schema: ${error.message}`
|
|
985
|
+
})
|
|
986
|
+
)
|
|
987
|
+
)
|
|
988
|
+
),
|
|
989
|
+
Effect.map((encoded) => ({ type: "json", value: encoded }))
|
|
990
|
+
);
|
|
991
|
+
var emitEvents = (call, result) => {
|
|
992
|
+
if (result.type === "error") {
|
|
993
|
+
if (isInterruptResult(result)) {
|
|
994
|
+
return [
|
|
995
|
+
LLMEvent.toolError({
|
|
996
|
+
id: call.id,
|
|
997
|
+
name: call.name,
|
|
998
|
+
message: String(result.value),
|
|
999
|
+
metadata: result.metadata
|
|
1000
|
+
})
|
|
1001
|
+
];
|
|
1002
|
+
}
|
|
1003
|
+
return [
|
|
1004
|
+
LLMEvent.toolError({
|
|
1005
|
+
id: call.id,
|
|
1006
|
+
name: call.name,
|
|
1007
|
+
message: String(result.value),
|
|
1008
|
+
metadata: result.metadata
|
|
1009
|
+
}),
|
|
1010
|
+
LLMEvent.toolResult({ id: call.id, name: call.name, result })
|
|
1011
|
+
];
|
|
1012
|
+
}
|
|
1013
|
+
return [LLMEvent.toolResult({ id: call.id, name: call.name, result })];
|
|
1014
|
+
};
|
|
1015
|
+
var followUpRequest = (request2, state, dispatched) => LLMRequest.update(request2, {
|
|
1016
|
+
messages: [
|
|
1017
|
+
...request2.messages,
|
|
1018
|
+
Message.assistant(state.assistantContent),
|
|
1019
|
+
...dispatched.map(([call, result]) => Message.tool({ id: call.id, name: call.name, result }))
|
|
1020
|
+
]
|
|
1021
|
+
});
|
|
1022
|
+
var ToolRuntime = { stream, stepCountIs };
|
|
1023
|
+
|
|
1024
|
+
// src/route/protocol.ts
|
|
1025
|
+
var protocol_exports = {};
|
|
1026
|
+
__export(protocol_exports, {
|
|
1027
|
+
Protocol: () => protocol_exports,
|
|
1028
|
+
jsonEvent: () => jsonEvent,
|
|
1029
|
+
make: () => make2
|
|
1030
|
+
});
|
|
1031
|
+
var make2 = (input) => input;
|
|
1032
|
+
var jsonEvent = (schema) => Schema.fromJsonString(schema);
|
|
1033
|
+
|
|
1034
|
+
// src/route/endpoint.ts
|
|
1035
|
+
var endpoint_exports = {};
|
|
1036
|
+
__export(endpoint_exports, {
|
|
1037
|
+
Endpoint: () => endpoint_exports,
|
|
1038
|
+
path: () => path,
|
|
1039
|
+
render: () => render
|
|
1040
|
+
});
|
|
1041
|
+
|
|
1042
|
+
// src/protocols/shared.ts
|
|
1043
|
+
var shared_exports = {};
|
|
1044
|
+
__export(shared_exports, {
|
|
1045
|
+
Json: () => Json,
|
|
1046
|
+
JsonObject: () => JsonObject,
|
|
1047
|
+
ProviderShared: () => shared_exports,
|
|
1048
|
+
decodeJson: () => decodeJson,
|
|
1049
|
+
encodeJson: () => encodeJson,
|
|
1050
|
+
errorText: () => errorText,
|
|
1051
|
+
eventError: () => eventError,
|
|
1052
|
+
invalidRequest: () => invalidRequest,
|
|
1053
|
+
isRecord: () => isRecord3,
|
|
1054
|
+
joinText: () => joinText,
|
|
1055
|
+
jsonPost: () => jsonPost,
|
|
1056
|
+
matchToolChoice: () => matchToolChoice,
|
|
1057
|
+
mediaBytes: () => mediaBytes,
|
|
1058
|
+
optionalArray: () => optionalArray,
|
|
1059
|
+
optionalNull: () => optionalNull,
|
|
1060
|
+
parseJson: () => parseJson,
|
|
1061
|
+
parseToolInput: () => parseToolInput,
|
|
1062
|
+
sseFraming: () => sseFraming,
|
|
1063
|
+
subtractTokens: () => subtractTokens,
|
|
1064
|
+
sumTokens: () => sumTokens,
|
|
1065
|
+
supportsContent: () => supportsContent,
|
|
1066
|
+
toolResultText: () => toolResultText,
|
|
1067
|
+
totalTokens: () => totalTokens,
|
|
1068
|
+
trimBaseUrl: () => trimBaseUrl,
|
|
1069
|
+
unsupportedContent: () => unsupportedContent,
|
|
1070
|
+
validateWith: () => validateWith
|
|
1071
|
+
});
|
|
1072
|
+
var Json = Schema.fromJsonString(Schema.Unknown);
|
|
1073
|
+
var decodeJson = Schema.decodeUnknownSync(Json);
|
|
1074
|
+
var encodeJson = Schema.encodeSync(Json);
|
|
1075
|
+
var JsonObject = Schema.Record(Schema.String, Schema.Unknown);
|
|
1076
|
+
var optionalArray = (schema) => Schema.optional(Schema.Array(schema));
|
|
1077
|
+
var optionalNull = (schema) => Schema.optional(Schema.NullOr(schema));
|
|
1078
|
+
var isRecord3 = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2);
|
|
1079
|
+
var totalTokens = (inputTokens, outputTokens, total) => {
|
|
1080
|
+
if (total !== void 0) return total;
|
|
1081
|
+
if (inputTokens === void 0 && outputTokens === void 0) return void 0;
|
|
1082
|
+
return (inputTokens ?? 0) + (outputTokens ?? 0);
|
|
1083
|
+
};
|
|
1084
|
+
var subtractTokens = (total, subtrahend) => {
|
|
1085
|
+
if (total === void 0) return void 0;
|
|
1086
|
+
if (subtrahend === void 0) return total;
|
|
1087
|
+
return Math.max(0, total - subtrahend);
|
|
1088
|
+
};
|
|
1089
|
+
var sumTokens = (...values) => {
|
|
1090
|
+
if (values.every((value2) => value2 === void 0)) return void 0;
|
|
1091
|
+
return values.reduce((acc, value2) => acc + (value2 ?? 0), 0);
|
|
1092
|
+
};
|
|
1093
|
+
var eventError = (route3, message2, raw) => new LLMError({
|
|
1094
|
+
module: "ProviderShared",
|
|
1095
|
+
method: "stream",
|
|
1096
|
+
reason: new InvalidProviderOutputReason({ route: route3, message: message2, raw })
|
|
1097
|
+
});
|
|
1098
|
+
var parseJson = (route3, input, message2) => Effect.try({
|
|
1099
|
+
try: () => decodeJson(input),
|
|
1100
|
+
catch: () => eventError(route3, message2, input)
|
|
1101
|
+
});
|
|
1102
|
+
var joinText = (parts) => parts.map((part) => part.text).join("\n");
|
|
1103
|
+
var parseToolInput = (route3, name, raw) => parseJson(route3, raw || "{}", `Invalid JSON input for ${route3} tool call ${name}`);
|
|
1104
|
+
var mediaBytes = (part) => typeof part.data === "string" ? part.data : Buffer.from(part.data).toString("base64");
|
|
1105
|
+
var trimBaseUrl = (value2) => value2.replace(/\/+$/, "");
|
|
1106
|
+
var IMAGE_BASE64_FIELDS = /* @__PURE__ */ new Set(["imageBase64", "base64", "data"]);
|
|
1107
|
+
var isImageResult = (value2) => typeof value2 === "object" && value2 !== null && !Array.isArray(value2) && typeof value2.mimeType === "string" && value2.mimeType.startsWith("image/");
|
|
1108
|
+
var redactImagePayload = (value2) => {
|
|
1109
|
+
if (Array.isArray(value2)) return value2.map(redactImagePayload);
|
|
1110
|
+
if (!value2 || typeof value2 !== "object") return value2;
|
|
1111
|
+
if (isImageResult(value2)) {
|
|
1112
|
+
const out2 = {};
|
|
1113
|
+
for (const [k, v] of Object.entries(value2)) {
|
|
1114
|
+
if (IMAGE_BASE64_FIELDS.has(k) && typeof v === "string") {
|
|
1115
|
+
out2[k] = `<image elided; ${v.length} chars base64 already shown to user>`;
|
|
1116
|
+
continue;
|
|
1117
|
+
}
|
|
1118
|
+
out2[k] = v;
|
|
1119
|
+
}
|
|
1120
|
+
return out2;
|
|
1121
|
+
}
|
|
1122
|
+
const out = {};
|
|
1123
|
+
for (const [k, v] of Object.entries(value2)) out[k] = redactImagePayload(v);
|
|
1124
|
+
return out;
|
|
1125
|
+
};
|
|
1126
|
+
var toolResultText = (part) => {
|
|
1127
|
+
if (part.result.type === "text" || part.result.type === "error") return String(part.result.value);
|
|
1128
|
+
return encodeJson(redactImagePayload(part.result.value));
|
|
1129
|
+
};
|
|
1130
|
+
var errorText = (error) => {
|
|
1131
|
+
if (error instanceof Error) return error.message;
|
|
1132
|
+
if (typeof error === "string") return error;
|
|
1133
|
+
if (typeof error === "number" || typeof error === "boolean" || typeof error === "bigint") return String(error);
|
|
1134
|
+
if (error === null) return "null";
|
|
1135
|
+
if (error === void 0) return "undefined";
|
|
1136
|
+
return "Unknown stream error";
|
|
1137
|
+
};
|
|
1138
|
+
var sseFraming = (bytes) => bytes.pipe(
|
|
1139
|
+
Stream.decodeText(),
|
|
1140
|
+
Stream.pipeThroughChannel(Sse.decode()),
|
|
1141
|
+
Stream.catchTag("Retry", () => Stream.empty),
|
|
1142
|
+
Stream.filter((event) => event.data.length > 0 && event.data !== "[DONE]"),
|
|
1143
|
+
Stream.map((event) => event.data)
|
|
1144
|
+
);
|
|
1145
|
+
var invalidRequest = (message2) => new LLMError({
|
|
1146
|
+
module: "ProviderShared",
|
|
1147
|
+
method: "request",
|
|
1148
|
+
reason: new InvalidRequestReason({ message: message2 })
|
|
1149
|
+
});
|
|
1150
|
+
var matchToolChoice = (route3, toolChoice2, cases) => Effect.gen(function* () {
|
|
1151
|
+
if (toolChoice2.type === "auto") return cases.auto();
|
|
1152
|
+
if (toolChoice2.type === "none") return cases.none();
|
|
1153
|
+
if (toolChoice2.type === "required") return cases.required();
|
|
1154
|
+
if (!toolChoice2.name) return yield* invalidRequest(`${route3} tool choice requires a tool name`);
|
|
1155
|
+
return cases.tool(toolChoice2.name);
|
|
1156
|
+
});
|
|
1157
|
+
var formatContentTypes = (types) => {
|
|
1158
|
+
if (types.length <= 1) return types[0] ?? "";
|
|
1159
|
+
if (types.length === 2) return `${types[0]} and ${types[1]}`;
|
|
1160
|
+
return `${types.slice(0, -1).join(", ")}, and ${types.at(-1)}`;
|
|
1161
|
+
};
|
|
1162
|
+
var supportsContent = (part, types) => types.includes(part.type);
|
|
1163
|
+
var unsupportedContent = (route3, role, types) => invalidRequest(`${route3} ${role} messages only support ${formatContentTypes(types)} content for now`);
|
|
1164
|
+
var validateWith = (decode2) => (payload) => decode2(payload).pipe(Effect.mapError((error) => invalidRequest(error.message)));
|
|
1165
|
+
var jsonPost = (input) => HttpClientRequest.post(input.url).pipe(
|
|
1166
|
+
HttpClientRequest.setHeaders(Headers.set(Headers.fromInput(input.headers), "content-type", "application/json")),
|
|
1167
|
+
HttpClientRequest.bodyText(input.body, "application/json")
|
|
1168
|
+
);
|
|
1169
|
+
|
|
1170
|
+
// src/route/endpoint.ts
|
|
1171
|
+
var path = (value2) => ({ path: value2 });
|
|
1172
|
+
var renderPart = (part, input) => typeof part === "function" ? part(input) : part;
|
|
1173
|
+
var render = (endpoint, input) => {
|
|
1174
|
+
const url = new URL(`${trimBaseUrl(input.request.model.baseURL)}${renderPart(endpoint.path, input)}`);
|
|
1175
|
+
const params = input.request.model.queryParams;
|
|
1176
|
+
if (params) for (const [key, value2] of Object.entries(params)) url.searchParams.set(key, value2);
|
|
1177
|
+
return url;
|
|
1178
|
+
};
|
|
1179
|
+
|
|
1180
|
+
// src/route/framing.ts
|
|
1181
|
+
var framing_exports = {};
|
|
1182
|
+
__export(framing_exports, {
|
|
1183
|
+
Framing: () => framing_exports,
|
|
1184
|
+
sse: () => sse
|
|
1185
|
+
});
|
|
1186
|
+
var sse = { id: "sse", frame: sseFraming };
|
|
1187
|
+
|
|
1188
|
+
// src/route/auth.ts
|
|
1189
|
+
var auth_exports = {};
|
|
1190
|
+
__export(auth_exports, {
|
|
1191
|
+
Auth: () => auth_exports,
|
|
1192
|
+
MissingCredentialError: () => MissingCredentialError,
|
|
1193
|
+
apiKey: () => apiKey,
|
|
1194
|
+
apiKeyHeader: () => apiKeyHeader,
|
|
1195
|
+
bearer: () => bearer,
|
|
1196
|
+
bearerHeader: () => bearerHeader,
|
|
1197
|
+
config: () => config,
|
|
1198
|
+
custom: () => custom,
|
|
1199
|
+
effect: () => effect,
|
|
1200
|
+
header: () => header,
|
|
1201
|
+
headers: () => headers,
|
|
1202
|
+
isAuth: () => isAuth,
|
|
1203
|
+
none: () => none,
|
|
1204
|
+
optional: () => optional,
|
|
1205
|
+
passthrough: () => passthrough,
|
|
1206
|
+
remove: () => remove,
|
|
1207
|
+
toEffect: () => toEffect,
|
|
1208
|
+
value: () => value
|
|
1209
|
+
});
|
|
1210
|
+
var MissingCredentialError = class extends Error {
|
|
1211
|
+
constructor(source) {
|
|
1212
|
+
super(`Missing auth credential: ${source}`);
|
|
1213
|
+
this.source = source;
|
|
1214
|
+
}
|
|
1215
|
+
_tag = "MissingCredentialError";
|
|
1216
|
+
};
|
|
1217
|
+
var isAuth = (input) => typeof input === "object" && input !== null && "apply" in input && typeof input.apply === "function";
|
|
1218
|
+
var credential = (load) => {
|
|
1219
|
+
const self = {
|
|
1220
|
+
load,
|
|
1221
|
+
orElse: (that) => credential(load.pipe(Effect.catch(() => that.load))),
|
|
1222
|
+
bearer: () => fromCredential(self, (secret) => ({ authorization: `Bearer ${secret}` })),
|
|
1223
|
+
header: (name) => fromCredential(self, (secret) => ({ [name]: secret })),
|
|
1224
|
+
pipe: (f) => f(self)
|
|
1225
|
+
};
|
|
1226
|
+
return self;
|
|
1227
|
+
};
|
|
1228
|
+
var auth = (apply) => {
|
|
1229
|
+
const self = {
|
|
1230
|
+
apply,
|
|
1231
|
+
andThen: (that) => auth((input) => apply(input).pipe(Effect.flatMap((headers2) => that.apply({ ...input, headers: headers2 })))),
|
|
1232
|
+
orElse: (that) => auth((input) => apply(input).pipe(Effect.catch(() => that.apply(input)))),
|
|
1233
|
+
pipe: (f) => f(self)
|
|
1234
|
+
};
|
|
1235
|
+
return self;
|
|
1236
|
+
};
|
|
1237
|
+
var fromCredential = (source, render2) => auth(
|
|
1238
|
+
(input) => source.load.pipe(Effect.map((secret) => Headers.setAll(input.headers, render2(Redacted.value(secret)))))
|
|
1239
|
+
);
|
|
1240
|
+
var secretEffect = (secret, source) => {
|
|
1241
|
+
const redacted = typeof secret === "string" ? Redacted.make(secret) : secret;
|
|
1242
|
+
if (Redacted.value(redacted) === "") return Effect.fail(new MissingCredentialError(source));
|
|
1243
|
+
return Effect.succeed(redacted);
|
|
1244
|
+
};
|
|
1245
|
+
var credentialFromSecret = (secret, source) => {
|
|
1246
|
+
if (typeof secret === "string" || Redacted.isRedacted(secret)) return credential(secretEffect(secret, source));
|
|
1247
|
+
return credential(
|
|
1248
|
+
Effect.gen(function* () {
|
|
1249
|
+
return yield* secretEffect(yield* secret, source);
|
|
1250
|
+
})
|
|
1251
|
+
);
|
|
1252
|
+
};
|
|
1253
|
+
var value = (secret, source = "value") => credentialFromSecret(secret, source);
|
|
1254
|
+
var optional = (secret, source = "optional value") => secret === void 0 ? credential(Effect.fail(new MissingCredentialError(source))) : credentialFromSecret(secret, source);
|
|
1255
|
+
var config = (name) => credentialFromSecret(Config.redacted(name), name);
|
|
1256
|
+
var effect = (load) => credential(load);
|
|
1257
|
+
var none = auth((input) => Effect.succeed(input.headers));
|
|
1258
|
+
var headers = (input) => auth((inputAuth) => Effect.succeed(Headers.setAll(inputAuth.headers, input)));
|
|
1259
|
+
var remove = (name) => auth((input) => Effect.succeed(Headers.remove(input.headers, name)));
|
|
1260
|
+
var custom = (apply) => auth(apply);
|
|
1261
|
+
var passthrough = none;
|
|
1262
|
+
var fromModelApiKey = (from) => auth(({ request: request2, headers: headers2 }) => {
|
|
1263
|
+
const key = request2.model.apiKey;
|
|
1264
|
+
if (!key) return Effect.succeed(headers2);
|
|
1265
|
+
return Effect.succeed(Headers.setAll(headers2, from(key)));
|
|
1266
|
+
});
|
|
1267
|
+
var credentialInput = (source) => typeof source === "string" || Redacted.isRedacted(source) || Config.isConfig(source) ? credentialFromSecret(source, "value") : source;
|
|
1268
|
+
function bearer(source) {
|
|
1269
|
+
if (source === void 0) return fromModelApiKey((key) => ({ authorization: `Bearer ${key}` }));
|
|
1270
|
+
return credentialInput(source).bearer();
|
|
1271
|
+
}
|
|
1272
|
+
var apiKey = bearer;
|
|
1273
|
+
var apiKeyHeader = (name) => fromModelApiKey((key) => ({ [name]: key }));
|
|
1274
|
+
function header(name, source) {
|
|
1275
|
+
if (source === void 0) {
|
|
1276
|
+
return (next) => credentialInput(next).header(name);
|
|
1277
|
+
}
|
|
1278
|
+
return credentialInput(source).header(name);
|
|
1279
|
+
}
|
|
1280
|
+
function bearerHeader(name, source) {
|
|
1281
|
+
const render2 = (input) => fromCredential(credentialInput(input), (secret) => ({ [name]: `Bearer ${secret}` }));
|
|
1282
|
+
if (source === void 0) return render2;
|
|
1283
|
+
return render2(source);
|
|
1284
|
+
}
|
|
1285
|
+
var toLLMError = (error) => {
|
|
1286
|
+
if (error instanceof MissingCredentialError || error instanceof Config.ConfigError) {
|
|
1287
|
+
return new LLMError({
|
|
1288
|
+
module: "Auth",
|
|
1289
|
+
method: "apply",
|
|
1290
|
+
reason: error instanceof MissingCredentialError ? new AuthenticationReason({ message: error.message, kind: "missing" }) : new InvalidRequestReason({ message: `Failed to resolve auth config: ${error.message}` })
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
return error;
|
|
1294
|
+
};
|
|
1295
|
+
var toEffect = (input) => (authInput) => input.apply(authInput).pipe(Effect.mapError(toLLMError));
|
|
1296
|
+
|
|
1297
|
+
// src/route/auth-options.ts
|
|
1298
|
+
var auth_options_exports = {};
|
|
1299
|
+
__export(auth_options_exports, {
|
|
1300
|
+
AuthOptions: () => auth_options_exports,
|
|
1301
|
+
bearer: () => bearer2
|
|
1302
|
+
});
|
|
1303
|
+
var bearer2 = (options2, envVar) => {
|
|
1304
|
+
if ("auth" in options2 && options2.auth) return options2.auth;
|
|
1305
|
+
return (Array.isArray(envVar) ? envVar : [envVar]).reduce(
|
|
1306
|
+
(auth3, name) => auth3.orElse(auth_exports.config(name)),
|
|
1307
|
+
auth_exports.optional("apiKey" in options2 ? options2.apiKey : void 0, "apiKey")
|
|
1308
|
+
).bearer();
|
|
1309
|
+
};
|
|
1310
|
+
|
|
1311
|
+
// src/route/transport/http.ts
|
|
1312
|
+
var http_exports = {};
|
|
1313
|
+
__export(http_exports, {
|
|
1314
|
+
httpJson: () => httpJson,
|
|
1315
|
+
jsonRequestParts: () => jsonRequestParts
|
|
1316
|
+
});
|
|
1317
|
+
var applyQuery = (url, query) => {
|
|
1318
|
+
if (!query) return url;
|
|
1319
|
+
const next = new URL(url);
|
|
1320
|
+
Object.entries(query).forEach(([key, value2]) => next.searchParams.set(key, value2));
|
|
1321
|
+
return next.toString();
|
|
1322
|
+
};
|
|
1323
|
+
var bodyWithOverlay = (body, request2, encodeBody2) => Effect.gen(function* () {
|
|
1324
|
+
if (request2.http?.body === void 0) return { jsonBody: body, bodyText: encodeBody2(body) };
|
|
1325
|
+
if (isRecord3(body)) {
|
|
1326
|
+
const overlaid = mergeJsonRecords(body, request2.http.body) ?? {};
|
|
1327
|
+
return { jsonBody: overlaid, bodyText: encodeJson(overlaid) };
|
|
1328
|
+
}
|
|
1329
|
+
return yield* invalidRequest("http.body can only overlay JSON object request bodies");
|
|
1330
|
+
});
|
|
1331
|
+
var jsonRequestParts = (input) => Effect.gen(function* () {
|
|
1332
|
+
const url = applyQuery(
|
|
1333
|
+
render(input.endpoint, { request: input.request, body: input.body }).toString(),
|
|
1334
|
+
input.request.http?.query
|
|
1335
|
+
);
|
|
1336
|
+
const body = yield* bodyWithOverlay(input.body, input.request, input.encodeBody);
|
|
1337
|
+
const headers2 = yield* auth_exports.toEffect(auth_exports.isAuth(input.request.model.auth) ? input.request.model.auth : input.auth)(
|
|
1338
|
+
{
|
|
1339
|
+
request: input.request,
|
|
1340
|
+
method: "POST",
|
|
1341
|
+
url,
|
|
1342
|
+
body: body.bodyText,
|
|
1343
|
+
headers: Headers.fromInput({
|
|
1344
|
+
...input.headers?.({ request: input.request }) ?? {},
|
|
1345
|
+
...input.request.model.headers,
|
|
1346
|
+
...input.request.http?.headers
|
|
1347
|
+
})
|
|
1348
|
+
}
|
|
1349
|
+
);
|
|
1350
|
+
return { url, jsonBody: body.jsonBody, bodyText: body.bodyText, headers: headers2 };
|
|
1351
|
+
});
|
|
1352
|
+
var httpJson = (input) => ({
|
|
1353
|
+
id: "http-json",
|
|
1354
|
+
with: (patch) => httpJson({ ...input, ...patch }),
|
|
1355
|
+
prepare: (body, request2) => jsonRequestParts({
|
|
1356
|
+
body,
|
|
1357
|
+
request: request2,
|
|
1358
|
+
endpoint: input.endpoint,
|
|
1359
|
+
auth: input.auth ?? auth_exports.bearer(),
|
|
1360
|
+
encodeBody: input.encodeBody,
|
|
1361
|
+
headers: input.headers
|
|
1362
|
+
}).pipe(
|
|
1363
|
+
Effect.map((parts) => ({
|
|
1364
|
+
request: jsonPost({ url: parts.url, body: parts.bodyText, headers: parts.headers }),
|
|
1365
|
+
framing: input.framing
|
|
1366
|
+
}))
|
|
1367
|
+
),
|
|
1368
|
+
frames: (prepared, request2, runtime) => Stream.unwrap(
|
|
1369
|
+
runtime.http.execute(prepared.request).pipe(
|
|
1370
|
+
Effect.map(
|
|
1371
|
+
(response) => prepared.framing.frame(
|
|
1372
|
+
response.stream.pipe(
|
|
1373
|
+
Stream.mapError(
|
|
1374
|
+
(error) => eventError(
|
|
1375
|
+
`${request2.model.provider}/${request2.model.route}`,
|
|
1376
|
+
`Failed to read ${request2.model.provider}/${request2.model.route} stream`,
|
|
1377
|
+
errorText(error)
|
|
1378
|
+
)
|
|
1379
|
+
)
|
|
1380
|
+
)
|
|
1381
|
+
)
|
|
1382
|
+
)
|
|
1383
|
+
)
|
|
1384
|
+
)
|
|
1385
|
+
});
|
|
1386
|
+
|
|
1387
|
+
// src/route/executor.ts
|
|
1388
|
+
var executor_exports = {};
|
|
1389
|
+
__export(executor_exports, {
|
|
1390
|
+
RequestExecutor: () => executor_exports,
|
|
1391
|
+
Service: () => Service,
|
|
1392
|
+
defaultLayer: () => defaultLayer,
|
|
1393
|
+
layer: () => layer
|
|
1394
|
+
});
|
|
1395
|
+
|
|
1396
|
+
// src/route/overflow-detect.ts
|
|
1397
|
+
var OVERFLOW_PATTERNS = [
|
|
1398
|
+
/prompt is too long/i,
|
|
1399
|
+
// Anthropic
|
|
1400
|
+
/input is too long for requested model/i,
|
|
1401
|
+
// Amazon Bedrock
|
|
1402
|
+
/exceeds the context window/i,
|
|
1403
|
+
// OpenAI
|
|
1404
|
+
/input token count.*exceeds the maximum/i,
|
|
1405
|
+
// Google (Gemini)
|
|
1406
|
+
/maximum prompt length is \d+/i,
|
|
1407
|
+
// xAI (Grok)
|
|
1408
|
+
/reduce the length of the messages/i,
|
|
1409
|
+
// Groq
|
|
1410
|
+
/maximum context length is \d+ tokens/i,
|
|
1411
|
+
// OpenRouter, DeepSeek, vLLM
|
|
1412
|
+
/exceeds the limit of \d+/i,
|
|
1413
|
+
// GitHub Copilot
|
|
1414
|
+
/exceeds the available context size/i,
|
|
1415
|
+
// llama.cpp server
|
|
1416
|
+
/greater than the context length/i,
|
|
1417
|
+
// LM Studio
|
|
1418
|
+
/context window exceeds limit/i,
|
|
1419
|
+
// MiniMax
|
|
1420
|
+
/exceeded model token limit/i,
|
|
1421
|
+
// Kimi, Moonshot
|
|
1422
|
+
/context[_ ]length[_ ]exceeded/i,
|
|
1423
|
+
// Generic OpenAI-style code
|
|
1424
|
+
/request entity too large/i,
|
|
1425
|
+
// HTTP 413
|
|
1426
|
+
/context length is only \d+ tokens/i,
|
|
1427
|
+
// vLLM
|
|
1428
|
+
/input length.*exceeds.*context length/i,
|
|
1429
|
+
// vLLM
|
|
1430
|
+
/prompt too long; exceeded (?:max )?context length/i,
|
|
1431
|
+
// Ollama
|
|
1432
|
+
/too large for model with \d+ maximum context length/i,
|
|
1433
|
+
// Mistral
|
|
1434
|
+
/model_context_window_exceeded/i
|
|
1435
|
+
// z.ai
|
|
1436
|
+
];
|
|
1437
|
+
var NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i;
|
|
1438
|
+
var isOverflowMessage = (message2) => {
|
|
1439
|
+
if (OVERFLOW_PATTERNS.some((p) => p.test(message2))) return true;
|
|
1440
|
+
return NO_BODY_4XX.test(message2);
|
|
1441
|
+
};
|
|
1442
|
+
var isOverflowStatus = (status) => status === 413;
|
|
1443
|
+
var TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i;
|
|
1444
|
+
var PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i;
|
|
1445
|
+
var INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i;
|
|
1446
|
+
var extractOverflowNumbers = (message2) => {
|
|
1447
|
+
const match = PROMPT_LENGTH.exec(message2) ?? INPUT_LIMIT.exec(message2) ?? TOKENS_GT_MAX.exec(message2);
|
|
1448
|
+
if (!match) return void 0;
|
|
1449
|
+
const promptTokens = Number(match[1]);
|
|
1450
|
+
const contextWindow = Number(match[2]);
|
|
1451
|
+
if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return void 0;
|
|
1452
|
+
return { promptTokens, contextWindow };
|
|
1453
|
+
};
|
|
1454
|
+
var isOverflowBody = (body) => {
|
|
1455
|
+
if (typeof body !== "object" || body === null) return false;
|
|
1456
|
+
const root = body;
|
|
1457
|
+
const code = root.error?.code ?? root.code;
|
|
1458
|
+
if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true;
|
|
1459
|
+
if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true;
|
|
1460
|
+
return false;
|
|
1461
|
+
};
|
|
1462
|
+
|
|
1463
|
+
// src/route/executor.ts
|
|
1464
|
+
var Service = class extends Context.Service()("@tinyweb-agent/LLM/RequestExecutor") {
|
|
1465
|
+
};
|
|
1466
|
+
var BODY_LIMIT = 16384;
|
|
1467
|
+
var MAX_RETRIES = 2;
|
|
1468
|
+
var BASE_DELAY_MS = 500;
|
|
1469
|
+
var MAX_DELAY_MS = 1e4;
|
|
1470
|
+
var REDACTED = "<redacted>";
|
|
1471
|
+
var SENSITIVE_NAME_SOURCE = "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature";
|
|
1472
|
+
var SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i");
|
|
1473
|
+
var SHORT_QUERY_NAME = /^(key|sig)$/i;
|
|
1474
|
+
var SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i");
|
|
1475
|
+
var REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi");
|
|
1476
|
+
var REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi");
|
|
1477
|
+
var isSensitiveHeaderName = (name) => SENSITIVE_NAME.test(name);
|
|
1478
|
+
var isSensitiveQueryName = (name) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name);
|
|
1479
|
+
var redactHeaders = (headers2, redactedNames) => Object.fromEntries(
|
|
1480
|
+
Object.entries(Headers.redact(headers2, [...redactedNames, SENSITIVE_NAME])).map(([name, value2]) => [
|
|
1481
|
+
name,
|
|
1482
|
+
String(value2)
|
|
1483
|
+
])
|
|
1484
|
+
);
|
|
1485
|
+
var redactUrl = (value2) => {
|
|
1486
|
+
if (!URL.canParse(value2)) return REDACTED;
|
|
1487
|
+
const url = new URL(value2);
|
|
1488
|
+
url.searchParams.forEach((_, key) => {
|
|
1489
|
+
if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED);
|
|
1490
|
+
});
|
|
1491
|
+
return url.toString();
|
|
1492
|
+
};
|
|
1493
|
+
var normalizedHeaders = (headers2) => Object.fromEntries(Object.entries(headers2).map(([key, value2]) => [key.toLowerCase(), value2]));
|
|
1494
|
+
var requestId = (headers2) => {
|
|
1495
|
+
return headers2["x-request-id"] ?? headers2["request-id"] ?? headers2["x-amzn-requestid"] ?? headers2["x-amz-request-id"] ?? headers2["x-goog-request-id"] ?? headers2["cf-ray"];
|
|
1496
|
+
};
|
|
1497
|
+
var retryableStatus = (status) => status === 429 || status === 503 || status === 504 || status === 529;
|
|
1498
|
+
var retryAfterMs = (headers2) => {
|
|
1499
|
+
const millis = Number(headers2["retry-after-ms"]);
|
|
1500
|
+
if (Number.isFinite(millis)) return Math.max(0, millis);
|
|
1501
|
+
const value2 = headers2["retry-after"];
|
|
1502
|
+
if (!value2) return void 0;
|
|
1503
|
+
const seconds = Number(value2);
|
|
1504
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
1505
|
+
const date = Date.parse(value2);
|
|
1506
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
1507
|
+
return void 0;
|
|
1508
|
+
};
|
|
1509
|
+
var addRateLimitValue = (target, key, value2) => {
|
|
1510
|
+
if (key.length > 0) target[key] = value2;
|
|
1511
|
+
};
|
|
1512
|
+
var rateLimitDetails = (headers2, retryAfter) => {
|
|
1513
|
+
const limit = {};
|
|
1514
|
+
const remaining = {};
|
|
1515
|
+
const reset = {};
|
|
1516
|
+
Object.entries(headers2).forEach(([name, value2]) => {
|
|
1517
|
+
const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1];
|
|
1518
|
+
if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value2);
|
|
1519
|
+
const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1];
|
|
1520
|
+
if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value2);
|
|
1521
|
+
const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1];
|
|
1522
|
+
if (openaiReset) return addRateLimitValue(reset, openaiReset, value2);
|
|
1523
|
+
const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name);
|
|
1524
|
+
if (!anthropic) return;
|
|
1525
|
+
if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value2);
|
|
1526
|
+
if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value2);
|
|
1527
|
+
return addRateLimitValue(reset, anthropic[1], value2);
|
|
1528
|
+
});
|
|
1529
|
+
if (retryAfter === void 0 && Object.keys(limit).length === 0 && Object.keys(remaining).length === 0 && Object.keys(reset).length === 0)
|
|
1530
|
+
return void 0;
|
|
1531
|
+
return new HttpRateLimitDetails({
|
|
1532
|
+
retryAfterMs: retryAfter,
|
|
1533
|
+
limit: Object.keys(limit).length === 0 ? void 0 : limit,
|
|
1534
|
+
remaining: Object.keys(remaining).length === 0 ? void 0 : remaining,
|
|
1535
|
+
reset: Object.keys(reset).length === 0 ? void 0 : reset
|
|
1536
|
+
});
|
|
1537
|
+
};
|
|
1538
|
+
var requestDetails = (request2, redactedNames) => new HttpRequestDetails({
|
|
1539
|
+
method: request2.method,
|
|
1540
|
+
url: redactUrl(request2.url),
|
|
1541
|
+
headers: redactHeaders(request2.headers, redactedNames)
|
|
1542
|
+
});
|
|
1543
|
+
var responseDetails = (response, redactedNames) => new HttpResponseDetails({
|
|
1544
|
+
status: response.status,
|
|
1545
|
+
headers: redactHeaders(response.headers, redactedNames)
|
|
1546
|
+
});
|
|
1547
|
+
var secretValues = (request2) => {
|
|
1548
|
+
const values = /* @__PURE__ */ new Set();
|
|
1549
|
+
const add = (value2) => {
|
|
1550
|
+
if (value2.length < 4) return;
|
|
1551
|
+
values.add(value2);
|
|
1552
|
+
values.add(encodeURIComponent(value2));
|
|
1553
|
+
};
|
|
1554
|
+
Object.entries(request2.headers).forEach(([name, value2]) => {
|
|
1555
|
+
if (!isSensitiveHeaderName(name)) return;
|
|
1556
|
+
add(value2);
|
|
1557
|
+
const bearer3 = /^Bearer\s+(.+)$/i.exec(value2)?.[1];
|
|
1558
|
+
if (bearer3) add(bearer3);
|
|
1559
|
+
});
|
|
1560
|
+
if (!URL.canParse(request2.url)) return values;
|
|
1561
|
+
new URL(request2.url).searchParams.forEach((value2, key) => {
|
|
1562
|
+
if (isSensitiveQueryName(key)) add(value2);
|
|
1563
|
+
});
|
|
1564
|
+
return values;
|
|
1565
|
+
};
|
|
1566
|
+
var redactBody = (body, request2) => Array.from(secretValues(request2)).reduce(
|
|
1567
|
+
(text2, secret) => text2.split(secret).join(REDACTED),
|
|
1568
|
+
body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`)
|
|
1569
|
+
);
|
|
1570
|
+
var responseBody = (body, request2) => {
|
|
1571
|
+
if (body === void 0) return {};
|
|
1572
|
+
const redacted = redactBody(body, request2);
|
|
1573
|
+
if (redacted.length <= BODY_LIMIT) return { body: redacted };
|
|
1574
|
+
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true };
|
|
1575
|
+
};
|
|
1576
|
+
var providerMessage = (status, body) => {
|
|
1577
|
+
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`;
|
|
1578
|
+
return `Provider request failed with HTTP ${status}`;
|
|
1579
|
+
};
|
|
1580
|
+
var responseHttp = (input) => new HttpContext({
|
|
1581
|
+
request: requestDetails(input.request, input.redactedNames),
|
|
1582
|
+
response: responseDetails(input.response, input.redactedNames),
|
|
1583
|
+
...input.body,
|
|
1584
|
+
requestId: input.requestId,
|
|
1585
|
+
rateLimit: input.rateLimit
|
|
1586
|
+
});
|
|
1587
|
+
var parseJsonBody = (body) => {
|
|
1588
|
+
if (body.length === 0) return void 0;
|
|
1589
|
+
try {
|
|
1590
|
+
return JSON.parse(body);
|
|
1591
|
+
} catch {
|
|
1592
|
+
return void 0;
|
|
1593
|
+
}
|
|
1594
|
+
};
|
|
1595
|
+
var isOverflow = (status, message2, body) => {
|
|
1596
|
+
if (isOverflowStatus(status)) return true;
|
|
1597
|
+
if (isOverflowMessage(message2)) return true;
|
|
1598
|
+
if (body.length > 0 && isOverflowMessage(body)) return true;
|
|
1599
|
+
return isOverflowBody(parseJsonBody(body));
|
|
1600
|
+
};
|
|
1601
|
+
var overflowReason = (input) => {
|
|
1602
|
+
const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body);
|
|
1603
|
+
return new ContextOverflowReason({
|
|
1604
|
+
message: input.message,
|
|
1605
|
+
promptTokens: numbers?.promptTokens,
|
|
1606
|
+
contextWindow: numbers?.contextWindow,
|
|
1607
|
+
http: input.http
|
|
1608
|
+
});
|
|
1609
|
+
};
|
|
1610
|
+
var statusReason = (input) => {
|
|
1611
|
+
const body = input.http.body ?? "";
|
|
1612
|
+
if (isOverflow(input.status, input.message, body)) {
|
|
1613
|
+
return overflowReason({ message: input.message, body, http: input.http });
|
|
1614
|
+
}
|
|
1615
|
+
if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
|
|
1616
|
+
return new ContentPolicyReason({ message: input.message, http: input.http });
|
|
1617
|
+
}
|
|
1618
|
+
if (input.status === 401) {
|
|
1619
|
+
return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http });
|
|
1620
|
+
}
|
|
1621
|
+
if (input.status === 403) {
|
|
1622
|
+
return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http });
|
|
1623
|
+
}
|
|
1624
|
+
if (input.status === 429) {
|
|
1625
|
+
if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
|
|
1626
|
+
return new QuotaExceededReason({ message: input.message, http: input.http });
|
|
1627
|
+
}
|
|
1628
|
+
return new RateLimitReason({
|
|
1629
|
+
message: input.message,
|
|
1630
|
+
retryAfterMs: input.retryAfterMs,
|
|
1631
|
+
rateLimit: input.rateLimit,
|
|
1632
|
+
http: input.http
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
|
|
1636
|
+
return new InvalidRequestReason({ message: input.message, http: input.http });
|
|
1637
|
+
}
|
|
1638
|
+
if (input.status >= 500 || retryableStatus(input.status)) {
|
|
1639
|
+
return new ProviderInternalReason({
|
|
1640
|
+
message: input.message,
|
|
1641
|
+
status: input.status,
|
|
1642
|
+
retryAfterMs: input.retryAfterMs,
|
|
1643
|
+
http: input.http
|
|
1644
|
+
});
|
|
1645
|
+
}
|
|
1646
|
+
return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http });
|
|
1647
|
+
};
|
|
1648
|
+
var statusError = (request2, redactedNames) => (response) => Effect.gen(function* () {
|
|
1649
|
+
if (response.status < 400) return response;
|
|
1650
|
+
const body = yield* response.text.pipe(Effect.catch(() => Effect.void));
|
|
1651
|
+
const headers2 = normalizedHeaders(response.headers);
|
|
1652
|
+
const retryAfter = retryAfterMs(headers2);
|
|
1653
|
+
const rateLimit = rateLimitDetails(headers2, retryAfter);
|
|
1654
|
+
const details = responseBody(body, request2);
|
|
1655
|
+
return yield* new LLMError({
|
|
1656
|
+
module: "RequestExecutor",
|
|
1657
|
+
method: "execute",
|
|
1658
|
+
reason: statusReason({
|
|
1659
|
+
status: response.status,
|
|
1660
|
+
message: providerMessage(response.status, details),
|
|
1661
|
+
retryAfterMs: retryAfter,
|
|
1662
|
+
rateLimit,
|
|
1663
|
+
http: responseHttp({
|
|
1664
|
+
request: request2,
|
|
1665
|
+
response,
|
|
1666
|
+
redactedNames,
|
|
1667
|
+
body: details,
|
|
1668
|
+
requestId: requestId(headers2),
|
|
1669
|
+
rateLimit
|
|
1670
|
+
})
|
|
1671
|
+
})
|
|
1672
|
+
});
|
|
1673
|
+
});
|
|
1674
|
+
var toHttpError = (redactedNames) => (error) => {
|
|
1675
|
+
const transportError = (input) => new LLMError({
|
|
1676
|
+
module: "RequestExecutor",
|
|
1677
|
+
method: "execute",
|
|
1678
|
+
reason: new TransportReason({
|
|
1679
|
+
message: input.message,
|
|
1680
|
+
kind: input.kind,
|
|
1681
|
+
url: input.request ? redactUrl(input.request.url) : void 0,
|
|
1682
|
+
http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : void 0
|
|
1683
|
+
})
|
|
1684
|
+
});
|
|
1685
|
+
if (Cause.isTimeoutError(error)) {
|
|
1686
|
+
return transportError({ message: error.message, kind: "Timeout" });
|
|
1687
|
+
}
|
|
1688
|
+
if (!HttpClientError.isHttpClientError(error)) {
|
|
1689
|
+
return transportError({ message: "HTTP transport failed" });
|
|
1690
|
+
}
|
|
1691
|
+
const request2 = "request" in error ? error.request : void 0;
|
|
1692
|
+
if (error.reason._tag === "TransportError") {
|
|
1693
|
+
return transportError({
|
|
1694
|
+
message: error.reason.description ?? "HTTP transport failed",
|
|
1695
|
+
kind: error.reason._tag,
|
|
1696
|
+
request: request2
|
|
1697
|
+
});
|
|
1698
|
+
}
|
|
1699
|
+
return transportError({
|
|
1700
|
+
message: `HTTP transport failed: ${error.reason._tag}`,
|
|
1701
|
+
kind: error.reason._tag,
|
|
1702
|
+
request: request2
|
|
1703
|
+
});
|
|
1704
|
+
};
|
|
1705
|
+
var retryDelay = (error, attempt) => {
|
|
1706
|
+
if (error.retryAfterMs !== void 0) return Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS));
|
|
1707
|
+
return Random.nextBetween(
|
|
1708
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
|
|
1709
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS)
|
|
1710
|
+
).pipe(Effect.map((delay) => Math.round(delay)));
|
|
1711
|
+
};
|
|
1712
|
+
var retryStatusFailures = (effect2, retries = MAX_RETRIES, attempt = 0) => Effect.catchTag(effect2, "LLM.Error", (error) => {
|
|
1713
|
+
if (!error.retryable || retries <= 0) return Effect.fail(error);
|
|
1714
|
+
return retryDelay(error, attempt).pipe(
|
|
1715
|
+
Effect.flatMap((delay) => Effect.sleep(delay)),
|
|
1716
|
+
Effect.flatMap(() => retryStatusFailures(effect2, retries - 1, attempt + 1))
|
|
1717
|
+
);
|
|
1718
|
+
});
|
|
1719
|
+
var layer = Layer.effect(
|
|
1720
|
+
Service,
|
|
1721
|
+
Effect.gen(function* () {
|
|
1722
|
+
const http = yield* HttpClient.HttpClient;
|
|
1723
|
+
const executeOnce = (request2) => Effect.gen(function* () {
|
|
1724
|
+
const redactedNames = yield* Headers.CurrentRedactedNames;
|
|
1725
|
+
return yield* http.execute(request2).pipe(Effect.mapError(toHttpError(redactedNames)), Effect.flatMap(statusError(request2, redactedNames)));
|
|
1726
|
+
});
|
|
1727
|
+
return Service.of({
|
|
1728
|
+
execute: (request2) => retryStatusFailures(executeOnce(request2))
|
|
1729
|
+
});
|
|
1730
|
+
})
|
|
1731
|
+
);
|
|
1732
|
+
var defaultLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
|
|
1733
|
+
|
|
1734
|
+
// src/cache-policy.ts
|
|
1735
|
+
var AUTO = {
|
|
1736
|
+
tools: true,
|
|
1737
|
+
system: true,
|
|
1738
|
+
messages: "latest-user-message"
|
|
1739
|
+
};
|
|
1740
|
+
var NONE = {};
|
|
1741
|
+
var resolve = (policy) => {
|
|
1742
|
+
if (policy === void 0 || policy === "auto") return AUTO;
|
|
1743
|
+
if (policy === "none") return NONE;
|
|
1744
|
+
return policy;
|
|
1745
|
+
};
|
|
1746
|
+
var RESPECTS_INLINE_HINTS = /* @__PURE__ */ new Set([]);
|
|
1747
|
+
var makeHint = (ttlSeconds) => ttlSeconds !== void 0 ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" });
|
|
1748
|
+
var markLastTool = (tools, hint) => {
|
|
1749
|
+
if (tools.length === 0) return tools;
|
|
1750
|
+
const last = tools.length - 1;
|
|
1751
|
+
if (tools[last].cache) return tools;
|
|
1752
|
+
return tools.map((tool2, i) => i === last ? new ToolDefinition({ ...tool2, cache: hint }) : tool2);
|
|
1753
|
+
};
|
|
1754
|
+
var markLastSystem = (system2, hint) => {
|
|
1755
|
+
if (system2.length === 0) return system2;
|
|
1756
|
+
const last = system2.length - 1;
|
|
1757
|
+
if (system2[last].cache) return system2;
|
|
1758
|
+
return system2.map((part, i) => i === last ? { ...part, cache: hint } : part);
|
|
1759
|
+
};
|
|
1760
|
+
var lastIndexOfRole = (messages, role) => messages.findLastIndex((m) => m.role === role);
|
|
1761
|
+
var markMessageAt = (messages, index, hint) => {
|
|
1762
|
+
if (index < 0 || index >= messages.length) return messages;
|
|
1763
|
+
const target = messages[index];
|
|
1764
|
+
if (target.content.length === 0) return messages;
|
|
1765
|
+
const lastTextIndex = target.content.findLastIndex((part) => part.type === "text");
|
|
1766
|
+
const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.length - 1;
|
|
1767
|
+
const existing = target.content[markAt];
|
|
1768
|
+
if ("cache" in existing && existing.cache) return messages;
|
|
1769
|
+
const nextContent = target.content.map((part, i) => i === markAt ? { ...part, cache: hint } : part);
|
|
1770
|
+
const next = new Message({ ...target, content: nextContent });
|
|
1771
|
+
const result = messages.slice();
|
|
1772
|
+
result[index] = next;
|
|
1773
|
+
return result;
|
|
1774
|
+
};
|
|
1775
|
+
var markMessages = (messages, strategy, hint) => {
|
|
1776
|
+
if (messages.length === 0) return messages;
|
|
1777
|
+
if (strategy === "latest-user-message") return markMessageAt(messages, lastIndexOfRole(messages, "user"), hint);
|
|
1778
|
+
if (strategy === "latest-assistant") return markMessageAt(messages, lastIndexOfRole(messages, "assistant"), hint);
|
|
1779
|
+
const start2 = Math.max(0, messages.length - strategy.tail);
|
|
1780
|
+
let next = messages;
|
|
1781
|
+
for (let i = start2; i < messages.length; i++) next = markMessageAt(next, i, hint);
|
|
1782
|
+
return next;
|
|
1783
|
+
};
|
|
1784
|
+
var applyCachePolicy = (request2) => {
|
|
1785
|
+
if (!RESPECTS_INLINE_HINTS.has(request2.model.route)) return request2;
|
|
1786
|
+
const policy = resolve(request2.cache);
|
|
1787
|
+
if (!policy.tools && !policy.system && !policy.messages) return request2;
|
|
1788
|
+
const hint = makeHint(policy.ttlSeconds);
|
|
1789
|
+
const tools = policy.tools ? markLastTool(request2.tools, hint) : request2.tools;
|
|
1790
|
+
const system2 = policy.system ? markLastSystem(request2.system, hint) : request2.system;
|
|
1791
|
+
const messages = policy.messages ? markMessages(request2.messages, policy.messages, hint) : request2.messages;
|
|
1792
|
+
if (tools === request2.tools && system2 === request2.system && messages === request2.messages) return request2;
|
|
1793
|
+
return LLMRequest.update(request2, { tools, system: system2, messages });
|
|
1794
|
+
};
|
|
1795
|
+
|
|
1796
|
+
// src/route/client.ts
|
|
1797
|
+
var routeRegistry = /* @__PURE__ */ new Map();
|
|
1798
|
+
var register = (route3) => {
|
|
1799
|
+
const existing = routeRegistry.get(route3.id);
|
|
1800
|
+
if (existing && existing !== route3) throw new Error(`Duplicate LLM route id "${route3.id}"`);
|
|
1801
|
+
routeRegistry.set(route3.id, route3);
|
|
1802
|
+
return route3;
|
|
1803
|
+
};
|
|
1804
|
+
var registeredRoute = (id3) => routeRegistry.get(id3);
|
|
1805
|
+
var modelWithDefaults = (route3, defaults, options2) => (input) => {
|
|
1806
|
+
const mapped = options2.mapInput === void 0 ? input : options2.mapInput(input);
|
|
1807
|
+
const provider3 = defaults.provider ?? route3.provider ?? ("provider" in mapped ? mapped.provider : void 0);
|
|
1808
|
+
if (!provider3) throw new Error(`Route.model(${route3.id}) requires a provider`);
|
|
1809
|
+
const baseURL = mapped.baseURL ?? defaults.baseURL ?? route3.defaults.baseURL;
|
|
1810
|
+
if (!baseURL)
|
|
1811
|
+
throw new Error(`Route.model(${route3.id}) requires a baseURL \u2014 supply it via input, defaults, or route defaults`);
|
|
1812
|
+
const generation2 = mergeGenerationOptions(route3.defaults.generation, defaults.generation);
|
|
1813
|
+
const providerOptions = mergeProviderOptions(route3.defaults.providerOptions, defaults.providerOptions);
|
|
1814
|
+
const http = mergeHttpOptions(httpOptions(route3.defaults.http), httpOptions(defaults.http));
|
|
1815
|
+
return modelRef({
|
|
1816
|
+
...route3.defaults,
|
|
1817
|
+
...defaults,
|
|
1818
|
+
...mapped,
|
|
1819
|
+
baseURL,
|
|
1820
|
+
provider: provider3,
|
|
1821
|
+
route: route3.id,
|
|
1822
|
+
limits: mapped.limits ?? defaults.limits ?? route3.defaults.limits,
|
|
1823
|
+
generation: mergeGenerationOptions(generation2, mapped.generation),
|
|
1824
|
+
providerOptions: mergeProviderOptions(providerOptions, mapped.providerOptions),
|
|
1825
|
+
http: mergeHttpOptions(http, httpOptions(mapped.http))
|
|
1826
|
+
});
|
|
1827
|
+
};
|
|
1828
|
+
var mergeRouteDefaults = (base, patch) => ({
|
|
1829
|
+
...base,
|
|
1830
|
+
...patch,
|
|
1831
|
+
limits: patch.limits ?? base?.limits,
|
|
1832
|
+
generation: mergeGenerationOptions(generationOptions(base?.generation), generationOptions(patch.generation)),
|
|
1833
|
+
providerOptions: mergeProviderOptions(base?.providerOptions, patch.providerOptions),
|
|
1834
|
+
http: mergeHttpOptions(httpOptions(base?.http), httpOptions(patch.http))
|
|
1835
|
+
});
|
|
1836
|
+
var modelLimits = ModelLimits.make;
|
|
1837
|
+
var generationOptions = (input) => input === void 0 ? void 0 : GenerationOptions.make(input);
|
|
1838
|
+
var httpOptions = (input) => {
|
|
1839
|
+
if (input === void 0) return input;
|
|
1840
|
+
return HttpOptions.make(input);
|
|
1841
|
+
};
|
|
1842
|
+
var modelRef = (input) => new ModelRef({
|
|
1843
|
+
...input,
|
|
1844
|
+
id: ModelID.make(input.id),
|
|
1845
|
+
provider: ProviderID.make(input.provider),
|
|
1846
|
+
route: RouteID.make(input.route),
|
|
1847
|
+
limits: modelLimits(input.limits),
|
|
1848
|
+
generation: generationOptions(input.generation),
|
|
1849
|
+
http: httpOptions(input.http)
|
|
1850
|
+
});
|
|
1851
|
+
function model(route3, defaults = {}, options2 = {}) {
|
|
1852
|
+
return modelWithDefaults(route3, defaults, options2);
|
|
1853
|
+
}
|
|
1854
|
+
var Service2 = class extends Context.Service()("@tinyweb-agent/LLMClient") {
|
|
1855
|
+
};
|
|
1856
|
+
var noRoute = (model7) => new LLMError({
|
|
1857
|
+
module: "LLMClient",
|
|
1858
|
+
method: "resolveRoute",
|
|
1859
|
+
reason: new NoRouteReason({ route: model7.route, provider: model7.provider, model: model7.id })
|
|
1860
|
+
});
|
|
1861
|
+
var resolveRequestOptions = (request2) => LLMRequest.update(request2, {
|
|
1862
|
+
generation: mergeGenerationOptions(request2.model.generation, request2.generation) ?? new GenerationOptions({}),
|
|
1863
|
+
providerOptions: mergeProviderOptions(request2.model.providerOptions, request2.providerOptions),
|
|
1864
|
+
http: mergeHttpOptions(request2.model.http, request2.http)
|
|
1865
|
+
});
|
|
1866
|
+
var streamError = (route3, message2, cause) => {
|
|
1867
|
+
const failed = cause.reasons.find(Cause.isFailReason)?.error;
|
|
1868
|
+
if (failed instanceof LLMError) return failed;
|
|
1869
|
+
return eventError(route3, message2, Cause.pretty(cause));
|
|
1870
|
+
};
|
|
1871
|
+
function makeFromTransport(input) {
|
|
1872
|
+
const protocol2 = input.protocol;
|
|
1873
|
+
const decodeEventEffect = Schema.decodeUnknownEffect(protocol2.stream.event);
|
|
1874
|
+
const decodeEvent = (route3) => (frame) => decodeEventEffect(frame).pipe(
|
|
1875
|
+
Effect.mapError(
|
|
1876
|
+
() => eventError(
|
|
1877
|
+
input.id,
|
|
1878
|
+
`Invalid ${route3} stream event`,
|
|
1879
|
+
typeof frame === "string" ? frame : encodeJson(frame)
|
|
1880
|
+
)
|
|
1881
|
+
)
|
|
1882
|
+
);
|
|
1883
|
+
const build = (routeInput) => {
|
|
1884
|
+
const route3 = {
|
|
1885
|
+
id: routeInput.id,
|
|
1886
|
+
provider: routeInput.provider === void 0 ? void 0 : ProviderID.make(routeInput.provider),
|
|
1887
|
+
protocol: protocol2.id,
|
|
1888
|
+
transport: routeInput.transport,
|
|
1889
|
+
defaults: routeInput.defaults ?? {},
|
|
1890
|
+
body: protocol2.body,
|
|
1891
|
+
with: (patch) => {
|
|
1892
|
+
const { id: id3, provider: provider3, transport, ...defaults } = patch;
|
|
1893
|
+
if (!id3 || id3 === routeInput.id) throw new Error(`Route.with(${routeInput.id}) requires a new route id`);
|
|
1894
|
+
return build({
|
|
1895
|
+
...routeInput,
|
|
1896
|
+
id: id3,
|
|
1897
|
+
provider: provider3 ?? routeInput.provider,
|
|
1898
|
+
transport: transport ?? routeInput.transport,
|
|
1899
|
+
defaults: mergeRouteDefaults(routeInput.defaults, defaults)
|
|
1900
|
+
});
|
|
1901
|
+
},
|
|
1902
|
+
model: (input2) => modelWithDefaults(route3, {}, {})(input2),
|
|
1903
|
+
prepareTransport: routeInput.transport.prepare,
|
|
1904
|
+
streamPrepared: (prepared, request2, runtime) => {
|
|
1905
|
+
const route4 = `${request2.model.provider}/${request2.model.route}`;
|
|
1906
|
+
const events = routeInput.transport.frames(prepared, request2, runtime).pipe(
|
|
1907
|
+
Stream.mapEffect(decodeEvent(route4)),
|
|
1908
|
+
protocol2.stream.terminal ? Stream.takeUntil(protocol2.stream.terminal) : (stream4) => stream4
|
|
1909
|
+
);
|
|
1910
|
+
return events.pipe(
|
|
1911
|
+
Stream.mapAccumEffect(
|
|
1912
|
+
protocol2.stream.initial,
|
|
1913
|
+
protocol2.stream.step,
|
|
1914
|
+
protocol2.stream.onHalt ? { onHalt: protocol2.stream.onHalt } : void 0
|
|
1915
|
+
),
|
|
1916
|
+
Stream.catchCause((cause) => Stream.fail(streamError(route4, `Failed to read ${route4} stream`, cause)))
|
|
1917
|
+
);
|
|
1918
|
+
}
|
|
1919
|
+
};
|
|
1920
|
+
return register(route3);
|
|
1921
|
+
};
|
|
1922
|
+
return build(input);
|
|
1923
|
+
}
|
|
1924
|
+
function make3(input) {
|
|
1925
|
+
if ("transport" in input) return makeFromTransport(input);
|
|
1926
|
+
const protocol2 = input.protocol;
|
|
1927
|
+
const encodeBody2 = Schema.encodeSync(Schema.fromJsonString(protocol2.body.schema));
|
|
1928
|
+
return makeFromTransport({
|
|
1929
|
+
id: input.id,
|
|
1930
|
+
provider: input.provider,
|
|
1931
|
+
protocol: protocol2,
|
|
1932
|
+
transport: http_exports.httpJson({
|
|
1933
|
+
endpoint: input.endpoint,
|
|
1934
|
+
auth: input.auth,
|
|
1935
|
+
framing: input.framing,
|
|
1936
|
+
encodeBody: encodeBody2,
|
|
1937
|
+
headers: input.headers
|
|
1938
|
+
}),
|
|
1939
|
+
defaults: input.defaults
|
|
1940
|
+
});
|
|
1941
|
+
}
|
|
1942
|
+
var compile = Effect.fn("LLM.compile")(function* (request2) {
|
|
1943
|
+
const resolved = applyCachePolicy(resolveRequestOptions(request2));
|
|
1944
|
+
const route3 = registeredRoute(resolved.model.route);
|
|
1945
|
+
if (!route3) return yield* noRoute(resolved.model);
|
|
1946
|
+
const body = yield* route3.body.from(resolved).pipe(Effect.flatMap(validateWith(Schema.decodeUnknownEffect(route3.body.schema))));
|
|
1947
|
+
const prepared = yield* route3.prepareTransport(body, resolved);
|
|
1948
|
+
return {
|
|
1949
|
+
request: resolved,
|
|
1950
|
+
route: route3,
|
|
1951
|
+
body,
|
|
1952
|
+
prepared
|
|
1953
|
+
};
|
|
1954
|
+
});
|
|
1955
|
+
var prepareWith = Effect.fn("LLMClient.prepare")(function* (request2) {
|
|
1956
|
+
const compiled = yield* compile(request2);
|
|
1957
|
+
return new PreparedRequest({
|
|
1958
|
+
id: compiled.request.id ?? "request",
|
|
1959
|
+
route: compiled.route.id,
|
|
1960
|
+
protocol: compiled.route.protocol,
|
|
1961
|
+
model: compiled.request.model,
|
|
1962
|
+
body: compiled.body,
|
|
1963
|
+
metadata: { transport: compiled.route.transport.id }
|
|
1964
|
+
});
|
|
1965
|
+
});
|
|
1966
|
+
var streamRequestWith = (runtime) => (request2) => Stream.unwrap(
|
|
1967
|
+
Effect.gen(function* () {
|
|
1968
|
+
const compiled = yield* compile(request2);
|
|
1969
|
+
return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime);
|
|
1970
|
+
})
|
|
1971
|
+
);
|
|
1972
|
+
var isToolRunOptions = (input) => "request" in input && "tools" in input;
|
|
1973
|
+
var streamWith = (streamRequest) => ((input) => {
|
|
1974
|
+
if (isToolRunOptions(input)) return stream({ ...input, stream: streamRequest });
|
|
1975
|
+
return streamRequest(input);
|
|
1976
|
+
});
|
|
1977
|
+
var generateWith = (stream4) => Effect.fn("LLM.generate")(function* (input) {
|
|
1978
|
+
return new LLMResponse(
|
|
1979
|
+
yield* stream4(input).pipe(
|
|
1980
|
+
Stream.runFold(
|
|
1981
|
+
() => ({ events: [], usage: void 0 }),
|
|
1982
|
+
(acc, event) => {
|
|
1983
|
+
acc.events.push(event);
|
|
1984
|
+
if ("usage" in event && event.usage !== void 0) acc.usage = event.usage;
|
|
1985
|
+
return acc;
|
|
1986
|
+
}
|
|
1987
|
+
)
|
|
1988
|
+
)
|
|
1989
|
+
);
|
|
1990
|
+
});
|
|
1991
|
+
var prepare = (request2) => prepareWith(request2);
|
|
1992
|
+
function stream2(input) {
|
|
1993
|
+
return Stream.unwrap(
|
|
1994
|
+
Effect.gen(function* () {
|
|
1995
|
+
return (yield* Service2).stream(input);
|
|
1996
|
+
})
|
|
1997
|
+
);
|
|
1998
|
+
}
|
|
1999
|
+
function generate(input) {
|
|
2000
|
+
return Effect.gen(function* () {
|
|
2001
|
+
return yield* (yield* Service2).generate(input);
|
|
2002
|
+
});
|
|
2003
|
+
}
|
|
2004
|
+
var layer2 = Layer.effect(
|
|
2005
|
+
Service2,
|
|
2006
|
+
Effect.gen(function* () {
|
|
2007
|
+
const stream4 = streamWith(streamRequestWith({ http: yield* executor_exports.Service }));
|
|
2008
|
+
return Service2.of({ prepare: prepareWith, stream: stream4, generate: generateWith(stream4) });
|
|
2009
|
+
})
|
|
2010
|
+
);
|
|
2011
|
+
var Route = { make: make3, model };
|
|
2012
|
+
var LLMClient = {
|
|
2013
|
+
Service: Service2,
|
|
2014
|
+
layer: layer2,
|
|
2015
|
+
prepare,
|
|
2016
|
+
stream: stream2,
|
|
2017
|
+
generate,
|
|
2018
|
+
stepCountIs,
|
|
2019
|
+
hasToolCall,
|
|
2020
|
+
stopWhenAny
|
|
2021
|
+
};
|
|
2022
|
+
|
|
2023
|
+
// src/protocols/openai-chat.ts
|
|
2024
|
+
var openai_chat_exports = {};
|
|
2025
|
+
__export(openai_chat_exports, {
|
|
2026
|
+
DEFAULT_BASE_URL: () => DEFAULT_BASE_URL,
|
|
2027
|
+
OpenAIChat: () => openai_chat_exports,
|
|
2028
|
+
PATH: () => PATH,
|
|
2029
|
+
bodyFields: () => bodyFields,
|
|
2030
|
+
httpTransport: () => httpTransport,
|
|
2031
|
+
model: () => model2,
|
|
2032
|
+
protocol: () => protocol,
|
|
2033
|
+
route: () => route
|
|
2034
|
+
});
|
|
2035
|
+
|
|
2036
|
+
// src/protocols/utils/openai-options.ts
|
|
2037
|
+
var openai_options_exports = {};
|
|
2038
|
+
__export(openai_options_exports, {
|
|
2039
|
+
OpenAIOptions: () => openai_options_exports,
|
|
2040
|
+
OpenAIReasoningEffort: () => OpenAIReasoningEffort,
|
|
2041
|
+
OpenAIReasoningEfforts: () => OpenAIReasoningEfforts,
|
|
2042
|
+
OpenAITextVerbosity: () => OpenAITextVerbosity,
|
|
2043
|
+
encryptedReasoning: () => encryptedReasoning,
|
|
2044
|
+
isReasoningEffort: () => isReasoningEffort,
|
|
2045
|
+
promptCacheKey: () => promptCacheKey,
|
|
2046
|
+
reasoningEffort: () => reasoningEffort,
|
|
2047
|
+
reasoningSummary: () => reasoningSummary,
|
|
2048
|
+
store: () => store,
|
|
2049
|
+
textVerbosity: () => textVerbosity
|
|
2050
|
+
});
|
|
2051
|
+
var OpenAIReasoningEfforts = ReasoningEfforts.filter(
|
|
2052
|
+
(effort) => effort !== "max"
|
|
2053
|
+
);
|
|
2054
|
+
var REASONING_EFFORTS = new Set(ReasoningEfforts);
|
|
2055
|
+
var OPENAI_REASONING_EFFORTS = new Set(OpenAIReasoningEfforts);
|
|
2056
|
+
var TEXT_VERBOSITY = /* @__PURE__ */ new Set(["low", "medium", "high"]);
|
|
2057
|
+
var OpenAIReasoningEffort = Schema.Literals(OpenAIReasoningEfforts);
|
|
2058
|
+
var OpenAITextVerbosity = TextVerbosity;
|
|
2059
|
+
var isAnyReasoningEffort = (effort) => typeof effort === "string" && REASONING_EFFORTS.has(effort);
|
|
2060
|
+
var isReasoningEffort = (effort) => typeof effort === "string" && OPENAI_REASONING_EFFORTS.has(effort);
|
|
2061
|
+
var isTextVerbosity = (value2) => typeof value2 === "string" && TEXT_VERBOSITY.has(value2);
|
|
2062
|
+
var options = (request2) => request2.providerOptions?.openai;
|
|
2063
|
+
var store = (request2) => {
|
|
2064
|
+
const value2 = options(request2)?.store;
|
|
2065
|
+
return typeof value2 === "boolean" ? value2 : void 0;
|
|
2066
|
+
};
|
|
2067
|
+
var reasoningEffort = (request2) => {
|
|
2068
|
+
const value2 = options(request2)?.reasoningEffort;
|
|
2069
|
+
return isAnyReasoningEffort(value2) ? value2 : void 0;
|
|
2070
|
+
};
|
|
2071
|
+
var reasoningSummary = (request2) => {
|
|
2072
|
+
return options(request2)?.reasoningSummary === "auto" ? "auto" : void 0;
|
|
2073
|
+
};
|
|
2074
|
+
var encryptedReasoning = (request2) => options(request2)?.includeEncryptedReasoning === true ? true : void 0;
|
|
2075
|
+
var promptCacheKey = (request2) => {
|
|
2076
|
+
const value2 = options(request2)?.promptCacheKey;
|
|
2077
|
+
return typeof value2 === "string" ? value2 : void 0;
|
|
2078
|
+
};
|
|
2079
|
+
var textVerbosity = (request2) => {
|
|
2080
|
+
const value2 = options(request2)?.textVerbosity;
|
|
2081
|
+
return isTextVerbosity(value2) ? value2 : void 0;
|
|
2082
|
+
};
|
|
2083
|
+
|
|
2084
|
+
// src/protocols/utils/tool-stream.ts
|
|
2085
|
+
var tool_stream_exports = {};
|
|
2086
|
+
__export(tool_stream_exports, {
|
|
2087
|
+
ToolStream: () => tool_stream_exports,
|
|
2088
|
+
appendExisting: () => appendExisting,
|
|
2089
|
+
appendOrStart: () => appendOrStart,
|
|
2090
|
+
empty: () => empty,
|
|
2091
|
+
finish: () => finish,
|
|
2092
|
+
finishAll: () => finishAll,
|
|
2093
|
+
finishWithInput: () => finishWithInput,
|
|
2094
|
+
isError: () => isError,
|
|
2095
|
+
start: () => start
|
|
2096
|
+
});
|
|
2097
|
+
var empty = () => ({});
|
|
2098
|
+
var withTool = (tools, key, tool2) => {
|
|
2099
|
+
return { ...tools, [key]: tool2 };
|
|
2100
|
+
};
|
|
2101
|
+
var withoutTool = (tools, key) => {
|
|
2102
|
+
const next = { ...tools };
|
|
2103
|
+
delete next[key];
|
|
2104
|
+
return next;
|
|
2105
|
+
};
|
|
2106
|
+
var inputDelta = (tool2, text2) => LLMEvent.toolInputDelta({
|
|
2107
|
+
id: tool2.id,
|
|
2108
|
+
name: tool2.name,
|
|
2109
|
+
text: text2
|
|
2110
|
+
});
|
|
2111
|
+
var toolCall = (route3, tool2, inputOverride) => parseToolInput(route3, tool2.name, inputOverride ?? tool2.input).pipe(
|
|
2112
|
+
Effect.map(
|
|
2113
|
+
(input) => LLMEvent.toolCall({
|
|
2114
|
+
id: tool2.id,
|
|
2115
|
+
name: tool2.name,
|
|
2116
|
+
input,
|
|
2117
|
+
providerExecuted: tool2.providerExecuted ? true : void 0,
|
|
2118
|
+
providerMetadata: tool2.providerMetadata
|
|
2119
|
+
})
|
|
2120
|
+
)
|
|
2121
|
+
);
|
|
2122
|
+
var appendTool = (tools, key, tool2, text2) => ({
|
|
2123
|
+
tools: withTool(tools, key, tool2),
|
|
2124
|
+
tool: tool2,
|
|
2125
|
+
event: text2.length === 0 ? void 0 : inputDelta(tool2, text2)
|
|
2126
|
+
});
|
|
2127
|
+
var isError = (result) => result instanceof LLMError;
|
|
2128
|
+
var start = (tools, key, tool2) => withTool(tools, key, { ...tool2, input: tool2.input ?? "" });
|
|
2129
|
+
var appendOrStart = (route3, tools, key, delta, missingToolMessage) => {
|
|
2130
|
+
const current = tools[key];
|
|
2131
|
+
const id3 = delta.id ?? current?.id;
|
|
2132
|
+
const name = delta.name ?? current?.name;
|
|
2133
|
+
if (!id3 || !name) return eventError(route3, missingToolMessage);
|
|
2134
|
+
const tool2 = {
|
|
2135
|
+
id: id3,
|
|
2136
|
+
name,
|
|
2137
|
+
input: `${current?.input ?? ""}${delta.text}`,
|
|
2138
|
+
providerExecuted: current?.providerExecuted,
|
|
2139
|
+
providerMetadata: current?.providerMetadata
|
|
2140
|
+
};
|
|
2141
|
+
if (current && delta.text.length === 0 && current.id === id3 && current.name === name) return { tools, tool: current };
|
|
2142
|
+
return appendTool(tools, key, tool2, delta.text);
|
|
2143
|
+
};
|
|
2144
|
+
var appendExisting = (route3, tools, key, text2, missingToolMessage) => {
|
|
2145
|
+
const current = tools[key];
|
|
2146
|
+
if (!current) return eventError(route3, missingToolMessage);
|
|
2147
|
+
if (text2.length === 0) return { tools, tool: current };
|
|
2148
|
+
return appendTool(tools, key, { ...current, input: `${current.input}${text2}` }, text2);
|
|
2149
|
+
};
|
|
2150
|
+
var finish = (route3, tools, key) => Effect.gen(function* () {
|
|
2151
|
+
const tool2 = tools[key];
|
|
2152
|
+
if (!tool2) return { tools };
|
|
2153
|
+
return { tools: withoutTool(tools, key), event: yield* toolCall(route3, tool2) };
|
|
2154
|
+
});
|
|
2155
|
+
var finishWithInput = (route3, tools, key, input) => Effect.gen(function* () {
|
|
2156
|
+
const tool2 = tools[key];
|
|
2157
|
+
if (!tool2) return { tools };
|
|
2158
|
+
return { tools: withoutTool(tools, key), event: yield* toolCall(route3, tool2, input) };
|
|
2159
|
+
});
|
|
2160
|
+
var finishAll = (route3, tools) => Effect.gen(function* () {
|
|
2161
|
+
const pending = Object.values(tools).filter(
|
|
2162
|
+
(tool2) => tool2 !== void 0
|
|
2163
|
+
);
|
|
2164
|
+
return {
|
|
2165
|
+
tools: empty(),
|
|
2166
|
+
events: yield* Effect.forEach(pending, (tool2) => toolCall(route3, tool2))
|
|
2167
|
+
};
|
|
2168
|
+
});
|
|
2169
|
+
|
|
2170
|
+
// src/protocols/openai-chat.ts
|
|
2171
|
+
var ADAPTER = "openai-chat";
|
|
2172
|
+
var DEFAULT_BASE_URL = "https://api.openai.com/v1";
|
|
2173
|
+
var PATH = "/chat/completions";
|
|
2174
|
+
var OpenAIChatFunction = Schema.Struct({
|
|
2175
|
+
name: Schema.String,
|
|
2176
|
+
description: Schema.String,
|
|
2177
|
+
parameters: JsonObject
|
|
2178
|
+
});
|
|
2179
|
+
var OpenAIChatTool = Schema.Struct({
|
|
2180
|
+
type: Schema.tag("function"),
|
|
2181
|
+
function: OpenAIChatFunction
|
|
2182
|
+
});
|
|
2183
|
+
var OpenAIChatAssistantToolCall = Schema.Struct({
|
|
2184
|
+
id: Schema.String,
|
|
2185
|
+
type: Schema.tag("function"),
|
|
2186
|
+
function: Schema.Struct({
|
|
2187
|
+
name: Schema.String,
|
|
2188
|
+
arguments: Schema.String
|
|
2189
|
+
})
|
|
2190
|
+
});
|
|
2191
|
+
var OpenAIChatUserContentText = Schema.Struct({
|
|
2192
|
+
type: Schema.Literal("text"),
|
|
2193
|
+
text: Schema.String
|
|
2194
|
+
});
|
|
2195
|
+
var OpenAIChatUserContentImageUrl = Schema.Struct({
|
|
2196
|
+
type: Schema.Literal("image_url"),
|
|
2197
|
+
image_url: Schema.Struct({ url: Schema.String })
|
|
2198
|
+
});
|
|
2199
|
+
var OpenAIChatUserContentPart = Schema.Union([OpenAIChatUserContentText, OpenAIChatUserContentImageUrl]).pipe(
|
|
2200
|
+
Schema.toTaggedUnion("type")
|
|
2201
|
+
);
|
|
2202
|
+
var OpenAIChatUserContent = Schema.Union([Schema.String, Schema.Array(OpenAIChatUserContentPart)]);
|
|
2203
|
+
var OpenAIChatMessage = Schema.Union([
|
|
2204
|
+
Schema.Struct({ role: Schema.Literal("system"), content: Schema.String }),
|
|
2205
|
+
Schema.Struct({ role: Schema.Literal("user"), content: OpenAIChatUserContent }),
|
|
2206
|
+
Schema.Struct({
|
|
2207
|
+
role: Schema.Literal("assistant"),
|
|
2208
|
+
content: Schema.NullOr(Schema.String),
|
|
2209
|
+
tool_calls: optionalArray(OpenAIChatAssistantToolCall),
|
|
2210
|
+
reasoning_content: Schema.optional(Schema.String)
|
|
2211
|
+
}),
|
|
2212
|
+
Schema.Struct({ role: Schema.Literal("tool"), tool_call_id: Schema.String, content: Schema.String })
|
|
2213
|
+
]).pipe(Schema.toTaggedUnion("role"));
|
|
2214
|
+
var OpenAIChatToolChoice = Schema.Union([
|
|
2215
|
+
Schema.Literals(["auto", "none", "required"]),
|
|
2216
|
+
Schema.Struct({
|
|
2217
|
+
type: Schema.tag("function"),
|
|
2218
|
+
function: Schema.Struct({ name: Schema.String })
|
|
2219
|
+
})
|
|
2220
|
+
]);
|
|
2221
|
+
var bodyFields = {
|
|
2222
|
+
model: Schema.String,
|
|
2223
|
+
messages: Schema.Array(OpenAIChatMessage),
|
|
2224
|
+
tools: optionalArray(OpenAIChatTool),
|
|
2225
|
+
tool_choice: Schema.optional(OpenAIChatToolChoice),
|
|
2226
|
+
stream: Schema.Literal(true),
|
|
2227
|
+
stream_options: Schema.optional(Schema.Struct({ include_usage: Schema.Boolean })),
|
|
2228
|
+
store: Schema.optional(Schema.Boolean),
|
|
2229
|
+
reasoning_effort: Schema.optional(openai_options_exports.OpenAIReasoningEffort),
|
|
2230
|
+
max_tokens: Schema.optional(Schema.Number),
|
|
2231
|
+
temperature: Schema.optional(Schema.Number),
|
|
2232
|
+
top_p: Schema.optional(Schema.Number),
|
|
2233
|
+
frequency_penalty: Schema.optional(Schema.Number),
|
|
2234
|
+
presence_penalty: Schema.optional(Schema.Number),
|
|
2235
|
+
seed: Schema.optional(Schema.Number),
|
|
2236
|
+
stop: optionalArray(Schema.String)
|
|
2237
|
+
};
|
|
2238
|
+
var OpenAIChatBody = Schema.Struct(bodyFields);
|
|
2239
|
+
var OpenAIChatUsage = Schema.Struct({
|
|
2240
|
+
prompt_tokens: Schema.optional(Schema.Number),
|
|
2241
|
+
completion_tokens: Schema.optional(Schema.Number),
|
|
2242
|
+
total_tokens: Schema.optional(Schema.Number),
|
|
2243
|
+
prompt_tokens_details: optionalNull(
|
|
2244
|
+
Schema.Struct({
|
|
2245
|
+
cached_tokens: Schema.optional(Schema.Number)
|
|
2246
|
+
})
|
|
2247
|
+
),
|
|
2248
|
+
completion_tokens_details: optionalNull(
|
|
2249
|
+
Schema.Struct({
|
|
2250
|
+
reasoning_tokens: Schema.optional(Schema.Number)
|
|
2251
|
+
})
|
|
2252
|
+
)
|
|
2253
|
+
});
|
|
2254
|
+
var OpenAIChatToolCallDeltaFunction = Schema.Struct({
|
|
2255
|
+
name: optionalNull(Schema.String),
|
|
2256
|
+
arguments: optionalNull(Schema.String)
|
|
2257
|
+
});
|
|
2258
|
+
var OpenAIChatToolCallDelta = Schema.Struct({
|
|
2259
|
+
index: Schema.Number,
|
|
2260
|
+
id: optionalNull(Schema.String),
|
|
2261
|
+
function: optionalNull(OpenAIChatToolCallDeltaFunction)
|
|
2262
|
+
});
|
|
2263
|
+
var OpenAIChatDelta = Schema.Struct({
|
|
2264
|
+
content: optionalNull(Schema.String),
|
|
2265
|
+
tool_calls: optionalNull(Schema.Array(OpenAIChatToolCallDelta))
|
|
2266
|
+
});
|
|
2267
|
+
var OpenAIChatChoice = Schema.Struct({
|
|
2268
|
+
delta: optionalNull(OpenAIChatDelta),
|
|
2269
|
+
finish_reason: optionalNull(Schema.String)
|
|
2270
|
+
});
|
|
2271
|
+
var OpenAIChatEvent = Schema.Struct({
|
|
2272
|
+
choices: Schema.Array(OpenAIChatChoice),
|
|
2273
|
+
usage: optionalNull(OpenAIChatUsage)
|
|
2274
|
+
});
|
|
2275
|
+
var invalid = shared_exports.invalidRequest;
|
|
2276
|
+
var lowerTool = (tool2) => ({
|
|
2277
|
+
type: "function",
|
|
2278
|
+
function: {
|
|
2279
|
+
name: tool2.name,
|
|
2280
|
+
description: tool2.description,
|
|
2281
|
+
parameters: tool2.inputSchema
|
|
2282
|
+
}
|
|
2283
|
+
});
|
|
2284
|
+
var lowerToolChoice = (toolChoice2) => shared_exports.matchToolChoice("OpenAI Chat", toolChoice2, {
|
|
2285
|
+
auto: () => "auto",
|
|
2286
|
+
none: () => "none",
|
|
2287
|
+
required: () => "required",
|
|
2288
|
+
tool: (name) => ({ type: "function", function: { name } })
|
|
2289
|
+
});
|
|
2290
|
+
var lowerToolCall = (part) => ({
|
|
2291
|
+
id: part.id,
|
|
2292
|
+
type: "function",
|
|
2293
|
+
function: {
|
|
2294
|
+
name: part.name,
|
|
2295
|
+
arguments: shared_exports.encodeJson(part.input)
|
|
2296
|
+
}
|
|
2297
|
+
});
|
|
2298
|
+
var openAICompatibleReasoningContent = (native) => isRecord3(native) && typeof native.reasoning_content === "string" ? native.reasoning_content : void 0;
|
|
2299
|
+
var mediaToImageUrl = (part) => {
|
|
2300
|
+
const data = part.data;
|
|
2301
|
+
if (typeof data === "string") {
|
|
2302
|
+
if (data.startsWith("http://") || data.startsWith("https://") || data.startsWith("data:") || data.startsWith("file://"))
|
|
2303
|
+
return data;
|
|
2304
|
+
return `data:${part.mediaType};base64,${data}`;
|
|
2305
|
+
}
|
|
2306
|
+
return `data:${part.mediaType};base64,${shared_exports.mediaBytes(part)}`;
|
|
2307
|
+
};
|
|
2308
|
+
var lowerUserMessage = Effect.fn("OpenAIChat.lowerUserMessage")(function* (message2) {
|
|
2309
|
+
const parts = [];
|
|
2310
|
+
let hasMedia = false;
|
|
2311
|
+
const textParts = [];
|
|
2312
|
+
for (const part of message2.content) {
|
|
2313
|
+
if (!shared_exports.supportsContent(part, ["text", "media"]))
|
|
2314
|
+
return yield* shared_exports.unsupportedContent("OpenAI Chat", "user", ["text", "media"]);
|
|
2315
|
+
if (part.type === "text") {
|
|
2316
|
+
textParts.push(part);
|
|
2317
|
+
parts.push({ type: "text", text: part.text });
|
|
2318
|
+
continue;
|
|
2319
|
+
}
|
|
2320
|
+
if (!part.mediaType.startsWith("image/"))
|
|
2321
|
+
return yield* shared_exports.invalidRequest(
|
|
2322
|
+
`OpenAI Chat user messages only support image/* media (received ${part.mediaType})`
|
|
2323
|
+
);
|
|
2324
|
+
hasMedia = true;
|
|
2325
|
+
parts.push({ type: "image_url", image_url: { url: mediaToImageUrl(part) } });
|
|
2326
|
+
}
|
|
2327
|
+
if (!hasMedia) return { role: "user", content: shared_exports.joinText(textParts) };
|
|
2328
|
+
return { role: "user", content: parts };
|
|
2329
|
+
});
|
|
2330
|
+
var lowerAssistantMessage = Effect.fn("OpenAIChat.lowerAssistantMessage")(function* (message2) {
|
|
2331
|
+
const content = [];
|
|
2332
|
+
const toolCalls = [];
|
|
2333
|
+
for (const part of message2.content) {
|
|
2334
|
+
if (!shared_exports.supportsContent(part, ["text", "tool-call"]))
|
|
2335
|
+
return yield* shared_exports.unsupportedContent("OpenAI Chat", "assistant", ["text", "tool-call"]);
|
|
2336
|
+
if (part.type === "text") {
|
|
2337
|
+
content.push(part);
|
|
2338
|
+
continue;
|
|
2339
|
+
}
|
|
2340
|
+
if (part.type === "tool-call") {
|
|
2341
|
+
toolCalls.push(lowerToolCall(part));
|
|
2342
|
+
continue;
|
|
2343
|
+
}
|
|
2344
|
+
}
|
|
2345
|
+
return {
|
|
2346
|
+
role: "assistant",
|
|
2347
|
+
content: content.length === 0 ? null : shared_exports.joinText(content),
|
|
2348
|
+
tool_calls: toolCalls.length === 0 ? void 0 : toolCalls,
|
|
2349
|
+
reasoning_content: openAICompatibleReasoningContent(message2.native?.openaiCompatible)
|
|
2350
|
+
};
|
|
2351
|
+
});
|
|
2352
|
+
var lowerToolMessages = Effect.fn("OpenAIChat.lowerToolMessages")(function* (message2) {
|
|
2353
|
+
const messages = [];
|
|
2354
|
+
for (const part of message2.content) {
|
|
2355
|
+
if (!shared_exports.supportsContent(part, ["tool-result"]))
|
|
2356
|
+
return yield* shared_exports.unsupportedContent("OpenAI Chat", "tool", ["tool-result"]);
|
|
2357
|
+
messages.push({ role: "tool", tool_call_id: part.id, content: shared_exports.toolResultText(part) });
|
|
2358
|
+
}
|
|
2359
|
+
return messages;
|
|
2360
|
+
});
|
|
2361
|
+
var lowerMessage = Effect.fn("OpenAIChat.lowerMessage")(function* (message2) {
|
|
2362
|
+
if (message2.role === "user") return [yield* lowerUserMessage(message2)];
|
|
2363
|
+
if (message2.role === "assistant") return [yield* lowerAssistantMessage(message2)];
|
|
2364
|
+
return yield* lowerToolMessages(message2);
|
|
2365
|
+
});
|
|
2366
|
+
var lowerMessages = Effect.fn("OpenAIChat.lowerMessages")(function* (request2) {
|
|
2367
|
+
const system2 = request2.system.length === 0 ? [] : [{ role: "system", content: shared_exports.joinText(request2.system) }];
|
|
2368
|
+
return [...system2, ...Array$1.flatten(yield* Effect.forEach(request2.messages, lowerMessage))];
|
|
2369
|
+
});
|
|
2370
|
+
var lowerOptions = Effect.fn("OpenAIChat.lowerOptions")(function* (request2) {
|
|
2371
|
+
const store2 = openai_options_exports.store(request2);
|
|
2372
|
+
const reasoningEffort2 = openai_options_exports.reasoningEffort(request2);
|
|
2373
|
+
if (reasoningEffort2 && !openai_options_exports.isReasoningEffort(reasoningEffort2))
|
|
2374
|
+
return yield* invalid(`OpenAI Chat does not support reasoning effort ${reasoningEffort2}`);
|
|
2375
|
+
return {
|
|
2376
|
+
...store2 !== void 0 ? { store: store2 } : {},
|
|
2377
|
+
...reasoningEffort2 ? { reasoning_effort: reasoningEffort2 } : {}
|
|
2378
|
+
};
|
|
2379
|
+
});
|
|
2380
|
+
var fromRequest = Effect.fn("OpenAIChat.fromRequest")(function* (request2) {
|
|
2381
|
+
const generation2 = request2.generation;
|
|
2382
|
+
return {
|
|
2383
|
+
model: request2.model.id,
|
|
2384
|
+
messages: yield* lowerMessages(request2),
|
|
2385
|
+
tools: request2.tools.length === 0 ? void 0 : request2.tools.map(lowerTool),
|
|
2386
|
+
tool_choice: request2.toolChoice ? yield* lowerToolChoice(request2.toolChoice) : void 0,
|
|
2387
|
+
stream: true,
|
|
2388
|
+
stream_options: { include_usage: true },
|
|
2389
|
+
max_tokens: generation2?.maxTokens,
|
|
2390
|
+
temperature: generation2?.temperature,
|
|
2391
|
+
top_p: generation2?.topP,
|
|
2392
|
+
frequency_penalty: generation2?.frequencyPenalty,
|
|
2393
|
+
presence_penalty: generation2?.presencePenalty,
|
|
2394
|
+
seed: generation2?.seed,
|
|
2395
|
+
stop: generation2?.stop,
|
|
2396
|
+
...yield* lowerOptions(request2)
|
|
2397
|
+
};
|
|
2398
|
+
});
|
|
2399
|
+
var mapFinishReason = (reason) => {
|
|
2400
|
+
if (reason === "stop") return "stop";
|
|
2401
|
+
if (reason === "length") return "length";
|
|
2402
|
+
if (reason === "content_filter") return "content-filter";
|
|
2403
|
+
if (reason === "function_call" || reason === "tool_calls") return "tool-calls";
|
|
2404
|
+
return "unknown";
|
|
2405
|
+
};
|
|
2406
|
+
var mapUsage = (usage) => {
|
|
2407
|
+
if (!usage) return void 0;
|
|
2408
|
+
const cached = usage.prompt_tokens_details?.cached_tokens;
|
|
2409
|
+
const reasoning = usage.completion_tokens_details?.reasoning_tokens;
|
|
2410
|
+
const nonCached = shared_exports.subtractTokens(usage.prompt_tokens, cached);
|
|
2411
|
+
return new Usage({
|
|
2412
|
+
inputTokens: usage.prompt_tokens,
|
|
2413
|
+
outputTokens: usage.completion_tokens,
|
|
2414
|
+
nonCachedInputTokens: nonCached,
|
|
2415
|
+
cacheReadInputTokens: cached,
|
|
2416
|
+
reasoningTokens: reasoning,
|
|
2417
|
+
totalTokens: shared_exports.totalTokens(usage.prompt_tokens, usage.completion_tokens, usage.total_tokens),
|
|
2418
|
+
providerMetadata: { openai: usage }
|
|
2419
|
+
});
|
|
2420
|
+
};
|
|
2421
|
+
var normaliseTextDelta = (prev, incoming) => {
|
|
2422
|
+
if (!incoming) return { emit: "", textAcc: prev };
|
|
2423
|
+
if (incoming === prev) return { emit: "", textAcc: prev };
|
|
2424
|
+
if (prev.length > 0 && incoming.startsWith(prev)) {
|
|
2425
|
+
return { emit: incoming.slice(prev.length), textAcc: incoming };
|
|
2426
|
+
}
|
|
2427
|
+
if (prev.length > 0 && prev.startsWith(incoming)) {
|
|
2428
|
+
return { emit: "", textAcc: prev };
|
|
2429
|
+
}
|
|
2430
|
+
return { emit: incoming, textAcc: prev + incoming };
|
|
2431
|
+
};
|
|
2432
|
+
var step = (state, event) => Effect.gen(function* () {
|
|
2433
|
+
const events = [];
|
|
2434
|
+
const usage = mapUsage(event.usage) ?? state.usage;
|
|
2435
|
+
const choice = event.choices[0];
|
|
2436
|
+
const finishReason = choice?.finish_reason ? mapFinishReason(choice.finish_reason) : state.finishReason;
|
|
2437
|
+
const delta = choice?.delta;
|
|
2438
|
+
const toolDeltas = delta?.tool_calls ?? [];
|
|
2439
|
+
let tools = state.tools;
|
|
2440
|
+
let textAcc = state.textAcc;
|
|
2441
|
+
if (delta?.content) {
|
|
2442
|
+
const normalised = normaliseTextDelta(textAcc, delta.content);
|
|
2443
|
+
textAcc = normalised.textAcc;
|
|
2444
|
+
if (normalised.emit) {
|
|
2445
|
+
events.push(LLMEvent.textDelta({ id: "text-0", text: normalised.emit }));
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
for (const tool2 of toolDeltas) {
|
|
2449
|
+
const result = tool_stream_exports.appendOrStart(
|
|
2450
|
+
ADAPTER,
|
|
2451
|
+
tools,
|
|
2452
|
+
tool2.index,
|
|
2453
|
+
{ id: tool2.id ?? void 0, name: tool2.function?.name ?? void 0, text: tool2.function?.arguments ?? "" },
|
|
2454
|
+
"OpenAI Chat tool call delta is missing id or name"
|
|
2455
|
+
);
|
|
2456
|
+
if (tool_stream_exports.isError(result)) return yield* result;
|
|
2457
|
+
tools = result.tools;
|
|
2458
|
+
if (result.event) events.push(result.event);
|
|
2459
|
+
}
|
|
2460
|
+
const finished = finishReason !== void 0 && state.finishReason === void 0 && Object.keys(tools).length > 0 ? yield* tool_stream_exports.finishAll(ADAPTER, tools) : void 0;
|
|
2461
|
+
return [
|
|
2462
|
+
{
|
|
2463
|
+
tools: finished?.tools ?? tools,
|
|
2464
|
+
toolCallEvents: finished?.events ?? state.toolCallEvents,
|
|
2465
|
+
usage,
|
|
2466
|
+
finishReason,
|
|
2467
|
+
textAcc
|
|
2468
|
+
},
|
|
2469
|
+
events
|
|
2470
|
+
];
|
|
2471
|
+
});
|
|
2472
|
+
var finishEvents = (state) => {
|
|
2473
|
+
const hasToolCalls = state.toolCallEvents.length > 0;
|
|
2474
|
+
const reason = state.finishReason === "stop" && hasToolCalls ? "tool-calls" : state.finishReason;
|
|
2475
|
+
return [...state.toolCallEvents, ...reason ? [LLMEvent.requestFinish({ reason, usage: state.usage })] : []];
|
|
2476
|
+
};
|
|
2477
|
+
var protocol = protocol_exports.make({
|
|
2478
|
+
id: ADAPTER,
|
|
2479
|
+
body: {
|
|
2480
|
+
schema: OpenAIChatBody,
|
|
2481
|
+
from: fromRequest
|
|
2482
|
+
},
|
|
2483
|
+
stream: {
|
|
2484
|
+
event: protocol_exports.jsonEvent(OpenAIChatEvent),
|
|
2485
|
+
initial: () => ({
|
|
2486
|
+
tools: tool_stream_exports.empty(),
|
|
2487
|
+
toolCallEvents: [],
|
|
2488
|
+
textAcc: ""
|
|
2489
|
+
}),
|
|
2490
|
+
step,
|
|
2491
|
+
onHalt: finishEvents
|
|
2492
|
+
}
|
|
2493
|
+
});
|
|
2494
|
+
var encodeBody = Schema.encodeSync(Schema.fromJsonString(OpenAIChatBody));
|
|
2495
|
+
var httpTransport = http_exports.httpJson({
|
|
2496
|
+
endpoint: endpoint_exports.path(PATH),
|
|
2497
|
+
auth: auth_exports.bearer(),
|
|
2498
|
+
framing: framing_exports.sse,
|
|
2499
|
+
encodeBody
|
|
2500
|
+
});
|
|
2501
|
+
var route = Route.make({
|
|
2502
|
+
id: ADAPTER,
|
|
2503
|
+
provider: "openai",
|
|
2504
|
+
protocol,
|
|
2505
|
+
transport: httpTransport,
|
|
2506
|
+
defaults: {
|
|
2507
|
+
baseURL: DEFAULT_BASE_URL
|
|
2508
|
+
}
|
|
2509
|
+
});
|
|
2510
|
+
var model2 = route.model;
|
|
2511
|
+
|
|
2512
|
+
// src/protocols/openai-compatible-chat.ts
|
|
2513
|
+
var openai_compatible_chat_exports = {};
|
|
2514
|
+
__export(openai_compatible_chat_exports, {
|
|
2515
|
+
OpenAICompatibleChat: () => openai_compatible_chat_exports,
|
|
2516
|
+
model: () => model3,
|
|
2517
|
+
route: () => route2
|
|
2518
|
+
});
|
|
2519
|
+
var ADAPTER2 = "openai-compatible-chat";
|
|
2520
|
+
var route2 = Route.make({
|
|
2521
|
+
id: ADAPTER2,
|
|
2522
|
+
protocol,
|
|
2523
|
+
endpoint: endpoint_exports.path("/chat/completions"),
|
|
2524
|
+
framing: framing_exports.sse
|
|
2525
|
+
});
|
|
2526
|
+
var model3 = Route.model(route2);
|
|
2527
|
+
|
|
2528
|
+
// src/provider.ts
|
|
2529
|
+
var provider_exports = {};
|
|
2530
|
+
__export(provider_exports, {
|
|
2531
|
+
Provider: () => provider_exports,
|
|
2532
|
+
make: () => make4
|
|
2533
|
+
});
|
|
2534
|
+
var make4 = (definition) => definition;
|
|
2535
|
+
|
|
2536
|
+
// src/providers/openai.ts
|
|
2537
|
+
var openai_exports = {};
|
|
2538
|
+
__export(openai_exports, {
|
|
2539
|
+
OpenAI: () => openai_exports,
|
|
2540
|
+
apis: () => apis,
|
|
2541
|
+
chat: () => chat,
|
|
2542
|
+
id: () => id,
|
|
2543
|
+
model: () => model4,
|
|
2544
|
+
provider: () => provider,
|
|
2545
|
+
routes: () => routes
|
|
2546
|
+
});
|
|
2547
|
+
|
|
2548
|
+
// src/providers/openai-options.ts
|
|
2549
|
+
var openai_options_exports2 = {};
|
|
2550
|
+
__export(openai_options_exports2, {
|
|
2551
|
+
OpenAIProviderOptions: () => openai_options_exports2,
|
|
2552
|
+
gpt5DefaultOptions: () => gpt5DefaultOptions,
|
|
2553
|
+
openAIDefaultOptions: () => openAIDefaultOptions,
|
|
2554
|
+
withOpenAIOptions: () => withOpenAIOptions
|
|
2555
|
+
});
|
|
2556
|
+
var definedEntries = (input) => Object.entries(input).filter((entry) => entry[1] !== void 0);
|
|
2557
|
+
var openAIProviderOptions = (options2) => {
|
|
2558
|
+
const openai = Object.fromEntries(
|
|
2559
|
+
definedEntries({
|
|
2560
|
+
store: options2?.store,
|
|
2561
|
+
promptCacheKey: options2?.promptCacheKey,
|
|
2562
|
+
reasoningEffort: options2?.reasoningEffort,
|
|
2563
|
+
reasoningSummary: options2?.reasoningSummary,
|
|
2564
|
+
includeEncryptedReasoning: options2?.includeEncryptedReasoning,
|
|
2565
|
+
textVerbosity: options2?.textVerbosity
|
|
2566
|
+
})
|
|
2567
|
+
);
|
|
2568
|
+
if (Object.keys(openai).length === 0) return void 0;
|
|
2569
|
+
return { openai };
|
|
2570
|
+
};
|
|
2571
|
+
var gpt5DefaultOptions = (modelID, options2 = {}) => {
|
|
2572
|
+
const id3 = modelID.toLowerCase();
|
|
2573
|
+
if (!id3.includes("gpt-5") || id3.includes("gpt-5-chat") || id3.includes("gpt-5-pro")) return void 0;
|
|
2574
|
+
return openAIProviderOptions({
|
|
2575
|
+
reasoningEffort: "medium",
|
|
2576
|
+
reasoningSummary: "auto",
|
|
2577
|
+
textVerbosity: options2.textVerbosity === true && id3.includes("gpt-5.") && !id3.includes("codex") && !id3.includes("-chat") ? "low" : void 0
|
|
2578
|
+
});
|
|
2579
|
+
};
|
|
2580
|
+
var openAIDefaultOptions = (modelID, options2 = {}) => mergeProviderOptions(openAIProviderOptions({ store: false }), gpt5DefaultOptions(modelID, options2));
|
|
2581
|
+
var withOpenAIOptions = (modelID, options2, defaults = {}) => {
|
|
2582
|
+
return {
|
|
2583
|
+
...options2,
|
|
2584
|
+
id: modelID,
|
|
2585
|
+
providerOptions: mergeProviderOptions(openAIDefaultOptions(modelID, defaults), options2.providerOptions)
|
|
2586
|
+
};
|
|
2587
|
+
};
|
|
2588
|
+
|
|
2589
|
+
// src/providers/openai.ts
|
|
2590
|
+
var id = ProviderID.make("openai");
|
|
2591
|
+
var routes = [route];
|
|
2592
|
+
var auth2 = (options2) => auth_options_exports.bearer(options2, "OPENAI_API_KEY");
|
|
2593
|
+
var chat = (id3, options2 = {}) => {
|
|
2594
|
+
const { apiKey: _, ...rest } = options2;
|
|
2595
|
+
return model2(withOpenAIOptions(id3, { ...rest, auth: auth2(options2) }));
|
|
2596
|
+
};
|
|
2597
|
+
var provider = provider_exports.make({
|
|
2598
|
+
id,
|
|
2599
|
+
model: chat,
|
|
2600
|
+
apis: { chat }
|
|
2601
|
+
});
|
|
2602
|
+
var model4 = provider.model;
|
|
2603
|
+
var apis = provider.apis;
|
|
2604
|
+
|
|
2605
|
+
// src/providers/openai-compatible.ts
|
|
2606
|
+
var openai_compatible_exports = {};
|
|
2607
|
+
__export(openai_compatible_exports, {
|
|
2608
|
+
OpenAICompatible: () => openai_compatible_exports,
|
|
2609
|
+
baseten: () => baseten,
|
|
2610
|
+
cerebras: () => cerebras,
|
|
2611
|
+
deepinfra: () => deepinfra,
|
|
2612
|
+
deepseek: () => deepseek,
|
|
2613
|
+
fireworks: () => fireworks,
|
|
2614
|
+
groq: () => groq,
|
|
2615
|
+
id: () => id2,
|
|
2616
|
+
lmstudio: () => lmstudio,
|
|
2617
|
+
model: () => model5,
|
|
2618
|
+
ollama: () => ollama,
|
|
2619
|
+
openrouter: () => openrouter,
|
|
2620
|
+
profileModel: () => profileModel,
|
|
2621
|
+
provider: () => provider2,
|
|
2622
|
+
routes: () => routes2,
|
|
2623
|
+
togetherai: () => togetherai,
|
|
2624
|
+
xai: () => xai
|
|
2625
|
+
});
|
|
2626
|
+
|
|
2627
|
+
// src/providers/openai-compatible-profile.ts
|
|
2628
|
+
var profiles = {
|
|
2629
|
+
baseten: { provider: "baseten", baseURL: "https://inference.baseten.co/v1" },
|
|
2630
|
+
cerebras: { provider: "cerebras", baseURL: "https://api.cerebras.ai/v1" },
|
|
2631
|
+
deepinfra: { provider: "deepinfra", baseURL: "https://api.deepinfra.com/v1/openai" },
|
|
2632
|
+
deepseek: { provider: "deepseek", baseURL: "https://api.deepseek.com/v1" },
|
|
2633
|
+
fireworks: { provider: "fireworks", baseURL: "https://api.fireworks.ai/inference/v1" },
|
|
2634
|
+
groq: { provider: "groq", baseURL: "https://api.groq.com/openai/v1" },
|
|
2635
|
+
openrouter: { provider: "openrouter", baseURL: "https://openrouter.ai/api/v1" },
|
|
2636
|
+
togetherai: { provider: "togetherai", baseURL: "https://api.together.xyz/v1" },
|
|
2637
|
+
xai: { provider: "xai", baseURL: "https://api.x.ai/v1" },
|
|
2638
|
+
ollama: { provider: "ollama", baseURL: "http://localhost:11434/v1" },
|
|
2639
|
+
lmstudio: { provider: "lmstudio", baseURL: "http://localhost:1234/v1" }
|
|
2640
|
+
};
|
|
2641
|
+
Object.fromEntries(
|
|
2642
|
+
Object.values(profiles).map((profile) => [profile.provider, profile])
|
|
2643
|
+
);
|
|
2644
|
+
|
|
2645
|
+
// src/providers/openai-compatible.ts
|
|
2646
|
+
var id2 = ProviderID.make("openai-compatible");
|
|
2647
|
+
var routes2 = [route2];
|
|
2648
|
+
var model5 = (id3, options2) => {
|
|
2649
|
+
return model3({
|
|
2650
|
+
...options2,
|
|
2651
|
+
id: id3,
|
|
2652
|
+
provider: ProviderID.make(options2.provider)
|
|
2653
|
+
});
|
|
2654
|
+
};
|
|
2655
|
+
var profileModel = (profile, id3, options2 = {}) => model3({
|
|
2656
|
+
...options2,
|
|
2657
|
+
id: id3,
|
|
2658
|
+
provider: profile.provider,
|
|
2659
|
+
baseURL: options2.baseURL ?? profile.baseURL
|
|
2660
|
+
});
|
|
2661
|
+
var define = (profile) => provider_exports.make({
|
|
2662
|
+
id: ProviderID.make(profile.provider),
|
|
2663
|
+
model: (id3, options2 = {}) => profileModel(profile, id3, options2)
|
|
2664
|
+
});
|
|
2665
|
+
var provider2 = provider_exports.make({
|
|
2666
|
+
id: id2,
|
|
2667
|
+
model: (id3, options2) => model5(id3, { ...options2, provider: options2.provider ?? "openai-compatible" })
|
|
2668
|
+
});
|
|
2669
|
+
var baseten = define(profiles.baseten);
|
|
2670
|
+
var cerebras = define(profiles.cerebras);
|
|
2671
|
+
var deepinfra = define(profiles.deepinfra);
|
|
2672
|
+
var deepseek = define(profiles.deepseek);
|
|
2673
|
+
var fireworks = define(profiles.fireworks);
|
|
2674
|
+
var groq = define(profiles.groq);
|
|
2675
|
+
var openrouter = define(profiles.openrouter);
|
|
2676
|
+
var togetherai = define(profiles.togetherai);
|
|
2677
|
+
var xai = define(profiles.xai);
|
|
2678
|
+
var ollama = define(profiles.ollama);
|
|
2679
|
+
var lmstudio = define(profiles.lmstudio);
|
|
2680
|
+
|
|
2681
|
+
// src/llm.ts
|
|
2682
|
+
var llm_exports = {};
|
|
2683
|
+
__export(llm_exports, {
|
|
2684
|
+
GenerateObjectResponse: () => GenerateObjectResponse,
|
|
2685
|
+
LLM: () => llm_exports,
|
|
2686
|
+
assistant: () => assistant,
|
|
2687
|
+
generate: () => generate2,
|
|
2688
|
+
generateObject: () => generateObject,
|
|
2689
|
+
generation: () => generation,
|
|
2690
|
+
hasToolCall: () => hasToolCall,
|
|
2691
|
+
limits: () => limits,
|
|
2692
|
+
message: () => message,
|
|
2693
|
+
model: () => model6,
|
|
2694
|
+
request: () => request,
|
|
2695
|
+
requestInput: () => requestInput,
|
|
2696
|
+
stepCountIs: () => stepCountIs2,
|
|
2697
|
+
stopWhenAny: () => stopWhenAny,
|
|
2698
|
+
stream: () => stream3,
|
|
2699
|
+
system: () => system,
|
|
2700
|
+
text: () => text,
|
|
2701
|
+
toolCall: () => toolCall2,
|
|
2702
|
+
toolChoice: () => toolChoice,
|
|
2703
|
+
toolChoiceName: () => toolChoiceName,
|
|
2704
|
+
toolDefinition: () => toolDefinition,
|
|
2705
|
+
toolMessage: () => toolMessage,
|
|
2706
|
+
toolResult: () => toolResult,
|
|
2707
|
+
updateRequest: () => updateRequest,
|
|
2708
|
+
user: () => user
|
|
2709
|
+
});
|
|
2710
|
+
var limits = modelLimits;
|
|
2711
|
+
var text = Message.text;
|
|
2712
|
+
var system = SystemPart.make;
|
|
2713
|
+
var message = Message.make;
|
|
2714
|
+
var user = Message.user;
|
|
2715
|
+
var assistant = Message.assistant;
|
|
2716
|
+
var model6 = modelRef;
|
|
2717
|
+
var toolDefinition = ToolDefinition.make;
|
|
2718
|
+
var toolCall2 = ToolCallPart.make;
|
|
2719
|
+
var toolResult = ToolResultPart.make;
|
|
2720
|
+
var toolMessage = Message.tool;
|
|
2721
|
+
var toolChoiceName = ToolChoice.named;
|
|
2722
|
+
var toolChoice = ToolChoice.make;
|
|
2723
|
+
var generation = GenerationOptions.make;
|
|
2724
|
+
var generate2 = LLMClient.generate;
|
|
2725
|
+
var stream3 = LLMClient.stream;
|
|
2726
|
+
var stepCountIs2 = LLMClient.stepCountIs;
|
|
2727
|
+
var requestInput = (input) => ({
|
|
2728
|
+
...LLMRequest.input(input)
|
|
2729
|
+
});
|
|
2730
|
+
var request = (input) => {
|
|
2731
|
+
const {
|
|
2732
|
+
system: requestSystem,
|
|
2733
|
+
prompt,
|
|
2734
|
+
messages,
|
|
2735
|
+
tools,
|
|
2736
|
+
toolChoice: requestToolChoice,
|
|
2737
|
+
generation: requestGeneration,
|
|
2738
|
+
providerOptions: requestProviderOptions,
|
|
2739
|
+
http: requestHttp,
|
|
2740
|
+
...rest
|
|
2741
|
+
} = input;
|
|
2742
|
+
return new LLMRequest({
|
|
2743
|
+
...rest,
|
|
2744
|
+
system: SystemPart.content(requestSystem),
|
|
2745
|
+
messages: [...messages?.map(message) ?? [], ...prompt === void 0 ? [] : [user(prompt)]],
|
|
2746
|
+
tools: tools?.map(toolDefinition) ?? [],
|
|
2747
|
+
toolChoice: requestToolChoice ? toolChoice(requestToolChoice) : void 0,
|
|
2748
|
+
generation: requestGeneration === void 0 ? void 0 : generation(requestGeneration),
|
|
2749
|
+
providerOptions: requestProviderOptions,
|
|
2750
|
+
http: requestHttp === void 0 ? void 0 : HttpOptions.make(requestHttp)
|
|
2751
|
+
});
|
|
2752
|
+
};
|
|
2753
|
+
var updateRequest = (input, patch) => request({ ...requestInput(input), ...patch });
|
|
2754
|
+
var GENERATE_OBJECT_TOOL_NAME = "generate_object";
|
|
2755
|
+
var GENERATE_OBJECT_TOOL_DESCRIPTION = "Return the structured result by calling this tool.";
|
|
2756
|
+
var GenerateObjectResponse = class {
|
|
2757
|
+
constructor(object, response) {
|
|
2758
|
+
this.object = object;
|
|
2759
|
+
this.response = response;
|
|
2760
|
+
}
|
|
2761
|
+
get events() {
|
|
2762
|
+
return this.response.events;
|
|
2763
|
+
}
|
|
2764
|
+
get usage() {
|
|
2765
|
+
return this.response.usage;
|
|
2766
|
+
}
|
|
2767
|
+
};
|
|
2768
|
+
var runGenerateObject = Effect.fn("LLM.generateObject")(function* (options2, tool2) {
|
|
2769
|
+
const baseRequest = request(options2);
|
|
2770
|
+
const generateRequest = LLMRequest.update(baseRequest, {
|
|
2771
|
+
toolChoice: ToolChoice.named(GENERATE_OBJECT_TOOL_NAME)
|
|
2772
|
+
});
|
|
2773
|
+
const response = yield* LLMClient.generate({
|
|
2774
|
+
request: generateRequest,
|
|
2775
|
+
tools: { [GENERATE_OBJECT_TOOL_NAME]: tool2 },
|
|
2776
|
+
toolExecution: "none"
|
|
2777
|
+
});
|
|
2778
|
+
const call = response.toolCalls.find(
|
|
2779
|
+
(event) => LLMEvent.is.toolCall(event) && event.name === GENERATE_OBJECT_TOOL_NAME
|
|
2780
|
+
);
|
|
2781
|
+
if (!call || !LLMEvent.is.toolCall(call))
|
|
2782
|
+
return yield* new LLMError({
|
|
2783
|
+
module: "LLM",
|
|
2784
|
+
method: "generateObject",
|
|
2785
|
+
reason: new InvalidProviderOutputReason({
|
|
2786
|
+
message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`
|
|
2787
|
+
})
|
|
2788
|
+
});
|
|
2789
|
+
const object = yield* tool2._decode(call.input).pipe(
|
|
2790
|
+
Effect.mapError(
|
|
2791
|
+
(error) => new LLMError({
|
|
2792
|
+
module: "LLM",
|
|
2793
|
+
method: "generateObject",
|
|
2794
|
+
reason: new InvalidProviderOutputReason({
|
|
2795
|
+
message: `generateObject: tool input failed schema decode: ${error.message}`
|
|
2796
|
+
})
|
|
2797
|
+
})
|
|
2798
|
+
)
|
|
2799
|
+
);
|
|
2800
|
+
return new GenerateObjectResponse(object, response);
|
|
2801
|
+
});
|
|
2802
|
+
function generateObject(options2) {
|
|
2803
|
+
if ("schema" in options2) {
|
|
2804
|
+
const { schema, ...rest2 } = options2;
|
|
2805
|
+
return runGenerateObject(
|
|
2806
|
+
rest2,
|
|
2807
|
+
make({
|
|
2808
|
+
description: GENERATE_OBJECT_TOOL_DESCRIPTION,
|
|
2809
|
+
parameters: schema,
|
|
2810
|
+
success: Schema.Unknown,
|
|
2811
|
+
execute: () => Effect.void
|
|
2812
|
+
})
|
|
2813
|
+
);
|
|
2814
|
+
}
|
|
2815
|
+
const { jsonSchema, ...rest } = options2;
|
|
2816
|
+
return runGenerateObject(
|
|
2817
|
+
rest,
|
|
2818
|
+
make({
|
|
2819
|
+
description: GENERATE_OBJECT_TOOL_DESCRIPTION,
|
|
2820
|
+
jsonSchema,
|
|
2821
|
+
execute: () => Effect.void
|
|
2822
|
+
})
|
|
2823
|
+
);
|
|
2824
|
+
}
|
|
2825
|
+
|
|
2826
|
+
// src/index.ts
|
|
2827
|
+
var VERSION = "0.0.1";
|
|
2828
|
+
|
|
2829
|
+
export { auth_exports as Auth, auth_options_exports as AuthOptions, AuthenticationReason, CacheHint, CachePolicy, CachePolicyObject, ContentBlockID, ContentPart, ContentPolicyReason, ContextOverflowReason, endpoint_exports as Endpoint, FinishReason, framing_exports as Framing, GenerationOptions, HttpContext, HttpOptions, HttpRateLimitDetails, HttpRequestDetails, HttpResponseDetails, http_exports as HttpTransport, InvalidProviderOutputReason, InvalidRequestReason, JsonSchema, llm_exports as LLM, LLMClient, LLMError, LLMErrorReason, LLMEvent, LLMRequest, LLMResponse, MediaPart, Message, MessageRole, MissingCredentialError, ModelID, ModelLimits, ModelRef, NoRouteReason, openai_exports as OpenAI, openai_chat_exports as OpenAIChat, openai_compatible_exports as OpenAICompatible, openai_compatible_chat_exports as OpenAICompatibleChat, openai_options_exports2 as OpenAIProviderOptions, PreparedRequest, protocol_exports as Protocol, ProtocolID, provider_exports as Provider, ProviderErrorEvent, ProviderID, ProviderInternalReason, ProviderMetadata, ProviderOptions, shared_exports as ProviderShared, QuotaExceededReason, RateLimitReason, ReasoningDelta, ReasoningEffort, ReasoningEfforts, ReasoningEnd, ReasoningPart, ReasoningStart, executor_exports as RequestExecutor, RequestFinish, RequestStart, ResponseFormat, ResponseID, Route, RouteID, StepFinish, StepStart, SystemPart, TextDelta, TextEnd, TextPart, TextStart, TextVerbosity, tool_exports as Tool, ToolCall, ToolCallID, ToolCallPart, ToolChoice, ToolDefinition, ToolError, ToolFailure, ToolInputDelta, ToolInputEnd, ToolInputStart, ToolResult, ToolResultPart, ToolResultValue, ToolRuntime, TransportReason, UnknownProviderReason, Usage, VERSION, extractOverflowNumbers, hasToolCall, isOverflowBody, isOverflowMessage, isOverflowStatus, make, mergeGenerationOptions, mergeHttpOptions, mergeJsonRecords, mergeProviderOptions, modelLimits, modelRef, profiles as openAICompatibleProfiles, stream as runtimeStream, stepCountIs, stopWhenAny, toDefinitions, tool };
|
|
2830
|
+
//# sourceMappingURL=index.js.map
|
|
2831
|
+
//# sourceMappingURL=index.js.map
|