Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

"Remove deprecated `web_search.py` and update web search configuration with support for multiple providers."

andresa2ec0f202e3f
diff --git a/.env.example b/.env.example
index 116a41d1e..5169c93b5 100644
--- a/.env.example
+++ b/.env.example
@@ -131,14 +131,14 @@ TTS_API_KEY=
# Configure external search APIs for research features.
# Search provider to use for web search
-# Options: perplexity, baidu
+# Options: perplexity, baidu, tavily, exa, serper, jina
# Default: perplexity
SEARCH_PROVIDER=perplexity
# ----------------------------------------------------------------------------
# Perplexity AI Search Configuration
# ----------------------------------------------------------------------------
-# Perplexity API key for web search functionality
+# Perplexity API key for AI-powered search
# Get your API key at: https://www.perplexity.ai/settings/api
PERPLEXITY_API_KEY=
@@ -150,6 +150,34 @@ PERPLEXITY_API_KEY=
# Format: bce-v3/ALTAK-xxx/xxx or the full API key
BAIDU_API_KEY=
+# ----------------------------------------------------------------------------
+# Tavily Research Search Configuration
+# ----------------------------------------------------------------------------
+# Tavily API key for research-focused search
+# Get your API key at: https://tavily.com
+TAVILY_API_KEY=
+
+# ----------------------------------------------------------------------------
+# Exa Neural Search Configuration
+# ----------------------------------------------------------------------------
+# Exa API key for embeddings-based neural search
+# Get your API key at: https://dashboard.exa.ai
+EXA_API_KEY=
+
+# ----------------------------------------------------------------------------
+# Serper Google SERP Configuration
+# ----------------------------------------------------------------------------
+# Serper API key for Google search results
+# Get your API key at: https://serper.dev
+SERPER_API_KEY=
+
+# ----------------------------------------------------------------------------
+# Jina Reader Search Configuration
+# ----------------------------------------------------------------------------
+# Jina API key for SERP with full content extraction
+# Get your API key at: https://jina.ai/reader (optional, has free tier)
+JINA_API_KEY=
+
# ============================================================================
# Logging Configuration
# ============================================================================
diff --git a/config/main.yaml b/config/main.yaml
index 9cc4d0a3f..c3c135357 100644
--- a/config/main.yaml
+++ b/config/main.yaml
@@ -21,6 +21,9 @@ tools:
- ./src/tools
web_search:
enabled: true
+ consolidation: template
+ consolid ation_template: ''
+ provider: jina
query_item:
enabled: true
max_results: 5
diff --git a/docker-compose.yml b/docker-compose.yml
index 31933365d..fbe9a848c 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -55,7 +55,13 @@ services:
- TTS_URL=${TTS_URL:-}
- TTS_VOICE=${TTS_VOICE:-alloy}
# Web Search Configuration (Optional)
+ - SEARCH_PROVIDER=${SEARCH_PROVIDER:-perplexity}
- PERPLEXITY_API_KEY=${PERPLEXITY_API_KEY:-}
+ - BAIDU_API_KEY=${BAIDU_API_KEY:-}
+ - TAVILY_API_KEY=${TAVILY_API_KEY:-}
+ - EXA_API_KEY=${EXA_API_KEY:-}
+ - SERPER_API_KEY=${SERPER_API_KEY:-}
+ - JINA_API_KEY=${JINA_API_KEY:-}
# Logging Configuration
- RAG_TOOL_MODULE_LOG_LEVEL=${RAG_TOOL_MODULE_LOG_LEVEL:-INFO}
# ============================================
diff --git a/settings.py b/settings.py
index c006b049b..8e78a2962 100644
--- a/settings.py
+++ b/settings.py
@@ -92,20 +92,63 @@ class TTSSettings(BaseSettings):
class WebSearchSettings(BaseSettings):
- # Environment var: PERPLEXITY_API_KEY
+ """Web search configuration with multiple provider support."""
+
model_config = SettingsConfigDict(
- env_prefix="PERPLEXITY_",
env_file=".env",
env_file_encoding="utf-8",
extra="ignore",
)
- api_key: Optional[str] = Field(
+ # Default provider (from SEARCH_PROVIDER env var)
+ provider: str = Field(
+ default="perplexity",
+ description="Default search provider (perplexity, baidu, tavily, exa, serper, jina).",
+ validation_alias="SEARCH_PROVIDER",
+ )
+
+ # Perplexity
+ perplexity_api_key: Optional[str] = Field(
default=None,
- description="Perplexity API key for web search functionality.",
+ description="Perplexity API key for AI-powered search.",
validation_alias="PERPLEXITY_API_KEY",
)
+ # Baidu
+ baidu_api_key: Optional[str] = Field(
+ default=None,
+ description="Baidu API key for AI search.",
+ validation_alias="BAIDU_API_KEY",
+ )
+
+ # Tavily
+ tavily_api_key: Optional[str] = Field(
+ default=None,
+ description="Tavily API key for research-focused search.",
+ validation_alias="TAVILY_API_KEY",
+ )
+
+ # Exa
+ exa_api_key: Optional[str] = Field(
+ default=None,
+ description="Exa API key for neural/embeddings search.",
+ validation_alias="EXA_API_KEY",
+ )
+
+ # Serper
+ serper_api_key: Optional[str] = Field(
+ default=None,
+ description="Serper API key for Google SERP results.",
+ validation_alias="SERPER_API_KEY",
+ )
+
+ # Jina
+ jina_api_key: Optional[str] = Field(
+ default=None,
+ description="Jina API key for SERP with content extraction (optional, has free tier).",
+ validation_alias="JINA_API_KEY",
+ )
+
class LoggingSettings(BaseSettings):
# Environment vars: RAG_TOOL_MODULE_LOG_LEVEL
diff --git a/src/agents/research/agents/reporting_agent.py b/src/agents/research/agents/reporting_agent.py
index ed3fae31c..3f7812355 100644
--- a/src/agents/research/agents/reporting_agent.py
+++ b/src/agents/research/agents/reporting_agent.py
@@ -1291,6 +1291,7 @@ class ReportingAgent(BaseAgent):
citation_output_hint=citation_output_hint,
)
+ # TODO Implement retry logic for LLM calls when JSON parsing or post-processing fails (e.g., malformed output, schema violations).
resp = await self.call_llm(
filled,
system_prompt,
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
index 36f75fb23..dbb8c8270 100644
--- a/src/api/routers/settings.py
+++ b/src/api/routers/settings.py
@@ -128,8 +128,50 @@ ENV_VAR_DEFINITIONS = {
"sensitive": False,
},
# Web Search Configuration
+ "SEARCH_PROVIDER": {
+ "description": "Default search provider: perplexity, baidu, tavily, exa, serper, jina",
+ "category": "search",
+ "required": False,
+ "default": "perplexity",
+ "sensitive": False,
+ },
"PERPLEXITY_API_KEY": {
- "description": "Perplexity API key for web search functionality",
+ "description": "Perplexity API key for AI-powered search (https://perplexity.ai/settings/api)",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "BAIDU_API_KEY": {
+ "description": "Baidu API key for AI search (https://console.bce.baidu.com/ai_apaas/resource)",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "TAVILY_API_KEY": {
+ "description": "Tavily API key for research-focused search (https://tavily.com)",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "EXA_API_KEY": {
+ "description": "Exa API key for neural/embeddings search (https://dashboard.exa.ai)",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "SERPER_API_KEY": {
+ "description": "Serper API key for Google SERP results (https://serper.dev)",
+ "category": "search",
+ "required": False,
+ "default": "",
+ "sensitive": True,
+ },
+ "JINA_API_KEY": {
+ "description": "Jina API key for SERP with content extraction (https://jina.ai/reader) - optional, has free tier",
"category": "search",
"required": False,
"default": "",
@@ -156,7 +198,7 @@ ENV_CATEGORIES = {
},
"search": {
"name": "Web Search Configuration",
- "description": "External search API settings (Perplexity)",
+ "description": "Web search providers: Perplexity, Baidu, Tavily, Exa, Serper, Jina",
"icon": "search",
},
}
@@ -751,6 +793,32 @@ async def test_single_service(service: Literal["llm", "embedding", "tts"]):
return result
+# ==================== Web Search Configuration ====================
+
+
[email protected]("/web-search/config")
+async def get_web_search_config():
+ """
+ Get current web search configuration.
+
+ Returns:
+ {
+ "enabled": bool,
+ "provider": str,
+ "consolidation": str | None,
+ "consolidation_template": str | None,
+ "available_providers": list[str],
+ "config_source": "env" | "yaml" | "default"
+ }
+ """
+ try:
+ from src.tools.web_search import get_current_config
+
+ return get_current_config()
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=f"Failed to get web search config: {str(e)}")
+
+
# ==================== RAG Provider Configuration ====================
@@ -773,4 +841,4 @@ async def get_rag_providers():
return {"providers": providers, "current": current}
except Exception as e:
- raise HTTPException(status_code=500, detail=f"Failed to get RAG providers: {str(e)}")
+ raise HTTPException(status_code=500, detail =f"Failed to get RAG providers: {str(e)}")
diff --git a/src/tools/web_search.py b/src/tools/web_search.py
deleted file mode 100644
index a88c78201..000000000
--- a/src/tools/web_search.py
+++ /dev/null
@@ -1,442 +0,0 @@
-#!/usr/bin/env python
-"""
-Web Search Tool - Network search using Perplexity API or Baidu AI Search API
-"""
-
-from datetime import datetime
-from enum import Enum
-import json
-import os
-
-import requests
-
-try:
- from perplexity import Perplexity
-
- PERPLEXITY_AVAILABLE = True
-except ImportError:
- PERPLEXITY_AVAILABLE = False
- Perplexity = None
-
-
-class SearchProvider(str, Enum):
- """Supported search providers"""
-
- PERPLEXITY = "perplexity"
- BAIDU = "baidu"
-
-
-class BaiduAISearch:
- """Baidu AI Search client for intelligent search and generation"""
-
- BASE_URL = "https://qianfan.baidubce.com/v2/ai_search/chat/completions"
-
- def __init__(self, api_key: str):
- """
- Initialize Baidu AI Search client
-
- Args:
- api_key: Baidu Qianfan API Key (format: bce-v3/xxx or Bearer token)
- """
- self.api_key = api_key
- self.headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {api_key}" if not api_key.startswith("Bearer ") else api_key,
- }
-
- def search(
- self,
- query: str,
- model: str = "ernie-4.5-turbo-32k",
- search_source: str = "baidu_search_v2",
- stream: bool = False,
- enable_deep_search: bool = False,
- enable_corner_markers: bool = True,
- enable_followup_queries: bool = False,
- temperature: float = 0.11,
- top_p: float = 0.55,
- search_mode: str = "auto",
- search_recency_filter: str | None = None,
- instruction: str = "",
- ) -> dict:
- """
- Perform intelligent search using Baidu AI Search API
-
- Args:
- query: Search query
- model: Model to use for generation (default: ernie-4.5-turbo-32k)
- search_source: Search engine version (baidu_search_v1 or baidu_search_v2)
- stream: Whether to use streaming response
- enable_deep_search: Enable deep search for more comprehensive results
- enable_corner_markers: Enable corner markers for reference citations
- enable_followup_queries: Enable follow-up query suggestions
- temperature: Model sampling temperature (0, 1]
- top_p: Model sampling top_p (0, 1]
- search_mode: Search mode (auto, required, disabled)
- search_recency_filter: Filter by recency (week, month, semiyear, year)
- instruction: System instruction for response style
- max_completion_tokens: Maximum output tokens
-
- Returns:
- dict: API response containing search results and generated answer
- """
- payload = {
- "messages": [{"role": "user", "content": query}],
- "model": model,
- "search_source": search_source,
- "stream": stream,
- "enable_deep_search": enable_deep_search,
- "enable_corner_markers": enable_corner_markers,
- "enable_followup_queries": enable_followup_queries,
- "temperature": temperature,
- "top_p": top_p,
- "search_mode": search_mode,
- }
-
- if search_recency_filter:
- payload["search_recency_filter"] = search_recency_filter
-
- if instruction:
- payload["instruction"] = instruction
-
- response = requests.post(self.BASE_URL, headers=self.headers, json=payload, timeout=120)
-
- if response.status_code != 200:
- error_data = response.json() if response.text else {}
- raise Exception(
- f"Baidu AI Search API error: {response.status_code} - "
- f"{error_data.get('message', response.text)}"
- )
-
- return response.json()
-
-
-def _search_with_baidu(
- query: str,
- model: str = "ernie-4.5-turbo-32k",
- enable_deep_search: bool = False,
- search_recency_filter: str | None = None,
- verbose: bool = False,
-) -> dict:
- """
- Perform search using Baidu AI Search API
-
- Args:
- query: Search query
- model: Model to use for generation
- enable_deep_search: Enable deep search
- search_recency_filter: Filter by recency
- verbose: Whether to print detailed information
-
- Returns:
- dict: Standardized search result
- """
- api_key = os.environ.get("BAIDU_API_KEY")
- if not api_key:
- raise ValueError(
- "BAIDU_API_KEY environment variable is not set. "
- "Please get your API key from https://console.bce.baidu.com/ai_apaas/resource"
- )
-
- client = BaiduAISearch(api_key=api_key)
-
- response = client.search(
- query=query,
- model=model,
- enable_deep_search=enable_deep_search,
- search_recency_filter=search_recency_filter,
- )
-
- # Extract answer from response
- answer = ""
- if response.get("choices"):
- choice = response["choices"][0]
- if choice.get("message"):
- answer = choice["message"].get("content", "")
-
- # Build standardized result
- result = {
- "timestamp": datetime.now().isoformat(),
- "query": query,
- "model": model,
- "provider": "baidu",
- "answer": answer,
- "response": {
- "content": answer,
- "role": "assistant",
- "finish_reason": response.get("choices", [{}])[0].get("finish_reason", ""),
- },
- "usage": {},
- "citations": [],
- "search_results": [],
- "is_safe": response.get("is_safe", True),
- "request_id": response.get("request_id", ""),
- }
-
- # Extract usage information
- if response.get("usage"):
- usage = response["usage"]
- result["usage"] = {
- "prompt_tokens": usage.get("prompt_tokens", 0),
- "completion_tokens": usage.get("completion_tokens", 0),
- "total_tokens": usage.get("total_tokens", 0),
- }
-
- # Extract references/citations
- if response.get("references"):
- for i, ref in enumerate(response["references"], 1):
- citation_data = {
- "id": ref.get("id", i),
- "reference": f"[{ref.get('id', i)}]",
- "url": ref.get("url", ""),
- "title": ref.get("title", ""),
- "snippet": ref.get("content", ""),
- "date": ref.get("date", ""),
- "type": ref.get("type", "web"),
- "icon": ref.get("icon", ""),
- "website": ref.get("website", ""),
- "web_anchor": ref.get("web_anchor", ""),
- }
- result["citations"].append(citation_data)
-
- # Also add to search_results for compatibility
- search_result = {
- "title": ref.get("title", ""),
- "url": ref.get("url", ""),
- "date": ref.get("date", ""),
- "snippet": ref.get("content", ""),
- "source": ref.get("web_anchor", ""),
- }
- result["search_results"].append(search_result)
-
- # Extract follow-up queries if available
- if response.get("followup_queries"):
- result["followup_queries"] = response["followup_queries"]
-
- if verbose:
- print(f"[Baidu AI Search] Query: {query}")
- print(f"[Baidu AI Search] Model: {model}")
- print(f"[Baidu AI Search] References count: {len(result['citations'])}")
-
- return result
-
-
-def _search_with_perplexity(query: str, verbose: bool = False) -> dict:
- """
- Perform search using Perplexity API
-
- Args:
- query: Search query
- verbose: Whether to print detailed information
-
- Returns:
- dict: Standardized search result
- """
- if not PERPLEXITY_AVAILABLE:
- raise ImportError(
- "perplexity module is not installed. To use Perplexity search, please install: "
- "pip install perplexity"
- )
-
- api_key = os.environ.get("PERPLEXITY_API_KEY")
- if not api_key:
- raise ValueError("PERPLEXITY_API_KEY environment variable is not set")
-
- if Perplexity is None:
- raise ImportError("Perplexity module is not available")
-
- client = Perplexity(api_key=api_key)
-
- completion = client.chat.completions.create(
- model="sonar",
- messages=[
- {
- "role": "system",
- "content": "You are a helpful AI assistant. Provide detailed and accurate answers based on web search results.",
- },
- {"role": "user", "content": query},
- ],
- )
-
- answer = completion.choices[0].message.content
-
- # Build usage info with safe attribute access
- usage_info: dict = {}
- if hasattr(completion, "usage") and completion.usage is not None:
- usage = completion.usage
- usage_info = {
- "prompt_tokens": getattr(usage, "prompt_tokens", 0),
- "completion_tokens": getattr(usage, "completion_tokens", 0),
- "total_tokens": getattr(usage, "total_tokens", 0),
- }
- if hasattr(usage, "cost") and usage.cost is not None:
- cost = usage.cost
- usage_info["cost"] = {
- "total_cost": getattr(cost, "total_cost", 0),
- "input_tokens_cost": getattr(cost, "input_tokens_cost", 0),
- "output_tokens_cost": getattr(cost, "output_tokens_cost", 0),
- }
-
- result = {
- "timestamp": datetime.now().isoformat(),
- "query": query,
- "model": completion.model,
- "provider": "perplexity",
- "answer": answer,
- "response": {
- "content": answer,
- "role": completion.choices[0].message.role,
- "finish_reason": completion.choices[0].finish_reason,
- },
- "usage": usage_info,
- "citations": [],
- "search_results": [],
- }
-
- # Extract citation links
- if hasattr(completion, "citations") and completion.citations:
- for i, citation_url in enumerate(completion.citations, 1):
- citation_data = {
- "id": i,
- "reference": f"[{i}]",
- "url": citation_url,
- "title": "",
- "snippet": "",
- }
-
- for search_item in result.get("search_results", []):
- if search_item.get("url") == citation_url:
- citation_data["title"] = search_item.get("title", "")
- citation_data["snippet"] = search_item.get("snippet", "")
- break
-
- result["citations"].append(citation_data)
-
- # Extract search result details
- if hasattr(completion, "search_results") and completion.search_results:
- for search_item in completion.search_results:
- search_result = {
- "title": search_item.title,
- "url": search_item.url,
- "date": search_item.date,
- "last_updated": search_item.last_updated,
- "snippet": search_item.snippet,
- "source": search_item.source,
- }
- result["search_results"].append(search_result)
-
- if verbose:
- print(f"[Perplexity] Query: {query}")
- print(f"[Perplexity] Model: {completion.model}")
-
- return result
-
-
-def web_search(
- query: str,
- output_dir: str | None = None,
- verbose: bool = False,
- # Baidu-specific options
- baidu_model: str = "ernie-4.5-turbo-32k",
- baidu_enable_deep_search: bool = False,
- baidu_search_recency_filter: str = "week",
-) -> dict:
- """
- Perform network search using specified search provider and return results
-
- Args:
- query: Search query
- output_dir: Output directory (optional, if provided will save results)
- verbose: Whether to print detailed information
- baidu_model: Model to use for Baidu AI Search (default: ernie-4.5-turbo-32k)
- baidu_enable_deep_search: Enable deep search for Baidu (more comprehensive results)
- baidu_search_recency_filter: Filter by recency for Baidu (week, month, semiyear, year)
-
- Returns:
- dict: Dictionary containing search results
- {
- "query": str,
- "answer": str,
- "provider": str,
- "result_file": str (if file was saved)
- }
-
- Raises:
- ImportError: If required module is not installed
- ValueError: If required environment variable is not set
- Exception: If API call fails
- """
- # Get search provider from environment variable
- provider = os.environ.get("SEARCH_PROVIDER", "perplexity").lower()
-
- try:
- if provider == "baidu":
- result = _search_with_baidu(
- query=query,
- model=baidu_model,
- enable_deep_search=baidu_enable_deep_search,
- search_recency_filter=baidu_search_recency_filter,
- verbose=verbose,
- )
- elif provider == "perplexity":
- result = _search_with_perplexity(query=query, verbose=verbose)
- else:
- raise ValueError(
- f"Unsupported search provider: {provider}. Use 'perplexity' or 'baidu'."
- )
-
- # If output directory provided, save results
- result_file = None
- if output_dir:
- os.makedirs(output_dir, exist_ok=True)
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
- output_filename = f"search_{provider}_{timestamp}.json"
- output_path = os.path.join(output_dir, output_filename)
-
- with open(output_path, "w", encoding="utf-8") as f:
- json.dump(result, f, ensure_ascii=False, indent=2)
-
- result_file = output_path
-
- if verbose:
- print(f"Search results saved to: {output_path}")
-
- # Add file path to result
- if result_file:
- result["result_file"] = result_file
-
- if verbose:
- answer = result.get("answer", "")
- print(f"Query: {query}")
- if answer:
- print(f"Answer: {answer[:200]}..." if len(answer) > 200 else f"Answer: {answer}")
-
- return result
-
- except Exception as e:
- raise Exception(f"{provider.capitalize()} API call failed: {e!s}")
-
-
-if __name__ == "__main__":
- import sys
-
- if sys.platform == "win32":
- import io
-
- sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")
-
- # Test with different providers
- # Default: Perplexity
- # result = web_search("What is a diffusion model?", output_dir="./test_output", verbose=True)
-
- # Test with Baidu AI Search
- result = web_search(
- "What is a diffusion model?",
- output_dir="./test_output",
- verbose=True,
- )
- print("\nSearch completed!")
- print(f"Provider: {result.get('provider', 'unknown')}")
- print(f"Query: {result['query']}")
- answer = result.get("answer", "")
- print(f"Answer: {answer[:300]}..." if len(answer) > 300 else f"Answer: {answer}")
diff --git a/src/tools/web_search/README.md b/src/tools/web_search/README.md
new file mode 100644
index 000000000..e3c4cdf46
--- /dev/null
+++ b/src/tools/web_search/README.md
@@ -0,0 +1,753 @@
+# Web Search Tool
+
+A unified, pluggable web search interface supporting multiple search providers with standardized responses.
+
+## Quick Start
+
+```python
+from src.tools.web_search import web_search
+
+# Basic search (uses default provider from config)
+result = web_search("What is machine learning?")
+print(result["answer"])
+print(result["citations"])
+
+# Specify a provider
+result = web_search("Latest AI news", provider="tavily")
+
+# With provider-specific options
+result = web_search(
+ query="Python best practices",
+ provider="serper",
+ output_dir="./search_cache",
+ verbose=True,
+ num=20, # Serper-specific option
+)
+```
+
+## Available Providers
+
+| Provider | Type | API Key Env Var | Generates Answer | Description |
+|----------|------|-----------------|------------------|-------------|
+| **perplexity** | AI Search | `PERPLEXITY_API_KEY` | ✅ Yes | AI-powered search with LLM answers |
+| **baidu** | AI Search | `BAIDU_API_KEY` | ✅ Yes | Baidu AI Search with ERNIE models |
+| **tavily** | AI Search | `TAVILY_API_KEY` | ✅ Yes | Research-focused with relevance scoring |
+| **exa** | AI Search | `EXA_API_KEY` | ✅ Yes | Neural/embeddings search with summaries |
+| **serper** | SERP | `SERPER_API_KEY` | ⚡ Partial | Google SERP (extracts from Knowledge Graph) |
+| **jina** | SERP | `JINA_API_KEY` | ❌ No | SERP with content extraction (free tier available) |
+
+### Provider-Specific Options
+
+#### Perplexity
+```python
+result = web_search(
+ query="Explain quantum computing",
+ provider="perplexity",
+ model="sonar",
+ system_prompt="Be concise and technical",
+)
+```
+
+#### Tavily
+```python
+result = web_search(
+ query="Latest developments in renewable energy",
+ provider="tavily",
+ search_depth="advanced", # "basic" or "advanced"
+ topic="news", # "general", "news", "finance"
+ max_results=15, # 1-20
+ include_answer=True,
+ include_raw_content=False,
+ include_images=False,
+ days=30, # Filter to last N days (1-365)
+ include_domains=["arxiv.org"],
+ exclude_domains=["example.com"],
+)
+```
+
+#### Exa
+```python
+result = web_search(
+ query="Machine learning optimization",
+ provider="exa",
+ search_type="neural", # "auto", "neural", "keyword"
+ num_results=10,
+ include_text=True,
+ include_highlights=True,
+ include_summary=True,
+ category="research paper", # "news", "company", "github", etc.
+ start_published_date="2024-01-01",
+ end_published_date="2024-12-31",
+)
+```
+
+#### Baidu
+```python
+result = web_search(
+ query="人工智能最新进展",
+ provider="baidu",
+ model="ernie-4.5-turbo-32k",
+ enable_deep_search=True,
+ search_recency_filter="month", # "week", "month", "semiyear", "year"
+)
+```
+
+#### Serper
+```python
+result = web_search(
+ query="Best Python frameworks 2024",
+ provider="serper",
+ mode="search", # "search" or "scholar"
+ num=20, # max: 100
+ gl="us", # Country code
+ hl="en", # Language code
+)
+
+# Scholar mode for academic papers
+result = web_search(
+ query="transformer architecture attention mechanism",
+ provider="serper",
+ mode="scholar", # Google Scholar results
+ num=10,
+ consolidation="template", # Uses serper_scholar template automatically
+)
+# Scholar results include in attributes: publicationInfo, citedBy, pdfUrl, year, paperId
+```
+
+#### Jina
+```python
+result = web_search(
+ query="Python async programming guide",
+ provider="jina",
+ enrich=True, # Full content + images (default: True)
+ timeout=60, # Request timeout in seconds
+)
+
+# Basic mode (SERP only, no content extraction)
+result = web_search(
+ query="Python async programming guide",
+ provider="jina",
+ enrich=False, # Basic SERP only, faster
+)
+```
+
+## Configuration
+
+### Environment Variables
+
+```bash
+# Provider selection (optional)
+export SEARCH_PROVIDER=tavily
+
+# API Keys
+export PERPLEXITY_API_KEY=your_key
+export TAVILY_API_KEY=your_key
+export EXA_API_KEY=your_key
+export BAIDU_API_KEY=your_key
+export SERPER_API_KEY=your_key
+export JINA_API_KEY=your_key
+```
+
+### YAML Configuration (`config/main.yaml`)
+
+```yaml
+tools:
+ web_search:
+ enabled: true
+ provider: perplexity
+ consolidation: template # "none", "template", "llm"
+```
+
+### Priority Order
+
+1. Function argument (`provider="tavily"`)
+2. Environment variable (`SEARCH_PROVIDER`)
+3. YAML config (`config/main.yaml`)
+4. Default (`perplexity`)
+
+## Response Format
+
+All providers return a standardized dictionary:
+
+```python
+{
+ "timestamp": "2024-01-15T10:30:00.000000",
+ "query": "What is machine learning?",
+ "provider": "tavily",
+ "model": "tavily-basic",
+ "answer": "Machine learning is a subset of AI...",
+ "citations": [
+ {
+ "id": 1,
+ "reference": "[1]",
+ "url": "https://example.com/ml-guide",
+ "title": "Machine Learning Guide",
+ "snippet": "A comprehensive introduction...",
+ "date": "2024-01-10",
+ "source": "example.com",
+ "content": "",
+ "type": "web",
+ "icon": "",
+ "website": "",
+ "web_anchor": ""
+ }
+ ],
+ "search_results": [
+ {
+ "title": "Machine Learning Guide",
+ "url": "https://example.com/ml-guide",
+ "snippet": "A comprehensive introduction...",
+ "date": "2024-01-10",
+ "source": "example.com",
+ "content": "",
+ "score": 0.95
+ }
+ ],
+ "usage": {},
+ "response": {
+ "content": "Machine learning is...",
+ "role": "assistant",
+ "finish_reason": "stop"
+ }
+ # Provider-specific metadata may be merged at top level
+}
+```
+
+## Answer Consolidation
+
+SERP providers (Serper, Jina) don't generate LLM answers. Use consolidation to generate answers from raw results:
+
+### Template Consolidation
+
+Uses provider-specific Jinja2 templates. **Available for: `serper`, `serper_scholar`, `jina`**.
+
+When using Serper with `mode="scholar"`, the provider automatically returns `provider="serper_scholar"` which triggers the academic-focused template with publication info, authors, and citation counts.
+
+```python
+result = web_search(
+ query="Python best practices",
+ provider="serper",
+ consolidation="template",
+)
+
+# Scholar mode with automatic template selection
+result = web_search(
+ query="deep learning optimization",
+ provider="serper",
+ mode="scholar", # Automatically uses serper_scholar template
+ consolidation="template",
+)
+```
+
+### LLM Consolidation
+
+Uses the project's LLM client to synthesize answers. Works with any provider.
+
+```python
+result = web_search(
+ query="Python best practices",
+ provider="serper",
+ consolidation="llm",
+)
+```
+
+### Custom Template
+
+```python
+result = web_search(
+ query="Python best practices",
+ provider="serper",
+ consolidation="template",
+ consolidation_custom_template="""
+# Results for: {{ query }}
+
+{% for result in results[:5] %}
+## {{ result.title }}
+{{ result.snippet }}
+[Source]({{ result.url }})
+{% endfor %}
+""",
+)
+```
+
+---
+
+# Creating New Providers
+
+This section documents how to add new search providers to the web_search module.
+
+## Architecture Overview
+
+```
+src/tools/web_search/
+├── __init__.py # Main entry point, web_search() function
+├── base.py # BaseSearchProvider abstract class
+├── types.py # WebSearchResponse, Citation, SearchResult dataclasses
+├── consolidation.py # Answer consolidation (template/LLM)
+├── utils.py # Helper utilities
+└── providers/
+ ├── __init__.py # Provider registry (@register_provider decorator)
+ ├── perplexity.py
+ ├── tavily.py
+ ├── exa.py
+ ├── baidu.py
+ ├── serper.py
+ └── jina.py
+```
+
+## Step 1: Create Provider File
+
+Create `src/tools/web_search/providers/my_provider.py`:
+
+```python
+"""
+MyProvider Search Provider
+
+API Docs: https://api.myprovider.com/docs
+"""
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("myprovider")
+class MyProvider(BaseSearchProvider):
+ """My custom search provider"""
+
+ # =========================================================================
+ # REQUIRED CLASS ATTRIBUTES
+ # =========================================================================
+
+ # Human-readable name for UI display
+ display_name = "MyProvider"
+
+ # Short description for UI
+ description = "My custom search engine"
+
+ # Environment variable name for API key
+ api_key_env_var = "MYPROVIDER_API_KEY"
+
+ # Does this provider generate LLM answers?
+ # - True: AI providers (Perplexity, Tavily, Exa, Baidu)
+ # - False: SERP providers (Serper, Jina) - need consolidation for answers
+ supports_answer = True
+
+ # =========================================================================
+ # OPTIONAL CLASS ATTRIBUTES
+ # =========================================================================
+
+ # Set to False if provider has a free tier (like Jina)
+ # Default: True
+ requires_api_key = True
+
+ # Provider name (auto-set by @register_provider decorator)
+ # Only override if you need a different internal name
+ # name = "myprovider"
+
+ # =========================================================================
+ # PROVIDER IMPLEMENTATION
+ # =========================================================================
+
+ BASE_URL = "https://api.myprovider.com/search"
+
+ def search(
+ self,
+ query: str,
+ # Add your provider-specific parameters here
+ max_results: int = 10,
+ language: str = "en",
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Execute search and return standardized response.
+
+ Args:
+ query: Search query string.
+ max_results: Maximum results to return.
+ language: Language code.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options (passed from web_search()).
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ # Use self.logger for logging (auto-configured in base class)
+ self.logger.debug(f"Calling MyProvider API max_results={max_results}")
+
+ # Use self.api_key (auto-loaded from env var or constructor)
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+
+ payload = {
+ "query": query,
+ "limit": max_results,
+ "lang": language,
+ }
+
+ response = requests.post(
+ self.BASE_URL,
+ headers=headers,
+ json=payload,
+ timeout=timeout,
+ )
+
+ if response.status_code != 200:
+ self.logger.error(f"MyProvider API error: {response.status_code}")
+ raise Exception(
+ f"MyProvider API error: {response.status_code} - {response.text}"
+ )
+
+ data = response.json()
+ self.logger.debug(f"MyProvider returned {len(data.get('results', []))} results")
+
+ # =====================================================================
+ # CONVERT API RESPONSE TO STANDARDIZED FORMAT
+ # =====================================================================
+
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ for i, item in enumerate(data.get("results", []), 1):
+ # Build SearchResult
+ sr = SearchResult(
+ title=item.get("title", ""),
+ url=item.get("url", ""),
+ snippet=item.get("snippet", ""),
+ date=item.get("published_date", ""),
+ source=item.get("domain", ""),
+ content=item.get("full_content", ""), # Full text if available
+ score=item.get("relevance_score", 0.0),
+ # Optional: sitelinks and attributes
+ sitelinks=[], # list[dict] with "title" and "link" keys
+ attributes={}, # dict with any extra data
+ )
+ search_results.append(sr)
+
+ # Build Citation (parallel to SearchResult)
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=item.get("url", ""),
+ title=item.get("title", ""),
+ snippet=item.get("snippet", ""),
+ date=item.get("published_date", ""),
+ source=item.get("domain", ""),
+ content=item.get("full_content", ""),
+ )
+ )
+
+ # Build the response
+ return WebSearchResponse(
+ query=query,
+ answer=data.get("generated_answer", ""), # Empty string for SERP providers
+ provider="myprovider",
+ timestamp=datetime.now().isoformat(),
+ model=data.get("model_used", "myprovider-default"),
+ citations=citations,
+ search_results=search_results,
+ usage={
+ # Token usage if available
+ "prompt_tokens": data.get("usage", {}).get("prompt_tokens", 0),
+ "completion_tokens": data.get("usage", {}).get("completion_tokens", 0),
+ "total_tokens": data.get("usage", {}).get("total_tokens", 0),
+ },
+ metadata={
+ "finish_reason": "stop",
+ # Add any provider-specific metadata here
+ # This data is available for template consolidation
+ },
+ )
+```
+
+## Step 2: Register the Provider
+
+Add the import to `src/tools/web_search/providers/__init__.py`:
+
+```python
+# At the bottom of the file, add your provider to the imports:
+from . import perplexity, baidu, tavily, exa, serper, jina, my_provider
+```
+
+That's it! The `@register_provider("myprovider")` decorator automatically registers your provider in the global registry.
+
+## Step 3: (Optional) Add Consolidation Template
+
+If your provider is a SERP provider (`supports_answer = False`), you can add a Jinja2 template for template consolidation.
+
+Edit `src/tools/web_search/consolidation.py`:
+
+```python
+# 1. Add to PROVIDER_TEMPLATES dict (module-level):
+PROVIDER_TEMPLATES = {
+ # ... existing templates ...
+
+ "myprovider": """### Search Results for "{{ query }}"
+
+{% for result in results[:max_results] %}
+**[{{ loop.index }}] {{ result.title }}**
+{{ result.snippet }}
+🔗 {{ result.url }}
+{% if result.date %}📅 {{ result.date }}{% endif %}
+
+{% endfor %}
+---
+*{{ results|length }} results from MyProvider*""",
+}
+
+# 2. Add to AnswerConsolidator.PROVIDER_TEMPLATE_MAP (class attribute):
+class AnswerConsolidator:
+ PROVIDER_TEMPLATE_MAP = {
+ "serper": "serper",
+ "jina": "jina",
+ "serper_scholar": "serper_scholar",
+ "myprovider": "myprovider", # Add this line
+ }
+```
+
+### Template Context Variables
+
+These variables are available in all templates:
+
+| Variable | Type | Description |
+|----------|------|-------------|
+| `query` | `str` | Original search query |
+| `provider` | `str` | Provider name |
+| `model` | `str` | Model used |
+| `max_results` | `int` | Max results to display (default: 5) |
+| `results` | `list[dict]` | Search results with `title`, `url`, `snippet`, `date`, `source`, `content`, `sitelinks`, `attributes` |
+| `citations` | `list[dict]` | Citations with `id`, `reference`, `url`, `title`, `snippet` |
+| `timestamp` | `str` | ISO timestamp |
+
+Provider-specific metadata from `WebSearchResponse.metadata` is also available. For example, Serper templates have access to:
+- `knowledge_graph`
+- `answer_box`
+- `people_also_ask`
+- `related_searches`
+
+## Step 4: Test Your Provider
+
+```python
+from src.tools.web_search import web_search, list_providers, get_available_providers
+
+# Verify registration
+print(list_providers())
+# ['baidu', 'exa', 'jina', 'myprovider', 'perplexity', 'serper', 'tavily']
+
+# Check if available (API key set)
+print(get_available_providers())
+
+# Test search
+result = web_search("test query", provider="myprovider")
+print(result["answer"])
+print(result["citations"])
+
+# Test with consolidation (for SERP providers)
+result = web_search(
+ "test query",
+ provider="myprovider",
+ consolidation="template",
+)
+```
+
+## BaseSearchProvider Reference
+
+```python
+class BaseSearchProvider(ABC):
+ """Abstract base class for search providers"""
+
+ # Class attributes (override in subclass)
+ name: str = "base" # Auto-set by @register_provider
+ display_name: str = "Base Provider" # Human-readable name
+ description: str = "" # Short description
+ requires_api_key: bool = True # False for free-tier providers
+ api_key_env_var: str = "" # Env var name for API key
+ supports_answer: bool = False # True for AI providers
+
+ def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
+ """
+ Initialize the provider.
+
+ Args:
+ api_key: API key. If not provided, reads from api_key_env_var.
+ **kwargs: Additional config stored in self.config.
+ """
+ self.logger = get_logger(f"WebSearch.{self.__class__.__name__}")
+ self.api_key = api_key or self._get_api_key()
+ self.config = kwargs
+
+ @abstractmethod
+ def search(self, query: str, **kwargs: Any) -> WebSearchResponse:
+ """Execute search - MUST be implemented by subclass."""
+ pass
+
+ def is_available(self) -> bool:
+ """Check if provider is available (API key set if required)."""
+ if self.requires_api_key:
+ return bool(self.api_key)
+ return True
+```
+
+## Types Reference
+
+### WebSearchResponse
+
+```python
+@dataclass
+class WebSearchResponse:
+ query: str # Original search query
+ answer: str # LLM answer (empty for SERP)
+ provider: str # Provider name
+ timestamp: str # ISO timestamp
+ model: str # Model used
+ citations: list[Citation] # Citation list
+ search_results: list[SearchResult] # Raw search results
+ usage: dict[str, Any] # Token/cost usage
+ metadata: dict[str, Any] # Provider-specific data
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to backward-compatible dict format."""
+```
+
+### Citation
+
+```python
+@dataclass
+class Citation:
+ id: int # Citation number (1, 2, 3...)
+ reference: str # Display reference ("[1]", "[2]"...)
+ url: str # Source URL
+ title: str = "" # Page title
+ snippet: str = "" # Text snippet
+ date: str = "" # Publication date
+ source: str = "" # Source domain
+ content: str = "" # Full content if available
+ # Additional fields for backward compatibility
+ type: str = "web" # Citation type (web, pdf, etc.)
+ icon: str = "" # Source icon URL
+ website: str = "" # Website name
+ web_anchor: str = "" # Web anchor text
+```
+
+### SearchResult
+
+```python
+@dataclass
+class SearchResult:
+ title: str # Result title
+ url: str # Result URL
+ snippet: str # Text snippet
+ date: str = "" # Publication date
+ source: str = "" # Source domain
+ content: str = "" # Full content if available
+ score: float = 0.0 # Relevance score
+ sitelinks: list[dict[str, str]] = [] # Related links
+ attributes: dict[str, Any] = {} # Additional attributes
+```
+
+## Helper Functions
+
+```python
+from src.tools.web_search import (
+ web_search, # Main search function
+ get_current_config, # Get active configuration
+ list_providers, # List all registered providers
+ get_available_providers, # List providers with API keys set
+ get_provider, # Get a provider instance directly
+ get_default_provider, # Get default provider instance
+ WebSearchResponse, # Response dataclass
+ Citation, # Citation dataclass
+ SearchResult, # SearchResult dataclass
+ AnswerConsolidator, # Consolidation class
+)
+
+# From providers submodule (for advanced use)
+from src.tools.web_search.providers import (
+ get_providers_info, # Get full provider info for frontend display
+ register_provider, # Decorator to register custom providers
+)
+```
+
+## Example: Real Provider Implementation
+
+Here's a simplified version of the Tavily provider as reference:
+
+```python
+@register_provider("tavily")
+class TavilyProvider(BaseSearchProvider):
+ """Tavily research-focused search provider"""
+
+ display_name = "Tavily"
+ description = "Research-focused search"
+ api_key_env_var = "TAVILY_API_KEY"
+ supports_answer = True # Tavily generates LLM answers
+
+ BASE_URL = "https://api.tavily.com/search"
+
+ def search(
+ self,
+ query: str,
+ search_depth: str = "basic",
+ topic: str = "general",
+ max_results: int = 10,
+ include_answer: bool = True,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ self.logger.debug(f"Calling Tavily API depth={search_depth}")
+
+ payload = {
+ "api_key": self.api_key,
+ "query": query,
+ "search_depth": search_depth,
+ "topic": topic,
+ "max_results": max_results,
+ "include_answer": include_answer,
+ }
+
+ response = requests.post(self.BASE_URL, json=payload, timeout=timeout)
+
+ if response.status_code != 200:
+ raise Exception(f"Tavily API error: {response.status_code}")
+
+ data = response.json()
+
+ citations = []
+ search_results = []
+
+ for i, result in enumerate(data.get("results", []), 1):
+ sr = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=result.get("content", ""),
+ score=result.get("score", 0.0),
+ )
+ search_results.append(sr)
+ citations.append(Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=result.get("url", ""),
+ title=result.get("title", ""),
+ snippet=result.get("content", ""),
+ ))
+
+ return WebSearchResponse(
+ query=query,
+ answer=data.get("answer", ""),
+ provider="tavily",
+ timestamp=datetime.now().isoformat(),
+ model=f"tavily-{search_depth}",
+ citations=citations,
+ search_results=search_results,
+ usage={},
+ metadata={"search_depth": search_depth},
+ )
+```
diff --git a/src/tools/web_search/__init__.py b/src/tools/web_search/__init__.py
new file mode 100644
index 000000000..68592b96f
--- /dev/null
+++ b/src/tools/web_search/__init__.py
@@ -0,0 +1,254 @@
+"""
+Web Search Tool - Pluggable search provider architecture
+
+This module provides a unified interface for web search across multiple providers.
+
+Usage:
+ from src.tools.web_search import web_search
+
+ # Simple usage (uses config/main.yaml or SEARCH_PROVIDER env var)
+ result = web_search("What is AI?")
+
+ # Specify provider
+ result = web_search("What is AI?", provider="tavily")
+
+ # With options
+ result = web_search(
+ query="What is AI?",
+ provider="serper",
+ output_dir="./cache",
+ verbose=True,
+ num=20, # Provider-specific option
+ )
+
+Available Providers:
+ - perplexity: AI-powered search (default)
+ - baidu: Baidu AI Search
+ - tavily: Research-focused with optional answers
+ - exa: Neural/embeddings search with summaries
+ - serper: Google SERP results
+ - jina: SERP with full content extraction
+"""
+import os
+from datetime import datetime
+from typing import Any
+
+from src.logging import get_logger
+from src.services.config import load_config_with_main, PROJECT_ROOT
+
+from .providers import (
+ get_available_providers,
+ get_default_provider,
+ get_provider,
+ list_providers,
+)
+from .types import Citation, SearchResult, WebSearchResponse
+from ._legacy import SearchProvider
+from .consolidation import AnswerConsolidator
+from .utils import save_results
+
+# Module logger
+_logger = get_logger("WebSearch", level="INFO")
+
+
+def _get_web_search_config() -> dict[str, Any]:
+ """
+ Load web search configuration from config/main.yaml using the standard config loader.
+
+ Returns:
+ dict with web_search config from tools.web_search section
+ """
+ try:
+ config = load_config_with_main("main.yaml", PROJECT_ROOT)
+ return config.get("tools", {}).get("web_search", {})
+ except Exception as e:
+ _logger.debug(f"Could not load config: {e}")
+ return {}
+
+
+def web_search(
+ query: str,
+ output_dir: str | None = None,
+ verbose: bool = False,
+ provider: str | None = None,
+ # Consolidation options (only for SERP providers: serper, jina)
+ consolidation: str | None = None, # none, template, llm
+ consolidation_custom_template: str | None = None, # Custom Jinja2 template
+ consolidation_llm_model: str | None = None, # Model for LLM consolidation
+ # Legacy Baidu-specific params (for backward compatibility)
+ baidu_model: str = "ernie-4.5-turbo-32k",
+ baidu_enable_deep_search: bool = False,
+ baidu_search_recency_filter: str = "week",
+ **provider_kwargs: Any,
+) -> dict[str, Any]:
+ """
+ Perform web search using configured provider.
+
+ Args:
+ query: Search query.
+ output_dir: Output directory for saving results (optional).
+ verbose: Whether to print detailed information.
+ provider: Provider name (perplexity, baidu, tavily, exa, serper, jina).
+ If not specified, uses SEARCH_PROVIDER env var (default: perplexity).
+ consolidation: Answer consolidation type ("none", "template", "llm").
+ Only for SERP providers (serper, jina) that return raw results.
+ Template consolidation uses provider-specific templates.
+ AI providers (perplexity, baidu, tavily, exa) already include answers.
+ consolidation_custom_template: Custom Jinja2 template string for unsupported providers.
+ consolidation_llm_model: LLM model for llm consolidation (default: gpt-4o-mini).
+ baidu_model: Model to use for Baidu AI Search (legacy param).
+ baidu_enable_deep_search: Enable deep search for Baidu (legacy param).
+ baidu_search_recency_filter: Recency filter for Baidu (legacy param).
+ **provider_kwargs: Provider-specific options.
+
+ Returns:
+ dict: Search results with answer, citations, search_results, etc.
+
+ Raises:
+ ImportError: If required module is not installed.
+ ValueError: If required environment variable is not set.
+ Exception: If API call fails.
+
+ Example:
+ >>> result = web_search("What is machine learning?")
+ >>> print(result["answer"])
+ Machine learning is a subset of artificial intelligence...
+ >>> print(result["citations"])
+ [{"id": 1, "url": "https://...", "title": "...", ...}]
+ """
+ # Load config from main.yaml
+ config = _get_web_search_config()
+
+ # Check if web_search is enabled (default: True)
+ if not config.get("enabled", True):
+ _logger.warning("Web search is disabled in config")
+ return {
+ "timestamp": datetime.now().isoformat(),
+ "query": query,
+ "answer": "Web search is disabled.",
+ "citations": [],
+ "search_results": [],
+ "provider": "disabled",
+ }
+
+ # Determine provider: function arg > env var > config > default
+ provider_name = (
+ provider
+ or os.environ.get("SEARCH_PROVIDER")
+ or config.get("provider")
+ or "perplexity"
+ ).lower()
+
+ # Determine consolidation from config if not provided
+ if consolidation is None:
+ consolidation = config.get("consolidation")
+
+ # Determine custom template from config if not provided
+ if consolidation_custom_template is None:
+ consolidation_custom_template = config.get("consolidation_template") or None
+
+ # Handle legacy Baidu params
+ if provider_name == "baidu":
+ provider_kwargs.setdefault("model", baidu_model)
+ provider_kwargs.setdefault("enable_deep_search", baidu_enable_deep_search)
+ provider_kwargs.setdefault("search_recency_filter", baidu_search_recency_filter)
+
+ # Get provider instance
+ search_provider = get_provider(provider_name)
+
+ _logger.progress(f"[{search_provider.name}] Searching: {query[:50]}...")
+
+ # Execute search
+ try:
+ response = search_provider.search(query, **provider_kwargs)
+ _logger.success(f"[{search_provider.name}] Search completed")
+ except Exception as e:
+ _logger.error(f"[{search_provider.name}] Search failed: {e}")
+ raise Exception(f"{search_provider.name} search failed: {e}")
+ # Apply consolidation for SERP providers without LLM answers
+ if consolidation and not search_provider.supports_answer:
+ llm_config = {}
+ if consolidation_llm_model:
+ llm_config["model"] = consolidation_llm_model
+
+ consolidator = AnswerConsolidator(
+ consolidation_type=consolidation,
+ custom_template=consolidation_custom_template,
+ llm_config=llm_config if llm_config else None,
+ )
+ response = consolidator.consolidate(response)
+
+ # Convert to dict (backward compatible format)
+ result = response.to_dict()
+
+ # Save if output_dir provided
+ if output_dir:
+ output_path = save_results(result, output_dir, provider_name)
+ result["result_file"] = output_path
+ _logger.debug(f"Search results saved to: {output_path}")
+
+ if verbose:
+ answer = result.get("answer", "")
+ _logger.info(f"Query: {query}")
+ if answer:
+ _logger.info(f"Answer: {answer[:200]}..." if len(answer) > 200 else f"Answer: {answer}")
+ _logger.info(f"Citations: {len(result.get('citations', []))}")
+
+ return result
+
+
+def get_current_config() -> dict[str, Any]:
+ """
+ Get the current web search configuration.
+
+ Returns:
+ dict with:
+ - enabled: bool
+ - provider: str (effective provider name)
+ - consolidation: str | None
+ - consolidation_template: str | None (custom Jinja2 template)
+ - providers: list[dict] (full provider info for frontend)
+ - consolidation_types: list[str]
+ - template_providers: list[str] (providers that support template consolidation)
+ - config_source: "env" | "yaml" | "default"
+ """
+ from .providers import get_providers_info
+ from .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES
+
+ config = _get_web_search_config()
+
+ # Determine effective provider
+ provider = (
+ os.environ.get("SEARCH_PROVIDER")
+ or config.get("provider")
+ or "perplexity"
+ ).lower()
+
+ return {
+ "enabled": config.get("enabled", True),
+ "provider": provider,
+ "consolidation": config.get("consolidation"),
+ "consolidation_template": config.get("consolidation_template") or None,
+ # For frontend display
+ "providers": get_providers_info(),
+ "consolidation_types": CONSOLIDATION_TYPES,
+ # Only these providers support template consolidation
+ "template_providers": list(PROVIDER_TEMPLATES.keys()),
+ "config_source": "env" if os.environ.get("SEARCH_PROVIDER") else "yaml" if config.get("provider") else "default",
+ }
+
+
+# Export public API
+__all__ = [
+ "web_search",
+ "get_current_config",
+ "get_provider",
+ "list_providers",
+ "get_available_providers",
+ "get_default_provider",
+ "WebSearchResponse",
+ "Citation",
+ "SearchResult",
+ "AnswerConsolidator",
+ "SearchProvider",
+]
diff --git a/src/tools/web_search/_legacy.py b/src/tools/web_search/_legacy.py
new file mode 100644
index 000000000..eb9e4b142
--- /dev/null
+++ b/src/tools/web_search/_legacy.py
@@ -0,0 +1,23 @@
+"""
+Legacy SearchProvider enum for backward compatibility.
+
+This enum is kept for any existing code that imports it.
+New code should use provider names as strings with the web_search() function.
+"""
+from enum import Enum
+
+
+class SearchProvider(str, Enum):
+ """
+ Supported search providers.
+
+ DEPRECATED: Use provider names directly as strings with web_search().
+ Example: web_search(query="...", provider="perplexity")
+ """
+
+ PERPLEXITY = "perplexity"
+ BAIDU = "baidu"
+ TAVILY = "tavily"
+ EXA = "exa"
+ SERPER = "serper"
+ JINA = "jina"
diff --git a/src/tools/web_search/base.py b/src/tools/web_search/base.py
new file mode 100644
index 000000000..5792cbf02
--- /dev/null
+++ b/src/tools/web_search/base.py
@@ -0,0 +1,77 @@
+"""
+Web Search Base Provider - Abstract base class for all search providers
+
+This module defines the BaseSearchProvider class that all search providers must inherit from.
+"""
+from abc import ABC, abstractmethod
+import os
+from typing import Any
+
+from src.logging import get_logger
+
+from .types import WebSearchResponse
+
+
+class BaseSearchProvider(ABC):
+ """Abstract base class for search providers"""
+
+ name: str = "base"
+ display_name: str = "Base Provider"
+ description: str = ""
+ requires_api_key: bool = True
+ api_key_env_var: str = ""
+ supports_answer: bool = False # Whether provider generates LLM answers
+
+ def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
+ """
+ Initialize the provider.
+
+ Args:
+ api_key: API key for the provider. If not provided, will be read from environment.
+ **kwargs: Additional configuration options.
+ """
+ self.logger = get_logger(f"WebSearch.{self.__class__.__name__}", level="INFO")
+ self.api_key = api_key or self._get_api_key()
+ self.config = kwargs
+
+ def _get_api_key(self) -> str:
+ """Get API key from environment variable"""
+ if not self.api_key_env_var:
+ return ""
+ key = os.environ.get(self.api_key_env_var, "")
+ if self.requires_api_key and not key:
+ raise ValueError(
+ f"{self.name} requires {self.api_key_env_var} environment variable. "
+ f"Please set it before using this provider."
+ )
+ return key
+
+ @abstractmethod
+ def search(self, query: str, **kwargs: Any) -> WebSearchResponse:
+ """
+ Execute search and return standardized response.
+
+ Args:
+ query: The search query.
+ **kwargs: Provider-specific options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ pass
+
+ def is_available(self) -> bool:
+ """
+ Check if provider is available (dependencies installed, API key set).
+
+ Returns:
+ bool: True if provider is available, False otherwise.
+ """
+ try:
+ if self.requires_api_key:
+ key = self.api_key or os.environ.get(self.api_key_env_var, "")
+ if not key:
+ return False
+ return True
+ except (ValueError, ImportError):
+ return False
diff --git a/src/tools/web_search/consolidation.py b/src/tools/web_search/consolidation.py
new file mode 100644
index 000000000..5723355ef
--- /dev/null
+++ b/src/tools/web_search/consolidation.py
@@ -0,0 +1,380 @@
+"""
+Answer Consolidation - Generate answers from raw search results
+
+Supports two strategies:
+1. template: Fast Jinja2 template rendering
+2. llm: LLM-based answer synthesis (uses project's LLM config from env vars)
+"""
+from typing import Any
+
+from jinja2 import BaseLoader, Environment
+
+from src.logging import get_logger
+from src.services.llm import get_llm_client
+
+from .types import WebSearchResponse
+
+# Module logger
+_logger = get_logger("WebSearch.Consolidation", level="INFO")
+
+
+# Available consolidation types
+CONSOLIDATION_TYPES = ["none", "template", "llm"]
+
+
+# =============================================================================
+# PROVIDER-SPECIFIC TEMPLATES
+# =============================================================================
+# Only providers that return raw SERP results (supports_answer=False) need templates.
+# AI providers (Perplexity, Tavily, Baidu, Exa) already generate answers.
+PROVIDER_TEMPLATES = {
+ # -------------------------------------------------------------------------
+ # SERPER TEMPLATE
+ # -------------------------------------------------------------------------
+ "serper": """{% if knowledge_graph %}
+## {{ knowledge_graph.title }}{% if knowledge_graph.type %} ({{ knowledge_graph.type }}){% endif %}
+
+{{ knowledge_graph.description }}
+{% if knowledge_graph.attributes %}
+{% for key, value in knowledge_graph.attributes.items() %}
+- **{{ key }}**: {{ value }}
+{% endfor %}
+{% endif %}
+{% if knowledge_graph.website %}🔗 [{{ knowledge_graph.website }}]({{ knowledge_graph.website }}){% endif %}
+
+---
+{% endif %}
+{% if answer_box %}
+### Direct Answer
+{{ answer_box.answer or answer_box.snippet }}
+{% if answer_box.title %}*Source: [{{ answer_box.title }}]({{ answer_box.link }})*{% endif %}
+
+---
+{% endif %}
+### Search Results for "{{ query }}"
+
+{% for result in results[:max_results] %}
+**[{{ loop.index }}] {{ result.title }}**
+{{ result.snippet }}
+{% if result.date %}📅 {{ result.date }}{% endif %}
+🔗 {{ result.url }}
+{% if result.sitelinks %}
+ └ Related: {% for link in result.sitelinks[:3] %}[{{ link.title }}]({{ link.link }}){% if not loop.last %} | {% endif %}{% endfor %}
+{% endif %}
+
+{% endfor %}
+{% if people_also_ask %}
+---
+### People Also Ask
+{% for qa in people_also_ask[:3] %}
+**Q: {{ qa.question }}**
+{{ qa.snippet }}
+*[{{ qa.title }}]({{ qa.link }})*
+
+{% endfor %}
+{% endif %}
+{% if related_searches %}
+---
+*Related searches: {% for rs in related_searches[:5] %}{{ rs.query }}{% if not loop.last %}, {% endif %}{% endfor %}*
+{% endif %}""",
+ # -------------------------------------------------------------------------
+ # JINA TEMPLATE
+ # -------------------------------------------------------------------------
+ "jina": """### Search Results for "{{ query }}"
+
+{% for result in results[:max_results] %}
+---
+## [{{ loop.index }}] {{ result.title }}
+
+{% if result.attributes.date %}📅 *{{ result.attributes.date }}*{% endif %}
+
+{% if result.content %}
+{% if result.snippet %}*{{ result.snippet }}*{% endif %}
+
+### Content Preview
+{{ result.content[:2000] }}{% if result.content|length > 2000 %}
+
+*[Content truncated - {{ result.attributes.tokens|default('many') }} tokens total]*{% endif %}
+{% else %}
+*{{ result.snippet }}*
+{% endif %}
+
+🔗 [{{ result.url }}]({{ result.url }})
+
+{% endfor %}
+---
+*{{ results|length }} results via Jina Reader{% if not results[0].content %} (no-content mode){% endif %}*
+
+{% if links %}
+### Extracted Links
+{% for name, url in links.items()[:10] %}
+- [{{ name }}]({{ url }})
+{% endfor %}
+{% endif %}
+{% if images %}
+### Images Found
+{% for alt, src in images.items()[:5] %}
+- ![{{ alt }}]({{ src }})
+{% endfor %}
+{% endif %}""",
+ # -------------------------------------------------------------------------
+ # SERPER SCHOLAR TEMPLATE
+ # -------------------------------------------------------------------------
+ "serper_scholar": """### Academic Results for "{{ query }}"
+
+{% for result in results[:max_results] %}
+**[{{ loop.index }}] {{ result.title }}**{% if result.attributes.year %} ({{ result.attributes.year }}){% endif %}
+
+{% if result.attributes.publicationInfo %}*{{ result.attributes.publicationInfo }}*{% endif %}
+
+{{ result.snippet }}
+
+{% if result.attributes.pdfUrl %}📄 [PDF]({{ result.attributes.pdfUrl }}) | {% endif %}🔗 [Link]({{ result.url }})
+{% if result.attributes.citedBy %}📚 Cited by: {{ result.attributes.citedBy }}{% endif %}
+
+{% endfor %}
+---
+*{{ results|length }} academic papers found via Google Scholar*""",
+}
+
+
+class AnswerConsolidator:
+ """
+ Consolidate raw SERP results into formatted answers.
+
+ IMPORTANT: Template consolidation only works for providers that have
+ specific templates defined (serper, jina, serper_scholar).
+
+ For other providers, use:
+ - consolidation_type="llm" for LLM-based synthesis
+ - custom_template for a custom Jinja2 template
+ """
+
+ # Map provider names to their specific templates
+ # Only these providers support template consolidation
+ PROVIDER_TEMPLATE_MAP = {
+ "serper": "serper",
+ "jina": "jina",
+ "serper_scholar": "serper_scholar",
+ }
+
+ def __init__(
+ self,
+ consolidation_type: str = "template",
+ custom_template: str | None = None,
+ llm_config: dict[str, Any] | None = None,
+ max_results: int = 5,
+ ):
+ """
+ Initialize consolidator.
+
+ Args:
+ consolidation_type: "none", "template", or "llm"
+ custom_template: Custom Jinja2 template string
+ llm_config: Optional overrides (system_prompt, max_tokens, temperature)
+ max_results: Maximum results to include in answer
+ """
+ self.consolidation_type = consolidation_type
+ self.custom_template = custom_template
+ self.llm_config = llm_config or {}
+ self.max_results = max_results
+ self.jinja_env = Environment(loader=BaseLoader())
+
+ def consolidate(self, response: WebSearchResponse) -> WebSearchResponse:
+ """
+ Consolidate search results into an answer.
+
+ Args:
+ response: WebSearchResponse with search_results populated
+
+ Returns:
+ WebSearchResponse with answer field populated
+ """
+ if self.consolidation_type == "none":
+ _logger.debug(f"Consolidation disabled, returning raw response")
+ return response
+
+ results_count = len(response.search_results)
+ _logger.info(f"Consolidating {results_count} results from {response.provider} using {self.consolidation_type}")
+
+ if self.consolidation_type == "template":
+ response.answer = self._consolidate_with_template(response)
+ _logger.success(f"Template consolidation completed ({len(response.answer)} chars)")
+ elif self.consolidation_type == "llm":
+ response.answer = self._consolidate_with_llm(response)
+ _logger.success(f"LLM consolidation completed ({len(response.answer)} chars)")
+ else:
+ _logger.error(f"Unknown consolidation type: {self.consolidation_type}")
+ raise ValueError(f"Unknown consolidation type: {self.consolidation_type}")
+
+ return response
+
+ def _get_template_for_provider(self, provider: str) -> str:
+ """
+ Get the template for a specific provider.
+
+ Only provider-specific templates exist because each provider has
+ different response schemas and metadata. No universal templates.
+
+ Args:
+ provider: Provider name (e.g., "serper", "jina")
+
+ Returns:
+ Template string for this provider
+
+ Raises:
+ ValueError: If no template exists for this provider
+ """
+ # 1. Custom template takes highest priority
+ if self.custom_template:
+ _logger.debug(f"Using custom template ({len(self.custom_template)} chars)")
+ return self.custom_template
+
+ # 2. Get provider-specific template
+ template_key = self.PROVIDER_TEMPLATE_MAP.get(provider.lower())
+ if template_key and template_key in PROVIDER_TEMPLATES:
+ _logger.debug(f"Using provider-specific template: {template_key}")
+ return PROVIDER_TEMPLATES[template_key]
+
+ # 3. No template exists for this provider - fail explicitly
+ available = list(PROVIDER_TEMPLATES.keys())
+ _logger.error(f"No template for provider '{provider}'. Available: {available}")
+ raise ValueError(
+ f"No template consolidation available for provider '{provider}'. "
+ f"Template consolidation only works with: {available}. "
+ f"Use consolidation='llm' or provide a custom_template for other providers."
+ )
+
+ def _build_provider_context(self, response: WebSearchResponse) -> dict[str, Any]:
+ """
+ Build template context with provider-specific fields.
+
+ Each provider has unique response fields that we extract from metadata.
+ """
+ # Base context (common to all providers)
+ context: dict[str, Any] = {
+ "query": response.query,
+ "provider": response.provider,
+ "model": response.model,
+ "max_results": self.max_results,
+ "results": [
+ {
+ "title": r.title,
+ "url": r.url,
+ "snippet": r.snippet,
+ "date": r.date,
+ "source": r.source,
+ "content": r.content,
+ "sitelinks": r.sitelinks,
+ "attributes": r.attributes,
+ }
+ for r in response.search_results
+ ],
+ "citations": [
+ {
+ "id": c.id,
+ "reference": c.reference,
+ "url": c.url,
+ "title": c.title,
+ "snippet": c.snippet,
+ }
+ for c in response.citations
+ ],
+ "timestamp": response.timestamp,
+ }
+
+ # Extract provider-specific metadata
+ metadata = response.metadata or {}
+ provider_lower = response.provider.lower()
+
+ # -----------------------------------------------------------------
+ # SERPER-specific context
+ # -----------------------------------------------------------------
+ if provider_lower == "serper":
+ context["knowledge_graph"] = metadata.get("knowledgeGraph")
+ context["answer_box"] = metadata.get("answerBox")
+ context["people_also_ask"] = metadata.get("peopleAlsoAsk")
+ context["related_searches"] = metadata.get("relatedSearches")
+
+ # -----------------------------------------------------------------
+ # JINA-specific context
+ # -----------------------------------------------------------------
+ elif provider_lower == "jina":
+ context["links"] = metadata.get("links", {})
+ context["images"] = metadata.get("images", {})
+
+ return context
+
+ def _consolidate_with_template(self, response: WebSearchResponse) -> str:
+ """Render results using Jinja2 template"""
+ _logger.debug(f"Building template context for {response.provider}")
+
+ # Get template (auto-detect provider-specific if not explicitly set)
+ template_str = self._get_template_for_provider(response.provider)
+ template = self.jinja_env.from_string(template_str)
+
+ # Build context with provider-specific fields
+ context = self._build_provider_context(response)
+ _logger.debug(f"Context has {len(context.get('results', []))} results, {len(context.get('citations', []))} citations")
+
+ try:
+ rendered = template.render(**context)
+ _logger.debug(f"Template rendered successfully")
+ return rendered
+ except Exception as e:
+ _logger.error(f"Template rendering failed: {e}")
+ raise
+
+ def _consolidate_with_llm(self, response: WebSearchResponse) -> str:
+ """Generate answer using LLM."""
+ system_prompt, user_prompt = self._build_prompts(response)
+
+ llm = get_llm_client()
+ max_tokens = self.llm_config.get("max_tokens", 1000)
+ temperature = self.llm_config.get("temperature", 0.3)
+
+ return llm.complete_sync(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ max_tokens=max_tokens,
+ temperature=temperature,
+ )
+
+ def _build_prompts(self, response: WebSearchResponse) -> tuple[str, str]:
+ """Build system and user prompts for LLM consolidation."""
+ results_text = []
+ for i, r in enumerate(response.search_results[:self.max_results], 1):
+ text = f"[{i}] {r.title}\nURL: {r.url}\n"
+ if r.snippet:
+ text += f"{r.snippet}\n"
+ if r.content:
+ text += f"{r.content[:5000]}{'...' if len(r.content) > 5000 else ''}"
+ results_text.append(text)
+
+ system_prompt = self.llm_config.get(
+ "system_prompt",
+ """You are a search result consolidator. Your output will be used as grounding context for another LLM.
+
+Task: Extract and structure relevant information from web search results.
+
+Output format:
+- Start with a brief factual summary (2-3 sentences)
+- List key facts as bullet points with citation numbers [1], [2], etc.
+- Include specific data: numbers, dates, names, definitions
+- Note any conflicting information between sources
+- End with a "Sources:" section listing [n] URL pairs
+
+Be factual and dense. Omit filler words. Prioritize information diversity.""",
+ )
+
+ user_prompt = f"""Query: {response.query}
+
+Search Results:
+---
+{chr(10).join(results_text)}
+---
+
+Consolidate these results into structured grounding context."""
+
+ return system_prompt, user_prompt
+
diff --git a/src/tools/web_search/providers/__init__.py b/src/tools/web_search/providers/__init__.py
new file mode 100644
index 000000000..58c89d564
--- /dev/null
+++ b/src/tools/web_search/providers/__init__.py
@@ -0,0 +1,126 @@
+"""
+Web Search Provider Registry
+
+This module manages the registration and retrieval of search providers.
+"""
+from typing import Type
+import os
+
+from ..base import BaseSearchProvider
+
+_PROVIDERS: dict[str, Type[BaseSearchProvider]] = {}
+
+
+def register_provider(name: str):
+ """
+ Decorator to register a provider.
+
+ Args:
+ name: Name to register the provider under.
+
+ Returns:
+ Decorator function.
+ """
+
+ def decorator(cls: Type[BaseSearchProvider]):
+ _PROVIDERS[name.lower()] = cls
+ cls.name = name.lower()
+ return cls
+
+ return decorator
+
+
+def get_provider(name: str, **kwargs) -> BaseSearchProvider:
+ """
+ Get a provider instance by name.
+
+ Args:
+ name: Provider name (case-insensitive).
+ **kwargs: Arguments to pass to provider constructor.
+
+ Returns:
+ BaseSearchProvider: Provider instance.
+
+ Raises:
+ ValueError: If provider is not found.
+ """
+ name = name.lower()
+ if name not in _PROVIDERS:
+ available = ", ".join(sorted(_PROVIDERS.keys()))
+ raise ValueError(f"Unknown provider: {name}. Available: {available}")
+ return _PROVIDERS[name](**kwargs)
+
+
+def list_providers() -> list[str]:
+ """
+ List all registered providers.
+
+ Returns:
+ list[str]: Sorted list of provider names.
+ """
+ return sorted(_PROVIDERS.keys())
+
+
+def get_available_providers() -> list[str]:
+ """
+ List providers that are currently available (have API keys set).
+
+ Returns:
+ list[str]: Sorted list of available provider names.
+ """
+ available = []
+ for name, cls in _PROVIDERS.items():
+ try:
+ instance = cls()
+ if instance.is_available():
+ available.append(name)
+ except Exception:
+ pass
+ return sorted(available)
+
+
+def get_providers_info() -> list[dict]:
+ """
+ Get full provider info from class attributes for frontend display.
+
+ Returns:
+ list[dict]: List of provider info dicts with id, name, description, keyEnv, supports_answer
+ """
+ providers_info = []
+ for provider_id, cls in sorted(_PROVIDERS.items()):
+ providers_info.append({
+ "id": provider_id,
+ "name": cls.display_name,
+ "description": cls.description,
+ "keyEnv": cls.api_key_env_var,
+ "supports_answer": cls.supports_answer,
+ "requires_api_key": cls.requires_api_key,
+ })
+ return providers_info
+
+
+def get_default_provider(**kwargs) -> BaseSearchProvider:
+ """
+ Get the default provider based on SEARCH_PROVIDER env var.
+
+ Args:
+ **kwargs: Arguments to pass to provider constructor.
+
+ Returns:
+ BaseSearchProvider: Default provider instance.
+ """
+ provider_name = os.environ.get("SEARCH_PROVIDER", "perplexity").lower()
+ return get_provider(provider_name, **kwargs)
+
+
+# Auto-import all providers to trigger registration
+from . import perplexity, baidu, tavily, exa, serper, jina
+
+__all__ = [
+ "register_provider",
+ "get_provider",
+ "list_providers",
+ "get_available_providers",
+ "get_providers_info",
+ "get_default_provider",
+]
diff --git a/src/tools/web_search/providers/baidu.py b/src/tools/web_search/providers/baidu.py
new file mode 100644
index 000000000..5176d3122
--- /dev/null
+++ b/src/tools/web_search/providers/baidu.py
@@ -0,0 +1,187 @@
+"""
+Baidu AI Search Provider
+
+API: https://qianfan.baidubce.com/v2/ai_search/chat/completions
+
+Features:
+- AI-powered search with ERNIE models
+- Deep search mode for comprehensive results
+- Corner markers for reference citations
+- Follow-up query suggestions
+- Recency filtering
+"""
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("baidu")
+class BaiduProvider(BaseSearchProvider):
+ """Baidu AI Search provider"""
+
+ display_name = "Baidu AI"
+ description = "百度AI搜索 with ERNIE models"
+ api_key_env_var = "BAIDU_API_KEY"
+ supports_answer = True
+
+ BASE_URL = "https://qianfan.baidubce.com/v2/ai_search/chat/completions"
+
+ def search(
+ self,
+ query: str,
+ model: str = "ernie-4.5-turbo-32k",
+ search_source: str = "baidu_search_v2",
+ enable_deep_search: bool = False,
+ enable_corner_markers: bool = True,
+ enable_followup_queries: bool = False,
+ temperature: float = 0.11,
+ top_p: float = 0.55,
+ search_mode: str = "auto",
+ search_recency_filter: str | None = None,
+ instruction: str = "",
+ timeout: int = 120,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Perform intelligent search using Baidu AI Search API.
+
+ Args:
+ query: Search query.
+ model: Model to use for generation (default: ernie-4.5-turbo-32k).
+ search_source: Search engine version (baidu_search_v1 or baidu_search_v2).
+ enable_deep_search: Enable deep search for more comprehensive results.
+ enable_corner_markers: Enable corner markers for reference citations.
+ enable_followup_queries: Enable follow-up query suggestions.
+ temperature: Model sampling temperature (0, 1].
+ top_p: Model sampling top_p (0, 1].
+ search_mode: Search mode (auto, required, disabled).
+ search_recency_filter: Filter by recency (week, month, semiyear, year).
+ instruction: System instruction for response style.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ self.logger.debug(f"Calling Baidu API with model={model}, deep_search={enable_deep_search}")
+ headers = {
+ "Content-Type": "application/json",
+ "Authorization": (
+ f"Bearer {self.api_key}"
+ if not self.api_key.startswith("Bearer ")
+ else self.api_key
+ ),
+ }
+
+ payload = {
+ "messages": [{"role": "user", "content": query}],
+ "model": model,
+ "search_source": search_source,
+ "stream": False,
+ "enable_deep_search": enable_deep_search,
+ "enable_corner_markers": enable_corner_markers,
+ "enable_followup_queries": enable_followup_queries,
+ "temperature": temperature,
+ "top_p": top_p,
+ "search_mode": search_mode,
+ }
+
+ if search_recency_filter:
+ payload["search_recency_filter"] = search_recency_filter
+
+ if instruction:
+ payload["instruction"] = instruction
+
+ response = requests.post(
+ self.BASE_URL, headers=headers, json=payload, timeout=timeout
+ )
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ raise Exception(
+ f"Baidu AI Search API error: {response.status_code} - "
+ f"{error_data.get('message', response.text)}"
+ )
+
+ data = response.json()
+
+ # Extract answer from response
+ answer = ""
+ finish_reason = ""
+ if data.get("choices"):
+ choice = data["choices"][0]
+ if choice.get("message"):
+ answer = choice["message"].get("content", "")
+ finish_reason = choice.get("finish_reason", "")
+
+ # Extract usage information
+ usage_info: dict[str, Any] = {}
+ if data.get("usage"):
+ usage = data["usage"]
+ usage_info = {
+ "prompt_tokens": usage.get("prompt_tokens", 0),
+ "completion_tokens": usage.get("completion_tokens", 0),
+ "total_tokens": usage.get("total_tokens", 0),
+ }
+
+ # Extract references/citations
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ if data.get("references"):
+ for i, ref in enumerate(data["references"], 1):
+ citations.append(
+ Citation(
+ id=ref.get("id", i),
+ reference=f"[{ref.get('id', i)}]",
+ url=ref.get("url", ""),
+ title=ref.get("title", ""),
+ snippet=ref.get("content", ""),
+ date=ref.get("date", ""),
+ source=ref.get("web_anchor", ""),
+ type=ref.get("type", "web"),
+ icon=ref.get("icon", ""),
+ website=ref.get("website", ""),
+ web_anchor=ref.get("web_anchor", ""),
+ )
+ )
+
+ search_results.append(
+ SearchResult(
+ title=ref.get("title", ""),
+ url=ref.get("url", ""),
+ snippet=ref.get("content", ""),
+ date=ref.get("date", ""),
+ source=ref.get("web_anchor", ""),
+ )
+ )
+
+ # Build metadata
+ metadata: dict[str, Any] = {
+ "finish_reason": finish_reason,
+ "is_safe": data.get("is_safe", True),
+ "request_id": data.get("request_id", ""),
+ }
+
+ # Add follow-up queries if available
+ if data.get("followup_queries"):
+ metadata["followup_queries"] = data["followup_queries"]
+
+ response_obj = WebSearchResponse(
+ query=query,
+ answer=answer,
+ provider="baidu",
+ timestamp=datetime.now().isoformat(),
+ model=model,
+ citations=citations,
+ search_results=search_results,
+ usage=usage_info,
+ metadata=metadata,
+ )
+
+ return response_obj
diff --git a/src/tools/web_search/providers/exa.py b/src/tools/web_search/providers/exa.py
new file mode 100644
index 000000000..08fa8a189
--- /dev/null
+++ b/src/tools/web_search/providers/exa.py
@@ -0,0 +1,194 @@
+"""
+Exa Neural Search Provider
+
+API Docs: https://exa.ai/docs/reference/search
+Endpoint: https://api.exa.ai/search
+
+Features:
+- Embeddings-based neural search (finds semantically similar content)
+- Multiple search types: auto, neural, keyword
+- Category filtering: research paper, news, company, people, github, tweet, pdf
+- Date filtering (published date and crawl date)
+- Domain include/exclude lists
+- Full text extraction with highlights and summaries
+- Cost tracking in response
+
+Pricing:
+- Neural search (1-25 results): $0.005/request
+- Neural search (26-100 results): $0.025/request
+- Content text/highlight/summary: $0.001/page
+"""
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("exa")
+class ExaProvider(BaseSearchProvider):
+ """Exa neural/embeddings-based search provider"""
+
+ display_name = "Exa"
+ description = "Neural/embeddings search"
+ api_key_env_var = "EXA_API_KEY"
+ supports_answer = True # Provides summaries and context
+
+ BASE_URL = "https://api.exa.ai/search"
+
+ def search(
+ self,
+ query: str,
+ search_type: str = "auto", # auto, neural, keyword
+ num_results: int = 10,
+ include_text: bool = True,
+ include_highlights: bool = True,
+ include_summary: bool = True,
+ max_characters: int | None = None,
+ category: str | None = None, # research paper, news, company, etc.
+ include_domains: list[str] | None = None,
+ exclude_domains: list[str] | None = None,
+ start_published_date: str | None = None, # ISO format
+ end_published_date: str | None = None,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Perform neural search using Exa API.
+
+ Args:
+ query: Search query.
+ search_type: Search type - "auto", "neural", or "keyword".
+ num_results: Number of results to return.
+ include_text: Include full text content.
+ include_highlights: Include relevant highlights.
+ include_summary: Include AI-generated summaries.
+ max_characters: Maximum characters per result.
+ category: Filter by category.
+ include_domains: List of domains to include.
+ exclude_domains: List of domains to exclude.
+ start_published_date: Filter by start date (ISO format).
+ end_published_date: Filter by end date (ISO format).
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ self.logger.debug(f"Calling Exa API type={search_type}, num_results={num_results}")
+ headers = {
+ "Content-Type": "application/json",
+ "x-api-key": self.api_key,
+ }
+
+ # Build contents configuration
+ contents: dict[str, Any] = {}
+ if include_text:
+ contents["text"] = (
+ {"maxCharacters": max_characters} if max_characters else True
+ )
+ if include_highlights:
+ contents["highlights"] = True
+ if include_summary:
+ contents["summary"] = True
+
+ payload: dict[str, Any] = {
+ "query": query,
+ "type": search_type,
+ "numResults": num_results,
+ "contents": contents,
+ }
+
+ if category:
+ payload["category"] = category
+ if include_domains:
+ payload["includeDomains"] = include_domains
+ if exclude_domains:
+ payload["excludeDomains"] = exclude_domains
+ if start_published_date:
+ payload["startPublishedDate"] = start_published_date
+ if end_published_date:
+ payload["endPublishedDate"] = end_published_date
+
+ response = requests.post(
+ self.BASE_URL, headers=headers, json=payload, timeout=timeout
+ )
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ self.logger.error(f"Exa API error: {response.status_code}")
+ raise Exception(
+ f"Exa API error: {response.status_code} - "
+ f"{error_data.get('error', response.text)}"
+ )
+
+ data = response.json()
+ self.logger.debug(f"Exa returned {len(data.get('results', []))} results")
+
+ # Build answer from summaries
+ summaries = []
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ for i, result in enumerate(data.get("results", []), 1):
+ # Extract summary for answer
+ summary = result.get("summary", "")
+ if summary:
+ summaries.append(f"[{i}] {summary}")
+
+ # Build search result
+ sr = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=summary or result.get("text", "")[:500],
+ date=result.get("publishedDate", ""),
+ source=result.get("author", ""),
+ content=result.get("text", ""),
+ score=result.get("score", 0.0),
+ )
+ search_results.append(sr)
+
+ # Build citation
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=result.get("url", ""),
+ title=result.get("title", ""),
+ snippet=summary or result.get("text", "")[:500],
+ date=result.get("publishedDate", ""),
+ source=result.get("author", ""),
+ content=result.get("text", ""),
+ )
+ )
+
+ # Combine summaries as answer
+ answer = "\n\n".join(summaries) if summaries else ""
+
+ # Build metadata
+ metadata: dict[str, Any] = {
+ "finish_reason": "stop",
+ "search_type": search_type,
+ "autoprompt_string": data.get("autopromptString", ""),
+ }
+
+ # Add cost info if available
+ if data.get("costDollars"):
+ metadata["cost_dollars"] = data["costDollars"]
+
+ response_obj = WebSearchResponse(
+ query=query,
+ answer=answer,
+ provider="exa",
+ timestamp=datetime.now().isoformat(),
+ model=f"exa-{search_type}",
+ citations=citations,
+ search_results=search_results,
+ usage={},
+ metadata=metadata,
+ )
+
+ return response_obj
diff --git a/src/tools/web_search/providers/jina.py b/src/tools/web_search/providers/jina.py
new file mode 100644
index 000000000..565c6ee81
--- /dev/null
+++ b/src/tools/web_search/providers/jina.py
@@ -0,0 +1,164 @@
+"""
+Jina Reader Search Provider
+
+API Docs: https://jina.ai/reader
+Search Endpoint: https://s.jina.ai/{query}
+Reader Endpoint: https://r.jina.ai/{url}
+
+Features:
+- Web search with SERP results (s.jina.ai)
+- URL to clean content conversion (r.jina.ai)
+- Returns clean, LLM-friendly text
+- Automatic content extraction
+- Image captioning support
+- PDF support
+- Free tier: 10M tokens
+"""
+from datetime import datetime
+from typing import Any
+import urllib.parse
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("jina")
+class JinaProvider(BaseSearchProvider):
+ """Jina Reader search provider"""
+
+ display_name = "Jina"
+ description = "SERP with content extraction (free tier)"
+ api_key_env_var = "JINA_API_KEY"
+ supports_answer = False # Returns raw content, not LLM answers
+ requires_api_key = False # Has free tier without API key
+
+ SEARCH_URL = "https://s.jina.ai"
+
+ def search(
+ self,
+ query: str,
+ enrich: bool = True,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Perform web search using Jina Reader API.
+
+ Args:
+ query: Search query.
+ enrich: If True, fetch full content + images. If False, basic SERP only.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ headers: dict[str, str] = {
+ "Accept": "application/json",
+ }
+
+ if self.api_key:
+ headers["Authorization"] = f"Bearer {self.api_key}"
+
+ if enrich:
+ # Enriched mode: full content + images
+ headers["X-Engine"] = "direct"
+ headers["X-Timeout"] = str(timeout)
+ headers["X-With-Images-Summary"] = "true"
+ else:
+ # Basic mode: SERP only, no content
+ headers["X-Respond-With"] = "no-content"
+
+ # URL encode the query
+ encoded_query = urllib.parse.quote(query)
+ url = f"{self.SEARCH_URL}/{encoded_query}"
+
+ response = requests.get(url, headers=headers, timeout=timeout)
+
+ if response.status_code != 200:
+ self.logger.error(f"Jina API error: {response.status_code}")
+ raise Exception(
+ f"Jina API error: {response.status_code} - {response.text}"
+ )
+
+ data = response.json()
+ self.logger.debug(f"Jina returned {len(data.get('data', []))} results")
+
+ # Extract search results
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ # Jina Search API returns results in 'data' array
+ # Basic fields: title, url, description, date, content, usage
+ # Enriched fields (enrich=true): images, publishedTime, metadata, external
+ for i, result in enumerate(data.get("data", []), 1):
+ # Build attributes dict for enriched fields
+ attributes: dict[str, Any] = {}
+ if result.get("images"):
+ attributes["images"] = result["images"]
+ if result.get("publishedTime"):
+ attributes["publishedTime"] = result["publishedTime"]
+ if result.get("metadata"):
+ attributes["metadata"] = result["metadata"]
+ if result.get("external"):
+ attributes["external"] = result["external"]
+
+ sr = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=result.get("description", ""),
+ date=result.get("date", ""),
+ content=result.get("content", ""),
+ attributes=attributes,
+ )
+ search_results.append(sr)
+
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=result.get("url", ""),
+ title=result.get("title", ""),
+ snippet=result.get("description", ""),
+ date=result.get("date", ""),
+ content=result.get("content", ""),
+ )
+ )
+
+ # Build metadata
+ metadata: dict[str, Any] = {
+ "finish_reason": "stop",
+ "code": data.get("code", 200),
+ "status": data.get("status", 20000),
+ }
+
+ # Calculate total tokens - prefer meta.usage.tokens if available
+ total_tokens = 0
+ if data.get("meta", {}).get("usage", {}).get("tokens"):
+ total_tokens = data["meta"]["usage"]["tokens"]
+ else:
+ # Fallback: sum per-result tokens
+ for result in data.get("data", []):
+ if result.get("usage", {}).get("tokens"):
+ total_tokens += result["usage"]["tokens"]
+
+ usage: dict[str, Any] = {}
+ if total_tokens > 0:
+ usage["total_tokens"] = total_tokens
+
+ response_obj = WebSearchResponse(
+ query=query,
+ answer="", # Jina doesn't provide LLM answers
+ provider="jina",
+ timestamp=datetime.now().isoformat(),
+ model="jina-reader",
+ citations=citations,
+ search_results=search_results,
+ usage=usage,
+ metadata=metadata,
+ )
+
+ return response_obj
diff --git a/src/tools/web_search/providers/perplexity.py b/src/tools/web_search/providers/perplexity.py
new file mode 100644
index 000000000..4a747d278
--- /dev/null
+++ b/src/tools/web_search/providers/perplexity.py
@@ -0,0 +1,147 @@
+"""
+Perplexity AI Search Provider
+
+API: Uses perplexity Python package
+Model: sonar (default)
+
+Features:
+- AI-powered search with LLM-generated answers
+- Automatic citation extraction
+- Usage tracking with cost information
+"""
+from datetime import datetime
+from typing import Any
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("perplexity")
+class PerplexityProvider(BaseSearchProvider):
+ """Perplexity AI search provider"""
+
+ display_name = "Perplexity"
+ description = "AI-powered search with answers"
+ api_key_env_var = "PERPLEXITY_API_KEY"
+ supports_answer = True
+
+ def __init__(self, api_key: str | None = None, **kwargs: Any) -> None:
+ super().__init__(api_key, **kwargs)
+ self._client = None
+
+ @property
+ def client(self):
+ """Lazy-load the Perplexity client."""
+ if self._client is None:
+ try:
+ from perplexity import Perplexity
+ except ImportError:
+ raise ImportError(
+ "perplexity module is not installed. To use Perplexity search, please install: "
+ "pip install perplexity"
+ )
+ self._client = Perplexity(api_key=self.api_key)
+ return self._client
+
+ def search(
+ self,
+ query: str,
+ model: str = "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 Perplexity API.
+
+ Args:
+ query: Search query.
+ model: Model to use (default: sonar).
+ system_prompt: System prompt for the model.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ self.logger.debug(f"Calling Perplexity API with model={model}")
+ completion = self.client.chat.completions.create(
+ model=model,
+ messages=[
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": query},
+ ],
+ )
+
+ answer = completion.choices[0].message.content
+
+ # Build usage info with safe attribute access
+ usage_info: dict[str, Any] = {}
+ if hasattr(completion, "usage") and completion.usage is not None:
+ usage = completion.usage
+ usage_info = {
+ "prompt_tokens": getattr(usage, "prompt_tokens", 0),
+ "completion_tokens": getattr(usage, "completion_tokens", 0),
+ "total_tokens": getattr(usage, "total_tokens", 0),
+ }
+ if hasattr(usage, "cost") and usage.cost is not None:
+ cost = usage.cost
+ usage_info["cost"] = {
+ "total_cost": getattr(cost, "total_cost", 0),
+ "input_tokens_cost": getattr(cost, "input_tokens_cost", 0),
+ "output_tokens_cost": getattr(cost, "output_tokens_cost", 0),
+ }
+
+ # Build search results list
+ search_results: list[SearchResult] = []
+ if hasattr(completion, "search_results") and completion.search_results:
+ for search_item in completion.search_results:
+ search_results.append(
+ SearchResult(
+ title=getattr(search_item, "title", "") or "",
+ url=getattr(search_item, "url", "") or "",
+ snippet=getattr(search_item, "snippet", "") or "",
+ date=getattr(search_item, "date", "") or "",
+ source=str(getattr(search_item, "source", "")) if getattr(search_item, "source", None) else "",
+ )
+ )
+
+ # Build citations list
+ citations: list[Citation] = []
+ if hasattr(completion, "citations") and completion.citations:
+ for i, citation_url in enumerate(completion.citations, 1):
+ # Try to find matching search result for more info
+ title = ""
+ snippet = ""
+ for sr in search_results:
+ if sr.url == citation_url:
+ title = sr.title
+ snippet = sr.snippet
+ break
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=citation_url,
+ title=title,
+ snippet=snippet,
+ )
+ )
+
+ # Ensure answer is a string
+ answer_str = str(answer) if answer else ""
+
+ response = WebSearchResponse(
+ query=query,
+ answer=answer_str,
+ provider="perplexity",
+ timestamp=datetime.now().isoformat(),
+ model=completion.model,
+ citations=citations,
+ search_results=search_results,
+ usage=usage_info,
+ metadata={
+ "finish_reason": completion.choices[0].finish_reason,
+ },
+ )
+
+ return response
diff --git a/src/tools/web_search/providers/serper.py b/src/tools/web_search/providers/serper.py
new file mode 100644
index 000000000..5e176a26b
--- /dev/null
+++ b/src/tools/web_search/providers/serper.py
@@ -0,0 +1,202 @@
+"""
+Serper Google SERP Provider
+
+API: https://serper.dev
+Endpoint: https://google.serper.dev/{mode}
+
+Features:
+- Real-time Google search results (1-2 seconds)
+- Modes: search, scholar
+- Knowledge graph extraction
+- People Also Ask extraction
+- Related searches
+- Very cheap: $1/1000 queries at scale
+"""
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("serper")
+class SerperProvider(BaseSearchProvider):
+ """Serper Google SERP provider"""
+
+ display_name = "Serper"
+ description = "Google SERP results"
+ api_key_env_var = "SERPER_API_KEY"
+ supports_answer = False # Raw SERP results, no LLM answer
+
+ BASE_URL = "https://google.serper.dev"
+
+ def search(
+ self,
+ query: str,
+ mode: str = "search", # search, scholar
+ num: int = 10,
+ gl: str = "us", # Country code
+ hl: str = "en", # Language code
+ page: int = 1,
+ autocorrect: bool = True,
+ timeout: int = 30,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Perform Google SERP search using Serper API.
+
+ Args:
+ query: Search query.
+ mode: Search mode - "search" or "scholar".
+ num: Number of results (default 10, max 100).
+ gl: Country code (default "us").
+ hl: Language code (default "en").
+ page: Page number for pagination.
+ autocorrect: Enable autocorrect (default True).
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ self.logger.debug(f"Calling Serper API mode={mode}, num={num}")
+ headers = {
+ "X-API-KEY": self.api_key,
+ "Content-Type": "application/json",
+ }
+
+ payload: dict[str, Any] = {
+ "q": query,
+ "num": num,
+ "gl": gl,
+ "hl": hl,
+ "page": page,
+ "autocorrect": autocorrect,
+ }
+
+ url = f"{self.BASE_URL}/{mode}"
+ response = requests.post(url, headers=headers, json=payload, timeout=timeout)
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ self.logger.error(f"Serper API error: {response.status_code}")
+ raise Exception(
+ f"Serper API error: {response.status_code} - "
+ f"{error_data.get('message', response.text)}"
+ )
+
+ data = response.json()
+ self.logger.debug(f"Serper returned {len(data.get('organic', []))} results")
+
+ # Extract search results
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ # Both search and scholar return results in "organic" key
+ results_key = "organic"
+
+ for i, result in enumerate(data.get(results_key, []), 1):
+ # Handle different result formats
+ title = result.get("title", "")
+ url_val = result.get("link", result.get("url", ""))
+ snippet = result.get("snippet", result.get("description", ""))
+ date = result.get("date", "")
+
+ # Extract sitelinks if available
+ sitelinks = []
+ if result.get("sitelinks"):
+ for sl in result["sitelinks"]:
+ sitelinks.append(
+ {"title": sl.get("title", ""), "link": sl.get("link", "")}
+ )
+
+ # Build attributes dict with scholar-specific fields
+ attributes: dict[str, Any] = result.get("attributes", {})
+
+ # Scholar mode: extract publication info, citations, PDF URL, year
+ if mode == "scholar":
+ # publicationInfo is a string like "A Vaswani, N Shazeer... - Advances in neural..., 2017"
+ if result.get("publicationInfo"):
+ attributes["publicationInfo"] = result["publicationInfo"]
+ # citedBy is a number
+ if result.get("citedBy") is not None:
+ attributes["citedBy"] = result["citedBy"]
+ # pdfUrl is a direct link to PDF
+ if result.get("pdfUrl"):
+ attributes["pdfUrl"] = result["pdfUrl"]
+ # year is a number
+ if result.get("year") is not None:
+ attributes["year"] = result["year"]
+ # paper ID
+ if result.get("id"):
+ attributes["paperId"] = result["id"]
+
+ sr = SearchResult(
+ title=title,
+ url=url_val,
+ snippet=snippet,
+ date=date,
+ source=result.get("source", ""),
+ sitelinks=sitelinks,
+ attributes=attributes,
+ )
+ search_results.append(sr)
+
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=url_val,
+ title=title,
+ snippet=snippet,
+ date=date,
+ source=result.get("source", ""),
+ )
+ )
+
+ # Build metadata with rich SERP data
+ metadata: dict[str, Any] = {
+ "finish_reason": "stop",
+ "mode": mode,
+ "searchParameters": data.get("searchParameters", {}),
+ }
+
+ # Include knowledge graph if available
+ if data.get("knowledgeGraph"):
+ metadata["knowledgeGraph"] = data["knowledgeGraph"]
+
+ # Include answer box if available
+ if data.get("answerBox"):
+ metadata["answerBox"] = data["answerBox"]
+
+ # Include People Also Ask
+ if data.get("peopleAlsoAsk"):
+ metadata["peopleAlsoAsk"] = data["peopleAlsoAsk"]
+
+ # Include related searches
+ if data.get("relatedSearches"):
+ metadata["relatedSearches"] = data["relatedSearches"]
+
+ # Build answer from answer box or knowledge graph if available
+ answer = ""
+ if data.get("answerBox"):
+ ab = data["answerBox"]
+ answer = ab.get("answer", ab.get("snippet", ""))
+ elif data.get("knowledgeGraph"):
+ kg = data["knowledgeGraph"]
+ answer = kg.get("description", "")
+
+ return WebSearchResponse(
+ query=query,
+ answer=answer,
+ provider="serper_scholar" if mode == "scholar" else "serper",
+ timestamp=datetime.now().isoformat(),
+ model=f"serper-{mode}",
+ citations=citations,
+ search_results=search_results,
+ usage={},
+ metadata=metadata,
+ )
diff --git a/src/tools/web_search/providers/tavily.py b/src/tools/web_search/providers/tavily.py
new file mode 100644
index 000000000..9c1e6e23b
--- /dev/null
+++ b/src/tools/web_search/providers/tavily.py
@@ -0,0 +1,157 @@
+"""
+Tavily Search Provider
+
+API Docs: https://docs.tavily.com/documentation/api-reference/endpoint/search
+
+Features:
+- Research-focused search with relevance scoring
+- Optional LLM-generated answers (include_answer=true)
+- Full raw content extraction (include_raw_content=true)
+- Topic filtering (general, news, finance)
+- Time range filtering (day, week, month, year)
+- Domain include/exclude lists
+"""
+from datetime import datetime
+from typing import Any
+
+import requests
+
+from ..base import BaseSearchProvider
+from ..types import Citation, SearchResult, WebSearchResponse
+from . import register_provider
+
+
+@register_provider("tavily")
+class TavilyProvider(BaseSearchProvider):
+ """Tavily research-focused search provider"""
+
+ display_name = "Tavily"
+ description = "Research-focused search"
+ api_key_env_var = "TAVILY_API_KEY"
+ supports_answer = True
+
+ BASE_URL = "https://api.tavily.com/search"
+
+ def search(
+ self,
+ query: str,
+ search_depth: str = "basic", # basic, advanced
+ topic: str = "general", # general, news, finance
+ max_results: int = 10,
+ include_answer: bool = True, # Get LLM-generated answer
+ include_raw_content: bool = False, # Get full page content
+ include_images: bool = False,
+ days: int | None = None, # Time filter (1-365)
+ include_domains: list[str] | None = None,
+ exclude_domains: list[str] | None = None,
+ timeout: int = 60,
+ **kwargs: Any,
+ ) -> WebSearchResponse:
+ """
+ Perform research-focused search using Tavily API.
+
+ Args:
+ query: Search query.
+ search_depth: Search depth - "basic" (faster) or "advanced" (more thorough).
+ topic: Topic category - "general", "news", or "finance".
+ max_results: Maximum number of results (1-20).
+ include_answer: Include LLM-generated answer.
+ include_raw_content: Include full raw content of pages.
+ include_images: Include images in results.
+ days: Filter results to last N days (1-365).
+ include_domains: List of domains to include.
+ exclude_domains: List of domains to exclude.
+ timeout: Request timeout in seconds.
+ **kwargs: Additional options.
+
+ Returns:
+ WebSearchResponse: Standardized search response.
+ """
+ self.logger.debug(f"Calling Tavily API depth={search_depth}, max_results={max_results}")
+ payload: dict[str, Any] = {
+ "api_key": self.api_key,
+ "query": query,
+ "search_depth": search_depth,
+ "topic": topic,
+ "max_results": max_results,
+ "include_answer": include_answer,
+ "include_raw_content": include_raw_content,
+ "include_images": include_images,
+ }
+
+ if days is not None:
+ payload["days"] = days
+ if include_domains:
+ payload["include_domains"] = include_domains
+ if exclude_domains:
+ payload["exclude_domains"] = exclude_domains
+
+ response = requests.post(self.BASE_URL, json=payload, timeout=timeout)
+
+ if response.status_code != 200:
+ error_data = response.json() if response.text else {}
+ self.logger.error(f"Tavily API error: {response.status_code}")
+ raise Exception(
+ f"Tavily API error: {response.status_code} - "
+ f"{error_data.get('error', response.text)}"
+ )
+
+ data = response.json()
+ self.logger.debug(f"Tavily returned {len(data.get('results', []))} results")
+
+ # Extract answer
+ answer = data.get("answer", "")
+
+ # Extract search results
+ citations: list[Citation] = []
+ search_results: list[SearchResult] = []
+
+ for i, result in enumerate(data.get("results", []), 1):
+ sr = SearchResult(
+ title=result.get("title", ""),
+ url=result.get("url", ""),
+ snippet=result.get("content", ""),
+ date=result.get("published_date", ""),
+ source=result.get("source", ""),
+ content=result.get("raw_content", ""),
+ score=result.get("score", 0.0),
+ )
+ search_results.append(sr)
+
+ citations.append(
+ Citation(
+ id=i,
+ reference=f"[{i}]",
+ url=result.get("url", ""),
+ title=result.get("title", ""),
+ snippet=result.get("content", ""),
+ source=result.get("source", ""),
+ content=result.get("raw_content", ""),
+ )
+ )
+
+ # Build metadata
+ metadata: dict[str, Any] = {
+ "finish_reason": "stop",
+ "search_depth": search_depth,
+ "topic": topic,
+ }
+
+ if data.get("images"):
+ metadata["images"] = data["images"]
+ if data.get("response_time"):
+ metadata["response_time"] = data["response_time"]
+
+ response_obj = WebSearchResponse(
+ query=query,
+ answer=answer,
+ provider="tavily",
+ timestamp=datetime.now().isoformat(),
+ model=f"tavily-{search_depth}",
+ citations=citations,
+ search_results=search_results,
+ usage={}, # Tavily doesn't provide token usage
+ metadata=metadata,
+ )
+
+ return response_obj
diff --git a/src/tools/web_search/types.py b/src/tools/web_search/types.py
new file mode 100644
index 000000000..bbd1a6d54
--- /dev/null
+++ b/src/tools/web_search/types.py
@@ -0,0 +1,108 @@
+"""
+Web Search Types - Shared dataclasses and type definitions
+
+This module defines the standardized types used across all search providers.
+"""
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Any
+
+
+@dataclass
+class Citation:
+ """Standardized citation from search results"""
+
+ id: int
+ reference: str # e.g., "[1]"
+ url: str
+ title: str = ""
+ snippet: str = ""
+ date: str = ""
+ source: str = ""
+ content: str = "" # Full content if available
+ # Additional fields for backward compatibility with legacy format
+ type: str = "web" # Citation type (web, pdf, etc.)
+ icon: str = "" # Source icon URL
+ website: str = "" # Website name
+ web_anchor: str = "" # Web anchor text
+
+
+@dataclass
+class SearchResult:
+ """Individual search result item"""
+
+ title: str
+ url: str
+ snippet: str
+ date: str = ""
+ source: str = ""
+ content: str = "" # Full content if available (e.g., from Jina)
+ score: float = 0.0 # Relevance score if available
+ # Additional fields for rich results
+ sitelinks: list[dict[str, str]] = field(default_factory=list)
+ attributes: dict[str, Any] = field(default_factory=dict)
+
+
+@dataclass
+class WebSearchResponse:
+ """Standardized response from any search provider"""
+
+ query: str
+ answer: str # LLM-generated answer or empty for raw SERP providers
+ provider: str
+ timestamp: str = field(default_factory=lambda: datetime.now().isoformat())
+ model: str = ""
+ citations: list[Citation] = field(default_factory=list)
+ search_results: list[SearchResult] = field(default_factory=list)
+ usage: dict[str, Any] = field(default_factory=dict)
+ metadata: dict[str, Any] = field(default_factory=dict)
+
+ def to_dict(self) -> dict[str, Any]:
+ """Convert to dictionary (backward compatible format)"""
+ result = {
+ "timestamp": self.timestamp,
+ "query": self.query,
+ "model": self.model,
+ "provider": self.provider,
+ "answer": self.answer,
+ "response": {
+ "content": self.answer,
+ "role": "assistant",
+ "finish_reason": self.metadata.get("finish_reason", "stop"),
+ },
+ "usage": self.usage,
+ "citations": [
+ {
+ "id": c.id,
+ "reference": c.reference,
+ "url": c.url,
+ "title": c.title,
+ "snippet": c.snippet,
+ "date": c.date,
+ "source": c.source,
+ "content": c.content,
+ "type": c.type,
+ "icon": c.icon,
+ "website": c.website,
+ "web_anchor": c.web_anchor,
+ }
+ for c in self.citations
+ ],
+ "search_results": [
+ {
+ "title": r.title,
+ "url": r.url,
+ "snippet": r.snippet,
+ "date": r.date,
+ "source": r.source,
+ "content": r.content,
+ "score": r.score,
+ }
+ for r in self.search_results
+ ],
+ }
+ # Add any extra metadata that isn't already in the result
+ for key, value in self.metadata.items():
+ if key not in result and key != "finish_reason":
+ result[key] = value
+ return result
diff --git a/src/tools/web_search/utils.py b/src/tools/web_search/utils.py
new file mode 100644
index 000000000..dd8480cdf
--- /dev/null
+++ b/src/tools/web_search/utils.py
@@ -0,0 +1,17 @@
+"""Web Search Utilities"""
+import json
+import os
+from datetime import datetime
+from typing import Any
+
+
+def save_results(result: dict[str, Any], output_dir: str, provider: str) -> str:
+ """Save search results to a JSON file."""
+ os.makedirs(output_dir, exist_ok=True)
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
+ output_path = os.path.join(output_dir, f"search_{provider}_{timestamp}.json")
+
+ with open(output_path, "w", encoding="utf-8") as f:
+ json.dump(result, f, ensure_ascii=False, indent=2)
+
+ return output_path
diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsx
index 919e453ff..df1cfdaf6 100644
--- a/web/app/settings/page.tsx
+++ b/web/app/settings/page.tsx
@@ -69,7 +69,10 @@ interface ConfigData {
};
web_search?: {
enabled?: boolean;
+ provider?: string;
max_results?: number;
+ consolidation?: "none" | "template" | "llm";
+ consolidation_template?: string;
[key: string]: any;
};
[key: string]: any;
@@ -92,6 +95,26 @@ interface FullSettingsResponse {
env: EnvInfo;
}
+// Web search config types (fetched from backend)
+interface WebSearchProvider {
+ id: string;
+ name: string;
+ description: string;
+ keyEnv: string;
+ supports_answer: boolean;
+ requires_api_key: boolean;
+}
+
+interface WebSearchConfigResponse {
+ enabled: boolean;
+ provider: string;
+ consolidation: string | null;
+ providers: WebSearchProvider[];
+ consolidation_types: string[]; // ["none", "template", "llm"]
+ template_providers: string[]; // Providers that support template consolidation (serper, jina, etc.)
+ config_source: "env" | "yaml" | "default";
+}
+
// Environment variable types
interface EnvVarInfo {
key: string;
@@ -335,11 +358,15 @@ export default function SettingsPage() {
useState<string>("raganything");
const [loadingRagProviders, setLoadingRagProviders] = useState(false);
+ // Web search config state (fetched from backend)
+ const [webSearchConfig, setWebSearchConfig] = useState<WebSearchConfigResponse | null>(null);
+
useEffect(() => {
fetchSettings();
fetchEnvConfig();
fetchRagProviders();
fetchLLMMode();
+ fetchWebSearchConfig();
if (activeTab === "local_models") {
fetchProviders();
}
@@ -388,6 +415,18 @@ export default function SettingsPage() {
}
};
+ const fetchWebSearchConfig = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/settings/web-search/config"));
+ if (res.ok) {
+ const data: WebSearchConfigResponse = await res.json();
+ setWebSearchConfig(data);
+ }
+ } catch (err) {
+ console.error("Failed to fetch web search config:", err);
+ }
+ };
+
const fetchModels = async () => {
if (!editingProvider || !editingProvider.base_url) return;
setFetchingModels(true);
@@ -639,6 +678,18 @@ export default function SettingsPage() {
const handleEnvVarChange = (key: string, value: string) => {
setEditedEnvVars((prev) => ({ ...prev, [key]: value }));
+
+ // Sync SEARCH_PROVIDER env var with config dropdown
+ if (key === "SEARCH_PROVIDER" && value) {
+ setEditedConfig((prev) => {
+ if (!prev) return null;
+ const newConfig = { ...prev };
+ if (!newConfig.tools) newConfig.tools = {};
+ if (!newConfig.tools.web_search) newConfig.tools.web_search = {};
+ newConfig.tools.web_search.provider = value;
+ return newConfig;
+ });
+ }
};
const toggleSensitiveVisibility = (key: string) => {
@@ -888,6 +939,11 @@ export default function SettingsPage() {
}
return newConfig;
});
+
+ // Sync search provider selection with SEARCH_PROVIDER env var
+ if (section === "tools" && subSection === "web_search" && key === "provider") {
+ setEditedEnvVars((prev) => ({ ...prev, SEARCH_PROVIDER: value }));
+ }
};
const handleUIChange = (key: keyof UISettings, value: any) => {
@@ -1458,146 +1514,213 @@ export default function SettingsPage() {
{/* Row 3: Research Tools (Web Search + Knowledge Base) + TTS */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
- {/* Research Tools */}
+ {/* Research Tools - Web Search */}
<section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
<div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
- <Search className="w-4 h-4 text-amber-500 dark:text-amber-400" />
+ <Globe className="w-4 h-4 text-blue-500 dark:text-blue-400" />
<h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
- {t("Research Tools")}
+ {t("Web Search")}
</h2>
</div>
- <div className="p-4 grid grid-cols-2 gap-3">
- {/* Web Search */}
- <div className="p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600">
- <div className="flex items-center justify-between mb-3">
- <span className="text-xs font-medium text-slate-700 dark:text-slate-300 flex items-center gap-1.5">
- <Globe className="w-3.5 h-3.5 text-blue-500" />
- {t("Web Search")}
- </span>
- <div className="relative inline-flex items-center cursor-pointer">
- <input
- type="checkbox"
- checked={
- editedConfig.tools?.web_search?.enabled ?? true
- }
- onChange={(e) =>
- handleConfigChange(
- "tools",
- "enabled",
- e.target.checked,
- "web_search",
- )
- }
- className="sr-only peer"
- />
- <div className="w-9 h-5 bg-slate-200 dark:bg-slate-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 dark:after:border-slate-500 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
- </div>
+ <div className="p-4 space-y-4">
+ {/* Enable/Disable Toggle */}
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-slate-700 dark:text-slate-300">
+ {t("Enable Web Search")}
+ </span>
+ <div className="relative inline-flex items-center cursor-pointer">
+ <input
+ type="checkbox"
+ checked={
+ editedConfig.tools?.web_search?.enabled ?? true
+ }
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "enabled",
+ e.target.checked,
+ "web_search",
+ )
+ }
+ className="sr-only peer"
+ />
+ <div className="w-9 h-5 bg-slate-200 dark:bg-slate-600 peer-focus:outline-none rounded-full peer peer-checked:after:translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:left-[2px] after:bg-white after:border-gray-300 dark:after:border-slate-500 after:border after:rounded-full after:h-4 after:w-4 after:transition-all peer-checked:bg-blue-600"></div>
</div>
+ </div>
+
+ {/* Provider Selection */}
+ <div>
+ <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
+ {t("Search Provider")}
+ </label>
+ <select
+ value={editedEnvVars["SEARCH_PROVIDER"] || editedConfig.tools?.web_search?.provider || "perplexity"}
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "provider",
+ e.target.value,
+ "web_search",
+ )
+ }
+ className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"
+ >
+ {(webSearchConfig?.providers || []).map((p) => (
+ <option key={p.id} value={p.id}>
+ {p.name}
+ </option>
+ ))}
+ </select>
+ <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1">
+ Also updates SEARCH_PROVIDER env variable
+ </p>
+ </div>
+
+ {/* Max Results */}
+ <div>
+ <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
+ {t("Max Results")}
+ </label>
+ <input
+ type="number"
+ min="1"
+ max="20"
+ value={editedConfig.tools?.web_search?.max_results || 5}
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "max_results",
+ parseInt(e.target.value),
+ "web_search",
+ )
+ }
+ className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"
+ />
+ </div>
+
+ {/* Consolidation Settings */}
+ <div className="p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600 space-y-3">
<div>
<label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
- {t("Max Results")}
+ {t("Answer Consolidation")}
</label>
- <input
- type="number"
- min="1"
- max="20"
- value={editedConfig.tools?.web_search?.max_results || 5}
+ <select
+ value={editedConfig.tools?.web_search?.consolidation || "template"}
onChange={(e) =>
handleConfigChange(
"tools",
- "max_results",
- parseInt(e.target.value),
+ "consolidation",
+ e.target.value,
"web_search",
)
}
className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"
- />
+ >
+ {(webSearchConfig?.consolidation_types || ["none", "template", "llm"]).map((type) => (
+ <option key={type} value={type}>
+ {type.charAt(0).toUpperCase() + type.slice(1)}
+ </option>
+ ))}
+ </select>
+ <p className="text-[10px] text-slate-500 dark:text-slate-400 mt-1">
+ For SERP providers that return raw results.
+ </p>
</div>
- </div>
- {/* Knowledge Base */}
- <div className="p-3 bg-slate-50 dark:bg-slate-700/50 rounded-lg border border-slate-100 dark:border-slate-600">
- <div className="flex items-center mb-3">
- <span className="text-xs font-medium text-slate-700 dark:text-slate-300 flex items-center gap-1.5">
- <Database className="w-3.5 h-3.5 text-purple-500" />
- {t("Knowledge Base")}
- </span>
- </div>
- <div className="space-y-2">
- <div>
- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
- {t("Default KB")}
- </label>
- <input
- type="text"
- value={editedConfig.tools?.rag_tool?.default_kb || ""}
- onChange={(e) =>
- handleConfigChange(
- "tools",
- "default_kb",
- e.target.value,
- "rag_tool",
- )
- }
- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"
- />
- </div>
- <div>
- <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
- {t("Base Directory")}
- </label>
- <input
- type="text"
- value={
- editedConfig.tools?.rag_tool?.kb_base_dir || ""
- }
- onChange={(e) =>
- handleConfigChange(
- "tools",
- "kb_base_dir",
- e.target.value,
- "rag_tool",
- )
- }
- className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs font-mono text-slate-600 dark:text-slate-300"
- />
+ {(editedConfig.tools?.web_search?.consolidation === "template" || editedConfig.tools?.web_search?.consolidation === "llm") && (
+ <div className="text-[10px] text-amber-600 dark:text-amber-400 bg-amber-50 dark:bg-amber-900/20 p-2 rounded space-y-1">
+ <div>Consolidation only works with: {webSearchConfig?.template_providers?.join(", ") || "serper, jina, serper_scholar"}</div>
+ {editedConfig.tools?.web_search?.consolidation === "llm" && (
+ <div className="text-amber-700 dark:text-amber-300 font-medium">⚠️ LLM consolidation is an experimental feature.</div>
+ )}
</div>
- </div>
+ )}
</div>
</div>
</section>
- {/* TTS Settings */}
+ {/* Knowledge Base */}
<section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
<div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
- <Volume2 className="w-4 h-4 text-rose-500 dark:text-rose-400" />
+ <Database className="w-4 h-4 text-purple-500 dark:text-purple-400" />
<h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
- {t("Text-to-Speech")}
+ {t("Knowledge Base")}
</h2>
</div>
- <div className="p-4 grid grid-cols-2 gap-4">
+ <div className="p-4 space-y-3">
<div>
- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">
- {t("Default Voice")}
+ <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
+ {t("Default KB")}
</label>
<input
type="text"
- value={editedConfig.tts?.default_voice || "Cherry"}
+ value={editedConfig.tools?.rag_tool?.default_kb || ""}
onChange={(e) =>
handleConfigChange(
- "tts",
- "default_voice",
+ "tools",
+ "default_kb",
e.target.value,
+ "rag_tool",
)
}
- className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"
+ className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs text-slate-900 dark:text-slate-100"
/>
</div>
<div>
- <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">
- {t("Default Language")}
+ <label className="block text-[10px] font-semibold text-slate-500 dark:text-slate-400 uppercase tracking-wider mb-1">
+ {t("Base Directory")}
</label>
<input
+ type="text"
+ value={
+ editedConfig.tools?.rag_tool?.kb_base_dir || ""
+ }
+ onChange={(e) =>
+ handleConfigChange(
+ "tools",
+ "kb_base_dir",
+ e.target.value,
+ "rag_tool",
+ )
+ }
+ className="w-full p-1.5 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded text-xs font-mono text-slate-600 dark:text-slate-300"
+ />
+ </div>
+ </div>
+ </section>
+ </div>
+
+ {/* TTS Settings */}
+ <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
+ <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center gap-2">
+ <Volume2 className="w-4 h-4 text-rose-500 dark:text-rose-400" />
+ <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
+ {t("Text-to-Speech")}
+ </h2>
+ </div>
+ <div className="p-4 grid grid-cols-2 gap-4">
+ <div>
+ <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">
+ {t("Default Voice")}
+ </label>
+ <input
+ type="text"
+ value={editedConfig.tts?.default_voice || "Cherry"}
+ onChange={(e) =>
+ handleConfigChange(
+ "tts",
+ "default_voice",
+ e.target.value,
+ )
+ }
+ className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"
+ />
+ </div>
+ <div>
+ <label className="block text-xs font-medium text-slate-600 dark:text-slate-400 mb-2">
+ {t("Default Language")}
+ </label>
+ <input
type="text"
value={editedConfig.tts?.default_language || "English"}
onChange={(e) =>
@@ -1609,10 +1732,9 @@ export default function SettingsPage() {
}
className="w-full p-2 bg-white dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg text-sm text-slate-900 dark:text-slate-100"
/>
- </div>
</div>
- </section>
- </div>
+ </div>
+ </section>
</div>
)}