@ai-sdk/perplexity 2.1.0-beta.9 → 2.1.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/dist/index.js CHANGED
@@ -18,72 +18,182 @@ var __copyProps = (to, from, except, desc) => {
18
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
19
 
20
20
  // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
23
  VERSION: () => VERSION,
24
24
  createPerplexity: () => createPerplexity,
25
25
  perplexity: () => perplexity
26
26
  });
27
- module.exports = __toCommonJS(src_exports);
27
+ module.exports = __toCommonJS(index_exports);
28
28
 
29
29
  // src/perplexity-provider.ts
30
- var import_provider2 = require("@ai-sdk/provider");
30
+ var import_provider3 = require("@ai-sdk/provider");
31
31
  var import_provider_utils3 = require("@ai-sdk/provider-utils");
32
32
 
33
33
  // src/perplexity-language-model.ts
34
+ var import_provider2 = require("@ai-sdk/provider");
34
35
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
35
- var import_v4 = require("zod/v4");
36
36
 
37
- // src/convert-to-perplexity-messages.ts
37
+ // src/convert-perplexity-usage.ts
38
+ function convertPerplexityUsage(usage) {
39
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
40
+ if (usage == null) {
41
+ return {
42
+ inputTokens: void 0,
43
+ outputTokens: void 0,
44
+ totalTokens: void 0
45
+ };
46
+ }
47
+ const inputTokens = (_a = usage.input_tokens) != null ? _a : void 0;
48
+ const outputTokens = (_b = usage.output_tokens) != null ? _b : void 0;
49
+ return {
50
+ inputTokens,
51
+ outputTokens,
52
+ totalTokens: (_c = usage.total_tokens) != null ? _c : inputTokens != null && outputTokens != null ? inputTokens + outputTokens : void 0,
53
+ reasoningTokens: (_e = (_d = usage.output_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : void 0,
54
+ cachedInputTokens: (_i = (_h = (_f = usage.input_tokens_details) == null ? void 0 : _f.cache_read_input_tokens) != null ? _h : (_g = usage.input_tokens_details) == null ? void 0 : _g.cached_tokens) != null ? _i : void 0
55
+ };
56
+ }
57
+
58
+ // src/convert-to-perplexity-input.ts
38
59
  var import_provider = require("@ai-sdk/provider");
39
60
  var import_provider_utils = require("@ai-sdk/provider-utils");
40
- function convertToPerplexityMessages(prompt) {
41
- const messages = [];
61
+ function serializeToolOutput(output) {
62
+ switch (output.type) {
63
+ case "text":
64
+ case "error-text":
65
+ return output.value;
66
+ case "json":
67
+ case "error-json":
68
+ return JSON.stringify(output.value);
69
+ case "content": {
70
+ if (output.value.some((part) => part.type !== "text")) {
71
+ throw new import_provider.UnsupportedFunctionalityError({
72
+ functionality: "file and custom tool result content"
73
+ });
74
+ }
75
+ return output.value.map((part) => part.type === "text" ? part.text : "").join("");
76
+ }
77
+ default: {
78
+ const _exhaustiveCheck = output;
79
+ throw new Error(`Unsupported tool output: ${_exhaustiveCheck}`);
80
+ }
81
+ }
82
+ }
83
+ function getTopLevelMediaType(mediaType) {
84
+ const slashIndex = mediaType.indexOf("/");
85
+ return slashIndex === -1 ? mediaType : mediaType.substring(0, slashIndex);
86
+ }
87
+ function getThoughtSignature(providerOptions) {
88
+ var _a;
89
+ const thoughtSignature = (_a = providerOptions == null ? void 0 : providerOptions.perplexity) == null ? void 0 : _a.thoughtSignature;
90
+ return typeof thoughtSignature === "string" ? thoughtSignature : void 0;
91
+ }
92
+ function convertToPerplexityInput(prompt) {
93
+ var _a;
94
+ const input = [];
95
+ const warnings = [];
42
96
  for (const { role, content } of prompt) {
43
97
  switch (role) {
44
98
  case "system": {
45
- messages.push({ role: "system", content });
99
+ input.push({ type: "message", role: "system", content });
46
100
  break;
47
101
  }
48
- case "user":
49
- case "assistant": {
50
- const hasImage = content.some(
51
- (part) => part.type === "file" && part.mediaType.startsWith("image/")
52
- );
53
- const messageContent = content.map((part) => {
54
- var _a;
55
- switch (part.type) {
56
- case "text": {
57
- return {
58
- type: "text",
59
- text: part.text
60
- };
61
- }
62
- case "file": {
63
- return part.data instanceof URL ? {
64
- type: "image_url",
65
- image_url: {
66
- url: part.data.toString()
102
+ case "user": {
103
+ const convertedContent = content.map(
104
+ (part) => {
105
+ switch (part.type) {
106
+ case "text":
107
+ return { type: "input_text", text: part.text };
108
+ case "file": {
109
+ if (getTopLevelMediaType(part.mediaType) !== "image") {
110
+ throw new import_provider.UnsupportedFunctionalityError({
111
+ functionality: `file part media type ${part.mediaType}`
112
+ });
67
113
  }
68
- } : {
69
- type: "image_url",
70
- image_url: {
71
- url: `data:${(_a = part.mediaType) != null ? _a : "image/jpeg"};base64,${typeof part.data === "string" ? part.data : (0, import_provider_utils.convertUint8ArrayToBase64)(part.data)}`
114
+ if (part.data instanceof URL) {
115
+ return {
116
+ type: "input_image",
117
+ image_url: part.data.toString()
118
+ };
72
119
  }
73
- };
120
+ const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
121
+ return {
122
+ type: "input_image",
123
+ image_url: `data:${mediaType};base64,${typeof part.data === "string" ? part.data : (0, import_provider_utils.convertUint8ArrayToBase64)(part.data)}`
124
+ };
125
+ }
74
126
  }
75
127
  }
76
- }).filter(Boolean);
77
- messages.push({
78
- role,
79
- content: hasImage ? messageContent : messageContent.filter((part) => part.type === "text").map((part) => part.text).join("")
128
+ );
129
+ const isTextOnly = convertedContent.every(
130
+ (part) => part.type === "input_text"
131
+ );
132
+ input.push({
133
+ type: "message",
134
+ role: "user",
135
+ content: isTextOnly ? convertedContent.map((part) => part.type === "input_text" ? part.text : "").join("") : convertedContent
80
136
  });
81
137
  break;
82
138
  }
139
+ case "assistant": {
140
+ const text = content.filter((part) => part.type === "text").map((part) => part.text).join("");
141
+ if (text.length > 0) {
142
+ input.push({ type: "message", role: "assistant", content: text });
143
+ }
144
+ for (const part of content) {
145
+ switch (part.type) {
146
+ case "text":
147
+ break;
148
+ case "tool-call":
149
+ input.push({
150
+ type: "function_call",
151
+ call_id: part.toolCallId,
152
+ name: part.toolName,
153
+ arguments: JSON.stringify((_a = part.input) != null ? _a : {}),
154
+ thought_signature: getThoughtSignature(part.providerOptions)
155
+ });
156
+ break;
157
+ case "tool-result":
158
+ input.push({
159
+ type: "function_call_output",
160
+ call_id: part.toolCallId,
161
+ name: part.toolName,
162
+ output: serializeToolOutput(part.output),
163
+ thought_signature: getThoughtSignature(part.providerOptions)
164
+ });
165
+ break;
166
+ case "reasoning":
167
+ warnings.push({
168
+ type: "other",
169
+ message: "reasoning content in prompt is not supported"
170
+ });
171
+ break;
172
+ case "file":
173
+ throw new import_provider.UnsupportedFunctionalityError({
174
+ functionality: `assistant ${part.type} parts`
175
+ });
176
+ default: {
177
+ const _exhaustiveCheck = part;
178
+ throw new Error(
179
+ `Unsupported assistant part: ${_exhaustiveCheck}`
180
+ );
181
+ }
182
+ }
183
+ }
184
+ break;
185
+ }
83
186
  case "tool": {
84
- throw new import_provider.UnsupportedFunctionalityError({
85
- functionality: "Tool messages"
86
- });
187
+ for (const part of content) {
188
+ input.push({
189
+ type: "function_call_output",
190
+ call_id: part.toolCallId,
191
+ name: part.toolName,
192
+ output: serializeToolOutput(part.output),
193
+ thought_signature: getThoughtSignature(part.providerOptions)
194
+ });
195
+ }
196
+ break;
87
197
  }
88
198
  default: {
89
199
  const _exhaustiveCheck = role;
@@ -91,32 +201,434 @@ function convertToPerplexityMessages(prompt) {
91
201
  }
92
202
  }
93
203
  }
94
- return messages;
204
+ return { input, warnings };
95
205
  }
96
206
 
97
207
  // src/map-perplexity-finish-reason.ts
98
- function mapPerplexityFinishReason(finishReason) {
99
- switch (finishReason) {
100
- case "stop":
101
- case "length":
102
- return finishReason;
208
+ function mapPerplexityFinishReason({
209
+ status,
210
+ incompleteReason,
211
+ hasFunctionCall
212
+ }) {
213
+ switch (incompleteReason) {
214
+ case "max_output_tokens":
215
+ return "length";
216
+ case "content_filter":
217
+ return "content-filter";
218
+ }
219
+ switch (status) {
220
+ case "completed":
221
+ return hasFunctionCall ? "tool-calls" : "stop";
222
+ case "requires_action":
223
+ return "tool-calls";
224
+ case "failed":
225
+ return "error";
226
+ case "cancelled":
227
+ case "queued":
228
+ case "in_progress":
103
229
  default:
104
- return "unknown";
230
+ return hasFunctionCall ? "tool-calls" : "other";
231
+ }
232
+ }
233
+
234
+ // src/perplexity-agent-api.ts
235
+ var import_v4 = require("zod/v4");
236
+ var perplexitySearchResultSchema = import_v4.z.looseObject({
237
+ id: import_v4.z.number().optional(),
238
+ title: import_v4.z.string(),
239
+ url: import_v4.z.string(),
240
+ snippet: import_v4.z.string().optional(),
241
+ date: import_v4.z.string().nullish(),
242
+ last_updated: import_v4.z.string().nullish(),
243
+ source: import_v4.z.string().optional()
244
+ });
245
+ var perplexityFetchedContentSchema = import_v4.z.looseObject({
246
+ title: import_v4.z.string(),
247
+ url: import_v4.z.string(),
248
+ snippet: import_v4.z.string().optional()
249
+ });
250
+ var perplexityContentPartSchema = import_v4.z.looseObject({
251
+ type: import_v4.z.string(),
252
+ text: import_v4.z.string().optional(),
253
+ annotations: import_v4.z.array(
254
+ import_v4.z.looseObject({
255
+ type: import_v4.z.string().optional(),
256
+ url: import_v4.z.string().optional(),
257
+ title: import_v4.z.string().optional()
258
+ })
259
+ ).nullish()
260
+ });
261
+ var handledOutputTypes = [
262
+ "message",
263
+ "search_results",
264
+ "fetch_url_results",
265
+ "function_call"
266
+ ];
267
+ var perplexityOutputItemSchema = import_v4.z.union([
268
+ import_v4.z.looseObject({
269
+ type: import_v4.z.literal("message"),
270
+ id: import_v4.z.string().nullish(),
271
+ content: import_v4.z.array(perplexityContentPartSchema).nullish()
272
+ }),
273
+ import_v4.z.looseObject({
274
+ type: import_v4.z.literal("search_results"),
275
+ results: import_v4.z.array(perplexitySearchResultSchema).nullish()
276
+ }),
277
+ import_v4.z.looseObject({
278
+ type: import_v4.z.literal("fetch_url_results"),
279
+ contents: import_v4.z.array(perplexityFetchedContentSchema).nullish()
280
+ }),
281
+ import_v4.z.looseObject({
282
+ type: import_v4.z.literal("function_call"),
283
+ id: import_v4.z.string().nullish(),
284
+ call_id: import_v4.z.string().nullish(),
285
+ name: import_v4.z.string().nullish(),
286
+ arguments: import_v4.z.string().nullish(),
287
+ thought_signature: import_v4.z.string().nullish()
288
+ }),
289
+ // Native tool traces remain available in raw responses and raw stream chunks.
290
+ // Their fields (e.g. finance_results.results) have different shapes. Do not
291
+ // validate them as search results, or let malformed handled items fall back.
292
+ import_v4.z.object({
293
+ type: import_v4.z.string().refine((type) => !handledOutputTypes.includes(type))
294
+ }).transform(() => ({ type: "unhandled" }))
295
+ ]);
296
+ var perplexityCostSchema = import_v4.z.looseObject({
297
+ currency: import_v4.z.string().optional(),
298
+ input_cost: import_v4.z.number().optional(),
299
+ output_cost: import_v4.z.number().optional(),
300
+ total_cost: import_v4.z.number().optional(),
301
+ cache_creation_cost: import_v4.z.number().nullish(),
302
+ cache_read_cost: import_v4.z.number().nullish(),
303
+ tool_calls_cost: import_v4.z.number().nullish()
304
+ });
305
+ var perplexityUsageSchema = import_v4.z.looseObject({
306
+ input_tokens: import_v4.z.number(),
307
+ output_tokens: import_v4.z.number(),
308
+ total_tokens: import_v4.z.number(),
309
+ input_tokens_details: import_v4.z.looseObject({
310
+ cached_tokens: import_v4.z.number().optional(),
311
+ cache_creation_input_tokens: import_v4.z.number().optional(),
312
+ cache_read_input_tokens: import_v4.z.number().optional()
313
+ }).nullish(),
314
+ output_tokens_details: import_v4.z.looseObject({
315
+ reasoning_tokens: import_v4.z.number().optional()
316
+ }).nullish(),
317
+ tool_calls_details: import_v4.z.record(
318
+ import_v4.z.string(),
319
+ import_v4.z.looseObject({
320
+ invocation: import_v4.z.number().optional()
321
+ })
322
+ ).nullish(),
323
+ cost: perplexityCostSchema.nullish()
324
+ });
325
+ var perplexityAgentResponseSchema = import_v4.z.looseObject({
326
+ id: import_v4.z.string(),
327
+ created_at: import_v4.z.number(),
328
+ model: import_v4.z.string(),
329
+ object: import_v4.z.literal("response"),
330
+ output: import_v4.z.array(perplexityOutputItemSchema),
331
+ status: import_v4.z.string(),
332
+ incomplete_details: import_v4.z.looseObject({
333
+ reason: import_v4.z.string()
334
+ }).nullish(),
335
+ error: import_v4.z.looseObject({
336
+ code: import_v4.z.string().optional(),
337
+ message: import_v4.z.string(),
338
+ type: import_v4.z.string().optional()
339
+ }).nullish(),
340
+ usage: perplexityUsageSchema.nullish()
341
+ });
342
+ var perplexityAgentChunkSchema = import_v4.z.looseObject({
343
+ type: import_v4.z.string(),
344
+ sequence_number: import_v4.z.number().nullish(),
345
+ response: perplexityAgentResponseSchema.nullish(),
346
+ item: perplexityOutputItemSchema.nullish(),
347
+ output_index: import_v4.z.number().nullish(),
348
+ item_id: import_v4.z.string().nullish(),
349
+ content_index: import_v4.z.number().nullish(),
350
+ delta: import_v4.z.string().nullish(),
351
+ text: import_v4.z.string().nullish(),
352
+ thought: import_v4.z.string().nullish(),
353
+ queries: import_v4.z.array(import_v4.z.string()).nullish(),
354
+ urls: import_v4.z.array(import_v4.z.string()).nullish(),
355
+ results: import_v4.z.array(perplexitySearchResultSchema).nullish(),
356
+ contents: import_v4.z.array(perplexityFetchedContentSchema).nullish(),
357
+ error: import_v4.z.looseObject({
358
+ code: import_v4.z.string().nullish(),
359
+ message: import_v4.z.string(),
360
+ type: import_v4.z.string().nullish()
361
+ }).nullish()
362
+ });
363
+ var perplexityErrorSchema = import_v4.z.looseObject({
364
+ error: import_v4.z.union([
365
+ import_v4.z.string(),
366
+ import_v4.z.looseObject({
367
+ code: import_v4.z.union([import_v4.z.string(), import_v4.z.number()]).optional(),
368
+ message: import_v4.z.string().nullish(),
369
+ type: import_v4.z.string().nullish()
370
+ })
371
+ ]).optional(),
372
+ detail: import_v4.z.union([
373
+ import_v4.z.string(),
374
+ import_v4.z.array(
375
+ import_v4.z.looseObject({
376
+ msg: import_v4.z.string()
377
+ })
378
+ )
379
+ ]).optional(),
380
+ message: import_v4.z.string().optional()
381
+ });
382
+ function perplexityErrorToMessage(data) {
383
+ var _a, _b, _c;
384
+ if (typeof data.error === "string") {
385
+ return data.error;
386
+ }
387
+ if (data.error != null) {
388
+ return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
389
+ }
390
+ if (typeof data.detail === "string") {
391
+ return data.detail;
392
+ }
393
+ if (Array.isArray(data.detail)) {
394
+ return data.detail.map((detail) => detail.msg).join(", ");
105
395
  }
396
+ return (_c = data.message) != null ? _c : "unknown error";
397
+ }
398
+
399
+ // src/perplexity-language-model-options.ts
400
+ var import_v42 = require("zod/v4");
401
+ var userLocationSchema = import_v42.z.looseObject({
402
+ latitude: import_v42.z.number().optional(),
403
+ longitude: import_v42.z.number().optional(),
404
+ country: import_v42.z.string().optional(),
405
+ city: import_v42.z.string().optional(),
406
+ region: import_v42.z.string().optional()
407
+ });
408
+ var webSearchFiltersSchema = import_v42.z.looseObject({
409
+ search_domain_filter: import_v42.z.array(import_v42.z.string()).optional(),
410
+ search_recency_filter: import_v42.z.enum(["hour", "day", "week", "month", "year"]).optional(),
411
+ search_after_date_filter: import_v42.z.string().optional(),
412
+ search_before_date_filter: import_v42.z.string().optional(),
413
+ last_updated_after_filter: import_v42.z.string().optional(),
414
+ last_updated_before_filter: import_v42.z.string().optional()
415
+ });
416
+ var webSearchToolSchema = import_v42.z.looseObject({
417
+ type: import_v42.z.literal("web_search"),
418
+ filters: webSearchFiltersSchema.optional(),
419
+ max_results: import_v42.z.number().int().positive().optional(),
420
+ max_tokens: import_v42.z.number().optional(),
421
+ max_tokens_per_page: import_v42.z.number().optional(),
422
+ search_context_size: import_v42.z.enum(["low", "medium", "high"]).optional(),
423
+ user_location: userLocationSchema.optional()
424
+ });
425
+ var nativeToolSchema = import_v42.z.union([
426
+ webSearchToolSchema,
427
+ import_v42.z.looseObject({
428
+ type: import_v42.z.literal("fetch_url"),
429
+ max_urls: import_v42.z.number().optional()
430
+ }),
431
+ import_v42.z.looseObject({ type: import_v42.z.literal("people_search") }),
432
+ import_v42.z.looseObject({ type: import_v42.z.literal("finance_search") }),
433
+ import_v42.z.looseObject({ type: import_v42.z.literal("sandbox") }),
434
+ import_v42.z.looseObject({
435
+ type: import_v42.z.literal("mcp"),
436
+ server_label: import_v42.z.string(),
437
+ server_url: import_v42.z.string(),
438
+ allowed_tools: import_v42.z.array(import_v42.z.string()).optional(),
439
+ authorization: import_v42.z.string().optional(),
440
+ defer_loading: import_v42.z.boolean().optional(),
441
+ headers: import_v42.z.record(import_v42.z.string(), import_v42.z.string()).optional()
442
+ }),
443
+ import_v42.z.looseObject({
444
+ type: import_v42.z.literal("connector"),
445
+ id: import_v42.z.string(),
446
+ server_label: import_v42.z.string(),
447
+ server_description: import_v42.z.string().optional(),
448
+ allowed_tools: import_v42.z.array(import_v42.z.string()).optional()
449
+ })
450
+ ]);
451
+ var perplexityLanguageModelOptions = import_v42.z.looseObject({
452
+ /** Top-level Agent API instructions. */
453
+ instructions: import_v42.z.string().optional(),
454
+ /**
455
+ * Native Agent API tools. AI SDK function tools can also be supplied through
456
+ * the top-level `tools` option on `generateText` and `streamText`.
457
+ */
458
+ tools: import_v42.z.array(nativeToolSchema).optional(),
459
+ /** A fallback model list for Agent API routing. */
460
+ models: import_v42.z.array(import_v42.z.string()).optional(),
461
+ /** Maximum number of agentic steps. */
462
+ max_steps: import_v42.z.number().int().positive().optional(),
463
+ /** Maximum number of native tool calls. */
464
+ max_tool_calls: import_v42.z.number().int().nonnegative().optional(),
465
+ /** Continue a conversation from an earlier Agent API response. */
466
+ previous_response_id: import_v42.z.string().optional(),
467
+ /**
468
+ * Whether the response can be retrieved later. Setting this to false does
469
+ * not disable persistence or prevent previous_response_id continuations.
470
+ */
471
+ store: import_v42.z.boolean().optional(),
472
+ /** Preferred response language as an ISO 639-1 language code. */
473
+ language_preference: import_v42.z.string().optional(),
474
+ /** Agent API reasoning configuration. */
475
+ reasoning: import_v42.z.looseObject({
476
+ effort: import_v42.z.enum(["minimal", "low", "medium", "high", "xhigh"]).optional()
477
+ }).optional(),
478
+ /** Agent API skill configuration. */
479
+ skills: import_v42.z.array(
480
+ import_v42.z.union([
481
+ import_v42.z.looseObject({
482
+ type: import_v42.z.literal("builtin"),
483
+ name: import_v42.z.enum([
484
+ "office",
485
+ "office/docx",
486
+ "office/pdf",
487
+ "office/pptx",
488
+ "office/xlsx"
489
+ ])
490
+ }),
491
+ import_v42.z.looseObject({
492
+ type: import_v42.z.literal("inline"),
493
+ name: import_v42.z.string(),
494
+ description: import_v42.z.string(),
495
+ instructions: import_v42.z.string()
496
+ })
497
+ ])
498
+ ).optional()
499
+ });
500
+
501
+ // src/perplexity-prepare-tools.ts
502
+ function preparePerplexityTools({
503
+ tools,
504
+ toolChoice
505
+ }) {
506
+ const preparedTools = [];
507
+ const warnings = [];
508
+ for (const tool of tools != null ? tools : []) {
509
+ if (tool.type === "provider-defined") {
510
+ warnings.push({ type: "unsupported-tool", tool });
511
+ continue;
512
+ }
513
+ preparedTools.push({
514
+ type: "function",
515
+ name: tool.name,
516
+ description: tool.description,
517
+ parameters: tool.inputSchema
518
+ });
519
+ }
520
+ if (toolChoice != null && toolChoice.type !== "auto") {
521
+ warnings.push({
522
+ type: "unsupported-setting",
523
+ setting: "toolChoice",
524
+ details: "The Perplexity Agent API currently selects tools automatically."
525
+ });
526
+ }
527
+ return { tools: preparedTools, warnings };
106
528
  }
107
529
 
108
530
  // src/perplexity-language-model.ts
531
+ var presetIds = /* @__PURE__ */ new Set([
532
+ "fast",
533
+ "low",
534
+ "medium",
535
+ "high",
536
+ "xhigh"
537
+ ]);
538
+ function getModelSelection(modelId) {
539
+ if (presetIds.has(modelId)) {
540
+ return { preset: modelId };
541
+ }
542
+ return { model: modelId };
543
+ }
544
+ function getResponseMetadata(response) {
545
+ var _a, _b;
546
+ return {
547
+ id: (_a = response.id) != null ? _a : void 0,
548
+ modelId: (_b = response.model) != null ? _b : void 0,
549
+ timestamp: response.created_at != null ? new Date(response.created_at * 1e3) : void 0
550
+ };
551
+ }
552
+ function getProviderMetadata(usage) {
553
+ var _a, _b, _c, _d, _e, _f, _g;
554
+ const cost = usage == null ? void 0 : usage.cost;
555
+ const numSearchQueries = (usage == null ? void 0 : usage.tool_calls_details) ? Object.entries(usage.tool_calls_details).filter(([name]) => name.includes("search")).reduce((total, [, details]) => {
556
+ var _a2;
557
+ return total + ((_a2 = details.invocation) != null ? _a2 : 0);
558
+ }, 0) : null;
559
+ return {
560
+ perplexity: {
561
+ usage: {
562
+ citationTokens: null,
563
+ numSearchQueries
564
+ },
565
+ images: null,
566
+ cost: cost == null ? null : {
567
+ inputTokensCost: (_a = cost.input_cost) != null ? _a : null,
568
+ outputTokensCost: (_b = cost.output_cost) != null ? _b : null,
569
+ requestCost: null,
570
+ totalCost: (_c = cost.total_cost) != null ? _c : null,
571
+ currency: (_d = cost.currency) != null ? _d : null,
572
+ cacheCreationCost: (_e = cost.cache_creation_cost) != null ? _e : null,
573
+ cacheReadCost: (_f = cost.cache_read_cost) != null ? _f : null,
574
+ toolCallsCost: (_g = cost.tool_calls_cost) != null ? _g : null
575
+ },
576
+ toolCalls: (usage == null ? void 0 : usage.tool_calls_details) == null ? null : Object.fromEntries(
577
+ Object.entries(usage.tool_calls_details).map(
578
+ ([name, details]) => {
579
+ var _a2;
580
+ return [
581
+ name,
582
+ { invocation: (_a2 = details.invocation) != null ? _a2 : null }
583
+ ];
584
+ }
585
+ )
586
+ )
587
+ }
588
+ };
589
+ }
590
+ function createSource(result, generateId2) {
591
+ var _a, _b, _c, _d, _e;
592
+ return {
593
+ type: "source",
594
+ sourceType: "url",
595
+ id: result.id == null ? generateId2() : String(result.id),
596
+ url: result.url,
597
+ title: result.title,
598
+ providerMetadata: {
599
+ perplexity: {
600
+ resultId: (_a = result.id) != null ? _a : null,
601
+ snippet: (_b = result.snippet) != null ? _b : null,
602
+ date: (_c = result.date) != null ? _c : null,
603
+ lastUpdated: (_d = result.last_updated) != null ? _d : null,
604
+ source: (_e = result.source) != null ? _e : null
605
+ }
606
+ }
607
+ };
608
+ }
609
+ function hasSearchResultId(source) {
610
+ var _a, _b;
611
+ return typeof ((_b = (_a = source.providerMetadata) == null ? void 0 : _a.perplexity) == null ? void 0 : _b.resultId) === "number";
612
+ }
613
+ function getSearchResults(item) {
614
+ var _a;
615
+ return item.type === "search_results" ? (_a = item.results) != null ? _a : [] : [];
616
+ }
617
+ function getFetchedSources(item) {
618
+ var _a;
619
+ return item.type === "fetch_url_results" ? (_a = item.contents) != null ? _a : [] : [];
620
+ }
109
621
  var PerplexityLanguageModel = class {
110
622
  constructor(modelId, config) {
111
- this.specificationVersion = "v3";
623
+ this.specificationVersion = "v2";
112
624
  this.provider = "perplexity";
113
625
  this.supportedUrls = {
114
- // No URLs are supported.
626
+ "image/*": [/^https?:\/\/.*$/]
115
627
  };
116
628
  this.modelId = modelId;
117
629
  this.config = config;
118
630
  }
119
- getArgs({
631
+ async getArgs({
120
632
  prompt,
121
633
  maxOutputTokens,
122
634
  temperature,
@@ -127,97 +639,181 @@ var PerplexityLanguageModel = class {
127
639
  stopSequences,
128
640
  responseFormat,
129
641
  seed,
130
- providerOptions
642
+ providerOptions,
643
+ tools,
644
+ toolChoice
131
645
  }) {
132
- var _a;
646
+ var _a, _b;
133
647
  const warnings = [];
648
+ const perplexityOptions = (_a = await (0, import_provider_utils2.parseProviderOptions)({
649
+ provider: "perplexity",
650
+ providerOptions,
651
+ schema: perplexityLanguageModelOptions
652
+ })) != null ? _a : {};
134
653
  if (topK != null) {
654
+ warnings.push({ type: "unsupported-setting", setting: "topK" });
655
+ }
656
+ if (frequencyPenalty != null) {
135
657
  warnings.push({
136
658
  type: "unsupported-setting",
137
- setting: "topK"
659
+ setting: "frequencyPenalty"
138
660
  });
139
661
  }
140
- if (stopSequences != null) {
662
+ if (presencePenalty != null) {
141
663
  warnings.push({
142
664
  type: "unsupported-setting",
143
- setting: "stopSequences"
665
+ setting: "presencePenalty"
144
666
  });
145
667
  }
668
+ if (stopSequences != null) {
669
+ warnings.push({ type: "unsupported-setting", setting: "stopSequences" });
670
+ }
146
671
  if (seed != null) {
672
+ warnings.push({ type: "unsupported-setting", setting: "seed" });
673
+ }
674
+ const { tools: nativeTools, ...agentOptions } = perplexityOptions;
675
+ const modelSelection = getModelSelection(this.modelId);
676
+ const { input, warnings: inputWarnings } = convertToPerplexityInput(prompt);
677
+ warnings.push(...inputWarnings);
678
+ const { tools: functionTools, warnings: toolWarnings } = preparePerplexityTools({ tools, toolChoice });
679
+ warnings.push(...toolWarnings);
680
+ const agentTools = [
681
+ ...nativeTools != null ? nativeTools : [],
682
+ ...functionTools
683
+ ];
684
+ const body = {
685
+ ...agentOptions,
686
+ ...modelSelection,
687
+ input,
688
+ max_output_tokens: maxOutputTokens,
689
+ temperature,
690
+ top_p: topP,
691
+ response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null ? {
692
+ type: "json_schema",
693
+ json_schema: {
694
+ name: (_b = responseFormat.name) != null ? _b : "response",
695
+ description: responseFormat.description,
696
+ schema: responseFormat.schema,
697
+ strict: true
698
+ }
699
+ } : void 0,
700
+ tools: agentTools.length > 0 ? agentTools : void 0
701
+ };
702
+ if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema == null) {
147
703
  warnings.push({
148
704
  type: "unsupported-setting",
149
- setting: "seed"
705
+ setting: "responseFormat",
706
+ details: "JSON response format without a schema is not supported."
150
707
  });
151
708
  }
152
- return {
153
- args: {
154
- // model id:
155
- model: this.modelId,
156
- // standardized settings:
157
- frequency_penalty: frequencyPenalty,
158
- max_tokens: maxOutputTokens,
159
- presence_penalty: presencePenalty,
160
- temperature,
161
- top_k: topK,
162
- top_p: topP,
163
- // response format:
164
- response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? {
165
- type: "json_schema",
166
- json_schema: { schema: responseFormat.schema }
167
- } : void 0,
168
- // provider extensions
169
- ...(_a = providerOptions == null ? void 0 : providerOptions.perplexity) != null ? _a : {},
170
- // messages:
171
- messages: convertToPerplexityMessages(prompt)
172
- },
173
- warnings
174
- };
709
+ return { args: body, warnings };
175
710
  }
176
711
  async doGenerate(options) {
177
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
178
- const { args: body, warnings } = this.getArgs(options);
712
+ var _a, _b, _c, _d, _e, _f, _g, _h, _i;
713
+ const { args: body, warnings } = await this.getArgs(options);
714
+ const url = `${this.config.baseURL}/v1/agent`;
179
715
  const {
180
716
  responseHeaders,
181
717
  value: response,
182
718
  rawValue: rawResponse
183
719
  } = await (0, import_provider_utils2.postJsonToApi)({
184
- url: `${this.config.baseURL}/chat/completions`,
185
- headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
720
+ url,
721
+ headers: (0, import_provider_utils2.combineHeaders)((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers),
186
722
  body,
187
723
  failedResponseHandler: (0, import_provider_utils2.createJsonErrorResponseHandler)({
188
724
  errorSchema: perplexityErrorSchema,
189
- errorToMessage
725
+ errorToMessage: perplexityErrorToMessage
190
726
  }),
191
727
  successfulResponseHandler: (0, import_provider_utils2.createJsonResponseHandler)(
192
- perplexityResponseSchema
728
+ perplexityAgentResponseSchema
193
729
  ),
194
730
  abortSignal: options.abortSignal,
195
731
  fetch: this.config.fetch
196
732
  });
197
- const choice = response.choices[0];
198
- const content = [];
199
- const text = choice.message.content;
200
- if (text.length > 0) {
201
- content.push({ type: "text", text });
733
+ if (response.error != null || response.status === "failed") {
734
+ throw new import_provider2.APICallError({
735
+ message: (_d = (_c = response.error) == null ? void 0 : _c.message) != null ? _d : "Perplexity response failed",
736
+ url,
737
+ requestBodyValues: body,
738
+ statusCode: 400,
739
+ responseHeaders,
740
+ responseBody: rawResponse,
741
+ isRetryable: false
742
+ });
202
743
  }
203
- if (response.citations != null) {
204
- for (const url of response.citations) {
744
+ const content = [];
745
+ const sourceIndexesByUrl = /* @__PURE__ */ new Map();
746
+ let hasFunctionCall = false;
747
+ const addSource = (source) => {
748
+ const existingIndex = sourceIndexesByUrl.get(source.url);
749
+ if (existingIndex == null) {
750
+ sourceIndexesByUrl.set(source.url, content.length);
751
+ content.push(source);
752
+ } else if (hasSearchResultId(source) && !hasSearchResultId(content[existingIndex])) {
753
+ content[existingIndex] = source;
754
+ }
755
+ };
756
+ for (const item of response.output) {
757
+ if (item.type === "message") {
758
+ for (const part of (_e = item.content) != null ? _e : []) {
759
+ if (part.type === "output_text" && part.text != null) {
760
+ content.push({ type: "text", text: part.text });
761
+ }
762
+ for (const annotation of (_f = part.annotations) != null ? _f : []) {
763
+ if (annotation.url != null) {
764
+ addSource({
765
+ type: "source",
766
+ sourceType: "url",
767
+ id: this.config.generateId(),
768
+ url: annotation.url,
769
+ title: annotation.title
770
+ });
771
+ }
772
+ }
773
+ }
774
+ } else if (item.type === "search_results") {
775
+ for (const result of getSearchResults(item)) {
776
+ addSource(createSource(result, this.config.generateId));
777
+ }
778
+ } else if (item.type === "fetch_url_results") {
779
+ for (const result of getFetchedSources(item)) {
780
+ addSource({
781
+ type: "source",
782
+ sourceType: "url",
783
+ id: this.config.generateId(),
784
+ url: result.url,
785
+ title: result.title,
786
+ providerMetadata: {
787
+ perplexity: { snippet: (_g = result.snippet) != null ? _g : null }
788
+ }
789
+ });
790
+ }
791
+ } else if (item.type === "function_call" && item.call_id != null && item.name != null && item.arguments != null) {
792
+ hasFunctionCall = true;
205
793
  content.push({
206
- type: "source",
207
- sourceType: "url",
208
- id: this.config.generateId(),
209
- url
794
+ type: "tool-call",
795
+ toolCallId: item.call_id,
796
+ toolName: item.name,
797
+ input: item.arguments,
798
+ providerMetadata: {
799
+ perplexity: {
800
+ itemId: (_h = item.id) != null ? _h : null,
801
+ ...item.thought_signature != null && {
802
+ thoughtSignature: item.thought_signature
803
+ }
804
+ }
805
+ }
210
806
  });
211
807
  }
212
808
  }
213
809
  return {
214
810
  content,
215
- finishReason: mapPerplexityFinishReason(choice.finish_reason),
216
- usage: {
217
- inputTokens: (_a = response.usage) == null ? void 0 : _a.prompt_tokens,
218
- outputTokens: (_b = response.usage) == null ? void 0 : _b.completion_tokens,
219
- totalTokens: (_d = (_c = response.usage) == null ? void 0 : _c.total_tokens) != null ? _d : void 0
220
- },
811
+ finishReason: mapPerplexityFinishReason({
812
+ status: response.status,
813
+ incompleteReason: (_i = response.incomplete_details) == null ? void 0 : _i.reason,
814
+ hasFunctionCall
815
+ }),
816
+ usage: convertPerplexityUsage(response.usage),
221
817
  request: { body },
222
818
  response: {
223
819
  ...getResponseMetadata(response),
@@ -225,57 +821,37 @@ var PerplexityLanguageModel = class {
225
821
  body: rawResponse
226
822
  },
227
823
  warnings,
228
- providerMetadata: {
229
- perplexity: {
230
- images: (_f = (_e = response.images) == null ? void 0 : _e.map((image) => ({
231
- imageUrl: image.image_url,
232
- originUrl: image.origin_url,
233
- height: image.height,
234
- width: image.width
235
- }))) != null ? _f : null,
236
- usage: {
237
- citationTokens: (_h = (_g = response.usage) == null ? void 0 : _g.citation_tokens) != null ? _h : null,
238
- numSearchQueries: (_j = (_i = response.usage) == null ? void 0 : _i.num_search_queries) != null ? _j : null
239
- }
240
- }
241
- }
824
+ providerMetadata: getProviderMetadata(response.usage)
242
825
  };
243
826
  }
244
827
  async doStream(options) {
245
- const { args, warnings } = this.getArgs(options);
828
+ var _a, _b;
829
+ const { args, warnings } = await this.getArgs(options);
246
830
  const body = { ...args, stream: true };
247
831
  const { responseHeaders, value: response } = await (0, import_provider_utils2.postJsonToApi)({
248
- url: `${this.config.baseURL}/chat/completions`,
249
- headers: (0, import_provider_utils2.combineHeaders)(this.config.headers(), options.headers),
832
+ url: `${this.config.baseURL}/v1/agent`,
833
+ headers: (0, import_provider_utils2.combineHeaders)((_b = (_a = this.config).headers) == null ? void 0 : _b.call(_a), options.headers),
250
834
  body,
251
835
  failedResponseHandler: (0, import_provider_utils2.createJsonErrorResponseHandler)({
252
836
  errorSchema: perplexityErrorSchema,
253
- errorToMessage
837
+ errorToMessage: perplexityErrorToMessage
254
838
  }),
255
839
  successfulResponseHandler: (0, import_provider_utils2.createEventSourceResponseHandler)(
256
- perplexityChunkSchema
840
+ perplexityAgentChunkSchema
257
841
  ),
258
842
  abortSignal: options.abortSignal,
259
843
  fetch: this.config.fetch
260
844
  });
261
845
  let finishReason = "unknown";
262
- const usage = {
263
- inputTokens: void 0,
264
- outputTokens: void 0,
265
- totalTokens: void 0
266
- };
267
- const providerMetadata = {
268
- perplexity: {
269
- usage: {
270
- citationTokens: null,
271
- numSearchQueries: null
272
- },
273
- images: null
274
- }
275
- };
276
- let isFirstChunk = true;
277
- let isActive = false;
278
- const self = this;
846
+ let usage;
847
+ let hasFunctionCall = false;
848
+ let hasResponseMetadata = false;
849
+ let activeReasoningId;
850
+ const textStates = /* @__PURE__ */ new Map();
851
+ const emittedSourceUrls = /* @__PURE__ */ new Set();
852
+ const pendingSourcesByUrl = /* @__PURE__ */ new Map();
853
+ const seenFunctionCalls = /* @__PURE__ */ new Set();
854
+ const generateId2 = this.config.generateId;
279
855
  return {
280
856
  stream: response.pipeThrough(
281
857
  new TransformStream({
@@ -283,76 +859,304 @@ var PerplexityLanguageModel = class {
283
859
  controller.enqueue({ type: "stream-start", warnings });
284
860
  },
285
861
  transform(chunk, controller) {
286
- var _a, _b, _c;
862
+ var _a2, _b2, _c, _d, _e, _f, _g;
287
863
  if (options.includeRawChunks) {
288
864
  controller.enqueue({ type: "raw", rawValue: chunk.rawValue });
289
865
  }
290
866
  if (!chunk.success) {
867
+ finishReason = "error";
291
868
  controller.enqueue({ type: "error", error: chunk.error });
292
869
  return;
293
870
  }
294
871
  const value = chunk.value;
295
- if (isFirstChunk) {
872
+ const getTextId = (itemId, outputIndex, contentIndex = 0) => {
873
+ const id = itemId != null ? itemId : String(outputIndex != null ? outputIndex : "text");
874
+ return contentIndex == null || contentIndex === 0 ? id : `${id}:${contentIndex}`;
875
+ };
876
+ const emitTextDelta = (id, delta) => {
877
+ let state = textStates.get(id);
878
+ if (state == null ? void 0 : state.ended) {
879
+ return;
880
+ }
881
+ if (state == null) {
882
+ state = { text: "", ended: false };
883
+ textStates.set(id, state);
884
+ controller.enqueue({ type: "text-start", id });
885
+ }
886
+ state.text += delta;
887
+ controller.enqueue({ type: "text-delta", id, delta });
888
+ };
889
+ const finishText = (id, text) => {
890
+ var _a3;
891
+ const state = textStates.get(id);
892
+ if (state == null ? void 0 : state.ended) {
893
+ return;
894
+ }
895
+ const emittedText = (_a3 = state == null ? void 0 : state.text) != null ? _a3 : "";
896
+ if (text != null && text.startsWith(emittedText) && text.length > emittedText.length) {
897
+ emitTextDelta(id, text.slice(emittedText.length));
898
+ }
899
+ const finalState = textStates.get(id);
900
+ if (finalState != null) {
901
+ finalState.ended = true;
902
+ controller.enqueue({ type: "text-end", id });
903
+ }
904
+ };
905
+ const finishOutputText = (item, outputIndex) => {
906
+ var _a3;
907
+ if (item.type === "message") {
908
+ for (const [contentIndex, part] of ((_a3 = item.content) != null ? _a3 : []).entries()) {
909
+ if (part.type === "output_text") {
910
+ finishText(
911
+ getTextId(item.id, outputIndex, contentIndex),
912
+ part.text
913
+ );
914
+ }
915
+ }
916
+ }
917
+ };
918
+ const emitSource = (source) => {
919
+ if (emittedSourceUrls.has(source.url)) {
920
+ return;
921
+ }
922
+ if (hasSearchResultId(source)) {
923
+ pendingSourcesByUrl.delete(source.url);
924
+ emittedSourceUrls.add(source.url);
925
+ controller.enqueue(source);
926
+ } else if (!pendingSourcesByUrl.has(source.url)) {
927
+ pendingSourcesByUrl.set(source.url, source);
928
+ }
929
+ };
930
+ const emitReasoningThought = (thought) => {
931
+ if (activeReasoningId != null && thought != null) {
932
+ controller.enqueue({
933
+ type: "reasoning-delta",
934
+ id: activeReasoningId,
935
+ delta: thought
936
+ });
937
+ }
938
+ };
939
+ const emitFunctionCall = (item) => {
940
+ var _a3;
941
+ if (item.type !== "function_call" || item.call_id == null || item.name == null || item.arguments == null || seenFunctionCalls.has(item.call_id)) {
942
+ return;
943
+ }
944
+ seenFunctionCalls.add(item.call_id);
945
+ hasFunctionCall = true;
296
946
  controller.enqueue({
297
- type: "response-metadata",
298
- ...getResponseMetadata(value)
947
+ type: "tool-input-start",
948
+ id: item.call_id,
949
+ toolName: item.name
299
950
  });
300
- (_a = value.citations) == null ? void 0 : _a.forEach((url) => {
301
- controller.enqueue({
951
+ controller.enqueue({
952
+ type: "tool-input-delta",
953
+ id: item.call_id,
954
+ delta: item.arguments
955
+ });
956
+ controller.enqueue({ type: "tool-input-end", id: item.call_id });
957
+ controller.enqueue({
958
+ type: "tool-call",
959
+ toolCallId: item.call_id,
960
+ toolName: item.name,
961
+ input: item.arguments,
962
+ providerMetadata: {
963
+ perplexity: {
964
+ itemId: (_a3 = item.id) != null ? _a3 : null,
965
+ ...item.thought_signature != null && {
966
+ thoughtSignature: item.thought_signature
967
+ }
968
+ }
969
+ }
970
+ });
971
+ };
972
+ const emitOutputSources = (item) => {
973
+ var _a3, _b3, _c2;
974
+ if (item.type === "message") {
975
+ for (const part of (_a3 = item.content) != null ? _a3 : []) {
976
+ for (const annotation of (_b3 = part.annotations) != null ? _b3 : []) {
977
+ if (annotation.url != null) {
978
+ emitSource({
979
+ type: "source",
980
+ sourceType: "url",
981
+ id: generateId2(),
982
+ url: annotation.url,
983
+ title: annotation.title
984
+ });
985
+ }
986
+ }
987
+ }
988
+ }
989
+ for (const result of getSearchResults(item)) {
990
+ emitSource(createSource(result, generateId2));
991
+ }
992
+ for (const result of getFetchedSources(item)) {
993
+ emitSource({
302
994
  type: "source",
303
995
  sourceType: "url",
304
- id: self.config.generateId(),
305
- url
996
+ id: generateId2(),
997
+ url: result.url,
998
+ title: result.title,
999
+ providerMetadata: {
1000
+ perplexity: { snippet: (_c2 = result.snippet) != null ? _c2 : null }
1001
+ }
306
1002
  });
307
- });
308
- isFirstChunk = false;
309
- }
310
- if (value.usage != null) {
311
- usage.inputTokens = value.usage.prompt_tokens;
312
- usage.outputTokens = value.usage.completion_tokens;
313
- providerMetadata.perplexity.usage = {
314
- citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null,
315
- numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null
316
- };
317
- }
318
- if (value.images != null) {
319
- providerMetadata.perplexity.images = value.images.map((image) => ({
320
- imageUrl: image.image_url,
321
- originUrl: image.origin_url,
322
- height: image.height,
323
- width: image.width
324
- }));
325
- }
326
- const choice = value.choices[0];
327
- if ((choice == null ? void 0 : choice.finish_reason) != null) {
328
- finishReason = mapPerplexityFinishReason(choice.finish_reason);
1003
+ }
1004
+ };
1005
+ switch (value.type) {
1006
+ case "response.created":
1007
+ case "response.in_progress": {
1008
+ if (!hasResponseMetadata && value.response != null) {
1009
+ controller.enqueue({
1010
+ type: "response-metadata",
1011
+ ...getResponseMetadata(value.response)
1012
+ });
1013
+ hasResponseMetadata = true;
1014
+ }
1015
+ break;
1016
+ }
1017
+ case "response.output_text.delta": {
1018
+ if (value.delta != null) {
1019
+ emitTextDelta(
1020
+ getTextId(
1021
+ value.item_id,
1022
+ value.output_index,
1023
+ value.content_index
1024
+ ),
1025
+ value.delta
1026
+ );
1027
+ }
1028
+ break;
1029
+ }
1030
+ case "response.output_text.done": {
1031
+ finishText(
1032
+ getTextId(
1033
+ value.item_id,
1034
+ value.output_index,
1035
+ value.content_index
1036
+ ),
1037
+ value.text
1038
+ );
1039
+ break;
1040
+ }
1041
+ case "response.reasoning.started": {
1042
+ if (activeReasoningId != null) {
1043
+ controller.enqueue({
1044
+ type: "reasoning-end",
1045
+ id: activeReasoningId
1046
+ });
1047
+ }
1048
+ activeReasoningId = `reasoning-${(_a2 = value.sequence_number) != null ? _a2 : generateId2()}`;
1049
+ controller.enqueue({
1050
+ type: "reasoning-start",
1051
+ id: activeReasoningId
1052
+ });
1053
+ emitReasoningThought(value.thought);
1054
+ break;
1055
+ }
1056
+ case "response.reasoning.search_queries":
1057
+ case "response.reasoning.fetch_url_queries": {
1058
+ emitReasoningThought(value.thought);
1059
+ break;
1060
+ }
1061
+ case "response.reasoning.search_results": {
1062
+ emitReasoningThought(value.thought);
1063
+ for (const result of (_b2 = value.results) != null ? _b2 : []) {
1064
+ emitSource(createSource(result, generateId2));
1065
+ }
1066
+ break;
1067
+ }
1068
+ case "response.reasoning.fetch_url_results": {
1069
+ emitReasoningThought(value.thought);
1070
+ for (const result of (_c = value.contents) != null ? _c : []) {
1071
+ emitSource({
1072
+ type: "source",
1073
+ sourceType: "url",
1074
+ id: generateId2(),
1075
+ url: result.url,
1076
+ title: result.title,
1077
+ providerMetadata: {
1078
+ perplexity: { snippet: (_d = result.snippet) != null ? _d : null }
1079
+ }
1080
+ });
1081
+ }
1082
+ break;
1083
+ }
1084
+ case "response.reasoning.stopped": {
1085
+ emitReasoningThought(value.thought);
1086
+ if (activeReasoningId != null) {
1087
+ controller.enqueue({
1088
+ type: "reasoning-end",
1089
+ id: activeReasoningId
1090
+ });
1091
+ activeReasoningId = void 0;
1092
+ }
1093
+ break;
1094
+ }
1095
+ case "response.output_item.done": {
1096
+ if (value.item != null) {
1097
+ finishOutputText(value.item, value.output_index);
1098
+ emitOutputSources(value.item);
1099
+ emitFunctionCall(value.item);
1100
+ }
1101
+ break;
1102
+ }
1103
+ case "response.completed":
1104
+ case "response.incomplete": {
1105
+ if (value.response != null) {
1106
+ if (!hasResponseMetadata) {
1107
+ controller.enqueue({
1108
+ type: "response-metadata",
1109
+ ...getResponseMetadata(value.response)
1110
+ });
1111
+ hasResponseMetadata = true;
1112
+ }
1113
+ for (const [
1114
+ outputIndex,
1115
+ item
1116
+ ] of value.response.output.entries()) {
1117
+ finishOutputText(item, outputIndex);
1118
+ emitOutputSources(item);
1119
+ emitFunctionCall(item);
1120
+ }
1121
+ usage = (_e = value.response.usage) != null ? _e : void 0;
1122
+ finishReason = mapPerplexityFinishReason({
1123
+ status: value.response.status,
1124
+ incompleteReason: (_f = value.response.incomplete_details) == null ? void 0 : _f.reason,
1125
+ hasFunctionCall
1126
+ });
1127
+ }
1128
+ break;
1129
+ }
1130
+ case "response.failed": {
1131
+ finishReason = "error";
1132
+ controller.enqueue({
1133
+ type: "error",
1134
+ error: (_g = value.error) != null ? _g : new Error("Perplexity response failed")
1135
+ });
1136
+ break;
1137
+ }
329
1138
  }
330
- if ((choice == null ? void 0 : choice.delta) == null) {
331
- return;
1139
+ },
1140
+ flush(controller) {
1141
+ for (const source of pendingSourcesByUrl.values()) {
1142
+ controller.enqueue(source);
332
1143
  }
333
- const delta = choice.delta;
334
- const textContent = delta.content;
335
- if (textContent != null) {
336
- if (!isActive) {
337
- controller.enqueue({ type: "text-start", id: "0" });
338
- isActive = true;
339
- }
1144
+ if (activeReasoningId != null) {
340
1145
  controller.enqueue({
341
- type: "text-delta",
342
- id: "0",
343
- delta: textContent
1146
+ type: "reasoning-end",
1147
+ id: activeReasoningId
344
1148
  });
345
1149
  }
346
- },
347
- flush(controller) {
348
- if (isActive) {
349
- controller.enqueue({ type: "text-end", id: "0" });
1150
+ for (const [id, state] of textStates) {
1151
+ if (!state.ended) {
1152
+ controller.enqueue({ type: "text-end", id });
1153
+ }
350
1154
  }
351
1155
  controller.enqueue({
352
1156
  type: "finish",
353
1157
  finishReason,
354
- usage,
355
- providerMetadata
1158
+ usage: convertPerplexityUsage(usage),
1159
+ providerMetadata: getProviderMetadata(usage)
356
1160
  });
357
1161
  }
358
1162
  })
@@ -362,78 +1166,9 @@ var PerplexityLanguageModel = class {
362
1166
  };
363
1167
  }
364
1168
  };
365
- function getResponseMetadata({
366
- id,
367
- model,
368
- created
369
- }) {
370
- return {
371
- id,
372
- modelId: model,
373
- timestamp: new Date(created * 1e3)
374
- };
375
- }
376
- var perplexityUsageSchema = import_v4.z.object({
377
- prompt_tokens: import_v4.z.number(),
378
- completion_tokens: import_v4.z.number(),
379
- total_tokens: import_v4.z.number().nullish(),
380
- citation_tokens: import_v4.z.number().nullish(),
381
- num_search_queries: import_v4.z.number().nullish()
382
- });
383
- var perplexityImageSchema = import_v4.z.object({
384
- image_url: import_v4.z.string(),
385
- origin_url: import_v4.z.string(),
386
- height: import_v4.z.number(),
387
- width: import_v4.z.number()
388
- });
389
- var perplexityResponseSchema = import_v4.z.object({
390
- id: import_v4.z.string(),
391
- created: import_v4.z.number(),
392
- model: import_v4.z.string(),
393
- choices: import_v4.z.array(
394
- import_v4.z.object({
395
- message: import_v4.z.object({
396
- role: import_v4.z.literal("assistant"),
397
- content: import_v4.z.string()
398
- }),
399
- finish_reason: import_v4.z.string().nullish()
400
- })
401
- ),
402
- citations: import_v4.z.array(import_v4.z.string()).nullish(),
403
- images: import_v4.z.array(perplexityImageSchema).nullish(),
404
- usage: perplexityUsageSchema.nullish()
405
- });
406
- var perplexityChunkSchema = import_v4.z.object({
407
- id: import_v4.z.string(),
408
- created: import_v4.z.number(),
409
- model: import_v4.z.string(),
410
- choices: import_v4.z.array(
411
- import_v4.z.object({
412
- delta: import_v4.z.object({
413
- role: import_v4.z.literal("assistant"),
414
- content: import_v4.z.string()
415
- }),
416
- finish_reason: import_v4.z.string().nullish()
417
- })
418
- ),
419
- citations: import_v4.z.array(import_v4.z.string()).nullish(),
420
- images: import_v4.z.array(perplexityImageSchema).nullish(),
421
- usage: perplexityUsageSchema.nullish()
422
- });
423
- var perplexityErrorSchema = import_v4.z.object({
424
- error: import_v4.z.object({
425
- code: import_v4.z.number(),
426
- message: import_v4.z.string().nullish(),
427
- type: import_v4.z.string().nullish()
428
- })
429
- });
430
- var errorToMessage = (data) => {
431
- var _a, _b;
432
- return (_b = (_a = data.error.message) != null ? _a : data.error.type) != null ? _b : "unknown error";
433
- };
434
1169
 
435
1170
  // src/version.ts
436
- var VERSION = true ? "2.1.0-beta.9" : "0.0.0-test";
1171
+ var VERSION = true ? "2.1.1" : "0.0.0-test";
437
1172
 
438
1173
  // src/perplexity-provider.ts
439
1174
  function createPerplexity(options = {}) {
@@ -462,10 +1197,10 @@ function createPerplexity(options = {}) {
462
1197
  const provider = (modelId) => createLanguageModel(modelId);
463
1198
  provider.languageModel = createLanguageModel;
464
1199
  provider.textEmbeddingModel = (modelId) => {
465
- throw new import_provider2.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
1200
+ throw new import_provider3.NoSuchModelError({ modelId, modelType: "textEmbeddingModel" });
466
1201
  };
467
1202
  provider.imageModel = (modelId) => {
468
- throw new import_provider2.NoSuchModelError({ modelId, modelType: "imageModel" });
1203
+ throw new import_provider3.NoSuchModelError({ modelId, modelType: "imageModel" });
469
1204
  };
470
1205
  return provider;
471
1206
  }