@chimp-labs/keel-ai-kit 0.0.0-stage → 0.1.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/CHANGELOG.md +7 -0
- package/LICENSE +21 -0
- package/README.md +33 -2
- package/dist/agent.d.ts +365 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/agent.js +886 -0
- package/dist/agent.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +18 -0
- package/dist/index.js.map +1 -0
- package/dist/internal/posix-path.d.ts +3 -0
- package/dist/internal/posix-path.d.ts.map +1 -0
- package/dist/internal/posix-path.js +13 -0
- package/dist/internal/posix-path.js.map +1 -0
- package/dist/llm/providers.d.ts +81 -0
- package/dist/llm/providers.d.ts.map +1 -0
- package/dist/llm/providers.js +854 -0
- package/dist/llm/providers.js.map +1 -0
- package/dist/llm.d.ts +133 -0
- package/dist/llm.d.ts.map +1 -0
- package/dist/llm.js +164 -0
- package/dist/llm.js.map +1 -0
- package/dist/sandbox/providers.d.ts +74 -0
- package/dist/sandbox/providers.d.ts.map +1 -0
- package/dist/sandbox/providers.js +655 -0
- package/dist/sandbox/providers.js.map +1 -0
- package/dist/sandbox.d.ts +390 -0
- package/dist/sandbox.d.ts.map +1 -0
- package/dist/sandbox.js +1000 -0
- package/dist/sandbox.js.map +1 -0
- package/package.json +85 -3
|
@@ -0,0 +1,854 @@
|
|
|
1
|
+
import { Effect, Layer, Option, Redacted } from "effect";
|
|
2
|
+
import { createHash, createHmac } from "node:crypto";
|
|
3
|
+
import { LlmError, LlmProvider, LlmRateLimitError, } from "../llm.js";
|
|
4
|
+
import { SecretStore } from "@chimp-labs/keel";
|
|
5
|
+
const resolveApiKey = (input, provider, model, required = true) => {
|
|
6
|
+
if (input === undefined) {
|
|
7
|
+
if (!required)
|
|
8
|
+
return Effect.succeed(undefined);
|
|
9
|
+
return Effect.fail(new LlmError({
|
|
10
|
+
provider,
|
|
11
|
+
model,
|
|
12
|
+
cause: new Error(`Missing API key for LLM provider "${provider}"`),
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
if (typeof input === "string")
|
|
16
|
+
return Effect.succeed(input);
|
|
17
|
+
if (typeof input === "function" && !("secretName" in input)) {
|
|
18
|
+
return Effect.try({
|
|
19
|
+
try: () => input(),
|
|
20
|
+
catch: (cause) => new LlmError({ provider, model, cause }),
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
if (Redacted.isRedacted(input)) {
|
|
24
|
+
return Effect.succeed(Redacted.value(input));
|
|
25
|
+
}
|
|
26
|
+
// Keel `Secret` descriptor -> resolve from `SecretStore` if present
|
|
27
|
+
const secDef = input;
|
|
28
|
+
return Effect.gen(function* () {
|
|
29
|
+
const storeOpt = yield* Effect.serviceOption(SecretStore);
|
|
30
|
+
if (Option.isNone(storeOpt)) {
|
|
31
|
+
return yield* new LlmError({
|
|
32
|
+
provider,
|
|
33
|
+
model,
|
|
34
|
+
cause: new Error(`SecretStore is required to resolve secret "${secDef.secretName}" for LLM provider "${provider}"`),
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
const val = yield* storeOpt.value.get(secDef.secretName).pipe(Effect.mapError((cause) => new LlmError({ provider, model, cause })));
|
|
38
|
+
return Redacted.value(val);
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
const parseRetryAfterMs = (res) => {
|
|
42
|
+
const header = res.headers.get("retry-after");
|
|
43
|
+
if (!header)
|
|
44
|
+
return undefined;
|
|
45
|
+
const secs = Number(header);
|
|
46
|
+
if (!Number.isNaN(secs) && secs >= 0)
|
|
47
|
+
return Math.ceil(secs * 1000);
|
|
48
|
+
const dateMs = Date.parse(header);
|
|
49
|
+
if (!Number.isNaN(dateMs))
|
|
50
|
+
return Math.max(0, dateMs - Date.now());
|
|
51
|
+
return undefined;
|
|
52
|
+
};
|
|
53
|
+
const fetchJson = (fetchFn, provider, model, url, init) => Effect.gen(function* () {
|
|
54
|
+
const res = yield* Effect.tryPromise({
|
|
55
|
+
try: () => fetchFn(url, init),
|
|
56
|
+
catch: (cause) => new LlmError({ provider, model, cause }),
|
|
57
|
+
});
|
|
58
|
+
if (res.status === 429) {
|
|
59
|
+
return yield* new LlmRateLimitError({
|
|
60
|
+
provider,
|
|
61
|
+
model,
|
|
62
|
+
...(parseRetryAfterMs(res) !== undefined
|
|
63
|
+
? { retryAfterMs: parseRetryAfterMs(res) }
|
|
64
|
+
: {}),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
const text = yield* Effect.tryPromise({
|
|
68
|
+
try: () => res.text(),
|
|
69
|
+
catch: (cause) => new LlmError({ provider, model, status: res.status, cause }),
|
|
70
|
+
});
|
|
71
|
+
if (!res.ok) {
|
|
72
|
+
return yield* new LlmError({
|
|
73
|
+
provider,
|
|
74
|
+
model,
|
|
75
|
+
status: res.status,
|
|
76
|
+
cause: new Error(`${provider} API returned HTTP ${res.status}: ${text.slice(0, 500)}`),
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
return yield* Effect.try({
|
|
80
|
+
try: () => JSON.parse(text),
|
|
81
|
+
catch: (cause) => new LlmError({ provider, model, status: res.status, cause }),
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
const safeParseJsonObject = (raw) => {
|
|
85
|
+
if (raw && typeof raw === "object" && !Array.isArray(raw)) {
|
|
86
|
+
return raw;
|
|
87
|
+
}
|
|
88
|
+
if (typeof raw === "string") {
|
|
89
|
+
try {
|
|
90
|
+
const parsed = JSON.parse(raw);
|
|
91
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
92
|
+
return parsed;
|
|
93
|
+
}
|
|
94
|
+
return { value: parsed };
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
return { raw };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return {};
|
|
101
|
+
};
|
|
102
|
+
// ---------------------------------------------------------------------------
|
|
103
|
+
// OpenAI-Compatible Wire Codec (Shared by OpenAI, OpenRouter, LiteLLM)
|
|
104
|
+
// ---------------------------------------------------------------------------
|
|
105
|
+
const toOpenAIMessages = (messages) => messages.map((m) => {
|
|
106
|
+
if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
|
|
107
|
+
return {
|
|
108
|
+
role: "assistant",
|
|
109
|
+
content: m.content || null,
|
|
110
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
111
|
+
id: tc.id,
|
|
112
|
+
type: "function",
|
|
113
|
+
function: {
|
|
114
|
+
name: tc.name,
|
|
115
|
+
arguments: JSON.stringify(tc.arguments),
|
|
116
|
+
},
|
|
117
|
+
})),
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
if (m.role === "tool") {
|
|
121
|
+
return {
|
|
122
|
+
role: "tool",
|
|
123
|
+
tool_call_id: m.toolCallId,
|
|
124
|
+
name: m.name,
|
|
125
|
+
content: m.content,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
return {
|
|
129
|
+
role: m.role,
|
|
130
|
+
content: m.content,
|
|
131
|
+
};
|
|
132
|
+
});
|
|
133
|
+
const parseOpenAIResponse = (data, fallbackModel) => {
|
|
134
|
+
const choice = data?.choices?.[0];
|
|
135
|
+
const msg = choice?.message ?? {};
|
|
136
|
+
const toolCalls = Array.isArray(msg.tool_calls)
|
|
137
|
+
? msg.tool_calls.map((tc, idx) => ({
|
|
138
|
+
id: String(tc.id ?? `call_${idx + 1}`),
|
|
139
|
+
name: String(tc.function?.name ?? tc.name ?? ""),
|
|
140
|
+
arguments: safeParseJsonObject(tc.function?.arguments ?? tc.arguments),
|
|
141
|
+
}))
|
|
142
|
+
: [];
|
|
143
|
+
const rawFinish = String(choice?.finish_reason ?? "");
|
|
144
|
+
const finishReason = rawFinish === "tool_calls" || toolCalls.length > 0
|
|
145
|
+
? "tool_calls"
|
|
146
|
+
: rawFinish === "stop"
|
|
147
|
+
? "stop"
|
|
148
|
+
: rawFinish === "length"
|
|
149
|
+
? "length"
|
|
150
|
+
: rawFinish === "content_filter"
|
|
151
|
+
? "content_filter"
|
|
152
|
+
: "unknown";
|
|
153
|
+
const usage = data?.usage
|
|
154
|
+
? {
|
|
155
|
+
inputTokens: Number(data.usage.prompt_tokens ?? 0),
|
|
156
|
+
outputTokens: Number(data.usage.completion_tokens ?? 0),
|
|
157
|
+
totalTokens: Number(data.usage.total_tokens ?? 0),
|
|
158
|
+
}
|
|
159
|
+
: undefined;
|
|
160
|
+
return {
|
|
161
|
+
content: typeof msg.content === "string" ? msg.content : "",
|
|
162
|
+
toolCalls,
|
|
163
|
+
finishReason,
|
|
164
|
+
...(usage ? { usage } : {}),
|
|
165
|
+
model: typeof data?.model === "string" ? data.model : fallbackModel,
|
|
166
|
+
raw: data,
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
const buildOpenAIChatBody = (request, extraBody) => ({
|
|
170
|
+
model: request.model,
|
|
171
|
+
messages: toOpenAIMessages(request.messages),
|
|
172
|
+
...(request.tools && request.tools.length > 0
|
|
173
|
+
? {
|
|
174
|
+
tools: request.tools.map((t) => ({
|
|
175
|
+
type: "function",
|
|
176
|
+
function: {
|
|
177
|
+
name: t.name,
|
|
178
|
+
description: t.description,
|
|
179
|
+
parameters: t.parameters,
|
|
180
|
+
},
|
|
181
|
+
})),
|
|
182
|
+
}
|
|
183
|
+
: {}),
|
|
184
|
+
...(request.temperature !== undefined
|
|
185
|
+
? { temperature: request.temperature }
|
|
186
|
+
: {}),
|
|
187
|
+
...(request.maxTokens !== undefined ? { max_tokens: request.maxTokens } : {}),
|
|
188
|
+
...(request.stop && request.stop.length > 0 ? { stop: request.stop } : {}),
|
|
189
|
+
...(request.responseSchema !== undefined
|
|
190
|
+
? {
|
|
191
|
+
response_format: {
|
|
192
|
+
type: "json_schema",
|
|
193
|
+
json_schema: {
|
|
194
|
+
name: "keel_agent_output",
|
|
195
|
+
schema: request.responseSchema,
|
|
196
|
+
strict: false,
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
}
|
|
200
|
+
: {}),
|
|
201
|
+
...(extraBody ?? {}),
|
|
202
|
+
});
|
|
203
|
+
export const LlmOpenAILive = (config) => {
|
|
204
|
+
const baseUrl = (config.baseUrl ?? "https://api.openai.com/v1").replace(/\/+$/, "");
|
|
205
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
206
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
207
|
+
providerName: "openai",
|
|
208
|
+
generate: (request) => Effect.gen(function* () {
|
|
209
|
+
const apiKey = yield* resolveApiKey(config.apiKey, "openai", request.model);
|
|
210
|
+
const headers = {
|
|
211
|
+
"content-type": "application/json",
|
|
212
|
+
authorization: `Bearer ${apiKey}`,
|
|
213
|
+
...(config.organization
|
|
214
|
+
? { "openai-organization": config.organization }
|
|
215
|
+
: {}),
|
|
216
|
+
...(config.headers ?? {}),
|
|
217
|
+
};
|
|
218
|
+
const data = yield* fetchJson(fetchFn, "openai", request.model, `${baseUrl}/chat/completions`, {
|
|
219
|
+
method: "POST",
|
|
220
|
+
headers,
|
|
221
|
+
body: JSON.stringify(buildOpenAIChatBody(request)),
|
|
222
|
+
});
|
|
223
|
+
return parseOpenAIResponse(data, request.model);
|
|
224
|
+
}),
|
|
225
|
+
}));
|
|
226
|
+
};
|
|
227
|
+
export const LlmAnthropicLive = (config) => {
|
|
228
|
+
const baseUrl = (config.baseUrl ?? "https://api.anthropic.com/v1").replace(/\/+$/, "");
|
|
229
|
+
const version = config.anthropicVersion ?? "2023-06-01";
|
|
230
|
+
const defaultMaxTokens = config.defaultMaxTokens ?? 4096;
|
|
231
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
232
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
233
|
+
providerName: "anthropic",
|
|
234
|
+
generate: (request) => Effect.gen(function* () {
|
|
235
|
+
const apiKey = yield* resolveApiKey(config.apiKey, "anthropic", request.model);
|
|
236
|
+
const systemParts = [];
|
|
237
|
+
const messages = [];
|
|
238
|
+
for (const m of request.messages) {
|
|
239
|
+
if (m.role === "system") {
|
|
240
|
+
systemParts.push(m.content);
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
if (m.role === "user") {
|
|
244
|
+
messages.push({ role: "user", content: m.content });
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (m.role === "assistant") {
|
|
248
|
+
const blocks = [];
|
|
249
|
+
if (m.content)
|
|
250
|
+
blocks.push({ type: "text", text: m.content });
|
|
251
|
+
for (const tc of m.toolCalls ?? []) {
|
|
252
|
+
blocks.push({
|
|
253
|
+
type: "tool_use",
|
|
254
|
+
id: tc.id,
|
|
255
|
+
name: tc.name,
|
|
256
|
+
input: tc.arguments,
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
messages.push({
|
|
260
|
+
role: "assistant",
|
|
261
|
+
content: blocks.length > 0 ? blocks : m.content,
|
|
262
|
+
});
|
|
263
|
+
continue;
|
|
264
|
+
}
|
|
265
|
+
if (m.role === "tool") {
|
|
266
|
+
messages.push({
|
|
267
|
+
role: "user",
|
|
268
|
+
content: [
|
|
269
|
+
{
|
|
270
|
+
type: "tool_result",
|
|
271
|
+
tool_use_id: m.toolCallId,
|
|
272
|
+
content: m.content,
|
|
273
|
+
...(m.isError ? { is_error: true } : {}),
|
|
274
|
+
},
|
|
275
|
+
],
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
const body = {
|
|
280
|
+
model: request.model,
|
|
281
|
+
max_tokens: request.maxTokens ?? defaultMaxTokens,
|
|
282
|
+
messages,
|
|
283
|
+
...(systemParts.length > 0
|
|
284
|
+
? { system: systemParts.join("\n\n") }
|
|
285
|
+
: {}),
|
|
286
|
+
...(request.temperature !== undefined
|
|
287
|
+
? { temperature: request.temperature }
|
|
288
|
+
: {}),
|
|
289
|
+
...(request.stop && request.stop.length > 0
|
|
290
|
+
? { stop_sequences: request.stop }
|
|
291
|
+
: {}),
|
|
292
|
+
...(request.tools && request.tools.length > 0
|
|
293
|
+
? {
|
|
294
|
+
tools: request.tools.map((t) => ({
|
|
295
|
+
name: t.name,
|
|
296
|
+
description: t.description,
|
|
297
|
+
input_schema: t.parameters,
|
|
298
|
+
})),
|
|
299
|
+
}
|
|
300
|
+
: {}),
|
|
301
|
+
};
|
|
302
|
+
const data = yield* fetchJson(fetchFn, "anthropic", request.model, `${baseUrl}/messages`, {
|
|
303
|
+
method: "POST",
|
|
304
|
+
headers: {
|
|
305
|
+
"content-type": "application/json",
|
|
306
|
+
"x-api-key": apiKey,
|
|
307
|
+
"anthropic-version": version,
|
|
308
|
+
...(config.headers ?? {}),
|
|
309
|
+
},
|
|
310
|
+
body: JSON.stringify(body),
|
|
311
|
+
});
|
|
312
|
+
const textParts = [];
|
|
313
|
+
const toolCalls = [];
|
|
314
|
+
for (const block of Array.isArray(data?.content) ? data.content : []) {
|
|
315
|
+
if (block.type === "text" && typeof block.text === "string") {
|
|
316
|
+
textParts.push(block.text);
|
|
317
|
+
}
|
|
318
|
+
else if (block.type === "tool_use") {
|
|
319
|
+
toolCalls.push({
|
|
320
|
+
id: String(block.id ?? `call_${toolCalls.length + 1}`),
|
|
321
|
+
name: String(block.name ?? ""),
|
|
322
|
+
arguments: safeParseJsonObject(block.input),
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
const stopReason = String(data?.stop_reason ?? "");
|
|
327
|
+
const finishReason = stopReason === "tool_use" || toolCalls.length > 0
|
|
328
|
+
? "tool_calls"
|
|
329
|
+
: stopReason === "end_turn" || stopReason === "stop_sequence"
|
|
330
|
+
? "stop"
|
|
331
|
+
: stopReason === "max_tokens"
|
|
332
|
+
? "length"
|
|
333
|
+
: "unknown";
|
|
334
|
+
const usage = data?.usage
|
|
335
|
+
? {
|
|
336
|
+
inputTokens: Number(data.usage.input_tokens ?? 0),
|
|
337
|
+
outputTokens: Number(data.usage.output_tokens ?? 0),
|
|
338
|
+
totalTokens: Number(data.usage.input_tokens ?? 0) +
|
|
339
|
+
Number(data.usage.output_tokens ?? 0),
|
|
340
|
+
}
|
|
341
|
+
: undefined;
|
|
342
|
+
return {
|
|
343
|
+
content: textParts.join(""),
|
|
344
|
+
toolCalls,
|
|
345
|
+
finishReason,
|
|
346
|
+
...(usage ? { usage } : {}),
|
|
347
|
+
model: typeof data?.model === "string" ? data.model : request.model,
|
|
348
|
+
raw: data,
|
|
349
|
+
};
|
|
350
|
+
}),
|
|
351
|
+
}));
|
|
352
|
+
};
|
|
353
|
+
export const LlmGeminiLive = (config) => {
|
|
354
|
+
const baseUrl = (config.baseUrl ?? "https://generativelanguage.googleapis.com/v1beta").replace(/\/+$/, "");
|
|
355
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
356
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
357
|
+
providerName: "gemini",
|
|
358
|
+
generate: (request) => Effect.gen(function* () {
|
|
359
|
+
const apiKey = yield* resolveApiKey(config.apiKey, "gemini", request.model);
|
|
360
|
+
const systemParts = [];
|
|
361
|
+
const contents = [];
|
|
362
|
+
for (const m of request.messages) {
|
|
363
|
+
if (m.role === "system") {
|
|
364
|
+
systemParts.push(m.content);
|
|
365
|
+
}
|
|
366
|
+
else if (m.role === "user") {
|
|
367
|
+
contents.push({ role: "user", parts: [{ text: m.content }] });
|
|
368
|
+
}
|
|
369
|
+
else if (m.role === "assistant") {
|
|
370
|
+
const parts = [];
|
|
371
|
+
if (m.content)
|
|
372
|
+
parts.push({ text: m.content });
|
|
373
|
+
for (const tc of m.toolCalls ?? []) {
|
|
374
|
+
parts.push({
|
|
375
|
+
functionCall: {
|
|
376
|
+
name: tc.name,
|
|
377
|
+
args: tc.arguments,
|
|
378
|
+
},
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
contents.push({ role: "model", parts });
|
|
382
|
+
}
|
|
383
|
+
else if (m.role === "tool") {
|
|
384
|
+
contents.push({
|
|
385
|
+
role: "user",
|
|
386
|
+
parts: [
|
|
387
|
+
{
|
|
388
|
+
functionResponse: {
|
|
389
|
+
name: m.name,
|
|
390
|
+
response: safeParseJsonObject(m.content),
|
|
391
|
+
},
|
|
392
|
+
},
|
|
393
|
+
],
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
const generationConfig = {
|
|
398
|
+
...(request.temperature !== undefined
|
|
399
|
+
? { temperature: request.temperature }
|
|
400
|
+
: {}),
|
|
401
|
+
...(request.maxTokens !== undefined
|
|
402
|
+
? { maxOutputTokens: request.maxTokens }
|
|
403
|
+
: {}),
|
|
404
|
+
...(request.stop && request.stop.length > 0
|
|
405
|
+
? { stopSequences: request.stop }
|
|
406
|
+
: {}),
|
|
407
|
+
...(request.responseSchema !== undefined
|
|
408
|
+
? {
|
|
409
|
+
responseMimeType: "application/json",
|
|
410
|
+
responseSchema: request.responseSchema,
|
|
411
|
+
}
|
|
412
|
+
: {}),
|
|
413
|
+
};
|
|
414
|
+
const body = {
|
|
415
|
+
contents,
|
|
416
|
+
...(systemParts.length > 0
|
|
417
|
+
? { systemInstruction: { parts: [{ text: systemParts.join("\n\n") }] } }
|
|
418
|
+
: {}),
|
|
419
|
+
...(Object.keys(generationConfig).length > 0
|
|
420
|
+
? { generationConfig }
|
|
421
|
+
: {}),
|
|
422
|
+
...(request.tools && request.tools.length > 0
|
|
423
|
+
? {
|
|
424
|
+
tools: [
|
|
425
|
+
{
|
|
426
|
+
functionDeclarations: request.tools.map((t) => ({
|
|
427
|
+
name: t.name,
|
|
428
|
+
description: t.description,
|
|
429
|
+
parameters: t.parameters,
|
|
430
|
+
})),
|
|
431
|
+
},
|
|
432
|
+
],
|
|
433
|
+
}
|
|
434
|
+
: {}),
|
|
435
|
+
};
|
|
436
|
+
const url = `${baseUrl}/models/${encodeURIComponent(request.model)}:generateContent`;
|
|
437
|
+
const data = yield* fetchJson(fetchFn, "gemini", request.model, url, {
|
|
438
|
+
method: "POST",
|
|
439
|
+
headers: {
|
|
440
|
+
"content-type": "application/json",
|
|
441
|
+
"x-goog-api-key": apiKey,
|
|
442
|
+
...(config.headers ?? {}),
|
|
443
|
+
},
|
|
444
|
+
body: JSON.stringify(body),
|
|
445
|
+
});
|
|
446
|
+
const candidate = data?.candidates?.[0];
|
|
447
|
+
const parts = Array.isArray(candidate?.content?.parts)
|
|
448
|
+
? candidate.content.parts
|
|
449
|
+
: [];
|
|
450
|
+
const textParts = [];
|
|
451
|
+
const toolCalls = [];
|
|
452
|
+
for (const part of parts) {
|
|
453
|
+
if (typeof part.text === "string")
|
|
454
|
+
textParts.push(part.text);
|
|
455
|
+
if (part.functionCall) {
|
|
456
|
+
toolCalls.push({
|
|
457
|
+
id: `gemini_call_${toolCalls.length + 1}`,
|
|
458
|
+
name: String(part.functionCall.name ?? ""),
|
|
459
|
+
arguments: safeParseJsonObject(part.functionCall.args),
|
|
460
|
+
});
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
const rawFinish = String(candidate?.finishReason ?? "");
|
|
464
|
+
const finishReason = toolCalls.length > 0
|
|
465
|
+
? "tool_calls"
|
|
466
|
+
: rawFinish === "STOP"
|
|
467
|
+
? "stop"
|
|
468
|
+
: rawFinish === "MAX_TOKENS"
|
|
469
|
+
? "length"
|
|
470
|
+
: rawFinish === "SAFETY"
|
|
471
|
+
? "content_filter"
|
|
472
|
+
: "unknown";
|
|
473
|
+
const meta = data?.usageMetadata;
|
|
474
|
+
const usage = meta
|
|
475
|
+
? {
|
|
476
|
+
inputTokens: Number(meta.promptTokenCount ?? 0),
|
|
477
|
+
outputTokens: Number(meta.candidatesTokenCount ?? 0),
|
|
478
|
+
totalTokens: Number(meta.totalTokenCount ?? 0),
|
|
479
|
+
}
|
|
480
|
+
: undefined;
|
|
481
|
+
return {
|
|
482
|
+
content: textParts.join(""),
|
|
483
|
+
toolCalls,
|
|
484
|
+
finishReason,
|
|
485
|
+
...(usage ? { usage } : {}),
|
|
486
|
+
model: request.model,
|
|
487
|
+
raw: data,
|
|
488
|
+
};
|
|
489
|
+
}),
|
|
490
|
+
}));
|
|
491
|
+
};
|
|
492
|
+
const sha256Hex = (data) => createHash("sha256").update(data).digest("hex");
|
|
493
|
+
const hmacSha256 = (key, data) => createHmac("sha256", key).update(data).digest();
|
|
494
|
+
const signAwsSigV4 = (params) => {
|
|
495
|
+
const now = new Date();
|
|
496
|
+
const amzDate = now.toISOString().replace(/[:-]|\.\d{3}/g, "");
|
|
497
|
+
const dateStamp = amzDate.slice(0, 8);
|
|
498
|
+
const payloadHash = sha256Hex(params.body);
|
|
499
|
+
const headers = {
|
|
500
|
+
"content-type": "application/json",
|
|
501
|
+
host: params.url.host,
|
|
502
|
+
"x-amz-date": amzDate,
|
|
503
|
+
"x-amz-content-sha256": payloadHash,
|
|
504
|
+
...(params.sessionToken
|
|
505
|
+
? { "x-amz-security-token": params.sessionToken }
|
|
506
|
+
: {}),
|
|
507
|
+
...(params.extraHeaders ?? {}),
|
|
508
|
+
};
|
|
509
|
+
const lowerEntries = Object.entries(headers)
|
|
510
|
+
.map(([k, v]) => [k.toLowerCase(), v.trim()])
|
|
511
|
+
.sort(([a], [b]) => a.localeCompare(b));
|
|
512
|
+
const canonicalHeaders = lowerEntries.map(([k, v]) => `${k}:${v}`).join("\n") + "\n";
|
|
513
|
+
const signedHeaders = lowerEntries.map(([k]) => k).join(";");
|
|
514
|
+
const canonicalUri = params.url.pathname
|
|
515
|
+
.split("/")
|
|
516
|
+
.map((seg) => encodeURIComponent(decodeURIComponent(seg)))
|
|
517
|
+
.join("/");
|
|
518
|
+
const canonicalRequest = [
|
|
519
|
+
params.method.toUpperCase(),
|
|
520
|
+
canonicalUri,
|
|
521
|
+
"",
|
|
522
|
+
canonicalHeaders,
|
|
523
|
+
signedHeaders,
|
|
524
|
+
payloadHash,
|
|
525
|
+
].join("\n");
|
|
526
|
+
const credentialScope = `${dateStamp}/${params.region}/${params.service}/aws4_request`;
|
|
527
|
+
const stringToSign = [
|
|
528
|
+
"AWS4-HMAC-SHA256",
|
|
529
|
+
amzDate,
|
|
530
|
+
credentialScope,
|
|
531
|
+
sha256Hex(canonicalRequest),
|
|
532
|
+
].join("\n");
|
|
533
|
+
const kDate = hmacSha256(`AWS4${params.secretAccessKey}`, dateStamp);
|
|
534
|
+
const kRegion = hmacSha256(kDate, params.region);
|
|
535
|
+
const kService = hmacSha256(kRegion, params.service);
|
|
536
|
+
const kSigning = hmacSha256(kService, "aws4_request");
|
|
537
|
+
const signature = createHmac("sha256", kSigning)
|
|
538
|
+
.update(stringToSign)
|
|
539
|
+
.digest("hex");
|
|
540
|
+
return {
|
|
541
|
+
...headers,
|
|
542
|
+
authorization: `AWS4-HMAC-SHA256 Credential=${params.accessKeyId}/${credentialScope}, SignedHeaders=${signedHeaders}, Signature=${signature}`,
|
|
543
|
+
};
|
|
544
|
+
};
|
|
545
|
+
export const LlmBedrockLive = (config) => {
|
|
546
|
+
const endpoint = (config.endpoint ?? `https://bedrock-runtime.${config.region}.amazonaws.com`).replace(/\/+$/, "");
|
|
547
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
548
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
549
|
+
providerName: "bedrock",
|
|
550
|
+
generate: (request) => Effect.gen(function* () {
|
|
551
|
+
const system = [];
|
|
552
|
+
const messages = [];
|
|
553
|
+
for (const m of request.messages) {
|
|
554
|
+
if (m.role === "system") {
|
|
555
|
+
system.push({ text: m.content });
|
|
556
|
+
}
|
|
557
|
+
else if (m.role === "user") {
|
|
558
|
+
messages.push({ role: "user", content: [{ text: m.content }] });
|
|
559
|
+
}
|
|
560
|
+
else if (m.role === "assistant") {
|
|
561
|
+
const content = [];
|
|
562
|
+
if (m.content)
|
|
563
|
+
content.push({ text: m.content });
|
|
564
|
+
for (const tc of m.toolCalls ?? []) {
|
|
565
|
+
content.push({
|
|
566
|
+
toolUse: {
|
|
567
|
+
toolUseId: tc.id,
|
|
568
|
+
name: tc.name,
|
|
569
|
+
input: tc.arguments,
|
|
570
|
+
},
|
|
571
|
+
});
|
|
572
|
+
}
|
|
573
|
+
messages.push({ role: "assistant", content });
|
|
574
|
+
}
|
|
575
|
+
else if (m.role === "tool") {
|
|
576
|
+
messages.push({
|
|
577
|
+
role: "user",
|
|
578
|
+
content: [
|
|
579
|
+
{
|
|
580
|
+
toolResult: {
|
|
581
|
+
toolUseId: m.toolCallId,
|
|
582
|
+
content: [{ text: m.content }],
|
|
583
|
+
...(m.isError ? { status: "error" } : {}),
|
|
584
|
+
},
|
|
585
|
+
},
|
|
586
|
+
],
|
|
587
|
+
});
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
const inferenceConfig = {
|
|
591
|
+
...(request.temperature !== undefined
|
|
592
|
+
? { temperature: request.temperature }
|
|
593
|
+
: {}),
|
|
594
|
+
...(request.maxTokens !== undefined
|
|
595
|
+
? { maxTokens: request.maxTokens }
|
|
596
|
+
: {}),
|
|
597
|
+
...(request.stop && request.stop.length > 0
|
|
598
|
+
? { stopSequences: request.stop }
|
|
599
|
+
: {}),
|
|
600
|
+
};
|
|
601
|
+
const bodyObj = {
|
|
602
|
+
messages,
|
|
603
|
+
...(system.length > 0 ? { system } : {}),
|
|
604
|
+
...(Object.keys(inferenceConfig).length > 0
|
|
605
|
+
? { inferenceConfig }
|
|
606
|
+
: {}),
|
|
607
|
+
...(request.tools && request.tools.length > 0
|
|
608
|
+
? {
|
|
609
|
+
toolConfig: {
|
|
610
|
+
tools: request.tools.map((t) => ({
|
|
611
|
+
toolSpec: {
|
|
612
|
+
name: t.name,
|
|
613
|
+
description: t.description,
|
|
614
|
+
inputSchema: { json: t.parameters },
|
|
615
|
+
},
|
|
616
|
+
})),
|
|
617
|
+
},
|
|
618
|
+
}
|
|
619
|
+
: {}),
|
|
620
|
+
};
|
|
621
|
+
const bodyStr = JSON.stringify(bodyObj);
|
|
622
|
+
const urlStr = `${endpoint}/model/${encodeURIComponent(request.model)}/converse`;
|
|
623
|
+
let headers;
|
|
624
|
+
if (config.bearerToken !== undefined) {
|
|
625
|
+
const token = yield* resolveApiKey(config.bearerToken, "bedrock", request.model);
|
|
626
|
+
headers = {
|
|
627
|
+
"content-type": "application/json",
|
|
628
|
+
authorization: `Bearer ${token}`,
|
|
629
|
+
...(config.headers ?? {}),
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
else {
|
|
633
|
+
const accessKeyId = yield* resolveApiKey(config.accessKeyId, "bedrock", request.model);
|
|
634
|
+
const secretAccessKey = yield* resolveApiKey(config.secretAccessKey, "bedrock", request.model);
|
|
635
|
+
const sessionToken = yield* resolveApiKey(config.sessionToken, "bedrock", request.model, false);
|
|
636
|
+
headers = signAwsSigV4({
|
|
637
|
+
method: "POST",
|
|
638
|
+
url: new URL(urlStr),
|
|
639
|
+
body: bodyStr,
|
|
640
|
+
region: config.region,
|
|
641
|
+
service: "bedrock",
|
|
642
|
+
accessKeyId: accessKeyId,
|
|
643
|
+
secretAccessKey: secretAccessKey,
|
|
644
|
+
...(sessionToken ? { sessionToken } : {}),
|
|
645
|
+
extraHeaders: config.headers,
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
const data = yield* fetchJson(fetchFn, "bedrock", request.model, urlStr, {
|
|
649
|
+
method: "POST",
|
|
650
|
+
headers,
|
|
651
|
+
body: bodyStr,
|
|
652
|
+
});
|
|
653
|
+
const blocks = Array.isArray(data?.output?.message?.content)
|
|
654
|
+
? data.output.message.content
|
|
655
|
+
: [];
|
|
656
|
+
const textParts = [];
|
|
657
|
+
const toolCalls = [];
|
|
658
|
+
for (const block of blocks) {
|
|
659
|
+
if (typeof block.text === "string")
|
|
660
|
+
textParts.push(block.text);
|
|
661
|
+
if (block.toolUse) {
|
|
662
|
+
toolCalls.push({
|
|
663
|
+
id: String(block.toolUse.toolUseId ?? `bedrock_call_${toolCalls.length + 1}`),
|
|
664
|
+
name: String(block.toolUse.name ?? ""),
|
|
665
|
+
arguments: safeParseJsonObject(block.toolUse.input),
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
const stopReason = String(data?.stopReason ?? "");
|
|
670
|
+
const finishReason = stopReason === "tool_use" || toolCalls.length > 0
|
|
671
|
+
? "tool_calls"
|
|
672
|
+
: stopReason === "end_turn" || stopReason === "stop_sequence"
|
|
673
|
+
? "stop"
|
|
674
|
+
: stopReason === "max_tokens"
|
|
675
|
+
? "length"
|
|
676
|
+
: stopReason === "content_filtered"
|
|
677
|
+
? "content_filter"
|
|
678
|
+
: "unknown";
|
|
679
|
+
const usage = data?.usage
|
|
680
|
+
? {
|
|
681
|
+
inputTokens: Number(data.usage.inputTokens ?? 0),
|
|
682
|
+
outputTokens: Number(data.usage.outputTokens ?? 0),
|
|
683
|
+
totalTokens: Number(data.usage.totalTokens ?? 0),
|
|
684
|
+
}
|
|
685
|
+
: undefined;
|
|
686
|
+
return {
|
|
687
|
+
content: textParts.join(""),
|
|
688
|
+
toolCalls,
|
|
689
|
+
finishReason,
|
|
690
|
+
...(usage ? { usage } : {}),
|
|
691
|
+
model: request.model,
|
|
692
|
+
raw: data,
|
|
693
|
+
};
|
|
694
|
+
}),
|
|
695
|
+
}));
|
|
696
|
+
};
|
|
697
|
+
export const LlmOllamaLive = (config) => {
|
|
698
|
+
const baseUrl = (config?.baseUrl ?? "http://127.0.0.1:11434").replace(/\/+$/, "");
|
|
699
|
+
const fetchFn = config?.fetch ?? globalThis.fetch;
|
|
700
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
701
|
+
providerName: "ollama",
|
|
702
|
+
generate: (request) => Effect.gen(function* () {
|
|
703
|
+
const apiKey = yield* resolveApiKey(config?.apiKey, "ollama", request.model, false);
|
|
704
|
+
const messages = request.messages.map((m) => {
|
|
705
|
+
if (m.role === "assistant" && m.toolCalls && m.toolCalls.length > 0) {
|
|
706
|
+
return {
|
|
707
|
+
role: "assistant",
|
|
708
|
+
content: m.content,
|
|
709
|
+
tool_calls: m.toolCalls.map((tc) => ({
|
|
710
|
+
function: {
|
|
711
|
+
name: tc.name,
|
|
712
|
+
arguments: tc.arguments,
|
|
713
|
+
},
|
|
714
|
+
})),
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
if (m.role === "tool") {
|
|
718
|
+
return { role: "tool", content: m.content };
|
|
719
|
+
}
|
|
720
|
+
return { role: m.role, content: m.content };
|
|
721
|
+
});
|
|
722
|
+
const options = {
|
|
723
|
+
...(request.temperature !== undefined
|
|
724
|
+
? { temperature: request.temperature }
|
|
725
|
+
: {}),
|
|
726
|
+
...(request.maxTokens !== undefined
|
|
727
|
+
? { num_predict: request.maxTokens }
|
|
728
|
+
: {}),
|
|
729
|
+
...(request.stop && request.stop.length > 0
|
|
730
|
+
? { stop: request.stop }
|
|
731
|
+
: {}),
|
|
732
|
+
};
|
|
733
|
+
const body = {
|
|
734
|
+
model: request.model,
|
|
735
|
+
stream: false,
|
|
736
|
+
messages,
|
|
737
|
+
...(Object.keys(options).length > 0 ? { options } : {}),
|
|
738
|
+
...(config?.keepAlive ? { keep_alive: config.keepAlive } : {}),
|
|
739
|
+
...(request.responseSchema !== undefined
|
|
740
|
+
? { format: request.responseSchema }
|
|
741
|
+
: {}),
|
|
742
|
+
...(request.tools && request.tools.length > 0
|
|
743
|
+
? {
|
|
744
|
+
tools: request.tools.map((t) => ({
|
|
745
|
+
type: "function",
|
|
746
|
+
function: {
|
|
747
|
+
name: t.name,
|
|
748
|
+
description: t.description,
|
|
749
|
+
parameters: t.parameters,
|
|
750
|
+
},
|
|
751
|
+
})),
|
|
752
|
+
}
|
|
753
|
+
: {}),
|
|
754
|
+
};
|
|
755
|
+
const data = yield* fetchJson(fetchFn, "ollama", request.model, `${baseUrl}/api/chat`, {
|
|
756
|
+
method: "POST",
|
|
757
|
+
headers: {
|
|
758
|
+
"content-type": "application/json",
|
|
759
|
+
...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
|
|
760
|
+
...(config?.headers ?? {}),
|
|
761
|
+
},
|
|
762
|
+
body: JSON.stringify(body),
|
|
763
|
+
});
|
|
764
|
+
const msg = data?.message ?? {};
|
|
765
|
+
const toolCalls = Array.isArray(msg.tool_calls)
|
|
766
|
+
? msg.tool_calls.map((tc, idx) => ({
|
|
767
|
+
id: String(tc.id ?? `ollama_call_${idx + 1}`),
|
|
768
|
+
name: String(tc.function?.name ?? ""),
|
|
769
|
+
arguments: safeParseJsonObject(tc.function?.arguments),
|
|
770
|
+
}))
|
|
771
|
+
: [];
|
|
772
|
+
const inputTokens = Number(data?.prompt_eval_count ?? 0);
|
|
773
|
+
const outputTokens = Number(data?.eval_count ?? 0);
|
|
774
|
+
const usage = inputTokens > 0 || outputTokens > 0
|
|
775
|
+
? {
|
|
776
|
+
inputTokens,
|
|
777
|
+
outputTokens,
|
|
778
|
+
totalTokens: inputTokens + outputTokens,
|
|
779
|
+
}
|
|
780
|
+
: undefined;
|
|
781
|
+
return {
|
|
782
|
+
content: typeof msg.content === "string" ? msg.content : "",
|
|
783
|
+
toolCalls,
|
|
784
|
+
finishReason: toolCalls.length > 0 ? "tool_calls" : "stop",
|
|
785
|
+
...(usage ? { usage } : {}),
|
|
786
|
+
model: typeof data?.model === "string" ? data.model : request.model,
|
|
787
|
+
raw: data,
|
|
788
|
+
};
|
|
789
|
+
}),
|
|
790
|
+
}));
|
|
791
|
+
};
|
|
792
|
+
export const LlmOpenRouterLive = (config) => {
|
|
793
|
+
const baseUrl = (config.baseUrl ?? "https://openrouter.ai/api/v1").replace(/\/+$/, "");
|
|
794
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
795
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
796
|
+
providerName: "openrouter",
|
|
797
|
+
generate: (request) => Effect.gen(function* () {
|
|
798
|
+
const apiKey = yield* resolveApiKey(config.apiKey, "openrouter", request.model);
|
|
799
|
+
const extraBody = {
|
|
800
|
+
...(config.fallbackModels && config.fallbackModels.length > 0
|
|
801
|
+
? { models: [request.model, ...config.fallbackModels] }
|
|
802
|
+
: {}),
|
|
803
|
+
...(config.providerPreferences
|
|
804
|
+
? { provider: config.providerPreferences }
|
|
805
|
+
: {}),
|
|
806
|
+
};
|
|
807
|
+
const headers = {
|
|
808
|
+
"content-type": "application/json",
|
|
809
|
+
authorization: `Bearer ${apiKey}`,
|
|
810
|
+
...(config.siteUrl ? { "http-referer": config.siteUrl } : {}),
|
|
811
|
+
...(config.appName ? { "x-title": config.appName } : {}),
|
|
812
|
+
...(config.headers ?? {}),
|
|
813
|
+
};
|
|
814
|
+
const data = yield* fetchJson(fetchFn, "openrouter", request.model, `${baseUrl}/chat/completions`, {
|
|
815
|
+
method: "POST",
|
|
816
|
+
headers,
|
|
817
|
+
body: JSON.stringify(buildOpenAIChatBody(request, extraBody)),
|
|
818
|
+
});
|
|
819
|
+
return parseOpenAIResponse(data, request.model);
|
|
820
|
+
}),
|
|
821
|
+
}));
|
|
822
|
+
};
|
|
823
|
+
export const LlmLiteLLMLive = (config) => {
|
|
824
|
+
const normalizedBase = config.baseUrl.replace(/\/+$/, "");
|
|
825
|
+
const chatUrl = normalizedBase.endsWith("/v1")
|
|
826
|
+
? `${normalizedBase}/chat/completions`
|
|
827
|
+
: `${normalizedBase}/v1/chat/completions`;
|
|
828
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
829
|
+
return Layer.succeed(LlmProvider, LlmProvider.of({
|
|
830
|
+
providerName: "litellm",
|
|
831
|
+
generate: (request) => Effect.gen(function* () {
|
|
832
|
+
const apiKey = yield* resolveApiKey(config.apiKey, "litellm", request.model, false);
|
|
833
|
+
const mergedMeta = config.metadata || request.metadata
|
|
834
|
+
? { ...(config.metadata ?? {}), ...(request.metadata ?? {}) }
|
|
835
|
+
: undefined;
|
|
836
|
+
const extraBody = {
|
|
837
|
+
...(config.extraBody ?? {}),
|
|
838
|
+
...(mergedMeta ? { metadata: mergedMeta } : {}),
|
|
839
|
+
};
|
|
840
|
+
const headers = {
|
|
841
|
+
"content-type": "application/json",
|
|
842
|
+
...(apiKey ? { authorization: `Bearer ${apiKey}` } : {}),
|
|
843
|
+
...(config.headers ?? {}),
|
|
844
|
+
};
|
|
845
|
+
const data = yield* fetchJson(fetchFn, "litellm", request.model, chatUrl, {
|
|
846
|
+
method: "POST",
|
|
847
|
+
headers,
|
|
848
|
+
body: JSON.stringify(buildOpenAIChatBody(request, extraBody)),
|
|
849
|
+
});
|
|
850
|
+
return parseOpenAIResponse(data, request.model);
|
|
851
|
+
}),
|
|
852
|
+
}));
|
|
853
|
+
};
|
|
854
|
+
//# sourceMappingURL=providers.js.map
|