@tinyweb_dev/agent-framework-llm 0.2.0 → 0.4.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 +2968 -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 +2843 -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 +2455 -0
- package/dist/protocols/openai-chat.cjs.map +1 -0
- package/dist/protocols/openai-chat.d.ts +359 -0
- package/dist/protocols/openai-chat.d.ts.map +1 -0
- package/dist/protocols/openai-chat.js +2426 -0
- package/dist/protocols/openai-chat.js.map +1 -0
- package/dist/protocols/openai-compatible-chat.cjs +2455 -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 +2431 -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 +2545 -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 +2507 -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 +2529 -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 +2501 -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
|
@@ -0,0 +1,1077 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var effect = require('effect');
|
|
4
|
+
var http = require('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
|
+
|
|
12
|
+
// src/route/executor.ts
|
|
13
|
+
var executor_exports = {};
|
|
14
|
+
__export(executor_exports, {
|
|
15
|
+
RequestExecutor: () => executor_exports,
|
|
16
|
+
Service: () => Service,
|
|
17
|
+
defaultLayer: () => defaultLayer,
|
|
18
|
+
layer: () => layer
|
|
19
|
+
});
|
|
20
|
+
var ProtocolID = effect.Schema.String;
|
|
21
|
+
var RouteID = effect.Schema.String;
|
|
22
|
+
var ModelID = effect.Schema.String.pipe(effect.Schema.brand("LLM.ModelID"));
|
|
23
|
+
var ProviderID = effect.Schema.String.pipe(effect.Schema.brand("LLM.ProviderID"));
|
|
24
|
+
var ResponseID = effect.Schema.String;
|
|
25
|
+
var ContentBlockID = effect.Schema.String;
|
|
26
|
+
var ToolCallID = effect.Schema.String;
|
|
27
|
+
var ReasoningEfforts = ["none", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
28
|
+
effect.Schema.Literals(ReasoningEfforts);
|
|
29
|
+
effect.Schema.Literals(["low", "medium", "high"]);
|
|
30
|
+
var MessageRole = effect.Schema.Literals(["user", "assistant", "tool"]);
|
|
31
|
+
var FinishReason = effect.Schema.Literals(["stop", "length", "tool-calls", "content-filter", "error", "unknown"]);
|
|
32
|
+
var JsonSchema = effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown);
|
|
33
|
+
var ProviderMetadata = effect.Schema.Record(effect.Schema.String, effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown));
|
|
34
|
+
var ProviderOptions = effect.Schema.Record(effect.Schema.String, effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown));
|
|
35
|
+
var HttpOptions = class extends effect.Schema.Class("LLM.HttpOptions")({
|
|
36
|
+
body: effect.Schema.optional(JsonSchema),
|
|
37
|
+
headers: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
|
|
38
|
+
query: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String))
|
|
39
|
+
}) {
|
|
40
|
+
};
|
|
41
|
+
((HttpOptions2) => {
|
|
42
|
+
HttpOptions2.make = (input) => input instanceof HttpOptions2 ? input : new HttpOptions2(input);
|
|
43
|
+
})(HttpOptions || (HttpOptions = {}));
|
|
44
|
+
var GenerationOptions = class extends effect.Schema.Class("LLM.GenerationOptions")({
|
|
45
|
+
maxTokens: effect.Schema.optional(effect.Schema.Number),
|
|
46
|
+
temperature: effect.Schema.optional(effect.Schema.Number),
|
|
47
|
+
topP: effect.Schema.optional(effect.Schema.Number),
|
|
48
|
+
topK: effect.Schema.optional(effect.Schema.Number),
|
|
49
|
+
frequencyPenalty: effect.Schema.optional(effect.Schema.Number),
|
|
50
|
+
presencePenalty: effect.Schema.optional(effect.Schema.Number),
|
|
51
|
+
seed: effect.Schema.optional(effect.Schema.Number),
|
|
52
|
+
stop: effect.Schema.optional(effect.Schema.Array(effect.Schema.String))
|
|
53
|
+
}) {
|
|
54
|
+
};
|
|
55
|
+
((GenerationOptions2) => {
|
|
56
|
+
GenerationOptions2.make = (input = {}) => input instanceof GenerationOptions2 ? input : new GenerationOptions2(input);
|
|
57
|
+
})(GenerationOptions || (GenerationOptions = {}));
|
|
58
|
+
var ModelLimits = class extends effect.Schema.Class("LLM.ModelLimits")({
|
|
59
|
+
context: effect.Schema.optional(effect.Schema.Number),
|
|
60
|
+
output: effect.Schema.optional(effect.Schema.Number)
|
|
61
|
+
}) {
|
|
62
|
+
};
|
|
63
|
+
((ModelLimits2) => {
|
|
64
|
+
ModelLimits2.make = (input) => input instanceof ModelLimits2 ? input : new ModelLimits2(input ?? {});
|
|
65
|
+
})(ModelLimits || (ModelLimits = {}));
|
|
66
|
+
var ModelRef = class extends effect.Schema.Class("LLM.ModelRef")({
|
|
67
|
+
id: ModelID,
|
|
68
|
+
provider: ProviderID,
|
|
69
|
+
route: RouteID,
|
|
70
|
+
baseURL: effect.Schema.String,
|
|
71
|
+
/** Provider-specific API key convenience. Provider helpers normalize this into `auth`. */
|
|
72
|
+
apiKey: effect.Schema.optional(effect.Schema.String),
|
|
73
|
+
/** Optional transport auth policy. Opaque because it may contain functions. */
|
|
74
|
+
auth: effect.Schema.optional(effect.Schema.Any),
|
|
75
|
+
headers: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
|
|
76
|
+
/**
|
|
77
|
+
* Query params appended to the request URL by `Endpoint.baseURL`. Used for
|
|
78
|
+
* deployment-level URL-scoped settings such as Azure's `api-version` or any
|
|
79
|
+
* provider that requires a per-request key in the URL. Generic concern, so
|
|
80
|
+
* lives as a typed first-class field instead of `native`.
|
|
81
|
+
*/
|
|
82
|
+
queryParams: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
|
|
83
|
+
limits: ModelLimits,
|
|
84
|
+
/** Provider-neutral generation defaults. Request-level values override them. */
|
|
85
|
+
generation: effect.Schema.optional(GenerationOptions),
|
|
86
|
+
/** Provider-owned typed-at-the-facade options for non-portable knobs. */
|
|
87
|
+
providerOptions: effect.Schema.optional(ProviderOptions),
|
|
88
|
+
/** Serializable raw HTTP overlays applied to the final outgoing request. */
|
|
89
|
+
http: effect.Schema.optional(HttpOptions),
|
|
90
|
+
/**
|
|
91
|
+
* Provider-specific opaque options. Reach for this only when the value is
|
|
92
|
+
* genuinely provider-private and does not fit a typed axis (e.g. Bedrock's
|
|
93
|
+
* `aws_credentials` / `aws_region` for SigV4). Anything used by more than
|
|
94
|
+
* one route should grow into a typed field instead.
|
|
95
|
+
*/
|
|
96
|
+
native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
97
|
+
}) {
|
|
98
|
+
};
|
|
99
|
+
((ModelRef2) => {
|
|
100
|
+
ModelRef2.input = (model) => ({
|
|
101
|
+
id: model.id,
|
|
102
|
+
provider: model.provider,
|
|
103
|
+
route: model.route,
|
|
104
|
+
baseURL: model.baseURL,
|
|
105
|
+
apiKey: model.apiKey,
|
|
106
|
+
auth: model.auth,
|
|
107
|
+
headers: model.headers,
|
|
108
|
+
queryParams: model.queryParams,
|
|
109
|
+
limits: model.limits,
|
|
110
|
+
generation: model.generation,
|
|
111
|
+
providerOptions: model.providerOptions,
|
|
112
|
+
http: model.http,
|
|
113
|
+
native: model.native
|
|
114
|
+
});
|
|
115
|
+
ModelRef2.update = (model, patch) => {
|
|
116
|
+
if (Object.keys(patch).length === 0) return model;
|
|
117
|
+
return new ModelRef2({
|
|
118
|
+
...(0, ModelRef2.input)(model),
|
|
119
|
+
...patch
|
|
120
|
+
});
|
|
121
|
+
};
|
|
122
|
+
})(ModelRef || (ModelRef = {}));
|
|
123
|
+
var CacheHint = class extends effect.Schema.Class("LLM.CacheHint")({
|
|
124
|
+
type: effect.Schema.Literals(["ephemeral", "persistent"]),
|
|
125
|
+
ttlSeconds: effect.Schema.optional(effect.Schema.Number)
|
|
126
|
+
}) {
|
|
127
|
+
};
|
|
128
|
+
var CachePolicyObject = effect.Schema.Struct({
|
|
129
|
+
tools: effect.Schema.optional(effect.Schema.Boolean),
|
|
130
|
+
system: effect.Schema.optional(effect.Schema.Boolean),
|
|
131
|
+
messages: effect.Schema.optional(
|
|
132
|
+
effect.Schema.Union([
|
|
133
|
+
effect.Schema.Literal("latest-user-message"),
|
|
134
|
+
effect.Schema.Literal("latest-assistant"),
|
|
135
|
+
effect.Schema.Struct({ tail: effect.Schema.Number })
|
|
136
|
+
])
|
|
137
|
+
),
|
|
138
|
+
ttlSeconds: effect.Schema.optional(effect.Schema.Number)
|
|
139
|
+
});
|
|
140
|
+
var CachePolicy = effect.Schema.Union([effect.Schema.Literal("auto"), effect.Schema.Literal("none"), CachePolicyObject]);
|
|
141
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
142
|
+
var systemPartSchema = effect.Schema.Struct({
|
|
143
|
+
type: effect.Schema.Literal("text"),
|
|
144
|
+
text: effect.Schema.String,
|
|
145
|
+
cache: effect.Schema.optional(CacheHint),
|
|
146
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
147
|
+
}).annotate({ identifier: "LLM.SystemPart" });
|
|
148
|
+
var makeSystemPart = (text) => ({ type: "text", text });
|
|
149
|
+
var SystemPart = Object.assign(systemPartSchema, {
|
|
150
|
+
make: makeSystemPart,
|
|
151
|
+
content: (input) => {
|
|
152
|
+
if (input === void 0) return [];
|
|
153
|
+
return typeof input === "string" ? [makeSystemPart(input)] : Array.isArray(input) ? [...input] : [input];
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
var TextPart = effect.Schema.Struct({
|
|
157
|
+
type: effect.Schema.Literal("text"),
|
|
158
|
+
text: effect.Schema.String,
|
|
159
|
+
cache: effect.Schema.optional(CacheHint),
|
|
160
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
161
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
162
|
+
}).annotate({ identifier: "LLM.Content.Text" });
|
|
163
|
+
var MediaPart = effect.Schema.Struct({
|
|
164
|
+
type: effect.Schema.Literal("media"),
|
|
165
|
+
mediaType: effect.Schema.String,
|
|
166
|
+
data: effect.Schema.Union([effect.Schema.String, effect.Schema.Uint8Array]),
|
|
167
|
+
filename: effect.Schema.optional(effect.Schema.String),
|
|
168
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
169
|
+
}).annotate({ identifier: "LLM.Content.Media" });
|
|
170
|
+
var isToolResultValue = (value) => isRecord(value) && (value.type === "text" || value.type === "json" || value.type === "error") && "value" in value;
|
|
171
|
+
var ToolResultValue = Object.assign(
|
|
172
|
+
effect.Schema.Struct({
|
|
173
|
+
type: effect.Schema.Literals(["json", "text", "error"]),
|
|
174
|
+
value: effect.Schema.Unknown,
|
|
175
|
+
/** Optional structured payload (e.g. tool-interrupt metadata). */
|
|
176
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
177
|
+
}).annotate({ identifier: "LLM.ToolResult" }),
|
|
178
|
+
{
|
|
179
|
+
make: (value, type = "json", metadata) => {
|
|
180
|
+
if (isToolResultValue(value)) {
|
|
181
|
+
return metadata ? { ...value, metadata: { ...value.metadata ?? {}, ...metadata } } : value;
|
|
182
|
+
}
|
|
183
|
+
return metadata ? { type, value, metadata } : { type, value };
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
);
|
|
187
|
+
var ToolCallPart = Object.assign(
|
|
188
|
+
effect.Schema.Struct({
|
|
189
|
+
type: effect.Schema.Literal("tool-call"),
|
|
190
|
+
id: effect.Schema.String,
|
|
191
|
+
name: effect.Schema.String,
|
|
192
|
+
input: effect.Schema.Unknown,
|
|
193
|
+
providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
|
|
194
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
195
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
196
|
+
}).annotate({ identifier: "LLM.Content.ToolCall" }),
|
|
197
|
+
{
|
|
198
|
+
make: (input) => ({ type: "tool-call", ...input })
|
|
199
|
+
}
|
|
200
|
+
);
|
|
201
|
+
var ToolResultPart = Object.assign(
|
|
202
|
+
effect.Schema.Struct({
|
|
203
|
+
type: effect.Schema.Literal("tool-result"),
|
|
204
|
+
id: effect.Schema.String,
|
|
205
|
+
name: effect.Schema.String,
|
|
206
|
+
result: ToolResultValue,
|
|
207
|
+
providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
|
|
208
|
+
cache: effect.Schema.optional(CacheHint),
|
|
209
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
210
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
211
|
+
}).annotate({ identifier: "LLM.Content.ToolResult" }),
|
|
212
|
+
{
|
|
213
|
+
make: (input) => ({
|
|
214
|
+
type: "tool-result",
|
|
215
|
+
id: input.id,
|
|
216
|
+
name: input.name,
|
|
217
|
+
result: ToolResultValue.make(input.result, input.resultType),
|
|
218
|
+
providerExecuted: input.providerExecuted,
|
|
219
|
+
cache: input.cache,
|
|
220
|
+
metadata: input.metadata,
|
|
221
|
+
providerMetadata: input.providerMetadata
|
|
222
|
+
})
|
|
223
|
+
}
|
|
224
|
+
);
|
|
225
|
+
var ReasoningPart = effect.Schema.Struct({
|
|
226
|
+
type: effect.Schema.Literal("reasoning"),
|
|
227
|
+
text: effect.Schema.String,
|
|
228
|
+
encrypted: effect.Schema.optional(effect.Schema.String),
|
|
229
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
230
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
231
|
+
}).annotate({ identifier: "LLM.Content.Reasoning" });
|
|
232
|
+
var ContentPart = effect.Schema.Union([TextPart, MediaPart, ToolCallPart, ToolResultPart, ReasoningPart]).pipe(
|
|
233
|
+
effect.Schema.toTaggedUnion("type")
|
|
234
|
+
);
|
|
235
|
+
var Message = class extends effect.Schema.Class("LLM.Message")({
|
|
236
|
+
id: effect.Schema.optional(effect.Schema.String),
|
|
237
|
+
role: MessageRole,
|
|
238
|
+
content: effect.Schema.Array(ContentPart),
|
|
239
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
240
|
+
native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
241
|
+
}) {
|
|
242
|
+
};
|
|
243
|
+
((Message2) => {
|
|
244
|
+
Message2.text = (value) => ({ type: "text", text: value });
|
|
245
|
+
Message2.content = (input) => typeof input === "string" ? [(0, Message2.text)(input)] : Array.isArray(input) ? [...input] : [input];
|
|
246
|
+
Message2.make = (input) => {
|
|
247
|
+
if (input instanceof Message2) return input;
|
|
248
|
+
return new Message2({ ...input, content: (0, Message2.content)(input.content) });
|
|
249
|
+
};
|
|
250
|
+
Message2.user = (content2) => (0, Message2.make)({ role: "user", content: content2 });
|
|
251
|
+
Message2.assistant = (content2) => (0, Message2.make)({ role: "assistant", content: content2 });
|
|
252
|
+
Message2.tool = (result) => (0, Message2.make)({ role: "tool", content: ["type" in result ? result : ToolResultPart.make(result)] });
|
|
253
|
+
})(Message || (Message = {}));
|
|
254
|
+
var ToolDefinition = class extends effect.Schema.Class("LLM.ToolDefinition")({
|
|
255
|
+
name: effect.Schema.String,
|
|
256
|
+
description: effect.Schema.String,
|
|
257
|
+
inputSchema: JsonSchema,
|
|
258
|
+
cache: effect.Schema.optional(CacheHint),
|
|
259
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
260
|
+
native: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
261
|
+
}) {
|
|
262
|
+
};
|
|
263
|
+
((ToolDefinition2) => {
|
|
264
|
+
ToolDefinition2.make = (input) => input instanceof ToolDefinition2 ? input : new ToolDefinition2(input);
|
|
265
|
+
})(ToolDefinition || (ToolDefinition = {}));
|
|
266
|
+
var ToolChoice = class extends effect.Schema.Class("LLM.ToolChoice")({
|
|
267
|
+
type: effect.Schema.Literals(["auto", "none", "required", "tool"]),
|
|
268
|
+
name: effect.Schema.optional(effect.Schema.String)
|
|
269
|
+
}) {
|
|
270
|
+
};
|
|
271
|
+
((ToolChoice2) => {
|
|
272
|
+
const isMode = (value) => value === "auto" || value === "none" || value === "required";
|
|
273
|
+
ToolChoice2.named = (value) => new ToolChoice2({ type: "tool", name: value });
|
|
274
|
+
ToolChoice2.make = (input) => {
|
|
275
|
+
if (input instanceof ToolChoice2) return input;
|
|
276
|
+
if (input instanceof ToolDefinition) return (0, ToolChoice2.named)(input.name);
|
|
277
|
+
if (typeof input === "string") return isMode(input) ? new ToolChoice2({ type: input }) : (0, ToolChoice2.named)(input);
|
|
278
|
+
return new ToolChoice2(input);
|
|
279
|
+
};
|
|
280
|
+
})(ToolChoice || (ToolChoice = {}));
|
|
281
|
+
var ResponseFormat = effect.Schema.Union([
|
|
282
|
+
effect.Schema.Struct({ type: effect.Schema.Literal("text") }),
|
|
283
|
+
effect.Schema.Struct({ type: effect.Schema.Literal("json"), schema: JsonSchema }),
|
|
284
|
+
effect.Schema.Struct({ type: effect.Schema.Literal("tool"), tool: ToolDefinition })
|
|
285
|
+
]).pipe(effect.Schema.toTaggedUnion("type"));
|
|
286
|
+
var LLMRequest = class extends effect.Schema.Class("LLM.Request")({
|
|
287
|
+
id: effect.Schema.optional(effect.Schema.String),
|
|
288
|
+
model: ModelRef,
|
|
289
|
+
system: effect.Schema.Array(SystemPart),
|
|
290
|
+
messages: effect.Schema.Array(Message),
|
|
291
|
+
tools: effect.Schema.Array(ToolDefinition),
|
|
292
|
+
toolChoice: effect.Schema.optional(ToolChoice),
|
|
293
|
+
generation: effect.Schema.optional(GenerationOptions),
|
|
294
|
+
providerOptions: effect.Schema.optional(ProviderOptions),
|
|
295
|
+
http: effect.Schema.optional(HttpOptions),
|
|
296
|
+
responseFormat: effect.Schema.optional(ResponseFormat),
|
|
297
|
+
cache: effect.Schema.optional(CachePolicy),
|
|
298
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
299
|
+
}) {
|
|
300
|
+
};
|
|
301
|
+
((LLMRequest2) => {
|
|
302
|
+
LLMRequest2.input = (request) => ({
|
|
303
|
+
id: request.id,
|
|
304
|
+
model: request.model,
|
|
305
|
+
system: request.system,
|
|
306
|
+
messages: request.messages,
|
|
307
|
+
tools: request.tools,
|
|
308
|
+
toolChoice: request.toolChoice,
|
|
309
|
+
generation: request.generation,
|
|
310
|
+
providerOptions: request.providerOptions,
|
|
311
|
+
http: request.http,
|
|
312
|
+
responseFormat: request.responseFormat,
|
|
313
|
+
cache: request.cache,
|
|
314
|
+
metadata: request.metadata
|
|
315
|
+
});
|
|
316
|
+
LLMRequest2.update = (request, patch) => {
|
|
317
|
+
if (Object.keys(patch).length === 0) return request;
|
|
318
|
+
return new LLMRequest2({
|
|
319
|
+
...(0, LLMRequest2.input)(request),
|
|
320
|
+
...patch,
|
|
321
|
+
model: patch.model ?? request.model
|
|
322
|
+
});
|
|
323
|
+
};
|
|
324
|
+
})(LLMRequest || (LLMRequest = {}));
|
|
325
|
+
var Usage = class extends effect.Schema.Class("LLM.Usage")({
|
|
326
|
+
inputTokens: effect.Schema.optional(effect.Schema.Number),
|
|
327
|
+
outputTokens: effect.Schema.optional(effect.Schema.Number),
|
|
328
|
+
nonCachedInputTokens: effect.Schema.optional(effect.Schema.Number),
|
|
329
|
+
cacheReadInputTokens: effect.Schema.optional(effect.Schema.Number),
|
|
330
|
+
cacheWriteInputTokens: effect.Schema.optional(effect.Schema.Number),
|
|
331
|
+
reasoningTokens: effect.Schema.optional(effect.Schema.Number),
|
|
332
|
+
totalTokens: effect.Schema.optional(effect.Schema.Number),
|
|
333
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
334
|
+
}) {
|
|
335
|
+
/**
|
|
336
|
+
* Visible output tokens — `outputTokens` minus `reasoningTokens`, clamped
|
|
337
|
+
* to zero. The one place subtraction happens in this contract; the clamp
|
|
338
|
+
* means a provider reporting `reasoningTokens > outputTokens` produces a
|
|
339
|
+
* harmless zero rather than a negative that crashes downstream schemas.
|
|
340
|
+
*/
|
|
341
|
+
get visibleOutputTokens() {
|
|
342
|
+
return Math.max(0, (this.outputTokens ?? 0) - (this.reasoningTokens ?? 0));
|
|
343
|
+
}
|
|
344
|
+
};
|
|
345
|
+
var RequestStart = effect.Schema.Struct({
|
|
346
|
+
type: effect.Schema.tag("request-start"),
|
|
347
|
+
id: ResponseID,
|
|
348
|
+
model: ModelRef
|
|
349
|
+
}).annotate({ identifier: "LLM.Event.RequestStart" });
|
|
350
|
+
var StepStart = effect.Schema.Struct({
|
|
351
|
+
type: effect.Schema.tag("step-start"),
|
|
352
|
+
index: effect.Schema.Number
|
|
353
|
+
}).annotate({ identifier: "LLM.Event.StepStart" });
|
|
354
|
+
var TextStart = effect.Schema.Struct({
|
|
355
|
+
type: effect.Schema.tag("text-start"),
|
|
356
|
+
id: ContentBlockID,
|
|
357
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
358
|
+
}).annotate({ identifier: "LLM.Event.TextStart" });
|
|
359
|
+
var TextDelta = effect.Schema.Struct({
|
|
360
|
+
type: effect.Schema.tag("text-delta"),
|
|
361
|
+
id: ContentBlockID,
|
|
362
|
+
text: effect.Schema.String
|
|
363
|
+
}).annotate({ identifier: "LLM.Event.TextDelta" });
|
|
364
|
+
var TextEnd = effect.Schema.Struct({
|
|
365
|
+
type: effect.Schema.tag("text-end"),
|
|
366
|
+
id: ContentBlockID,
|
|
367
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
368
|
+
}).annotate({ identifier: "LLM.Event.TextEnd" });
|
|
369
|
+
var ReasoningStart = effect.Schema.Struct({
|
|
370
|
+
type: effect.Schema.tag("reasoning-start"),
|
|
371
|
+
id: ContentBlockID,
|
|
372
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
373
|
+
}).annotate({ identifier: "LLM.Event.ReasoningStart" });
|
|
374
|
+
var ReasoningDelta = effect.Schema.Struct({
|
|
375
|
+
type: effect.Schema.tag("reasoning-delta"),
|
|
376
|
+
id: ContentBlockID,
|
|
377
|
+
text: effect.Schema.String
|
|
378
|
+
}).annotate({ identifier: "LLM.Event.ReasoningDelta" });
|
|
379
|
+
var ReasoningEnd = effect.Schema.Struct({
|
|
380
|
+
type: effect.Schema.tag("reasoning-end"),
|
|
381
|
+
id: ContentBlockID,
|
|
382
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
383
|
+
}).annotate({ identifier: "LLM.Event.ReasoningEnd" });
|
|
384
|
+
var ToolInputStart = effect.Schema.Struct({
|
|
385
|
+
type: effect.Schema.tag("tool-input-start"),
|
|
386
|
+
id: ToolCallID,
|
|
387
|
+
name: effect.Schema.String,
|
|
388
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
389
|
+
}).annotate({ identifier: "LLM.Event.ToolInputStart" });
|
|
390
|
+
var ToolInputDelta = effect.Schema.Struct({
|
|
391
|
+
type: effect.Schema.tag("tool-input-delta"),
|
|
392
|
+
id: ToolCallID,
|
|
393
|
+
name: effect.Schema.String,
|
|
394
|
+
text: effect.Schema.String
|
|
395
|
+
}).annotate({ identifier: "LLM.Event.ToolInputDelta" });
|
|
396
|
+
var ToolInputEnd = effect.Schema.Struct({
|
|
397
|
+
type: effect.Schema.tag("tool-input-end"),
|
|
398
|
+
id: ToolCallID,
|
|
399
|
+
name: effect.Schema.String,
|
|
400
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
401
|
+
}).annotate({ identifier: "LLM.Event.ToolInputEnd" });
|
|
402
|
+
var ToolCall = effect.Schema.Struct({
|
|
403
|
+
type: effect.Schema.tag("tool-call"),
|
|
404
|
+
id: ToolCallID,
|
|
405
|
+
name: effect.Schema.String,
|
|
406
|
+
input: effect.Schema.Unknown,
|
|
407
|
+
providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
|
|
408
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
409
|
+
}).annotate({ identifier: "LLM.Event.ToolCall" });
|
|
410
|
+
var ToolResult = effect.Schema.Struct({
|
|
411
|
+
type: effect.Schema.tag("tool-result"),
|
|
412
|
+
id: ToolCallID,
|
|
413
|
+
name: effect.Schema.String,
|
|
414
|
+
result: ToolResultValue,
|
|
415
|
+
providerExecuted: effect.Schema.optional(effect.Schema.Boolean),
|
|
416
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
417
|
+
}).annotate({ identifier: "LLM.Event.ToolResult" });
|
|
418
|
+
var ToolError = effect.Schema.Struct({
|
|
419
|
+
type: effect.Schema.tag("tool-error"),
|
|
420
|
+
id: ToolCallID,
|
|
421
|
+
name: effect.Schema.String,
|
|
422
|
+
message: effect.Schema.String,
|
|
423
|
+
/** Optional structured payload (e.g. tool-interrupt metadata for approval). */
|
|
424
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown)),
|
|
425
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
426
|
+
}).annotate({ identifier: "LLM.Event.ToolError" });
|
|
427
|
+
var StepFinish = effect.Schema.Struct({
|
|
428
|
+
type: effect.Schema.tag("step-finish"),
|
|
429
|
+
index: effect.Schema.Number,
|
|
430
|
+
reason: FinishReason,
|
|
431
|
+
usage: effect.Schema.optional(Usage),
|
|
432
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
433
|
+
}).annotate({ identifier: "LLM.Event.StepFinish" });
|
|
434
|
+
var RequestFinish = effect.Schema.Struct({
|
|
435
|
+
type: effect.Schema.tag("request-finish"),
|
|
436
|
+
reason: FinishReason,
|
|
437
|
+
usage: effect.Schema.optional(Usage),
|
|
438
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
439
|
+
}).annotate({ identifier: "LLM.Event.RequestFinish" });
|
|
440
|
+
var ProviderErrorEvent = effect.Schema.Struct({
|
|
441
|
+
type: effect.Schema.tag("provider-error"),
|
|
442
|
+
message: effect.Schema.String,
|
|
443
|
+
retryable: effect.Schema.optional(effect.Schema.Boolean),
|
|
444
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
445
|
+
}).annotate({ identifier: "LLM.Event.ProviderError" });
|
|
446
|
+
var llmEventTagged = effect.Schema.Union([
|
|
447
|
+
RequestStart,
|
|
448
|
+
StepStart,
|
|
449
|
+
TextStart,
|
|
450
|
+
TextDelta,
|
|
451
|
+
TextEnd,
|
|
452
|
+
ReasoningStart,
|
|
453
|
+
ReasoningDelta,
|
|
454
|
+
ReasoningEnd,
|
|
455
|
+
ToolInputStart,
|
|
456
|
+
ToolInputDelta,
|
|
457
|
+
ToolInputEnd,
|
|
458
|
+
ToolCall,
|
|
459
|
+
ToolResult,
|
|
460
|
+
ToolError,
|
|
461
|
+
StepFinish,
|
|
462
|
+
RequestFinish,
|
|
463
|
+
ProviderErrorEvent
|
|
464
|
+
]).pipe(effect.Schema.toTaggedUnion("type"));
|
|
465
|
+
var responseID = (value) => ResponseID.make(value);
|
|
466
|
+
var contentBlockID = (value) => ContentBlockID.make(value);
|
|
467
|
+
var toolCallID = (value) => ToolCallID.make(value);
|
|
468
|
+
var LLMEvent = Object.assign(llmEventTagged, {
|
|
469
|
+
requestStart: (input) => RequestStart.make({ ...input, id: responseID(input.id) }),
|
|
470
|
+
stepStart: StepStart.make,
|
|
471
|
+
textStart: (input) => TextStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
472
|
+
textDelta: (input) => TextDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
473
|
+
textEnd: (input) => TextEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
474
|
+
reasoningStart: (input) => ReasoningStart.make({ ...input, id: contentBlockID(input.id) }),
|
|
475
|
+
reasoningDelta: (input) => ReasoningDelta.make({ ...input, id: contentBlockID(input.id) }),
|
|
476
|
+
reasoningEnd: (input) => ReasoningEnd.make({ ...input, id: contentBlockID(input.id) }),
|
|
477
|
+
toolInputStart: (input) => ToolInputStart.make({ ...input, id: toolCallID(input.id) }),
|
|
478
|
+
toolInputDelta: (input) => ToolInputDelta.make({ ...input, id: toolCallID(input.id) }),
|
|
479
|
+
toolInputEnd: (input) => ToolInputEnd.make({ ...input, id: toolCallID(input.id) }),
|
|
480
|
+
toolCall: (input) => ToolCall.make({ ...input, id: toolCallID(input.id) }),
|
|
481
|
+
toolResult: (input) => ToolResult.make({ ...input, id: toolCallID(input.id) }),
|
|
482
|
+
toolError: (input) => ToolError.make({ ...input, id: toolCallID(input.id) }),
|
|
483
|
+
stepFinish: StepFinish.make,
|
|
484
|
+
requestFinish: RequestFinish.make,
|
|
485
|
+
providerError: ProviderErrorEvent.make,
|
|
486
|
+
is: {
|
|
487
|
+
requestStart: llmEventTagged.guards["request-start"],
|
|
488
|
+
stepStart: llmEventTagged.guards["step-start"],
|
|
489
|
+
textStart: llmEventTagged.guards["text-start"],
|
|
490
|
+
textDelta: llmEventTagged.guards["text-delta"],
|
|
491
|
+
textEnd: llmEventTagged.guards["text-end"],
|
|
492
|
+
reasoningStart: llmEventTagged.guards["reasoning-start"],
|
|
493
|
+
reasoningDelta: llmEventTagged.guards["reasoning-delta"],
|
|
494
|
+
reasoningEnd: llmEventTagged.guards["reasoning-end"],
|
|
495
|
+
toolInputStart: llmEventTagged.guards["tool-input-start"],
|
|
496
|
+
toolInputDelta: llmEventTagged.guards["tool-input-delta"],
|
|
497
|
+
toolInputEnd: llmEventTagged.guards["tool-input-end"],
|
|
498
|
+
toolCall: llmEventTagged.guards["tool-call"],
|
|
499
|
+
toolResult: llmEventTagged.guards["tool-result"],
|
|
500
|
+
toolError: llmEventTagged.guards["tool-error"],
|
|
501
|
+
stepFinish: llmEventTagged.guards["step-finish"],
|
|
502
|
+
requestFinish: llmEventTagged.guards["request-finish"],
|
|
503
|
+
providerError: llmEventTagged.guards["provider-error"]
|
|
504
|
+
}
|
|
505
|
+
});
|
|
506
|
+
(class extends effect.Schema.Class("LLM.PreparedRequest")({
|
|
507
|
+
id: effect.Schema.String,
|
|
508
|
+
route: RouteID,
|
|
509
|
+
protocol: ProtocolID,
|
|
510
|
+
model: ModelRef,
|
|
511
|
+
body: effect.Schema.Unknown,
|
|
512
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
513
|
+
}) {
|
|
514
|
+
});
|
|
515
|
+
var responseText = (events) => events.filter(LLMEvent.is.textDelta).map((event) => event.text).join("");
|
|
516
|
+
var responseReasoning = (events) => events.filter(LLMEvent.is.reasoningDelta).map((event) => event.text).join("");
|
|
517
|
+
var responseUsage = (events) => events.reduce(
|
|
518
|
+
(usage, event) => "usage" in event && event.usage !== void 0 ? event.usage : usage,
|
|
519
|
+
void 0
|
|
520
|
+
);
|
|
521
|
+
var LLMResponse = class extends effect.Schema.Class("LLM.Response")({
|
|
522
|
+
events: effect.Schema.Array(LLMEvent),
|
|
523
|
+
usage: effect.Schema.optional(Usage)
|
|
524
|
+
}) {
|
|
525
|
+
/** Concatenated assistant text assembled from streamed `text-delta` events. */
|
|
526
|
+
get text() {
|
|
527
|
+
return responseText(this.events);
|
|
528
|
+
}
|
|
529
|
+
/** Concatenated reasoning text assembled from streamed `reasoning-delta` events. */
|
|
530
|
+
get reasoning() {
|
|
531
|
+
return responseReasoning(this.events);
|
|
532
|
+
}
|
|
533
|
+
/** Completed tool calls emitted by the provider. */
|
|
534
|
+
get toolCalls() {
|
|
535
|
+
return this.events.filter(LLMEvent.is.toolCall);
|
|
536
|
+
}
|
|
537
|
+
};
|
|
538
|
+
((LLMResponse2) => {
|
|
539
|
+
LLMResponse2.text = (response) => responseText(response.events);
|
|
540
|
+
LLMResponse2.usage = (response) => response.usage ?? responseUsage(response.events);
|
|
541
|
+
LLMResponse2.toolCalls = (response) => response.events.filter(LLMEvent.is.toolCall);
|
|
542
|
+
LLMResponse2.reasoning = (response) => responseReasoning(response.events);
|
|
543
|
+
})(LLMResponse || (LLMResponse = {}));
|
|
544
|
+
var HttpRequestDetails = class extends effect.Schema.Class("LLM.HttpRequestDetails")({
|
|
545
|
+
method: effect.Schema.String,
|
|
546
|
+
url: effect.Schema.String,
|
|
547
|
+
headers: effect.Schema.Record(effect.Schema.String, effect.Schema.String)
|
|
548
|
+
}) {
|
|
549
|
+
};
|
|
550
|
+
var HttpResponseDetails = class extends effect.Schema.Class("LLM.HttpResponseDetails")({
|
|
551
|
+
status: effect.Schema.Number,
|
|
552
|
+
headers: effect.Schema.Record(effect.Schema.String, effect.Schema.String)
|
|
553
|
+
}) {
|
|
554
|
+
};
|
|
555
|
+
var HttpRateLimitDetails = class extends effect.Schema.Class("LLM.HttpRateLimitDetails")({
|
|
556
|
+
retryAfterMs: effect.Schema.optional(effect.Schema.Number),
|
|
557
|
+
limit: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
|
|
558
|
+
remaining: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String)),
|
|
559
|
+
reset: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.String))
|
|
560
|
+
}) {
|
|
561
|
+
};
|
|
562
|
+
var HttpContext = class extends effect.Schema.Class("LLM.HttpContext")({
|
|
563
|
+
request: HttpRequestDetails,
|
|
564
|
+
response: effect.Schema.optional(HttpResponseDetails),
|
|
565
|
+
body: effect.Schema.optional(effect.Schema.String),
|
|
566
|
+
bodyTruncated: effect.Schema.optional(effect.Schema.Boolean),
|
|
567
|
+
requestId: effect.Schema.optional(effect.Schema.String),
|
|
568
|
+
rateLimit: effect.Schema.optional(HttpRateLimitDetails)
|
|
569
|
+
}) {
|
|
570
|
+
};
|
|
571
|
+
var InvalidRequestReason = class extends effect.Schema.Class("LLM.Error.InvalidRequest")({
|
|
572
|
+
_tag: effect.Schema.tag("InvalidRequest"),
|
|
573
|
+
message: effect.Schema.String,
|
|
574
|
+
parameter: effect.Schema.optional(effect.Schema.String),
|
|
575
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
576
|
+
http: effect.Schema.optional(HttpContext)
|
|
577
|
+
}) {
|
|
578
|
+
get retryable() {
|
|
579
|
+
return false;
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
var ContextOverflowReason = class extends effect.Schema.Class("LLM.Error.ContextOverflow")({
|
|
583
|
+
_tag: effect.Schema.tag("ContextOverflow"),
|
|
584
|
+
message: effect.Schema.String,
|
|
585
|
+
/** Provider-reported prompt token count when present in the error body. */
|
|
586
|
+
promptTokens: effect.Schema.optional(effect.Schema.Number),
|
|
587
|
+
/** Provider-reported context window size when present in the error body. */
|
|
588
|
+
contextWindow: effect.Schema.optional(effect.Schema.Number),
|
|
589
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
590
|
+
http: effect.Schema.optional(HttpContext)
|
|
591
|
+
}) {
|
|
592
|
+
get retryable() {
|
|
593
|
+
return false;
|
|
594
|
+
}
|
|
595
|
+
};
|
|
596
|
+
var NoRouteReason = class extends effect.Schema.Class("LLM.Error.NoRoute")({
|
|
597
|
+
_tag: effect.Schema.tag("NoRoute"),
|
|
598
|
+
route: RouteID,
|
|
599
|
+
provider: ProviderID,
|
|
600
|
+
model: ModelID
|
|
601
|
+
}) {
|
|
602
|
+
get retryable() {
|
|
603
|
+
return false;
|
|
604
|
+
}
|
|
605
|
+
get message() {
|
|
606
|
+
return `No LLM route for ${this.provider}/${this.model} using ${this.route}`;
|
|
607
|
+
}
|
|
608
|
+
};
|
|
609
|
+
var AuthenticationReason = class extends effect.Schema.Class("LLM.Error.Authentication")({
|
|
610
|
+
_tag: effect.Schema.tag("Authentication"),
|
|
611
|
+
message: effect.Schema.String,
|
|
612
|
+
kind: effect.Schema.Literals(["missing", "invalid", "expired", "insufficient-permissions", "unknown"]),
|
|
613
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
614
|
+
http: effect.Schema.optional(HttpContext)
|
|
615
|
+
}) {
|
|
616
|
+
get retryable() {
|
|
617
|
+
return false;
|
|
618
|
+
}
|
|
619
|
+
};
|
|
620
|
+
var RateLimitReason = class extends effect.Schema.Class("LLM.Error.RateLimit")({
|
|
621
|
+
_tag: effect.Schema.tag("RateLimit"),
|
|
622
|
+
message: effect.Schema.String,
|
|
623
|
+
retryAfterMs: effect.Schema.optional(effect.Schema.Number),
|
|
624
|
+
rateLimit: effect.Schema.optional(HttpRateLimitDetails),
|
|
625
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
626
|
+
http: effect.Schema.optional(HttpContext)
|
|
627
|
+
}) {
|
|
628
|
+
get retryable() {
|
|
629
|
+
return true;
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
var QuotaExceededReason = class extends effect.Schema.Class("LLM.Error.QuotaExceeded")({
|
|
633
|
+
_tag: effect.Schema.tag("QuotaExceeded"),
|
|
634
|
+
message: effect.Schema.String,
|
|
635
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
636
|
+
http: effect.Schema.optional(HttpContext)
|
|
637
|
+
}) {
|
|
638
|
+
get retryable() {
|
|
639
|
+
return false;
|
|
640
|
+
}
|
|
641
|
+
};
|
|
642
|
+
var ContentPolicyReason = class extends effect.Schema.Class("LLM.Error.ContentPolicy")({
|
|
643
|
+
_tag: effect.Schema.tag("ContentPolicy"),
|
|
644
|
+
message: effect.Schema.String,
|
|
645
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
646
|
+
http: effect.Schema.optional(HttpContext)
|
|
647
|
+
}) {
|
|
648
|
+
get retryable() {
|
|
649
|
+
return false;
|
|
650
|
+
}
|
|
651
|
+
};
|
|
652
|
+
var ProviderInternalReason = class extends effect.Schema.Class("LLM.Error.ProviderInternal")({
|
|
653
|
+
_tag: effect.Schema.tag("ProviderInternal"),
|
|
654
|
+
message: effect.Schema.String,
|
|
655
|
+
status: effect.Schema.Number,
|
|
656
|
+
retryAfterMs: effect.Schema.optional(effect.Schema.Number),
|
|
657
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
658
|
+
http: effect.Schema.optional(HttpContext)
|
|
659
|
+
}) {
|
|
660
|
+
get retryable() {
|
|
661
|
+
return true;
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
var TransportReason = class extends effect.Schema.Class("LLM.Error.Transport")({
|
|
665
|
+
_tag: effect.Schema.tag("Transport"),
|
|
666
|
+
message: effect.Schema.String,
|
|
667
|
+
kind: effect.Schema.optional(effect.Schema.String),
|
|
668
|
+
url: effect.Schema.optional(effect.Schema.String),
|
|
669
|
+
http: effect.Schema.optional(HttpContext)
|
|
670
|
+
}) {
|
|
671
|
+
get retryable() {
|
|
672
|
+
return false;
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
var InvalidProviderOutputReason = class extends effect.Schema.Class(
|
|
676
|
+
"LLM.Error.InvalidProviderOutput"
|
|
677
|
+
)({
|
|
678
|
+
_tag: effect.Schema.tag("InvalidProviderOutput"),
|
|
679
|
+
message: effect.Schema.String,
|
|
680
|
+
route: effect.Schema.optional(effect.Schema.String),
|
|
681
|
+
raw: effect.Schema.optional(effect.Schema.String),
|
|
682
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata)
|
|
683
|
+
}) {
|
|
684
|
+
get retryable() {
|
|
685
|
+
return false;
|
|
686
|
+
}
|
|
687
|
+
};
|
|
688
|
+
var UnknownProviderReason = class extends effect.Schema.Class("LLM.Error.UnknownProvider")({
|
|
689
|
+
_tag: effect.Schema.tag("UnknownProvider"),
|
|
690
|
+
message: effect.Schema.String,
|
|
691
|
+
status: effect.Schema.optional(effect.Schema.Number),
|
|
692
|
+
providerMetadata: effect.Schema.optional(ProviderMetadata),
|
|
693
|
+
http: effect.Schema.optional(HttpContext)
|
|
694
|
+
}) {
|
|
695
|
+
get retryable() {
|
|
696
|
+
return false;
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
var LLMErrorReason = effect.Schema.Union([
|
|
700
|
+
InvalidRequestReason,
|
|
701
|
+
ContextOverflowReason,
|
|
702
|
+
NoRouteReason,
|
|
703
|
+
AuthenticationReason,
|
|
704
|
+
RateLimitReason,
|
|
705
|
+
QuotaExceededReason,
|
|
706
|
+
ContentPolicyReason,
|
|
707
|
+
ProviderInternalReason,
|
|
708
|
+
TransportReason,
|
|
709
|
+
InvalidProviderOutputReason,
|
|
710
|
+
UnknownProviderReason
|
|
711
|
+
]).pipe(effect.Schema.toTaggedUnion("_tag"));
|
|
712
|
+
var LLMError = class extends effect.Schema.TaggedErrorClass()("LLM.Error", {
|
|
713
|
+
module: effect.Schema.String,
|
|
714
|
+
method: effect.Schema.String,
|
|
715
|
+
reason: LLMErrorReason
|
|
716
|
+
}) {
|
|
717
|
+
cause = this.reason;
|
|
718
|
+
get retryable() {
|
|
719
|
+
return this.reason.retryable;
|
|
720
|
+
}
|
|
721
|
+
get retryAfterMs() {
|
|
722
|
+
return "retryAfterMs" in this.reason ? this.reason.retryAfterMs : void 0;
|
|
723
|
+
}
|
|
724
|
+
get message() {
|
|
725
|
+
return `${this.module}.${this.method}: ${this.reason.message}`;
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
(class extends effect.Schema.TaggedErrorClass()("LLM.ToolFailure", {
|
|
729
|
+
message: effect.Schema.String,
|
|
730
|
+
metadata: effect.Schema.optional(effect.Schema.Record(effect.Schema.String, effect.Schema.Unknown))
|
|
731
|
+
}) {
|
|
732
|
+
});
|
|
733
|
+
|
|
734
|
+
// src/route/overflow-detect.ts
|
|
735
|
+
var OVERFLOW_PATTERNS = [
|
|
736
|
+
/prompt is too long/i,
|
|
737
|
+
// Anthropic
|
|
738
|
+
/input is too long for requested model/i,
|
|
739
|
+
// Amazon Bedrock
|
|
740
|
+
/exceeds the context window/i,
|
|
741
|
+
// OpenAI
|
|
742
|
+
/input token count.*exceeds the maximum/i,
|
|
743
|
+
// Google (Gemini)
|
|
744
|
+
/maximum prompt length is \d+/i,
|
|
745
|
+
// xAI (Grok)
|
|
746
|
+
/reduce the length of the messages/i,
|
|
747
|
+
// Groq
|
|
748
|
+
/maximum context length is \d+ tokens/i,
|
|
749
|
+
// OpenRouter, DeepSeek, vLLM
|
|
750
|
+
/exceeds the limit of \d+/i,
|
|
751
|
+
// GitHub Copilot
|
|
752
|
+
/exceeds the available context size/i,
|
|
753
|
+
// llama.cpp server
|
|
754
|
+
/greater than the context length/i,
|
|
755
|
+
// LM Studio
|
|
756
|
+
/context window exceeds limit/i,
|
|
757
|
+
// MiniMax
|
|
758
|
+
/exceeded model token limit/i,
|
|
759
|
+
// Kimi, Moonshot
|
|
760
|
+
/context[_ ]length[_ ]exceeded/i,
|
|
761
|
+
// Generic OpenAI-style code
|
|
762
|
+
/request entity too large/i,
|
|
763
|
+
// HTTP 413
|
|
764
|
+
/context length is only \d+ tokens/i,
|
|
765
|
+
// vLLM
|
|
766
|
+
/input length.*exceeds.*context length/i,
|
|
767
|
+
// vLLM
|
|
768
|
+
/prompt too long; exceeded (?:max )?context length/i,
|
|
769
|
+
// Ollama
|
|
770
|
+
/too large for model with \d+ maximum context length/i,
|
|
771
|
+
// Mistral
|
|
772
|
+
/model_context_window_exceeded/i
|
|
773
|
+
// z.ai
|
|
774
|
+
];
|
|
775
|
+
var NO_BODY_4XX = /^4(00|13)\s*(status code)?\s*\(no body\)/i;
|
|
776
|
+
var isOverflowMessage = (message) => {
|
|
777
|
+
if (OVERFLOW_PATTERNS.some((p) => p.test(message))) return true;
|
|
778
|
+
return NO_BODY_4XX.test(message);
|
|
779
|
+
};
|
|
780
|
+
var isOverflowStatus = (status) => status === 413;
|
|
781
|
+
var TOKENS_GT_MAX = /(\d{4,})\s*tokens?\s*[>≥]\s*(\d{4,})/i;
|
|
782
|
+
var PROMPT_LENGTH = /prompt is too long:\s*(\d{4,})\s*tokens?\s*>\s*(\d{4,})\s*maximum/i;
|
|
783
|
+
var INPUT_LIMIT = /input length\s*(\d{4,}).*context length\s*(\d{4,})/i;
|
|
784
|
+
var extractOverflowNumbers = (message) => {
|
|
785
|
+
const match = PROMPT_LENGTH.exec(message) ?? INPUT_LIMIT.exec(message) ?? TOKENS_GT_MAX.exec(message);
|
|
786
|
+
if (!match) return void 0;
|
|
787
|
+
const promptTokens = Number(match[1]);
|
|
788
|
+
const contextWindow = Number(match[2]);
|
|
789
|
+
if (!Number.isFinite(promptTokens) || !Number.isFinite(contextWindow)) return void 0;
|
|
790
|
+
return { promptTokens, contextWindow };
|
|
791
|
+
};
|
|
792
|
+
var isOverflowBody = (body) => {
|
|
793
|
+
if (typeof body !== "object" || body === null) return false;
|
|
794
|
+
const root = body;
|
|
795
|
+
const code = root.error?.code ?? root.code;
|
|
796
|
+
if (typeof code === "string" && /context[_ ]length[_ ]exceeded/i.test(code)) return true;
|
|
797
|
+
if (typeof code === "string" && /model_context_window_exceeded/i.test(code)) return true;
|
|
798
|
+
return false;
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// src/route/executor.ts
|
|
802
|
+
var Service = class extends effect.Context.Service()("@tinyweb-agent/LLM/RequestExecutor") {
|
|
803
|
+
};
|
|
804
|
+
var BODY_LIMIT = 16384;
|
|
805
|
+
var MAX_RETRIES = 2;
|
|
806
|
+
var BASE_DELAY_MS = 500;
|
|
807
|
+
var MAX_DELAY_MS = 1e4;
|
|
808
|
+
var REDACTED = "<redacted>";
|
|
809
|
+
var SENSITIVE_NAME_SOURCE = "authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|token|secret|credential|signature|x-amz-signature";
|
|
810
|
+
var SENSITIVE_NAME = new RegExp(SENSITIVE_NAME_SOURCE, "i");
|
|
811
|
+
var SHORT_QUERY_NAME = /^(key|sig)$/i;
|
|
812
|
+
var SENSITIVE_BODY_FIELD = new RegExp(`(?:${SENSITIVE_NAME_SOURCE}|key)`, "i");
|
|
813
|
+
var REDACT_JSON_FIELD = new RegExp(`("(?:${SENSITIVE_BODY_FIELD.source})"\\s*:\\s*)"[^"]*"`, "gi");
|
|
814
|
+
var REDACT_QUERY_FIELD = new RegExp(`((?:${SENSITIVE_BODY_FIELD.source})=)[^&\\s"]+`, "gi");
|
|
815
|
+
var isSensitiveHeaderName = (name) => SENSITIVE_NAME.test(name);
|
|
816
|
+
var isSensitiveQueryName = (name) => isSensitiveHeaderName(name) || SHORT_QUERY_NAME.test(name);
|
|
817
|
+
var redactHeaders = (headers, redactedNames) => Object.fromEntries(
|
|
818
|
+
Object.entries(http.Headers.redact(headers, [...redactedNames, SENSITIVE_NAME])).map(([name, value]) => [
|
|
819
|
+
name,
|
|
820
|
+
String(value)
|
|
821
|
+
])
|
|
822
|
+
);
|
|
823
|
+
var redactUrl = (value) => {
|
|
824
|
+
if (!URL.canParse(value)) return REDACTED;
|
|
825
|
+
const url = new URL(value);
|
|
826
|
+
url.searchParams.forEach((_, key) => {
|
|
827
|
+
if (isSensitiveQueryName(key)) url.searchParams.set(key, REDACTED);
|
|
828
|
+
});
|
|
829
|
+
return url.toString();
|
|
830
|
+
};
|
|
831
|
+
var normalizedHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([key, value]) => [key.toLowerCase(), value]));
|
|
832
|
+
var requestId = (headers) => {
|
|
833
|
+
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"];
|
|
834
|
+
};
|
|
835
|
+
var retryableStatus = (status) => status === 429 || status === 503 || status === 504 || status === 529;
|
|
836
|
+
var retryAfterMs = (headers) => {
|
|
837
|
+
const millis = Number(headers["retry-after-ms"]);
|
|
838
|
+
if (Number.isFinite(millis)) return Math.max(0, millis);
|
|
839
|
+
const value = headers["retry-after"];
|
|
840
|
+
if (!value) return void 0;
|
|
841
|
+
const seconds = Number(value);
|
|
842
|
+
if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
|
|
843
|
+
const date = Date.parse(value);
|
|
844
|
+
if (!Number.isNaN(date)) return Math.max(0, date - Date.now());
|
|
845
|
+
return void 0;
|
|
846
|
+
};
|
|
847
|
+
var addRateLimitValue = (target, key, value) => {
|
|
848
|
+
if (key.length > 0) target[key] = value;
|
|
849
|
+
};
|
|
850
|
+
var rateLimitDetails = (headers, retryAfter) => {
|
|
851
|
+
const limit = {};
|
|
852
|
+
const remaining = {};
|
|
853
|
+
const reset = {};
|
|
854
|
+
Object.entries(headers).forEach(([name, value]) => {
|
|
855
|
+
const openaiLimit = /^x-ratelimit-limit-(.+)$/.exec(name)?.[1];
|
|
856
|
+
if (openaiLimit) return addRateLimitValue(limit, openaiLimit, value);
|
|
857
|
+
const openaiRemaining = /^x-ratelimit-remaining-(.+)$/.exec(name)?.[1];
|
|
858
|
+
if (openaiRemaining) return addRateLimitValue(remaining, openaiRemaining, value);
|
|
859
|
+
const openaiReset = /^x-ratelimit-reset-(.+)$/.exec(name)?.[1];
|
|
860
|
+
if (openaiReset) return addRateLimitValue(reset, openaiReset, value);
|
|
861
|
+
const anthropic = /^anthropic-ratelimit-(.+)-(limit|remaining|reset)$/.exec(name);
|
|
862
|
+
if (!anthropic) return;
|
|
863
|
+
if (anthropic[2] === "limit") return addRateLimitValue(limit, anthropic[1], value);
|
|
864
|
+
if (anthropic[2] === "remaining") return addRateLimitValue(remaining, anthropic[1], value);
|
|
865
|
+
return addRateLimitValue(reset, anthropic[1], value);
|
|
866
|
+
});
|
|
867
|
+
if (retryAfter === void 0 && Object.keys(limit).length === 0 && Object.keys(remaining).length === 0 && Object.keys(reset).length === 0)
|
|
868
|
+
return void 0;
|
|
869
|
+
return new HttpRateLimitDetails({
|
|
870
|
+
retryAfterMs: retryAfter,
|
|
871
|
+
limit: Object.keys(limit).length === 0 ? void 0 : limit,
|
|
872
|
+
remaining: Object.keys(remaining).length === 0 ? void 0 : remaining,
|
|
873
|
+
reset: Object.keys(reset).length === 0 ? void 0 : reset
|
|
874
|
+
});
|
|
875
|
+
};
|
|
876
|
+
var requestDetails = (request, redactedNames) => new HttpRequestDetails({
|
|
877
|
+
method: request.method,
|
|
878
|
+
url: redactUrl(request.url),
|
|
879
|
+
headers: redactHeaders(request.headers, redactedNames)
|
|
880
|
+
});
|
|
881
|
+
var responseDetails = (response, redactedNames) => new HttpResponseDetails({
|
|
882
|
+
status: response.status,
|
|
883
|
+
headers: redactHeaders(response.headers, redactedNames)
|
|
884
|
+
});
|
|
885
|
+
var secretValues = (request) => {
|
|
886
|
+
const values = /* @__PURE__ */ new Set();
|
|
887
|
+
const add = (value) => {
|
|
888
|
+
if (value.length < 4) return;
|
|
889
|
+
values.add(value);
|
|
890
|
+
values.add(encodeURIComponent(value));
|
|
891
|
+
};
|
|
892
|
+
Object.entries(request.headers).forEach(([name, value]) => {
|
|
893
|
+
if (!isSensitiveHeaderName(name)) return;
|
|
894
|
+
add(value);
|
|
895
|
+
const bearer = /^Bearer\s+(.+)$/i.exec(value)?.[1];
|
|
896
|
+
if (bearer) add(bearer);
|
|
897
|
+
});
|
|
898
|
+
if (!URL.canParse(request.url)) return values;
|
|
899
|
+
new URL(request.url).searchParams.forEach((value, key) => {
|
|
900
|
+
if (isSensitiveQueryName(key)) add(value);
|
|
901
|
+
});
|
|
902
|
+
return values;
|
|
903
|
+
};
|
|
904
|
+
var redactBody = (body, request) => Array.from(secretValues(request)).reduce(
|
|
905
|
+
(text, secret) => text.split(secret).join(REDACTED),
|
|
906
|
+
body.replace(REDACT_JSON_FIELD, `$1"${REDACTED}"`).replace(REDACT_QUERY_FIELD, `$1${REDACTED}`)
|
|
907
|
+
);
|
|
908
|
+
var responseBody = (body, request) => {
|
|
909
|
+
if (body === void 0) return {};
|
|
910
|
+
const redacted = redactBody(body, request);
|
|
911
|
+
if (redacted.length <= BODY_LIMIT) return { body: redacted };
|
|
912
|
+
return { body: redacted.slice(0, BODY_LIMIT), bodyTruncated: true };
|
|
913
|
+
};
|
|
914
|
+
var providerMessage = (status, body) => {
|
|
915
|
+
if (body.body && body.body.length <= 500) return `Provider request failed with HTTP ${status}: ${body.body}`;
|
|
916
|
+
return `Provider request failed with HTTP ${status}`;
|
|
917
|
+
};
|
|
918
|
+
var responseHttp = (input) => new HttpContext({
|
|
919
|
+
request: requestDetails(input.request, input.redactedNames),
|
|
920
|
+
response: responseDetails(input.response, input.redactedNames),
|
|
921
|
+
...input.body,
|
|
922
|
+
requestId: input.requestId,
|
|
923
|
+
rateLimit: input.rateLimit
|
|
924
|
+
});
|
|
925
|
+
var parseJsonBody = (body) => {
|
|
926
|
+
if (body.length === 0) return void 0;
|
|
927
|
+
try {
|
|
928
|
+
return JSON.parse(body);
|
|
929
|
+
} catch {
|
|
930
|
+
return void 0;
|
|
931
|
+
}
|
|
932
|
+
};
|
|
933
|
+
var isOverflow = (status, message, body) => {
|
|
934
|
+
if (isOverflowStatus(status)) return true;
|
|
935
|
+
if (isOverflowMessage(message)) return true;
|
|
936
|
+
if (body.length > 0 && isOverflowMessage(body)) return true;
|
|
937
|
+
return isOverflowBody(parseJsonBody(body));
|
|
938
|
+
};
|
|
939
|
+
var overflowReason = (input) => {
|
|
940
|
+
const numbers = extractOverflowNumbers(input.message) ?? extractOverflowNumbers(input.body);
|
|
941
|
+
return new ContextOverflowReason({
|
|
942
|
+
message: input.message,
|
|
943
|
+
promptTokens: numbers?.promptTokens,
|
|
944
|
+
contextWindow: numbers?.contextWindow,
|
|
945
|
+
http: input.http
|
|
946
|
+
});
|
|
947
|
+
};
|
|
948
|
+
var statusReason = (input) => {
|
|
949
|
+
const body = input.http.body ?? "";
|
|
950
|
+
if (isOverflow(input.status, input.message, body)) {
|
|
951
|
+
return overflowReason({ message: input.message, body, http: input.http });
|
|
952
|
+
}
|
|
953
|
+
if (/content[-_\s]?policy|content_filter|safety/i.test(body)) {
|
|
954
|
+
return new ContentPolicyReason({ message: input.message, http: input.http });
|
|
955
|
+
}
|
|
956
|
+
if (input.status === 401) {
|
|
957
|
+
return new AuthenticationReason({ message: input.message, kind: "invalid", http: input.http });
|
|
958
|
+
}
|
|
959
|
+
if (input.status === 403) {
|
|
960
|
+
return new AuthenticationReason({ message: input.message, kind: "insufficient-permissions", http: input.http });
|
|
961
|
+
}
|
|
962
|
+
if (input.status === 429) {
|
|
963
|
+
if (/insufficient[-_\s]?quota|quota[-_\s]?exceeded/i.test(body)) {
|
|
964
|
+
return new QuotaExceededReason({ message: input.message, http: input.http });
|
|
965
|
+
}
|
|
966
|
+
return new RateLimitReason({
|
|
967
|
+
message: input.message,
|
|
968
|
+
retryAfterMs: input.retryAfterMs,
|
|
969
|
+
rateLimit: input.rateLimit,
|
|
970
|
+
http: input.http
|
|
971
|
+
});
|
|
972
|
+
}
|
|
973
|
+
if (input.status === 400 || input.status === 404 || input.status === 409 || input.status === 422) {
|
|
974
|
+
return new InvalidRequestReason({ message: input.message, http: input.http });
|
|
975
|
+
}
|
|
976
|
+
if (input.status >= 500 || retryableStatus(input.status)) {
|
|
977
|
+
return new ProviderInternalReason({
|
|
978
|
+
message: input.message,
|
|
979
|
+
status: input.status,
|
|
980
|
+
retryAfterMs: input.retryAfterMs,
|
|
981
|
+
http: input.http
|
|
982
|
+
});
|
|
983
|
+
}
|
|
984
|
+
return new UnknownProviderReason({ message: input.message, status: input.status, http: input.http });
|
|
985
|
+
};
|
|
986
|
+
var statusError = (request, redactedNames) => (response) => effect.Effect.gen(function* () {
|
|
987
|
+
if (response.status < 400) return response;
|
|
988
|
+
const body = yield* response.text.pipe(effect.Effect.catch(() => effect.Effect.void));
|
|
989
|
+
const headers = normalizedHeaders(response.headers);
|
|
990
|
+
const retryAfter = retryAfterMs(headers);
|
|
991
|
+
const rateLimit = rateLimitDetails(headers, retryAfter);
|
|
992
|
+
const details = responseBody(body, request);
|
|
993
|
+
return yield* new LLMError({
|
|
994
|
+
module: "RequestExecutor",
|
|
995
|
+
method: "execute",
|
|
996
|
+
reason: statusReason({
|
|
997
|
+
status: response.status,
|
|
998
|
+
message: providerMessage(response.status, details),
|
|
999
|
+
retryAfterMs: retryAfter,
|
|
1000
|
+
rateLimit,
|
|
1001
|
+
http: responseHttp({
|
|
1002
|
+
request,
|
|
1003
|
+
response,
|
|
1004
|
+
redactedNames,
|
|
1005
|
+
body: details,
|
|
1006
|
+
requestId: requestId(headers),
|
|
1007
|
+
rateLimit
|
|
1008
|
+
})
|
|
1009
|
+
})
|
|
1010
|
+
});
|
|
1011
|
+
});
|
|
1012
|
+
var toHttpError = (redactedNames) => (error) => {
|
|
1013
|
+
const transportError = (input) => new LLMError({
|
|
1014
|
+
module: "RequestExecutor",
|
|
1015
|
+
method: "execute",
|
|
1016
|
+
reason: new TransportReason({
|
|
1017
|
+
message: input.message,
|
|
1018
|
+
kind: input.kind,
|
|
1019
|
+
url: input.request ? redactUrl(input.request.url) : void 0,
|
|
1020
|
+
http: input.request ? new HttpContext({ request: requestDetails(input.request, redactedNames) }) : void 0
|
|
1021
|
+
})
|
|
1022
|
+
});
|
|
1023
|
+
if (effect.Cause.isTimeoutError(error)) {
|
|
1024
|
+
return transportError({ message: error.message, kind: "Timeout" });
|
|
1025
|
+
}
|
|
1026
|
+
if (!http.HttpClientError.isHttpClientError(error)) {
|
|
1027
|
+
return transportError({ message: "HTTP transport failed" });
|
|
1028
|
+
}
|
|
1029
|
+
const request = "request" in error ? error.request : void 0;
|
|
1030
|
+
if (error.reason._tag === "TransportError") {
|
|
1031
|
+
return transportError({
|
|
1032
|
+
message: error.reason.description ?? "HTTP transport failed",
|
|
1033
|
+
kind: error.reason._tag,
|
|
1034
|
+
request
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
return transportError({
|
|
1038
|
+
message: `HTTP transport failed: ${error.reason._tag}`,
|
|
1039
|
+
kind: error.reason._tag,
|
|
1040
|
+
request
|
|
1041
|
+
});
|
|
1042
|
+
};
|
|
1043
|
+
var retryDelay = (error, attempt) => {
|
|
1044
|
+
if (error.retryAfterMs !== void 0) return effect.Effect.succeed(Math.min(error.retryAfterMs, MAX_DELAY_MS));
|
|
1045
|
+
return effect.Random.nextBetween(
|
|
1046
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 0.8, MAX_DELAY_MS),
|
|
1047
|
+
Math.min(BASE_DELAY_MS * 2 ** attempt * 1.2, MAX_DELAY_MS)
|
|
1048
|
+
).pipe(effect.Effect.map((delay) => Math.round(delay)));
|
|
1049
|
+
};
|
|
1050
|
+
var retryStatusFailures = (effect$1, retries = MAX_RETRIES, attempt = 0) => effect.Effect.catchTag(effect$1, "LLM.Error", (error) => {
|
|
1051
|
+
if (!error.retryable || retries <= 0) return effect.Effect.fail(error);
|
|
1052
|
+
return retryDelay(error, attempt).pipe(
|
|
1053
|
+
effect.Effect.flatMap((delay) => effect.Effect.sleep(delay)),
|
|
1054
|
+
effect.Effect.flatMap(() => retryStatusFailures(effect$1, retries - 1, attempt + 1))
|
|
1055
|
+
);
|
|
1056
|
+
});
|
|
1057
|
+
var layer = effect.Layer.effect(
|
|
1058
|
+
Service,
|
|
1059
|
+
effect.Effect.gen(function* () {
|
|
1060
|
+
const http$1 = yield* http.HttpClient.HttpClient;
|
|
1061
|
+
const executeOnce = (request) => effect.Effect.gen(function* () {
|
|
1062
|
+
const redactedNames = yield* http.Headers.CurrentRedactedNames;
|
|
1063
|
+
return yield* http$1.execute(request).pipe(effect.Effect.mapError(toHttpError(redactedNames)), effect.Effect.flatMap(statusError(request, redactedNames)));
|
|
1064
|
+
});
|
|
1065
|
+
return Service.of({
|
|
1066
|
+
execute: (request) => retryStatusFailures(executeOnce(request))
|
|
1067
|
+
});
|
|
1068
|
+
})
|
|
1069
|
+
);
|
|
1070
|
+
var defaultLayer = layer.pipe(effect.Layer.provide(http.FetchHttpClient.layer));
|
|
1071
|
+
|
|
1072
|
+
exports.RequestExecutor = executor_exports;
|
|
1073
|
+
exports.Service = Service;
|
|
1074
|
+
exports.defaultLayer = defaultLayer;
|
|
1075
|
+
exports.layer = layer;
|
|
1076
|
+
//# sourceMappingURL=executor.cjs.map
|
|
1077
|
+
//# sourceMappingURL=executor.cjs.map
|