返回 last30days-skill
perplexity.py
根目录 / skills / last30days / scripts / lib / perplexity.py
1 """Perplexity Agent API, Search API, and OpenRouter compatibility integration.
2
3 The Perplexity source is paid and opt-in. A direct key uses a controlled Agent
4 API request with only web search enabled. Direct Deep Research uses an Agent
5 API background run with the dynamic high preset. When no direct Perplexity key
6 exists, OpenRouter preserves the legacy synchronous Sonar fallback.
7 """
8
9 from __future__ import annotations
10
11 import time
12 from datetime import datetime
13 from typing import Any
14 from urllib.parse import urlparse
15
16 from . import health, http, log, providers
17
18
19 OPENROUTER_URL = "https://openrouter.ai/api/v1/chat/completions"
20 PERPLEXITY_AGENT_URL = "https://api.perplexity.ai/v1/agent"
21 PERPLEXITY_SEARCH_URL = "https://api.perplexity.ai/search"
22
23 PERPLEXITY_MODE_AGENT = "agent"
24 PERPLEXITY_MODE_SONAR = "sonar" # Direct-key alias and OpenRouter artifact mode.
25 PERPLEXITY_MODE_SEARCH = "search"
26 PERPLEXITY_MODE_BOTH = "both"
27 PERPLEXITY_DEFAULT_AGENT_TIMEOUT_SECONDS = 120
28 PERPLEXITY_DEFAULT_DEEP_TIMEOUT_SECONDS = 600
29 PERPLEXITY_DEEP_INITIAL_POLL_DELAY_SECONDS = 5.0
30 PERPLEXITY_DEEP_MAX_POLL_DELAY_SECONDS = 60.0
31
32 PERPLEXITY_DEFAULT_AGENT_MODEL = "perplexity/sonar"
33 OPENROUTER_MODEL_SONAR_PRO = "perplexity/sonar-pro"
34 OPENROUTER_MODEL_DEEP_RESEARCH = "perplexity/sonar-deep-research"
35 PERPLEXITY_DEFAULT_ANTHROPIC_MAX_OUTPUT_TOKENS = 4096
36 PERPLEXITY_CONTROLLED_PROFILE = "last30days-controlled-web-search/v1"
37 PERPLEXITY_PRESET_PROFILE = "perplexity-agent-preset"
38 AGENT_PRESETS = {"fast", "low", "medium", "high"}
39 DIRECT_MODES = {
40 PERPLEXITY_MODE_AGENT,
41 PERPLEXITY_MODE_SEARCH,
42 PERPLEXITY_MODE_BOTH,
43 }
44 SEARCH_CONTEXT_SIZES = {"low", "medium", "high"}
45 SEARCH_RECENCY_FILTERS = {"hour", "day", "week", "month", "year"}
46 REASONING_EFFORTS = {"minimal", "low", "medium", "high"}
47
48 CONTROLLED_AGENT_INSTRUCTIONS = (
49 "Use the supplied web search tool for current, source-grounded research. "
50 "Keep the answer concise. Cite source-backed claims in the answer. "
51 "Do not use tools other than those supplied in this request."
52 )
53
54
55 class AgentBackgroundTimeout(TimeoutError):
56 def __init__(self, metadata: dict[str, Any]):
57 timeout_seconds = metadata.get("backgroundTimeoutSeconds") or "unknown"
58 super().__init__(f"Agent background run exceeded {timeout_seconds}s wall timeout")
59 self.metadata = metadata
60
61
62 class AgentBackgroundFailed(RuntimeError):
63 def __init__(self, metadata: dict[str, Any]):
64 detail = metadata.get("backgroundErrorMessage") or "Agent background run failed"
65 super().__init__(str(detail))
66 self.metadata = metadata
67
68
69 class AgentBackgroundPollError(RuntimeError):
70 def __init__(self, metadata: dict[str, Any]):
71 detail = metadata.get("backgroundPollError") or "Agent background poll failed"
72 super().__init__(str(detail))
73 self.metadata = metadata
74
75
76 def _log(message: str) -> None:
77 log.source_log("Perplexity", message, tty_only=False)
78
79
80 def _domain(url: str) -> str:
81 return urlparse(url).netloc.strip().lower()
82
83
84 def _config_text(config: dict[str, Any], key: str) -> str:
85 return str(config.get(key) or "").strip()
86
87
88 def _csv_values(raw: str, limit: int | None = None) -> list[str]:
89 values = [part.strip() for part in raw.split(",") if part.strip()]
90 return values[:limit]
91
92
93 def _positive_int(
94 raw: object,
95 default: int,
96 min_value: int,
97 max_value: int | None = None,
98 ) -> int:
99 try:
100 value = int(str(raw).strip())
101 except (TypeError, ValueError):
102 return default
103 value = max(value, min_value)
104 if max_value is not None:
105 value = min(value, max_value)
106 return value
107
108
109 def _mmddyyyy(date: str | None) -> str | None:
110 if not date:
111 return None
112 try:
113 return datetime.strptime(date, "%Y-%m-%d").strftime("%m/%d/%Y")
114 except ValueError:
115 return None
116
117
118 def _usage(data: dict[str, Any]) -> dict[str, Any]:
119 usage = data.get("usage")
120 return usage if isinstance(usage, dict) else {}
121
122
123 def _error_artifact(exc: Exception) -> dict[str, Any]:
124 artifact: dict[str, Any] = {
125 "error": type(exc).__name__,
126 "message": str(exc)[:200],
127 }
128 if isinstance(exc, http.HTTPError):
129 artifact["statusCode"] = exc.status_code
130 return artifact
131
132
133 def _provider(config: dict[str, Any]) -> tuple[str, str] | None:
134 """Prefer direct Perplexity, then preserve the OpenRouter Sonar fallback."""
135 api_key = _config_text(config, "PERPLEXITY_API_KEY")
136 if api_key:
137 return "perplexity", api_key
138 openrouter_key = _config_text(config, "OPENROUTER_API_KEY")
139 if openrouter_key:
140 return "openrouter", openrouter_key
141 return None
142
143
144 def _mode(config: dict[str, Any], deep: bool, provider: str) -> str:
145 if deep:
146 return (
147 PERPLEXITY_MODE_AGENT
148 if provider == "perplexity"
149 else PERPLEXITY_MODE_SONAR
150 )
151
152 mode = (
153 _config_text(config, "LAST30DAYS_PERPLEXITY_MODE")
154 or PERPLEXITY_MODE_AGENT
155 ).lower()
156 if provider == "openrouter":
157 if mode in {PERPLEXITY_MODE_SEARCH, PERPLEXITY_MODE_BOTH}:
158 _log(
159 f"LAST30DAYS_PERPLEXITY_MODE={mode} requires PERPLEXITY_API_KEY; "
160 "using the OpenRouter Sonar fallback"
161 )
162 return PERPLEXITY_MODE_SONAR
163 if mode == PERPLEXITY_MODE_SONAR:
164 _log(
165 "LAST30DAYS_PERPLEXITY_MODE=sonar is deprecated; "
166 "using the Agent API controlled profile"
167 )
168 return PERPLEXITY_MODE_AGENT
169 if mode not in DIRECT_MODES:
170 _log(f"Unsupported LAST30DAYS_PERPLEXITY_MODE={mode!r}; using agent")
171 return PERPLEXITY_MODE_AGENT
172 return mode
173
174
175 def _agent_preset(config: dict[str, Any], deep: bool) -> str | None:
176 if deep:
177 return "high"
178
179 preset = _config_text(config, "LAST30DAYS_PERPLEXITY_AGENT_PRESET").lower()
180 if not preset:
181 return None
182 if preset in AGENT_PRESETS:
183 return preset
184 _log(
185 "Unsupported LAST30DAYS_PERPLEXITY_AGENT_PRESET="
186 f"{preset!r}; using the controlled profile"
187 )
188 return None
189
190
191 def _agent_model(config: dict[str, Any]) -> str:
192 legacy_model = _config_text(config, "LAST30DAYS_PERPLEXITY_MODEL")
193 if legacy_model:
194 _log(
195 "LAST30DAYS_PERPLEXITY_MODEL is a legacy Sonar setting and is "
196 "ignored by the Agent API; set LAST30DAYS_PERPLEXITY_AGENT_MODEL "
197 "for an explicit Agent model"
198 )
199 return (
200 _config_text(config, "LAST30DAYS_PERPLEXITY_AGENT_MODEL")
201 or PERPLEXITY_DEFAULT_AGENT_MODEL
202 )
203
204
205 def _agent_timeout(config: dict[str, Any]) -> int:
206 return _positive_int(
207 config.get("LAST30DAYS_PERPLEXITY_AGENT_TIMEOUT_SECONDS"),
208 PERPLEXITY_DEFAULT_AGENT_TIMEOUT_SECONDS,
209 1,
210 600,
211 )
212
213
214 def _safe_error_message(data: dict[str, Any]) -> str | None:
215 error = data.get("error")
216 if isinstance(error, str):
217 return error[:200]
218 if isinstance(error, dict):
219 for key in ("message", "detail", "code"):
220 value = error.get(key)
221 if isinstance(value, str) and value:
222 return value[:200]
223 return None
224
225
226 def _safe_incomplete_reason(data: dict[str, Any]) -> str | None:
227 details = data.get("incomplete_details")
228 if not isinstance(details, dict):
229 return None
230 reason = details.get("reason")
231 return reason[:100] if isinstance(reason, str) and reason else None
232
233
234 def _search_type(config: dict[str, Any]) -> str | None:
235 """Keep omission intact; search backends are separate from Agent presets."""
236 value = _config_text(config, "LAST30DAYS_PERPLEXITY_SEARCH_TYPE").lower()
237 if not value:
238 return None
239 if value not in {"web", "fast"}:
240 raise ValueError("LAST30DAYS_PERPLEXITY_SEARCH_TYPE must be web or fast")
241 return value
242
243
244 def _build_search_payload(
245 query: str,
246 date_range: tuple[str, str],
247 config: dict[str, Any],
248 ) -> dict[str, Any]:
249 from_date, to_date = date_range
250 payload: dict[str, Any] = {
251 "query": query,
252 "max_results": _positive_int(
253 config.get("LAST30DAYS_PERPLEXITY_MAX_RESULTS"),
254 10,
255 1,
256 20,
257 ),
258 }
259
260 context_size = _config_text(
261 config,
262 "LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE",
263 ).lower()
264 search_type = _search_type(config)
265 if search_type is not None:
266 payload["search_type"] = search_type
267 if context_size in SEARCH_CONTEXT_SIZES:
268 payload["search_context_size"] = context_size
269
270 country = _config_text(config, "LAST30DAYS_PERPLEXITY_COUNTRY").upper()
271 if len(country) == 2:
272 payload["country"] = country
273
274 domains = _csv_values(
275 _config_text(config, "LAST30DAYS_PERPLEXITY_DOMAIN_FILTER"),
276 limit=20,
277 )
278 if domains:
279 payload["search_domain_filter"] = domains
280
281 languages = _csv_values(
282 _config_text(config, "LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER"),
283 limit=20,
284 )
285 if languages:
286 payload["search_language_filter"] = languages
287
288 after = _mmddyyyy(from_date)
289 before = _mmddyyyy(to_date)
290 if after:
291 payload["search_after_date_filter"] = after
292 if before:
293 payload["search_before_date_filter"] = before
294
295 # Perplexity Search API rejects search_recency_filter when explicit
296 # published-date filters are present. Preserve the upstream fix.
297 recency = _config_text(
298 config,
299 "LAST30DAYS_PERPLEXITY_RECENCY_FILTER",
300 ).lower()
301 if recency in SEARCH_RECENCY_FILTERS and not (after or before):
302 payload["search_recency_filter"] = recency
303
304 return payload
305
306
307 def _build_web_search_tool(
308 date_range: tuple[str, str],
309 config: dict[str, Any],
310 ) -> dict[str, Any]:
311 from_date, to_date = date_range
312 tool: dict[str, Any] = {
313 "type": "web_search",
314 "max_results": _positive_int(
315 config.get("LAST30DAYS_PERPLEXITY_MAX_RESULTS"),
316 10,
317 1,
318 20,
319 ),
320 }
321
322 context_size = _config_text(
323 config,
324 "LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE",
325 ).lower()
326 search_type = _search_type(config)
327 if search_type is not None:
328 tool["search_type"] = search_type
329 if context_size in SEARCH_CONTEXT_SIZES:
330 tool["search_context_size"] = context_size
331
332 country = _config_text(config, "LAST30DAYS_PERPLEXITY_COUNTRY").upper()
333 if len(country) == 2:
334 tool["user_location"] = {"country": country}
335
336 filters: dict[str, Any] = {}
337 domains = _csv_values(
338 _config_text(config, "LAST30DAYS_PERPLEXITY_DOMAIN_FILTER"),
339 limit=20,
340 )
341 if domains:
342 filters["search_domain_filter"] = domains
343
344 after = _mmddyyyy(from_date)
345 before = _mmddyyyy(to_date)
346 if after:
347 filters["search_after_date_filter"] = after
348 if before:
349 filters["search_before_date_filter"] = before
350
351 recency = _config_text(
352 config,
353 "LAST30DAYS_PERPLEXITY_RECENCY_FILTER",
354 ).lower()
355 if recency in SEARCH_RECENCY_FILTERS and not (after or before):
356 filters["search_recency_filter"] = recency
357 if filters:
358 tool["filters"] = filters
359
360 language_filter = _config_text(
361 config,
362 "LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER",
363 )
364 if language_filter:
365 _log(
366 "LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER has no Agent API "
367 "equivalent and applies only to Search API mode"
368 )
369 search_mode = _config_text(config, "LAST30DAYS_PERPLEXITY_SEARCH_MODE").lower()
370 if search_mode and search_mode != "web":
371 _log(
372 "LAST30DAYS_PERPLEXITY_SEARCH_MODE has no Agent API equivalent; "
373 "using web search"
374 )
375
376 return tool
377
378
379 def _safe_request(payload: dict[str, Any]) -> dict[str, Any]:
380 request: dict[str, Any] = {}
381 for key in (
382 "model",
383 "preset",
384 "max_steps",
385 "max_output_tokens",
386 "background",
387 ):
388 if key in payload:
389 request[key] = payload[key]
390 reasoning = payload.get("reasoning")
391 if isinstance(reasoning, dict) and isinstance(reasoning.get("effort"), str):
392 request["reasoning"] = {"effort": reasoning["effort"]}
393 tool_choice = payload.get("tool_choice")
394 if tool_choice == {"type": "web_search"}:
395 request["tool_choice"] = tool_choice
396 tools = payload.get("tools")
397 if isinstance(tools, list):
398 request["tools"] = [
399 {
400 key: tool[key]
401 for key in (
402 "type",
403 "max_results",
404 "search_context_size",
405 "search_type",
406 "user_location",
407 "filters",
408 )
409 if key in tool
410 }
411 for tool in tools
412 if isinstance(tool, dict) and tool.get("type") == "web_search"
413 ]
414 return request
415
416
417 def _build_agent_payload(
418 prompt: str,
419 date_range: tuple[str, str],
420 config: dict[str, Any],
421 deep: bool,
422 ) -> tuple[dict[str, Any], dict[str, Any]]:
423 preset = _agent_preset(config, deep)
424 if preset:
425 payload = {
426 "preset": preset,
427 "input": prompt,
428 # A supplied web_search tool merges with a preset's tools. This
429 # preserves the user's date, domain, location, and result bounds
430 # without claiming to disable any other dynamic-preset tools.
431 "tools": [_build_web_search_tool(date_range, config)],
432 }
433 if deep:
434 payload["background"] = True
435 return payload, {
436 "profile": PERPLEXITY_PRESET_PROFILE,
437 "preset": preset,
438 "dynamicPreset": True,
439 "request": _safe_request(payload),
440 }
441
442 payload: dict[str, Any] = {
443 "model": _agent_model(config),
444 "instructions": CONTROLLED_AGENT_INSTRUCTIONS,
445 "input": prompt,
446 "tools": [_build_web_search_tool(date_range, config)],
447 "tool_choice": {"type": "web_search"},
448 "max_steps": _positive_int(
449 config.get("LAST30DAYS_PERPLEXITY_AGENT_MAX_STEPS"),
450 5,
451 1,
452 15,
453 ),
454 }
455 if str(payload["model"]).lower().startswith("anthropic/"):
456 payload["max_output_tokens"] = _positive_int(
457 config.get("LAST30DAYS_PERPLEXITY_AGENT_MAX_OUTPUT_TOKENS"),
458 PERPLEXITY_DEFAULT_ANTHROPIC_MAX_OUTPUT_TOKENS,
459 1,
460 32768,
461 )
462 effort = _config_text(
463 config,
464 "LAST30DAYS_PERPLEXITY_REASONING_EFFORT",
465 ).lower()
466 if effort in REASONING_EFFORTS:
467 payload["reasoning"] = {"effort": effort}
468 return payload, {
469 "profile": PERPLEXITY_CONTROLLED_PROFILE,
470 "model": payload["model"],
471 "dynamicPreset": False,
472 "request": _safe_request(payload),
473 }
474
475
476 def _append_citation(
477 citations: list[dict[str, Any]],
478 seen_urls: set[str],
479 citation: dict[str, Any],
480 ) -> None:
481 url = str(citation.get("url") or "").strip()
482 if not url:
483 return
484 if url in seen_urls:
485 # Message annotations commonly carry only a URL and title. Merge the
486 # later search_results item instead of discarding its snippet/date.
487 for existing in citations:
488 if existing.get("url") != url:
489 continue
490 for key in ("title", "snippet", "date"):
491 if not existing.get(key) and citation.get(key):
492 existing[key] = citation[key]
493 return
494 seen_urls.add(url)
495 citations.append(
496 {
497 "url": url,
498 "title": citation.get("title") or "",
499 "snippet": citation.get("snippet") or "",
500 "date": citation.get("date"),
501 }
502 )
503
504
505 def _append_annotations(
506 citations: list[dict[str, Any]],
507 seen_urls: set[str],
508 annotations: Any,
509 ) -> None:
510 if not isinstance(annotations, list):
511 return
512 for annotation in annotations:
513 if not isinstance(annotation, dict):
514 continue
515 citation = annotation.get("url_citation")
516 if not isinstance(citation, dict):
517 citation = annotation
518 _append_citation(citations, seen_urls, citation)
519
520
521 def _extract_agent_citations(data: dict[str, Any]) -> list[dict[str, Any]]:
522 citations: list[dict[str, Any]] = []
523 seen_urls: set[str] = set()
524
525 for result in data.get("results") or []:
526 if isinstance(result, dict):
527 _append_citation(citations, seen_urls, result)
528
529 output = data.get("output")
530 if not isinstance(output, list):
531 return citations
532
533 for item in output:
534 if not isinstance(item, dict):
535 continue
536 item_type = item.get("type")
537 if item_type == "search_results":
538 for result in item.get("results") or []:
539 if isinstance(result, dict):
540 _append_citation(citations, seen_urls, result)
541 continue
542 if item_type != "message":
543 continue
544 _append_annotations(citations, seen_urls, item.get("annotations"))
545 content = item.get("content")
546 if not isinstance(content, list):
547 continue
548 for part in content:
549 if isinstance(part, dict):
550 _append_annotations(citations, seen_urls, part.get("annotations"))
551
552 return citations
553
554
555 def _extract_openrouter_citations(
556 data: dict[str, Any],
557 choice: dict[str, Any],
558 ) -> list[dict[str, Any]]:
559 """Read the legacy OpenAI-compatible Sonar citation shapes."""
560 citations: list[dict[str, Any]] = []
561 seen_urls: set[str] = set()
562 search_results: dict[str, dict[str, Any]] = {}
563 for result in data.get("search_results") or []:
564 if not isinstance(result, dict):
565 continue
566 url = str(result.get("url") or "").strip()
567 if not url:
568 continue
569 search_results[url] = result
570 _append_citation(citations, seen_urls, result)
571
572 for url in data.get("citations") or []:
573 if not isinstance(url, str):
574 continue
575 result = search_results.get(url, {})
576 _append_citation(
577 citations,
578 seen_urls,
579 {
580 "url": url,
581 "title": result.get("title") or _domain(url),
582 "snippet": result.get("snippet") or "",
583 "date": result.get("date"),
584 },
585 )
586
587 message = choice.get("message")
588 if isinstance(message, dict):
589 _append_annotations(citations, seen_urls, message.get("annotations"))
590 return citations
591
592
593 def _output_types(data: dict[str, Any]) -> list[str]:
594 output = data.get("output")
595 if not isinstance(output, list):
596 return []
597 return [
598 item["type"]
599 for item in output
600 if isinstance(item, dict) and isinstance(item.get("type"), str)
601 ]
602
603
604 def _output_text(data: dict[str, Any]) -> str:
605 direct = data.get("output_text")
606 if isinstance(direct, str) and direct.strip():
607 return direct
608
609 parts: list[str] = []
610 output = data.get("output")
611 if not isinstance(output, list):
612 return ""
613 for item in output:
614 if not isinstance(item, dict) or item.get("type") != "message":
615 continue
616 content = item.get("content")
617 if isinstance(content, str):
618 parts.append(content)
619 continue
620 if not isinstance(content, list):
621 continue
622 for part in content:
623 if not isinstance(part, dict):
624 continue
625 if part.get("type") not in {"output_text", "text"}:
626 continue
627 text = part.get("text")
628 if isinstance(text, str):
629 parts.append(text)
630 return "".join(parts).strip()
631
632
633 def _background_metadata(
634 data: dict[str, Any],
635 response_id: str,
636 timeout_seconds: int,
637 poll_count: int,
638 local_status: str,
639 ) -> dict[str, Any]:
640 metadata: dict[str, Any] = {
641 "background": True,
642 "responseId": response_id,
643 "backgroundStatus": data.get("status"),
644 "servedModel": data.get("model"),
645 "usage": _usage(data),
646 "outputTypes": _output_types(data),
647 "backgroundTimeoutSeconds": timeout_seconds,
648 "backgroundPollCount": poll_count,
649 "backgroundLocalStatus": local_status,
650 }
651 message = _safe_error_message(data)
652 if message:
653 metadata["backgroundErrorMessage"] = message
654 incomplete_reason = _safe_incomplete_reason(data)
655 if incomplete_reason:
656 metadata["incompleteReason"] = incomplete_reason
657 return {key: value for key, value in metadata.items() if value is not None}
658
659
660 def _log_deep_receipt(artifact: dict[str, Any]) -> None:
661 """Expose the safe Deep receipt to slash-command and CLI consumers."""
662 fields = (
663 ("model", artifact.get("servedModel")),
664 ("response_id", artifact.get("responseId")),
665 ("provider_status", artifact.get("backgroundStatus") or artifact.get("status")),
666 ("local_status", artifact.get("backgroundLocalStatus")),
667 ("incomplete_reason", artifact.get("incompleteReason")),
668 ("polls", artifact.get("backgroundPollCount")),
669 ("timeout_seconds", artifact.get("backgroundTimeoutSeconds")),
670 )
671 rendered = " ".join(
672 f"{key}={value}"
673 for key, value in fields
674 if value is not None
675 )
676 _log(f"Deep Research receipt: {rendered or 'unavailable'}")
677
678
679 def deep_timeout_seconds(config: dict[str, Any]) -> int:
680 timeout = _positive_int(
681 config.get("LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS"),
682 PERPLEXITY_DEFAULT_DEEP_TIMEOUT_SECONDS,
683 1,
684 )
685 try:
686 float(timeout)
687 except OverflowError:
688 return PERPLEXITY_DEFAULT_DEEP_TIMEOUT_SECONDS
689 return timeout
690
691
692 def _poll_agent_background(
693 payload: dict[str, Any],
694 headers: dict[str, str],
695 config: dict[str, Any],
696 ) -> tuple[dict[str, Any], dict[str, Any]]:
697 timeout_seconds = deep_timeout_seconds(config)
698 deadline = config.get("_research_deadline")
699 if deadline is None:
700 deadline = time.monotonic() + timeout_seconds
701 cancel = config.get("_enrich_cancel")
702 created = http.post(
703 PERPLEXITY_AGENT_URL,
704 payload,
705 headers=headers,
706 timeout=30,
707 retries=1,
708 deadline_monotonic=deadline,
709 cancel=cancel,
710 )
711 response_id = created.get("id")
712 if not isinstance(response_id, str) or not response_id:
713 raise http.HTTPError("Agent background response missing id")
714
715 terminal = {"completed", "failed", "cancelled", "incomplete"}
716 status = str(created.get("status") or "").lower()
717 data = created
718 poll_count = 0
719 if status:
720 _log(f"Agent background status: {status}")
721
722 delay = PERPLEXITY_DEEP_INITIAL_POLL_DELAY_SECONDS
723 while status not in terminal:
724 if (cancel is not None and cancel.is_set()) or time.monotonic() >= deadline:
725 raise AgentBackgroundTimeout(
726 _background_metadata(
727 data,
728 response_id,
729 timeout_seconds,
730 poll_count,
731 "PENDING_REMOTE",
732 )
733 )
734 try:
735 data = http.get(
736 f"{PERPLEXITY_AGENT_URL}/{response_id}",
737 headers=headers,
738 timeout=30,
739 retries=2,
740 deadline_monotonic=deadline,
741 cancel=cancel,
742 )
743 except http.HTTPError as exc:
744 if isinstance(exc, http.DeadlineExceeded) or time.monotonic() >= deadline:
745 raise AgentBackgroundTimeout(
746 _background_metadata(
747 data,
748 response_id,
749 timeout_seconds,
750 poll_count + 1,
751 "PENDING_REMOTE",
752 )
753 ) from exc
754 metadata = _background_metadata(
755 data,
756 response_id,
757 timeout_seconds,
758 poll_count + 1,
759 "POLL_ERROR",
760 )
761 metadata["backgroundPollError"] = str(exc)[:200]
762 if exc.status_code is not None:
763 metadata["backgroundPollStatusCode"] = exc.status_code
764 raise AgentBackgroundPollError(metadata) from exc
765
766 poll_count += 1
767 next_status = str(data.get("status") or "").lower()
768 if next_status and next_status != status:
769 _log(f"Agent background status: {next_status}")
770 status = next_status
771 remaining = deadline - time.monotonic()
772 if remaining <= 0 or (cancel is not None and cancel.is_set()):
773 raise AgentBackgroundTimeout(
774 _background_metadata(
775 data,
776 response_id,
777 timeout_seconds,
778 poll_count,
779 "PENDING_REMOTE",
780 )
781 )
782 if status in terminal:
783 break
784 if cancel is None:
785 time.sleep(min(delay, remaining))
786 else:
787 cancel.wait(min(delay, remaining))
788 delay = min(delay * 1.5, PERPLEXITY_DEEP_MAX_POLL_DELAY_SECONDS)
789
790 metadata = _background_metadata(
791 data,
792 response_id,
793 timeout_seconds,
794 poll_count,
795 "COMPLETED_REMOTE" if status == "completed" else "TERMINAL_REMOTE",
796 )
797 if status == "completed":
798 return data, metadata
799 if not status:
800 metadata["backgroundErrorMessage"] = "Agent background response has no status"
801 raise AgentBackgroundFailed(metadata)
802
803
804 def _search_api(
805 query: str,
806 date_range: tuple[str, str],
807 config: dict[str, Any],
808 api_key: str,
809 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
810 from_date, to_date = date_range
811 headers = {
812 "Authorization": f"Bearer {api_key}",
813 "Content-Type": "application/json",
814 }
815 payload = _build_search_payload(query, date_range, config)
816 _log(f"Querying Perplexity Search API for '{query}' ({from_date} to {to_date})")
817
818 data = http.post(
819 PERPLEXITY_SEARCH_URL,
820 payload,
821 headers=headers,
822 timeout=30,
823 retries=1,
824 )
825 results = data.get("results") or []
826 if not isinstance(results, list):
827 results = []
828
829 items: list[dict[str, Any]] = []
830 for index, result in enumerate(results):
831 if not isinstance(result, dict):
832 continue
833 url = str(result.get("url") or "").strip()
834 if not url:
835 continue
836 items.append(
837 {
838 "id": f"PXS{index + 1}",
839 "title": result.get("title") or _domain(url),
840 "url": url,
841 "source_domain": _domain(url),
842 "snippet": result.get("snippet") or "",
843 "date": result.get("date"),
844 "relevance": max(0.55, 0.85 - (index * 0.03)),
845 "why_relevant": f"Ranked by Perplexity Search API for '{query}'",
846 "engagement": {},
847 "metadata": {
848 "last_updated": result.get("last_updated"),
849 "perplexity_search_id": data.get("id"),
850 },
851 }
852 )
853
854 artifact = {
855 "label": "perplexity",
856 "provider": "perplexity",
857 "mode": PERPLEXITY_MODE_SEARCH,
858 "endpoint": "search",
859 "query": query,
860 "resultCount": len(items),
861 "request": {key: value for key, value in payload.items() if key != "query"},
862 "responseId": data.get("id"),
863 "serverTime": data.get("server_time"),
864 }
865 _log(f"Got {len(items)} Search API results")
866 return items, artifact
867
868
869 def _agent_failure_artifact(
870 query: str,
871 deep: bool,
872 selection: dict[str, Any],
873 *,
874 error: str,
875 metadata: dict[str, Any] | None = None,
876 ) -> dict[str, Any]:
877 return {
878 "label": "perplexity",
879 "provider": "perplexity",
880 "mode": PERPLEXITY_MODE_AGENT,
881 "endpoint": "agent-background" if deep else "agent",
882 "deep": deep,
883 "query": query,
884 "error": error,
885 "synthesisLength": 0,
886 "citationCount": 0,
887 **selection,
888 **(metadata or {}),
889 }
890
891
892 def _agent_result(
893 query: str,
894 date_range: tuple[str, str],
895 deep: bool,
896 data: dict[str, Any],
897 selection: dict[str, Any],
898 background_metadata: dict[str, Any] | None = None,
899 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
900 _, to_date = date_range
901 status = str(data.get("status") or "").lower()
902 if status and status != "completed":
903 metadata: dict[str, Any] = {
904 "responseId": data.get("id"),
905 "status": data.get("status"),
906 "servedModel": data.get("model"),
907 "usage": _usage(data),
908 "outputTypes": _output_types(data),
909 }
910 message = _safe_error_message(data)
911 if message:
912 metadata["agentErrorMessage"] = message
913 incomplete_reason = _safe_incomplete_reason(data)
914 if incomplete_reason:
915 metadata["incompleteReason"] = incomplete_reason
916 if background_metadata:
917 metadata.update(background_metadata)
918 return [], _agent_failure_artifact(
919 query,
920 deep,
921 selection,
922 error=status,
923 metadata=metadata,
924 )
925
926 synthesis = _output_text(data)
927 citations = _extract_agent_citations(data)
928 if not synthesis:
929 _log("Empty Agent API synthesis")
930 return [], _agent_failure_artifact(
931 query,
932 deep,
933 selection,
934 error="empty_synthesis",
935 metadata={
936 "responseId": data.get("id"),
937 "status": data.get("status"),
938 "servedModel": data.get("model"),
939 "usage": _usage(data),
940 "outputTypes": _output_types(data),
941 **(background_metadata or {}),
942 },
943 )
944
945 _log(f"Got Agent API synthesis ({len(synthesis)} chars) with {len(citations)} citations")
946 title_mode = "Deep Research" if deep else "Agent"
947 items: list[dict[str, Any]] = [
948 {
949 "id": "PX1",
950 "title": f"Perplexity {title_mode}: {query}",
951 "url": "",
952 "source_domain": "perplexity.ai",
953 "snippet": synthesis[:2000],
954 "date": to_date,
955 "relevance": 0.9,
956 "why_relevant": f"AI synthesis of recent activity for '{query}'",
957 "engagement": {"citations": len(citations)},
958 "metadata": {
959 "citations": citations,
960 "usage": _usage(data),
961 "perplexity_response_id": data.get("id"),
962 },
963 }
964 ]
965 for index, citation in enumerate(citations):
966 items.append(
967 {
968 "id": f"PX{index + 2}",
969 "title": citation["title"] or _domain(citation["url"]),
970 "url": citation["url"],
971 "source_domain": _domain(citation["url"]),
972 "snippet": citation.get("snippet") or "",
973 "date": citation.get("date"),
974 "relevance": 0.7,
975 "why_relevant": f"Cited in Perplexity synthesis for '{query}'",
976 "engagement": {"citations": 1},
977 "metadata": {"citations": [citation]},
978 }
979 )
980
981 artifact: dict[str, Any] = {
982 "label": "perplexity",
983 "provider": "perplexity",
984 "mode": PERPLEXITY_MODE_AGENT,
985 "endpoint": "agent-background" if deep else "agent",
986 "deep": deep,
987 "query": query,
988 "synthesisLength": len(synthesis),
989 "citationCount": len(citations),
990 "responseId": data.get("id"),
991 "status": data.get("status"),
992 "servedModel": data.get("model"),
993 "usage": _usage(data),
994 "outputTypes": _output_types(data),
995 **selection,
996 }
997 if background_metadata:
998 artifact.update(background_metadata)
999 return items, artifact
1000
1001
1002 def _agent_search(
1003 query: str,
1004 date_range: tuple[str, str],
1005 config: dict[str, Any],
1006 api_key: str,
1007 deep: bool,
1008 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
1009 from_date, to_date = date_range
1010 prompt = (
1011 f"What has been happening with {query} between {from_date} and {to_date}? "
1012 "Include specific dates, names, numbers, and sources."
1013 )
1014 payload, selection = _build_agent_payload(prompt, date_range, config, deep)
1015 headers = {
1016 "Authorization": f"Bearer {api_key}",
1017 "Content-Type": "application/json",
1018 }
1019 _log(f"Querying Perplexity Agent API for '{query}' ({from_date} to {to_date})")
1020
1021 try:
1022 if deep:
1023 data, background_metadata = _poll_agent_background(payload, headers, config)
1024 else:
1025 data = http.post(
1026 PERPLEXITY_AGENT_URL,
1027 payload,
1028 headers=headers,
1029 timeout=_agent_timeout(config),
1030 retries=1,
1031 )
1032 background_metadata = None
1033 except AgentBackgroundTimeout as exc:
1034 _log(f"Agent background request timed out: {exc}")
1035 return [], _agent_failure_artifact(
1036 query,
1037 deep,
1038 selection,
1039 error="timeout",
1040 metadata=exc.metadata,
1041 )
1042 except AgentBackgroundFailed as exc:
1043 _log(f"Agent background request failed: {exc}")
1044 return [], _agent_failure_artifact(
1045 query,
1046 deep,
1047 selection,
1048 error="failed",
1049 metadata=exc.metadata,
1050 )
1051 except AgentBackgroundPollError as exc:
1052 _log(f"Agent background poll failed: {exc}")
1053 return [], _agent_failure_artifact(
1054 query,
1055 deep,
1056 selection,
1057 error="poll_error",
1058 metadata=exc.metadata,
1059 )
1060
1061 return _agent_result(
1062 query,
1063 date_range,
1064 deep,
1065 data,
1066 selection,
1067 background_metadata,
1068 )
1069
1070
1071 def _openrouter_sonar_search(
1072 query: str,
1073 date_range: tuple[str, str],
1074 api_key: str,
1075 deep: bool,
1076 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
1077 """Preserve the pre-Agent OpenRouter Sonar compatibility path."""
1078 from_date, to_date = date_range
1079 model = (
1080 OPENROUTER_MODEL_DEEP_RESEARCH
1081 if deep
1082 else OPENROUTER_MODEL_SONAR_PRO
1083 )
1084 prompt = (
1085 f"What has been happening with {query} between {from_date} and {to_date}? "
1086 "Include specific dates, names, numbers, and sources."
1087 )
1088 payload = {
1089 "model": model,
1090 "messages": [{"role": "user", "content": prompt}],
1091 }
1092 headers = {
1093 "Authorization": f"Bearer {api_key}",
1094 "Content-Type": "application/json",
1095 }
1096 _log(f"Querying OpenRouter {model} for '{query}' ({from_date} to {to_date})")
1097 # Honor OPENROUTER_BASE_URL like the planner/rerank client does (providers.py).
1098 url = providers.resolve_endpoint("OPENROUTER_BASE_URL", OPENROUTER_URL)
1099 data = http.post(
1100 url,
1101 payload,
1102 headers=headers,
1103 timeout=120 if deep else 30,
1104 retries=1,
1105 bypass_proxy=providers.is_loopback_http_endpoint(url),
1106 )
1107
1108 choices = data.get("choices")
1109 if not isinstance(choices, list) or not choices:
1110 return [], {
1111 "label": "perplexity",
1112 "provider": "openrouter",
1113 "mode": PERPLEXITY_MODE_SONAR,
1114 "endpoint": "openrouter-chat-completions",
1115 "model": model,
1116 "deep": deep,
1117 "query": query,
1118 "error": "empty_choices",
1119 "responseId": data.get("id"),
1120 "servedModel": data.get("model") or model,
1121 "usage": _usage(data),
1122 }
1123
1124 choice = choices[0] if isinstance(choices[0], dict) else {}
1125 message = choice.get("message")
1126 message = message if isinstance(message, dict) else {}
1127 synthesis = message.get("content")
1128 synthesis = synthesis if isinstance(synthesis, str) else ""
1129 if not synthesis:
1130 return [], {
1131 "label": "perplexity",
1132 "provider": "openrouter",
1133 "mode": PERPLEXITY_MODE_SONAR,
1134 "endpoint": "openrouter-chat-completions",
1135 "model": model,
1136 "deep": deep,
1137 "query": query,
1138 "error": "empty_synthesis",
1139 "responseId": data.get("id"),
1140 "servedModel": data.get("model") or model,
1141 "usage": _usage(data),
1142 }
1143
1144 citations = _extract_openrouter_citations(data, choice)
1145 title_mode = "Deep Research" if deep else "Sonar"
1146 items: list[dict[str, Any]] = [
1147 {
1148 "id": "PX1",
1149 "title": f"Perplexity {title_mode}: {query}",
1150 "url": "",
1151 "source_domain": "perplexity.ai",
1152 "snippet": synthesis[:2000],
1153 "date": to_date,
1154 "relevance": 0.9,
1155 "why_relevant": f"AI synthesis of recent activity for '{query}'",
1156 "engagement": {"citations": len(citations)},
1157 "metadata": {
1158 "citations": citations,
1159 "usage": _usage(data),
1160 "openrouter_response_id": data.get("id"),
1161 },
1162 }
1163 ]
1164 for index, citation in enumerate(citations):
1165 items.append(
1166 {
1167 "id": f"PX{index + 2}",
1168 "title": citation["title"] or _domain(citation["url"]),
1169 "url": citation["url"],
1170 "source_domain": _domain(citation["url"]),
1171 "snippet": citation.get("snippet") or "",
1172 "date": citation.get("date"),
1173 "relevance": 0.7,
1174 "why_relevant": f"Cited in Perplexity synthesis for '{query}'",
1175 "engagement": {"citations": 1},
1176 "metadata": {"citations": [citation]},
1177 }
1178 )
1179
1180 return items, {
1181 "label": "perplexity",
1182 "provider": "openrouter",
1183 "mode": PERPLEXITY_MODE_SONAR,
1184 "endpoint": "openrouter-chat-completions",
1185 "model": model,
1186 "deep": deep,
1187 "query": query,
1188 "synthesisLength": len(synthesis),
1189 "citationCount": len(citations),
1190 "responseId": data.get("id"),
1191 "servedModel": data.get("model") or model,
1192 "usage": _usage(data),
1193 }
1194
1195
1196 def _merge_agent_and_search(
1197 agent_items: list[dict[str, Any]],
1198 search_items: list[dict[str, Any]],
1199 ) -> list[dict[str, Any]]:
1200 if not agent_items:
1201 return search_items
1202 merged = agent_items[:1]
1203 seen_urls = {item.get("url") for item in merged if item.get("url")}
1204 for item in [*search_items, *agent_items[1:]]:
1205 url = item.get("url")
1206 if url and url in seen_urls:
1207 continue
1208 if url:
1209 seen_urls.add(url)
1210 merged.append(item)
1211 return merged
1212
1213
1214 def _top_level_failure(
1215 query: str,
1216 mode: str,
1217 deep: bool,
1218 exc: Exception,
1219 provider: str = "perplexity",
1220 requested_search_type: str | None = None,
1221 ) -> dict[str, Any]:
1222 artifact = _error_artifact(exc)
1223 if provider == "perplexity" and requested_search_type is not None:
1224 artifact["requested_search_type"] = requested_search_type
1225 if provider == "openrouter":
1226 endpoint = "openrouter-chat-completions"
1227 elif deep:
1228 endpoint = "agent-background"
1229 elif mode == PERPLEXITY_MODE_SEARCH:
1230 endpoint = "search"
1231 else:
1232 endpoint = "agent"
1233 artifact.update(
1234 {
1235 "label": "perplexity",
1236 "provider": provider,
1237 "mode": mode,
1238 "endpoint": endpoint,
1239 "deep": deep,
1240 "query": query,
1241 }
1242 )
1243 return artifact
1244
1245
1246 def search(
1247 query: str,
1248 date_range: tuple[str, str],
1249 config: dict[str, Any],
1250 deep: bool = False,
1251 ) -> tuple[list[dict[str, Any]], dict[str, Any]]:
1252 """Search through Perplexity's Agent API or raw Search API.
1253
1254 Normal synthesis uses the controlled Agent profile. Search API mode remains
1255 available for raw ranked rows. Deep Research is a dynamic high-preset
1256 background run and requires an explicit --deep-research invocation.
1257 """
1258 resolved = _provider(config)
1259 if not resolved:
1260 _log(
1261 "No PERPLEXITY_API_KEY or OPENROUTER_API_KEY configured, skipping"
1262 )
1263 return [], {}
1264 provider, api_key = resolved
1265
1266 mode = _mode(config, deep, provider)
1267 search_type = None
1268 try:
1269 if provider == "openrouter":
1270 # Sonar ignores the direct-only setting, so never validate it here:
1271 # an unusable value must not block an otherwise working search.
1272 if _config_text(config, "LAST30DAYS_PERPLEXITY_SEARCH_TYPE"):
1273 _log("LAST30DAYS_PERPLEXITY_SEARCH_TYPE requires PERPLEXITY_API_KEY; "
1274 "it does not change OpenRouter Sonar search")
1275 result = _openrouter_sonar_search(
1276 query,
1277 date_range,
1278 api_key,
1279 deep,
1280 )
1281 if deep:
1282 _log_deep_receipt(result[1])
1283 return result
1284 search_type = _search_type(config)
1285 if mode == PERPLEXITY_MODE_SEARCH:
1286 return _search_api(query, date_range, config, api_key)
1287 if mode == PERPLEXITY_MODE_BOTH:
1288 search_items: list[dict[str, Any]] = []
1289 agent_items: list[dict[str, Any]] = []
1290 search_artifact: dict[str, Any] = {}
1291 agent_artifact: dict[str, Any] = {}
1292 try:
1293 search_items, search_artifact = _search_api(
1294 query,
1295 date_range,
1296 config,
1297 api_key,
1298 )
1299 except Exception as exc:
1300 _log(f"Search API leg failed in both mode: {exc}")
1301 search_artifact = _error_artifact(exc)
1302 if search_type is not None:
1303 search_artifact["requested_search_type"] = search_type
1304 try:
1305 agent_items, agent_artifact = _agent_search(
1306 query,
1307 date_range,
1308 config,
1309 api_key,
1310 deep=False,
1311 )
1312 except Exception as exc:
1313 _log(f"Agent API leg failed in both mode: {exc}")
1314 agent_artifact = _error_artifact(exc)
1315 if search_type is not None:
1316 agent_artifact["requested_search_type"] = search_type
1317 items = _merge_agent_and_search(agent_items, search_items)
1318 return items, {
1319 "label": "perplexity",
1320 "provider": "perplexity",
1321 "mode": PERPLEXITY_MODE_BOTH,
1322 "query": query,
1323 "search": search_artifact,
1324 "agent": agent_artifact,
1325 "itemCount": len(items),
1326 }
1327 result = _agent_search(query, date_range, config, api_key, deep)
1328 if deep:
1329 _log_deep_receipt(result[1])
1330 return result
1331 except http.HTTPError as exc:
1332 if exc.status_code == 401:
1333 _log(f"Invalid {provider} API key (401)")
1334 elif exc.status_code == 429:
1335 _log(f"Rate limited by {provider} (429)")
1336 else:
1337 _log(f"HTTP error: {exc}")
1338 artifact = _top_level_failure(
1339 query,
1340 mode,
1341 deep,
1342 exc,
1343 provider=provider,
1344 requested_search_type=search_type,
1345 )
1346 if deep:
1347 _log_deep_receipt(artifact)
1348 return [], artifact
1349 except TimeoutError as exc:
1350 _log(f"Request timed out: {exc}")
1351 artifact = _top_level_failure(
1352 query,
1353 mode,
1354 deep,
1355 exc,
1356 provider=provider,
1357 requested_search_type=search_type,
1358 )
1359 if deep:
1360 _log_deep_receipt(artifact)
1361 return [], artifact
1362 except Exception as exc:
1363 _log(f"Request failed: {exc}")
1364 artifact = _top_level_failure(
1365 query,
1366 mode,
1367 deep,
1368 exc,
1369 provider=provider,
1370 requested_search_type=search_type,
1371 )
1372 if deep:
1373 _log_deep_receipt(artifact)
1374 return [], artifact
1375
1375 lines PYTHON