@yourgpt/llm-sdk 2.1.8 → 2.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -21,7 +21,12 @@ function togetherai(modelId, options = {}) {
|
|
|
21
21
|
supportsThinking: false,
|
|
22
22
|
supportsPDF: false,
|
|
23
23
|
maxTokens: 131072,
|
|
24
|
-
supportedImageTypes: [
|
|
24
|
+
supportedImageTypes: [
|
|
25
|
+
"image/png",
|
|
26
|
+
"image/jpeg",
|
|
27
|
+
"image/gif",
|
|
28
|
+
"image/webp"
|
|
29
|
+
]
|
|
25
30
|
},
|
|
26
31
|
async doGenerate(params) {
|
|
27
32
|
const client2 = await getClient();
|
|
@@ -197,6 +202,725 @@ function formatMessages(messages) {
|
|
|
197
202
|
});
|
|
198
203
|
}
|
|
199
204
|
|
|
200
|
-
|
|
205
|
+
// src/core/utils.ts
|
|
206
|
+
function generateId(prefix = "id") {
|
|
207
|
+
return `${prefix}_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;
|
|
208
|
+
}
|
|
209
|
+
function generateMessageId() {
|
|
210
|
+
return generateId("msg");
|
|
211
|
+
}
|
|
212
|
+
function generateToolCallId() {
|
|
213
|
+
return generateId("call");
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
// src/adapters/base.ts
|
|
217
|
+
function stringifyForDebug(value) {
|
|
218
|
+
return JSON.stringify(
|
|
219
|
+
value,
|
|
220
|
+
(_key, currentValue) => {
|
|
221
|
+
if (typeof currentValue === "bigint") {
|
|
222
|
+
return currentValue.toString();
|
|
223
|
+
}
|
|
224
|
+
if (currentValue instanceof Error) {
|
|
225
|
+
return {
|
|
226
|
+
name: currentValue.name,
|
|
227
|
+
message: currentValue.message,
|
|
228
|
+
stack: currentValue.stack
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
return currentValue;
|
|
232
|
+
},
|
|
233
|
+
2
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
function logProviderPayload(provider, label, payload, enabled) {
|
|
237
|
+
if (!enabled) {
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
if (label.toLowerCase().includes("stream ")) {
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
try {
|
|
244
|
+
console.log(
|
|
245
|
+
`[llm-sdk:${provider}] ${label}
|
|
246
|
+
${stringifyForDebug(payload)}`
|
|
247
|
+
);
|
|
248
|
+
} catch (error) {
|
|
249
|
+
console.log(
|
|
250
|
+
`[llm-sdk:${provider}] ${label} (failed to stringify payload)`,
|
|
251
|
+
error
|
|
252
|
+
);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
function parameterToJsonSchema(param) {
|
|
256
|
+
const schema = {
|
|
257
|
+
type: param.type
|
|
258
|
+
};
|
|
259
|
+
if (param.description) {
|
|
260
|
+
schema.description = param.description;
|
|
261
|
+
}
|
|
262
|
+
if (param.enum) {
|
|
263
|
+
schema.enum = param.enum;
|
|
264
|
+
}
|
|
265
|
+
if (param.type === "array" && param.items) {
|
|
266
|
+
schema.items = parameterToJsonSchema(
|
|
267
|
+
param.items
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
if (param.type === "object" && param.properties) {
|
|
271
|
+
schema.properties = Object.fromEntries(
|
|
272
|
+
Object.entries(param.properties).map(([key, prop]) => [
|
|
273
|
+
key,
|
|
274
|
+
parameterToJsonSchema(
|
|
275
|
+
prop
|
|
276
|
+
)
|
|
277
|
+
])
|
|
278
|
+
);
|
|
279
|
+
schema.additionalProperties = false;
|
|
280
|
+
}
|
|
281
|
+
return schema;
|
|
282
|
+
}
|
|
283
|
+
function normalizeObjectJsonSchema(schema) {
|
|
284
|
+
if (!schema || typeof schema !== "object") {
|
|
285
|
+
return {
|
|
286
|
+
type: "object",
|
|
287
|
+
properties: {},
|
|
288
|
+
required: [],
|
|
289
|
+
additionalProperties: false
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
const normalized = { ...schema };
|
|
293
|
+
const type = normalized.type;
|
|
294
|
+
if (type === "object") {
|
|
295
|
+
const properties = normalized.properties && typeof normalized.properties === "object" && !Array.isArray(normalized.properties) ? normalized.properties : {};
|
|
296
|
+
normalized.properties = Object.fromEntries(
|
|
297
|
+
Object.entries(properties).map(([key, value]) => [
|
|
298
|
+
key,
|
|
299
|
+
normalizeObjectJsonSchema(value)
|
|
300
|
+
])
|
|
301
|
+
);
|
|
302
|
+
const propertyKeys = Object.keys(properties);
|
|
303
|
+
const required = Array.isArray(normalized.required) ? normalized.required.filter(
|
|
304
|
+
(value) => typeof value === "string"
|
|
305
|
+
) : [];
|
|
306
|
+
normalized.required = Array.from(/* @__PURE__ */ new Set([...required, ...propertyKeys]));
|
|
307
|
+
if (normalized.additionalProperties === void 0) {
|
|
308
|
+
normalized.additionalProperties = false;
|
|
309
|
+
}
|
|
310
|
+
} else if (type === "array" && normalized.items && typeof normalized.items === "object") {
|
|
311
|
+
normalized.items = normalizeObjectJsonSchema(
|
|
312
|
+
normalized.items
|
|
313
|
+
);
|
|
314
|
+
}
|
|
315
|
+
return normalized;
|
|
316
|
+
}
|
|
317
|
+
function formatTools(actions) {
|
|
318
|
+
return actions.map((action) => ({
|
|
319
|
+
type: "function",
|
|
320
|
+
function: {
|
|
321
|
+
name: action.name,
|
|
322
|
+
description: action.description,
|
|
323
|
+
parameters: {
|
|
324
|
+
type: "object",
|
|
325
|
+
properties: action.parameters ? Object.fromEntries(
|
|
326
|
+
Object.entries(action.parameters).map(([key, param]) => [
|
|
327
|
+
key,
|
|
328
|
+
parameterToJsonSchema(param)
|
|
329
|
+
])
|
|
330
|
+
) : {},
|
|
331
|
+
required: action.parameters ? Object.entries(action.parameters).filter(([, param]) => param.required).map(([key]) => key) : [],
|
|
332
|
+
additionalProperties: false
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}));
|
|
336
|
+
}
|
|
337
|
+
function hasImageAttachments(message) {
|
|
338
|
+
const attachments = message.metadata?.attachments;
|
|
339
|
+
return attachments?.some((a) => a.type === "image") ?? false;
|
|
340
|
+
}
|
|
341
|
+
function attachmentToOpenAIImage(attachment) {
|
|
342
|
+
if (attachment.type !== "image") return null;
|
|
343
|
+
let imageUrl;
|
|
344
|
+
if (attachment.url) {
|
|
345
|
+
imageUrl = attachment.url;
|
|
346
|
+
} else if (attachment.data) {
|
|
347
|
+
imageUrl = attachment.data.startsWith("data:") ? attachment.data : `data:${attachment.mimeType || "image/png"};base64,${attachment.data}`;
|
|
348
|
+
} else {
|
|
349
|
+
return null;
|
|
350
|
+
}
|
|
351
|
+
return {
|
|
352
|
+
type: "image_url",
|
|
353
|
+
image_url: {
|
|
354
|
+
url: imageUrl,
|
|
355
|
+
detail: "auto"
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
function messageToOpenAIContent(message) {
|
|
360
|
+
const attachments = message.metadata?.attachments;
|
|
361
|
+
const content = message.content ?? "";
|
|
362
|
+
if (!hasImageAttachments(message)) {
|
|
363
|
+
return content;
|
|
364
|
+
}
|
|
365
|
+
const blocks = [];
|
|
366
|
+
if (content) {
|
|
367
|
+
blocks.push({ type: "text", text: content });
|
|
368
|
+
}
|
|
369
|
+
if (attachments) {
|
|
370
|
+
for (const attachment of attachments) {
|
|
371
|
+
const imageBlock = attachmentToOpenAIImage(attachment);
|
|
372
|
+
if (imageBlock) {
|
|
373
|
+
blocks.push(imageBlock);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
return blocks;
|
|
378
|
+
}
|
|
379
|
+
function formatMessagesForOpenAI(messages, systemPrompt) {
|
|
380
|
+
const formatted = [];
|
|
381
|
+
if (systemPrompt) {
|
|
382
|
+
formatted.push({ role: "system", content: systemPrompt });
|
|
383
|
+
}
|
|
384
|
+
for (const msg of messages) {
|
|
385
|
+
if (msg.role === "system") {
|
|
386
|
+
formatted.push({ role: "system", content: msg.content ?? "" });
|
|
387
|
+
} else if (msg.role === "user") {
|
|
388
|
+
formatted.push({
|
|
389
|
+
role: "user",
|
|
390
|
+
content: messageToOpenAIContent(msg)
|
|
391
|
+
});
|
|
392
|
+
} else if (msg.role === "assistant") {
|
|
393
|
+
const hasToolCalls = msg.tool_calls && msg.tool_calls.length > 0;
|
|
394
|
+
const assistantMsg = {
|
|
395
|
+
role: "assistant",
|
|
396
|
+
// Gemini/xAI (OpenAI-compatible) reject content: "" on assistant messages with tool_calls
|
|
397
|
+
content: hasToolCalls ? msg.content || null : msg.content
|
|
398
|
+
};
|
|
399
|
+
if (hasToolCalls) {
|
|
400
|
+
assistantMsg.tool_calls = msg.tool_calls;
|
|
401
|
+
}
|
|
402
|
+
formatted.push(assistantMsg);
|
|
403
|
+
} else if (msg.role === "tool" && msg.tool_call_id) {
|
|
404
|
+
formatted.push({
|
|
405
|
+
role: "tool",
|
|
406
|
+
content: msg.content ?? "",
|
|
407
|
+
tool_call_id: msg.tool_call_id
|
|
408
|
+
});
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
return formatted;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
// src/adapters/openai.ts
|
|
415
|
+
var OpenAIAdapter = class _OpenAIAdapter {
|
|
416
|
+
constructor(config) {
|
|
417
|
+
this.config = config;
|
|
418
|
+
this.model = config.model || "gpt-4o";
|
|
419
|
+
this.provider = _OpenAIAdapter.resolveProviderName(config.baseUrl);
|
|
420
|
+
}
|
|
421
|
+
static resolveProviderName(baseUrl) {
|
|
422
|
+
if (!baseUrl) return "openai";
|
|
423
|
+
if (baseUrl.includes("generativelanguage.googleapis.com")) return "google";
|
|
424
|
+
if (baseUrl.includes("x.ai")) return "xai";
|
|
425
|
+
if (baseUrl.includes("azure")) return "azure";
|
|
426
|
+
return "openai";
|
|
427
|
+
}
|
|
428
|
+
async getClient() {
|
|
429
|
+
if (!this.client) {
|
|
430
|
+
const { default: OpenAI } = await import('openai');
|
|
431
|
+
this.client = new OpenAI({
|
|
432
|
+
apiKey: this.config.apiKey,
|
|
433
|
+
baseURL: this.config.baseUrl
|
|
434
|
+
});
|
|
435
|
+
}
|
|
436
|
+
return this.client;
|
|
437
|
+
}
|
|
438
|
+
shouldUseResponsesApi(request) {
|
|
439
|
+
return request.providerToolOptions?.openai?.nativeToolSearch?.enabled === true && request.providerToolOptions.openai.nativeToolSearch.useResponsesApi !== false && Array.isArray(request.toolDefinitions) && request.toolDefinitions.length > 0;
|
|
440
|
+
}
|
|
441
|
+
buildResponsesInput(request) {
|
|
442
|
+
const sourceMessages = request.rawMessages && request.rawMessages.length > 0 ? request.rawMessages : formatMessagesForOpenAI(request.messages, void 0);
|
|
443
|
+
const input = [];
|
|
444
|
+
for (const message of sourceMessages) {
|
|
445
|
+
if (message.role === "system") {
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
if (message.role === "assistant") {
|
|
449
|
+
const content = typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content : message.content ? JSON.stringify(message.content) : "";
|
|
450
|
+
if (content) {
|
|
451
|
+
input.push({
|
|
452
|
+
type: "message",
|
|
453
|
+
role: "assistant",
|
|
454
|
+
content
|
|
455
|
+
});
|
|
456
|
+
}
|
|
457
|
+
const toolCalls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
|
458
|
+
for (const toolCall of toolCalls) {
|
|
459
|
+
input.push({
|
|
460
|
+
type: "function_call",
|
|
461
|
+
call_id: toolCall.id,
|
|
462
|
+
name: toolCall.function?.name,
|
|
463
|
+
arguments: toolCall.function?.arguments ?? "{}"
|
|
464
|
+
});
|
|
465
|
+
}
|
|
466
|
+
continue;
|
|
467
|
+
}
|
|
468
|
+
if (message.role === "tool") {
|
|
469
|
+
input.push({
|
|
470
|
+
type: "function_call_output",
|
|
471
|
+
call_id: message.tool_call_id,
|
|
472
|
+
output: typeof message.content === "string" ? message.content : JSON.stringify(message.content ?? null)
|
|
473
|
+
});
|
|
474
|
+
continue;
|
|
475
|
+
}
|
|
476
|
+
input.push({
|
|
477
|
+
type: "message",
|
|
478
|
+
role: message.role === "developer" ? "developer" : "user",
|
|
479
|
+
content: typeof message.content === "string" ? message.content : Array.isArray(message.content) ? message.content : JSON.stringify(message.content ?? "")
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
return input;
|
|
483
|
+
}
|
|
484
|
+
buildResponsesTools(tools) {
|
|
485
|
+
const nativeTools = tools.filter((tool) => tool.available !== false).map((tool) => ({
|
|
486
|
+
type: "function",
|
|
487
|
+
name: tool.name,
|
|
488
|
+
description: tool.description,
|
|
489
|
+
parameters: normalizeObjectJsonSchema(
|
|
490
|
+
tool.inputSchema ?? {
|
|
491
|
+
type: "object",
|
|
492
|
+
properties: {},
|
|
493
|
+
required: []
|
|
494
|
+
}
|
|
495
|
+
),
|
|
496
|
+
strict: true,
|
|
497
|
+
defer_loading: tool.deferLoading === true
|
|
498
|
+
}));
|
|
499
|
+
return [{ type: "tool_search" }, ...nativeTools];
|
|
500
|
+
}
|
|
501
|
+
parseResponsesResult(response) {
|
|
502
|
+
const content = typeof response?.output_text === "string" ? response.output_text : "";
|
|
503
|
+
const toolCalls = Array.isArray(response?.output) ? response.output.filter((item) => item?.type === "function_call").map((item) => ({
|
|
504
|
+
id: item.call_id ?? item.id ?? generateToolCallId(),
|
|
505
|
+
name: item.name,
|
|
506
|
+
args: (() => {
|
|
507
|
+
try {
|
|
508
|
+
return JSON.parse(item.arguments ?? "{}");
|
|
509
|
+
} catch {
|
|
510
|
+
return {};
|
|
511
|
+
}
|
|
512
|
+
})()
|
|
513
|
+
})) : [];
|
|
514
|
+
return {
|
|
515
|
+
content,
|
|
516
|
+
toolCalls,
|
|
517
|
+
usage: response?.usage ? {
|
|
518
|
+
promptTokens: response.usage.input_tokens ?? 0,
|
|
519
|
+
completionTokens: response.usage.output_tokens ?? 0,
|
|
520
|
+
totalTokens: response.usage.total_tokens ?? (response.usage.input_tokens ?? 0) + (response.usage.output_tokens ?? 0)
|
|
521
|
+
} : void 0,
|
|
522
|
+
rawResponse: response
|
|
523
|
+
};
|
|
524
|
+
}
|
|
525
|
+
async completeWithResponses(request) {
|
|
526
|
+
const client = await this.getClient();
|
|
527
|
+
const openaiToolOptions = request.providerToolOptions?.openai;
|
|
528
|
+
const payload = {
|
|
529
|
+
model: request.config?.model || this.model,
|
|
530
|
+
instructions: request.systemPrompt,
|
|
531
|
+
input: this.buildResponsesInput(request),
|
|
532
|
+
tools: this.buildResponsesTools(request.toolDefinitions ?? []),
|
|
533
|
+
tool_choice: openaiToolOptions?.toolChoice === "required" ? "required" : openaiToolOptions?.toolChoice === "auto" ? "auto" : void 0,
|
|
534
|
+
parallel_tool_calls: openaiToolOptions?.parallelToolCalls,
|
|
535
|
+
temperature: request.config?.temperature ?? this.config.temperature,
|
|
536
|
+
max_output_tokens: request.config?.maxTokens ?? this.config.maxTokens,
|
|
537
|
+
stream: false
|
|
538
|
+
};
|
|
539
|
+
logProviderPayload("openai", "request payload", payload, request.debug);
|
|
540
|
+
const response = await client.responses.create(payload);
|
|
541
|
+
logProviderPayload("openai", "response payload", response, request.debug);
|
|
542
|
+
return this.parseResponsesResult(response);
|
|
543
|
+
}
|
|
544
|
+
async *stream(request) {
|
|
545
|
+
if (this.shouldUseResponsesApi(request)) {
|
|
546
|
+
const messageId2 = generateMessageId();
|
|
547
|
+
yield { type: "message:start", id: messageId2 };
|
|
548
|
+
try {
|
|
549
|
+
const result = await this.completeWithResponses(request);
|
|
550
|
+
if (result.content) {
|
|
551
|
+
yield { type: "message:delta", content: result.content };
|
|
552
|
+
}
|
|
553
|
+
for (const toolCall of result.toolCalls) {
|
|
554
|
+
yield {
|
|
555
|
+
type: "action:start",
|
|
556
|
+
id: toolCall.id,
|
|
557
|
+
name: toolCall.name
|
|
558
|
+
};
|
|
559
|
+
yield {
|
|
560
|
+
type: "action:args",
|
|
561
|
+
id: toolCall.id,
|
|
562
|
+
args: JSON.stringify(toolCall.args)
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
yield { type: "message:end" };
|
|
566
|
+
yield {
|
|
567
|
+
type: "done",
|
|
568
|
+
usage: result.usage ? {
|
|
569
|
+
prompt_tokens: result.usage.promptTokens,
|
|
570
|
+
completion_tokens: result.usage.completionTokens,
|
|
571
|
+
total_tokens: result.usage.totalTokens
|
|
572
|
+
} : void 0
|
|
573
|
+
};
|
|
574
|
+
return;
|
|
575
|
+
} catch (error) {
|
|
576
|
+
yield {
|
|
577
|
+
type: "error",
|
|
578
|
+
message: error instanceof Error ? error.message : "Unknown error",
|
|
579
|
+
code: "OPENAI_RESPONSES_ERROR"
|
|
580
|
+
};
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
const client = await this.getClient();
|
|
585
|
+
let messages;
|
|
586
|
+
if (request.rawMessages && request.rawMessages.length > 0) {
|
|
587
|
+
const processedMessages = request.rawMessages.map((msg) => {
|
|
588
|
+
if (msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0 && msg.content === "") {
|
|
589
|
+
return { ...msg, content: null };
|
|
590
|
+
}
|
|
591
|
+
const hasAttachments = msg.attachments && Array.isArray(msg.attachments) && msg.attachments.length > 0;
|
|
592
|
+
if (hasAttachments) {
|
|
593
|
+
const content = [];
|
|
594
|
+
if (msg.content) {
|
|
595
|
+
content.push({ type: "text", text: msg.content });
|
|
596
|
+
}
|
|
597
|
+
for (const attachment of msg.attachments) {
|
|
598
|
+
if (attachment.type === "image") {
|
|
599
|
+
let imageUrl;
|
|
600
|
+
if (attachment.url) {
|
|
601
|
+
imageUrl = attachment.url;
|
|
602
|
+
} else if (attachment.data) {
|
|
603
|
+
imageUrl = attachment.data.startsWith("data:") ? attachment.data : `data:${attachment.mimeType || "image/png"};base64,${attachment.data}`;
|
|
604
|
+
} else {
|
|
605
|
+
continue;
|
|
606
|
+
}
|
|
607
|
+
content.push({
|
|
608
|
+
type: "image_url",
|
|
609
|
+
image_url: { url: imageUrl, detail: "auto" }
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
return { ...msg, content, attachments: void 0 };
|
|
614
|
+
}
|
|
615
|
+
return msg;
|
|
616
|
+
});
|
|
617
|
+
if (request.systemPrompt) {
|
|
618
|
+
const hasSystem = processedMessages.some((m) => m.role === "system");
|
|
619
|
+
if (!hasSystem) {
|
|
620
|
+
messages = [
|
|
621
|
+
{ role: "system", content: request.systemPrompt },
|
|
622
|
+
...processedMessages
|
|
623
|
+
];
|
|
624
|
+
} else {
|
|
625
|
+
messages = processedMessages;
|
|
626
|
+
}
|
|
627
|
+
} else {
|
|
628
|
+
messages = processedMessages;
|
|
629
|
+
}
|
|
630
|
+
} else {
|
|
631
|
+
messages = formatMessagesForOpenAI(
|
|
632
|
+
request.messages,
|
|
633
|
+
request.systemPrompt
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
const tools = request.actions?.length ? formatTools(request.actions) : [];
|
|
637
|
+
const webSearchConfig = request.webSearch ?? this.config.webSearch;
|
|
638
|
+
if (webSearchConfig) {
|
|
639
|
+
const webSearchTool = {
|
|
640
|
+
type: "web_search_preview"
|
|
641
|
+
};
|
|
642
|
+
const wsConfig = typeof webSearchConfig === "object" ? webSearchConfig : {};
|
|
643
|
+
if (wsConfig.userLocation) {
|
|
644
|
+
webSearchTool.search_context_size = "medium";
|
|
645
|
+
}
|
|
646
|
+
tools.push(webSearchTool);
|
|
647
|
+
}
|
|
648
|
+
const messageId = generateMessageId();
|
|
649
|
+
yield { type: "message:start", id: messageId };
|
|
650
|
+
try {
|
|
651
|
+
const openaiToolOptions = request.providerToolOptions?.openai;
|
|
652
|
+
const toolChoice = openaiToolOptions?.toolChoice && typeof openaiToolOptions.toolChoice === "object" ? {
|
|
653
|
+
type: "function",
|
|
654
|
+
function: {
|
|
655
|
+
name: openaiToolOptions.toolChoice.name
|
|
656
|
+
}
|
|
657
|
+
} : openaiToolOptions?.toolChoice;
|
|
658
|
+
const payload = {
|
|
659
|
+
model: request.config?.model || this.model,
|
|
660
|
+
messages,
|
|
661
|
+
tools: tools.length > 0 ? tools : void 0,
|
|
662
|
+
tool_choice: tools.length > 0 ? toolChoice : void 0,
|
|
663
|
+
parallel_tool_calls: tools.length > 0 ? openaiToolOptions?.parallelToolCalls : void 0,
|
|
664
|
+
temperature: request.config?.temperature ?? this.config.temperature,
|
|
665
|
+
max_tokens: request.config?.maxTokens ?? this.config.maxTokens,
|
|
666
|
+
stream: true,
|
|
667
|
+
stream_options: { include_usage: true }
|
|
668
|
+
};
|
|
669
|
+
logProviderPayload("openai", "request payload", payload, request.debug);
|
|
670
|
+
const stream = await client.chat.completions.create(payload);
|
|
671
|
+
let currentToolCall = null;
|
|
672
|
+
const collectedCitations = [];
|
|
673
|
+
let citationIndex = 0;
|
|
674
|
+
let usage;
|
|
675
|
+
for await (const chunk of stream) {
|
|
676
|
+
logProviderPayload("openai", "stream chunk", chunk, request.debug);
|
|
677
|
+
if (request.signal?.aborted) {
|
|
678
|
+
break;
|
|
679
|
+
}
|
|
680
|
+
const delta = chunk.choices[0]?.delta;
|
|
681
|
+
const choice = chunk.choices[0];
|
|
682
|
+
if (delta?.content) {
|
|
683
|
+
yield { type: "message:delta", content: delta.content };
|
|
684
|
+
}
|
|
685
|
+
const annotations = delta?.annotations;
|
|
686
|
+
if (annotations && annotations.length > 0) {
|
|
687
|
+
for (const annotation of annotations) {
|
|
688
|
+
if (annotation.type === "url_citation" && annotation.url_citation?.url) {
|
|
689
|
+
citationIndex++;
|
|
690
|
+
const url = annotation.url_citation.url;
|
|
691
|
+
const domain = extractDomain(url);
|
|
692
|
+
collectedCitations.push({
|
|
693
|
+
index: citationIndex,
|
|
694
|
+
url,
|
|
695
|
+
title: annotation.url_citation.title || domain,
|
|
696
|
+
domain,
|
|
697
|
+
favicon: domain ? `https://www.google.com/s2/favicons?domain=${domain}&sz=32` : void 0
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
if (delta?.tool_calls) {
|
|
703
|
+
for (const toolCall of delta.tool_calls) {
|
|
704
|
+
if (toolCall.id) {
|
|
705
|
+
if (currentToolCall) {
|
|
706
|
+
yield {
|
|
707
|
+
type: "action:args",
|
|
708
|
+
id: currentToolCall.id,
|
|
709
|
+
args: currentToolCall.arguments
|
|
710
|
+
};
|
|
711
|
+
yield {
|
|
712
|
+
type: "action:end",
|
|
713
|
+
id: currentToolCall.id,
|
|
714
|
+
name: currentToolCall.name
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
const tcExtraContent = toolCall.extra_content;
|
|
718
|
+
currentToolCall = {
|
|
719
|
+
id: toolCall.id,
|
|
720
|
+
name: toolCall.function?.name || "",
|
|
721
|
+
arguments: toolCall.function?.arguments || "",
|
|
722
|
+
...tcExtraContent ? { extra_content: tcExtraContent } : {}
|
|
723
|
+
};
|
|
724
|
+
yield {
|
|
725
|
+
type: "action:start",
|
|
726
|
+
id: currentToolCall.id,
|
|
727
|
+
name: currentToolCall.name,
|
|
728
|
+
...currentToolCall.extra_content ? { extra_content: currentToolCall.extra_content } : {}
|
|
729
|
+
};
|
|
730
|
+
} else if (currentToolCall && toolCall.function?.arguments) {
|
|
731
|
+
currentToolCall.arguments += toolCall.function.arguments;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
if (chunk.usage) {
|
|
736
|
+
usage = {
|
|
737
|
+
prompt_tokens: chunk.usage.prompt_tokens,
|
|
738
|
+
completion_tokens: chunk.usage.completion_tokens,
|
|
739
|
+
total_tokens: chunk.usage.total_tokens
|
|
740
|
+
};
|
|
741
|
+
}
|
|
742
|
+
if (choice?.finish_reason) {
|
|
743
|
+
if (currentToolCall) {
|
|
744
|
+
yield {
|
|
745
|
+
type: "action:args",
|
|
746
|
+
id: currentToolCall.id,
|
|
747
|
+
args: currentToolCall.arguments
|
|
748
|
+
};
|
|
749
|
+
yield {
|
|
750
|
+
type: "action:end",
|
|
751
|
+
id: currentToolCall.id,
|
|
752
|
+
name: currentToolCall.name
|
|
753
|
+
};
|
|
754
|
+
currentToolCall = null;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
if (collectedCitations.length > 0) {
|
|
759
|
+
const uniqueCitations = deduplicateCitations(collectedCitations);
|
|
760
|
+
yield { type: "citation", citations: uniqueCitations };
|
|
761
|
+
}
|
|
762
|
+
yield { type: "message:end" };
|
|
763
|
+
yield { type: "done", usage };
|
|
764
|
+
} catch (error) {
|
|
765
|
+
yield {
|
|
766
|
+
type: "error",
|
|
767
|
+
message: error instanceof Error ? error.message : "Unknown error",
|
|
768
|
+
code: `${this.provider.toUpperCase()}_ERROR`
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
async complete(request) {
|
|
773
|
+
if (this.shouldUseResponsesApi(request)) {
|
|
774
|
+
return this.completeWithResponses(request);
|
|
775
|
+
}
|
|
776
|
+
const client = await this.getClient();
|
|
777
|
+
let messages;
|
|
778
|
+
if (request.rawMessages && request.rawMessages.length > 0) {
|
|
779
|
+
const sanitized = request.rawMessages.map((msg) => {
|
|
780
|
+
if (msg.role === "assistant" && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0 && msg.content === "") {
|
|
781
|
+
return { ...msg, content: null };
|
|
782
|
+
}
|
|
783
|
+
return msg;
|
|
784
|
+
});
|
|
785
|
+
if (request.systemPrompt && !sanitized.some((message2) => message2.role === "system")) {
|
|
786
|
+
messages = [
|
|
787
|
+
{ role: "system", content: request.systemPrompt },
|
|
788
|
+
...sanitized
|
|
789
|
+
];
|
|
790
|
+
} else {
|
|
791
|
+
messages = sanitized;
|
|
792
|
+
}
|
|
793
|
+
} else {
|
|
794
|
+
messages = formatMessagesForOpenAI(
|
|
795
|
+
request.messages,
|
|
796
|
+
request.systemPrompt
|
|
797
|
+
);
|
|
798
|
+
}
|
|
799
|
+
const tools = request.actions?.length ? formatTools(request.actions) : [];
|
|
800
|
+
const openaiToolOptions = request.providerToolOptions?.openai;
|
|
801
|
+
const toolChoice = openaiToolOptions?.toolChoice && typeof openaiToolOptions.toolChoice === "object" ? {
|
|
802
|
+
type: "function",
|
|
803
|
+
function: {
|
|
804
|
+
name: openaiToolOptions.toolChoice.name
|
|
805
|
+
}
|
|
806
|
+
} : openaiToolOptions?.toolChoice;
|
|
807
|
+
const payload = {
|
|
808
|
+
model: request.config?.model || this.model,
|
|
809
|
+
messages,
|
|
810
|
+
tools: tools.length > 0 ? tools : void 0,
|
|
811
|
+
tool_choice: tools.length > 0 ? toolChoice : void 0,
|
|
812
|
+
parallel_tool_calls: tools.length > 0 ? openaiToolOptions?.parallelToolCalls : void 0,
|
|
813
|
+
temperature: request.config?.temperature ?? this.config.temperature,
|
|
814
|
+
max_tokens: request.config?.maxTokens ?? this.config.maxTokens,
|
|
815
|
+
stream: false
|
|
816
|
+
};
|
|
817
|
+
logProviderPayload("openai", "request payload", payload, request.debug);
|
|
818
|
+
const response = await client.chat.completions.create(payload);
|
|
819
|
+
logProviderPayload("openai", "response payload", response, request.debug);
|
|
820
|
+
const choice = response.choices?.[0];
|
|
821
|
+
const message = choice?.message;
|
|
822
|
+
return {
|
|
823
|
+
content: message?.content ?? "",
|
|
824
|
+
toolCalls: message?.tool_calls?.map((toolCall) => ({
|
|
825
|
+
id: toolCall.id ?? generateToolCallId(),
|
|
826
|
+
name: toolCall.function?.name ?? "",
|
|
827
|
+
args: (() => {
|
|
828
|
+
try {
|
|
829
|
+
return JSON.parse(toolCall.function?.arguments ?? "{}");
|
|
830
|
+
} catch {
|
|
831
|
+
return {};
|
|
832
|
+
}
|
|
833
|
+
})(),
|
|
834
|
+
...toolCall.extra_content ? { extra_content: toolCall.extra_content } : {}
|
|
835
|
+
})) ?? [],
|
|
836
|
+
usage: response.usage ? {
|
|
837
|
+
promptTokens: response.usage.prompt_tokens,
|
|
838
|
+
completionTokens: response.usage.completion_tokens,
|
|
839
|
+
totalTokens: response.usage.total_tokens
|
|
840
|
+
} : void 0,
|
|
841
|
+
rawResponse: response
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
};
|
|
845
|
+
function extractDomain(url) {
|
|
846
|
+
try {
|
|
847
|
+
const parsed = new URL(url);
|
|
848
|
+
return parsed.hostname;
|
|
849
|
+
} catch {
|
|
850
|
+
return "";
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
function deduplicateCitations(citations) {
|
|
854
|
+
const seen = /* @__PURE__ */ new Map();
|
|
855
|
+
let index = 0;
|
|
856
|
+
for (const citation of citations) {
|
|
857
|
+
if (!seen.has(citation.url)) {
|
|
858
|
+
index++;
|
|
859
|
+
seen.set(citation.url, { ...citation, index });
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
return Array.from(seen.values());
|
|
863
|
+
}
|
|
864
|
+
function createOpenAIAdapter(config) {
|
|
865
|
+
return new OpenAIAdapter(config);
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// src/providers/types.ts
|
|
869
|
+
function createCallableProvider(providerFn, properties) {
|
|
870
|
+
Object.defineProperty(providerFn, "name", {
|
|
871
|
+
value: properties.name,
|
|
872
|
+
writable: false,
|
|
873
|
+
configurable: true
|
|
874
|
+
});
|
|
875
|
+
Object.assign(providerFn, {
|
|
876
|
+
supportedModels: properties.supportedModels,
|
|
877
|
+
languageModel: providerFn,
|
|
878
|
+
getCapabilities: properties.getCapabilities,
|
|
879
|
+
embeddingModel: properties.embeddingModel
|
|
880
|
+
});
|
|
881
|
+
return providerFn;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
// src/providers/togetherai/index.ts
|
|
885
|
+
var DEFAULT_CAPABILITIES = {
|
|
886
|
+
vision: true,
|
|
887
|
+
tools: true,
|
|
888
|
+
jsonMode: true,
|
|
889
|
+
maxTokens: 131072
|
|
890
|
+
};
|
|
891
|
+
function createTogetherAI(config = {}) {
|
|
892
|
+
const apiKey = config.apiKey ?? process.env.TOGETHER_API_KEY ?? "";
|
|
893
|
+
const baseUrl = config.baseUrl ?? "https://api.together.xyz/v1";
|
|
894
|
+
const providerFn = (modelId) => {
|
|
895
|
+
return createOpenAIAdapter({
|
|
896
|
+
apiKey,
|
|
897
|
+
model: modelId,
|
|
898
|
+
baseUrl
|
|
899
|
+
});
|
|
900
|
+
};
|
|
901
|
+
const getCapabilities = (_modelId) => {
|
|
902
|
+
return {
|
|
903
|
+
supportsVision: DEFAULT_CAPABILITIES.vision,
|
|
904
|
+
supportsTools: DEFAULT_CAPABILITIES.tools,
|
|
905
|
+
supportsThinking: false,
|
|
906
|
+
supportsStreaming: true,
|
|
907
|
+
supportsPDF: false,
|
|
908
|
+
supportsAudio: false,
|
|
909
|
+
supportsVideo: false,
|
|
910
|
+
maxTokens: DEFAULT_CAPABILITIES.maxTokens,
|
|
911
|
+
supportedImageTypes: ["image/png", "image/jpeg", "image/gif", "image/webp"] ,
|
|
912
|
+
supportsJsonMode: DEFAULT_CAPABILITIES.jsonMode,
|
|
913
|
+
supportsSystemMessages: true
|
|
914
|
+
};
|
|
915
|
+
};
|
|
916
|
+
return createCallableProvider(providerFn, {
|
|
917
|
+
name: "togetherai",
|
|
918
|
+
supportedModels: [],
|
|
919
|
+
getCapabilities
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
var createTogetherAIProvider = createTogetherAI;
|
|
923
|
+
|
|
924
|
+
export { createTogetherAI, createTogetherAIProvider, togetherai };
|
|
201
925
|
//# sourceMappingURL=index.mjs.map
|
|
202
926
|
//# sourceMappingURL=index.mjs.map
|