@thanh01.pmt/domain-kit 0.6.0 → 0.6.1
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/LICENSE +21 -0
- package/README.md +10 -10
- package/dist/assembly/index.d.cts +3 -2
- package/dist/assembly/index.d.ts +3 -2
- package/dist/{chunk-2OGNQUXC.mjs → chunk-4UCXYRM3.mjs} +152 -303
- package/dist/chunk-4UCXYRM3.mjs.map +1 -0
- package/dist/chunk-7A2SG466.mjs +325 -0
- package/dist/chunk-7A2SG466.mjs.map +1 -0
- package/dist/{chunk-DRVOV5ZD.mjs → chunk-DSEJLTUO.mjs} +2 -2
- package/dist/chunk-DSEJLTUO.mjs.map +1 -0
- package/dist/{chunk-ERDTHXQA.mjs → chunk-H4W3YJLK.mjs} +10 -3
- package/dist/chunk-H4W3YJLK.mjs.map +1 -0
- package/dist/chunk-IBVXXVGE.mjs +14 -0
- package/dist/chunk-IBVXXVGE.mjs.map +1 -0
- package/dist/{chunk-5OMSYKQP.mjs → chunk-KHCZYLKM.mjs} +33 -18
- package/dist/chunk-KHCZYLKM.mjs.map +1 -0
- package/dist/{chunk-67GXK3ZE.mjs → chunk-WD3P5V3B.mjs} +3 -2
- package/dist/chunk-WD3P5V3B.mjs.map +1 -0
- package/dist/{conceptEscalator-DPrs4PwC.d.cts → conceptEscalator-BmMJD8C5.d.cts} +1 -1
- package/dist/{conceptEscalator-BCsw0ys_.d.ts → conceptEscalator-DMsehscs.d.ts} +1 -1
- package/dist/concepts/index.d.cts +4 -3
- package/dist/concepts/index.d.ts +4 -3
- package/dist/{cpp-CZUPqJt9.d.cts → cpp-vlDl6pCL.d.cts} +4 -4
- package/dist/{cpp-CZUPqJt9.d.ts → cpp-vlDl6pCL.d.ts} +4 -4
- package/dist/detector/index.cjs +1 -0
- package/dist/detector/index.cjs.map +1 -1
- package/dist/detector/index.d.cts +2 -2
- package/dist/detector/index.d.ts +2 -2
- package/dist/detector/index.mjs +1 -1
- package/dist/{domainProfileDetector-DHb1T0zB.d.ts → domainProfileDetector-6pjgL-6_.d.ts} +1 -1
- package/dist/{domainProfileDetector-bzugdQmS.d.cts → domainProfileDetector-BsADsuRV.d.cts} +1 -1
- package/dist/{domainProfileSchema-CwT3Ffsw.d.cts → domainProfileSchema-779FGk14.d.cts} +38 -1
- package/dist/{domainProfileSchema-CwT3Ffsw.d.ts → domainProfileSchema-779FGk14.d.ts} +38 -1
- package/dist/extractors/index.d.cts +3 -3
- package/dist/extractors/index.d.ts +3 -3
- package/dist/feed/index.d.cts +1 -1
- package/dist/feed/index.d.ts +1 -1
- package/dist/graph/index.cjs +235 -57
- package/dist/graph/index.cjs.map +1 -1
- package/dist/graph/index.d.cts +9 -6
- package/dist/graph/index.d.ts +9 -6
- package/dist/graph/index.mjs +3 -1
- package/dist/{hybridGraphPipeline-CocfYe4d.d.cts → hybridGraphPipeline-B4mamLim.d.cts} +1 -1
- package/dist/{hybridGraphPipeline-9dRKJj7r.d.ts → hybridGraphPipeline-D2_1GUva.d.ts} +1 -1
- package/dist/index.cjs +277 -68
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -8
- package/dist/index.d.ts +9 -8
- package/dist/index.mjs +11 -9
- package/dist/{keywordExtractor-BxlGRMHC.d.cts → keywordExtractor-1YAFntsn.d.cts} +1 -1
- package/dist/{keywordExtractor-DU5XRN8-.d.ts → keywordExtractor-DWw8z_AF.d.ts} +1 -1
- package/dist/parsers/index.cjs.map +1 -1
- package/dist/parsers/index.d.cts +1 -1
- package/dist/parsers/index.d.ts +1 -1
- package/dist/parsers/index.mjs +1 -1
- package/dist/pipeline/index.cjs +261 -68
- package/dist/pipeline/index.cjs.map +1 -1
- package/dist/pipeline/index.d.cts +10 -9
- package/dist/pipeline/index.d.ts +10 -9
- package/dist/pipeline/index.mjs +8 -6
- package/dist/schemas/index.cjs +8 -0
- package/dist/schemas/index.cjs.map +1 -1
- package/dist/schemas/index.d.cts +2 -2
- package/dist/schemas/index.d.ts +2 -2
- package/dist/schemas/index.mjs +1 -1
- package/dist/utils/llmClient.cjs +344 -0
- package/dist/utils/llmClient.cjs.map +1 -0
- package/dist/utils/llmClient.d.cts +118 -0
- package/dist/utils/llmClient.d.ts +118 -0
- package/dist/utils/llmClient.mjs +4 -0
- package/dist/utils/llmClient.mjs.map +1 -0
- package/dist/utils/llmTransportResult.cjs +16 -0
- package/dist/utils/llmTransportResult.cjs.map +1 -0
- package/dist/utils/llmTransportResult.d.cts +36 -0
- package/dist/utils/llmTransportResult.d.ts +36 -0
- package/dist/utils/llmTransportResult.mjs +3 -0
- package/dist/utils/llmTransportResult.mjs.map +1 -0
- package/package.json +9 -10
- package/dist/chunk-2OGNQUXC.mjs.map +0 -1
- package/dist/chunk-5OMSYKQP.mjs.map +0 -1
- package/dist/chunk-67GXK3ZE.mjs.map +0 -1
- package/dist/chunk-DRVOV5ZD.mjs.map +0 -1
- package/dist/chunk-ERDTHXQA.mjs.map +0 -1
- package/dist/llmClient-CX5uUiQ1.d.cts +0 -60
- package/dist/llmClient-CX5uUiQ1.d.ts +0 -60
- package/dist/{curriculumFeedSchema-DYayelAA.d.ts → curriculumFeedSchema-DK-TUAJZ.d.cts} +8 -8
- package/dist/{curriculumFeedSchema-DYayelAA.d.cts → curriculumFeedSchema-DK-TUAJZ.d.ts} +8 -8
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/utils/llmTransportResult.ts
|
|
4
|
+
function transportResultFrom(provider, model, options) {
|
|
5
|
+
return {
|
|
6
|
+
provider,
|
|
7
|
+
model,
|
|
8
|
+
framingStripped: !!options?.framingStripped,
|
|
9
|
+
upstreamError: options?.upstreamError,
|
|
10
|
+
usage: options?.usage
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// src/utils/llmClient.ts
|
|
15
|
+
function summarizeProvenance(callLog) {
|
|
16
|
+
const providers = [];
|
|
17
|
+
const models = [];
|
|
18
|
+
let failed = 0;
|
|
19
|
+
for (const r of callLog) {
|
|
20
|
+
if (!providers.includes(r.provider)) providers.push(r.provider);
|
|
21
|
+
if (!models.includes(r.model)) models.push(r.model);
|
|
22
|
+
if (!r.ok) failed++;
|
|
23
|
+
}
|
|
24
|
+
return { providers, models, calls: callLog.length, failed_calls: failed, degraded: failed > 0 };
|
|
25
|
+
}
|
|
26
|
+
async function responseJsonCompat(response) {
|
|
27
|
+
const text = await response.text();
|
|
28
|
+
try {
|
|
29
|
+
return JSON.parse(text);
|
|
30
|
+
} catch {
|
|
31
|
+
const start = text.indexOf("{");
|
|
32
|
+
if (start < 0) {
|
|
33
|
+
throw new LlmClientError(`LLM API returned a non-JSON body: ${text.slice(0, 200)}`);
|
|
34
|
+
}
|
|
35
|
+
let depth = 0;
|
|
36
|
+
let inString = false;
|
|
37
|
+
let escape = false;
|
|
38
|
+
for (let i = start; i < text.length; i++) {
|
|
39
|
+
const ch = text[i];
|
|
40
|
+
if (escape) {
|
|
41
|
+
escape = false;
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (ch === "\\") {
|
|
45
|
+
escape = true;
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
if (ch === '"') {
|
|
49
|
+
inString = !inString;
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
if (inString) continue;
|
|
53
|
+
if (ch === "{") depth++;
|
|
54
|
+
if (ch === "}") {
|
|
55
|
+
depth--;
|
|
56
|
+
if (depth === 0) {
|
|
57
|
+
return JSON.parse(text.slice(start, i + 1));
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
throw new LlmClientError(`LLM API returned an unterminated JSON body: ${text.slice(0, 200)}`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
var LlmClientError = class extends Error {
|
|
65
|
+
constructor(message, status, cause) {
|
|
66
|
+
super(message);
|
|
67
|
+
this.status = status;
|
|
68
|
+
this.cause = cause;
|
|
69
|
+
this.name = "LlmClientError";
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
function build9routerProvider(model) {
|
|
73
|
+
const apiKey = process.env.NINEROUTER_API_KEY;
|
|
74
|
+
if (!apiKey) return null;
|
|
75
|
+
const baseUrl = (process.env.NINEROUTER_BASE_URL || "https://ai-router.orchable.app/v1").replace(/^["']|["']$/g, "").trim();
|
|
76
|
+
const label = "9router";
|
|
77
|
+
const modelName = (model || process.env.NINEROUTER_MODEL || "laguna-s-2.1").trim();
|
|
78
|
+
return { label, baseUrl, apiKey, model: modelName };
|
|
79
|
+
}
|
|
80
|
+
function resolve9routerChain(configModel) {
|
|
81
|
+
const primary = build9routerProvider(configModel);
|
|
82
|
+
if (!primary) return [];
|
|
83
|
+
const alt = process.env.NINEROUTER_MODEL_ALT && process.env.NINEROUTER_MODEL_ALT.trim();
|
|
84
|
+
if (!alt) return [primary];
|
|
85
|
+
const secondary = build9routerProvider(alt);
|
|
86
|
+
if (!secondary) return [primary];
|
|
87
|
+
return primary.model === secondary.model ? [primary] : [primary, secondary];
|
|
88
|
+
}
|
|
89
|
+
var MIN_REQUEST_INTERVAL_MS = 2500;
|
|
90
|
+
var requestIntervalMs = Number(process.env.LLM_MIN_REQUEST_INTERVAL_MS || MIN_REQUEST_INTERVAL_MS);
|
|
91
|
+
var lastRequestAt = 0;
|
|
92
|
+
async function pacedDelay() {
|
|
93
|
+
const wait = lastRequestAt + requestIntervalMs - Date.now();
|
|
94
|
+
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
|
|
95
|
+
lastRequestAt = Date.now();
|
|
96
|
+
}
|
|
97
|
+
function createLlmClient(config) {
|
|
98
|
+
const chain = resolve9routerChain(config?.model);
|
|
99
|
+
const primary = chain[0];
|
|
100
|
+
if (!primary) {
|
|
101
|
+
throw new LlmClientError(
|
|
102
|
+
"No 9router provider configured. Set NINEROUTER_API_KEY and NINEROUTER_MODEL (or the NINEROUTER_* env defaults expected by the kit)."
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
primary.apiKey;
|
|
106
|
+
primary.baseUrl;
|
|
107
|
+
const model = primary.model;
|
|
108
|
+
if (config?.minRequestIntervalMs !== void 0) {
|
|
109
|
+
requestIntervalMs = Math.max(0, config.minRequestIntervalMs);
|
|
110
|
+
}
|
|
111
|
+
const callLog = [];
|
|
112
|
+
async function chat(messages, options) {
|
|
113
|
+
const temperature = options?.temperature ?? config?.temperature ?? 0.1;
|
|
114
|
+
const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || "65536", 10);
|
|
115
|
+
const attempts = [];
|
|
116
|
+
let lastError = null;
|
|
117
|
+
const TRANSIENT = /* @__PURE__ */ new Set([408, 429, 500, 502, 503, 504]);
|
|
118
|
+
const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 3e5);
|
|
119
|
+
const MAX_CHAIN_ROUNDS = 3;
|
|
120
|
+
for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {
|
|
121
|
+
if (round > 1) {
|
|
122
|
+
attempts.push("round " + (round - 1) + " failed \u2014 backing off 20s before rewalking the chain");
|
|
123
|
+
await new Promise((resolve) => setTimeout(resolve, 2e4));
|
|
124
|
+
}
|
|
125
|
+
for (const provider of chain) {
|
|
126
|
+
const recIdx = callLog.push({ provider: provider.label, model: provider.model, ok: false }) - 1;
|
|
127
|
+
try {
|
|
128
|
+
const headers = {
|
|
129
|
+
"Content-Type": "application/json",
|
|
130
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
131
|
+
};
|
|
132
|
+
const payload = {
|
|
133
|
+
model: provider.model,
|
|
134
|
+
messages,
|
|
135
|
+
temperature,
|
|
136
|
+
max_tokens: maxTokens
|
|
137
|
+
};
|
|
138
|
+
await pacedDelay();
|
|
139
|
+
const doFetch = () => fetch(`${provider.baseUrl}/chat/completions`, {
|
|
140
|
+
method: "POST",
|
|
141
|
+
headers: {
|
|
142
|
+
"Content-Type": "application/json",
|
|
143
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
144
|
+
},
|
|
145
|
+
body: JSON.stringify({
|
|
146
|
+
model: provider.model,
|
|
147
|
+
messages,
|
|
148
|
+
temperature,
|
|
149
|
+
max_tokens: maxTokens
|
|
150
|
+
}),
|
|
151
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
152
|
+
});
|
|
153
|
+
let response;
|
|
154
|
+
try {
|
|
155
|
+
response = await doFetch();
|
|
156
|
+
} catch (netErr) {
|
|
157
|
+
attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) \u2014 retrying once`);
|
|
158
|
+
await new Promise((r) => setTimeout(r, 5e3));
|
|
159
|
+
lastRequestAt = Date.now();
|
|
160
|
+
response = await doFetch();
|
|
161
|
+
}
|
|
162
|
+
if (!response.ok) {
|
|
163
|
+
const body = await response.text().catch(() => "");
|
|
164
|
+
const err = new LlmClientError(
|
|
165
|
+
`[${provider.label}] LLM API error: ${response.status} ${response.statusText} \u2014 ${body.slice(0, 200)}`,
|
|
166
|
+
response.status
|
|
167
|
+
);
|
|
168
|
+
if (response.status === 429) {
|
|
169
|
+
const retryAfterRaw = response.headers.get("retry-after");
|
|
170
|
+
const retryAfterMs = Math.min(
|
|
171
|
+
6e4,
|
|
172
|
+
Math.max(15e3, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1e3)
|
|
173
|
+
);
|
|
174
|
+
attempts.push(`${provider.label}: 429 rate-limited \u2014 backing off ${Math.round(retryAfterMs / 1e3)}s`);
|
|
175
|
+
await new Promise((resolve) => setTimeout(resolve, retryAfterMs));
|
|
176
|
+
lastRequestAt = Date.now();
|
|
177
|
+
const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
|
|
178
|
+
method: "POST",
|
|
179
|
+
headers,
|
|
180
|
+
body: JSON.stringify(payload),
|
|
181
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
|
|
182
|
+
});
|
|
183
|
+
if (!retry.ok) throw err;
|
|
184
|
+
const retryData = await responseJsonCompat(retry);
|
|
185
|
+
const retryContent2 = retryData.choices?.[0]?.message?.content || "";
|
|
186
|
+
if (!retryContent2.trim()) throw err;
|
|
187
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: true };
|
|
188
|
+
const transport2 = transportResultFrom(provider.label, retryData.model || provider.model, {
|
|
189
|
+
usage: retryData.usage,
|
|
190
|
+
framingStripped: true
|
|
191
|
+
});
|
|
192
|
+
return {
|
|
193
|
+
content: retryContent2,
|
|
194
|
+
model: retryData.model || provider.model,
|
|
195
|
+
provider: provider.label,
|
|
196
|
+
attempts: attempts.slice(),
|
|
197
|
+
usage: retryData.usage,
|
|
198
|
+
finishReason: retryData.choices?.[0]?.finish_reason,
|
|
199
|
+
_transport: transport2
|
|
200
|
+
};
|
|
201
|
+
}
|
|
202
|
+
if (TRANSIENT.has(response.status)) {
|
|
203
|
+
await new Promise((r) => setTimeout(r, 3e3));
|
|
204
|
+
const retry = await fetch(`${provider.baseUrl}/chat/completions`, {
|
|
205
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
206
|
+
method: "POST",
|
|
207
|
+
headers: {
|
|
208
|
+
"Content-Type": "application/json",
|
|
209
|
+
"Authorization": `Bearer ${provider.apiKey}`
|
|
210
|
+
},
|
|
211
|
+
body: JSON.stringify({
|
|
212
|
+
model: provider.model,
|
|
213
|
+
messages,
|
|
214
|
+
temperature,
|
|
215
|
+
max_tokens: maxTokens
|
|
216
|
+
})
|
|
217
|
+
});
|
|
218
|
+
if (!retry.ok) throw err;
|
|
219
|
+
const retryData = await responseJsonCompat(retry);
|
|
220
|
+
const retryContent = retryData.choices?.[0]?.message?.content || "";
|
|
221
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: true };
|
|
222
|
+
const transport2 = transportResultFrom(provider.label, retryData.model || provider.model, {
|
|
223
|
+
usage: retryData.usage,
|
|
224
|
+
framingStripped: true
|
|
225
|
+
});
|
|
226
|
+
return {
|
|
227
|
+
content: retryContent,
|
|
228
|
+
model: retryData.model || provider.model,
|
|
229
|
+
provider: provider.label,
|
|
230
|
+
attempts: attempts.slice(),
|
|
231
|
+
usage: retryData.usage,
|
|
232
|
+
finishReason: retryData.choices?.[0]?.finish_reason,
|
|
233
|
+
_transport: transport2
|
|
234
|
+
};
|
|
235
|
+
}
|
|
236
|
+
throw err;
|
|
237
|
+
}
|
|
238
|
+
const data = await responseJsonCompat(response);
|
|
239
|
+
const wrappedError = data.error;
|
|
240
|
+
if (wrappedError) {
|
|
241
|
+
throw new LlmClientError("[" + provider.label + "] upstream error " + (wrappedError.code ?? "") + ": " + (wrappedError.message ?? "unknown"));
|
|
242
|
+
}
|
|
243
|
+
const content = data.choices?.[0]?.message?.content || "";
|
|
244
|
+
if (!content.trim()) {
|
|
245
|
+
throw new LlmClientError("[" + provider.label + "] empty completion returned");
|
|
246
|
+
}
|
|
247
|
+
const transport = transportResultFrom(provider.label, data.model || provider.model, {
|
|
248
|
+
usage: data.usage,
|
|
249
|
+
framingStripped: true
|
|
250
|
+
});
|
|
251
|
+
return {
|
|
252
|
+
content,
|
|
253
|
+
model: data.model || provider.model,
|
|
254
|
+
provider: provider.label,
|
|
255
|
+
attempts: attempts.slice(),
|
|
256
|
+
usage: data.usage,
|
|
257
|
+
finishReason: data.choices?.[0]?.finish_reason,
|
|
258
|
+
_transport: transport
|
|
259
|
+
};
|
|
260
|
+
} catch (err) {
|
|
261
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
262
|
+
callLog[recIdx] = { ...callLog[recIdx], ok: false, error: msg.slice(0, 200) };
|
|
263
|
+
attempts.push(`${provider.label}: ${msg}`);
|
|
264
|
+
lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
if (round < MAX_CHAIN_ROUNDS) continue;
|
|
268
|
+
throw lastError ?? new LlmClientError("All LLM providers failed (empty chain).");
|
|
269
|
+
}
|
|
270
|
+
throw lastError ?? new LlmClientError("All LLM providers failed after " + MAX_CHAIN_ROUNDS + " rounds.");
|
|
271
|
+
}
|
|
272
|
+
return { chat, model, callLog };
|
|
273
|
+
}
|
|
274
|
+
function parseJsonFromLlm(text) {
|
|
275
|
+
let cleaned = text.trim();
|
|
276
|
+
if (cleaned.startsWith("```json")) {
|
|
277
|
+
cleaned = cleaned.slice(7);
|
|
278
|
+
} else if (cleaned.startsWith("```")) {
|
|
279
|
+
cleaned = cleaned.slice(3);
|
|
280
|
+
}
|
|
281
|
+
if (cleaned.endsWith("```")) {
|
|
282
|
+
cleaned = cleaned.slice(0, -3);
|
|
283
|
+
}
|
|
284
|
+
cleaned = cleaned.trim();
|
|
285
|
+
try {
|
|
286
|
+
return JSON.parse(cleaned);
|
|
287
|
+
} catch {
|
|
288
|
+
const start = cleaned.indexOf("{");
|
|
289
|
+
if (start >= 0) {
|
|
290
|
+
let depth = 0;
|
|
291
|
+
let inString = false;
|
|
292
|
+
let escape = false;
|
|
293
|
+
for (let i = start; i < cleaned.length; i++) {
|
|
294
|
+
const ch = cleaned[i];
|
|
295
|
+
if (escape) {
|
|
296
|
+
escape = false;
|
|
297
|
+
continue;
|
|
298
|
+
}
|
|
299
|
+
if (ch === "\\") {
|
|
300
|
+
escape = true;
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
if (ch === '"') {
|
|
304
|
+
inString = !inString;
|
|
305
|
+
continue;
|
|
306
|
+
}
|
|
307
|
+
if (inString) continue;
|
|
308
|
+
if (ch === "{") depth++;
|
|
309
|
+
if (ch === "}") {
|
|
310
|
+
depth--;
|
|
311
|
+
if (depth === 0) {
|
|
312
|
+
try {
|
|
313
|
+
return JSON.parse(cleaned.slice(start, i + 1));
|
|
314
|
+
} catch {
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
async function llmChatJson(client, systemPrompt, userPrompt, options) {
|
|
324
|
+
const result = await client.chat(
|
|
325
|
+
[
|
|
326
|
+
{ role: "system", content: systemPrompt },
|
|
327
|
+
{ role: "user", content: userPrompt }
|
|
328
|
+
],
|
|
329
|
+
options
|
|
330
|
+
);
|
|
331
|
+
return parseJsonFromLlm(result.content);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
exports.LlmClientError = LlmClientError;
|
|
335
|
+
exports.build9routerProvider = build9routerProvider;
|
|
336
|
+
exports.createLlmClient = createLlmClient;
|
|
337
|
+
exports.llmChatJson = llmChatJson;
|
|
338
|
+
exports.parseJsonFromLlm = parseJsonFromLlm;
|
|
339
|
+
exports.resolve9routerChain = resolve9routerChain;
|
|
340
|
+
exports.responseJsonCompat = responseJsonCompat;
|
|
341
|
+
exports.summarizeProvenance = summarizeProvenance;
|
|
342
|
+
exports.transportResultFrom = transportResultFrom;
|
|
343
|
+
//# sourceMappingURL=llmClient.cjs.map
|
|
344
|
+
//# sourceMappingURL=llmClient.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/utils/llmTransportResult.ts","../../src/utils/llmClient.ts"],"names":["transport"],"mappings":";;;AA8BO,SAAS,mBAAA,CACd,QAAA,EACA,KAAA,EACA,OAAA,EAKoB;AACpB,EAAA,OAAO;AAAA,IACL,QAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA,EAAiB,CAAC,CAAC,OAAA,EAAS,eAAA;AAAA,IAC5B,eAAe,OAAA,EAAS,aAAA;AAAA,IACxB,OAAO,OAAA,EAAS;AAAA,GAClB;AACF;;;ACFO,SAAS,oBAAoB,OAAA,EAAyC;AAC3E,EAAA,MAAM,YAAsB,EAAC;AAC7B,EAAA,MAAM,SAAmB,EAAC;AAC1B,EAAA,IAAI,MAAA,GAAS,CAAA;AACb,EAAA,KA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AAAA,QAAU;AAClD,QAAA,IAAI,QAAA,EAAU;AACd,QAAA,IAAI,OAAO,GAAA,EAAK,KAAA,EAAA;AAChB,QAAA,IAAI,OAAO,GAAA,EAAK;AACd,UAAA,KAAA,EAAA;AACA,UAAA,IAAI,UAAU,CAAA,EAAG;AACf,YAAA,IAAI;AACF,cAAA,OAAO,KAAK,KAAA,CAAM,OAAA,CAAQ,MAAM,KAAA,EAAO,CAAA,GAAI,CAAC,CAAC,CAAA;AAAA,YAC/C,CAAA,CAAA,MAAQ;AAAA,YAER;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF;AACA,IAAA,MAAM,IAAI,eAAe,CAAA,wCAAA,EAA2C,OAAA,CAAQ,MAAM,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,CAAA;AAAA,EAC7F;AACF;AAKA,eAAsB,WAAA,CACpB,MAAA,EACA,YAAA,EACA,UAAA,EACA,OAAA,EACkC;AAClC,EAAA,MAAM,MAAA,GAAS,MAAM,MAAA,CAAO,IAAA;AAAA,IAC1B;AAAA,MACE,EAAE,IAAA,EAAM,QAAA,EAAU,OAAA,EAAS,YAAA,EAAa;AAAA,MACxC,EAAE,IAAA,EAAM,MAAA,EAAQ,OAAA,EAAS,UAAA;AAAW,KACtC;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,gBAAA,CAAiB,OAAO,OAAO,CAAA;AACxC","file":"llmClient.cjs","sourcesContent":["/**\n * Single source of truth for ONE LLM response through the kit.\n *\n * Every `LlmClient.chat` return path attaches one of these so downstream\n * code inspects the ACTUAL resolved provider/model and framing flags instead\n * of trusting the static client.model card. This is the contract behind the\n * \"no silent cross-gateway rerouting\" policy: each response carries its own\n * provenance and framing metadata.\n */\nexport interface LlmTransportResult {\n /** Provider label that actually served this response (e.g. '9router'). */\n provider: string;\n /** Exact model string sent to and returned by that provider. */\n model: string;\n /** True when the response body was stripped of 9router SSE framing. */\n framingStripped: boolean;\n /** When present, the upstream returned an error envelope inside HTTP 200. */\n upstreamError?: string;\n /** When present, usage record attached to the response. */\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n finishReason?: string;\n };\n}\n\n/**\n * Build the transport result that accompanies a successful chat completion.\n */\nexport function transportResultFrom(\n provider: string,\n model: string,\n options?: {\n framingStripped?: boolean;\n upstreamError?: string;\n usage?: LlmTransportResult['usage'];\n },\n): LlmTransportResult {\n return {\n provider,\n model,\n framingStripped: !!options?.framingStripped,\n upstreamError: options?.upstreamError,\n usage: options?.usage,\n };\n}\n","/**\n * LLM client wrapper — provides a unified interface for LLM calls\n * used by the graph generation pipeline.\n *\n * Supports OpenAI-compatible APIs via environment variables:\n * LLM_API_KEY, LLM_BASE_URL, LLM_MODEL (or LLM_TIER_FAST / LLM_TIER_STRONG)\n */\n\nimport { transportResultFrom, type LlmTransportResult } from './llmTransportResult';\nexport { transportResultFrom, type LlmTransportResult } from './llmTransportResult';\n\nexport interface LlmClientConfig {\n apiKey?: string;\n baseUrl?: string;\n model?: string;\n temperature?: number;\n maxTokens?: number;\n /**\n * Minimum ms between requests, enforced process-wide so free tiers are not\n * rate-limited by a burst. Defaults to LLM_MIN_REQUEST_INTERVAL_MS (2500).\n * Set 0 to disable — correct when several pipelines run concurrently in one\n * process and per-pipeline pacing is enough, or when the caller owns the\n * rate limit itself (serverless).\n */\n minRequestIntervalMs?: number;\n}\n\n/** One provider attempt. Kept per client instance so provenance never leaks across requests. */\nexport interface LlmCallRecord {\n provider: string;\n model: string;\n ok: boolean;\n error?: string;\n}\n\nexport interface LlmProvenance {\n providers: string[];\n models: string[];\n calls: number;\n failed_calls: number;\n /** true when at least one provider fell through to the next in the chain. */\n degraded: boolean;\n}\n\nexport function summarizeProvenance(callLog: LlmCallRecord[]): LlmProvenance {\n const providers: string[] = [];\n const models: string[] = [];\n let failed = 0;\n for (const r of callLog) {\n if (!providers.includes(r.provider)) providers.push(r.provider);\n if (!models.includes(r.model)) models.push(r.model);\n if (!r.ok) failed++;\n }\n return { providers, models, calls: callLog.length, failed_calls: failed, degraded: failed > 0 };\n}\n\n/**\n * Some OpenAI-compatible gateways (observed: 9router / ai-router.orchable.app)\n * paste SSE stream framing onto NON-stream responses: a leading blank line,\n * then the chat.completion JSON object, wrapped with a trailing `data: [DONE]`.\n * response.json() throws \"Unexpected non-whitespace character after JSON\", so\n * read the text and cut the body back to the first balanced JSON object.\n */\nexport async function responseJsonCompat(response: Response): Promise<Record<string, any>> {\n const text = await response.text();\n try {\n return JSON.parse(text);\n } catch {\n const start = text.indexOf('{');\n if (start < 0) {\n throw new LlmClientError(`LLM API returned a non-JSON body: ${text.slice(0, 200)}`);\n }\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = start; i < text.length; i++) {\n const ch = text[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\') { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n return JSON.parse(text.slice(start, i + 1));\n }\n }\n }\n throw new LlmClientError(`LLM API returned an unterminated JSON body: ${text.slice(0, 200)}`);\n }\n}\n\n/** One callable provider endpoint in the fallback chain. */\nexport interface ProviderSpec {\n label: string;\n baseUrl: string;\n apiKey: string;\n model: string;\n}\n\nexport interface LlmClient {\n chat(messages: LlmChatMessage[], options?: { temperature?: number; maxTokens?: number }): Promise<LlmChatResult>;\n model: string;\n /** Every provider attempt made through this client — the provenance of the graph it produced. */\n callLog: LlmCallRecord[];\n}\n\nexport interface LlmChatMessage {\n role: 'system' | 'user' | 'assistant';\n content: string;\n}\n\nexport interface LlmChatResult {\n content: string;\n model: string;\n /** Provider label that ultimately served the request. */\n provider?: string;\n /** What happened per provider when fallback occurred (empty when first try succeeded). */\n attempts?: string[];\n /** 'stop' when complete; 'length' means the response was TRUNCATED by max_tokens. */\n finishReason?: string;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n finishReason?: string;\n };\n _transport?: LlmTransportResult;\n}\n\nexport class LlmClientError extends Error {\n constructor(\n message: string,\n public readonly status?: number,\n public readonly cause?: Error,\n ) {\n super(message);\n this.name = 'LlmClientError';\n }\n}\n\n/**\n * Create an LLM client from environment variables.\n */\nexport function build9routerProvider(model?: string): ProviderSpec | null {\n const apiKey = process.env.NINEROUTER_API_KEY;\n if (!apiKey) return null;\n const baseUrl = (process.env.NINEROUTER_BASE_URL || 'https://ai-router.orchable.app/v1').replace(/^[\"']|[\"']$/g, '').trim();\n const label = '9router';\n const modelName = (model || process.env.NINEROUTER_MODEL || 'laguna-s-2.1').trim();\n return { label, baseUrl, apiKey, model: modelName };\n}\n\n/**\n * Synthesize a 9router-only chain from the configured primary model.\n * POLICY (user directive 2026-10-07): 9router free-tier ONLY — laguna-s-2.1\n * and nemotron-ultra ride the same pool from different upstream providers.\n * The returned chain is PRIMARY then SAME-POOL SECONDARY; the caller owns any\n * fallback semantics and MUST NOT silently branch to another gateway.\n */\nexport function resolve9routerChain(configModel?: string): ProviderSpec[] {\n const primary = build9routerProvider(configModel);\n if (!primary) return [];\n const alt = process.env.NINEROUTER_MODEL_ALT && process.env.NINEROUTER_MODEL_ALT.trim();\n if (!alt) return [primary];\n const secondary = build9routerProvider(alt);\n if (!secondary) return [primary];\n return primary.model === secondary.model ? [primary] : [primary, secondary];\n}\n\n// Free-tier rate limits (NVIDIA NIM, OpenRouter) trip when a pipeline fires\n// many requests in a burst. Global pacing keeps us under the limit; a single\n// isolated call still goes through immediately.\nconst MIN_REQUEST_INTERVAL_MS = 2_500;\nlet requestIntervalMs = Number(process.env.LLM_MIN_REQUEST_INTERVAL_MS || MIN_REQUEST_INTERVAL_MS);\nlet lastRequestAt = 0;\n\nasync function pacedDelay(): Promise<void> {\n const wait = lastRequestAt + requestIntervalMs - Date.now();\n if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));\n lastRequestAt = Date.now();\n}\n\nexport function createLlmClient(config?: LlmClientConfig): LlmClient {\n const chain = resolve9routerChain(config?.model);\n const primary = chain[0];\n if (!primary) {\n throw new LlmClientError(\n 'No 9router provider configured. Set NINEROUTER_API_KEY and NINEROUTER_MODEL (or the NINEROUTER_* env defaults expected by the kit).',\n );\n }\n const apiKey = primary.apiKey;\n const baseUrl = primary.baseUrl;\n const model = primary.model;\n if (config?.minRequestIntervalMs !== undefined) {\n requestIntervalMs = Math.max(0, config.minRequestIntervalMs);\n }\n // Per-client, so concurrent pipelines never inherit each other's provenance.\n const callLog: LlmCallRecord[] = [];\n\n async function chat(\n messages: LlmChatMessage[],\n options?: { temperature?: number; maxTokens?: number },\n ): Promise<LlmChatResult> {\n const temperature = options?.temperature ?? config?.temperature ?? 0.1;\n const maxTokens = options?.maxTokens ?? config?.maxTokens ?? parseInt(process.env.LLM_MAX_TOKENS || '65536', 10);\n\n const attempts: string[] = [];\n let lastError: LlmClientError | null = null;\n const TRANSIENT = new Set([408, 429, 500, 502, 503, 504]);\n // Hard per-request cap so a hanging provider degrades to a transient error\n // and the chain falls through instead of blocking the pipeline forever.\n // Reasoning presets (e.g. deepseek-v4-flash) can legitimately think for\n // minutes on large structured outputs — 5 minutes default, env-overridable.\n const REQUEST_TIMEOUT_MS = Number(process.env.LLM_REQUEST_TIMEOUT_MS || 300_000);\n const MAX_CHAIN_ROUNDS = 3;\n for (let round = 1; round <= MAX_CHAIN_ROUNDS; round++) {\n if (round > 1) {\n // Whole chain failed transiently (rate limits / upstream 5xx) — back\n // off and rewalk the chain from the primary instead of dying.\n attempts.push('round ' + (round - 1) + ' failed — backing off 20s before rewalking the chain');\n await new Promise((resolve) => setTimeout(resolve, 20_000));\n }\n for (const provider of chain) {\n // Provenance: opened as failed, flipped to ok on the paths that return.\n const recIdx = callLog.push({ provider: provider.label, model: provider.model, ok: false }) - 1;\n try {\n const headers = {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n };\n const payload = {\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n };\n await pacedDelay();\n const doFetch = (): Promise<Response> => fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n // Transient network failures (DNS blip, TLS reset, \"fetch failed\") get\n // one same-provider retry before falling through the chain.\n let response: Response;\n try {\n response = await doFetch();\n } catch (netErr) {\n attempts.push(`${provider.label}: network error (${netErr instanceof Error ? netErr.message : String(netErr)}) — retrying once`);\n await new Promise((r) => setTimeout(r, 5_000));\n lastRequestAt = Date.now();\n response = await doFetch();\n }\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const err = new LlmClientError(\n `[${provider.label}] LLM API error: ${response.status} ${response.statusText} — ${body.slice(0, 200)}`,\n response.status,\n );\n if (response.status === 429) {\n // Rate-limited: honor Retry-After (bounded) and retry once on the\n // same provider before falling through to the next one.\n const retryAfterRaw = response.headers.get('retry-after');\n const retryAfterMs = Math.min(\n 60_000,\n Math.max(15_000, (Number.isFinite(Number(retryAfterRaw)) ? Number(retryAfterRaw) : 20) * 1_000),\n );\n attempts.push(`${provider.label}: 429 rate-limited — backing off ${Math.round(retryAfterMs / 1000)}s`);\n await new Promise((resolve) => setTimeout(resolve, retryAfterMs));\n lastRequestAt = Date.now();\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n method: 'POST',\n headers,\n body: JSON.stringify(payload),\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n });\n if (!retry.ok) throw err;\n const retryData = await responseJsonCompat(retry) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent2 = retryData.choices?.[0]?.message?.content || '';\n if (!retryContent2.trim()) throw err;\n callLog[recIdx] = { ...callLog[recIdx], ok: true };\n const transport = transportResultFrom(provider.label, retryData.model || provider.model, {\n usage: retryData.usage,\n framingStripped: true,\n });\n return {\n content: retryContent2,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n }\n if (TRANSIENT.has(response.status)) {\n await new Promise((r) => setTimeout(r, 3000));\n const retry = await fetch(`${provider.baseUrl}/chat/completions`, {\n signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${provider.apiKey}`,\n },\n body: JSON.stringify({\n model: provider.model,\n messages,\n temperature,\n max_tokens: maxTokens,\n }),\n });\n if (!retry.ok) throw err; // still transient-failing — fall through to next provider\n const retryData = await responseJsonCompat(retry) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const retryContent = retryData.choices?.[0]?.message?.content || '';\n callLog[recIdx] = { ...callLog[recIdx], ok: true };\n const transport = transportResultFrom(provider.label, retryData.model || provider.model, {\n usage: retryData.usage,\n framingStripped: true,\n });\n return {\n content: retryContent,\n model: retryData.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: retryData.usage,\n finishReason: retryData.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n }\n throw err;\n }\n const data = await responseJsonCompat(response) as {\n choices?: Array<{ message?: { content?: string }; finish_reason?: string }>;\n model?: string;\n usage?: { prompt_tokens: number; completion_tokens: number; total_tokens: number };\n };\n const wrappedError = (data as { error?: { message?: string; code?: number } }).error;\n if (wrappedError) {\n // OpenRouter proxies some upstream failures as HTTP 200 with an\n // {\"error\": {...}} body — treat as transient and fall through.\n throw new LlmClientError('[' + provider.label + '] upstream error ' + (wrappedError.code ?? '') + ': ' + (wrappedError.message ?? 'unknown'));\n }\n const content = data.choices?.[0]?.message?.content || '';\n if (!content.trim()) {\n // Empty completion (provider outage / content filter) is transient —\n // fall through to the next provider instead of returning unusable ''.\n throw new LlmClientError('[' + provider.label + '] empty completion returned');\n }\n const transport = transportResultFrom(provider.label, data.model || provider.model, {\n usage: data.usage,\n framingStripped: true,\n });\n return {\n content,\n model: data.model || provider.model,\n provider: provider.label,\n attempts: attempts.slice(),\n usage: data.usage,\n finishReason: data.choices?.[0]?.finish_reason,\n _transport: transport,\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n callLog[recIdx] = { ...callLog[recIdx], ok: false, error: msg.slice(0, 200) };\n attempts.push(`${provider.label}: ${msg}`);\n lastError = err instanceof LlmClientError ? err : new LlmClientError(`[${provider.label}] ${msg}`);\n // try next provider\n }\n }\n if (round < MAX_CHAIN_ROUNDS) continue; // rewalk the chain\n throw lastError ?? new LlmClientError('All LLM providers failed (empty chain).');\n }\n throw lastError ?? new LlmClientError('All LLM providers failed after ' + MAX_CHAIN_ROUNDS + ' rounds.');\n }\n\n return { chat, model, callLog };\n}\n\n/**\n * Parse JSON from LLM response, handling markdown code fences.\n */\nexport function parseJsonFromLlm(text: string): Record<string, unknown> {\n // Strip markdown code fences if present\n let cleaned = text.trim();\n if (cleaned.startsWith('```json')) {\n cleaned = cleaned.slice(7);\n } else if (cleaned.startsWith('```')) {\n cleaned = cleaned.slice(3);\n }\n if (cleaned.endsWith('```')) {\n cleaned = cleaned.slice(0, -3);\n }\n cleaned = cleaned.trim();\n\n try {\n return JSON.parse(cleaned) as Record<string, unknown>;\n } catch {\n // Try to find first complete JSON object using brace-depth tracking\n const start = cleaned.indexOf('{');\n if (start >= 0) {\n let depth = 0;\n let inString = false;\n let escape = false;\n for (let i = start; i < cleaned.length; i++) {\n const ch = cleaned[i];\n if (escape) { escape = false; continue; }\n if (ch === '\\\\') { escape = true; continue; }\n if (ch === '\"') { inString = !inString; continue; }\n if (inString) continue;\n if (ch === '{') depth++;\n if (ch === '}') {\n depth--;\n if (depth === 0) {\n try {\n return JSON.parse(cleaned.slice(start, i + 1)) as Record<string, unknown>;\n } catch {\n // keep looking\n }\n }\n }\n }\n }\n throw new LlmClientError(`Failed to parse JSON from LLM response: ${cleaned.slice(0, 200)}`);\n }\n}\n\n/**\n * Call LLM and parse JSON response.\n */\nexport async function llmChatJson(\n client: ReturnType<typeof createLlmClient>,\n systemPrompt: string,\n userPrompt: string,\n options?: { temperature?: number; maxTokens?: number },\n): Promise<Record<string, unknown>> {\n const result = await client.chat(\n [\n { role: 'system', content: systemPrompt },\n { role: 'user', content: userPrompt },\n ],\n options,\n );\n\n return parseJsonFromLlm(result.content);\n}\n"]}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { LlmTransportResult } from './llmTransportResult.cjs';
|
|
2
|
+
export { transportResultFrom } from './llmTransportResult.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* LLM client wrapper — provides a unified interface for LLM calls
|
|
6
|
+
* used by the graph generation pipeline.
|
|
7
|
+
*
|
|
8
|
+
* Supports OpenAI-compatible APIs via environment variables:
|
|
9
|
+
* LLM_API_KEY, LLM_BASE_URL, LLM_MODEL (or LLM_TIER_FAST / LLM_TIER_STRONG)
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
interface LlmClientConfig {
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
temperature?: number;
|
|
17
|
+
maxTokens?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Minimum ms between requests, enforced process-wide so free tiers are not
|
|
20
|
+
* rate-limited by a burst. Defaults to LLM_MIN_REQUEST_INTERVAL_MS (2500).
|
|
21
|
+
* Set 0 to disable — correct when several pipelines run concurrently in one
|
|
22
|
+
* process and per-pipeline pacing is enough, or when the caller owns the
|
|
23
|
+
* rate limit itself (serverless).
|
|
24
|
+
*/
|
|
25
|
+
minRequestIntervalMs?: number;
|
|
26
|
+
}
|
|
27
|
+
/** One provider attempt. Kept per client instance so provenance never leaks across requests. */
|
|
28
|
+
interface LlmCallRecord {
|
|
29
|
+
provider: string;
|
|
30
|
+
model: string;
|
|
31
|
+
ok: boolean;
|
|
32
|
+
error?: string;
|
|
33
|
+
}
|
|
34
|
+
interface LlmProvenance {
|
|
35
|
+
providers: string[];
|
|
36
|
+
models: string[];
|
|
37
|
+
calls: number;
|
|
38
|
+
failed_calls: number;
|
|
39
|
+
/** true when at least one provider fell through to the next in the chain. */
|
|
40
|
+
degraded: boolean;
|
|
41
|
+
}
|
|
42
|
+
declare function summarizeProvenance(callLog: LlmCallRecord[]): LlmProvenance;
|
|
43
|
+
/**
|
|
44
|
+
* Some OpenAI-compatible gateways (observed: 9router / ai-router.orchable.app)
|
|
45
|
+
* paste SSE stream framing onto NON-stream responses: a leading blank line,
|
|
46
|
+
* then the chat.completion JSON object, wrapped with a trailing `data: [DONE]`.
|
|
47
|
+
* response.json() throws "Unexpected non-whitespace character after JSON", so
|
|
48
|
+
* read the text and cut the body back to the first balanced JSON object.
|
|
49
|
+
*/
|
|
50
|
+
declare function responseJsonCompat(response: Response): Promise<Record<string, any>>;
|
|
51
|
+
/** One callable provider endpoint in the fallback chain. */
|
|
52
|
+
interface ProviderSpec {
|
|
53
|
+
label: string;
|
|
54
|
+
baseUrl: string;
|
|
55
|
+
apiKey: string;
|
|
56
|
+
model: string;
|
|
57
|
+
}
|
|
58
|
+
interface LlmClient {
|
|
59
|
+
chat(messages: LlmChatMessage[], options?: {
|
|
60
|
+
temperature?: number;
|
|
61
|
+
maxTokens?: number;
|
|
62
|
+
}): Promise<LlmChatResult>;
|
|
63
|
+
model: string;
|
|
64
|
+
/** Every provider attempt made through this client — the provenance of the graph it produced. */
|
|
65
|
+
callLog: LlmCallRecord[];
|
|
66
|
+
}
|
|
67
|
+
interface LlmChatMessage {
|
|
68
|
+
role: 'system' | 'user' | 'assistant';
|
|
69
|
+
content: string;
|
|
70
|
+
}
|
|
71
|
+
interface LlmChatResult {
|
|
72
|
+
content: string;
|
|
73
|
+
model: string;
|
|
74
|
+
/** Provider label that ultimately served the request. */
|
|
75
|
+
provider?: string;
|
|
76
|
+
/** What happened per provider when fallback occurred (empty when first try succeeded). */
|
|
77
|
+
attempts?: string[];
|
|
78
|
+
/** 'stop' when complete; 'length' means the response was TRUNCATED by max_tokens. */
|
|
79
|
+
finishReason?: string;
|
|
80
|
+
usage?: {
|
|
81
|
+
prompt_tokens: number;
|
|
82
|
+
completion_tokens: number;
|
|
83
|
+
total_tokens: number;
|
|
84
|
+
finishReason?: string;
|
|
85
|
+
};
|
|
86
|
+
_transport?: LlmTransportResult;
|
|
87
|
+
}
|
|
88
|
+
declare class LlmClientError extends Error {
|
|
89
|
+
readonly status?: number | undefined;
|
|
90
|
+
readonly cause?: Error | undefined;
|
|
91
|
+
constructor(message: string, status?: number | undefined, cause?: Error | undefined);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Create an LLM client from environment variables.
|
|
95
|
+
*/
|
|
96
|
+
declare function build9routerProvider(model?: string): ProviderSpec | null;
|
|
97
|
+
/**
|
|
98
|
+
* Synthesize a 9router-only chain from the configured primary model.
|
|
99
|
+
* POLICY (user directive 2026-10-07): 9router free-tier ONLY — laguna-s-2.1
|
|
100
|
+
* and nemotron-ultra ride the same pool from different upstream providers.
|
|
101
|
+
* The returned chain is PRIMARY then SAME-POOL SECONDARY; the caller owns any
|
|
102
|
+
* fallback semantics and MUST NOT silently branch to another gateway.
|
|
103
|
+
*/
|
|
104
|
+
declare function resolve9routerChain(configModel?: string): ProviderSpec[];
|
|
105
|
+
declare function createLlmClient(config?: LlmClientConfig): LlmClient;
|
|
106
|
+
/**
|
|
107
|
+
* Parse JSON from LLM response, handling markdown code fences.
|
|
108
|
+
*/
|
|
109
|
+
declare function parseJsonFromLlm(text: string): Record<string, unknown>;
|
|
110
|
+
/**
|
|
111
|
+
* Call LLM and parse JSON response.
|
|
112
|
+
*/
|
|
113
|
+
declare function llmChatJson(client: ReturnType<typeof createLlmClient>, systemPrompt: string, userPrompt: string, options?: {
|
|
114
|
+
temperature?: number;
|
|
115
|
+
maxTokens?: number;
|
|
116
|
+
}): Promise<Record<string, unknown>>;
|
|
117
|
+
|
|
118
|
+
export { type LlmCallRecord, type LlmChatMessage, type LlmChatResult, type LlmClient, type LlmClientConfig, LlmClientError, type LlmProvenance, LlmTransportResult, type ProviderSpec, build9routerProvider, createLlmClient, llmChatJson, parseJsonFromLlm, resolve9routerChain, responseJsonCompat, summarizeProvenance };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import { LlmTransportResult } from './llmTransportResult.js';
|
|
2
|
+
export { transportResultFrom } from './llmTransportResult.js';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* LLM client wrapper — provides a unified interface for LLM calls
|
|
6
|
+
* used by the graph generation pipeline.
|
|
7
|
+
*
|
|
8
|
+
* Supports OpenAI-compatible APIs via environment variables:
|
|
9
|
+
* LLM_API_KEY, LLM_BASE_URL, LLM_MODEL (or LLM_TIER_FAST / LLM_TIER_STRONG)
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
interface LlmClientConfig {
|
|
13
|
+
apiKey?: string;
|
|
14
|
+
baseUrl?: string;
|
|
15
|
+
model?: string;
|
|
16
|
+
temperature?: number;
|
|
17
|
+
maxTokens?: number;
|
|
18
|
+
/**
|
|
19
|
+
* Minimum ms between requests, enforced process-wide so free tiers are not
|
|
20
|
+
* rate-limited by a burst. Defaults to LLM_MIN_REQUEST_INTERVAL_MS (2500).
|
|
21
|
+
* Set 0 to disable — correct when several pipelines run concurrently in one
|
|
22
|
+
* process and per-pipeline pacing is enough, or when the caller owns the
|
|
23
|
+
* rate limit itself (serverless).
|
|
24
|
+
*/
|
|
25
|
+
minRequestIntervalMs?: number;
|
|
26
|
+
}
|
|
27
|
+
/** One provider attempt. Kept per client instance so provenance never leaks across requests. */
|
|
28
|
+
interface LlmCallRecord {
|
|
29
|
+
provider: string;
|
|
30
|
+
model: string;
|
|
31
|
+
ok: boolean;
|
|
32
|
+
error?: string;
|
|
33
|
+
}
|
|
34
|
+
interface LlmProvenance {
|
|
35
|
+
providers: string[];
|
|
36
|
+
models: string[];
|
|
37
|
+
calls: number;
|
|
38
|
+
failed_calls: number;
|
|
39
|
+
/** true when at least one provider fell through to the next in the chain. */
|
|
40
|
+
degraded: boolean;
|
|
41
|
+
}
|
|
42
|
+
declare function summarizeProvenance(callLog: LlmCallRecord[]): LlmProvenance;
|
|
43
|
+
/**
|
|
44
|
+
* Some OpenAI-compatible gateways (observed: 9router / ai-router.orchable.app)
|
|
45
|
+
* paste SSE stream framing onto NON-stream responses: a leading blank line,
|
|
46
|
+
* then the chat.completion JSON object, wrapped with a trailing `data: [DONE]`.
|
|
47
|
+
* response.json() throws "Unexpected non-whitespace character after JSON", so
|
|
48
|
+
* read the text and cut the body back to the first balanced JSON object.
|
|
49
|
+
*/
|
|
50
|
+
declare function responseJsonCompat(response: Response): Promise<Record<string, any>>;
|
|
51
|
+
/** One callable provider endpoint in the fallback chain. */
|
|
52
|
+
interface ProviderSpec {
|
|
53
|
+
label: string;
|
|
54
|
+
baseUrl: string;
|
|
55
|
+
apiKey: string;
|
|
56
|
+
model: string;
|
|
57
|
+
}
|
|
58
|
+
interface LlmClient {
|
|
59
|
+
chat(messages: LlmChatMessage[], options?: {
|
|
60
|
+
temperature?: number;
|
|
61
|
+
maxTokens?: number;
|
|
62
|
+
}): Promise<LlmChatResult>;
|
|
63
|
+
model: string;
|
|
64
|
+
/** Every provider attempt made through this client — the provenance of the graph it produced. */
|
|
65
|
+
callLog: LlmCallRecord[];
|
|
66
|
+
}
|
|
67
|
+
interface LlmChatMessage {
|
|
68
|
+
role: 'system' | 'user' | 'assistant';
|
|
69
|
+
content: string;
|
|
70
|
+
}
|
|
71
|
+
interface LlmChatResult {
|
|
72
|
+
content: string;
|
|
73
|
+
model: string;
|
|
74
|
+
/** Provider label that ultimately served the request. */
|
|
75
|
+
provider?: string;
|
|
76
|
+
/** What happened per provider when fallback occurred (empty when first try succeeded). */
|
|
77
|
+
attempts?: string[];
|
|
78
|
+
/** 'stop' when complete; 'length' means the response was TRUNCATED by max_tokens. */
|
|
79
|
+
finishReason?: string;
|
|
80
|
+
usage?: {
|
|
81
|
+
prompt_tokens: number;
|
|
82
|
+
completion_tokens: number;
|
|
83
|
+
total_tokens: number;
|
|
84
|
+
finishReason?: string;
|
|
85
|
+
};
|
|
86
|
+
_transport?: LlmTransportResult;
|
|
87
|
+
}
|
|
88
|
+
declare class LlmClientError extends Error {
|
|
89
|
+
readonly status?: number | undefined;
|
|
90
|
+
readonly cause?: Error | undefined;
|
|
91
|
+
constructor(message: string, status?: number | undefined, cause?: Error | undefined);
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Create an LLM client from environment variables.
|
|
95
|
+
*/
|
|
96
|
+
declare function build9routerProvider(model?: string): ProviderSpec | null;
|
|
97
|
+
/**
|
|
98
|
+
* Synthesize a 9router-only chain from the configured primary model.
|
|
99
|
+
* POLICY (user directive 2026-10-07): 9router free-tier ONLY — laguna-s-2.1
|
|
100
|
+
* and nemotron-ultra ride the same pool from different upstream providers.
|
|
101
|
+
* The returned chain is PRIMARY then SAME-POOL SECONDARY; the caller owns any
|
|
102
|
+
* fallback semantics and MUST NOT silently branch to another gateway.
|
|
103
|
+
*/
|
|
104
|
+
declare function resolve9routerChain(configModel?: string): ProviderSpec[];
|
|
105
|
+
declare function createLlmClient(config?: LlmClientConfig): LlmClient;
|
|
106
|
+
/**
|
|
107
|
+
* Parse JSON from LLM response, handling markdown code fences.
|
|
108
|
+
*/
|
|
109
|
+
declare function parseJsonFromLlm(text: string): Record<string, unknown>;
|
|
110
|
+
/**
|
|
111
|
+
* Call LLM and parse JSON response.
|
|
112
|
+
*/
|
|
113
|
+
declare function llmChatJson(client: ReturnType<typeof createLlmClient>, systemPrompt: string, userPrompt: string, options?: {
|
|
114
|
+
temperature?: number;
|
|
115
|
+
maxTokens?: number;
|
|
116
|
+
}): Promise<Record<string, unknown>>;
|
|
117
|
+
|
|
118
|
+
export { type LlmCallRecord, type LlmChatMessage, type LlmChatResult, type LlmClient, type LlmClientConfig, LlmClientError, type LlmProvenance, LlmTransportResult, type ProviderSpec, build9routerProvider, createLlmClient, llmChatJson, parseJsonFromLlm, resolve9routerChain, responseJsonCompat, summarizeProvenance };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { LlmClientError, build9routerProvider, createLlmClient, llmChatJson, parseJsonFromLlm, resolve9routerChain, responseJsonCompat, summarizeProvenance } from '../chunk-7A2SG466.mjs';
|
|
2
|
+
export { transportResultFrom } from '../chunk-IBVXXVGE.mjs';
|
|
3
|
+
//# sourceMappingURL=llmClient.mjs.map
|
|
4
|
+
//# sourceMappingURL=llmClient.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"names":[],"mappings":"","file":"llmClient.mjs"}
|