@ai-sdk/perplexity 3.0.63 → 3.1.0

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