| 1 | import os |
| 2 | import unittest |
| 3 | from threading import Event |
| 4 | from unittest.mock import patch |
| 5 | |
| 6 | from lib import perplexity |
| 7 | |
| 8 | |
| 9 | def _agent_response( |
| 10 | text: str = "Agent synthesis", |
| 11 | *, |
| 12 | response_id: str = "agent-1", |
| 13 | status: str = "completed", |
| 14 | model: str = "perplexity/sonar", |
| 15 | citations: list[dict] | None = None, |
| 16 | include_output_text: bool = True, |
| 17 | ) -> dict: |
| 18 | citation_parts = [ |
| 19 | { |
| 20 | "type": "output_text", |
| 21 | "text": text, |
| 22 | "annotations": [ |
| 23 | { |
| 24 | "url_citation": { |
| 25 | "url": citation["url"], |
| 26 | "title": citation.get("title", ""), |
| 27 | } |
| 28 | } |
| 29 | for citation in citations or [] |
| 30 | ], |
| 31 | } |
| 32 | ] |
| 33 | response = { |
| 34 | "id": response_id, |
| 35 | "status": status, |
| 36 | "model": model, |
| 37 | "output": [ |
| 38 | {"type": "message", "content": citation_parts}, |
| 39 | {"type": "search_results", "results": citations or []}, |
| 40 | ], |
| 41 | "usage": {"total_tokens": 123}, |
| 42 | } |
| 43 | if include_output_text: |
| 44 | response["output_text"] = text |
| 45 | return response |
| 46 | |
| 47 | |
| 48 | class PerplexityAgentTests(unittest.TestCase): |
| 49 | def setUp(self): |
| 50 | # The default-URL assertions must not depend on an ambient override. |
| 51 | env_patch = patch.dict("os.environ") |
| 52 | env_patch.start() |
| 53 | self.addCleanup(env_patch.stop) |
| 54 | os.environ.pop("OPENROUTER_BASE_URL", None) |
| 55 | |
| 56 | def test_controlled_agent_uses_direct_key_and_explicit_web_search(self): |
| 57 | citations = [ |
| 58 | { |
| 59 | "title": "Example A", |
| 60 | "url": "https://example.com/a", |
| 61 | "date": "2026-06-01", |
| 62 | "snippet": "Direct source snippet", |
| 63 | } |
| 64 | ] |
| 65 | response = _agent_response("Direct synthesis", citations=citations) |
| 66 | config = { |
| 67 | "PERPLEXITY_API_KEY": "pplx-test", |
| 68 | "OPENROUTER_API_KEY": "or-test", |
| 69 | "LAST30DAYS_PERPLEXITY_MAX_RESULTS": "3", |
| 70 | "LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE": "low", |
| 71 | "LAST30DAYS_PERPLEXITY_COUNTRY": "us", |
| 72 | "LAST30DAYS_PERPLEXITY_DOMAIN_FILTER": "example.com,example.org", |
| 73 | "LAST30DAYS_PERPLEXITY_RECENCY_FILTER": "year", |
| 74 | "LAST30DAYS_PERPLEXITY_REASONING_EFFORT": "high", |
| 75 | "LAST30DAYS_PERPLEXITY_AGENT_MAX_STEPS": "4", |
| 76 | } |
| 77 | with patch("lib.perplexity.http.post", return_value=response) as post: |
| 78 | items, artifact = perplexity.search( |
| 79 | "test topic", |
| 80 | ("2026-05-01", "2026-06-01"), |
| 81 | config, |
| 82 | ) |
| 83 | |
| 84 | url, payload = post.call_args.args[:2] |
| 85 | headers = post.call_args.kwargs["headers"] |
| 86 | tool = payload["tools"][0] |
| 87 | self.assertEqual(perplexity.PERPLEXITY_AGENT_URL, url) |
| 88 | self.assertEqual("Bearer pplx-test", headers["Authorization"]) |
| 89 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 90 | self.assertEqual("perplexity/sonar", payload["model"]) |
| 91 | self.assertIn("input", payload) |
| 92 | self.assertIn("instructions", payload) |
| 93 | self.assertEqual(4, payload["max_steps"]) |
| 94 | self.assertEqual({"effort": "high"}, payload["reasoning"]) |
| 95 | self.assertEqual({"type": "web_search"}, payload["tool_choice"]) |
| 96 | self.assertEqual("web_search", tool["type"]) |
| 97 | self.assertEqual(3, tool["max_results"]) |
| 98 | self.assertEqual("low", tool["search_context_size"]) |
| 99 | self.assertEqual({"country": "US"}, tool["user_location"]) |
| 100 | self.assertEqual( |
| 101 | ["example.com", "example.org"], |
| 102 | tool["filters"]["search_domain_filter"], |
| 103 | ) |
| 104 | self.assertEqual("05/01/2026", tool["filters"]["search_after_date_filter"]) |
| 105 | self.assertEqual("06/01/2026", tool["filters"]["search_before_date_filter"]) |
| 106 | self.assertNotIn("search_recency_filter", tool["filters"]) |
| 107 | self.assertNotIn("preset", payload) |
| 108 | |
| 109 | self.assertEqual("perplexity", artifact["provider"]) |
| 110 | self.assertEqual("agent", artifact["mode"]) |
| 111 | self.assertEqual("agent", artifact["endpoint"]) |
| 112 | self.assertEqual("perplexity/sonar", artifact["model"]) |
| 113 | self.assertEqual(perplexity.PERPLEXITY_CONTROLLED_PROFILE, artifact["profile"]) |
| 114 | self.assertFalse(artifact["dynamicPreset"]) |
| 115 | self.assertEqual("agent-1", artifact["responseId"]) |
| 116 | self.assertEqual("perplexity/sonar", artifact["servedModel"]) |
| 117 | self.assertEqual(["message", "search_results"], artifact["outputTypes"]) |
| 118 | self.assertNotIn("input", artifact["request"]) |
| 119 | self.assertNotIn("instructions", artifact["request"]) |
| 120 | self.assertEqual({"effort": "high"}, artifact["request"]["reasoning"]) |
| 121 | self.assertEqual( |
| 122 | {"type": "web_search"}, |
| 123 | artifact["request"]["tool_choice"], |
| 124 | ) |
| 125 | self.assertEqual("Example A", items[1]["title"]) |
| 126 | self.assertEqual("Direct source snippet", items[1]["snippet"]) |
| 127 | |
| 128 | def test_legacy_sonar_mode_is_an_agent_alias(self): |
| 129 | response = _agent_response() |
| 130 | with patch("lib.perplexity.http.post", return_value=response) as post: |
| 131 | _, artifact = perplexity.search( |
| 132 | "test topic", |
| 133 | ("2026-05-01", "2026-06-01"), |
| 134 | { |
| 135 | "PERPLEXITY_API_KEY": "pplx-test", |
| 136 | "LAST30DAYS_PERPLEXITY_MODE": "sonar", |
| 137 | "LAST30DAYS_PERPLEXITY_MODEL": "sonar-pro", |
| 138 | }, |
| 139 | ) |
| 140 | |
| 141 | self.assertEqual(perplexity.PERPLEXITY_AGENT_URL, post.call_args.args[0]) |
| 142 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 143 | self.assertEqual("perplexity/sonar", post.call_args.args[1]["model"]) |
| 144 | self.assertEqual("agent", artifact["mode"]) |
| 145 | |
| 146 | def test_controlled_agent_max_steps_clamps_to_local_safety_limit(self): |
| 147 | payload, _ = perplexity._build_agent_payload( |
| 148 | "test topic", |
| 149 | ("2026-05-01", "2026-06-01"), |
| 150 | {"LAST30DAYS_PERPLEXITY_AGENT_MAX_STEPS": "100"}, |
| 151 | deep=False, |
| 152 | ) |
| 153 | |
| 154 | self.assertEqual(15, payload["max_steps"]) |
| 155 | |
| 156 | def test_explicit_anthropic_model_gets_required_output_token_budget(self): |
| 157 | payload, selection = perplexity._build_agent_payload( |
| 158 | "test topic", |
| 159 | ("2026-05-01", "2026-06-01"), |
| 160 | { |
| 161 | "LAST30DAYS_PERPLEXITY_AGENT_MODEL": "anthropic/claude-sonnet-4-6", |
| 162 | "LAST30DAYS_PERPLEXITY_AGENT_MAX_OUTPUT_TOKENS": "8192", |
| 163 | }, |
| 164 | deep=False, |
| 165 | ) |
| 166 | |
| 167 | self.assertEqual(8192, payload["max_output_tokens"]) |
| 168 | self.assertEqual(8192, selection["request"]["max_output_tokens"]) |
| 169 | |
| 170 | def test_non_anthropic_model_omits_output_token_override(self): |
| 171 | payload, _ = perplexity._build_agent_payload( |
| 172 | "test topic", |
| 173 | ("2026-05-01", "2026-06-01"), |
| 174 | {}, |
| 175 | deep=False, |
| 176 | ) |
| 177 | |
| 178 | self.assertNotIn("max_output_tokens", payload) |
| 179 | |
| 180 | def test_explicit_agent_preset_is_marked_dynamic(self): |
| 181 | response = _agent_response(model="openai/gpt-5.6-luna") |
| 182 | with patch("lib.perplexity.http.post", return_value=response) as post: |
| 183 | _, artifact = perplexity.search( |
| 184 | "test topic", |
| 185 | ("2026-05-01", "2026-06-01"), |
| 186 | { |
| 187 | "PERPLEXITY_API_KEY": "pplx-test", |
| 188 | "LAST30DAYS_PERPLEXITY_AGENT_PRESET": "low", |
| 189 | }, |
| 190 | ) |
| 191 | |
| 192 | payload = post.call_args.args[1] |
| 193 | self.assertEqual("low", payload["preset"]) |
| 194 | self.assertIn("input", payload) |
| 195 | self.assertNotIn("model", payload) |
| 196 | self.assertEqual("web_search", payload["tools"][0]["type"]) |
| 197 | self.assertEqual(10, payload["tools"][0]["max_results"]) |
| 198 | self.assertTrue(artifact["dynamicPreset"]) |
| 199 | self.assertEqual("low", artifact["preset"]) |
| 200 | self.assertEqual("openai/gpt-5.6-luna", artifact["servedModel"]) |
| 201 | self.assertEqual(perplexity.PERPLEXITY_PRESET_PROFILE, artifact["profile"]) |
| 202 | |
| 203 | def test_agent_falls_back_to_message_output_when_output_text_is_missing(self): |
| 204 | citations = [ |
| 205 | { |
| 206 | "title": "Example A", |
| 207 | "url": "https://example.com/a", |
| 208 | "snippet": "Direct source snippet", |
| 209 | } |
| 210 | ] |
| 211 | response = _agent_response( |
| 212 | "Message-only synthesis", |
| 213 | citations=citations, |
| 214 | include_output_text=False, |
| 215 | ) |
| 216 | with patch("lib.perplexity.http.post", return_value=response): |
| 217 | items, artifact = perplexity.search( |
| 218 | "test topic", |
| 219 | ("2026-05-01", "2026-06-01"), |
| 220 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 221 | ) |
| 222 | |
| 223 | self.assertEqual("Message-only synthesis", items[0]["snippet"]) |
| 224 | self.assertEqual(1, artifact["citationCount"]) |
| 225 | |
| 226 | def test_malformed_agent_output_returns_safe_empty_artifact(self): |
| 227 | response = { |
| 228 | "id": "agent-empty", |
| 229 | "status": "completed", |
| 230 | "model": "perplexity/sonar", |
| 231 | "output": [{"type": "function_call", "arguments": "untrusted trace"}], |
| 232 | "usage": {"total_tokens": 2}, |
| 233 | } |
| 234 | with patch("lib.perplexity.http.post", return_value=response): |
| 235 | items, artifact = perplexity.search( |
| 236 | "test topic", |
| 237 | ("2026-05-01", "2026-06-01"), |
| 238 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 239 | ) |
| 240 | |
| 241 | self.assertEqual([], items) |
| 242 | self.assertEqual("empty_synthesis", artifact["error"]) |
| 243 | self.assertEqual("perplexity/sonar", artifact["servedModel"]) |
| 244 | self.assertEqual(["function_call"], artifact["outputTypes"]) |
| 245 | self.assertNotIn("arguments", artifact) |
| 246 | |
| 247 | def test_sync_terminal_failure_keeps_safe_response_metadata(self): |
| 248 | response = { |
| 249 | "id": "agent-failed", |
| 250 | "status": "failed", |
| 251 | "error": {"message": "Provider safely rejected this request"}, |
| 252 | "output": [{"type": "function_call", "arguments": "raw tool trace"}], |
| 253 | "usage": {"total_tokens": 7}, |
| 254 | } |
| 255 | with patch("lib.perplexity.http.post", return_value=response): |
| 256 | items, artifact = perplexity.search( |
| 257 | "test topic", |
| 258 | ("2026-05-01", "2026-06-01"), |
| 259 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 260 | ) |
| 261 | |
| 262 | self.assertEqual([], items) |
| 263 | self.assertEqual("failed", artifact["error"]) |
| 264 | self.assertEqual("agent-failed", artifact["responseId"]) |
| 265 | self.assertEqual("failed", artifact["status"]) |
| 266 | self.assertEqual("Provider safely rejected this request", artifact["agentErrorMessage"]) |
| 267 | self.assertEqual({"total_tokens": 7}, artifact["usage"]) |
| 268 | self.assertEqual(["function_call"], artifact["outputTypes"]) |
| 269 | self.assertNotIn("arguments", artifact) |
| 270 | |
| 271 | def test_sync_incomplete_response_keeps_safe_reason(self): |
| 272 | response = { |
| 273 | "id": "agent-incomplete", |
| 274 | "status": "incomplete", |
| 275 | "incomplete_details": {"reason": "max_output_tokens"}, |
| 276 | "output": [], |
| 277 | "usage": {"total_tokens": 11}, |
| 278 | } |
| 279 | with patch("lib.perplexity.http.post", return_value=response): |
| 280 | items, artifact = perplexity.search( |
| 281 | "test topic", |
| 282 | ("2026-05-01", "2026-06-01"), |
| 283 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 284 | ) |
| 285 | |
| 286 | self.assertEqual([], items) |
| 287 | self.assertEqual("incomplete", artifact["error"]) |
| 288 | self.assertEqual("max_output_tokens", artifact["incompleteReason"]) |
| 289 | self.assertNotIn("incomplete_details", artifact) |
| 290 | |
| 291 | def test_openrouter_only_config_uses_sonar_fallback(self): |
| 292 | response = { |
| 293 | "id": "openrouter-1", |
| 294 | "model": "perplexity/sonar-pro", |
| 295 | "choices": [ |
| 296 | { |
| 297 | "message": { |
| 298 | "content": "OpenRouter fallback synthesis", |
| 299 | "annotations": [ |
| 300 | { |
| 301 | "url_citation": { |
| 302 | "url": "https://example.com/openrouter", |
| 303 | "title": "OpenRouter citation", |
| 304 | } |
| 305 | } |
| 306 | ], |
| 307 | } |
| 308 | } |
| 309 | ], |
| 310 | "usage": {"total_tokens": 42}, |
| 311 | } |
| 312 | with patch("lib.perplexity.http.post", return_value=response) as post, patch( |
| 313 | "lib.perplexity.http.get" |
| 314 | ) as get: |
| 315 | items, artifact = perplexity.search( |
| 316 | "test topic", |
| 317 | ("2026-05-01", "2026-06-01"), |
| 318 | {"OPENROUTER_API_KEY": "or-test"}, |
| 319 | ) |
| 320 | |
| 321 | url, payload = post.call_args.args[:2] |
| 322 | self.assertEqual(perplexity.OPENROUTER_URL, url) |
| 323 | self.assertEqual("perplexity/sonar-pro", payload["model"]) |
| 324 | self.assertEqual("Bearer or-test", post.call_args.kwargs["headers"]["Authorization"]) |
| 325 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 326 | get.assert_not_called() |
| 327 | self.assertEqual("openrouter", artifact["provider"]) |
| 328 | self.assertEqual("sonar", artifact["mode"]) |
| 329 | self.assertEqual("openrouter-chat-completions", artifact["endpoint"]) |
| 330 | self.assertEqual("OpenRouter fallback synthesis", items[0]["snippet"]) |
| 331 | self.assertEqual("OpenRouter citation", items[1]["title"]) |
| 332 | |
| 333 | def test_openrouter_sonar_fallback_honors_base_url_override(self): |
| 334 | response = {"id": "openrouter-2", "model": "perplexity/sonar-pro", |
| 335 | "choices": [{"message": {"content": "ok"}}]} |
| 336 | endpoint = "https://gateway.test/v1/chat/completions" |
| 337 | for override in ("https://gateway.test/v1", endpoint): |
| 338 | for deep, model, timeout in ( |
| 339 | (False, "perplexity/sonar-pro", 30), |
| 340 | (True, "perplexity/sonar-deep-research", 120), |
| 341 | ): |
| 342 | with self.subTest(override=override, deep=deep), patch.dict( |
| 343 | "os.environ", {"OPENROUTER_BASE_URL": override} |
| 344 | ), patch("lib.perplexity.http.post", return_value=response) as post: |
| 345 | items, artifact = perplexity.search( |
| 346 | "test topic", |
| 347 | ("2026-05-01", "2026-06-01"), |
| 348 | {"OPENROUTER_API_KEY": "or-test"}, |
| 349 | deep=deep, |
| 350 | ) |
| 351 | |
| 352 | post.assert_called_once() |
| 353 | url, payload = post.call_args.args |
| 354 | self.assertEqual(endpoint, url) |
| 355 | self.assertEqual(model, payload["model"]) |
| 356 | self.assertIn("test topic", payload["messages"][0]["content"]) |
| 357 | self.assertEqual("Bearer or-test", post.call_args.kwargs["headers"]["Authorization"]) |
| 358 | self.assertEqual(timeout, post.call_args.kwargs["timeout"]) |
| 359 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 360 | self.assertEqual("openrouter", artifact["provider"]) |
| 361 | self.assertEqual("ok", items[0]["snippet"]) |
| 362 | |
| 363 | def test_openrouter_search_mode_degrades_to_sonar_fallback(self): |
| 364 | response = { |
| 365 | "id": "openrouter-2", |
| 366 | "model": "perplexity/sonar-pro", |
| 367 | "choices": [{"message": {"content": "Fallback synthesis"}}], |
| 368 | } |
| 369 | with patch("lib.perplexity.http.post", return_value=response) as post: |
| 370 | _, artifact = perplexity.search( |
| 371 | "test topic", |
| 372 | ("2026-05-01", "2026-06-01"), |
| 373 | { |
| 374 | "OPENROUTER_API_KEY": "or-test", |
| 375 | "LAST30DAYS_PERPLEXITY_MODE": "search", |
| 376 | }, |
| 377 | ) |
| 378 | |
| 379 | self.assertEqual(perplexity.OPENROUTER_URL, post.call_args.args[0]) |
| 380 | self.assertEqual("openrouter", artifact["provider"]) |
| 381 | self.assertEqual("sonar", artifact["mode"]) |
| 382 | |
| 383 | def test_openrouter_deep_research_keeps_synchronous_legacy_fallback(self): |
| 384 | response = { |
| 385 | "id": "openrouter-deep-1", |
| 386 | "model": "perplexity/sonar-deep-research", |
| 387 | "choices": [{"message": {"content": "Deep fallback synthesis"}}], |
| 388 | } |
| 389 | with patch("lib.perplexity.http.post", return_value=response) as post, patch( |
| 390 | "lib.perplexity.http.get" |
| 391 | ) as get: |
| 392 | items, artifact = perplexity.search( |
| 393 | "test topic", |
| 394 | ("2026-05-01", "2026-06-01"), |
| 395 | {"OPENROUTER_API_KEY": "or-test"}, |
| 396 | deep=True, |
| 397 | ) |
| 398 | |
| 399 | self.assertEqual(perplexity.OPENROUTER_URL, post.call_args.args[0]) |
| 400 | self.assertEqual( |
| 401 | "perplexity/sonar-deep-research", |
| 402 | post.call_args.args[1]["model"], |
| 403 | ) |
| 404 | get.assert_not_called() |
| 405 | self.assertEqual("Deep fallback synthesis", items[0]["snippet"]) |
| 406 | self.assertTrue(artifact["deep"]) |
| 407 | self.assertEqual("openrouter", artifact["provider"]) |
| 408 | |
| 409 | def test_openrouter_failure_keeps_typed_source_receipt(self): |
| 410 | with patch( |
| 411 | "lib.perplexity.http.post", |
| 412 | side_effect=perplexity.http.HTTPError( |
| 413 | "HTTP 429: Too Many Requests", |
| 414 | status_code=429, |
| 415 | ), |
| 416 | ): |
| 417 | items, artifact = perplexity.search( |
| 418 | "test topic", |
| 419 | ("2026-05-01", "2026-06-01"), |
| 420 | {"OPENROUTER_API_KEY": "or-test"}, |
| 421 | ) |
| 422 | |
| 423 | self.assertEqual([], items) |
| 424 | self.assertEqual("openrouter", artifact["provider"]) |
| 425 | self.assertEqual("openrouter-chat-completions", artifact["endpoint"]) |
| 426 | self.assertEqual(429, artifact["statusCode"]) |
| 427 | |
| 428 | def test_search_api_mode_returns_ranked_rows_with_filters(self): |
| 429 | response = { |
| 430 | "id": "search-1", |
| 431 | "server_time": "2026-06-01T00:00:00Z", |
| 432 | "results": [ |
| 433 | { |
| 434 | "title": "Ranked result", |
| 435 | "url": "https://example.com/ranked", |
| 436 | "snippet": "Search API snippet", |
| 437 | "date": "2026-05-15", |
| 438 | "last_updated": "2026-05-20", |
| 439 | } |
| 440 | ], |
| 441 | } |
| 442 | config = { |
| 443 | "PERPLEXITY_API_KEY": "pplx-test", |
| 444 | "LAST30DAYS_PERPLEXITY_MODE": "search", |
| 445 | "LAST30DAYS_PERPLEXITY_MAX_RESULTS": "3", |
| 446 | "LAST30DAYS_PERPLEXITY_SEARCH_CONTEXT_SIZE": "low", |
| 447 | "LAST30DAYS_PERPLEXITY_COUNTRY": "us", |
| 448 | "LAST30DAYS_PERPLEXITY_DOMAIN_FILTER": "example.com,example.org", |
| 449 | "LAST30DAYS_PERPLEXITY_LANGUAGE_FILTER": "en", |
| 450 | "LAST30DAYS_PERPLEXITY_RECENCY_FILTER": "year", |
| 451 | } |
| 452 | with patch("lib.perplexity.http.post", return_value=response) as post: |
| 453 | items, artifact = perplexity.search( |
| 454 | "test topic", |
| 455 | ("2026-05-01", "2026-06-01"), |
| 456 | config, |
| 457 | ) |
| 458 | |
| 459 | url, payload = post.call_args.args[:2] |
| 460 | self.assertEqual(perplexity.PERPLEXITY_SEARCH_URL, url) |
| 461 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 462 | self.assertEqual("test topic", payload["query"]) |
| 463 | self.assertEqual(3, payload["max_results"]) |
| 464 | self.assertEqual("low", payload["search_context_size"]) |
| 465 | self.assertEqual("US", payload["country"]) |
| 466 | self.assertEqual(["example.com", "example.org"], payload["search_domain_filter"]) |
| 467 | self.assertEqual(["en"], payload["search_language_filter"]) |
| 468 | self.assertEqual("05/01/2026", payload["search_after_date_filter"]) |
| 469 | self.assertEqual("06/01/2026", payload["search_before_date_filter"]) |
| 470 | self.assertNotIn("search_recency_filter", payload) |
| 471 | self.assertEqual("search", artifact["mode"]) |
| 472 | self.assertEqual("Ranked result", items[0]["title"]) |
| 473 | self.assertEqual("2026-05-20", items[0]["metadata"]["last_updated"]) |
| 474 | |
| 475 | def test_search_api_keeps_recency_filter_when_no_exact_dates_are_available(self): |
| 476 | payload = perplexity._build_search_payload( |
| 477 | "test topic", |
| 478 | ("not-a-date", "also-not-a-date"), |
| 479 | {"LAST30DAYS_PERPLEXITY_RECENCY_FILTER": "week"}, |
| 480 | ) |
| 481 | |
| 482 | self.assertEqual("week", payload["search_recency_filter"]) |
| 483 | self.assertNotIn("search_after_date_filter", payload) |
| 484 | self.assertNotIn("search_before_date_filter", payload) |
| 485 | |
| 486 | def test_both_mode_keeps_synthesis_and_dedupes_raw_rows(self): |
| 487 | search_response = { |
| 488 | "id": "search-1", |
| 489 | "results": [ |
| 490 | { |
| 491 | "title": "Duplicate ranked result", |
| 492 | "url": "https://example.com/a", |
| 493 | "snippet": "Raw row", |
| 494 | "date": "2026-05-15", |
| 495 | }, |
| 496 | { |
| 497 | "title": "Unique ranked result", |
| 498 | "url": "https://example.com/unique", |
| 499 | "snippet": "Unique raw row", |
| 500 | "date": "2026-05-16", |
| 501 | }, |
| 502 | ], |
| 503 | } |
| 504 | agent_response = _agent_response( |
| 505 | citations=[ |
| 506 | { |
| 507 | "title": "Citation result", |
| 508 | "url": "https://example.com/a", |
| 509 | "snippet": "Citation row", |
| 510 | "date": "2026-05-15", |
| 511 | } |
| 512 | ] |
| 513 | ) |
| 514 | with patch( |
| 515 | "lib.perplexity.http.post", |
| 516 | side_effect=[search_response, agent_response], |
| 517 | ) as post: |
| 518 | items, artifact = perplexity.search( |
| 519 | "test topic", |
| 520 | ("2026-05-01", "2026-06-01"), |
| 521 | { |
| 522 | "PERPLEXITY_API_KEY": "pplx-test", |
| 523 | "LAST30DAYS_PERPLEXITY_MODE": "both", |
| 524 | }, |
| 525 | ) |
| 526 | |
| 527 | self.assertEqual(perplexity.PERPLEXITY_SEARCH_URL, post.call_args_list[0].args[0]) |
| 528 | self.assertEqual(perplexity.PERPLEXITY_AGENT_URL, post.call_args_list[1].args[0]) |
| 529 | self.assertEqual("both", artifact["mode"]) |
| 530 | self.assertEqual(3, artifact["itemCount"]) |
| 531 | self.assertEqual("perplexity.ai", items[0]["source_domain"]) |
| 532 | urls = [item["url"] for item in items if item["url"]] |
| 533 | self.assertEqual(["https://example.com/a", "https://example.com/unique"], urls) |
| 534 | self.assertIn("agent", artifact) |
| 535 | self.assertNotIn("sonar", artifact) |
| 536 | |
| 537 | def test_both_mode_keeps_search_rows_when_agent_leg_fails(self): |
| 538 | search_response = { |
| 539 | "id": "search-1", |
| 540 | "results": [ |
| 541 | { |
| 542 | "title": "Raw result", |
| 543 | "url": "https://example.com/raw", |
| 544 | "snippet": "Raw row", |
| 545 | "date": "2026-05-15", |
| 546 | }, |
| 547 | ], |
| 548 | } |
| 549 | with patch( |
| 550 | "lib.perplexity.http.post", |
| 551 | side_effect=[ |
| 552 | search_response, |
| 553 | perplexity.http.HTTPError("HTTP 500: Server Error", status_code=500), |
| 554 | ], |
| 555 | ): |
| 556 | items, artifact = perplexity.search( |
| 557 | "test topic", |
| 558 | ("2026-05-01", "2026-06-01"), |
| 559 | { |
| 560 | "PERPLEXITY_API_KEY": "pplx-test", |
| 561 | "LAST30DAYS_PERPLEXITY_MODE": "both", |
| 562 | }, |
| 563 | ) |
| 564 | |
| 565 | self.assertEqual("Raw result", items[0]["title"]) |
| 566 | self.assertEqual(1, artifact["itemCount"]) |
| 567 | self.assertEqual("HTTPError", artifact["agent"]["error"]) |
| 568 | self.assertEqual(500, artifact["agent"]["statusCode"]) |
| 569 | |
| 570 | def test_deep_research_uses_agent_background_high_preset(self): |
| 571 | created = {"id": "agent-deep-1", "status": "queued"} |
| 572 | completed = _agent_response( |
| 573 | "Deep synthesis", |
| 574 | response_id="agent-deep-1", |
| 575 | citations=[ |
| 576 | { |
| 577 | "title": "Deep citation", |
| 578 | "url": "https://example.com/deep", |
| 579 | "snippet": "Deep snippet", |
| 580 | } |
| 581 | ], |
| 582 | ) |
| 583 | with patch("lib.perplexity.http.post", return_value=created) as post, patch( |
| 584 | "lib.perplexity.http.get", |
| 585 | return_value=completed, |
| 586 | ) as get: |
| 587 | items, artifact = perplexity.search( |
| 588 | "test topic", |
| 589 | ("2026-05-01", "2026-06-01"), |
| 590 | { |
| 591 | "PERPLEXITY_API_KEY": "pplx-test", |
| 592 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "300", |
| 593 | }, |
| 594 | deep=True, |
| 595 | ) |
| 596 | |
| 597 | self.assertEqual(perplexity.PERPLEXITY_AGENT_URL, post.call_args.args[0]) |
| 598 | payload = post.call_args.args[1] |
| 599 | self.assertEqual(1, post.call_args.kwargs["retries"]) |
| 600 | self.assertEqual("high", payload["preset"]) |
| 601 | self.assertTrue(payload["background"]) |
| 602 | self.assertNotIn("model", payload) |
| 603 | tool = payload["tools"][0] |
| 604 | self.assertEqual("web_search", tool["type"]) |
| 605 | self.assertEqual(10, tool["max_results"]) |
| 606 | self.assertEqual("05/01/2026", tool["filters"]["search_after_date_filter"]) |
| 607 | self.assertEqual("06/01/2026", tool["filters"]["search_before_date_filter"]) |
| 608 | self.assertEqual( |
| 609 | f"{perplexity.PERPLEXITY_AGENT_URL}/agent-deep-1", |
| 610 | get.call_args.args[0], |
| 611 | ) |
| 612 | self.assertEqual("agent-background", artifact["endpoint"]) |
| 613 | self.assertTrue(artifact["background"]) |
| 614 | self.assertEqual(300, artifact["backgroundTimeoutSeconds"]) |
| 615 | self.assertEqual(1, artifact["backgroundPollCount"]) |
| 616 | self.assertEqual("COMPLETED_REMOTE", artifact["backgroundLocalStatus"]) |
| 617 | self.assertEqual("high", artifact["preset"]) |
| 618 | self.assertTrue(artifact["dynamicPreset"]) |
| 619 | self.assertEqual(123, items[0]["metadata"]["usage"]["total_tokens"]) |
| 620 | |
| 621 | def test_deep_research_timeout_preserves_background_response_id(self): |
| 622 | with patch( |
| 623 | "lib.perplexity.http.post", |
| 624 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 625 | ) as post, patch( |
| 626 | "lib.perplexity.time.monotonic", |
| 627 | side_effect=[0, 1], |
| 628 | ), patch("lib.perplexity.http.get") as get: |
| 629 | items, artifact = perplexity.search( |
| 630 | "test topic", |
| 631 | ("2026-05-01", "2026-06-01"), |
| 632 | { |
| 633 | "PERPLEXITY_API_KEY": "pplx-test", |
| 634 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "1", |
| 635 | }, |
| 636 | deep=True, |
| 637 | ) |
| 638 | |
| 639 | post.assert_called_once() |
| 640 | get.assert_not_called() |
| 641 | self.assertEqual([], items) |
| 642 | self.assertEqual("timeout", artifact["error"]) |
| 643 | self.assertEqual("agent-deep-1", artifact["responseId"]) |
| 644 | self.assertEqual("queued", artifact["backgroundStatus"]) |
| 645 | self.assertEqual(1, artifact["backgroundTimeoutSeconds"]) |
| 646 | self.assertEqual(0, artifact["backgroundPollCount"]) |
| 647 | self.assertEqual("PENDING_REMOTE", artifact["backgroundLocalStatus"]) |
| 648 | |
| 649 | def test_deep_research_uses_shared_deadline_for_submit_and_poll(self): |
| 650 | cancel = Event() |
| 651 | |
| 652 | def complete_after_cancellation(*_args, **_kwargs): |
| 653 | cancel.set() |
| 654 | return _agent_response(response_id="agent-deep-1") |
| 655 | |
| 656 | with patch( |
| 657 | "lib.perplexity.http.post", |
| 658 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 659 | ) as post, patch( |
| 660 | "lib.perplexity.http.get", |
| 661 | side_effect=complete_after_cancellation, |
| 662 | ) as get, patch( |
| 663 | "lib.perplexity.time.monotonic", return_value=200.0, |
| 664 | ): |
| 665 | items, artifact = perplexity.search( |
| 666 | "test topic", |
| 667 | ("2026-05-01", "2026-06-01"), |
| 668 | { |
| 669 | "PERPLEXITY_API_KEY": "pplx-test", |
| 670 | "_research_deadline": 220.0, |
| 671 | "_enrich_cancel": cancel, |
| 672 | }, |
| 673 | deep=True, |
| 674 | ) |
| 675 | |
| 676 | post.assert_called_once() |
| 677 | get.assert_called_once() |
| 678 | for request in (post, get): |
| 679 | self.assertEqual(220.0, request.call_args.kwargs["deadline_monotonic"]) |
| 680 | self.assertIs(cancel, request.call_args.kwargs["cancel"]) |
| 681 | self.assertEqual([], items) |
| 682 | self.assertEqual("timeout", artifact["error"]) |
| 683 | self.assertEqual("agent-deep-1", artifact["responseId"]) |
| 684 | |
| 685 | def test_deep_research_nonterminal_poll_after_deadline_is_timeout(self): |
| 686 | with patch( |
| 687 | "lib.perplexity.http.post", |
| 688 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 689 | ), patch( |
| 690 | "lib.perplexity.http.get", |
| 691 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 692 | ) as get, patch( |
| 693 | "lib.perplexity.time.monotonic", |
| 694 | side_effect=[0.0, 0.5, 1.5], |
| 695 | ): |
| 696 | items, artifact = perplexity.search( |
| 697 | "test topic", |
| 698 | ("2026-05-01", "2026-06-01"), |
| 699 | { |
| 700 | "PERPLEXITY_API_KEY": "pplx-test", |
| 701 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "1", |
| 702 | }, |
| 703 | deep=True, |
| 704 | ) |
| 705 | |
| 706 | self.assertEqual([], items) |
| 707 | self.assertEqual("timeout", artifact["error"]) |
| 708 | self.assertEqual("PENDING_REMOTE", artifact["backgroundLocalStatus"]) |
| 709 | self.assertEqual(1, artifact["backgroundPollCount"]) |
| 710 | self.assertEqual(1.0, get.call_args.kwargs["deadline_monotonic"]) |
| 711 | |
| 712 | def test_deep_research_poll_retry_deadline_is_timeout_not_poll_error(self): |
| 713 | with patch( |
| 714 | "lib.perplexity.http.post", |
| 715 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 716 | ), patch( |
| 717 | "lib.perplexity.http.get", |
| 718 | side_effect=perplexity.http.DeadlineExceeded(), |
| 719 | ), patch( |
| 720 | "lib.perplexity.time.monotonic", |
| 721 | side_effect=[0.0, 0.5], |
| 722 | ): |
| 723 | items, artifact = perplexity.search( |
| 724 | "test topic", |
| 725 | ("2026-05-01", "2026-06-01"), |
| 726 | { |
| 727 | "PERPLEXITY_API_KEY": "pplx-test", |
| 728 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "1", |
| 729 | }, |
| 730 | deep=True, |
| 731 | ) |
| 732 | |
| 733 | self.assertEqual([], items) |
| 734 | self.assertEqual("timeout", artifact["error"]) |
| 735 | self.assertEqual("PENDING_REMOTE", artifact["backgroundLocalStatus"]) |
| 736 | self.assertEqual(1, artifact["backgroundPollCount"]) |
| 737 | |
| 738 | def test_deep_research_early_transport_timeout_is_poll_error(self): |
| 739 | with patch( |
| 740 | "lib.perplexity.http.post", |
| 741 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 742 | ), patch( |
| 743 | "lib.perplexity.http.get", |
| 744 | side_effect=perplexity.http.HTTPError( |
| 745 | "URL Error: timed out", |
| 746 | outcome_state=perplexity.health.TIMEOUT, |
| 747 | ), |
| 748 | ), patch( |
| 749 | "lib.perplexity.time.monotonic", |
| 750 | side_effect=[0.0, 10.0, 10.0], |
| 751 | ): |
| 752 | items, artifact = perplexity.search( |
| 753 | "test topic", |
| 754 | ("2026-05-01", "2026-06-01"), |
| 755 | { |
| 756 | "PERPLEXITY_API_KEY": "pplx-test", |
| 757 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "600", |
| 758 | }, |
| 759 | deep=True, |
| 760 | ) |
| 761 | |
| 762 | self.assertEqual([], items) |
| 763 | self.assertEqual("poll_error", artifact["error"]) |
| 764 | self.assertEqual("POLL_ERROR", artifact["backgroundLocalStatus"]) |
| 765 | |
| 766 | def test_deep_research_terminal_poll_after_deadline_is_timeout(self): |
| 767 | with patch( |
| 768 | "lib.perplexity.http.post", |
| 769 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 770 | ), patch( |
| 771 | "lib.perplexity.http.get", |
| 772 | return_value={"id": "agent-deep-1", "status": "completed"}, |
| 773 | ), patch( |
| 774 | "lib.perplexity.time.monotonic", |
| 775 | side_effect=[0.0, 0.5, 1.5], |
| 776 | ): |
| 777 | items, artifact = perplexity.search( |
| 778 | "test topic", |
| 779 | ("2026-05-01", "2026-06-01"), |
| 780 | { |
| 781 | "PERPLEXITY_API_KEY": "pplx-test", |
| 782 | "LAST30DAYS_PERPLEXITY_DEEP_TIMEOUT_SECONDS": "1", |
| 783 | }, |
| 784 | deep=True, |
| 785 | ) |
| 786 | |
| 787 | self.assertEqual([], items) |
| 788 | self.assertEqual("timeout", artifact["error"]) |
| 789 | self.assertEqual("completed", artifact["backgroundStatus"]) |
| 790 | self.assertEqual("PENDING_REMOTE", artifact["backgroundLocalStatus"]) |
| 791 | |
| 792 | def test_deep_research_terminal_failures_are_recorded(self): |
| 793 | for status in ("failed", "cancelled", "incomplete"): |
| 794 | response = { |
| 795 | "id": "agent-deep-1", |
| 796 | "status": status, |
| 797 | "model": "openai/gpt-5.6-sol", |
| 798 | "usage": {"total_tokens": 17}, |
| 799 | "output": [{"type": "message", "content": []}], |
| 800 | } |
| 801 | if status == "incomplete": |
| 802 | response["incomplete_details"] = {"reason": "max_output_tokens"} |
| 803 | with self.subTest(status=status), patch( |
| 804 | "lib.perplexity.http.post", |
| 805 | return_value=response, |
| 806 | ) as post, patch("lib.perplexity.http.get") as get: |
| 807 | items, artifact = perplexity.search( |
| 808 | "test topic", |
| 809 | ("2026-05-01", "2026-06-01"), |
| 810 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 811 | deep=True, |
| 812 | ) |
| 813 | |
| 814 | post.assert_called_once() |
| 815 | get.assert_not_called() |
| 816 | self.assertEqual([], items) |
| 817 | self.assertEqual("failed", artifact["error"]) |
| 818 | self.assertEqual(status, artifact["backgroundStatus"]) |
| 819 | self.assertEqual("TERMINAL_REMOTE", artifact["backgroundLocalStatus"]) |
| 820 | self.assertEqual("openai/gpt-5.6-sol", artifact["servedModel"]) |
| 821 | self.assertEqual({"total_tokens": 17}, artifact["usage"]) |
| 822 | self.assertEqual(["message"], artifact["outputTypes"]) |
| 823 | if status == "incomplete": |
| 824 | self.assertEqual("max_output_tokens", artifact["incompleteReason"]) |
| 825 | |
| 826 | def test_deep_research_logs_safe_receipt_for_cli_consumers(self): |
| 827 | response = { |
| 828 | "id": "agent-deep-1", |
| 829 | "status": "incomplete", |
| 830 | "model": "openai/gpt-5.6-sol", |
| 831 | "incomplete_details": {"reason": "max_output_tokens"}, |
| 832 | } |
| 833 | with patch("lib.perplexity.http.post", return_value=response), patch( |
| 834 | "lib.perplexity._log", |
| 835 | ) as logger: |
| 836 | perplexity.search( |
| 837 | "test topic", |
| 838 | ("2026-05-01", "2026-06-01"), |
| 839 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 840 | deep=True, |
| 841 | ) |
| 842 | |
| 843 | receipt = next( |
| 844 | call.args[0] |
| 845 | for call in logger.call_args_list |
| 846 | if call.args and call.args[0].startswith("Deep Research receipt:") |
| 847 | ) |
| 848 | self.assertIn("model=openai/gpt-5.6-sol", receipt) |
| 849 | self.assertIn("response_id=agent-deep-1", receipt) |
| 850 | self.assertIn("provider_status=incomplete", receipt) |
| 851 | self.assertIn("incomplete_reason=max_output_tokens", receipt) |
| 852 | |
| 853 | def test_deep_research_poll_error_preserves_response_id(self): |
| 854 | with patch( |
| 855 | "lib.perplexity.http.post", |
| 856 | return_value={"id": "agent-deep-1", "status": "queued"}, |
| 857 | ), patch( |
| 858 | "lib.perplexity.http.get", |
| 859 | side_effect=perplexity.http.HTTPError( |
| 860 | "HTTP 429: Too Many Requests", |
| 861 | status_code=429, |
| 862 | ), |
| 863 | ): |
| 864 | items, artifact = perplexity.search( |
| 865 | "test topic", |
| 866 | ("2026-05-01", "2026-06-01"), |
| 867 | {"PERPLEXITY_API_KEY": "pplx-test"}, |
| 868 | deep=True, |
| 869 | ) |
| 870 | |
| 871 | self.assertEqual([], items) |
| 872 | self.assertEqual("poll_error", artifact["error"]) |
| 873 | self.assertEqual("agent-deep-1", artifact["responseId"]) |
| 874 | self.assertEqual("queued", artifact["backgroundStatus"]) |
| 875 | self.assertEqual("POLL_ERROR", artifact["backgroundLocalStatus"]) |
| 876 | self.assertEqual(1, artifact["backgroundPollCount"]) |
| 877 | self.assertEqual(429, artifact["backgroundPollStatusCode"]) |
| 878 | |
| 879 | def test_missing_keys_skip_without_http(self): |
| 880 | with patch("lib.perplexity.http.post") as post: |
| 881 | items, artifact = perplexity.search( |
| 882 | "test topic", |
| 883 | ("2026-05-01", "2026-06-01"), |
| 884 | {}, |
| 885 | ) |
| 886 | |
| 887 | post.assert_not_called() |
| 888 | self.assertEqual([], items) |
| 889 | self.assertEqual({}, artifact) |
| 890 | |
| 891 | |
| 892 | if __name__ == "__main__": |
| 893 | unittest.main() |
| 894 |