DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
feat: Add OpenRouter search provider
infstellar5654c0c9a153
diff --git a/README.md b/README.mdindex 7193ec7a8..05cbf8ca3 100644--- a/README.md+++ b/README.md@@ -291,7 +291,7 @@ cp .env.example .env| `FRONTEND_PORT` | No | Frontend port (default: `3782`) || `NEXT_PUBLIC_API_BASE` | No | **Frontend API URL** - Set this for remote/LAN access (e.g., `http://192.168.1.100:8001`) || `TTS_*` | No | Text-to-Speech settings |-| `SEARCH_PROVIDER` | No | Search provider (options: `perplexity`, `tavily`, `serper`, `jina`, `exa`, `baidu`, default: `perplexity`) |+| `SEARCH_PROVIDER` | No | Search provider (options: `perplexity`, `openrouter`, `tavily`, `serper`, `jina`, `exa`, `baidu`, default: `perplexity`) || `SEARCH_API_KEY` | No | Unified API key for all search providers |> 💡 **Remote Access**: If accessing from another device (e.g., `192.168.31.66:3782`), add to `.env`:diff --git a/src/services/search/providers/__init__.py b/src/services/search/providers/__init__.pyindex 70e04991b..2035fd5ea 100644--- a/src/services/search/providers/__init__.py+++ b/src/services/search/providers/__init__.py@@ -117,7 +117,7 @@ def get_default_provider(**kwargs) -> BaseSearchProvider:# Auto-import all providers to trigger registration-from . import baidu, exa, jina, perplexity, serper, tavily+from . import baidu, exa, jina, openrouter, perplexity, serper, tavily__all__ = ["register_provider",diff --git a/src/services/search/providers/openrouter.py b/src/services/search/providers/openrouter.pynew file mode 100644index 000000000..ba24e955a--- /dev/null+++ b/src/services/search/providers/openrouter.py@@ -0,0 +1,174 @@+# -*- coding: utf-8 -*-+"""+OpenRouter Search Provider+==========================++API: Uses openai Python package with OpenRouter base URL+Model: perplexity/sonar (or other supported models)++Features:+- Compatible with OpenRouter's OpenAI-like API+- Extracts citations from response (supports 'citations' in root or choice)+- Maps string URLs to Citation objects+"""++from datetime import datetime+from typing import Any, List++from src.services.search.base import BaseSearchProvider+from src.services.search.providers import register_provider+from src.services.search.types import Citation, SearchResult, WebSearchResponse+++@register_provider("openrouter")+class OpenRouterProvider(BaseSearchProvider):+ """OpenRouter search provider (wrapper for Perplexity models via OpenRouter)"""++ display_name = "OpenRouter"+ description = "Search via OpenRouter (Perplexity models)"+ supports_answer = True+ requires_api_key = True++ def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:+ super().__init__(api_key, **kwargs)+ self._client = None+ # Default base URL for OpenRouter+ # Note: kwargs might override base_url if provided by config+ self.base_url = kwargs.get("base_url", "https://openrouter.ai/api/v1")++ @property+ def client(self):+ """Lazy-load the OpenAI client configured for OpenRouter."""+ if self._client is None:+ try:+ from openai import OpenAI+ except ImportError as e:+ raise ImportError(+ "openai module is not installed. To use OpenRouter search, please install: "+ "pip install openai"+ ) from e++ if not self.api_key:+ # Try getting from env if not passed explicitly (though BaseSearchProvider handles this usually)+ import os++ self.api_key = os.environ.get("SEARCH_API_KEY") or os.environ.get(+ "OPENROUTER_API_KEY"+ )++ if not self.api_key:+ raise ValueError("API Key is required for OpenRouter search provider.")++ self._client = OpenAI(+ api_key=self.api_key,+ base_url=self.base_url,+ )+ return self._client++ def search(+ self,+ query: str,+ model: str = "perplexity/sonar",+ system_prompt: str = "You are a helpful AI assistant. Provide detailed and accurate answers based on web search results.",+ **kwargs: Any,+ ) -> WebSearchResponse:+ """+ Perform search using OpenRouter API.++ Args:+ query: Search query.+ model: Model to use (default: perplexity/sonar).+ system_prompt: System prompt for the model.+ **kwargs: Additional options.++ Returns:+ WebSearchResponse: Standardized search response.+ """+ self.logger.debug(f"Calling OpenRouter API with model={model}")++ completion = self.client.chat.completions.create(+ model=model,+ messages=[+ {"role": "system", "content": system_prompt},+ {"role": "user", "content": query},+ ],+ # Request citations explicitly+ extra_body={"return_citations": True},+ )++ if not completion.choices or len(completion.choices) == 0:+ raise ValueError("OpenRouter API returned no choices")++ choice = completion.choices[0]+ answer = choice.message.content or ""++ # Build usage info+ usage_info: dict[str, Any] = {}+ if completion.usage:+ usage = completion.usage+ usage_info = {+ "prompt_tokens": usage.prompt_tokens,+ "completion_tokens": usage.completion_tokens,+ "total_tokens": usage.total_tokens,+ }++ # Extract citations+ # OpenRouter returns citations in the root of the response object usually+ # But openai library models usage as Pydantic models, so we access via model_extra or dict++ citations_data = []+ raw_dict = completion.model_dump()++ # Check root level 'citations' (OpenRouter standard for Perplexity models)+ if "citations" in raw_dict:+ citations_data = raw_dict["citations"]+ elif "citations" in raw_dict.get("choices", [{}])[0]:+ citations_data = raw_dict["choices"][0]["citations"]++ citations: List[Citation] = []+ search_results: List[SearchResult] = []++ if citations_data:+ for i, cite_item in enumerate(citations_data, 1):+ url = ""+ if isinstance(cite_item, str):+ url = cite_item+ elif isinstance(cite_item, dict):+ url = cite_item.get("url", "")++ if url:+ citations.append(+ Citation(+ id=i,+ reference=f"[{i}]",+ url=url,+ title=f"Source {i}", # Fallback as we don't get title+ snippet="Content not available from meta-data.", # Fallback+ source="OpenRouter",+ )+ )+ # Also populate search_results as some UI components might use it+ search_results.append(+ SearchResult(+ title=f"Source {i}",+ url=url,+ snippet="Content not available from meta-data.",+ source="OpenRouter",+ )+ )++ response = WebSearchResponse(+ query=query,+ answer=answer,+ provider="openrouter",+ timestamp=datetime.now().isoformat(),+ model=completion.model,+ citations=citations,+ search_results=search_results,+ usage=usage_info,+ metadata={+ "finish_reason": choice.finish_reason,+ },+ )++ return responsediff --git a/tests/test_openrouter_provider.py b/tests/test_openrouter_provider.pynew file mode 100644index 000000000..b8efc6246--- /dev/null+++ b/tests/test_openrouter_provider.py@@ -0,0 +1,79 @@+import os+import sys+import unittest+from unittest.mock import MagicMock, patch++# Add project root to path+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))++from src.services.search.providers.openrouter import OpenRouterProvider+from src.services.search.types import WebSearchResponse+++class TestOpenRouterProvider(unittest.TestCase):+ def setUp(self):+ self.api_key = "test-key"+ # Mock openai module+ self.mock_openai = MagicMock()+ self.mock_client = MagicMock()+ self.mock_openai.OpenAI.return_value = self.mock_client++ # Patch import+ self.patcher = patch.dict("sys.modules", {"openai": self.mock_openai})+ self.patcher.start()++ def tearDown(self):+ self.patcher.stop()++ def test_search_success_root_citations(self):+ """Test search with citations in root response (standard OpenRouter Perplexity)"""+ provider = OpenRouterProvider(api_key=self.api_key)++ # Mock response+ mock_completion = MagicMock()+ mock_completion.choices = [MagicMock()]+ mock_completion.choices[0].message.content = "Test answer"+ mock_completion.choices[0].finish_reason = "stop"+ mock_completion.model = "perplexity/sonar"+ mock_completion.usage.prompt_tokens = 10+ mock_completion.usage.completion_tokens = 20+ mock_completion.usage.total_tokens = 30++ # model_dump return value+ mock_completion.model_dump.return_value = {+ "citations": ["https://example.com/1", {"url": "https://example.com/2"}]+ }++ self.mock_client.chat.completions.create.return_value = mock_completion++ result = provider.search("test query")++ self.assertIsInstance(result, WebSearchResponse)+ self.assertEqual(result.answer, "Test answer")+ self.assertEqual(len(result.citations), 2)+ self.assertEqual(result.citations[0].url, "https://example.com/1")+ self.assertEqual(result.citations[1].url, "https://example.com/2")+ self.assertEqual(result.provider, "openrouter")++ def test_search_success_choice_citations(self):+ """Test search with citations in choice (alternative format)"""+ provider = OpenRouterProvider(api_key=self.api_key)++ mock_completion = MagicMock()+ mock_completion.choices = [MagicMock()]+ mock_completion.choices[0].message.content = "Test answer"++ mock_completion.model_dump.return_value = {+ "choices": [{"citations": ["https://example.com/choice"]}]+ }++ self.mock_client.chat.completions.create.return_value = mock_completion++ result = provider.search("test query")++ self.assertEqual(len(result.citations), 1)+ self.assertEqual(result.citations[0].url, "https://example.com/choice")+++if __name__ == "__main__":+ unittest.main()