@fractal-solutions/qflow 1.0.84 → 2.0.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 +119 -0
- package/LICENSE +21 -504
- package/MIGRATION.md +1130 -0
- package/README.md +1432 -823
- package/dist/agent/agent.d.ts +4 -22
- package/dist/agent/agent.js +4 -364
- package/dist/agent/base_agent.d.ts +8 -20
- package/dist/agent/base_agent.js +8 -205
- package/dist/agent/control_nodes.d.ts +61 -0
- package/dist/agent/control_nodes.js +164 -0
- package/dist/agent/engine.d.ts +45 -0
- package/dist/agent/engine.js +415 -0
- package/dist/agent/flow.d.ts +77 -0
- package/dist/agent/flow.js +148 -0
- package/dist/agent/index.d.ts +12 -0
- package/dist/agent/index.js +12 -0
- package/dist/agent/lpavrl_agent.d.ts +1 -2
- package/dist/agent/lpavrl_agent.js +2 -175
- package/dist/agent/ooda_agent.d.ts +1 -2
- package/dist/agent/ooda_agent.js +2 -164
- package/dist/agent/pema_agent.d.ts +1 -2
- package/dist/agent/pema_agent.js +2 -168
- package/dist/agent/raor_agent.d.ts +1 -2
- package/dist/agent/raor_agent.js +2 -161
- package/dist/agent/strategies.d.ts +126 -0
- package/dist/agent/strategies.js +159 -0
- package/dist/agent/tools.d.ts +1 -0
- package/dist/agent/tools.js +42 -24
- package/dist/approval.d.ts +42 -0
- package/dist/approval.js +86 -0
- package/dist/budget.d.ts +103 -0
- package/dist/budget.js +133 -0
- package/dist/bun_nodes.d.ts +119 -0
- package/dist/bun_nodes.js +331 -0
- package/dist/contracts.d.ts +30 -0
- package/dist/contracts.js +103 -0
- package/dist/durable.d.ts +278 -0
- package/dist/durable.js +730 -0
- package/dist/eval.d.ts +165 -0
- package/dist/eval.js +263 -0
- package/dist/graph.d.ts +157 -0
- package/dist/graph.js +330 -0
- package/dist/llm/index.d.ts +359 -0
- package/dist/llm/index.js +924 -0
- package/dist/logger.js +7 -3
- package/dist/mcp/client.d.ts +55 -0
- package/dist/mcp/client.js +145 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +106 -0
- package/dist/mcp/server.js +154 -0
- package/dist/mcp/stdio.d.ts +2 -0
- package/dist/mcp/stdio.js +3 -0
- package/dist/memory.d.ts +101 -0
- package/dist/memory.js +217 -0
- package/dist/nodes/browser_control.js +5 -4
- package/dist/nodes/data_extractor.js +2 -1
- package/dist/nodes/data_validation.d.ts +3 -3
- package/dist/nodes/data_validation.js +19 -5
- package/dist/nodes/database.d.ts +2 -1
- package/dist/nodes/database.js +71 -58
- package/dist/nodes/gis.js +1 -1
- package/dist/nodes/git.d.ts +1 -1
- package/dist/nodes/git.js +65 -51
- package/dist/nodes/github.d.ts +1 -0
- package/dist/nodes/hardware_interaction.d.ts +2 -4
- package/dist/nodes/hardware_interaction.js +4 -3
- package/dist/nodes/http.d.ts +1 -7
- package/dist/nodes/http.js +46 -33
- package/dist/nodes/image_gallery.js +45 -45
- package/dist/nodes/index.d.ts +8 -0
- package/dist/nodes/index.js +8 -0
- package/dist/nodes/interactive_webview.d.ts +1 -2
- package/dist/nodes/interactive_webview.js +217 -216
- package/dist/nodes/multimedia_processing.js +1 -1
- package/dist/nodes/navigator.d.ts +7 -0
- package/dist/nodes/navigator.js +48 -8
- package/dist/nodes/pdf_processor.js +2 -1
- package/dist/nodes/remote_execution.js +2 -2
- package/dist/nodes/s3.d.ts +1 -0
- package/dist/nodes/scheduler.js +2 -2
- package/dist/nodes/search.d.ts +1 -1
- package/dist/nodes/search.js +3 -2
- package/dist/nodes/speech_synthesis.js +2 -1
- package/dist/nodes/spreadsheet.d.ts +1 -7
- package/dist/nodes/spreadsheet.js +2 -1
- package/dist/nodes/streaming_llm.d.ts +51 -0
- package/dist/nodes/streaming_llm.js +120 -0
- package/dist/nodes/webhook.d.ts +1 -5
- package/dist/nodes/webhook.js +106 -93
- package/dist/nodes/websockets.js +5 -3
- package/dist/nodes/webview.js +3 -2
- package/dist/optional.d.ts +32 -0
- package/dist/optional.js +61 -0
- package/dist/qflow.d.ts +25 -14
- package/dist/qflow.js +140 -49
- package/dist/schedule.d.ts +41 -0
- package/dist/schedule.js +149 -0
- package/dist/side_effects.d.ts +50 -0
- package/dist/side_effects.js +94 -0
- package/dist/streaming.d.ts +35 -0
- package/dist/streaming.js +199 -0
- package/dist/testing.d.ts +47 -0
- package/dist/testing.js +130 -0
- package/dist/tool_spec.d.ts +76 -0
- package/dist/tool_spec.js +321 -0
- package/dist/trace.d.ts +28 -0
- package/dist/trace.js +190 -0
- package/dist/util.d.ts +57 -0
- package/dist/util.js +122 -0
- package/package.json +153 -67
- package/qflow.config.js +18 -18
- package/scripts/postinstall.js +50 -0
- package/scripts/verify-package.js +114 -0
|
@@ -0,0 +1,924 @@
|
|
|
1
|
+
import { AsyncNode } from '../qflow.js';
|
|
2
|
+
import { resolveTemplate, stableHash } from '../util.js';
|
|
3
|
+
import { streamChatCompletions, LLM_DELTA_EVENT, LLM_REASONING_EVENT, LLM_DONE_EVENT, } from '../streaming.js';
|
|
4
|
+
export { LLM_DELTA_EVENT, LLM_REASONING_EVENT, LLM_DONE_EVENT };
|
|
5
|
+
export const LLM_RETRY_EVENT = 'llm:retry';
|
|
6
|
+
export const LLM_FALLBACK_EVENT = 'llm:fallback';
|
|
7
|
+
export const LLM_NEGOTIATED_EVENT = 'llm:negotiated';
|
|
8
|
+
export const LLM_CAPABILITY_EVENT = 'llm:capability';
|
|
9
|
+
export const LLM_USAGE_EVENT = 'llm:usage';
|
|
10
|
+
export const LLM_TOOL_CALL_EVENT = 'llm:tool_call';
|
|
11
|
+
export const LLM_CACHE_HIT_EVENT = 'llm:cache_hit';
|
|
12
|
+
export const LLM_EVENTS = {
|
|
13
|
+
delta: LLM_DELTA_EVENT,
|
|
14
|
+
reasoning: LLM_REASONING_EVENT,
|
|
15
|
+
done: LLM_DONE_EVENT,
|
|
16
|
+
retry: LLM_RETRY_EVENT,
|
|
17
|
+
fallback: LLM_FALLBACK_EVENT,
|
|
18
|
+
negotiated: LLM_NEGOTIATED_EVENT,
|
|
19
|
+
capability: LLM_CAPABILITY_EVENT,
|
|
20
|
+
usage: LLM_USAGE_EVENT,
|
|
21
|
+
toolCall: LLM_TOOL_CALL_EVENT,
|
|
22
|
+
cacheHit: LLM_CACHE_HIT_EVENT,
|
|
23
|
+
};
|
|
24
|
+
const DEFAULT_URLS = {
|
|
25
|
+
openai: 'https://api.openai.com/v1/chat/completions',
|
|
26
|
+
deepseek: 'https://api.deepseek.com/chat/completions',
|
|
27
|
+
openrouter: 'https://openrouter.ai/api/v1/chat/completions',
|
|
28
|
+
huggingface: 'https://router.huggingface.co/v1/chat/completions',
|
|
29
|
+
groq: 'https://api.groq.com/openai/v1/chat/completions',
|
|
30
|
+
together: 'https://api.together.xyz/v1/chat/completions',
|
|
31
|
+
anthropic: 'https://api.anthropic.com/v1/messages',
|
|
32
|
+
ollama: 'http://localhost:11434/api/chat',
|
|
33
|
+
gemini: 'https://generativelanguage.googleapis.com/v1beta/models',
|
|
34
|
+
};
|
|
35
|
+
const DEFAULT_CAPABILITIES = {
|
|
36
|
+
streaming: false,
|
|
37
|
+
toolCalls: false,
|
|
38
|
+
structuredOutput: false,
|
|
39
|
+
reasoning: false,
|
|
40
|
+
tokenUsage: false,
|
|
41
|
+
cost: false,
|
|
42
|
+
};
|
|
43
|
+
const OPENAI_CAPABILITIES = {
|
|
44
|
+
streaming: true,
|
|
45
|
+
toolCalls: true,
|
|
46
|
+
structuredOutput: true,
|
|
47
|
+
reasoning: true,
|
|
48
|
+
tokenUsage: true,
|
|
49
|
+
cost: true,
|
|
50
|
+
};
|
|
51
|
+
function toMessages(request = {}) {
|
|
52
|
+
if (Array.isArray(request.messages))
|
|
53
|
+
return request.messages;
|
|
54
|
+
return [{ role: 'user', content: String(request.prompt ?? '') }];
|
|
55
|
+
}
|
|
56
|
+
function serializeTool(tool) {
|
|
57
|
+
if (!tool)
|
|
58
|
+
return null;
|
|
59
|
+
if (typeof tool.getToolDefinition === 'function')
|
|
60
|
+
return tool.getToolDefinition();
|
|
61
|
+
if (typeof tool.definition === 'function')
|
|
62
|
+
return tool.definition();
|
|
63
|
+
if (tool.function?.parameters || tool.function?.name)
|
|
64
|
+
return tool.function;
|
|
65
|
+
return tool;
|
|
66
|
+
}
|
|
67
|
+
function normalizeToolCalls(calls = []) {
|
|
68
|
+
return (Array.isArray(calls) ? calls : [])
|
|
69
|
+
.filter(call => call?.function?.name || call?.name || call?.id)
|
|
70
|
+
.map(call => ({
|
|
71
|
+
index: call.index ?? 0,
|
|
72
|
+
id: call.id ?? null,
|
|
73
|
+
type: call.type ?? 'function',
|
|
74
|
+
function: {
|
|
75
|
+
name: call.function?.name ?? call.name ?? '',
|
|
76
|
+
arguments: typeof call.function?.arguments === 'string'
|
|
77
|
+
? call.function.arguments
|
|
78
|
+
: JSON.stringify(call.function?.arguments ?? call.input ?? call.arguments ?? {}),
|
|
79
|
+
},
|
|
80
|
+
}));
|
|
81
|
+
}
|
|
82
|
+
function finite(value) {
|
|
83
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
|
|
84
|
+
}
|
|
85
|
+
export function normalizeUsage(raw) {
|
|
86
|
+
if (!raw || typeof raw !== 'object')
|
|
87
|
+
return null;
|
|
88
|
+
const prompt = finite(raw.prompt_tokens ?? raw.promptTokenCount ?? raw.input_tokens ?? raw.prompt_eval_count ?? raw.input);
|
|
89
|
+
const completion = finite(raw.completion_tokens ?? raw.candidatesTokenCount ?? raw.output_tokens ?? raw.eval_count ?? raw.output);
|
|
90
|
+
return {
|
|
91
|
+
prompt,
|
|
92
|
+
completion,
|
|
93
|
+
total: finite(raw.total_tokens ?? raw.totalTokenCount ?? raw.total) || prompt + completion,
|
|
94
|
+
raw,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
export function normalizeCompletion(raw, provider = 'unknown') {
|
|
98
|
+
const result = typeof raw === 'string' ? { text: raw } : raw ?? {};
|
|
99
|
+
const choice = result.choices?.[0] ?? {};
|
|
100
|
+
const message = choice.message ?? {};
|
|
101
|
+
const rawText = result.text ?? message.content ?? choice.text ?? '';
|
|
102
|
+
const text = typeof rawText === 'string' ? rawText : JSON.stringify(rawText);
|
|
103
|
+
return {
|
|
104
|
+
text,
|
|
105
|
+
reasoning: String(result.reasoning ?? message.reasoning_content ?? message.reasoning ?? ''),
|
|
106
|
+
toolCalls: normalizeToolCalls(result.toolCalls ?? result.tool_calls ?? message.tool_calls ?? choice.delta?.tool_calls ?? []),
|
|
107
|
+
usage: normalizeUsage(result.usage ?? result.usageMetadata),
|
|
108
|
+
finishReason: result.finishReason ?? choice.finish_reason ?? result.stopReason ?? null,
|
|
109
|
+
cost: result.cost ?? null,
|
|
110
|
+
raw: result.raw ?? result,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export async function resolveCost({ provider, model, usage, pricing = null, result = null }) {
|
|
114
|
+
if (result?.cost != null)
|
|
115
|
+
return result.cost;
|
|
116
|
+
if (typeof pricing === 'function') {
|
|
117
|
+
return await pricing({ provider, model, usage });
|
|
118
|
+
}
|
|
119
|
+
if (!pricing || typeof pricing !== 'object' || !usage)
|
|
120
|
+
return null;
|
|
121
|
+
const inputPerMillion = pricing.inputPerMillion ?? pricing.input ?? pricing.prompt ?? 0;
|
|
122
|
+
const outputPerMillion = pricing.outputPerMillion ?? pricing.output ?? pricing.completion ?? 0;
|
|
123
|
+
return (finite(usage.prompt) / 1_000_000) * inputPerMillion
|
|
124
|
+
+ (finite(usage.completion) / 1_000_000) * outputPerMillion;
|
|
125
|
+
}
|
|
126
|
+
function openAITool(tool) {
|
|
127
|
+
const definition = serializeTool(tool);
|
|
128
|
+
if (!definition?.function && !definition?.name)
|
|
129
|
+
return definition;
|
|
130
|
+
const fn = definition.function ?? definition;
|
|
131
|
+
return {
|
|
132
|
+
type: 'function',
|
|
133
|
+
function: {
|
|
134
|
+
name: fn.name,
|
|
135
|
+
description: fn.description ?? '',
|
|
136
|
+
parameters: fn.parameters ?? definition.parameters ?? { type: 'object', properties: {} },
|
|
137
|
+
},
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
async function readSSE(response, onData) {
|
|
141
|
+
const reader = response.body?.getReader();
|
|
142
|
+
if (!reader)
|
|
143
|
+
throw new Error('Provider returned no streaming body.');
|
|
144
|
+
const decoder = new TextDecoder();
|
|
145
|
+
let buffer = '';
|
|
146
|
+
let done = false;
|
|
147
|
+
while (!done) {
|
|
148
|
+
const { done: streamDone, value } = await reader.read();
|
|
149
|
+
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !streamDone });
|
|
150
|
+
let newline = buffer.indexOf('\n');
|
|
151
|
+
while (newline !== -1) {
|
|
152
|
+
const line = buffer.slice(0, newline).trim();
|
|
153
|
+
buffer = buffer.slice(newline + 1);
|
|
154
|
+
if (!line.startsWith('data:')) {
|
|
155
|
+
if (reader.read && line === '[DONE]')
|
|
156
|
+
done = true;
|
|
157
|
+
newline = buffer.indexOf('\n');
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
const data = line.slice(5).trim();
|
|
161
|
+
if (data === '[DONE]') {
|
|
162
|
+
done = true;
|
|
163
|
+
break;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
onData(JSON.parse(data));
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
// Ignore malformed keep-alive payloads.
|
|
170
|
+
}
|
|
171
|
+
newline = buffer.indexOf('\n');
|
|
172
|
+
}
|
|
173
|
+
if (streamDone) {
|
|
174
|
+
if (buffer.trim().startsWith('data:')) {
|
|
175
|
+
const data = buffer.trim().slice(5).trim();
|
|
176
|
+
if (data !== '[DONE]') {
|
|
177
|
+
try {
|
|
178
|
+
onData(JSON.parse(data));
|
|
179
|
+
}
|
|
180
|
+
catch { }
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
reader.releaseLock?.();
|
|
187
|
+
}
|
|
188
|
+
async function readJsonLines(response, onObject) {
|
|
189
|
+
const reader = response.body?.getReader();
|
|
190
|
+
if (!reader)
|
|
191
|
+
throw new Error('Provider returned no streaming body.');
|
|
192
|
+
const decoder = new TextDecoder();
|
|
193
|
+
let buffer = '';
|
|
194
|
+
while (true) {
|
|
195
|
+
const { done, value } = await reader.read();
|
|
196
|
+
buffer += decoder.decode(value ?? new Uint8Array(), { stream: !done });
|
|
197
|
+
let newline = buffer.indexOf('\n');
|
|
198
|
+
while (newline !== -1) {
|
|
199
|
+
const line = buffer.slice(0, newline).trim();
|
|
200
|
+
buffer = buffer.slice(newline + 1);
|
|
201
|
+
if (line) {
|
|
202
|
+
try {
|
|
203
|
+
onObject(JSON.parse(line));
|
|
204
|
+
}
|
|
205
|
+
catch { }
|
|
206
|
+
}
|
|
207
|
+
newline = buffer.indexOf('\n');
|
|
208
|
+
}
|
|
209
|
+
if (done)
|
|
210
|
+
break;
|
|
211
|
+
}
|
|
212
|
+
if (buffer.trim()) {
|
|
213
|
+
try {
|
|
214
|
+
onObject(JSON.parse(buffer.trim()));
|
|
215
|
+
}
|
|
216
|
+
catch { }
|
|
217
|
+
}
|
|
218
|
+
reader.releaseLock?.();
|
|
219
|
+
}
|
|
220
|
+
async function throwProviderError(response, provider) {
|
|
221
|
+
let detail;
|
|
222
|
+
try {
|
|
223
|
+
detail = await response.json();
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
detail = await response.text();
|
|
227
|
+
}
|
|
228
|
+
const message = detail?.error?.message ?? detail?.message ?? JSON.stringify(detail);
|
|
229
|
+
throw new Error(`${provider} LLM request failed (${response.status}): ${message}`);
|
|
230
|
+
}
|
|
231
|
+
/** Base class for provider-neutral adapters. */
|
|
232
|
+
export class LLMAdapter {
|
|
233
|
+
static id = 'base';
|
|
234
|
+
constructor(options = {}) {
|
|
235
|
+
this.options = options;
|
|
236
|
+
this.provider = options.provider ?? this.constructor.id;
|
|
237
|
+
this.capabilities = { ...DEFAULT_CAPABILITIES, ...(options.capabilities ?? {}) };
|
|
238
|
+
}
|
|
239
|
+
get id() {
|
|
240
|
+
return this.options.id ?? this.provider ?? this.constructor.id;
|
|
241
|
+
}
|
|
242
|
+
requireModel(request) {
|
|
243
|
+
const model = request.model ?? this.options.model;
|
|
244
|
+
if (!model)
|
|
245
|
+
throw new Error(`LLM adapter '${this.id}' requires a model.`);
|
|
246
|
+
return model;
|
|
247
|
+
}
|
|
248
|
+
async complete() {
|
|
249
|
+
throw new Error(`LLM adapter '${this.id}' does not implement complete().`);
|
|
250
|
+
}
|
|
251
|
+
async stream(request, context = {}) {
|
|
252
|
+
const result = await this.complete(request, context);
|
|
253
|
+
if (result.text && typeof context.onDelta === 'function') {
|
|
254
|
+
context.onDelta({ delta: result.text, text: result.text, index: 0, raw: result.raw });
|
|
255
|
+
}
|
|
256
|
+
return result;
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
/** OpenAI-compatible dialect: OpenAI, DeepSeek, OpenRouter, Hugging Face, Groq, Together. */
|
|
260
|
+
export class OpenAICompatibleAdapter extends LLMAdapter {
|
|
261
|
+
static id = 'openai-compatible';
|
|
262
|
+
constructor(options = {}) {
|
|
263
|
+
super({ ...options, capabilities: { ...OPENAI_CAPABILITIES, ...(options.capabilities ?? {}) } });
|
|
264
|
+
this.provider = options.provider ?? 'openai';
|
|
265
|
+
this.baseUrl = options.baseUrl ?? DEFAULT_URLS[this.provider] ?? DEFAULT_URLS.openai;
|
|
266
|
+
}
|
|
267
|
+
get id() {
|
|
268
|
+
return this.options.id ?? this.provider;
|
|
269
|
+
}
|
|
270
|
+
buildPayload(request) {
|
|
271
|
+
const payload = {
|
|
272
|
+
model: this.requireModel(request),
|
|
273
|
+
messages: toMessages(request),
|
|
274
|
+
...(request.options ?? {}),
|
|
275
|
+
};
|
|
276
|
+
const tools = (request.tools ?? []).map(openAITool).filter(Boolean);
|
|
277
|
+
if (tools.length)
|
|
278
|
+
payload.tools = tools;
|
|
279
|
+
if (request.toolChoice)
|
|
280
|
+
payload.tool_choice = request.toolChoice;
|
|
281
|
+
if (request.responseFormat)
|
|
282
|
+
payload.response_format = request.responseFormat;
|
|
283
|
+
return payload;
|
|
284
|
+
}
|
|
285
|
+
buildHeaders(request) {
|
|
286
|
+
const apiKey = request.apiKey ?? this.options.apiKey;
|
|
287
|
+
return {
|
|
288
|
+
'Content-Type': 'application/json',
|
|
289
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
290
|
+
...(this.options.headers ?? {}),
|
|
291
|
+
...(request.headers ?? {}),
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
url(request) {
|
|
295
|
+
return request.baseUrl ?? this.baseUrl;
|
|
296
|
+
}
|
|
297
|
+
async complete(request, context = {}) {
|
|
298
|
+
const response = await fetch(this.url(request), {
|
|
299
|
+
method: 'POST',
|
|
300
|
+
headers: this.buildHeaders(request),
|
|
301
|
+
body: JSON.stringify(this.buildPayload(request)),
|
|
302
|
+
signal: context.signal,
|
|
303
|
+
});
|
|
304
|
+
if (!response.ok)
|
|
305
|
+
await throwProviderError(response, this.id);
|
|
306
|
+
const data = await response.json();
|
|
307
|
+
return normalizeCompletion(data, this.id);
|
|
308
|
+
}
|
|
309
|
+
async stream(request, context = {}) {
|
|
310
|
+
const result = await streamChatCompletions({
|
|
311
|
+
url: this.url(request),
|
|
312
|
+
apiKey: request.apiKey ?? this.options.apiKey,
|
|
313
|
+
model: this.requireModel(request),
|
|
314
|
+
messages: toMessages(request),
|
|
315
|
+
headers: { ...(this.options.headers ?? {}), ...(request.headers ?? {}) },
|
|
316
|
+
body: this.buildPayload(request),
|
|
317
|
+
signal: context.signal,
|
|
318
|
+
onDelta: context.onDelta,
|
|
319
|
+
onReasoning: context.onReasoning,
|
|
320
|
+
});
|
|
321
|
+
return normalizeCompletion(result, this.id);
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
function anthropicTool(tool) {
|
|
325
|
+
const definition = serializeTool(tool);
|
|
326
|
+
const fn = definition?.function ?? definition;
|
|
327
|
+
if (!fn?.name)
|
|
328
|
+
return null;
|
|
329
|
+
return {
|
|
330
|
+
name: fn.name,
|
|
331
|
+
description: fn.description ?? '',
|
|
332
|
+
input_schema: fn.parameters ?? definition.parameters ?? { type: 'object', properties: {} },
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
export class AnthropicAdapter extends LLMAdapter {
|
|
336
|
+
static id = 'anthropic';
|
|
337
|
+
constructor(options = {}) {
|
|
338
|
+
super({
|
|
339
|
+
...options,
|
|
340
|
+
capabilities: { streaming: true, toolCalls: true, structuredOutput: false, reasoning: false, tokenUsage: true, cost: true, ...(options.capabilities ?? {}) },
|
|
341
|
+
});
|
|
342
|
+
this.baseUrl = options.baseUrl ?? DEFAULT_URLS.anthropic;
|
|
343
|
+
}
|
|
344
|
+
buildPayload(request) {
|
|
345
|
+
const messages = toMessages(request);
|
|
346
|
+
const system = messages.filter(message => message.role === 'system').map(message => message.content).join('\n');
|
|
347
|
+
const conversation = messages.filter(message => message.role !== 'system');
|
|
348
|
+
const tools = (request.tools ?? []).map(anthropicTool).filter(Boolean);
|
|
349
|
+
return {
|
|
350
|
+
model: this.requireModel(request),
|
|
351
|
+
messages: conversation,
|
|
352
|
+
max_tokens: request.max_tokens ?? request.maxTokens ?? this.options.maxTokens ?? 4096,
|
|
353
|
+
...(system ? { system } : {}),
|
|
354
|
+
...(tools.length ? { tools } : {}),
|
|
355
|
+
...(request.toolChoice ? { tool_choice: request.toolChoice } : {}),
|
|
356
|
+
...(request.options ?? {}),
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
buildHeaders(request) {
|
|
360
|
+
const apiKey = request.apiKey ?? this.options.apiKey;
|
|
361
|
+
return {
|
|
362
|
+
'Content-Type': 'application/json',
|
|
363
|
+
'anthropic-version': request.anthropicVersion ?? this.options.anthropicVersion ?? '2023-06-01',
|
|
364
|
+
...(apiKey ? { 'x-api-key': apiKey } : {}),
|
|
365
|
+
...(this.options.headers ?? {}),
|
|
366
|
+
...(request.headers ?? {}),
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
url() {
|
|
370
|
+
return this.baseUrl;
|
|
371
|
+
}
|
|
372
|
+
async complete(request, context = {}) {
|
|
373
|
+
const response = await fetch(this.url(request), {
|
|
374
|
+
method: 'POST',
|
|
375
|
+
headers: this.buildHeaders(request),
|
|
376
|
+
body: JSON.stringify(this.buildPayload(request)),
|
|
377
|
+
signal: context.signal,
|
|
378
|
+
});
|
|
379
|
+
if (!response.ok)
|
|
380
|
+
await throwProviderError(response, this.id);
|
|
381
|
+
const data = await response.json();
|
|
382
|
+
const parts = data.content ?? [];
|
|
383
|
+
return normalizeCompletion({
|
|
384
|
+
text: parts.filter(part => part.type === 'text').map(part => part.text).join(''),
|
|
385
|
+
toolCalls: parts.filter(part => part.type === 'tool_use').map(part => ({
|
|
386
|
+
id: part.id,
|
|
387
|
+
function: { name: part.name, arguments: part.input ?? {} },
|
|
388
|
+
})),
|
|
389
|
+
usage: data.usage,
|
|
390
|
+
finishReason: data.stop_reason,
|
|
391
|
+
raw: data,
|
|
392
|
+
}, this.id);
|
|
393
|
+
}
|
|
394
|
+
async stream(request, context = {}) {
|
|
395
|
+
const response = await fetch(this.url(request), {
|
|
396
|
+
method: 'POST',
|
|
397
|
+
headers: { ...this.buildHeaders(request), Accept: 'text/event-stream' },
|
|
398
|
+
body: JSON.stringify({ ...this.buildPayload(request), stream: true }),
|
|
399
|
+
signal: context.signal,
|
|
400
|
+
});
|
|
401
|
+
if (!response.ok)
|
|
402
|
+
await throwProviderError(response, this.id);
|
|
403
|
+
const state = {
|
|
404
|
+
text: '',
|
|
405
|
+
toolCalls: [],
|
|
406
|
+
usage: null,
|
|
407
|
+
finishReason: null,
|
|
408
|
+
toolBuffers: new Map(),
|
|
409
|
+
done: false,
|
|
410
|
+
};
|
|
411
|
+
await readSSE(response, event => {
|
|
412
|
+
if (event.type === 'message_start')
|
|
413
|
+
state.usage = event.message?.usage ?? null;
|
|
414
|
+
if (event.type === 'content_block_start' && event.content_block?.type === 'tool_use') {
|
|
415
|
+
state.toolBuffers.set(event.index, {
|
|
416
|
+
index: event.index,
|
|
417
|
+
id: event.content_block.id,
|
|
418
|
+
name: event.content_block.name,
|
|
419
|
+
input: '',
|
|
420
|
+
});
|
|
421
|
+
}
|
|
422
|
+
if (event.type === 'content_block_delta') {
|
|
423
|
+
if (event.delta?.type === 'text_delta' && event.delta.text) {
|
|
424
|
+
state.text += event.delta.text;
|
|
425
|
+
context.onDelta?.({
|
|
426
|
+
delta: event.delta.text,
|
|
427
|
+
text: state.text,
|
|
428
|
+
index: event.index,
|
|
429
|
+
raw: event,
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
if (event.delta?.type === 'input_json_delta') {
|
|
433
|
+
const buffer = state.toolBuffers.get(event.index);
|
|
434
|
+
if (buffer)
|
|
435
|
+
buffer.input += event.delta.partial_json ?? '';
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
if (event.type === 'message_delta') {
|
|
439
|
+
state.finishReason = event.delta?.stop_reason ?? state.finishReason;
|
|
440
|
+
state.usage = { ...(state.usage ?? {}), ...(event.usage ?? {}) };
|
|
441
|
+
}
|
|
442
|
+
if (event.type === 'message_stop')
|
|
443
|
+
state.done = true;
|
|
444
|
+
});
|
|
445
|
+
const toolCalls = [...state.toolBuffers.values()].map(buffer => {
|
|
446
|
+
let input = {};
|
|
447
|
+
try {
|
|
448
|
+
input = buffer.input ? JSON.parse(buffer.input) : {};
|
|
449
|
+
}
|
|
450
|
+
catch { }
|
|
451
|
+
return { index: buffer.index, id: buffer.id, function: { name: buffer.name, arguments: input } };
|
|
452
|
+
});
|
|
453
|
+
return normalizeCompletion({
|
|
454
|
+
text: state.text,
|
|
455
|
+
toolCalls,
|
|
456
|
+
usage: state.usage,
|
|
457
|
+
finishReason: state.finishReason,
|
|
458
|
+
raw: state,
|
|
459
|
+
}, this.id);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
function ollamaTool(tool) {
|
|
463
|
+
const definition = serializeTool(tool);
|
|
464
|
+
const fn = definition?.function ?? definition;
|
|
465
|
+
if (!fn?.name)
|
|
466
|
+
return null;
|
|
467
|
+
return {
|
|
468
|
+
type: 'function',
|
|
469
|
+
function: {
|
|
470
|
+
name: fn.name,
|
|
471
|
+
description: fn.description ?? '',
|
|
472
|
+
parameters: fn.parameters ?? definition.parameters ?? { type: 'object', properties: {} },
|
|
473
|
+
},
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
export class OllamaAdapter extends LLMAdapter {
|
|
477
|
+
static id = 'ollama';
|
|
478
|
+
constructor(options = {}) {
|
|
479
|
+
super({
|
|
480
|
+
...options,
|
|
481
|
+
capabilities: { streaming: true, toolCalls: true, structuredOutput: true, reasoning: false, tokenUsage: true, cost: false, ...(options.capabilities ?? {}) },
|
|
482
|
+
});
|
|
483
|
+
this.baseUrl = options.baseUrl ?? DEFAULT_URLS.ollama;
|
|
484
|
+
}
|
|
485
|
+
buildPayload(request) {
|
|
486
|
+
const tools = (request.tools ?? []).map(ollamaTool).filter(Boolean);
|
|
487
|
+
const format = request.format ?? request.responseFormat;
|
|
488
|
+
return {
|
|
489
|
+
model: this.requireModel(request),
|
|
490
|
+
messages: toMessages(request),
|
|
491
|
+
stream: false,
|
|
492
|
+
...(tools.length ? { tools } : {}),
|
|
493
|
+
...(format ? { format } : {}),
|
|
494
|
+
...(request.options ?? {}),
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
url(request) {
|
|
498
|
+
return request.baseUrl ?? this.baseUrl;
|
|
499
|
+
}
|
|
500
|
+
buildHeaders(request) {
|
|
501
|
+
const apiKey = request.apiKey ?? this.options.apiKey;
|
|
502
|
+
return {
|
|
503
|
+
'Content-Type': 'application/json',
|
|
504
|
+
...(apiKey ? { Authorization: `Bearer ${apiKey}` } : {}),
|
|
505
|
+
...(this.options.headers ?? {}),
|
|
506
|
+
...(request.headers ?? {}),
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
async complete(request, context = {}) {
|
|
510
|
+
const response = await fetch(this.url(request), {
|
|
511
|
+
method: 'POST',
|
|
512
|
+
headers: this.buildHeaders(request),
|
|
513
|
+
body: JSON.stringify(this.buildPayload(request)),
|
|
514
|
+
signal: context.signal,
|
|
515
|
+
});
|
|
516
|
+
if (!response.ok)
|
|
517
|
+
await throwProviderError(response, this.id);
|
|
518
|
+
const data = await response.json();
|
|
519
|
+
return normalizeCompletion({
|
|
520
|
+
text: data.message?.content ?? data.response ?? '',
|
|
521
|
+
toolCalls: data.message?.tool_calls ?? [],
|
|
522
|
+
usage: { prompt_eval_count: data.prompt_eval_count, eval_count: data.eval_count, total: data.eval_count ? data.prompt_eval_count + data.eval_count : undefined },
|
|
523
|
+
finishReason: data.done ? 'stop' : null,
|
|
524
|
+
raw: data,
|
|
525
|
+
}, this.id);
|
|
526
|
+
}
|
|
527
|
+
async stream(request, context = {}) {
|
|
528
|
+
const response = await fetch(this.url(request), {
|
|
529
|
+
method: 'POST',
|
|
530
|
+
headers: this.buildHeaders(request),
|
|
531
|
+
body: JSON.stringify({ ...this.buildPayload(request), stream: true }),
|
|
532
|
+
signal: context.signal,
|
|
533
|
+
});
|
|
534
|
+
if (!response.ok)
|
|
535
|
+
await throwProviderError(response, this.id);
|
|
536
|
+
const state = { text: '', toolCalls: [], usage: null, finishReason: null };
|
|
537
|
+
await readJsonLines(response, event => {
|
|
538
|
+
const delta = event.message?.content ?? event.response ?? '';
|
|
539
|
+
if (delta) {
|
|
540
|
+
state.text += delta;
|
|
541
|
+
context.onDelta?.({ delta, text: state.text, raw: event });
|
|
542
|
+
}
|
|
543
|
+
const calls = normalizeToolCalls(event.message?.tool_calls ?? []);
|
|
544
|
+
for (const call of calls) {
|
|
545
|
+
const existing = state.toolCalls.find(entry => entry.index === call.index);
|
|
546
|
+
if (existing)
|
|
547
|
+
existing.function.arguments += call.function.arguments;
|
|
548
|
+
else
|
|
549
|
+
state.toolCalls.push(call);
|
|
550
|
+
}
|
|
551
|
+
if (event.prompt_eval_count || event.eval_count) {
|
|
552
|
+
state.usage = {
|
|
553
|
+
prompt_eval_count: event.prompt_eval_count,
|
|
554
|
+
eval_count: event.eval_count,
|
|
555
|
+
total: (event.prompt_eval_count ?? 0) + (event.eval_count ?? 0),
|
|
556
|
+
};
|
|
557
|
+
}
|
|
558
|
+
if (event.done)
|
|
559
|
+
state.finishReason = 'stop';
|
|
560
|
+
});
|
|
561
|
+
return normalizeCompletion({ ...state, raw: state }, this.id);
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
function geminiContents(messages) {
|
|
565
|
+
return messages
|
|
566
|
+
.filter(message => message.role !== 'system')
|
|
567
|
+
.map(message => ({
|
|
568
|
+
role: message.role === 'assistant' ? 'model' : 'user',
|
|
569
|
+
parts: [{ text: typeof message.content === 'string' ? message.content : JSON.stringify(message.content) }],
|
|
570
|
+
}));
|
|
571
|
+
}
|
|
572
|
+
function geminiTool(tool) {
|
|
573
|
+
const definition = serializeTool(tool);
|
|
574
|
+
const fn = definition?.function ?? definition;
|
|
575
|
+
if (!fn?.name)
|
|
576
|
+
return null;
|
|
577
|
+
return {
|
|
578
|
+
functionDeclarations: [{
|
|
579
|
+
name: fn.name,
|
|
580
|
+
description: fn.description ?? '',
|
|
581
|
+
parameters: fn.parameters ?? definition.parameters ?? { type: 'object', properties: {} },
|
|
582
|
+
}],
|
|
583
|
+
};
|
|
584
|
+
}
|
|
585
|
+
export class GeminiAdapter extends LLMAdapter {
|
|
586
|
+
static id = 'gemini';
|
|
587
|
+
constructor(options = {}) {
|
|
588
|
+
super({
|
|
589
|
+
...options,
|
|
590
|
+
capabilities: { streaming: true, toolCalls: true, structuredOutput: true, reasoning: false, tokenUsage: true, cost: false, ...(options.capabilities ?? {}) },
|
|
591
|
+
});
|
|
592
|
+
this.baseUrl = options.baseUrl ?? DEFAULT_URLS.gemini;
|
|
593
|
+
}
|
|
594
|
+
buildUrl(request, { stream = false } = {}) {
|
|
595
|
+
const model = this.requireModel(request);
|
|
596
|
+
const apiKey = request.apiKey ?? this.options.apiKey;
|
|
597
|
+
const action = stream ? 'streamGenerateContent' : 'generateContent';
|
|
598
|
+
const url = `${request.baseUrl ?? this.baseUrl}/${model}:${action}`;
|
|
599
|
+
return apiKey ? `${url}?alt=${stream ? 'sse' : 'json'}&key=${encodeURIComponent(apiKey)}` : `${url}?alt=${stream ? 'sse' : 'json'}`;
|
|
600
|
+
}
|
|
601
|
+
buildPayload(request) {
|
|
602
|
+
const messages = toMessages(request);
|
|
603
|
+
const system = messages.filter(message => message.role === 'system').map(message => message.content).join('\n');
|
|
604
|
+
const tools = (request.tools ?? []).map(geminiTool).filter(Boolean);
|
|
605
|
+
const responseFormat = request.responseFormat ?? request.format;
|
|
606
|
+
const generationConfig = { ...(request.options ?? {}) };
|
|
607
|
+
if (responseFormat?.type === 'json_object' || responseFormat?.mimeType) {
|
|
608
|
+
generationConfig.responseMimeType = 'application/json';
|
|
609
|
+
}
|
|
610
|
+
if (responseFormat?.schema)
|
|
611
|
+
generationConfig.responseSchema = responseFormat.schema;
|
|
612
|
+
return {
|
|
613
|
+
contents: geminiContents(messages),
|
|
614
|
+
...(system ? { systemInstruction: { parts: [{ text: system }] } } : {}),
|
|
615
|
+
...(tools.length ? { tools } : {}),
|
|
616
|
+
...(Object.keys(generationConfig).length ? { generationConfig } : {}),
|
|
617
|
+
};
|
|
618
|
+
}
|
|
619
|
+
normalize(data) {
|
|
620
|
+
const candidate = data.candidates?.[0] ?? {};
|
|
621
|
+
const parts = candidate.content?.parts ?? [];
|
|
622
|
+
return normalizeCompletion({
|
|
623
|
+
text: parts.filter(part => typeof part.text === 'string').map(part => part.text).join(''),
|
|
624
|
+
toolCalls: parts.filter(part => part.functionCall).map(part => ({
|
|
625
|
+
function: { name: part.functionCall.name, arguments: part.functionCall.args ?? {} },
|
|
626
|
+
})),
|
|
627
|
+
usage: data.usageMetadata,
|
|
628
|
+
finishReason: candidate.finishReason ?? null,
|
|
629
|
+
raw: data,
|
|
630
|
+
}, this.id);
|
|
631
|
+
}
|
|
632
|
+
async complete(request, context = {}) {
|
|
633
|
+
const response = await fetch(this.buildUrl(request), {
|
|
634
|
+
method: 'POST',
|
|
635
|
+
headers: { 'Content-Type': 'application/json', ...(this.options.headers ?? {}), ...(request.headers ?? {}) },
|
|
636
|
+
body: JSON.stringify(this.buildPayload(request)),
|
|
637
|
+
signal: context.signal,
|
|
638
|
+
});
|
|
639
|
+
if (!response.ok)
|
|
640
|
+
await throwProviderError(response, this.id);
|
|
641
|
+
return this.normalize(await response.json());
|
|
642
|
+
}
|
|
643
|
+
async stream(request, context = {}) {
|
|
644
|
+
const response = await fetch(this.buildUrl(request, { stream: true }), {
|
|
645
|
+
method: 'POST',
|
|
646
|
+
headers: { 'Content-Type': 'application/json', ...(this.options.headers ?? {}), ...(request.headers ?? {}) },
|
|
647
|
+
body: JSON.stringify(this.buildPayload(request)),
|
|
648
|
+
signal: context.signal,
|
|
649
|
+
});
|
|
650
|
+
if (!response.ok)
|
|
651
|
+
await throwProviderError(response, this.id);
|
|
652
|
+
const state = { text: '', toolCalls: [], usage: null, finishReason: null, raw: [] };
|
|
653
|
+
await readSSE(response, chunk => {
|
|
654
|
+
state.raw.push(chunk);
|
|
655
|
+
const candidate = chunk.candidates?.[0] ?? {};
|
|
656
|
+
const parts = candidate.content?.parts ?? [];
|
|
657
|
+
for (const part of parts) {
|
|
658
|
+
if (typeof part.text === 'string' && part.text) {
|
|
659
|
+
state.text += part.text;
|
|
660
|
+
context.onDelta?.({ delta: part.text, text: state.text, raw: chunk });
|
|
661
|
+
}
|
|
662
|
+
if (part.functionCall) {
|
|
663
|
+
state.toolCalls.push({ function: { name: part.functionCall.name, arguments: part.functionCall.args ?? {} } });
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
if (chunk.usageMetadata)
|
|
667
|
+
state.usage = chunk.usageMetadata;
|
|
668
|
+
if (candidate.finishReason)
|
|
669
|
+
state.finishReason = candidate.finishReason;
|
|
670
|
+
});
|
|
671
|
+
return normalizeCompletion({ ...state, raw: state.raw }, this.id);
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
export const llmAdapters = new Map();
|
|
675
|
+
export function registerLLMAdapter(id, adapter) {
|
|
676
|
+
if (!id || (typeof adapter !== 'function' && typeof adapter?.complete !== 'function')) {
|
|
677
|
+
throw new Error("registerLLMAdapter(id, adapter) requires an id and an adapter with complete().");
|
|
678
|
+
}
|
|
679
|
+
llmAdapters.set(id, adapter);
|
|
680
|
+
return adapter;
|
|
681
|
+
}
|
|
682
|
+
for (const [id, adapter] of [
|
|
683
|
+
['openai', OpenAICompatibleAdapter],
|
|
684
|
+
['deepseek', OpenAICompatibleAdapter],
|
|
685
|
+
['openrouter', OpenAICompatibleAdapter],
|
|
686
|
+
['huggingface', OpenAICompatibleAdapter],
|
|
687
|
+
['groq', OpenAICompatibleAdapter],
|
|
688
|
+
['together', OpenAICompatibleAdapter],
|
|
689
|
+
['openai-compatible', OpenAICompatibleAdapter],
|
|
690
|
+
['anthropic', AnthropicAdapter],
|
|
691
|
+
['ollama', OllamaAdapter],
|
|
692
|
+
['gemini', GeminiAdapter],
|
|
693
|
+
]) {
|
|
694
|
+
registerLLMAdapter(id, adapter);
|
|
695
|
+
}
|
|
696
|
+
export function listLLMAdapters() {
|
|
697
|
+
return [...llmAdapters.keys()].sort();
|
|
698
|
+
}
|
|
699
|
+
export function resolveLLMAdapter(provider, options = {}) {
|
|
700
|
+
if (provider && typeof provider === 'object' && typeof provider.complete === 'function')
|
|
701
|
+
return provider;
|
|
702
|
+
const Adapter = llmAdapters.get(provider);
|
|
703
|
+
if (!Adapter) {
|
|
704
|
+
throw new Error(`Unknown LLM provider '${provider}'. Available: ${listLLMAdapters().join(', ')}`);
|
|
705
|
+
}
|
|
706
|
+
if (typeof Adapter === 'function')
|
|
707
|
+
return new Adapter({ ...options, provider });
|
|
708
|
+
return Adapter;
|
|
709
|
+
}
|
|
710
|
+
export function negotiateCapabilities(adapter, requested = []) {
|
|
711
|
+
const supported = adapter?.capabilities ?? DEFAULT_CAPABILITIES;
|
|
712
|
+
return {
|
|
713
|
+
provider: adapter?.id ?? adapter?.constructor?.id ?? 'unknown',
|
|
714
|
+
requested: [...requested],
|
|
715
|
+
supported: { ...supported },
|
|
716
|
+
missing: requested.filter(capability => !supported[capability]),
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
|
|
720
|
+
/** Accept a cache object, or build one from a durable checkpointer. */
|
|
721
|
+
function resolveLLMCache(request, shared, observer = {}) {
|
|
722
|
+
const cache = request.cache ?? shared.llmCache ?? null;
|
|
723
|
+
if (!cache)
|
|
724
|
+
return null;
|
|
725
|
+
if (typeof cache.get === 'function' && typeof cache.set === 'function')
|
|
726
|
+
return cache;
|
|
727
|
+
if (cache === true) {
|
|
728
|
+
const checkpointer = request.checkpointer ?? observer.checkpointer ?? shared.checkpointer;
|
|
729
|
+
if (checkpointer && typeof checkpointer.cacheGet === 'function' && typeof checkpointer.cacheSet === 'function') {
|
|
730
|
+
return {
|
|
731
|
+
get: key => checkpointer.cacheGet('llm', key),
|
|
732
|
+
set: (key, value, ttlMs) => checkpointer.cacheSet('llm', key, value, ttlMs),
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
}
|
|
736
|
+
throw new Error('LLMNode caching requires a cache object or a checkpointer with cacheGet/cacheSet().');
|
|
737
|
+
}
|
|
738
|
+
/** Stable cache key: explicit template/function, or a hash of the request. */
|
|
739
|
+
export function buildLLMCacheKey(request, shared = {}) {
|
|
740
|
+
if (typeof request.cacheKey === 'function') {
|
|
741
|
+
return String(request.cacheKey({ request, shared }));
|
|
742
|
+
}
|
|
743
|
+
const template = request.cacheKey ?? request.operationId;
|
|
744
|
+
if (typeof template === 'string' && template.includes('{{')) {
|
|
745
|
+
const rendered = resolveTemplate(template, { ...shared, ...request, shared });
|
|
746
|
+
if (rendered.trim())
|
|
747
|
+
return rendered;
|
|
748
|
+
}
|
|
749
|
+
return `llm:${stableHash({
|
|
750
|
+
provider: request.provider,
|
|
751
|
+
model: request.model,
|
|
752
|
+
messages: Array.isArray(request.messages)
|
|
753
|
+
? request.messages
|
|
754
|
+
: [{ role: 'user', content: String(request.prompt ?? '') }],
|
|
755
|
+
tools: request.tools ?? null,
|
|
756
|
+
responseFormat: request.responseFormat ?? null,
|
|
757
|
+
temperature: request.temperature ?? null,
|
|
758
|
+
maxTokens: request.maxTokens ?? null,
|
|
759
|
+
})}`;
|
|
760
|
+
}
|
|
761
|
+
/** One LLM node for every provider, with retries, fallbacks and usage events. */
|
|
762
|
+
export class LLMNode extends AsyncNode {
|
|
763
|
+
static getToolDefinition() {
|
|
764
|
+
return {
|
|
765
|
+
name: 'llm',
|
|
766
|
+
description: 'Runs a provider-neutral LLM completion with retries and fallbacks.',
|
|
767
|
+
parameters: {
|
|
768
|
+
type: 'object',
|
|
769
|
+
properties: {
|
|
770
|
+
prompt: { type: 'string', description: 'Prompt to send to the model.' },
|
|
771
|
+
messages: { type: 'array', description: 'Chat messages to send to the model.' },
|
|
772
|
+
provider: { type: 'string', description: 'Adapter id (openai, anthropic, ollama, gemini, ...).' },
|
|
773
|
+
model: { type: 'string', description: 'Model name.' },
|
|
774
|
+
fallbackProviders: { type: 'array', items: { type: 'string' } },
|
|
775
|
+
},
|
|
776
|
+
required: ['prompt'],
|
|
777
|
+
},
|
|
778
|
+
};
|
|
779
|
+
}
|
|
780
|
+
constructor(options = {}) {
|
|
781
|
+
super(options.maxRetries ?? 1, options.wait ?? 0);
|
|
782
|
+
this.options = { ...options };
|
|
783
|
+
}
|
|
784
|
+
async prepAsync(shared = {}, observer = {}) {
|
|
785
|
+
const request = {
|
|
786
|
+
...this.options,
|
|
787
|
+
...this.params,
|
|
788
|
+
...(shared.llm ?? {}),
|
|
789
|
+
};
|
|
790
|
+
const prompt = request.prompt ?? shared.prompt;
|
|
791
|
+
const messages = request.messages ?? shared.messages;
|
|
792
|
+
if (!prompt && !Array.isArray(messages)) {
|
|
793
|
+
throw new Error('LLMNode requires a prompt or messages.');
|
|
794
|
+
}
|
|
795
|
+
return { request: { ...request, prompt, messages }, shared };
|
|
796
|
+
}
|
|
797
|
+
async execAsync(prepRes, _shared, observer = {}) {
|
|
798
|
+
const request = prepRes.request;
|
|
799
|
+
const providers = [request.provider, ...(request.fallbackProviders ?? [])].filter(Boolean);
|
|
800
|
+
if (!providers.length)
|
|
801
|
+
throw new Error('LLMNode requires a provider or an adapter.');
|
|
802
|
+
const cache = resolveLLMCache(request, prepRes.shared ?? {}, observer);
|
|
803
|
+
const cacheKey = cache ? buildLLMCacheKey(request, prepRes.shared ?? {}) : null;
|
|
804
|
+
if (cache) {
|
|
805
|
+
const hit = await cache.get(cacheKey);
|
|
806
|
+
if (hit) {
|
|
807
|
+
observer.emit?.(LLM_CACHE_HIT_EVENT, {
|
|
808
|
+
key: cacheKey,
|
|
809
|
+
provider: hit.provider ?? providers[0],
|
|
810
|
+
model: hit.model ?? request.model ?? null,
|
|
811
|
+
});
|
|
812
|
+
return hit;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
const requested = new Set(request.capabilities ?? request.requireCapabilities ?? []);
|
|
816
|
+
if (request.stream)
|
|
817
|
+
requested.add('streaming');
|
|
818
|
+
if (request.tools?.length)
|
|
819
|
+
requested.add('toolCalls');
|
|
820
|
+
if (request.responseFormat)
|
|
821
|
+
requested.add('structuredOutput');
|
|
822
|
+
if (request.includeReasoning)
|
|
823
|
+
requested.add('reasoning');
|
|
824
|
+
let lastError = null;
|
|
825
|
+
for (let providerIndex = 0; providerIndex < providers.length; providerIndex += 1) {
|
|
826
|
+
const provider = providers[providerIndex];
|
|
827
|
+
let adapter;
|
|
828
|
+
try {
|
|
829
|
+
adapter = providerIndex === 0 && request.adapter
|
|
830
|
+
? request.adapter
|
|
831
|
+
: resolveLLMAdapter(provider, request);
|
|
832
|
+
}
|
|
833
|
+
catch (error) {
|
|
834
|
+
lastError = error;
|
|
835
|
+
continue;
|
|
836
|
+
}
|
|
837
|
+
const negotiation = negotiateCapabilities(adapter, [...requested]);
|
|
838
|
+
observer.emit?.(LLM_NEGOTIATED_EVENT, negotiation);
|
|
839
|
+
if (negotiation.missing.length) {
|
|
840
|
+
const error = new Error(`Provider '${provider}' does not support required LLM capabilities: ${negotiation.missing.join(', ')}.`);
|
|
841
|
+
error.code = 'QFLOW_LLM_CAPABILITY_MISSING';
|
|
842
|
+
observer.emit?.(LLM_CAPABILITY_EVENT, { ...negotiation, provider });
|
|
843
|
+
lastError = error;
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
const maxAttempts = Math.max(1, request.maxRetries ?? this.maxRetries ?? 1);
|
|
847
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
848
|
+
try {
|
|
849
|
+
const raw = request.stream
|
|
850
|
+
? await adapter.stream(request, {
|
|
851
|
+
signal: observer.signal ?? request.signal,
|
|
852
|
+
onDelta: entry => {
|
|
853
|
+
observer.emit?.(LLM_DELTA_EVENT, { ...entry, provider, model: request.model });
|
|
854
|
+
request.onDelta?.(entry);
|
|
855
|
+
},
|
|
856
|
+
onReasoning: entry => {
|
|
857
|
+
observer.emit?.(LLM_REASONING_EVENT, { ...entry, provider, model: request.model });
|
|
858
|
+
request.onReasoning?.(entry);
|
|
859
|
+
},
|
|
860
|
+
})
|
|
861
|
+
: await adapter.complete(request, { signal: observer.signal ?? request.signal });
|
|
862
|
+
const result = normalizeCompletion(raw, provider);
|
|
863
|
+
result.provider = provider;
|
|
864
|
+
result.model = request.model ?? adapter.options?.model ?? null;
|
|
865
|
+
const usage = result.usage
|
|
866
|
+
? {
|
|
867
|
+
...result.usage,
|
|
868
|
+
cost: await resolveCost({ provider, model: result.model, usage: result.usage, pricing: request.pricing, result }),
|
|
869
|
+
}
|
|
870
|
+
: null;
|
|
871
|
+
result.usage = usage;
|
|
872
|
+
result.cost = usage?.cost ?? null;
|
|
873
|
+
observer.emit?.(LLM_USAGE_EVENT, { provider, model: result.model, usage });
|
|
874
|
+
if (result.toolCalls.length) {
|
|
875
|
+
observer.emit?.(LLM_TOOL_CALL_EVENT, { provider, toolCalls: result.toolCalls });
|
|
876
|
+
}
|
|
877
|
+
observer.emit?.(LLM_DONE_EVENT, {
|
|
878
|
+
provider,
|
|
879
|
+
model: result.model,
|
|
880
|
+
text: result.text,
|
|
881
|
+
reasoning: result.reasoning,
|
|
882
|
+
finishReason: result.finishReason,
|
|
883
|
+
usage,
|
|
884
|
+
});
|
|
885
|
+
if (request.budget && typeof request.budget.record === 'function') {
|
|
886
|
+
request.budget.record(result.usage, result.cost);
|
|
887
|
+
if (typeof request.budget.assertWithin === 'function') {
|
|
888
|
+
request.budget.assertWithin({ steps: (prepRes.shared ?? {}).agentFlowSteps ?? 0 });
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (cache)
|
|
892
|
+
await cache.set(cacheKey, result, request.cacheTtlMs ?? null);
|
|
893
|
+
return result;
|
|
894
|
+
}
|
|
895
|
+
catch (error) {
|
|
896
|
+
lastError = error;
|
|
897
|
+
observer.emit?.(LLM_RETRY_EVENT, {
|
|
898
|
+
provider,
|
|
899
|
+
attempt,
|
|
900
|
+
maxRetries: maxAttempts,
|
|
901
|
+
error: { message: error.message },
|
|
902
|
+
});
|
|
903
|
+
if (attempt < maxAttempts && request.wait)
|
|
904
|
+
await delay(request.wait);
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
if (providerIndex < providers.length - 1) {
|
|
908
|
+
observer.emit?.(LLM_FALLBACK_EVENT, {
|
|
909
|
+
from: provider,
|
|
910
|
+
to: providers[providerIndex + 1],
|
|
911
|
+
error: { message: lastError?.message ?? 'Unknown LLM error' },
|
|
912
|
+
});
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
throw lastError ?? new Error('LLMNode could not complete the request.');
|
|
916
|
+
}
|
|
917
|
+
async postAsync(shared, prepRes, execRes) {
|
|
918
|
+
shared.llmResult = execRes;
|
|
919
|
+
shared.llmUsage = execRes?.usage ?? null;
|
|
920
|
+
shared.llmToolCalls = execRes?.toolCalls ?? [];
|
|
921
|
+
shared.llmCost = execRes?.cost ?? null;
|
|
922
|
+
return Object.keys(this.successors).length ? 'default' : execRes;
|
|
923
|
+
}
|
|
924
|
+
}
|