tracia 0.1.1 → 0.2.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.mts +474 -3
- package/dist/index.d.ts +474 -3
- package/dist/index.js +1182 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1170 -3
- package/dist/index.mjs.map +1 -1
- package/package.json +28 -3
package/dist/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,11 +17,21 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
21
31
|
var index_exports = {};
|
|
22
32
|
__export(index_exports, {
|
|
33
|
+
Eval: () => Eval,
|
|
34
|
+
LLMProvider: () => LLMProvider,
|
|
23
35
|
Tracia: () => Tracia,
|
|
24
36
|
TraciaError: () => TraciaError,
|
|
25
37
|
TraciaErrorCode: () => TraciaErrorCode
|
|
@@ -48,13 +60,23 @@ var TraciaErrorCode = /* @__PURE__ */ ((TraciaErrorCode2) => {
|
|
|
48
60
|
TraciaErrorCode2["INVALID_REQUEST"] = "INVALID_REQUEST";
|
|
49
61
|
TraciaErrorCode2["NETWORK_ERROR"] = "NETWORK_ERROR";
|
|
50
62
|
TraciaErrorCode2["TIMEOUT"] = "TIMEOUT";
|
|
63
|
+
TraciaErrorCode2["ABORTED"] = "ABORTED";
|
|
51
64
|
TraciaErrorCode2["UNKNOWN"] = "UNKNOWN";
|
|
65
|
+
TraciaErrorCode2["MISSING_PROVIDER_SDK"] = "MISSING_PROVIDER_SDK";
|
|
66
|
+
TraciaErrorCode2["MISSING_PROVIDER_API_KEY"] = "MISSING_PROVIDER_API_KEY";
|
|
67
|
+
TraciaErrorCode2["UNSUPPORTED_MODEL"] = "UNSUPPORTED_MODEL";
|
|
52
68
|
return TraciaErrorCode2;
|
|
53
69
|
})(TraciaErrorCode || {});
|
|
70
|
+
var LLMProvider = /* @__PURE__ */ ((LLMProvider2) => {
|
|
71
|
+
LLMProvider2["OPENAI"] = "openai";
|
|
72
|
+
LLMProvider2["ANTHROPIC"] = "anthropic";
|
|
73
|
+
LLMProvider2["GOOGLE"] = "google";
|
|
74
|
+
return LLMProvider2;
|
|
75
|
+
})(LLMProvider || {});
|
|
54
76
|
|
|
55
77
|
// src/client.ts
|
|
56
|
-
var SDK_VERSION = "0.
|
|
57
|
-
var DEFAULT_TIMEOUT_MS =
|
|
78
|
+
var SDK_VERSION = "0.2.2";
|
|
79
|
+
var DEFAULT_TIMEOUT_MS = 12e4;
|
|
58
80
|
function mapApiErrorCodeToTraciaErrorCode(apiCode) {
|
|
59
81
|
const codeMap = {
|
|
60
82
|
UNAUTHORIZED: "UNAUTHORIZED" /* UNAUTHORIZED */,
|
|
@@ -202,10 +224,511 @@ var Prompts = class {
|
|
|
202
224
|
}
|
|
203
225
|
};
|
|
204
226
|
|
|
227
|
+
// src/models.ts
|
|
228
|
+
var MODEL_TO_PROVIDER = {
|
|
229
|
+
// OpenAI
|
|
230
|
+
"chatgpt-4o-latest": "openai" /* OPENAI */,
|
|
231
|
+
"gpt-3.5-turbo": "openai" /* OPENAI */,
|
|
232
|
+
"gpt-3.5-turbo-0125": "openai" /* OPENAI */,
|
|
233
|
+
"gpt-3.5-turbo-1106": "openai" /* OPENAI */,
|
|
234
|
+
"gpt-3.5-turbo-16k": "openai" /* OPENAI */,
|
|
235
|
+
"gpt-4": "openai" /* OPENAI */,
|
|
236
|
+
"gpt-4-0125-preview": "openai" /* OPENAI */,
|
|
237
|
+
"gpt-4-1106-preview": "openai" /* OPENAI */,
|
|
238
|
+
"gpt-4-turbo": "openai" /* OPENAI */,
|
|
239
|
+
"gpt-4-turbo-2024-04-09": "openai" /* OPENAI */,
|
|
240
|
+
"gpt-4-turbo-preview": "openai" /* OPENAI */,
|
|
241
|
+
"gpt-4.1": "openai" /* OPENAI */,
|
|
242
|
+
"gpt-4.1-2025-04-14": "openai" /* OPENAI */,
|
|
243
|
+
"gpt-4.1-mini": "openai" /* OPENAI */,
|
|
244
|
+
"gpt-4.1-mini-2025-04-14": "openai" /* OPENAI */,
|
|
245
|
+
"gpt-4.1-nano": "openai" /* OPENAI */,
|
|
246
|
+
"gpt-4.1-nano-2025-04-14": "openai" /* OPENAI */,
|
|
247
|
+
"gpt-4o": "openai" /* OPENAI */,
|
|
248
|
+
"gpt-4o-2024-05-13": "openai" /* OPENAI */,
|
|
249
|
+
"gpt-4o-2024-08-06": "openai" /* OPENAI */,
|
|
250
|
+
"gpt-4o-2024-11-20": "openai" /* OPENAI */,
|
|
251
|
+
"gpt-4o-mini": "openai" /* OPENAI */,
|
|
252
|
+
"gpt-4o-mini-2024-07-18": "openai" /* OPENAI */,
|
|
253
|
+
"gpt-4o-mini-search-preview": "openai" /* OPENAI */,
|
|
254
|
+
"gpt-4o-mini-search-preview-2025-03-11": "openai" /* OPENAI */,
|
|
255
|
+
"gpt-4o-search-preview": "openai" /* OPENAI */,
|
|
256
|
+
"gpt-4o-search-preview-2025-03-11": "openai" /* OPENAI */,
|
|
257
|
+
"gpt-5": "openai" /* OPENAI */,
|
|
258
|
+
"gpt-5.1": "openai" /* OPENAI */,
|
|
259
|
+
"gpt-5.1-2025-11-13": "openai" /* OPENAI */,
|
|
260
|
+
"gpt-5.1-chat-latest": "openai" /* OPENAI */,
|
|
261
|
+
"gpt-5.2": "openai" /* OPENAI */,
|
|
262
|
+
"gpt-5.2-2025-12-11": "openai" /* OPENAI */,
|
|
263
|
+
"gpt-5.2-chat-latest": "openai" /* OPENAI */,
|
|
264
|
+
"gpt-5.2-pro": "openai" /* OPENAI */,
|
|
265
|
+
"gpt-5.2-pro-2025-12-11": "openai" /* OPENAI */,
|
|
266
|
+
"gpt-5-pro": "openai" /* OPENAI */,
|
|
267
|
+
"gpt-5-pro-2025-10-06": "openai" /* OPENAI */,
|
|
268
|
+
"gpt-5-2025-08-07": "openai" /* OPENAI */,
|
|
269
|
+
"gpt-5-chat-latest": "openai" /* OPENAI */,
|
|
270
|
+
"gpt-5-codex": "openai" /* OPENAI */,
|
|
271
|
+
"gpt-5.1-codex": "openai" /* OPENAI */,
|
|
272
|
+
"gpt-5.1-codex-max": "openai" /* OPENAI */,
|
|
273
|
+
"gpt-5.1-codex-mini": "openai" /* OPENAI */,
|
|
274
|
+
"gpt-5-mini": "openai" /* OPENAI */,
|
|
275
|
+
"gpt-5-mini-2025-08-07": "openai" /* OPENAI */,
|
|
276
|
+
"gpt-5-nano": "openai" /* OPENAI */,
|
|
277
|
+
"gpt-5-nano-2025-08-07": "openai" /* OPENAI */,
|
|
278
|
+
"o1": "openai" /* OPENAI */,
|
|
279
|
+
"o1-2024-12-17": "openai" /* OPENAI */,
|
|
280
|
+
"o1-pro": "openai" /* OPENAI */,
|
|
281
|
+
"o1-pro-2025-03-19": "openai" /* OPENAI */,
|
|
282
|
+
"o3": "openai" /* OPENAI */,
|
|
283
|
+
"o3-2025-04-16": "openai" /* OPENAI */,
|
|
284
|
+
"o3-mini": "openai" /* OPENAI */,
|
|
285
|
+
"o3-mini-2025-01-31": "openai" /* OPENAI */,
|
|
286
|
+
"o4-mini": "openai" /* OPENAI */,
|
|
287
|
+
"o4-mini-2025-04-16": "openai" /* OPENAI */,
|
|
288
|
+
// Anthropic
|
|
289
|
+
"claude-haiku-4-5-20251001": "anthropic" /* ANTHROPIC */,
|
|
290
|
+
"claude-haiku-4-5": "anthropic" /* ANTHROPIC */,
|
|
291
|
+
"claude-3-7-sonnet-20250219": "anthropic" /* ANTHROPIC */,
|
|
292
|
+
"claude-3-haiku-20240307": "anthropic" /* ANTHROPIC */,
|
|
293
|
+
"claude-3-opus-20240229": "anthropic" /* ANTHROPIC */,
|
|
294
|
+
"claude-4-opus-20250514": "anthropic" /* ANTHROPIC */,
|
|
295
|
+
"claude-4-sonnet-20250514": "anthropic" /* ANTHROPIC */,
|
|
296
|
+
"claude-sonnet-4-5": "anthropic" /* ANTHROPIC */,
|
|
297
|
+
"claude-sonnet-4-5-20250929": "anthropic" /* ANTHROPIC */,
|
|
298
|
+
"claude-opus-4-1": "anthropic" /* ANTHROPIC */,
|
|
299
|
+
"claude-opus-4-1-20250805": "anthropic" /* ANTHROPIC */,
|
|
300
|
+
"claude-opus-4-20250514": "anthropic" /* ANTHROPIC */,
|
|
301
|
+
"claude-opus-4-5-20251101": "anthropic" /* ANTHROPIC */,
|
|
302
|
+
"claude-opus-4-5": "anthropic" /* ANTHROPIC */,
|
|
303
|
+
"claude-sonnet-4-20250514": "anthropic" /* ANTHROPIC */,
|
|
304
|
+
// Google
|
|
305
|
+
"gemini-2.0-flash": "google" /* GOOGLE */,
|
|
306
|
+
"gemini-2.0-flash-001": "google" /* GOOGLE */,
|
|
307
|
+
"gemini-2.0-flash-exp": "google" /* GOOGLE */,
|
|
308
|
+
"gemini-2.0-flash-lite": "google" /* GOOGLE */,
|
|
309
|
+
"gemini-2.0-flash-lite-001": "google" /* GOOGLE */,
|
|
310
|
+
"gemini-2.5-flash": "google" /* GOOGLE */,
|
|
311
|
+
"gemini-2.5-flash-lite": "google" /* GOOGLE */,
|
|
312
|
+
"gemini-2.5-flash-lite-preview-09-2025": "google" /* GOOGLE */,
|
|
313
|
+
"gemini-2.5-flash-preview-09-2025": "google" /* GOOGLE */,
|
|
314
|
+
"gemini-2.5-pro": "google" /* GOOGLE */,
|
|
315
|
+
"gemini-3-pro-preview": "google" /* GOOGLE */,
|
|
316
|
+
"gemini-3-flash-preview": "google" /* GOOGLE */
|
|
317
|
+
};
|
|
318
|
+
function getProviderForModel(modelId) {
|
|
319
|
+
return MODEL_TO_PROVIDER[modelId];
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// src/providers/ai-sdk.ts
|
|
323
|
+
var aiSdk = null;
|
|
324
|
+
var openaiProvider = null;
|
|
325
|
+
var anthropicProvider = null;
|
|
326
|
+
var googleProvider = null;
|
|
327
|
+
async function loadAISdk() {
|
|
328
|
+
if (aiSdk) return aiSdk;
|
|
329
|
+
try {
|
|
330
|
+
aiSdk = await import("ai");
|
|
331
|
+
return aiSdk;
|
|
332
|
+
} catch {
|
|
333
|
+
throw new TraciaError(
|
|
334
|
+
"MISSING_PROVIDER_SDK" /* MISSING_PROVIDER_SDK */,
|
|
335
|
+
"Vercel AI SDK not installed. Run: npm install ai"
|
|
336
|
+
);
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
async function loadOpenAIProvider() {
|
|
340
|
+
if (openaiProvider) return openaiProvider;
|
|
341
|
+
try {
|
|
342
|
+
openaiProvider = await import("@ai-sdk/openai");
|
|
343
|
+
return openaiProvider;
|
|
344
|
+
} catch {
|
|
345
|
+
throw new TraciaError(
|
|
346
|
+
"MISSING_PROVIDER_SDK" /* MISSING_PROVIDER_SDK */,
|
|
347
|
+
"OpenAI provider not installed. Run: npm install @ai-sdk/openai"
|
|
348
|
+
);
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
async function loadAnthropicProvider() {
|
|
352
|
+
if (anthropicProvider) return anthropicProvider;
|
|
353
|
+
try {
|
|
354
|
+
anthropicProvider = await import("@ai-sdk/anthropic");
|
|
355
|
+
return anthropicProvider;
|
|
356
|
+
} catch {
|
|
357
|
+
throw new TraciaError(
|
|
358
|
+
"MISSING_PROVIDER_SDK" /* MISSING_PROVIDER_SDK */,
|
|
359
|
+
"Anthropic provider not installed. Run: npm install @ai-sdk/anthropic"
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
async function loadGoogleProvider() {
|
|
364
|
+
if (googleProvider) return googleProvider;
|
|
365
|
+
try {
|
|
366
|
+
googleProvider = await import("@ai-sdk/google");
|
|
367
|
+
return googleProvider;
|
|
368
|
+
} catch {
|
|
369
|
+
throw new TraciaError(
|
|
370
|
+
"MISSING_PROVIDER_SDK" /* MISSING_PROVIDER_SDK */,
|
|
371
|
+
"Google provider not installed. Run: npm install @ai-sdk/google"
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
function combineAbortSignals(userSignal, timeoutMs) {
|
|
376
|
+
if (!timeoutMs && !userSignal) return void 0;
|
|
377
|
+
if (timeoutMs && !userSignal) return AbortSignal.timeout(timeoutMs);
|
|
378
|
+
if (!timeoutMs && userSignal) return userSignal;
|
|
379
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
380
|
+
const controller = new AbortController();
|
|
381
|
+
const cleanup = () => {
|
|
382
|
+
userSignal.removeEventListener("abort", onAbort);
|
|
383
|
+
timeoutSignal.removeEventListener("abort", onAbort);
|
|
384
|
+
};
|
|
385
|
+
const onAbort = () => {
|
|
386
|
+
cleanup();
|
|
387
|
+
controller.abort();
|
|
388
|
+
};
|
|
389
|
+
userSignal.addEventListener("abort", onAbort, { once: true });
|
|
390
|
+
timeoutSignal.addEventListener("abort", onAbort, { once: true });
|
|
391
|
+
return controller.signal;
|
|
392
|
+
}
|
|
393
|
+
function sanitizeErrorMessage(message) {
|
|
394
|
+
return message.replace(/\b(sk-|tr_|key-|api[_-]?key[=:\s]+)[a-zA-Z0-9_-]{10,}\b/gi, "[REDACTED]").replace(/Bearer\s+[a-zA-Z0-9_.-]+/gi, "Bearer [REDACTED]").replace(/Basic\s+[a-zA-Z0-9+/=]{20,}/gi, "Basic [REDACTED]").replace(/(authorization[=:\s]+)[^\s,}]+/gi, "$1[REDACTED]");
|
|
395
|
+
}
|
|
396
|
+
function resolveProvider(model, explicitProvider) {
|
|
397
|
+
if (explicitProvider) return explicitProvider;
|
|
398
|
+
const fromRegistry = getProviderForModel(model);
|
|
399
|
+
if (fromRegistry) return fromRegistry;
|
|
400
|
+
if (model.startsWith("gpt-") || model.startsWith("o1") || model.startsWith("o3") || model.startsWith("o4")) {
|
|
401
|
+
return "openai" /* OPENAI */;
|
|
402
|
+
}
|
|
403
|
+
if (model.startsWith("claude-")) {
|
|
404
|
+
return "anthropic" /* ANTHROPIC */;
|
|
405
|
+
}
|
|
406
|
+
if (model.startsWith("gemini-")) {
|
|
407
|
+
return "google" /* GOOGLE */;
|
|
408
|
+
}
|
|
409
|
+
throw new TraciaError(
|
|
410
|
+
"UNSUPPORTED_MODEL" /* UNSUPPORTED_MODEL */,
|
|
411
|
+
`Cannot determine provider for model: ${model}. Specify provider explicitly.`
|
|
412
|
+
);
|
|
413
|
+
}
|
|
414
|
+
async function getLanguageModel(provider, model, apiKey) {
|
|
415
|
+
switch (provider) {
|
|
416
|
+
case "openai" /* OPENAI */: {
|
|
417
|
+
const { createOpenAI } = await loadOpenAIProvider();
|
|
418
|
+
const openai = createOpenAI({ apiKey });
|
|
419
|
+
return openai(model);
|
|
420
|
+
}
|
|
421
|
+
case "anthropic" /* ANTHROPIC */: {
|
|
422
|
+
const { createAnthropic } = await loadAnthropicProvider();
|
|
423
|
+
const anthropic = createAnthropic({ apiKey });
|
|
424
|
+
return anthropic(model);
|
|
425
|
+
}
|
|
426
|
+
case "google" /* GOOGLE */: {
|
|
427
|
+
const { createGoogleGenerativeAI } = await loadGoogleProvider();
|
|
428
|
+
const google = createGoogleGenerativeAI({ apiKey });
|
|
429
|
+
return google(model);
|
|
430
|
+
}
|
|
431
|
+
default:
|
|
432
|
+
throw new TraciaError(
|
|
433
|
+
"UNSUPPORTED_MODEL" /* UNSUPPORTED_MODEL */,
|
|
434
|
+
`Unsupported provider: ${provider}`
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
function convertMessages(messages) {
|
|
439
|
+
return messages.map((msg) => {
|
|
440
|
+
if (msg.role === "tool") {
|
|
441
|
+
return {
|
|
442
|
+
role: "tool",
|
|
443
|
+
content: [{
|
|
444
|
+
type: "tool-result",
|
|
445
|
+
toolCallId: msg.toolCallId,
|
|
446
|
+
toolName: msg.toolCallId,
|
|
447
|
+
// AI SDK requires toolName, use toolCallId as fallback
|
|
448
|
+
input: {},
|
|
449
|
+
output: msg.content
|
|
450
|
+
}]
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
if (msg.role === "assistant" && Array.isArray(msg.content)) {
|
|
454
|
+
if (msg.content.length === 0) {
|
|
455
|
+
return { role: "assistant", content: "" };
|
|
456
|
+
}
|
|
457
|
+
const convertedContent = msg.content.map((part) => {
|
|
458
|
+
if (part.type === "tool_call") {
|
|
459
|
+
const toolCall = part;
|
|
460
|
+
return {
|
|
461
|
+
type: "tool-call",
|
|
462
|
+
toolCallId: toolCall.id,
|
|
463
|
+
toolName: toolCall.name,
|
|
464
|
+
input: toolCall.arguments
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
return part;
|
|
468
|
+
});
|
|
469
|
+
return {
|
|
470
|
+
role: "assistant",
|
|
471
|
+
content: convertedContent
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
return {
|
|
475
|
+
role: msg.role,
|
|
476
|
+
content: typeof msg.content === "string" ? msg.content : msg.content.map((b) => b.type === "text" ? b.text : "").join("")
|
|
477
|
+
};
|
|
478
|
+
});
|
|
479
|
+
}
|
|
480
|
+
async function convertTools(tools) {
|
|
481
|
+
if (!tools || tools.length === 0) return void 0;
|
|
482
|
+
const { tool, jsonSchema } = await loadAISdk();
|
|
483
|
+
const result = {};
|
|
484
|
+
for (const toolDef of tools) {
|
|
485
|
+
result[toolDef.name] = tool({
|
|
486
|
+
description: toolDef.description,
|
|
487
|
+
inputSchema: jsonSchema(toolDef.parameters),
|
|
488
|
+
execute: async (args) => args
|
|
489
|
+
// No-op execute function
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
return result;
|
|
493
|
+
}
|
|
494
|
+
function convertToolChoice(toolChoice) {
|
|
495
|
+
if (!toolChoice) return void 0;
|
|
496
|
+
if (toolChoice === "auto") return "auto";
|
|
497
|
+
if (toolChoice === "none") return "none";
|
|
498
|
+
if (toolChoice === "required") return "required";
|
|
499
|
+
return { type: "tool", toolName: toolChoice.tool };
|
|
500
|
+
}
|
|
501
|
+
function parseFinishReason(reason) {
|
|
502
|
+
if (reason === "tool-calls") return "tool_calls";
|
|
503
|
+
if (reason === "length") return "max_tokens";
|
|
504
|
+
return "stop";
|
|
505
|
+
}
|
|
506
|
+
function extractToolCalls(toolCalls) {
|
|
507
|
+
if (!toolCalls) return [];
|
|
508
|
+
return toolCalls.filter((tc) => tc.toolCallId && tc.toolName).map((tc) => ({
|
|
509
|
+
id: tc.toolCallId,
|
|
510
|
+
name: tc.toolName,
|
|
511
|
+
arguments: tc.input ?? {}
|
|
512
|
+
}));
|
|
513
|
+
}
|
|
514
|
+
async function complete(options) {
|
|
515
|
+
const { generateText } = await loadAISdk();
|
|
516
|
+
const provider = resolveProvider(options.model, options.provider);
|
|
517
|
+
const model = await getLanguageModel(provider, options.model, options.apiKey);
|
|
518
|
+
const convertedMessages = convertMessages(options.messages);
|
|
519
|
+
const convertedTools = await convertTools(options.tools);
|
|
520
|
+
const convertedToolChoice = convertToolChoice(options.toolChoice);
|
|
521
|
+
try {
|
|
522
|
+
const result = await generateText({
|
|
523
|
+
model,
|
|
524
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
525
|
+
messages: convertedMessages,
|
|
526
|
+
temperature: options.temperature,
|
|
527
|
+
maxOutputTokens: options.maxOutputTokens,
|
|
528
|
+
topP: options.topP,
|
|
529
|
+
stopSequences: options.stopSequences,
|
|
530
|
+
tools: convertedTools,
|
|
531
|
+
toolChoice: convertedToolChoice,
|
|
532
|
+
abortSignal: options.timeoutMs ? AbortSignal.timeout(options.timeoutMs) : void 0
|
|
533
|
+
});
|
|
534
|
+
const toolCalls = extractToolCalls(result.toolCalls);
|
|
535
|
+
return {
|
|
536
|
+
text: result.text,
|
|
537
|
+
inputTokens: result.usage?.inputTokens ?? 0,
|
|
538
|
+
outputTokens: result.usage?.outputTokens ?? 0,
|
|
539
|
+
totalTokens: result.usage?.totalTokens ?? 0,
|
|
540
|
+
toolCalls,
|
|
541
|
+
finishReason: parseFinishReason(result.finishReason),
|
|
542
|
+
provider
|
|
543
|
+
};
|
|
544
|
+
} catch (error) {
|
|
545
|
+
if (error instanceof TraciaError) throw error;
|
|
546
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
547
|
+
throw new TraciaError(
|
|
548
|
+
"PROVIDER_ERROR" /* PROVIDER_ERROR */,
|
|
549
|
+
`${provider} error: ${sanitizeErrorMessage(rawMessage)}`
|
|
550
|
+
);
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
function stream(options) {
|
|
554
|
+
const provider = resolveProvider(options.model, options.provider);
|
|
555
|
+
let resolveResult;
|
|
556
|
+
let rejectResult;
|
|
557
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
558
|
+
resolveResult = resolve;
|
|
559
|
+
rejectResult = reject;
|
|
560
|
+
});
|
|
561
|
+
async function* generateChunks() {
|
|
562
|
+
try {
|
|
563
|
+
const { streamText } = await loadAISdk();
|
|
564
|
+
const model = await getLanguageModel(provider, options.model, options.apiKey);
|
|
565
|
+
const convertedMessages = convertMessages(options.messages);
|
|
566
|
+
const convertedTools = await convertTools(options.tools);
|
|
567
|
+
const convertedToolChoice = convertToolChoice(options.toolChoice);
|
|
568
|
+
const abortSignal = combineAbortSignals(options.signal, options.timeoutMs);
|
|
569
|
+
const result = streamText({
|
|
570
|
+
model,
|
|
571
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
572
|
+
messages: convertedMessages,
|
|
573
|
+
temperature: options.temperature,
|
|
574
|
+
maxOutputTokens: options.maxOutputTokens,
|
|
575
|
+
topP: options.topP,
|
|
576
|
+
stopSequences: options.stopSequences,
|
|
577
|
+
tools: convertedTools,
|
|
578
|
+
toolChoice: convertedToolChoice,
|
|
579
|
+
abortSignal
|
|
580
|
+
});
|
|
581
|
+
for await (const chunk of result.textStream) {
|
|
582
|
+
yield chunk;
|
|
583
|
+
}
|
|
584
|
+
const [text, usageData, toolCallsData, finishReasonData] = await Promise.all([
|
|
585
|
+
result.text,
|
|
586
|
+
result.usage,
|
|
587
|
+
result.toolCalls,
|
|
588
|
+
result.finishReason
|
|
589
|
+
]);
|
|
590
|
+
const toolCalls = extractToolCalls(toolCallsData);
|
|
591
|
+
resolveResult({
|
|
592
|
+
text,
|
|
593
|
+
inputTokens: usageData?.inputTokens ?? 0,
|
|
594
|
+
outputTokens: usageData?.outputTokens ?? 0,
|
|
595
|
+
totalTokens: usageData?.totalTokens ?? 0,
|
|
596
|
+
toolCalls,
|
|
597
|
+
finishReason: parseFinishReason(finishReasonData),
|
|
598
|
+
provider
|
|
599
|
+
});
|
|
600
|
+
} catch (error) {
|
|
601
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
602
|
+
const traciaError2 = new TraciaError("ABORTED" /* ABORTED */, "Stream aborted");
|
|
603
|
+
rejectResult(traciaError2);
|
|
604
|
+
throw traciaError2;
|
|
605
|
+
}
|
|
606
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
607
|
+
const traciaError = error instanceof TraciaError ? error : new TraciaError(
|
|
608
|
+
"PROVIDER_ERROR" /* PROVIDER_ERROR */,
|
|
609
|
+
`${provider} error: ${sanitizeErrorMessage(rawMessage)}`
|
|
610
|
+
);
|
|
611
|
+
rejectResult(traciaError);
|
|
612
|
+
throw traciaError;
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
return {
|
|
616
|
+
chunks: generateChunks(),
|
|
617
|
+
result: resultPromise
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
function responsesStream(options) {
|
|
621
|
+
let resolveResult;
|
|
622
|
+
let rejectResult;
|
|
623
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
624
|
+
resolveResult = resolve;
|
|
625
|
+
rejectResult = reject;
|
|
626
|
+
});
|
|
627
|
+
async function* generateEvents() {
|
|
628
|
+
let fullText = "";
|
|
629
|
+
let usage = { inputTokens: 0, outputTokens: 0, totalTokens: 0 };
|
|
630
|
+
const outputItems = [];
|
|
631
|
+
const toolCalls = [];
|
|
632
|
+
let aborted = false;
|
|
633
|
+
try {
|
|
634
|
+
const { createOpenAI } = await loadOpenAIProvider();
|
|
635
|
+
const openai = createOpenAI({ apiKey: options.apiKey });
|
|
636
|
+
const model = openai.responses(options.model);
|
|
637
|
+
const { streamText } = await loadAISdk();
|
|
638
|
+
const convertedTools = options.tools ? await convertTools(options.tools) : void 0;
|
|
639
|
+
const abortSignal = combineAbortSignals(options.signal, options.timeoutMs);
|
|
640
|
+
const result = streamText({
|
|
641
|
+
model,
|
|
642
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
643
|
+
messages: options.input,
|
|
644
|
+
maxOutputTokens: options.maxOutputTokens,
|
|
645
|
+
tools: convertedTools,
|
|
646
|
+
abortSignal
|
|
647
|
+
});
|
|
648
|
+
for await (const chunk of result.textStream) {
|
|
649
|
+
fullText += chunk;
|
|
650
|
+
yield { type: "text_delta", data: chunk };
|
|
651
|
+
}
|
|
652
|
+
const [usageData, toolCallsData] = await Promise.all([
|
|
653
|
+
result.usage,
|
|
654
|
+
result.toolCalls
|
|
655
|
+
]);
|
|
656
|
+
usage = {
|
|
657
|
+
inputTokens: usageData?.inputTokens ?? 0,
|
|
658
|
+
outputTokens: usageData?.outputTokens ?? 0,
|
|
659
|
+
totalTokens: usageData?.totalTokens ?? 0
|
|
660
|
+
};
|
|
661
|
+
if (toolCallsData) {
|
|
662
|
+
for (const tc of toolCallsData) {
|
|
663
|
+
if (!tc.toolCallId || !tc.toolName) continue;
|
|
664
|
+
const toolCall = {
|
|
665
|
+
id: tc.toolCallId,
|
|
666
|
+
callId: tc.toolCallId,
|
|
667
|
+
name: tc.toolName,
|
|
668
|
+
arguments: tc.input ?? {}
|
|
669
|
+
};
|
|
670
|
+
toolCalls.push(toolCall);
|
|
671
|
+
yield {
|
|
672
|
+
type: "tool_call",
|
|
673
|
+
id: toolCall.id,
|
|
674
|
+
callId: toolCall.callId,
|
|
675
|
+
name: toolCall.name,
|
|
676
|
+
arguments: toolCall.arguments
|
|
677
|
+
};
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
if (fullText) {
|
|
681
|
+
yield { type: "text", data: fullText };
|
|
682
|
+
outputItems.push({ type: "message", content: fullText });
|
|
683
|
+
}
|
|
684
|
+
yield { type: "done", usage };
|
|
685
|
+
resolveResult({
|
|
686
|
+
text: fullText,
|
|
687
|
+
usage,
|
|
688
|
+
outputItems,
|
|
689
|
+
toolCalls,
|
|
690
|
+
aborted
|
|
691
|
+
});
|
|
692
|
+
} catch (error) {
|
|
693
|
+
if (error instanceof Error && error.name === "AbortError") {
|
|
694
|
+
aborted = true;
|
|
695
|
+
resolveResult({
|
|
696
|
+
text: fullText,
|
|
697
|
+
usage,
|
|
698
|
+
outputItems,
|
|
699
|
+
toolCalls,
|
|
700
|
+
aborted
|
|
701
|
+
});
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
const rawMessage = error instanceof Error ? error.message : String(error);
|
|
705
|
+
const traciaError = new TraciaError(
|
|
706
|
+
"PROVIDER_ERROR" /* PROVIDER_ERROR */,
|
|
707
|
+
`OpenAI Responses API error: ${sanitizeErrorMessage(rawMessage)}`
|
|
708
|
+
);
|
|
709
|
+
rejectResult(traciaError);
|
|
710
|
+
throw traciaError;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return {
|
|
714
|
+
events: generateEvents(),
|
|
715
|
+
result: resultPromise
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
|
|
205
719
|
// src/traces.ts
|
|
720
|
+
var INTERNAL_SET_PENDING_TRACES = /* @__PURE__ */ Symbol("setPendingTracesMap");
|
|
206
721
|
var Traces = class {
|
|
207
722
|
constructor(client) {
|
|
208
723
|
this.client = client;
|
|
724
|
+
this.pendingTraces = null;
|
|
725
|
+
}
|
|
726
|
+
/** @internal */
|
|
727
|
+
[INTERNAL_SET_PENDING_TRACES](map) {
|
|
728
|
+
this.pendingTraces = map;
|
|
729
|
+
}
|
|
730
|
+
async create(payload) {
|
|
731
|
+
return this.client.post("/api/v1/traces", payload);
|
|
209
732
|
}
|
|
210
733
|
async get(traceId) {
|
|
211
734
|
return this.client.get(`/api/v1/traces/${encodeURIComponent(traceId)}`);
|
|
@@ -243,25 +766,681 @@ var Traces = class {
|
|
|
243
766
|
const path = query ? `/api/v1/traces?${query}` : "/api/v1/traces";
|
|
244
767
|
return this.client.get(path);
|
|
245
768
|
}
|
|
769
|
+
async evaluate(traceId, options) {
|
|
770
|
+
if (this.pendingTraces) {
|
|
771
|
+
const pendingTrace = this.pendingTraces.get(traceId);
|
|
772
|
+
if (pendingTrace) {
|
|
773
|
+
await pendingTrace;
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
if (typeof options.value !== "number") {
|
|
777
|
+
throw new TraciaError(
|
|
778
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
779
|
+
`Invalid evaluation value. Must be a number.`
|
|
780
|
+
);
|
|
781
|
+
}
|
|
782
|
+
const body = {
|
|
783
|
+
evaluatorKey: options.evaluator,
|
|
784
|
+
value: options.value
|
|
785
|
+
};
|
|
786
|
+
if (options.note !== void 0) {
|
|
787
|
+
body.note = options.note;
|
|
788
|
+
}
|
|
789
|
+
return this.client.post(
|
|
790
|
+
`/api/v1/traces/${encodeURIComponent(traceId)}/evaluations`,
|
|
791
|
+
body
|
|
792
|
+
);
|
|
793
|
+
}
|
|
246
794
|
};
|
|
247
795
|
|
|
796
|
+
// src/utils.ts
|
|
797
|
+
var import_crypto = __toESM(require("crypto"));
|
|
798
|
+
var TRACE_ID_REGEX = /^tr_[a-f0-9]{16}$/i;
|
|
799
|
+
function generateTraceId() {
|
|
800
|
+
const randomPart = import_crypto.default.randomBytes(8).toString("hex");
|
|
801
|
+
return `tr_${randomPart}`;
|
|
802
|
+
}
|
|
803
|
+
function isValidTraceIdFormat(traceId) {
|
|
804
|
+
return TRACE_ID_REGEX.test(traceId);
|
|
805
|
+
}
|
|
806
|
+
|
|
248
807
|
// src/index.ts
|
|
808
|
+
var Eval = {
|
|
809
|
+
POSITIVE: 1,
|
|
810
|
+
NEGATIVE: 0
|
|
811
|
+
};
|
|
249
812
|
var DEFAULT_BASE_URL = "https://app.tracia.io";
|
|
813
|
+
var MAX_PENDING_TRACES = 1e3;
|
|
814
|
+
var TRACE_RETRY_ATTEMPTS = 2;
|
|
815
|
+
var TRACE_RETRY_DELAY_MS = 500;
|
|
816
|
+
var TRACE_STATUS_SUCCESS = "SUCCESS";
|
|
817
|
+
var TRACE_STATUS_ERROR = "ERROR";
|
|
818
|
+
var ENV_VAR_MAP = {
|
|
819
|
+
["openai" /* OPENAI */]: "OPENAI_API_KEY",
|
|
820
|
+
["anthropic" /* ANTHROPIC */]: "ANTHROPIC_API_KEY",
|
|
821
|
+
["google" /* GOOGLE */]: "GOOGLE_API_KEY"
|
|
822
|
+
};
|
|
823
|
+
function convertResponsesItemToMessage(item) {
|
|
824
|
+
if ("role" in item && (item.role === "developer" || item.role === "user")) {
|
|
825
|
+
const messageItem = item;
|
|
826
|
+
return {
|
|
827
|
+
role: messageItem.role === "developer" ? "system" : "user",
|
|
828
|
+
content: messageItem.content
|
|
829
|
+
};
|
|
830
|
+
}
|
|
831
|
+
if ("type" in item && item.type === "function_call_output") {
|
|
832
|
+
const outputItem = item;
|
|
833
|
+
return {
|
|
834
|
+
role: "tool",
|
|
835
|
+
toolCallId: outputItem.call_id,
|
|
836
|
+
content: outputItem.output
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
if ("type" in item) {
|
|
840
|
+
return {
|
|
841
|
+
role: "assistant",
|
|
842
|
+
content: JSON.stringify(item)
|
|
843
|
+
};
|
|
844
|
+
}
|
|
845
|
+
return {
|
|
846
|
+
role: "user",
|
|
847
|
+
content: JSON.stringify(item)
|
|
848
|
+
};
|
|
849
|
+
}
|
|
250
850
|
var Tracia = class {
|
|
251
851
|
constructor(options) {
|
|
852
|
+
this.pendingTraces = /* @__PURE__ */ new Map();
|
|
252
853
|
if (!options.apiKey) {
|
|
253
|
-
throw new
|
|
854
|
+
throw new TraciaError(
|
|
855
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
856
|
+
"apiKey is required"
|
|
857
|
+
);
|
|
254
858
|
}
|
|
255
859
|
this.client = new HttpClient({
|
|
256
860
|
apiKey: options.apiKey,
|
|
257
861
|
baseUrl: DEFAULT_BASE_URL
|
|
258
862
|
});
|
|
863
|
+
this.onTraceError = options.onTraceError;
|
|
259
864
|
this.prompts = new Prompts(this.client);
|
|
260
865
|
this.traces = new Traces(this.client);
|
|
866
|
+
this.traces[INTERNAL_SET_PENDING_TRACES](this.pendingTraces);
|
|
867
|
+
}
|
|
868
|
+
runLocal(input) {
|
|
869
|
+
if (input.stream === true) {
|
|
870
|
+
return this.runLocalStreaming(input);
|
|
871
|
+
}
|
|
872
|
+
return this.runLocalNonStreaming(input);
|
|
873
|
+
}
|
|
874
|
+
async runLocalNonStreaming(input) {
|
|
875
|
+
this.validateRunLocalInput(input);
|
|
876
|
+
let traceId = "";
|
|
877
|
+
if (input.sendTrace !== false) {
|
|
878
|
+
if (input.traceId && !isValidTraceIdFormat(input.traceId)) {
|
|
879
|
+
throw new TraciaError(
|
|
880
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
881
|
+
`Invalid trace ID format. Must match: tr_ + 16 hex characters (e.g., tr_1234567890abcdef)`
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
traceId = input.traceId || generateTraceId();
|
|
885
|
+
}
|
|
886
|
+
const interpolatedMessages = this.interpolateMessages(input.messages, input.variables);
|
|
887
|
+
const provider = resolveProvider(input.model, input.provider);
|
|
888
|
+
const apiKey = this.getProviderApiKey(provider, input.providerApiKey);
|
|
889
|
+
const startTime = Date.now();
|
|
890
|
+
let completionResult = null;
|
|
891
|
+
let errorMessage = null;
|
|
892
|
+
try {
|
|
893
|
+
completionResult = await complete({
|
|
894
|
+
model: input.model,
|
|
895
|
+
messages: interpolatedMessages,
|
|
896
|
+
apiKey,
|
|
897
|
+
provider: input.provider,
|
|
898
|
+
temperature: input.temperature,
|
|
899
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
900
|
+
topP: input.topP,
|
|
901
|
+
stopSequences: input.stopSequences,
|
|
902
|
+
tools: input.tools,
|
|
903
|
+
toolChoice: input.toolChoice,
|
|
904
|
+
timeoutMs: input.timeoutMs
|
|
905
|
+
});
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (error instanceof TraciaError) {
|
|
908
|
+
errorMessage = error.message;
|
|
909
|
+
} else {
|
|
910
|
+
errorMessage = error instanceof Error ? error.message : String(error);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
const latencyMs = Date.now() - startTime;
|
|
914
|
+
if (traceId) {
|
|
915
|
+
this.scheduleTraceCreation(traceId, {
|
|
916
|
+
traceId,
|
|
917
|
+
model: input.model,
|
|
918
|
+
provider: completionResult?.provider ?? provider,
|
|
919
|
+
input: { messages: interpolatedMessages },
|
|
920
|
+
variables: input.variables ?? null,
|
|
921
|
+
output: completionResult?.text ?? null,
|
|
922
|
+
status: errorMessage ? TRACE_STATUS_ERROR : TRACE_STATUS_SUCCESS,
|
|
923
|
+
error: errorMessage,
|
|
924
|
+
latencyMs,
|
|
925
|
+
inputTokens: completionResult?.inputTokens ?? 0,
|
|
926
|
+
outputTokens: completionResult?.outputTokens ?? 0,
|
|
927
|
+
totalTokens: completionResult?.totalTokens ?? 0,
|
|
928
|
+
tags: input.tags,
|
|
929
|
+
userId: input.userId,
|
|
930
|
+
sessionId: input.sessionId,
|
|
931
|
+
temperature: input.temperature,
|
|
932
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
933
|
+
topP: input.topP,
|
|
934
|
+
tools: input.tools,
|
|
935
|
+
toolCalls: completionResult?.toolCalls
|
|
936
|
+
});
|
|
937
|
+
}
|
|
938
|
+
if (errorMessage) {
|
|
939
|
+
throw new TraciaError("PROVIDER_ERROR" /* PROVIDER_ERROR */, errorMessage);
|
|
940
|
+
}
|
|
941
|
+
const toolCalls = completionResult.toolCalls;
|
|
942
|
+
const finishReason = completionResult.finishReason;
|
|
943
|
+
const message = this.buildAssistantMessage(completionResult.text, toolCalls);
|
|
944
|
+
return {
|
|
945
|
+
text: completionResult.text,
|
|
946
|
+
traceId,
|
|
947
|
+
latencyMs,
|
|
948
|
+
usage: {
|
|
949
|
+
inputTokens: completionResult.inputTokens,
|
|
950
|
+
outputTokens: completionResult.outputTokens,
|
|
951
|
+
totalTokens: completionResult.totalTokens
|
|
952
|
+
},
|
|
953
|
+
cost: null,
|
|
954
|
+
provider: completionResult.provider,
|
|
955
|
+
model: input.model,
|
|
956
|
+
toolCalls,
|
|
957
|
+
finishReason,
|
|
958
|
+
message
|
|
959
|
+
};
|
|
960
|
+
}
|
|
961
|
+
runLocalStreaming(input) {
|
|
962
|
+
this.validateRunLocalInput(input);
|
|
963
|
+
let traceId = "";
|
|
964
|
+
if (input.sendTrace !== false) {
|
|
965
|
+
if (input.traceId && !isValidTraceIdFormat(input.traceId)) {
|
|
966
|
+
throw new TraciaError(
|
|
967
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
968
|
+
`Invalid trace ID format. Must match: tr_ + 16 hex characters (e.g., tr_1234567890abcdef)`
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
traceId = input.traceId || generateTraceId();
|
|
972
|
+
}
|
|
973
|
+
const interpolatedMessages = this.interpolateMessages(input.messages, input.variables);
|
|
974
|
+
const provider = resolveProvider(input.model, input.provider);
|
|
975
|
+
const apiKey = this.getProviderApiKey(provider, input.providerApiKey);
|
|
976
|
+
const abortController = new AbortController();
|
|
977
|
+
const combinedSignal = input.signal ? this.combineAbortSignals(input.signal, abortController.signal) : abortController.signal;
|
|
978
|
+
return this.createLocalStream(
|
|
979
|
+
input,
|
|
980
|
+
interpolatedMessages,
|
|
981
|
+
provider,
|
|
982
|
+
apiKey,
|
|
983
|
+
traceId,
|
|
984
|
+
combinedSignal,
|
|
985
|
+
abortController
|
|
986
|
+
);
|
|
987
|
+
}
|
|
988
|
+
runResponses(input) {
|
|
989
|
+
if (input.stream === true) {
|
|
990
|
+
return this.runResponsesStreaming(input);
|
|
991
|
+
}
|
|
992
|
+
return this.runResponsesNonStreaming(input);
|
|
993
|
+
}
|
|
994
|
+
async runResponsesNonStreaming(input) {
|
|
995
|
+
const stream2 = this.runResponsesStreaming(input);
|
|
996
|
+
for await (const _event of stream2) {
|
|
997
|
+
}
|
|
998
|
+
return stream2.result;
|
|
999
|
+
}
|
|
1000
|
+
runResponsesStreaming(input) {
|
|
1001
|
+
this.validateResponsesInput(input);
|
|
1002
|
+
let traceId = "";
|
|
1003
|
+
if (input.sendTrace !== false) {
|
|
1004
|
+
if (input.traceId && !isValidTraceIdFormat(input.traceId)) {
|
|
1005
|
+
throw new TraciaError(
|
|
1006
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1007
|
+
`Invalid trace ID format. Must match: tr_ + 16 hex characters (e.g., tr_1234567890abcdef)`
|
|
1008
|
+
);
|
|
1009
|
+
}
|
|
1010
|
+
traceId = input.traceId || generateTraceId();
|
|
1011
|
+
}
|
|
1012
|
+
const apiKey = this.getProviderApiKey("openai" /* OPENAI */, input.providerApiKey);
|
|
1013
|
+
const abortController = new AbortController();
|
|
1014
|
+
const combinedSignal = input.signal ? this.combineAbortSignals(input.signal, abortController.signal) : abortController.signal;
|
|
1015
|
+
return this.createResponsesStream(
|
|
1016
|
+
input,
|
|
1017
|
+
apiKey,
|
|
1018
|
+
traceId,
|
|
1019
|
+
combinedSignal,
|
|
1020
|
+
abortController
|
|
1021
|
+
);
|
|
1022
|
+
}
|
|
1023
|
+
validateResponsesInput(input) {
|
|
1024
|
+
if (!input.model || input.model.trim() === "") {
|
|
1025
|
+
throw new TraciaError(
|
|
1026
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1027
|
+
"model is required and cannot be empty"
|
|
1028
|
+
);
|
|
1029
|
+
}
|
|
1030
|
+
if (!input.input || input.input.length === 0) {
|
|
1031
|
+
throw new TraciaError(
|
|
1032
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1033
|
+
"input array is required and cannot be empty"
|
|
1034
|
+
);
|
|
1035
|
+
}
|
|
1036
|
+
}
|
|
1037
|
+
createResponsesStream(input, apiKey, traceId, signal, abortController) {
|
|
1038
|
+
const startTime = Date.now();
|
|
1039
|
+
let aborted = false;
|
|
1040
|
+
let resolveResult;
|
|
1041
|
+
let rejectResult;
|
|
1042
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
1043
|
+
resolveResult = resolve;
|
|
1044
|
+
rejectResult = reject;
|
|
1045
|
+
});
|
|
1046
|
+
const providerStream = responsesStream({
|
|
1047
|
+
model: input.model,
|
|
1048
|
+
input: input.input,
|
|
1049
|
+
apiKey,
|
|
1050
|
+
tools: input.tools,
|
|
1051
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
1052
|
+
timeoutMs: input.timeoutMs,
|
|
1053
|
+
signal
|
|
1054
|
+
});
|
|
1055
|
+
let collectedText = "";
|
|
1056
|
+
const scheduleTrace = this.scheduleTraceCreation.bind(this);
|
|
1057
|
+
async function* wrappedEvents() {
|
|
1058
|
+
try {
|
|
1059
|
+
for await (const event of providerStream.events) {
|
|
1060
|
+
if (event.type === "text_delta") {
|
|
1061
|
+
collectedText += event.data;
|
|
1062
|
+
}
|
|
1063
|
+
yield event;
|
|
1064
|
+
}
|
|
1065
|
+
const providerResult = await providerStream.result;
|
|
1066
|
+
const latencyMs = Date.now() - startTime;
|
|
1067
|
+
if (traceId) {
|
|
1068
|
+
scheduleTrace(traceId, {
|
|
1069
|
+
traceId,
|
|
1070
|
+
model: input.model,
|
|
1071
|
+
provider: "openai" /* OPENAI */,
|
|
1072
|
+
input: { messages: input.input.map((item) => convertResponsesItemToMessage(item)) },
|
|
1073
|
+
variables: null,
|
|
1074
|
+
output: providerResult.text,
|
|
1075
|
+
status: providerResult.aborted ? TRACE_STATUS_ERROR : TRACE_STATUS_SUCCESS,
|
|
1076
|
+
error: providerResult.aborted ? "Stream aborted" : null,
|
|
1077
|
+
latencyMs,
|
|
1078
|
+
inputTokens: providerResult.usage.inputTokens,
|
|
1079
|
+
outputTokens: providerResult.usage.outputTokens,
|
|
1080
|
+
totalTokens: providerResult.usage.totalTokens,
|
|
1081
|
+
tags: input.tags,
|
|
1082
|
+
userId: input.userId,
|
|
1083
|
+
sessionId: input.sessionId,
|
|
1084
|
+
tools: input.tools,
|
|
1085
|
+
toolCalls: providerResult.toolCalls.map((tc) => ({
|
|
1086
|
+
id: tc.id,
|
|
1087
|
+
name: tc.name,
|
|
1088
|
+
arguments: tc.arguments
|
|
1089
|
+
}))
|
|
1090
|
+
});
|
|
1091
|
+
}
|
|
1092
|
+
resolveResult({
|
|
1093
|
+
text: providerResult.text,
|
|
1094
|
+
traceId,
|
|
1095
|
+
latencyMs,
|
|
1096
|
+
usage: providerResult.usage,
|
|
1097
|
+
outputItems: providerResult.outputItems,
|
|
1098
|
+
toolCalls: providerResult.toolCalls,
|
|
1099
|
+
aborted: providerResult.aborted
|
|
1100
|
+
});
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
const latencyMs = Date.now() - startTime;
|
|
1103
|
+
const isAborted = aborted || signal.aborted;
|
|
1104
|
+
const errorMessage = isAborted ? "Stream aborted" : error instanceof Error ? error.message : String(error);
|
|
1105
|
+
if (traceId) {
|
|
1106
|
+
scheduleTrace(traceId, {
|
|
1107
|
+
traceId,
|
|
1108
|
+
model: input.model,
|
|
1109
|
+
provider: "openai" /* OPENAI */,
|
|
1110
|
+
input: { messages: input.input.map((item) => convertResponsesItemToMessage(item)) },
|
|
1111
|
+
variables: null,
|
|
1112
|
+
output: collectedText || null,
|
|
1113
|
+
status: TRACE_STATUS_ERROR,
|
|
1114
|
+
error: errorMessage,
|
|
1115
|
+
latencyMs,
|
|
1116
|
+
inputTokens: 0,
|
|
1117
|
+
outputTokens: 0,
|
|
1118
|
+
totalTokens: 0,
|
|
1119
|
+
tags: input.tags,
|
|
1120
|
+
userId: input.userId,
|
|
1121
|
+
sessionId: input.sessionId,
|
|
1122
|
+
tools: input.tools
|
|
1123
|
+
});
|
|
1124
|
+
}
|
|
1125
|
+
if (isAborted) {
|
|
1126
|
+
resolveResult({
|
|
1127
|
+
text: collectedText,
|
|
1128
|
+
traceId,
|
|
1129
|
+
latencyMs,
|
|
1130
|
+
usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },
|
|
1131
|
+
outputItems: [],
|
|
1132
|
+
toolCalls: [],
|
|
1133
|
+
aborted: true
|
|
1134
|
+
});
|
|
1135
|
+
} else {
|
|
1136
|
+
const traciaError = error instanceof TraciaError ? error : new TraciaError("PROVIDER_ERROR" /* PROVIDER_ERROR */, errorMessage);
|
|
1137
|
+
rejectResult(traciaError);
|
|
1138
|
+
throw traciaError;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
const asyncIterator = wrappedEvents();
|
|
1143
|
+
return {
|
|
1144
|
+
traceId,
|
|
1145
|
+
[Symbol.asyncIterator]() {
|
|
1146
|
+
return asyncIterator;
|
|
1147
|
+
},
|
|
1148
|
+
result: resultPromise,
|
|
1149
|
+
abort() {
|
|
1150
|
+
aborted = true;
|
|
1151
|
+
abortController.abort();
|
|
1152
|
+
}
|
|
1153
|
+
};
|
|
1154
|
+
}
|
|
1155
|
+
createLocalStream(input, interpolatedMessages, provider, apiKey, traceId, signal, abortController) {
|
|
1156
|
+
const startTime = Date.now();
|
|
1157
|
+
let aborted = false;
|
|
1158
|
+
let resolveResult;
|
|
1159
|
+
let rejectResult;
|
|
1160
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
1161
|
+
resolveResult = resolve;
|
|
1162
|
+
rejectResult = reject;
|
|
1163
|
+
});
|
|
1164
|
+
const providerStream = stream({
|
|
1165
|
+
model: input.model,
|
|
1166
|
+
messages: interpolatedMessages,
|
|
1167
|
+
apiKey,
|
|
1168
|
+
provider: input.provider,
|
|
1169
|
+
temperature: input.temperature,
|
|
1170
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
1171
|
+
topP: input.topP,
|
|
1172
|
+
stopSequences: input.stopSequences,
|
|
1173
|
+
tools: input.tools,
|
|
1174
|
+
toolChoice: input.toolChoice,
|
|
1175
|
+
timeoutMs: input.timeoutMs,
|
|
1176
|
+
signal
|
|
1177
|
+
});
|
|
1178
|
+
let collectedText = "";
|
|
1179
|
+
const scheduleTrace = this.scheduleTraceCreation.bind(this);
|
|
1180
|
+
const buildAssistantMessage = this.buildAssistantMessage.bind(this);
|
|
1181
|
+
async function* wrappedChunks() {
|
|
1182
|
+
try {
|
|
1183
|
+
for await (const chunk of providerStream.chunks) {
|
|
1184
|
+
collectedText += chunk;
|
|
1185
|
+
yield chunk;
|
|
1186
|
+
}
|
|
1187
|
+
const completionResult = await providerStream.result;
|
|
1188
|
+
const latencyMs = Date.now() - startTime;
|
|
1189
|
+
if (traceId) {
|
|
1190
|
+
scheduleTrace(traceId, {
|
|
1191
|
+
traceId,
|
|
1192
|
+
model: input.model,
|
|
1193
|
+
provider: completionResult.provider,
|
|
1194
|
+
input: { messages: interpolatedMessages },
|
|
1195
|
+
variables: input.variables ?? null,
|
|
1196
|
+
output: completionResult.text,
|
|
1197
|
+
status: TRACE_STATUS_SUCCESS,
|
|
1198
|
+
error: null,
|
|
1199
|
+
latencyMs,
|
|
1200
|
+
inputTokens: completionResult.inputTokens,
|
|
1201
|
+
outputTokens: completionResult.outputTokens,
|
|
1202
|
+
totalTokens: completionResult.totalTokens,
|
|
1203
|
+
tags: input.tags,
|
|
1204
|
+
userId: input.userId,
|
|
1205
|
+
sessionId: input.sessionId,
|
|
1206
|
+
temperature: input.temperature,
|
|
1207
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
1208
|
+
topP: input.topP,
|
|
1209
|
+
tools: input.tools,
|
|
1210
|
+
toolCalls: completionResult.toolCalls
|
|
1211
|
+
});
|
|
1212
|
+
}
|
|
1213
|
+
const toolCalls = completionResult.toolCalls;
|
|
1214
|
+
const finishReason = completionResult.finishReason;
|
|
1215
|
+
const message = buildAssistantMessage(completionResult.text, toolCalls);
|
|
1216
|
+
resolveResult({
|
|
1217
|
+
text: completionResult.text,
|
|
1218
|
+
traceId,
|
|
1219
|
+
latencyMs,
|
|
1220
|
+
usage: {
|
|
1221
|
+
inputTokens: completionResult.inputTokens,
|
|
1222
|
+
outputTokens: completionResult.outputTokens,
|
|
1223
|
+
totalTokens: completionResult.totalTokens
|
|
1224
|
+
},
|
|
1225
|
+
cost: null,
|
|
1226
|
+
provider: completionResult.provider,
|
|
1227
|
+
model: input.model,
|
|
1228
|
+
aborted: false,
|
|
1229
|
+
toolCalls,
|
|
1230
|
+
finishReason,
|
|
1231
|
+
message
|
|
1232
|
+
});
|
|
1233
|
+
} catch (error) {
|
|
1234
|
+
const latencyMs = Date.now() - startTime;
|
|
1235
|
+
const isAborted = aborted || signal.aborted;
|
|
1236
|
+
const errorMessage = isAborted ? "Stream aborted" : error instanceof Error ? error.message : String(error);
|
|
1237
|
+
if (traceId) {
|
|
1238
|
+
scheduleTrace(traceId, {
|
|
1239
|
+
traceId,
|
|
1240
|
+
model: input.model,
|
|
1241
|
+
provider,
|
|
1242
|
+
input: { messages: interpolatedMessages },
|
|
1243
|
+
variables: input.variables ?? null,
|
|
1244
|
+
output: collectedText || null,
|
|
1245
|
+
status: TRACE_STATUS_ERROR,
|
|
1246
|
+
error: errorMessage,
|
|
1247
|
+
latencyMs,
|
|
1248
|
+
inputTokens: 0,
|
|
1249
|
+
outputTokens: 0,
|
|
1250
|
+
totalTokens: 0,
|
|
1251
|
+
tags: input.tags,
|
|
1252
|
+
userId: input.userId,
|
|
1253
|
+
sessionId: input.sessionId,
|
|
1254
|
+
temperature: input.temperature,
|
|
1255
|
+
maxOutputTokens: input.maxOutputTokens,
|
|
1256
|
+
topP: input.topP
|
|
1257
|
+
});
|
|
1258
|
+
}
|
|
1259
|
+
if (isAborted) {
|
|
1260
|
+
const abortedMessage = buildAssistantMessage(collectedText, []);
|
|
1261
|
+
resolveResult({
|
|
1262
|
+
text: collectedText,
|
|
1263
|
+
traceId,
|
|
1264
|
+
latencyMs,
|
|
1265
|
+
usage: {
|
|
1266
|
+
inputTokens: 0,
|
|
1267
|
+
outputTokens: 0,
|
|
1268
|
+
totalTokens: 0
|
|
1269
|
+
},
|
|
1270
|
+
cost: null,
|
|
1271
|
+
provider,
|
|
1272
|
+
model: input.model,
|
|
1273
|
+
aborted: true,
|
|
1274
|
+
toolCalls: [],
|
|
1275
|
+
finishReason: "stop",
|
|
1276
|
+
message: abortedMessage
|
|
1277
|
+
});
|
|
1278
|
+
} else {
|
|
1279
|
+
const traciaError = error instanceof TraciaError ? error : new TraciaError("PROVIDER_ERROR" /* PROVIDER_ERROR */, errorMessage);
|
|
1280
|
+
rejectResult(traciaError);
|
|
1281
|
+
throw traciaError;
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
const asyncIterator = wrappedChunks();
|
|
1286
|
+
return {
|
|
1287
|
+
traceId,
|
|
1288
|
+
[Symbol.asyncIterator]() {
|
|
1289
|
+
return asyncIterator;
|
|
1290
|
+
},
|
|
1291
|
+
result: resultPromise,
|
|
1292
|
+
abort() {
|
|
1293
|
+
aborted = true;
|
|
1294
|
+
abortController.abort();
|
|
1295
|
+
}
|
|
1296
|
+
};
|
|
1297
|
+
}
|
|
1298
|
+
combineAbortSignals(signal1, signal2) {
|
|
1299
|
+
const controller = new AbortController();
|
|
1300
|
+
if (signal1.aborted || signal2.aborted) {
|
|
1301
|
+
controller.abort();
|
|
1302
|
+
return controller.signal;
|
|
1303
|
+
}
|
|
1304
|
+
const onAbort = () => {
|
|
1305
|
+
signal1.removeEventListener("abort", onAbort);
|
|
1306
|
+
signal2.removeEventListener("abort", onAbort);
|
|
1307
|
+
controller.abort();
|
|
1308
|
+
};
|
|
1309
|
+
signal1.addEventListener("abort", onAbort, { once: true });
|
|
1310
|
+
signal2.addEventListener("abort", onAbort, { once: true });
|
|
1311
|
+
return controller.signal;
|
|
1312
|
+
}
|
|
1313
|
+
async flush() {
|
|
1314
|
+
await Promise.all(this.pendingTraces.values());
|
|
1315
|
+
}
|
|
1316
|
+
validateRunLocalInput(input) {
|
|
1317
|
+
if (!input.model || input.model.trim() === "") {
|
|
1318
|
+
throw new TraciaError(
|
|
1319
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1320
|
+
"model is required and cannot be empty"
|
|
1321
|
+
);
|
|
1322
|
+
}
|
|
1323
|
+
if (!input.messages || input.messages.length === 0) {
|
|
1324
|
+
throw new TraciaError(
|
|
1325
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1326
|
+
"messages array is required and cannot be empty"
|
|
1327
|
+
);
|
|
1328
|
+
}
|
|
1329
|
+
for (const message of input.messages) {
|
|
1330
|
+
if (message.role === "tool") {
|
|
1331
|
+
if (!message.toolCallId) {
|
|
1332
|
+
throw new TraciaError(
|
|
1333
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1334
|
+
`Tool messages must include toolCallId. Example: { role: "tool", toolCallId: "call_123", content: '{"result": "data"}' }`
|
|
1335
|
+
);
|
|
1336
|
+
}
|
|
1337
|
+
if (typeof message.content !== "string") {
|
|
1338
|
+
throw new TraciaError(
|
|
1339
|
+
"INVALID_REQUEST" /* INVALID_REQUEST */,
|
|
1340
|
+
`Tool message content must be a string (the tool result). Example: { role: "tool", toolCallId: "call_123", content: '{"result": "data"}' }`
|
|
1341
|
+
);
|
|
1342
|
+
}
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
}
|
|
1346
|
+
scheduleTraceCreation(traceId, payload) {
|
|
1347
|
+
if (this.pendingTraces.size >= MAX_PENDING_TRACES) {
|
|
1348
|
+
const oldestTraceId = this.pendingTraces.keys().next().value;
|
|
1349
|
+
if (oldestTraceId) {
|
|
1350
|
+
this.pendingTraces.delete(oldestTraceId);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
const tracePromise = this.createTraceWithRetry(traceId, payload);
|
|
1354
|
+
this.pendingTraces.set(traceId, tracePromise);
|
|
1355
|
+
tracePromise.finally(() => this.pendingTraces.delete(traceId));
|
|
1356
|
+
}
|
|
1357
|
+
async createTraceWithRetry(traceId, payload) {
|
|
1358
|
+
let lastError = null;
|
|
1359
|
+
for (let attempt = 0; attempt <= TRACE_RETRY_ATTEMPTS; attempt++) {
|
|
1360
|
+
try {
|
|
1361
|
+
await this.traces.create(payload);
|
|
1362
|
+
return;
|
|
1363
|
+
} catch (error) {
|
|
1364
|
+
lastError = error instanceof Error ? error : new Error(String(error));
|
|
1365
|
+
if (attempt < TRACE_RETRY_ATTEMPTS) {
|
|
1366
|
+
await this.delay(TRACE_RETRY_DELAY_MS * (attempt + 1));
|
|
1367
|
+
}
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
if (this.onTraceError && lastError) {
|
|
1371
|
+
this.onTraceError(lastError, traceId);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
delay(ms) {
|
|
1375
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
1376
|
+
}
|
|
1377
|
+
interpolateMessages(messages, variables) {
|
|
1378
|
+
if (!variables) return messages;
|
|
1379
|
+
return messages.map((message) => {
|
|
1380
|
+
if (typeof message.content === "string") {
|
|
1381
|
+
return {
|
|
1382
|
+
...message,
|
|
1383
|
+
content: message.content.replace(
|
|
1384
|
+
/\{\{(\w+)\}\}/g,
|
|
1385
|
+
(match, key) => variables[key] ?? match
|
|
1386
|
+
)
|
|
1387
|
+
};
|
|
1388
|
+
}
|
|
1389
|
+
if (message.role === "tool") {
|
|
1390
|
+
return message;
|
|
1391
|
+
}
|
|
1392
|
+
return {
|
|
1393
|
+
...message,
|
|
1394
|
+
content: message.content.map((block) => {
|
|
1395
|
+
if (block.type === "text") {
|
|
1396
|
+
return {
|
|
1397
|
+
...block,
|
|
1398
|
+
text: block.text.replace(
|
|
1399
|
+
/\{\{(\w+)\}\}/g,
|
|
1400
|
+
(match, key) => variables[key] ?? match
|
|
1401
|
+
)
|
|
1402
|
+
};
|
|
1403
|
+
}
|
|
1404
|
+
return block;
|
|
1405
|
+
})
|
|
1406
|
+
};
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
buildAssistantMessage(text, toolCalls) {
|
|
1410
|
+
if (toolCalls.length === 0) {
|
|
1411
|
+
return { role: "assistant", content: text };
|
|
1412
|
+
}
|
|
1413
|
+
const contentParts = [];
|
|
1414
|
+
if (text) {
|
|
1415
|
+
contentParts.push({ type: "text", text });
|
|
1416
|
+
}
|
|
1417
|
+
for (const toolCall of toolCalls) {
|
|
1418
|
+
contentParts.push({
|
|
1419
|
+
type: "tool_call",
|
|
1420
|
+
id: toolCall.id,
|
|
1421
|
+
name: toolCall.name,
|
|
1422
|
+
arguments: toolCall.arguments
|
|
1423
|
+
});
|
|
1424
|
+
}
|
|
1425
|
+
return { role: "assistant", content: contentParts };
|
|
1426
|
+
}
|
|
1427
|
+
getProviderApiKey(provider, override) {
|
|
1428
|
+
if (override) return override;
|
|
1429
|
+
const envVar = ENV_VAR_MAP[provider];
|
|
1430
|
+
const key = process.env[envVar];
|
|
1431
|
+
if (!key) {
|
|
1432
|
+
throw new TraciaError(
|
|
1433
|
+
"MISSING_PROVIDER_API_KEY" /* MISSING_PROVIDER_API_KEY */,
|
|
1434
|
+
`Missing API key for ${provider}. Set the ${envVar} environment variable or provide providerApiKey in options.`
|
|
1435
|
+
);
|
|
1436
|
+
}
|
|
1437
|
+
return key;
|
|
261
1438
|
}
|
|
262
1439
|
};
|
|
263
1440
|
// Annotate the CommonJS export names for ESM import in node:
|
|
264
1441
|
0 && (module.exports = {
|
|
1442
|
+
Eval,
|
|
1443
|
+
LLMProvider,
|
|
265
1444
|
Tracia,
|
|
266
1445
|
TraciaError,
|
|
267
1446
|
TraciaErrorCode
|