From b4a37238943f0751dd690fb73d07db22c728a8d2 Mon Sep 17 00:00:00 2001 From: Saleh Alghusson <1331721+qirh@users.noreply.github.com> Date: Wed, 14 Oct 2026 13:15:23 +0000 Subject: [PATCH] Add integration header to Perplexity requests --- src/api_perplexity_search.py | 7 ++++++- tests/test_perplexity_headers.py | 27 +++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 tests/test_perplexity_headers.py diff --git a/src/api_perplexity_search.py b/src/api_perplexity_search.py index c266713..901cc4f 100644 --- a/src/api_perplexity_search.py +++ b/src/api_perplexity_search.py @@ -27,6 +27,7 @@ import random import re from typing import Any, Dict, Iterable, List, Optional +from urllib.parse import urlparse import httpx @@ -216,11 +217,15 @@ def _backoff_delay(attempt: int) -> float: def _perplexity_headers() -> Dict[str, str]: - return { + headers = { "Authorization": f"Bearer {PERPLEXITY_API_KEY}", "Content-Type": "application/json", "Accept": "application/json", } + # Identify this integration to Perplexity; skipped for custom endpoints. + if urlparse(PERPLEXITY_ENDPOINT).hostname == "api.perplexity.ai": + headers["X-Pplx-Integration"] = "telegrambot-openai-api" + return headers def _extract_perplexity_content(response_data: Dict[str, Any]) -> str: diff --git a/tests/test_perplexity_headers.py b/tests/test_perplexity_headers.py new file mode 100644 index 0000000..5a4dad6 --- /dev/null +++ b/tests/test_perplexity_headers.py @@ -0,0 +1,27 @@ +import sys +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) + +import api_perplexity_search # noqa: E402 + + +def test_default_endpoint_sends_integration_header(monkeypatch): + monkeypatch.setattr( + api_perplexity_search, + "PERPLEXITY_ENDPOINT", + "https://api.perplexity.ai/chat/completions", + ) + headers = api_perplexity_search._perplexity_headers() + assert headers["X-Pplx-Integration"] == "telegrambot-openai-api" + assert [k.lower() for k in headers].count("x-pplx-integration") == 1 + + +def test_custom_endpoint_omits_integration_header(monkeypatch): + for endpoint in ( + "https://proxy.example.com/chat/completions", + "https://api.perplexity.ai.example.com/chat/completions", + ): + monkeypatch.setattr(api_perplexity_search, "PERPLEXITY_ENDPOINT", endpoint) + headers = api_perplexity_search._perplexity_headers() + assert "X-Pplx-Integration" not in headers