@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/llm.js
ADDED
|
@@ -0,0 +1,1692 @@
|
|
|
1
|
+
import { Schema, Context, Layer, Effect, Stream, Random, Cause } from 'effect';
|
|
2
|
+
import { HttpClient, FetchHttpClient, Headers, HttpClientError } from 'effect/unstable/http';
|
|
3
|
+
import 'buffer';
|
|
4
|
+
import 'effect/unstable/encoding/Sse';
|
|
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
|
+
|
|
12
|
+
// src/llm.ts
|
|
13
|
+
var llm_exports = {};
|
|
14
|
+
__export(llm_exports, {
|
|
15
|
+
GenerateObjectResponse: () => GenerateObjectResponse,
|
|
16
|
+
LLM: () => llm_exports,
|
|
17
|
+
assistant: () => assistant,
|
|
18
|
+
generate: () => generate2,
|
|
19
|
+
generateObject: () => generateObject,
|
|
20
|
+
generation: () => generation,
|
|
21
|
+
hasToolCall: () => hasToolCall,
|
|
22
|
+
limits: () => limits,
|
|
23
|
+
message: () => message,
|
|
24
|
+
model: () => model,
|
|
25
|
+
request: () => request,
|
|
26
|
+
requestInput: () => requestInput,
|
|
27
|
+
stepCountIs: () => stepCountIs2,
|
|
28
|
+
stopWhenAny: () => stopWhenAny,
|
|
29
|
+
stream: () => stream3,
|
|
30
|
+
system: () => system,
|
|
31
|
+
text: () => text,
|
|
32
|
+
toolCall: () => toolCall,
|
|
33
|
+
toolChoice: () => toolChoice,
|
|
34
|
+
toolChoiceName: () => toolChoiceName,
|
|
35
|
+
toolDefinition: () => toolDefinition,
|
|
36
|
+
toolMessage: () => toolMessage,
|
|
37
|
+
toolResult: () => toolResult,
|
|
38
|
+
updateRequest: () => updateRequest,
|
|
39
|
+
user: () => user
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// src/route/executor.ts
|
|
43
|
+
var executor_exports = {};
|
|
44
|
+
__export(executor_exports, {
|
|
45
|
+
RequestExecutor: () => executor_exports,
|
|
46
|
+
Service: () => Service,
|
|
47
|
+
defaultLayer: () => defaultLayer,
|
|
48
|
+
layer: () => layer
|
|
49
|
+
});
|
|
50
|
+
var ProtocolID = Schema.String;
|
|
51
|
+
var RouteID = Schema.String;
|
|
52
|
+
var ModelID = Schema.String.pipe(Schema.brand("LLM.ModelID"));
|
|
53
|
+
var ProviderID = Schema.String.pipe(Schema.brand("LLM.ProviderID"));
|
|
54
|
+
var ResponseID = Schema.String;
|
|
55
|
+
var ContentBlockID = Schema.String;
|
|
56
|
+
var ToolCallID = Schema.String;
|
|
57
|
+
var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
58
|
+
Schema.Literals(ReasoningEfforts);
|
|
59
|
+
Schema.Literals(["low", "medium", "high"]);
|
|
60
|
+
var MessageRole = Schema.Literals(["user", "assistant", "tool"]);
|
|
61
|
+
var FinishReason = Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
|
|
62
|
+
var JsonSchema = Schema.Record(Schema.String, Schema.Unknown);
|
|
63
|
+
var ProviderMetadata = Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown));
|
|
64
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
65
|
+
var mergeJsonRecords = (...items) => {
|
|
66
|
+
const defined = items.filter((item) => item !== void 0);
|
|
67
|
+
if (defined.length === 0) return void 0;
|
|
68
|
+
if (defined.length === 1 && Object.values(defined[0]).every((value) => value !== void 0)) return defined[0];
|
|
69
|
+
const result = {};
|
|
70
|
+
for (const item of defined) {
|
|
71
|
+
for (const [key, value] of Object.entries(item)) {
|
|
72
|
+
if (value === void 0) continue;
|
|
73
|
+
result[key] = isRecord(result[key]) && isRecord(value) ? mergeJsonRecords(result[key], value) : value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
77
|
+
};
|
|
78
|
+
var mergeStringRecords = (...items) => {
|
|
79
|
+
const defined = items.filter((item) => item !== void 0);
|
|
80
|
+
if (defined.length === 0) return void 0;
|
|
81
|
+
if (defined.length === 1) return defined[0];
|
|
82
|
+
const result = Object.fromEntries(
|
|
83
|
+
defined.flatMap(
|
|
84
|
+
(item) => Object.entries(item).filter((entry) => entry[1] !== void 0)
|
|
85
|
+
)
|
|
86
|
+
);
|
|
87
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
88
|
+
};
|
|
89
|
+
var ProviderOptions = Schema.Record(Schema.String, Schema.Record(Schema.String, Schema.Unknown));
|
|
90
|
+
var mergeProviderOptions = (...items) => {
|
|
91
|
+
const result = {};
|
|
92
|
+
for (const item of items) {
|
|
93
|
+
if (!item) continue;
|
|
94
|
+
for (const [provider, options] of Object.entries(item)) {
|
|
95
|
+
const merged = mergeJsonRecords(result[provider], options);
|
|
96
|
+
if (merged) result[provider] = merged;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return Object.keys(result).length === 0 ? void 0 : result;
|
|
100
|
+
};
|
|
101
|
+
var HttpOptions = class extends Schema.Class("LLM.HttpOptions")({
|
|
102
|
+
body: Schema.optional(JsonSchema),
|
|
103
|
+
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
104
|
+
query: Schema.optional(Schema.Record(Schema.String, Schema.String))
|
|
105
|
+
}) {
|
|
106
|
+
};
|
|
107
|
+
((HttpOptions2) => {
|
|
108
|
+
HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
|
|
109
|
+
})(HttpOptions || (HttpOptions = {}));
|
|
110
|
+
var mergeHttpOptions = (...items) => {
|
|
111
|
+
const body = mergeJsonRecords(...items.map((item) => item?.body));
|
|
112
|
+
const headers = mergeStringRecords(...items.map((item) => item?.headers));
|
|
113
|
+
const query = mergeStringRecords(...items.map((item) => item?.query));
|
|
114
|
+
if (!body && !headers && !query) return void 0;
|
|
115
|
+
return new HttpOptions({ body, headers, query });
|
|
116
|
+
};
|
|
117
|
+
var GenerationOptions = class extends Schema.Class("LLM.GenerationOptions")({
|
|
118
|
+
maxTokens: Schema.optional(Schema.Number),
|
|
119
|
+
temperature: Schema.optional(Schema.Number),
|
|
120
|
+
topP: Schema.optional(Schema.Number),
|
|
121
|
+
topK: Schema.optional(Schema.Number),
|
|
122
|
+
frequencyPenalty: Schema.optional(Schema.Number),
|
|
123
|
+
presencePenalty: Schema.optional(Schema.Number),
|
|
124
|
+
seed: Schema.optional(Schema.Number),
|
|
125
|
+
stop: Schema.optional(Schema.Array(Schema.String))
|
|
126
|
+
}) {
|
|
127
|
+
};
|
|
128
|
+
((GenerationOptions2) => {
|
|
129
|
+
GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
|
|
130
|
+
})(GenerationOptions || (GenerationOptions = {}));
|
|
131
|
+
var latestGeneration = (items, key) => items.findLast((item) => item?.[key] !== void 0)?.[key];
|
|
132
|
+
var mergeGenerationOptions = (...items) => {
|
|
133
|
+
const result = new GenerationOptions({
|
|
134
|
+
maxTokens: latestGeneration(items, "maxTokens"),
|
|
135
|
+
temperature: latestGeneration(items, "temperature"),
|
|
136
|
+
topP: latestGeneration(items, "topP"),
|
|
137
|
+
topK: latestGeneration(items, "topK"),
|
|
138
|
+
frequencyPenalty: latestGeneration(items, "frequencyPenalty"),
|
|
139
|
+
presencePenalty: latestGeneration(items, "presencePenalty"),
|
|
140
|
+
seed: latestGeneration(items, "seed"),
|
|
141
|
+
stop: latestGeneration(items, "stop")
|
|
142
|
+
});
|
|
143
|
+
return Object.values(result).some((value) => value !== void 0) ? result : void 0;
|
|
144
|
+
};
|
|
145
|
+
var ModelLimits = class extends Schema.Class("LLM.ModelLimits")({
|
|
146
|
+
context: Schema.optional(Schema.Number),
|
|
147
|
+
output: Schema.optional(Schema.Number)
|
|
148
|
+
}) {
|
|
149
|
+
};
|
|
150
|
+
((ModelLimits2) => {
|
|
151
|
+
ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
|
|
152
|
+
})(ModelLimits || (ModelLimits = {}));
|
|
153
|
+
var ModelRef = class extends Schema.Class("LLM.ModelRef")({
|
|
154
|
+
id: ModelID,
|
|
155
|
+
provider: ProviderID,
|
|
156
|
+
route: RouteID,
|
|
157
|
+
baseURL: Schema.String,
|
|
158
|
+
/** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
|
|
159
|
+
apiKey: Schema.optional(Schema.String),
|
|
160
|
+
/** Optional transport auth policy. Opaque because it may contain functions. */
|
|
161
|
+
auth: Schema.optional(Schema.Any),
|
|
162
|
+
headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
163
|
+
/**
|
|
164
|
+
* Query params appended to the request URL by `Endpoint.baseURL`. Used for
|
|
165
|
+
* deployment-level URL-scoped settings such as Azure's `api-version` or any
|
|
166
|
+
* provider that requires a per-request key in the URL. Generic concern, so
|
|
167
|
+
* lives as a typed first-class field instead of `native`.
|
|
168
|
+
*/
|
|
169
|
+
queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
170
|
+
limits: ModelLimits,
|
|
171
|
+
/** Provider-neutral generation defaults. Request-level values override them. */
|
|
172
|
+
generation: Schema.optional(GenerationOptions),
|
|
173
|
+
/** Provider-owned typed-at-the-facade options for non-portable knobs. */
|
|
174
|
+
providerOptions: Schema.optional(ProviderOptions),
|
|
175
|
+
/** Serializable raw HTTP overlays applied to the final outgoing request. */
|
|
176
|
+
http: Schema.optional(HttpOptions),
|
|
177
|
+
/**
|
|
178
|
+
* Provider-specific opaque options. Reach for this only when the value is
|
|
179
|
+
* genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
|
|
180
|
+
* `aws_credentials` / `aws_region` for SigV4). Anything used by more than
|
|
181
|
+
* one route should grow into a typed field instead.
|
|
182
|
+
*/
|
|
183
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
184
|
+
}) {
|
|
185
|
+
};
|
|
186
|
+
((ModelRef2) => {
|
|
187
|
+
ModelRef2.input = (model2) => ({
|
|
188
|
+
id: model2.id,
|
|
189
|
+
provider: model2.provider,
|
|
190
|
+
route: model2.route,
|
|
191
|
+
baseURL: model2.baseURL,
|
|
192
|
+
apiKey: model2.apiKey,
|
|
193
|
+
auth: model2.auth,
|
|
194
|
+
headers: model2.headers,
|
|
195
|
+
queryParams: model2.queryParams,
|
|
196
|
+
limits: model2.limits,
|
|
197
|
+
generation: model2.generation,
|
|
198
|
+
providerOptions: model2.providerOptions,
|
|
199
|
+
http: model2.http,
|
|
200
|
+
native: model2.native
|
|
201
|
+
});
|
|
202
|
+
ModelRef2.update = (model2, patch) => {
|
|
203
|
+
if (Object.keys(patch).length === 0) return model2;
|
|
204
|
+
return new ModelRef2({
|
|
205
|
+
...(0, ModelRef2.input)(model2),
|
|
206
|
+
...patch
|
|
207
|
+
});
|
|
208
|
+
};
|
|
209
|
+
})(ModelRef || (ModelRef = {}));
|
|
210
|
+
var CacheHint = class extends Schema.Class("LLM.CacheHint")({
|
|
211
|
+
type: Schema.Literals(["ephemeral", "persistent"]),
|
|
212
|
+
ttlSeconds: Schema.optional(Schema.Number)
|
|
213
|
+
}) {
|
|
214
|
+
};
|
|
215
|
+
var CachePolicyObject = Schema.Struct({
|
|
216
|
+
tools: Schema.optional(Schema.Boolean),
|
|
217
|
+
system: Schema.optional(Schema.Boolean),
|
|
218
|
+
messages: Schema.optional(
|
|
219
|
+
Schema.Union([
|
|
220
|
+
Schema.Literal("latest-user-message"),
|
|
221
|
+
Schema.Literal("latest-assistant"),
|
|
222
|
+
Schema.Struct({ tail: Schema.Number })
|
|
223
|
+
])
|
|
224
|
+
),
|
|
225
|
+
ttlSeconds: Schema.optional(Schema.Number)
|
|
226
|
+
});
|
|
227
|
+
var CachePolicy = Schema.Union([Schema.Literal("auto"), Schema.Literal("none"), CachePolicyObject]);
|
|
228
|
+
var isRecord2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
229
|
+
var systemPartSchema = Schema.Struct({
|
|
230
|
+
type: Schema.Literal("text"),
|
|
231
|
+
text: Schema.String,
|
|
232
|
+
cache: Schema.optional(CacheHint),
|
|
233
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
234
|
+
}).annotate({ identifier: "LLM.SystemPart" });
|
|
235
|
+
var makeSystemPart = (text2) => ({ type: "text", text: text2 });
|
|
236
|
+
var SystemPart = Object.assign(systemPartSchema, {
|
|
237
|
+
make: makeSystemPart,
|
|
238
|
+
content: (input) => {
|
|
239
|
+
if (input === void 0) return [];
|
|
240
|
+
return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
var TextPart = Schema.Struct({
|
|
244
|
+
type: Schema.Literal("text"),
|
|
245
|
+
text: Schema.String,
|
|
246
|
+
cache: Schema.optional(CacheHint),
|
|
247
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
248
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
249
|
+
}).annotate({ identifier: "LLM.Content.Text" });
|
|
250
|
+
var MediaPart = Schema.Struct({
|
|
251
|
+
type: Schema.Literal("media"),
|
|
252
|
+
mediaType: Schema.String,
|
|
253
|
+
data: Schema.Union([Schema.String, Schema.Uint8Array]),
|
|
254
|
+
filename: Schema.optional(Schema.String),
|
|
255
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
256
|
+
}).annotate({ identifier: "LLM.Content.Media" });
|
|
257
|
+
var isToolResultValue = (value) => isRecord2(value) && (value.type === "text" || value.type === "json" || value.type === "error") && "value" in value;
|
|
258
|
+
var ToolResultValue = Object.assign(
|
|
259
|
+
Schema.Struct({
|
|
260
|
+
type: Schema.Literals(["json", "text", "error"]),
|
|
261
|
+
value: Schema.Unknown,
|
|
262
|
+
/** Optional structured payload (e.g. tool-interrupt metadata). */
|
|
263
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
264
|
+
}).annotate({ identifier: "LLM.ToolResult" }),
|
|
265
|
+
{
|
|
266
|
+
make: (value, type = "json", metadata) => {
|
|
267
|
+
if (isToolResultValue(value)) {
|
|
268
|
+
return metadata ? { ...value, metadata: { ...value.metadata ?? {}, ...metadata } } : value;
|
|
269
|
+
}
|
|
270
|
+
return metadata ? { type, value, metadata } : { type, value };
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
);
|
|
274
|
+
var ToolCallPart = Object.assign(
|
|
275
|
+
Schema.Struct({
|
|
276
|
+
type: Schema.Literal("tool-call"),
|
|
277
|
+
id: Schema.String,
|
|
278
|
+
name: Schema.String,
|
|
279
|
+
input: Schema.Unknown,
|
|
280
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
281
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
282
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
283
|
+
}).annotate({ identifier: "LLM.Content.ToolCall" }),
|
|
284
|
+
{
|
|
285
|
+
make: (input) => ({ type: "tool-call", ...input })
|
|
286
|
+
}
|
|
287
|
+
);
|
|
288
|
+
var ToolResultPart = Object.assign(
|
|
289
|
+
Schema.Struct({
|
|
290
|
+
type: Schema.Literal("tool-result"),
|
|
291
|
+
id: Schema.String,
|
|
292
|
+
name: Schema.String,
|
|
293
|
+
result: ToolResultValue,
|
|
294
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
295
|
+
cache: Schema.optional(CacheHint),
|
|
296
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
297
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
298
|
+
}).annotate({ identifier: "LLM.Content.ToolResult" }),
|
|
299
|
+
{
|
|
300
|
+
make: (input) => ({
|
|
301
|
+
type: "tool-result",
|
|
302
|
+
id: input.id,
|
|
303
|
+
name: input.name,
|
|
304
|
+
result: ToolResultValue.make(input.result, input.resultType),
|
|
305
|
+
providerExecuted: input.providerExecuted,
|
|
306
|
+
cache: input.cache,
|
|
307
|
+
metadata: input.metadata,
|
|
308
|
+
providerMetadata: input.providerMetadata
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
);
|
|
312
|
+
var ReasoningPart = Schema.Struct({
|
|
313
|
+
type: Schema.Literal("reasoning"),
|
|
314
|
+
text: Schema.String,
|
|
315
|
+
encrypted: Schema.optional(Schema.String),
|
|
316
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
317
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
318
|
+
}).annotate({ identifier: "LLM.Content.Reasoning" });
|
|
319
|
+
var ContentPart = Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
|
|
320
|
+
Schema.toTaggedUnion("type")
|
|
321
|
+
);
|
|
322
|
+
var Message = class extends Schema.Class("LLM.Message")({
|
|
323
|
+
id: Schema.optional(Schema.String),
|
|
324
|
+
role: MessageRole,
|
|
325
|
+
content: Schema.Array(ContentPart),
|
|
326
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
327
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
328
|
+
}) {
|
|
329
|
+
};
|
|
330
|
+
((Message2) => {
|
|
331
|
+
Message2.text = (value) => ({ type: "text", text: value });
|
|
332
|
+
Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
|
|
333
|
+
Message2.make = (input) => {
|
|
334
|
+
if (input instanceof Message2) return input;
|
|
335
|
+
return new Message2({ ...input, content: (0, Message2.content)(input.content) });
|
|
336
|
+
};
|
|
337
|
+
Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
|
|
338
|
+
Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
|
|
339
|
+
Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
|
|
340
|
+
})(Message || (Message = {}));
|
|
341
|
+
var ToolDefinition = class extends Schema.Class("LLM.ToolDefinition")({
|
|
342
|
+
name: Schema.String,
|
|
343
|
+
description: Schema.String,
|
|
344
|
+
inputSchema: JsonSchema,
|
|
345
|
+
cache: Schema.optional(CacheHint),
|
|
346
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
347
|
+
native: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
348
|
+
}) {
|
|
349
|
+
};
|
|
350
|
+
((ToolDefinition2) => {
|
|
351
|
+
ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
|
|
352
|
+
})(ToolDefinition || (ToolDefinition = {}));
|
|
353
|
+
var ToolChoice = class extends Schema.Class("LLM.ToolChoice")({
|
|
354
|
+
type: Schema.Literals(["auto", "none", "required", "tool"]),
|
|
355
|
+
name: Schema.optional(Schema.String)
|
|
356
|
+
}) {
|
|
357
|
+
};
|
|
358
|
+
((ToolChoice2) => {
|
|
359
|
+
const isMode = (value) => value === "auto" || value === "none" || value === "required";
|
|
360
|
+
ToolChoice2.named = (value) => new ToolChoice2({ type: "tool", name: value });
|
|
361
|
+
ToolChoice2.make = (input) => {
|
|
362
|
+
if (input instanceof ToolChoice2) return input;
|
|
363
|
+
if (input instanceof ToolDefinition) return (0, ToolChoice2.named)(input.name);
|
|
364
|
+
if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
|
|
365
|
+
return new ToolChoice2(input);
|
|
366
|
+
};
|
|
367
|
+
})(ToolChoice || (ToolChoice = {}));
|
|
368
|
+
var ResponseFormat = Schema.Union([
|
|
369
|
+
Schema.Struct({ type: Schema.Literal("text") }),
|
|
370
|
+
Schema.Struct({ type: Schema.Literal("json"), schema: JsonSchema }),
|
|
371
|
+
Schema.Struct({ type: Schema.Literal("tool"), tool: ToolDefinition })
|
|
372
|
+
]).pipe(Schema.toTaggedUnion("type"));
|
|
373
|
+
var LLMRequest = class extends Schema.Class("LLM.Request")({
|
|
374
|
+
id: Schema.optional(Schema.String),
|
|
375
|
+
model: ModelRef,
|
|
376
|
+
system: Schema.Array(SystemPart),
|
|
377
|
+
messages: Schema.Array(Message),
|
|
378
|
+
tools: Schema.Array(ToolDefinition),
|
|
379
|
+
toolChoice: Schema.optional(ToolChoice),
|
|
380
|
+
generation: Schema.optional(GenerationOptions),
|
|
381
|
+
providerOptions: Schema.optional(ProviderOptions),
|
|
382
|
+
http: Schema.optional(HttpOptions),
|
|
383
|
+
responseFormat: Schema.optional(ResponseFormat),
|
|
384
|
+
cache: Schema.optional(CachePolicy),
|
|
385
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
386
|
+
}) {
|
|
387
|
+
};
|
|
388
|
+
((LLMRequest2) => {
|
|
389
|
+
LLMRequest2.input = (request2) => ({
|
|
390
|
+
id: request2.id,
|
|
391
|
+
model: request2.model,
|
|
392
|
+
system: request2.system,
|
|
393
|
+
messages: request2.messages,
|
|
394
|
+
tools: request2.tools,
|
|
395
|
+
toolChoice: request2.toolChoice,
|
|
396
|
+
generation: request2.generation,
|
|
397
|
+
providerOptions: request2.providerOptions,
|
|
398
|
+
http: request2.http,
|
|
399
|
+
responseFormat: request2.responseFormat,
|
|
400
|
+
cache: request2.cache,
|
|
401
|
+
metadata: request2.metadata
|
|
402
|
+
});
|
|
403
|
+
LLMRequest2.update = (request2, patch) => {
|
|
404
|
+
if (Object.keys(patch).length === 0) return request2;
|
|
405
|
+
return new LLMRequest2({
|
|
406
|
+
...(0, LLMRequest2.input)(request2),
|
|
407
|
+
...patch,
|
|
408
|
+
model: patch.model ?? request2.model
|
|
409
|
+
});
|
|
410
|
+
};
|
|
411
|
+
})(LLMRequest || (LLMRequest = {}));
|
|
412
|
+
var Usage = class extends Schema.Class("LLM.Usage")({
|
|
413
|
+
inputTokens: Schema.optional(Schema.Number),
|
|
414
|
+
outputTokens: Schema.optional(Schema.Number),
|
|
415
|
+
nonCachedInputTokens: Schema.optional(Schema.Number),
|
|
416
|
+
cacheReadInputTokens: Schema.optional(Schema.Number),
|
|
417
|
+
cacheWriteInputTokens: Schema.optional(Schema.Number),
|
|
418
|
+
reasoningTokens: Schema.optional(Schema.Number),
|
|
419
|
+
totalTokens: Schema.optional(Schema.Number),
|
|
420
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
421
|
+
}) {
|
|
422
|
+
/**
|
|
423
|
+
* Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
|
|
424
|
+
* to zero. The one place subtraction happens in this contract; the clamp
|
|
425
|
+
* means a provider reporting `reasoningTokens > outputTokens` produces a
|
|
426
|
+
* harmless zero rather than a negative that crashes downstream schemas.
|
|
427
|
+
*/
|
|
428
|
+
get visibleOutputTokens() {
|
|
429
|
+
return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
var RequestStart = Schema.Struct({
|
|
433
|
+
type: Schema.tag("request-start"),
|
|
434
|
+
id: ResponseID,
|
|
435
|
+
model: ModelRef
|
|
436
|
+
}).annotate({ identifier: "LLM.Event.RequestStart" });
|
|
437
|
+
var StepStart = Schema.Struct({
|
|
438
|
+
type: Schema.tag("step-start"),
|
|
439
|
+
index: Schema.Number
|
|
440
|
+
}).annotate({ identifier: "LLM.Event.StepStart" });
|
|
441
|
+
var TextStart = Schema.Struct({
|
|
442
|
+
type: Schema.tag("text-start"),
|
|
443
|
+
id: ContentBlockID,
|
|
444
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
445
|
+
}).annotate({ identifier: "LLM.Event.TextStart" });
|
|
446
|
+
var TextDelta = Schema.Struct({
|
|
447
|
+
type: Schema.tag("text-delta"),
|
|
448
|
+
id: ContentBlockID,
|
|
449
|
+
text: Schema.String
|
|
450
|
+
}).annotate({ identifier: "LLM.Event.TextDelta" });
|
|
451
|
+
var TextEnd = Schema.Struct({
|
|
452
|
+
type: Schema.tag("text-end"),
|
|
453
|
+
id: ContentBlockID,
|
|
454
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
455
|
+
}).annotate({ identifier: "LLM.Event.TextEnd" });
|
|
456
|
+
var ReasoningStart = Schema.Struct({
|
|
457
|
+
type: Schema.tag("reasoning-start"),
|
|
458
|
+
id: ContentBlockID,
|
|
459
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
460
|
+
}).annotate({ identifier: "LLM.Event.ReasoningStart" });
|
|
461
|
+
var ReasoningDelta = Schema.Struct({
|
|
462
|
+
type: Schema.tag("reasoning-delta"),
|
|
463
|
+
id: ContentBlockID,
|
|
464
|
+
text: Schema.String
|
|
465
|
+
}).annotate({ identifier: "LLM.Event.ReasoningDelta" });
|
|
466
|
+
var ReasoningEnd = Schema.Struct({
|
|
467
|
+
type: Schema.tag("reasoning-end"),
|
|
468
|
+
id: ContentBlockID,
|
|
469
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
470
|
+
}).annotate({ identifier: "LLM.Event.ReasoningEnd" });
|
|
471
|
+
var ToolInputStart = Schema.Struct({
|
|
472
|
+
type: Schema.tag("tool-input-start"),
|
|
473
|
+
id: ToolCallID,
|
|
474
|
+
name: Schema.String,
|
|
475
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
476
|
+
}).annotate({ identifier: "LLM.Event.ToolInputStart" });
|
|
477
|
+
var ToolInputDelta = Schema.Struct({
|
|
478
|
+
type: Schema.tag("tool-input-delta"),
|
|
479
|
+
id: ToolCallID,
|
|
480
|
+
name: Schema.String,
|
|
481
|
+
text: Schema.String
|
|
482
|
+
}).annotate({ identifier: "LLM.Event.ToolInputDelta" });
|
|
483
|
+
var ToolInputEnd = Schema.Struct({
|
|
484
|
+
type: Schema.tag("tool-input-end"),
|
|
485
|
+
id: ToolCallID,
|
|
486
|
+
name: Schema.String,
|
|
487
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
488
|
+
}).annotate({ identifier: "LLM.Event.ToolInputEnd" });
|
|
489
|
+
var ToolCall = Schema.Struct({
|
|
490
|
+
type: Schema.tag("tool-call"),
|
|
491
|
+
id: ToolCallID,
|
|
492
|
+
name: Schema.String,
|
|
493
|
+
input: Schema.Unknown,
|
|
494
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
495
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
496
|
+
}).annotate({ identifier: "LLM.Event.ToolCall" });
|
|
497
|
+
var ToolResult = Schema.Struct({
|
|
498
|
+
type: Schema.tag("tool-result"),
|
|
499
|
+
id: ToolCallID,
|
|
500
|
+
name: Schema.String,
|
|
501
|
+
result: ToolResultValue,
|
|
502
|
+
providerExecuted: Schema.optional(Schema.Boolean),
|
|
503
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
504
|
+
}).annotate({ identifier: "LLM.Event.ToolResult" });
|
|
505
|
+
var ToolError = Schema.Struct({
|
|
506
|
+
type: Schema.tag("tool-error"),
|
|
507
|
+
id: ToolCallID,
|
|
508
|
+
name: Schema.String,
|
|
509
|
+
message: Schema.String,
|
|
510
|
+
/** Optional structured payload (e.g. tool-interrupt metadata for approval). */
|
|
511
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown)),
|
|
512
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
513
|
+
}).annotate({ identifier: "LLM.Event.ToolError" });
|
|
514
|
+
var StepFinish = Schema.Struct({
|
|
515
|
+
type: Schema.tag("step-finish"),
|
|
516
|
+
index: Schema.Number,
|
|
517
|
+
reason: FinishReason,
|
|
518
|
+
usage: Schema.optional(Usage),
|
|
519
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
520
|
+
}).annotate({ identifier: "LLM.Event.StepFinish" });
|
|
521
|
+
var RequestFinish = Schema.Struct({
|
|
522
|
+
type: Schema.tag("request-finish"),
|
|
523
|
+
reason: FinishReason,
|
|
524
|
+
usage: Schema.optional(Usage),
|
|
525
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
526
|
+
}).annotate({ identifier: "LLM.Event.RequestFinish" });
|
|
527
|
+
var ProviderErrorEvent = Schema.Struct({
|
|
528
|
+
type: Schema.tag("provider-error"),
|
|
529
|
+
message: Schema.String,
|
|
530
|
+
retryable: Schema.optional(Schema.Boolean),
|
|
531
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
532
|
+
}).annotate({ identifier: "LLM.Event.ProviderError" });
|
|
533
|
+
var llmEventTagged = Schema.Union([
|
|
534
|
+
RequestStart,
|
|
535
|
+
StepStart,
|
|
536
|
+
TextStart,
|
|
537
|
+
TextDelta,
|
|
538
|
+
TextEnd,
|
|
539
|
+
ReasoningStart,
|
|
540
|
+
ReasoningDelta,
|
|
541
|
+
ReasoningEnd,
|
|
542
|
+
ToolInputStart,
|
|
543
|
+
ToolInputDelta,
|
|
544
|
+
ToolInputEnd,
|
|
545
|
+
ToolCall,
|
|
546
|
+
ToolResult,
|
|
547
|
+
ToolError,
|
|
548
|
+
StepFinish,
|
|
549
|
+
RequestFinish,
|
|
550
|
+
ProviderErrorEvent
|
|
551
|
+
]).pipe(Schema.toTaggedUnion("type"));
|
|
552
|
+
var responseID = (value) => ResponseID.make(value);
|
|
553
|
+
var contentBlockID = (value) => ContentBlockID.make(value);
|
|
554
|
+
var toolCallID = (value) => ToolCallID.make(value);
|
|
555
|
+
var LLMEvent = Object.assign(llmEventTagged, {
|
|
556
|
+
requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
|
|
557
|
+
stepStart: StepStart.make,
|
|
558
|
+
textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
559
|
+
textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
560
|
+
textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
561
|
+
reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
562
|
+
reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
563
|
+
reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
564
|
+
toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
|
|
565
|
+
toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
|
|
566
|
+
toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
|
|
567
|
+
toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
|
|
568
|
+
toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
|
|
569
|
+
toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
|
|
570
|
+
stepFinish: StepFinish.make,
|
|
571
|
+
requestFinish: RequestFinish.make,
|
|
572
|
+
providerError: ProviderErrorEvent.make,
|
|
573
|
+
is: {
|
|
574
|
+
requestStart: llmEventTagged.guards["request-start"],
|
|
575
|
+
stepStart: llmEventTagged.guards["step-start"],
|
|
576
|
+
textStart: llmEventTagged.guards["text-start"],
|
|
577
|
+
textDelta: llmEventTagged.guards["text-delta"],
|
|
578
|
+
textEnd: llmEventTagged.guards["text-end"],
|
|
579
|
+
reasoningStart: llmEventTagged.guards["reasoning-start"],
|
|
580
|
+
reasoningDelta: llmEventTagged.guards["reasoning-delta"],
|
|
581
|
+
reasoningEnd: llmEventTagged.guards["reasoning-end"],
|
|
582
|
+
toolInputStart: llmEventTagged.guards["tool-input-start"],
|
|
583
|
+
toolInputDelta: llmEventTagged.guards["tool-input-delta"],
|
|
584
|
+
toolInputEnd: llmEventTagged.guards["tool-input-end"],
|
|
585
|
+
toolCall: llmEventTagged.guards["tool-call"],
|
|
586
|
+
toolResult: llmEventTagged.guards["tool-result"],
|
|
587
|
+
toolError: llmEventTagged.guards["tool-error"],
|
|
588
|
+
stepFinish: llmEventTagged.guards["step-finish"],
|
|
589
|
+
requestFinish: llmEventTagged.guards["request-finish"],
|
|
590
|
+
providerError: llmEventTagged.guards["provider-error"]
|
|
591
|
+
}
|
|
592
|
+
});
|
|
593
|
+
var PreparedRequest = class extends Schema.Class("LLM.PreparedRequest")({
|
|
594
|
+
id: Schema.String,
|
|
595
|
+
route: RouteID,
|
|
596
|
+
protocol: ProtocolID,
|
|
597
|
+
model: ModelRef,
|
|
598
|
+
body: Schema.Unknown,
|
|
599
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
600
|
+
}) {
|
|
601
|
+
};
|
|
602
|
+
var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
|
|
603
|
+
var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
|
|
604
|
+
var responseUsage = (events) => events.reduce(
|
|
605
|
+
(usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
|
|
606
|
+
void 0
|
|
607
|
+
);
|
|
608
|
+
var LLMResponse = class extends Schema.Class("LLM.Response")({
|
|
609
|
+
events: Schema.Array(LLMEvent),
|
|
610
|
+
usage: Schema.optional(Usage)
|
|
611
|
+
}) {
|
|
612
|
+
/** Concatenated assistant text assembled from streamed `text-delta` events. */
|
|
613
|
+
get text() {
|
|
614
|
+
return responseText(this.events);
|
|
615
|
+
}
|
|
616
|
+
/** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
|
|
617
|
+
get reasoning() {
|
|
618
|
+
return responseReasoning(this.events);
|
|
619
|
+
}
|
|
620
|
+
/** Completed tool calls emitted by the provider. */
|
|
621
|
+
get toolCalls() {
|
|
622
|
+
return this.events.filter(LLMEvent.is.toolCall);
|
|
623
|
+
}
|
|
624
|
+
};
|
|
625
|
+
((LLMResponse3) => {
|
|
626
|
+
LLMResponse3.text = (response) => responseText(response.events);
|
|
627
|
+
LLMResponse3.usage = (response) => response.usage ?? responseUsage(response.events);
|
|
628
|
+
LLMResponse3.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
|
|
629
|
+
LLMResponse3.reasoning = (response) => responseReasoning(response.events);
|
|
630
|
+
})(LLMResponse || (LLMResponse = {}));
|
|
631
|
+
var HttpRequestDetails = class extends Schema.Class("LLM.HttpRequestDetails")({
|
|
632
|
+
method: Schema.String,
|
|
633
|
+
url: Schema.String,
|
|
634
|
+
headers: Schema.Record(Schema.String, Schema.String)
|
|
635
|
+
}) {
|
|
636
|
+
};
|
|
637
|
+
var HttpResponseDetails = class extends Schema.Class("LLM.HttpResponseDetails")({
|
|
638
|
+
status: Schema.Number,
|
|
639
|
+
headers: Schema.Record(Schema.String, Schema.String)
|
|
640
|
+
}) {
|
|
641
|
+
};
|
|
642
|
+
var HttpRateLimitDetails = class extends Schema.Class("LLM.HttpRateLimitDetails")({
|
|
643
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
644
|
+
limit: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
645
|
+
remaining: Schema.optional(Schema.Record(Schema.String, Schema.String)),
|
|
646
|
+
reset: Schema.optional(Schema.Record(Schema.String, Schema.String))
|
|
647
|
+
}) {
|
|
648
|
+
};
|
|
649
|
+
var HttpContext = class extends Schema.Class("LLM.HttpContext")({
|
|
650
|
+
request: HttpRequestDetails,
|
|
651
|
+
response: Schema.optional(HttpResponseDetails),
|
|
652
|
+
body: Schema.optional(Schema.String),
|
|
653
|
+
bodyTruncated: Schema.optional(Schema.Boolean),
|
|
654
|
+
requestId: Schema.optional(Schema.String),
|
|
655
|
+
rateLimit: Schema.optional(HttpRateLimitDetails)
|
|
656
|
+
}) {
|
|
657
|
+
};
|
|
658
|
+
var InvalidRequestReason = class extends Schema.Class("LLM.Error.InvalidRequest")({
|
|
659
|
+
_tag: Schema.tag("InvalidRequest"),
|
|
660
|
+
message: Schema.String,
|
|
661
|
+
parameter: Schema.optional(Schema.String),
|
|
662
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
663
|
+
http: Schema.optional(HttpContext)
|
|
664
|
+
}) {
|
|
665
|
+
get retryable() {
|
|
666
|
+
return false;
|
|
667
|
+
}
|
|
668
|
+
};
|
|
669
|
+
var ContextOverflowReason = class extends Schema.Class("LLM.Error.ContextOverflow")({
|
|
670
|
+
_tag: Schema.tag("ContextOverflow"),
|
|
671
|
+
message: Schema.String,
|
|
672
|
+
/** Provider-reported prompt token count when present in the error body. */
|
|
673
|
+
promptTokens: Schema.optional(Schema.Number),
|
|
674
|
+
/** Provider-reported context window size when present in the error body. */
|
|
675
|
+
contextWindow: Schema.optional(Schema.Number),
|
|
676
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
677
|
+
http: Schema.optional(HttpContext)
|
|
678
|
+
}) {
|
|
679
|
+
get retryable() {
|
|
680
|
+
return false;
|
|
681
|
+
}
|
|
682
|
+
};
|
|
683
|
+
var NoRouteReason = class extends Schema.Class("LLM.Error.NoRoute")({
|
|
684
|
+
_tag: Schema.tag("NoRoute"),
|
|
685
|
+
route: RouteID,
|
|
686
|
+
provider: ProviderID,
|
|
687
|
+
model: ModelID
|
|
688
|
+
}) {
|
|
689
|
+
get retryable() {
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
get message() {
|
|
693
|
+
return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
var AuthenticationReason = class extends Schema.Class("LLM.Error.Authentication")({
|
|
697
|
+
_tag: Schema.tag("Authentication"),
|
|
698
|
+
message: Schema.String,
|
|
699
|
+
kind: Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
|
|
700
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
701
|
+
http: Schema.optional(HttpContext)
|
|
702
|
+
}) {
|
|
703
|
+
get retryable() {
|
|
704
|
+
return false;
|
|
705
|
+
}
|
|
706
|
+
};
|
|
707
|
+
var RateLimitReason = class extends Schema.Class("LLM.Error.RateLimit")({
|
|
708
|
+
_tag: Schema.tag("RateLimit"),
|
|
709
|
+
message: Schema.String,
|
|
710
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
711
|
+
rateLimit: Schema.optional(HttpRateLimitDetails),
|
|
712
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
713
|
+
http: Schema.optional(HttpContext)
|
|
714
|
+
}) {
|
|
715
|
+
get retryable() {
|
|
716
|
+
return true;
|
|
717
|
+
}
|
|
718
|
+
};
|
|
719
|
+
var QuotaExceededReason = class extends Schema.Class("LLM.Error.QuotaExceeded")({
|
|
720
|
+
_tag: Schema.tag("QuotaExceeded"),
|
|
721
|
+
message: Schema.String,
|
|
722
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
723
|
+
http: Schema.optional(HttpContext)
|
|
724
|
+
}) {
|
|
725
|
+
get retryable() {
|
|
726
|
+
return false;
|
|
727
|
+
}
|
|
728
|
+
};
|
|
729
|
+
var ContentPolicyReason = class extends Schema.Class("LLM.Error.ContentPolicy")({
|
|
730
|
+
_tag: Schema.tag("ContentPolicy"),
|
|
731
|
+
message: Schema.String,
|
|
732
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
733
|
+
http: Schema.optional(HttpContext)
|
|
734
|
+
}) {
|
|
735
|
+
get retryable() {
|
|
736
|
+
return false;
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
var ProviderInternalReason = class extends Schema.Class("LLM.Error.ProviderInternal")({
|
|
740
|
+
_tag: Schema.tag("ProviderInternal"),
|
|
741
|
+
message: Schema.String,
|
|
742
|
+
status: Schema.Number,
|
|
743
|
+
retryAfterMs: Schema.optional(Schema.Number),
|
|
744
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
745
|
+
http: Schema.optional(HttpContext)
|
|
746
|
+
}) {
|
|
747
|
+
get retryable() {
|
|
748
|
+
return true;
|
|
749
|
+
}
|
|
750
|
+
};
|
|
751
|
+
var TransportReason = class extends Schema.Class("LLM.Error.Transport")({
|
|
752
|
+
_tag: Schema.tag("Transport"),
|
|
753
|
+
message: Schema.String,
|
|
754
|
+
kind: Schema.optional(Schema.String),
|
|
755
|
+
url: Schema.optional(Schema.String),
|
|
756
|
+
http: Schema.optional(HttpContext)
|
|
757
|
+
}) {
|
|
758
|
+
get retryable() {
|
|
759
|
+
return false;
|
|
760
|
+
}
|
|
761
|
+
};
|
|
762
|
+
var InvalidProviderOutputReason = class extends Schema.Class(
|
|
763
|
+
"LLM.Error.InvalidProviderOutput"
|
|
764
|
+
)({
|
|
765
|
+
_tag: Schema.tag("InvalidProviderOutput"),
|
|
766
|
+
message: Schema.String,
|
|
767
|
+
route: Schema.optional(Schema.String),
|
|
768
|
+
raw: Schema.optional(Schema.String),
|
|
769
|
+
providerMetadata: Schema.optional(ProviderMetadata)
|
|
770
|
+
}) {
|
|
771
|
+
get retryable() {
|
|
772
|
+
return false;
|
|
773
|
+
}
|
|
774
|
+
};
|
|
775
|
+
var UnknownProviderReason = class extends Schema.Class("LLM.Error.UnknownProvider")({
|
|
776
|
+
_tag: Schema.tag("UnknownProvider"),
|
|
777
|
+
message: Schema.String,
|
|
778
|
+
status: Schema.optional(Schema.Number),
|
|
779
|
+
providerMetadata: Schema.optional(ProviderMetadata),
|
|
780
|
+
http: Schema.optional(HttpContext)
|
|
781
|
+
}) {
|
|
782
|
+
get retryable() {
|
|
783
|
+
return false;
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
var LLMErrorReason = Schema.Union([
|
|
787
|
+
InvalidRequestReason,
|
|
788
|
+
ContextOverflowReason,
|
|
789
|
+
NoRouteReason,
|
|
790
|
+
AuthenticationReason,
|
|
791
|
+
RateLimitReason,
|
|
792
|
+
QuotaExceededReason,
|
|
793
|
+
ContentPolicyReason,
|
|
794
|
+
ProviderInternalReason,
|
|
795
|
+
TransportReason,
|
|
796
|
+
InvalidProviderOutputReason,
|
|
797
|
+
UnknownProviderReason
|
|
798
|
+
]).pipe(Schema.toTaggedUnion("_tag"));
|
|
799
|
+
var LLMError = class extends Schema.TaggedErrorClass()("LLM.Error", {
|
|
800
|
+
module: Schema.String,
|
|
801
|
+
method: Schema.String,
|
|
802
|
+
reason: LLMErrorReason
|
|
803
|
+
}) {
|
|
804
|
+
cause = this.reason;
|
|
805
|
+
get retryable() {
|
|
806
|
+
return this.reason.retryable;
|
|
807
|
+
}
|
|
808
|
+
get retryAfterMs() {
|
|
809
|
+
return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
|
|
810
|
+
}
|
|
811
|
+
get message() {
|
|
812
|
+
return `${this.module}.${this.method}: ${this.reason.message}`;
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
var ToolFailure = class extends Schema.TaggedErrorClass()("LLM.ToolFailure", {
|
|
816
|
+
message: Schema.String,
|
|
817
|
+
metadata: Schema.optional(Schema.Record(Schema.String, Schema.Unknown))
|
|
818
|
+
}) {
|
|
819
|
+
};
|
|
820
|
+
|
|
821
|
+
// src/route/overflow-detect.ts
|
|
822
|
+
var OVERFLOW_PATTERNS = [
|
|
823
|
+
/prompt is too long/i,
|
|
824
|
+
// Anthropic
|
|
825
|
+
/input is too long for requested model/i,
|
|
826
|
+
// Amazon Bedrock
|
|
827
|
+
/exceeds the context window/i,
|
|
828
|
+
// OpenAI
|
|
829
|
+
/input token count.*exceeds the maximum/i,
|
|
830
|
+
// Google (Gemini)
|
|
831
|
+
/maximum prompt length is \d+/i,
|
|
832
|
+
// xAI (Grok)
|
|
833
|
+
/reduce the length of the messages/i,
|
|
834
|
+
// Groq
|
|
835
|
+
/maximum context length is \d+ tokens/i,
|
|
836
|
+
// OpenRouter, DeepSeek, vLLM
|
|
837
|
+
/exceeds the limit of \d+/i,
|
|
838
|
+
// GitHub Copilot
|
|
839
|
+
/exceeds the available context size/i,
|
|
840
|
+
// llama.cpp server
|
|
841
|
+
/greater than the context length/i,
|
|
842
|
+
// LM Studio
|
|
843
|
+
/context window exceeds limit/i,
|
|
844
|
+
// MiniMax
|
|
845
|
+
/exceeded model token limit/i,
|
|
846
|
+
// Kimi, Moonshot
|
|
847
|
+
/context[_ ]length[_ ]exceeded/i,
|
|
848
|
+
// Generic OpenAI-style code
|
|
849
|
+
/request entity too large/i,
|
|
850
|
+
// HTTP 413
|
|
851
|
+
/context length is only \d+ tokens/i,
|
|
852
|
+
// vLLM
|
|
853
|
+
/input length.*exceeds.*context length/i,
|
|
854
|
+
// vLLM
|
|
855
|
+
/prompt too long; exceeded (?:max )?context length/i,
|
|
856
|
+
// Ollama
|
|
857
|
+
/too large for model with \d+ maximum context length/i,
|
|
858
|
+
// Mistral
|
|
859
|
+
/model_context_window_exceeded/i
|
|
860
|
+
// z.ai
|
|
861
|
+
];
|
|
862
|
+
var NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i;
|
|
863
|
+
var isOverflowMessage = (message2) => {
|
|
864
|
+
if (OVERFLOW_PATTERNS.some((p) => p.test(message2))) return true;
|
|
865
|
+
return NO_BODY_4XX.test(message2);
|
|
866
|
+
};
|
|
867
|
+
var isOverflowStatus = (status) => status === 413;
|
|
868
|
+
var TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i;
|
|
869
|
+
var PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i;
|
|
870
|
+
var INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i;
|
|
871
|
+
var extractOverflowNumbers = (message2) => {
|
|
872
|
+
const match = PROMPT_LENGTH.exec(message2) ?? INPUT_LIMIT.exec(message2) ?? TOKENS_GT_MAX.exec(message2);
|
|
873
|
+
if (!match) return void 0;
|
|
874
|
+
const promptTokens = Number(match[1]);
|
|
875
|
+
const contextWindow = Number(match[2]);
|
|
876
|
+
if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return void 0;
|
|
877
|
+
return { promptTokens, contextWindow };
|
|
878
|
+
};
|
|
879
|
+
var isOverflowBody = (body) => {
|
|
880
|
+
if (typeof body !== "object" || body === null) return false;
|
|
881
|
+
const root = body;
|
|
882
|
+
const code = root.error?.code ?? root.code;
|
|
883
|
+
if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true;
|
|
884
|
+
if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true;
|
|
885
|
+
return false;
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
// src/route/executor.ts
|
|
889
|
+
var Service = class extends Context.Service()("@tinyweb-agent/LLM/RequestExecutor") {
|
|
890
|
+
};
|
|
891
|
+
var BODY_LIMIT = 16384;
|
|
892
|
+
var MAX_RETRIES = 2;
|
|
893
|
+
var BASE_DELAY_MS = 500;
|
|
894
|
+
var MAX_DELAY_MS = 1e4;
|
|
895
|
+
var REDACTED = "<redacted>";
|
|
896
|
+
var SENSITIVE_NAME_SOURCE = "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature";
|
|
897
|
+
var SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i");
|
|
898
|
+
var SHORT_QUERY_NAME = /^(key|sig)$/i;
|
|
899
|
+
var SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i");
|
|
900
|
+
var REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi");
|
|
901
|
+
var REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi");
|
|
902
|
+
var isSensitiveHeaderName = (name) => SENSITIVE_NAME.test(name);
|
|
903
|
+
var isSensitiveQueryName = (name) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name);
|
|
904
|
+
var redactHeaders = (headers, redactedNames) => Object.fromEntries(
|
|
905
|
+
Object.entries(Headers.redact(headers, [...redactedNames, SENSITIVE_NAME])).map(([name, value]) => [
|
|
906
|
+
name,
|
|
907
|
+
String(value)
|
|
908
|
+
])
|
|
909
|
+
);
|
|
910
|
+
var redactUrl = (value) => {
|
|
911
|
+
if (!URL.canParse(value)) return REDACTED;
|
|
912
|
+
const url = new URL(value);
|
|
913
|
+
url.searchParams.forEach((_, key) => {
|
|
914
|
+
if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED);
|
|
915
|
+
});
|
|
916
|
+
return url.toString();
|
|
917
|
+
};
|
|
918
|
+
var normalizedHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
|
|
919
|
+
var requestId = (headers) => {
|
|
920
|
+
return headers["x-request-id"] ?? headers["request-id"] ?? headers["x-amzn-requestid"] ?? headers["x-amz-request-id"] ?? headers["x-goog-request-id"] ?? headers["cf-ray"];
|
|
921
|
+
};
|
|
922
|
+
var retryableStatus = (status) => status === 429 || status === 503 || status === 504 || status === 529;
|
|
923
|
+
var retryAfterMs = (headers) => {
|
|
924
|
+
const millis = Number(headers["retry-after-ms"]);
|
|
925
|
+
if (Number.isFinite(millis)) return Math.max(0, millis);
|
|
926
|
+
const value = headers["retry-after"];
|
|
927
|
+
if (!value) return void 0;
|
|
928
|
+
const seconds = Number(value);
|
|
929
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
930
|
+
const date = Date.parse(value);
|
|
931
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
932
|
+
return void 0;
|
|
933
|
+
};
|
|
934
|
+
var addRateLimitValue = (target, key, value) => {
|
|
935
|
+
if (key.length > 0) target[key] = value;
|
|
936
|
+
};
|
|
937
|
+
var rateLimitDetails = (headers, retryAfter) => {
|
|
938
|
+
const limit = {};
|
|
939
|
+
const remaining = {};
|
|
940
|
+
const reset = {};
|
|
941
|
+
Object.entries(headers).forEach(([name, value]) => {
|
|
942
|
+
const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1];
|
|
943
|
+
if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value);
|
|
944
|
+
const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1];
|
|
945
|
+
if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value);
|
|
946
|
+
const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1];
|
|
947
|
+
if (openaiReset) return addRateLimitValue(reset, openaiReset, value);
|
|
948
|
+
const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name);
|
|
949
|
+
if (!anthropic) return;
|
|
950
|
+
if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value);
|
|
951
|
+
if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value);
|
|
952
|
+
return addRateLimitValue(reset, anthropic[1], value);
|
|
953
|
+
});
|
|
954
|
+
if (retryAfter === void 0 && Object.keys(limit).length === 0 && Object.keys(remaining).length === 0 && Object.keys(reset).length === 0)
|
|
955
|
+
return void 0;
|
|
956
|
+
return new HttpRateLimitDetails({
|
|
957
|
+
retryAfterMs: retryAfter,
|
|
958
|
+
limit: Object.keys(limit).length === 0 ? void 0 : limit,
|
|
959
|
+
remaining: Object.keys(remaining).length === 0 ? void 0 : remaining,
|
|
960
|
+
reset: Object.keys(reset).length === 0 ? void 0 : reset
|
|
961
|
+
});
|
|
962
|
+
};
|
|
963
|
+
var requestDetails = (request2, redactedNames) => new HttpRequestDetails({
|
|
964
|
+
method: request2.method,
|
|
965
|
+
url: redactUrl(request2.url),
|
|
966
|
+
headers: redactHeaders(request2.headers, redactedNames)
|
|
967
|
+
});
|
|
968
|
+
var responseDetails = (response, redactedNames) => new HttpResponseDetails({
|
|
969
|
+
status: response.status,
|
|
970
|
+
headers: redactHeaders(response.headers, redactedNames)
|
|
971
|
+
});
|
|
972
|
+
var secretValues = (request2) => {
|
|
973
|
+
const values = /* @__PURE__ */ new Set();
|
|
974
|
+
const add = (value) => {
|
|
975
|
+
if (value.length < 4) return;
|
|
976
|
+
values.add(value);
|
|
977
|
+
values.add(encodeURIComponent(value));
|
|
978
|
+
};
|
|
979
|
+
Object.entries(request2.headers).forEach(([name, value]) => {
|
|
980
|
+
if (!isSensitiveHeaderName(name)) return;
|
|
981
|
+
add(value);
|
|
982
|
+
const bearer = /^Bearer\s+(.+)$/i.exec(value)?.[1];
|
|
983
|
+
if (bearer) add(bearer);
|
|
984
|
+
});
|
|
985
|
+
if (!URL.canParse(request2.url)) return values;
|
|
986
|
+
new URL(request2.url).searchParams.forEach((value, key) => {
|
|
987
|
+
if (isSensitiveQueryName(key)) add(value);
|
|
988
|
+
});
|
|
989
|
+
return values;
|
|
990
|
+
};
|
|
991
|
+
var redactBody = (body, request2) => Array.from(secretValues(request2)).reduce(
|
|
992
|
+
(text2, secret) => text2.split(secret).join(REDACTED),
|
|
993
|
+
body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`)
|
|
994
|
+
);
|
|
995
|
+
var responseBody = (body, request2) => {
|
|
996
|
+
if (body === void 0) return {};
|
|
997
|
+
const redacted = redactBody(body, request2);
|
|
998
|
+
if (redacted.length <= BODY_LIMIT) return { body: redacted };
|
|
999
|
+
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true };
|
|
1000
|
+
};
|
|
1001
|
+
var providerMessage = (status, body) => {
|
|
1002
|
+
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`;
|
|
1003
|
+
return `Provider request failed with HTTP ${status}`;
|
|
1004
|
+
};
|
|
1005
|
+
var responseHttp = (input) => new HttpContext({
|
|
1006
|
+
request: requestDetails(input.request, input.redactedNames),
|
|
1007
|
+
response: responseDetails(input.response, input.redactedNames),
|
|
1008
|
+
...input.body,
|
|
1009
|
+
requestId: input.requestId,
|
|
1010
|
+
rateLimit: input.rateLimit
|
|
1011
|
+
});
|
|
1012
|
+
var parseJsonBody = (body) => {
|
|
1013
|
+
if (body.length === 0) return void 0;
|
|
1014
|
+
try {
|
|
1015
|
+
return JSON.parse(body);
|
|
1016
|
+
} catch {
|
|
1017
|
+
return void 0;
|
|
1018
|
+
}
|
|
1019
|
+
};
|
|
1020
|
+
var isOverflow = (status, message2, body) => {
|
|
1021
|
+
if (isOverflowStatus(status)) return true;
|
|
1022
|
+
if (isOverflowMessage(message2)) return true;
|
|
1023
|
+
if (body.length > 0 && isOverflowMessage(body)) return true;
|
|
1024
|
+
return isOverflowBody(parseJsonBody(body));
|
|
1025
|
+
};
|
|
1026
|
+
var overflowReason = (input) => {
|
|
1027
|
+
const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body);
|
|
1028
|
+
return new ContextOverflowReason({
|
|
1029
|
+
message: input.message,
|
|
1030
|
+
promptTokens: numbers?.promptTokens,
|
|
1031
|
+
contextWindow: numbers?.contextWindow,
|
|
1032
|
+
http: input.http
|
|
1033
|
+
});
|
|
1034
|
+
};
|
|
1035
|
+
var statusReason = (input) => {
|
|
1036
|
+
const body = input.http.body ?? "";
|
|
1037
|
+
if (isOverflow(input.status, input.message, body)) {
|
|
1038
|
+
return overflowReason({ message: input.message, body, http: input.http });
|
|
1039
|
+
}
|
|
1040
|
+
if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
|
|
1041
|
+
return new ContentPolicyReason({ message: input.message, http: input.http });
|
|
1042
|
+
}
|
|
1043
|
+
if (input.status === 401) {
|
|
1044
|
+
return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http });
|
|
1045
|
+
}
|
|
1046
|
+
if (input.status === 403) {
|
|
1047
|
+
return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http });
|
|
1048
|
+
}
|
|
1049
|
+
if (input.status === 429) {
|
|
1050
|
+
if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
|
|
1051
|
+
return new QuotaExceededReason({ message: input.message, http: input.http });
|
|
1052
|
+
}
|
|
1053
|
+
return new RateLimitReason({
|
|
1054
|
+
message: input.message,
|
|
1055
|
+
retryAfterMs: input.retryAfterMs,
|
|
1056
|
+
rateLimit: input.rateLimit,
|
|
1057
|
+
http: input.http
|
|
1058
|
+
});
|
|
1059
|
+
}
|
|
1060
|
+
if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
|
|
1061
|
+
return new InvalidRequestReason({ message: input.message, http: input.http });
|
|
1062
|
+
}
|
|
1063
|
+
if (input.status >= 500 || retryableStatus(input.status)) {
|
|
1064
|
+
return new ProviderInternalReason({
|
|
1065
|
+
message: input.message,
|
|
1066
|
+
status: input.status,
|
|
1067
|
+
retryAfterMs: input.retryAfterMs,
|
|
1068
|
+
http: input.http
|
|
1069
|
+
});
|
|
1070
|
+
}
|
|
1071
|
+
return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http });
|
|
1072
|
+
};
|
|
1073
|
+
var statusError = (request2, redactedNames) => (response) => Effect.gen(function* () {
|
|
1074
|
+
if (response.status < 400) return response;
|
|
1075
|
+
const body = yield* response.text.pipe(Effect.catch(() => Effect.void));
|
|
1076
|
+
const headers = normalizedHeaders(response.headers);
|
|
1077
|
+
const retryAfter = retryAfterMs(headers);
|
|
1078
|
+
const rateLimit = rateLimitDetails(headers, retryAfter);
|
|
1079
|
+
const details = responseBody(body, request2);
|
|
1080
|
+
return yield* new LLMError({
|
|
1081
|
+
module: "RequestExecutor",
|
|
1082
|
+
method: "execute",
|
|
1083
|
+
reason: statusReason({
|
|
1084
|
+
status: response.status,
|
|
1085
|
+
message: providerMessage(response.status, details),
|
|
1086
|
+
retryAfterMs: retryAfter,
|
|
1087
|
+
rateLimit,
|
|
1088
|
+
http: responseHttp({
|
|
1089
|
+
request: request2,
|
|
1090
|
+
response,
|
|
1091
|
+
redactedNames,
|
|
1092
|
+
body: details,
|
|
1093
|
+
requestId: requestId(headers),
|
|
1094
|
+
rateLimit
|
|
1095
|
+
})
|
|
1096
|
+
})
|
|
1097
|
+
});
|
|
1098
|
+
});
|
|
1099
|
+
var toHttpError = (redactedNames) => (error) => {
|
|
1100
|
+
const transportError = (input) => new LLMError({
|
|
1101
|
+
module: "RequestExecutor",
|
|
1102
|
+
method: "execute",
|
|
1103
|
+
reason: new TransportReason({
|
|
1104
|
+
message: input.message,
|
|
1105
|
+
kind: input.kind,
|
|
1106
|
+
url: input.request ? redactUrl(input.request.url) : void 0,
|
|
1107
|
+
http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : void 0
|
|
1108
|
+
})
|
|
1109
|
+
});
|
|
1110
|
+
if (Cause.isTimeoutError(error)) {
|
|
1111
|
+
return transportError({ message: error.message, kind: "Timeout" });
|
|
1112
|
+
}
|
|
1113
|
+
if (!HttpClientError.isHttpClientError(error)) {
|
|
1114
|
+
return transportError({ message: "HTTP transport failed" });
|
|
1115
|
+
}
|
|
1116
|
+
const request2 = "request" in error ? error.request : void 0;
|
|
1117
|
+
if (error.reason._tag === "TransportError") {
|
|
1118
|
+
return transportError({
|
|
1119
|
+
message: error.reason.description ?? "HTTP transport failed",
|
|
1120
|
+
kind: error.reason._tag,
|
|
1121
|
+
request: request2
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
return transportError({
|
|
1125
|
+
message: `HTTP transport failed: ${error.reason._tag}`,
|
|
1126
|
+
kind: error.reason._tag,
|
|
1127
|
+
request: request2
|
|
1128
|
+
});
|
|
1129
|
+
};
|
|
1130
|
+
var retryDelay = (error, attempt) => {
|
|
1131
|
+
if (error.retryAfterMs !== void 0) return Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS));
|
|
1132
|
+
return Random.nextBetween(
|
|
1133
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
|
|
1134
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS)
|
|
1135
|
+
).pipe(Effect.map((delay) => Math.round(delay)));
|
|
1136
|
+
};
|
|
1137
|
+
var retryStatusFailures = (effect, retries = MAX_RETRIES, attempt = 0) => Effect.catchTag(effect, "LLM.Error", (error) => {
|
|
1138
|
+
if (!error.retryable || retries <= 0) return Effect.fail(error);
|
|
1139
|
+
return retryDelay(error, attempt).pipe(
|
|
1140
|
+
Effect.flatMap((delay) => Effect.sleep(delay)),
|
|
1141
|
+
Effect.flatMap(() => retryStatusFailures(effect, retries - 1, attempt + 1))
|
|
1142
|
+
);
|
|
1143
|
+
});
|
|
1144
|
+
var layer = Layer.effect(
|
|
1145
|
+
Service,
|
|
1146
|
+
Effect.gen(function* () {
|
|
1147
|
+
const http = yield* HttpClient.HttpClient;
|
|
1148
|
+
const executeOnce = (request2) => Effect.gen(function* () {
|
|
1149
|
+
const redactedNames = yield* Headers.CurrentRedactedNames;
|
|
1150
|
+
return yield* http.execute(request2).pipe(Effect.mapError(toHttpError(redactedNames)), Effect.flatMap(statusError(request2, redactedNames)));
|
|
1151
|
+
});
|
|
1152
|
+
return Service.of({
|
|
1153
|
+
execute: (request2) => retryStatusFailures(executeOnce(request2))
|
|
1154
|
+
});
|
|
1155
|
+
})
|
|
1156
|
+
);
|
|
1157
|
+
var defaultLayer = layer.pipe(Layer.provide(FetchHttpClient.layer));
|
|
1158
|
+
var Json = Schema.fromJsonString(Schema.Unknown);
|
|
1159
|
+
Schema.decodeUnknownSync(Json);
|
|
1160
|
+
Schema.encodeSync(Json);
|
|
1161
|
+
Schema.Record(Schema.String, Schema.Unknown);
|
|
1162
|
+
var invalidRequest = (message2) => new LLMError({
|
|
1163
|
+
module: "ProviderShared",
|
|
1164
|
+
method: "request",
|
|
1165
|
+
reason: new InvalidRequestReason({ message: message2 })
|
|
1166
|
+
});
|
|
1167
|
+
var validateWith = (decode2) => (payload) => decode2(payload).pipe(Effect.mapError((error) => invalidRequest(error.message)));
|
|
1168
|
+
|
|
1169
|
+
// src/cache-policy.ts
|
|
1170
|
+
var AUTO = {
|
|
1171
|
+
tools: true,
|
|
1172
|
+
system: true,
|
|
1173
|
+
messages: "latest-user-message"
|
|
1174
|
+
};
|
|
1175
|
+
var NONE = {};
|
|
1176
|
+
var resolve = (policy) => {
|
|
1177
|
+
if (policy === void 0 || policy === "auto") return AUTO;
|
|
1178
|
+
if (policy === "none") return NONE;
|
|
1179
|
+
return policy;
|
|
1180
|
+
};
|
|
1181
|
+
var RESPECTS_INLINE_HINTS = /* @__PURE__ */ new Set([]);
|
|
1182
|
+
var makeHint = (ttlSeconds) => ttlSeconds !== void 0 ? new CacheHint({ type: "ephemeral", ttlSeconds }) : new CacheHint({ type: "ephemeral" });
|
|
1183
|
+
var markLastTool = (tools, hint) => {
|
|
1184
|
+
if (tools.length === 0) return tools;
|
|
1185
|
+
const last = tools.length - 1;
|
|
1186
|
+
if (tools[last].cache) return tools;
|
|
1187
|
+
return tools.map((tool, i) => i === last ? new ToolDefinition({ ...tool, cache: hint }) : tool);
|
|
1188
|
+
};
|
|
1189
|
+
var markLastSystem = (system2, hint) => {
|
|
1190
|
+
if (system2.length === 0) return system2;
|
|
1191
|
+
const last = system2.length - 1;
|
|
1192
|
+
if (system2[last].cache) return system2;
|
|
1193
|
+
return system2.map((part, i) => i === last ? { ...part, cache: hint } : part);
|
|
1194
|
+
};
|
|
1195
|
+
var lastIndexOfRole = (messages, role) => messages.findLastIndex((m) => m.role === role);
|
|
1196
|
+
var markMessageAt = (messages, index, hint) => {
|
|
1197
|
+
if (index < 0 || index >= messages.length) return messages;
|
|
1198
|
+
const target = messages[index];
|
|
1199
|
+
if (target.content.length === 0) return messages;
|
|
1200
|
+
const lastTextIndex = target.content.findLastIndex((part) => part.type === "text");
|
|
1201
|
+
const markAt = lastTextIndex >= 0 ? lastTextIndex : target.content.length - 1;
|
|
1202
|
+
const existing = target.content[markAt];
|
|
1203
|
+
if ("cache" in existing && existing.cache) return messages;
|
|
1204
|
+
const nextContent = target.content.map((part, i) => i === markAt ? { ...part, cache: hint } : part);
|
|
1205
|
+
const next = new Message({ ...target, content: nextContent });
|
|
1206
|
+
const result = messages.slice();
|
|
1207
|
+
result[index] = next;
|
|
1208
|
+
return result;
|
|
1209
|
+
};
|
|
1210
|
+
var markMessages = (messages, strategy, hint) => {
|
|
1211
|
+
if (messages.length === 0) return messages;
|
|
1212
|
+
if (strategy === "latest-user-message") return markMessageAt(messages, lastIndexOfRole(messages, "user"), hint);
|
|
1213
|
+
if (strategy === "latest-assistant") return markMessageAt(messages, lastIndexOfRole(messages, "assistant"), hint);
|
|
1214
|
+
const start = Math.max(0, messages.length - strategy.tail);
|
|
1215
|
+
let next = messages;
|
|
1216
|
+
for (let i = start; i < messages.length; i++) next = markMessageAt(next, i, hint);
|
|
1217
|
+
return next;
|
|
1218
|
+
};
|
|
1219
|
+
var applyCachePolicy = (request2) => {
|
|
1220
|
+
if (!RESPECTS_INLINE_HINTS.has(request2.model.route)) return request2;
|
|
1221
|
+
const policy = resolve(request2.cache);
|
|
1222
|
+
if (!policy.tools && !policy.system && !policy.messages) return request2;
|
|
1223
|
+
const hint = makeHint(policy.ttlSeconds);
|
|
1224
|
+
const tools = policy.tools ? markLastTool(request2.tools, hint) : request2.tools;
|
|
1225
|
+
const system2 = policy.system ? markLastSystem(request2.system, hint) : request2.system;
|
|
1226
|
+
const messages = policy.messages ? markMessages(request2.messages, policy.messages, hint) : request2.messages;
|
|
1227
|
+
if (tools === request2.tools && system2 === request2.system && messages === request2.messages) return request2;
|
|
1228
|
+
return LLMRequest.update(request2, { tools, system: system2, messages });
|
|
1229
|
+
};
|
|
1230
|
+
function make(config) {
|
|
1231
|
+
if ("jsonSchema" in config) {
|
|
1232
|
+
return {
|
|
1233
|
+
description: config.description,
|
|
1234
|
+
parameters: Schema.Unknown,
|
|
1235
|
+
success: Schema.Unknown,
|
|
1236
|
+
execute: config.execute,
|
|
1237
|
+
_decode: Effect.succeed,
|
|
1238
|
+
_encode: Effect.succeed,
|
|
1239
|
+
_definition: new ToolDefinition({
|
|
1240
|
+
name: "",
|
|
1241
|
+
description: config.description,
|
|
1242
|
+
inputSchema: config.jsonSchema
|
|
1243
|
+
})
|
|
1244
|
+
};
|
|
1245
|
+
}
|
|
1246
|
+
return {
|
|
1247
|
+
description: config.description,
|
|
1248
|
+
parameters: config.parameters,
|
|
1249
|
+
success: config.success,
|
|
1250
|
+
execute: config.execute,
|
|
1251
|
+
_decode: Schema.decodeUnknownEffect(config.parameters),
|
|
1252
|
+
_encode: Schema.encodeEffect(config.success),
|
|
1253
|
+
_definition: new ToolDefinition({
|
|
1254
|
+
name: "",
|
|
1255
|
+
description: config.description,
|
|
1256
|
+
inputSchema: toJsonSchema(config.parameters)
|
|
1257
|
+
})
|
|
1258
|
+
};
|
|
1259
|
+
}
|
|
1260
|
+
var toDefinitions = (tools) => Object.entries(tools).map(
|
|
1261
|
+
([name, item]) => new ToolDefinition({
|
|
1262
|
+
name,
|
|
1263
|
+
description: item._definition.description,
|
|
1264
|
+
inputSchema: item._definition.inputSchema
|
|
1265
|
+
})
|
|
1266
|
+
);
|
|
1267
|
+
var toJsonSchema = (schema) => {
|
|
1268
|
+
const document = Schema.toJsonSchemaDocument(schema);
|
|
1269
|
+
const base = Object.keys(document.definitions).length === 0 ? document.schema : { ...document.schema, $defs: document.definitions };
|
|
1270
|
+
return normalizeTopLevel(base);
|
|
1271
|
+
};
|
|
1272
|
+
var normalizeTopLevel = (s) => {
|
|
1273
|
+
if (!s || typeof s !== "object") {
|
|
1274
|
+
return { type: "object", properties: {}, additionalProperties: false };
|
|
1275
|
+
}
|
|
1276
|
+
const obj = s;
|
|
1277
|
+
if (obj.type === "object") return s;
|
|
1278
|
+
if (Array.isArray(obj.anyOf)) {
|
|
1279
|
+
const objectVariant = obj.anyOf.find(
|
|
1280
|
+
(v) => v != null && typeof v === "object" && v.type === "object"
|
|
1281
|
+
);
|
|
1282
|
+
if (objectVariant) {
|
|
1283
|
+
const { anyOf: _omit, ...rest } = obj;
|
|
1284
|
+
return { ...rest, ...objectVariant };
|
|
1285
|
+
}
|
|
1286
|
+
}
|
|
1287
|
+
return { type: "object", properties: {}, additionalProperties: false };
|
|
1288
|
+
};
|
|
1289
|
+
|
|
1290
|
+
// src/tool-runtime.ts
|
|
1291
|
+
var hasToolCall = (name) => (state) => state.toolCalls.some((call) => call.name === name);
|
|
1292
|
+
var stopWhenAny = (...conditions) => (state) => conditions.some((condition) => condition(state));
|
|
1293
|
+
var stepCountIs = (count) => (state) => state.step + 1 >= count;
|
|
1294
|
+
var stream = (options) => {
|
|
1295
|
+
const concurrency = options.concurrency ?? 10;
|
|
1296
|
+
const tools = options.tools;
|
|
1297
|
+
const runtimeTools = toDefinitions(tools);
|
|
1298
|
+
const runtimeToolNames = new Set(runtimeTools.map((tool) => tool.name));
|
|
1299
|
+
const initialRequest = runtimeTools.length === 0 ? options.request : LLMRequest.update(options.request, {
|
|
1300
|
+
tools: [...options.request.tools.filter((tool) => !runtimeToolNames.has(tool.name)), ...runtimeTools]
|
|
1301
|
+
});
|
|
1302
|
+
const loop = (request2, step) => Stream.unwrap(
|
|
1303
|
+
Effect.gen(function* () {
|
|
1304
|
+
const state = { assistantContent: [], toolCalls: [], finishReason: void 0 };
|
|
1305
|
+
const modelStream = options.stream(request2).pipe(Stream.tap((event) => Effect.sync(() => accumulate(state, event))));
|
|
1306
|
+
const continuation = Stream.unwrap(
|
|
1307
|
+
Effect.gen(function* () {
|
|
1308
|
+
if (state.finishReason !== "tool-calls" || state.toolCalls.length === 0) return Stream.empty;
|
|
1309
|
+
if (options.toolExecution === "none") return Stream.empty;
|
|
1310
|
+
const dispatched = yield* Effect.forEach(
|
|
1311
|
+
state.toolCalls,
|
|
1312
|
+
(call) => dispatch(tools, call).pipe(Effect.map((result) => [call, result])),
|
|
1313
|
+
{ concurrency }
|
|
1314
|
+
);
|
|
1315
|
+
const resultStream = Stream.fromIterable(dispatched.flatMap(([call, result]) => emitEvents(call, result)));
|
|
1316
|
+
if (dispatched.some(([, result]) => isInterruptResult(result))) return resultStream;
|
|
1317
|
+
if (!options.stopWhen) return resultStream;
|
|
1318
|
+
if (options.stopWhen({ step, request: request2, toolCalls: state.toolCalls })) return resultStream;
|
|
1319
|
+
const followUp = dispatched.filter(([, result]) => !isInterruptResult(result));
|
|
1320
|
+
if (followUp.length === 0) return resultStream;
|
|
1321
|
+
return resultStream.pipe(Stream.concat(loop(followUpRequest(request2, state, followUp), step + 1)));
|
|
1322
|
+
})
|
|
1323
|
+
);
|
|
1324
|
+
return modelStream.pipe(Stream.concat(continuation));
|
|
1325
|
+
})
|
|
1326
|
+
);
|
|
1327
|
+
return loop(initialRequest, 0);
|
|
1328
|
+
};
|
|
1329
|
+
var accumulate = (state, event) => {
|
|
1330
|
+
if (event.type === "text-delta") {
|
|
1331
|
+
appendStreamingText(state, "text", event.text, void 0);
|
|
1332
|
+
return;
|
|
1333
|
+
}
|
|
1334
|
+
if (event.type === "reasoning-delta") {
|
|
1335
|
+
appendStreamingText(state, "reasoning", event.text, void 0);
|
|
1336
|
+
return;
|
|
1337
|
+
}
|
|
1338
|
+
if (event.type === "reasoning-end") {
|
|
1339
|
+
appendStreamingText(state, "reasoning", "", event.providerMetadata);
|
|
1340
|
+
return;
|
|
1341
|
+
}
|
|
1342
|
+
if (event.type === "text-end") {
|
|
1343
|
+
appendStreamingText(state, "text", "", event.providerMetadata);
|
|
1344
|
+
return;
|
|
1345
|
+
}
|
|
1346
|
+
if (event.type === "tool-call") {
|
|
1347
|
+
const part = ToolCallPart.make({
|
|
1348
|
+
id: event.id,
|
|
1349
|
+
name: event.name,
|
|
1350
|
+
input: event.input,
|
|
1351
|
+
providerExecuted: event.providerExecuted,
|
|
1352
|
+
providerMetadata: event.providerMetadata
|
|
1353
|
+
});
|
|
1354
|
+
state.assistantContent.push(part);
|
|
1355
|
+
if (!event.providerExecuted) state.toolCalls.push(part);
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (event.type === "tool-result" && event.providerExecuted) {
|
|
1359
|
+
state.assistantContent.push(
|
|
1360
|
+
ToolResultPart.make({
|
|
1361
|
+
id: event.id,
|
|
1362
|
+
name: event.name,
|
|
1363
|
+
result: event.result,
|
|
1364
|
+
providerExecuted: true,
|
|
1365
|
+
providerMetadata: event.providerMetadata
|
|
1366
|
+
})
|
|
1367
|
+
);
|
|
1368
|
+
return;
|
|
1369
|
+
}
|
|
1370
|
+
if (event.type === "request-finish") {
|
|
1371
|
+
state.finishReason = event.reason;
|
|
1372
|
+
}
|
|
1373
|
+
};
|
|
1374
|
+
var sameProviderMetadata = (left, right) => left === right || JSON.stringify(left) === JSON.stringify(right);
|
|
1375
|
+
var mergeProviderMetadata = (left, right) => {
|
|
1376
|
+
if (!left) return right;
|
|
1377
|
+
if (!right) return left;
|
|
1378
|
+
return Object.fromEntries(
|
|
1379
|
+
Array.from(/* @__PURE__ */ new Set([...Object.keys(left), ...Object.keys(right)])).map((provider) => [
|
|
1380
|
+
provider,
|
|
1381
|
+
{ ...left[provider], ...right[provider] }
|
|
1382
|
+
])
|
|
1383
|
+
);
|
|
1384
|
+
};
|
|
1385
|
+
var appendStreamingText = (state, type, text2, providerMetadata) => {
|
|
1386
|
+
const last = state.assistantContent.at(-1);
|
|
1387
|
+
if (last?.type === type && text2.length === 0) {
|
|
1388
|
+
state.assistantContent[state.assistantContent.length - 1] = {
|
|
1389
|
+
...last,
|
|
1390
|
+
providerMetadata: mergeProviderMetadata(last.providerMetadata, providerMetadata)
|
|
1391
|
+
};
|
|
1392
|
+
return;
|
|
1393
|
+
}
|
|
1394
|
+
if (last?.type === type && sameProviderMetadata(last.providerMetadata, providerMetadata)) {
|
|
1395
|
+
state.assistantContent[state.assistantContent.length - 1] = { ...last, text: `${last.text}${text2}` };
|
|
1396
|
+
return;
|
|
1397
|
+
}
|
|
1398
|
+
state.assistantContent.push({ type, text: text2, providerMetadata });
|
|
1399
|
+
};
|
|
1400
|
+
var isInterruptResult = (result) => result.type === "error" && typeof result.metadata === "object" && result.metadata !== null && result.metadata.kind === "tool-interrupt";
|
|
1401
|
+
var dispatch = (tools, call) => {
|
|
1402
|
+
const tool = tools[call.name];
|
|
1403
|
+
if (!tool) return Effect.succeed({ type: "error", value: `Unknown tool: ${call.name}` });
|
|
1404
|
+
if (!tool.execute)
|
|
1405
|
+
return Effect.succeed({ type: "error", value: `Tool has no execute handler: ${call.name}` });
|
|
1406
|
+
return decodeAndExecute(tool, call.input).pipe(
|
|
1407
|
+
Effect.catchTag(
|
|
1408
|
+
"LLM.ToolFailure",
|
|
1409
|
+
(failure) => Effect.succeed({
|
|
1410
|
+
type: "error",
|
|
1411
|
+
value: failure.message,
|
|
1412
|
+
...failure.metadata ? { metadata: failure.metadata } : {}
|
|
1413
|
+
})
|
|
1414
|
+
)
|
|
1415
|
+
);
|
|
1416
|
+
};
|
|
1417
|
+
var decodeAndExecute = (tool, input) => tool._decode(input).pipe(
|
|
1418
|
+
Effect.mapError((error) => new ToolFailure({ message: `Invalid tool input: ${error.message}` })),
|
|
1419
|
+
Effect.flatMap((decoded) => tool.execute(decoded)),
|
|
1420
|
+
Effect.flatMap(
|
|
1421
|
+
(value) => tool._encode(value).pipe(
|
|
1422
|
+
Effect.mapError(
|
|
1423
|
+
(error) => new ToolFailure({
|
|
1424
|
+
message: `Tool returned an invalid value for its success schema: ${error.message}`
|
|
1425
|
+
})
|
|
1426
|
+
)
|
|
1427
|
+
)
|
|
1428
|
+
),
|
|
1429
|
+
Effect.map((encoded) => ({ type: "json", value: encoded }))
|
|
1430
|
+
);
|
|
1431
|
+
var emitEvents = (call, result) => {
|
|
1432
|
+
if (result.type === "error") {
|
|
1433
|
+
if (isInterruptResult(result)) {
|
|
1434
|
+
return [
|
|
1435
|
+
LLMEvent.toolError({
|
|
1436
|
+
id: call.id,
|
|
1437
|
+
name: call.name,
|
|
1438
|
+
message: String(result.value),
|
|
1439
|
+
metadata: result.metadata
|
|
1440
|
+
})
|
|
1441
|
+
];
|
|
1442
|
+
}
|
|
1443
|
+
return [
|
|
1444
|
+
LLMEvent.toolError({
|
|
1445
|
+
id: call.id,
|
|
1446
|
+
name: call.name,
|
|
1447
|
+
message: String(result.value),
|
|
1448
|
+
metadata: result.metadata
|
|
1449
|
+
}),
|
|
1450
|
+
LLMEvent.toolResult({ id: call.id, name: call.name, result })
|
|
1451
|
+
];
|
|
1452
|
+
}
|
|
1453
|
+
return [LLMEvent.toolResult({ id: call.id, name: call.name, result })];
|
|
1454
|
+
};
|
|
1455
|
+
var followUpRequest = (request2, state, dispatched) => LLMRequest.update(request2, {
|
|
1456
|
+
messages: [
|
|
1457
|
+
...request2.messages,
|
|
1458
|
+
Message.assistant(state.assistantContent),
|
|
1459
|
+
...dispatched.map(([call, result]) => Message.tool({ id: call.id, name: call.name, result }))
|
|
1460
|
+
]
|
|
1461
|
+
});
|
|
1462
|
+
|
|
1463
|
+
// src/route/client.ts
|
|
1464
|
+
var routeRegistry = /* @__PURE__ */ new Map();
|
|
1465
|
+
var registeredRoute = (id) => routeRegistry.get(id);
|
|
1466
|
+
var modelLimits = ModelLimits.make;
|
|
1467
|
+
var generationOptions = (input) => input === void 0 ? void 0 : GenerationOptions.make(input);
|
|
1468
|
+
var httpOptions = (input) => {
|
|
1469
|
+
if (input === void 0) return input;
|
|
1470
|
+
return HttpOptions.make(input);
|
|
1471
|
+
};
|
|
1472
|
+
var modelRef = (input) => new ModelRef({
|
|
1473
|
+
...input,
|
|
1474
|
+
id: ModelID.make(input.id),
|
|
1475
|
+
provider: ProviderID.make(input.provider),
|
|
1476
|
+
route: RouteID.make(input.route),
|
|
1477
|
+
limits: modelLimits(input.limits),
|
|
1478
|
+
generation: generationOptions(input.generation),
|
|
1479
|
+
http: httpOptions(input.http)
|
|
1480
|
+
});
|
|
1481
|
+
var Service2 = class extends Context.Service()("@tinyweb-agent/LLMClient") {
|
|
1482
|
+
};
|
|
1483
|
+
var noRoute = (model2) => new LLMError({
|
|
1484
|
+
module: "LLMClient",
|
|
1485
|
+
method: "resolveRoute",
|
|
1486
|
+
reason: new NoRouteReason({ route: model2.route, provider: model2.provider, model: model2.id })
|
|
1487
|
+
});
|
|
1488
|
+
var resolveRequestOptions = (request2) => LLMRequest.update(request2, {
|
|
1489
|
+
generation: mergeGenerationOptions(request2.model.generation, request2.generation) ?? new GenerationOptions({}),
|
|
1490
|
+
providerOptions: mergeProviderOptions(request2.model.providerOptions, request2.providerOptions),
|
|
1491
|
+
http: mergeHttpOptions(request2.model.http, request2.http)
|
|
1492
|
+
});
|
|
1493
|
+
var compile = Effect.fn("LLM.compile")(function* (request2) {
|
|
1494
|
+
const resolved = applyCachePolicy(resolveRequestOptions(request2));
|
|
1495
|
+
const route = registeredRoute(resolved.model.route);
|
|
1496
|
+
if (!route) return yield* noRoute(resolved.model);
|
|
1497
|
+
const body = yield* route.body.from(resolved).pipe(Effect.flatMap(validateWith(Schema.decodeUnknownEffect(route.body.schema))));
|
|
1498
|
+
const prepared = yield* route.prepareTransport(body, resolved);
|
|
1499
|
+
return {
|
|
1500
|
+
request: resolved,
|
|
1501
|
+
route,
|
|
1502
|
+
body,
|
|
1503
|
+
prepared
|
|
1504
|
+
};
|
|
1505
|
+
});
|
|
1506
|
+
var prepareWith = Effect.fn("LLMClient.prepare")(function* (request2) {
|
|
1507
|
+
const compiled = yield* compile(request2);
|
|
1508
|
+
return new PreparedRequest({
|
|
1509
|
+
id: compiled.request.id ?? "request",
|
|
1510
|
+
route: compiled.route.id,
|
|
1511
|
+
protocol: compiled.route.protocol,
|
|
1512
|
+
model: compiled.request.model,
|
|
1513
|
+
body: compiled.body,
|
|
1514
|
+
metadata: { transport: compiled.route.transport.id }
|
|
1515
|
+
});
|
|
1516
|
+
});
|
|
1517
|
+
var streamRequestWith = (runtime) => (request2) => Stream.unwrap(
|
|
1518
|
+
Effect.gen(function* () {
|
|
1519
|
+
const compiled = yield* compile(request2);
|
|
1520
|
+
return compiled.route.streamPrepared(compiled.prepared, compiled.request, runtime);
|
|
1521
|
+
})
|
|
1522
|
+
);
|
|
1523
|
+
var isToolRunOptions = (input) => "request" in input && "tools" in input;
|
|
1524
|
+
var streamWith = (streamRequest) => ((input) => {
|
|
1525
|
+
if (isToolRunOptions(input)) return stream({ ...input, stream: streamRequest });
|
|
1526
|
+
return streamRequest(input);
|
|
1527
|
+
});
|
|
1528
|
+
var generateWith = (stream4) => Effect.fn("LLM.generate")(function* (input) {
|
|
1529
|
+
return new LLMResponse(
|
|
1530
|
+
yield* stream4(input).pipe(
|
|
1531
|
+
Stream.runFold(
|
|
1532
|
+
() => ({ events: [], usage: void 0 }),
|
|
1533
|
+
(acc, event) => {
|
|
1534
|
+
acc.events.push(event);
|
|
1535
|
+
if ("usage" in event && event.usage !== void 0) acc.usage = event.usage;
|
|
1536
|
+
return acc;
|
|
1537
|
+
}
|
|
1538
|
+
)
|
|
1539
|
+
)
|
|
1540
|
+
);
|
|
1541
|
+
});
|
|
1542
|
+
var prepare = (request2) => prepareWith(request2);
|
|
1543
|
+
function stream2(input) {
|
|
1544
|
+
return Stream.unwrap(
|
|
1545
|
+
Effect.gen(function* () {
|
|
1546
|
+
return (yield* Service2).stream(input);
|
|
1547
|
+
})
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
function generate(input) {
|
|
1551
|
+
return Effect.gen(function* () {
|
|
1552
|
+
return yield* (yield* Service2).generate(input);
|
|
1553
|
+
});
|
|
1554
|
+
}
|
|
1555
|
+
var layer2 = Layer.effect(
|
|
1556
|
+
Service2,
|
|
1557
|
+
Effect.gen(function* () {
|
|
1558
|
+
const stream4 = streamWith(streamRequestWith({ http: yield* executor_exports.Service }));
|
|
1559
|
+
return Service2.of({ prepare: prepareWith, stream: stream4, generate: generateWith(stream4) });
|
|
1560
|
+
})
|
|
1561
|
+
);
|
|
1562
|
+
var LLMClient = {
|
|
1563
|
+
Service: Service2,
|
|
1564
|
+
layer: layer2,
|
|
1565
|
+
prepare,
|
|
1566
|
+
stream: stream2,
|
|
1567
|
+
generate,
|
|
1568
|
+
stepCountIs,
|
|
1569
|
+
hasToolCall,
|
|
1570
|
+
stopWhenAny
|
|
1571
|
+
};
|
|
1572
|
+
|
|
1573
|
+
// src/llm.ts
|
|
1574
|
+
var limits = modelLimits;
|
|
1575
|
+
var text = Message.text;
|
|
1576
|
+
var system = SystemPart.make;
|
|
1577
|
+
var message = Message.make;
|
|
1578
|
+
var user = Message.user;
|
|
1579
|
+
var assistant = Message.assistant;
|
|
1580
|
+
var model = modelRef;
|
|
1581
|
+
var toolDefinition = ToolDefinition.make;
|
|
1582
|
+
var toolCall = ToolCallPart.make;
|
|
1583
|
+
var toolResult = ToolResultPart.make;
|
|
1584
|
+
var toolMessage = Message.tool;
|
|
1585
|
+
var toolChoiceName = ToolChoice.named;
|
|
1586
|
+
var toolChoice = ToolChoice.make;
|
|
1587
|
+
var generation = GenerationOptions.make;
|
|
1588
|
+
var generate2 = LLMClient.generate;
|
|
1589
|
+
var stream3 = LLMClient.stream;
|
|
1590
|
+
var stepCountIs2 = LLMClient.stepCountIs;
|
|
1591
|
+
var requestInput = (input) => ({
|
|
1592
|
+
...LLMRequest.input(input)
|
|
1593
|
+
});
|
|
1594
|
+
var request = (input) => {
|
|
1595
|
+
const {
|
|
1596
|
+
system: requestSystem,
|
|
1597
|
+
prompt,
|
|
1598
|
+
messages,
|
|
1599
|
+
tools,
|
|
1600
|
+
toolChoice: requestToolChoice,
|
|
1601
|
+
generation: requestGeneration,
|
|
1602
|
+
providerOptions: requestProviderOptions,
|
|
1603
|
+
http: requestHttp,
|
|
1604
|
+
...rest
|
|
1605
|
+
} = input;
|
|
1606
|
+
return new LLMRequest({
|
|
1607
|
+
...rest,
|
|
1608
|
+
system: SystemPart.content(requestSystem),
|
|
1609
|
+
messages: [...messages?.map(message) ?? [], ...prompt === void 0 ? [] : [user(prompt)]],
|
|
1610
|
+
tools: tools?.map(toolDefinition) ?? [],
|
|
1611
|
+
toolChoice: requestToolChoice ? toolChoice(requestToolChoice) : void 0,
|
|
1612
|
+
generation: requestGeneration === void 0 ? void 0 : generation(requestGeneration),
|
|
1613
|
+
providerOptions: requestProviderOptions,
|
|
1614
|
+
http: requestHttp === void 0 ? void 0 : HttpOptions.make(requestHttp)
|
|
1615
|
+
});
|
|
1616
|
+
};
|
|
1617
|
+
var updateRequest = (input, patch) => request({ ...requestInput(input), ...patch });
|
|
1618
|
+
var GENERATE_OBJECT_TOOL_NAME = "generate_object";
|
|
1619
|
+
var GENERATE_OBJECT_TOOL_DESCRIPTION = "Return the structured result by calling this tool.";
|
|
1620
|
+
var GenerateObjectResponse = class {
|
|
1621
|
+
constructor(object, response) {
|
|
1622
|
+
this.object = object;
|
|
1623
|
+
this.response = response;
|
|
1624
|
+
}
|
|
1625
|
+
get events() {
|
|
1626
|
+
return this.response.events;
|
|
1627
|
+
}
|
|
1628
|
+
get usage() {
|
|
1629
|
+
return this.response.usage;
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
var runGenerateObject = Effect.fn("LLM.generateObject")(function* (options, tool) {
|
|
1633
|
+
const baseRequest = request(options);
|
|
1634
|
+
const generateRequest = LLMRequest.update(baseRequest, {
|
|
1635
|
+
toolChoice: ToolChoice.named(GENERATE_OBJECT_TOOL_NAME)
|
|
1636
|
+
});
|
|
1637
|
+
const response = yield* LLMClient.generate({
|
|
1638
|
+
request: generateRequest,
|
|
1639
|
+
tools: { [GENERATE_OBJECT_TOOL_NAME]: tool },
|
|
1640
|
+
toolExecution: "none"
|
|
1641
|
+
});
|
|
1642
|
+
const call = response.toolCalls.find(
|
|
1643
|
+
(event) => LLMEvent.is.toolCall(event) && event.name === GENERATE_OBJECT_TOOL_NAME
|
|
1644
|
+
);
|
|
1645
|
+
if (!call || !LLMEvent.is.toolCall(call))
|
|
1646
|
+
return yield* new LLMError({
|
|
1647
|
+
module: "LLM",
|
|
1648
|
+
method: "generateObject",
|
|
1649
|
+
reason: new InvalidProviderOutputReason({
|
|
1650
|
+
message: `generateObject: model did not call the forced \`${GENERATE_OBJECT_TOOL_NAME}\` tool`
|
|
1651
|
+
})
|
|
1652
|
+
});
|
|
1653
|
+
const object = yield* tool._decode(call.input).pipe(
|
|
1654
|
+
Effect.mapError(
|
|
1655
|
+
(error) => new LLMError({
|
|
1656
|
+
module: "LLM",
|
|
1657
|
+
method: "generateObject",
|
|
1658
|
+
reason: new InvalidProviderOutputReason({
|
|
1659
|
+
message: `generateObject: tool input failed schema decode: ${error.message}`
|
|
1660
|
+
})
|
|
1661
|
+
})
|
|
1662
|
+
)
|
|
1663
|
+
);
|
|
1664
|
+
return new GenerateObjectResponse(object, response);
|
|
1665
|
+
});
|
|
1666
|
+
function generateObject(options) {
|
|
1667
|
+
if ("schema" in options) {
|
|
1668
|
+
const { schema, ...rest2 } = options;
|
|
1669
|
+
return runGenerateObject(
|
|
1670
|
+
rest2,
|
|
1671
|
+
make({
|
|
1672
|
+
description: GENERATE_OBJECT_TOOL_DESCRIPTION,
|
|
1673
|
+
parameters: schema,
|
|
1674
|
+
success: Schema.Unknown,
|
|
1675
|
+
execute: () => Effect.void
|
|
1676
|
+
})
|
|
1677
|
+
);
|
|
1678
|
+
}
|
|
1679
|
+
const { jsonSchema, ...rest } = options;
|
|
1680
|
+
return runGenerateObject(
|
|
1681
|
+
rest,
|
|
1682
|
+
make({
|
|
1683
|
+
description: GENERATE_OBJECT_TOOL_DESCRIPTION,
|
|
1684
|
+
jsonSchema,
|
|
1685
|
+
execute: () => Effect.void
|
|
1686
|
+
})
|
|
1687
|
+
);
|
|
1688
|
+
}
|
|
1689
|
+
|
|
1690
|
+
export { GenerateObjectResponse, llm_exports as LLM, assistant, generate2 as generate, generateObject, generation, hasToolCall, limits, message, model, request, requestInput, stepCountIs2 as stepCountIs, stopWhenAny, stream3 as stream, system, text, toolCall, toolChoice, toolChoiceName, toolDefinition, toolMessage, toolResult, updateRequest, user };
|
|
1691
|
+
//# sourceMappingURL=llm.js.map
|
|
1692
|
+
//# sourceMappingURL=llm.js.map
|