Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/api_perplexity_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import random
import re
from typing import Any, Dict, Iterable, List, Optional
from urllib.parse import urlparse

import httpx

Expand Down Expand Up @@ -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:
Expand Down
27 changes: 27 additions & 0 deletions tests/test_perplexity_headers.py
Original file line number Diff line number Diff line change
@@ -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