Skip to content

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

improve llm services

Pancake1b3150e42e95
diff --git a/settings.py b/settings.py
deleted file mode 100644
index c006b049b..000000000
--- a/settings.py
+++ /dev/null
@@ -1,152 +0,0 @@
-from typing import Optional
-
-from pydantic import Field
-from pydantic_settings import BaseSettings, SettingsConfigDict
-
-
-class LLMSettings(BaseSettings):
- # Environment vars: LLM_BINDING, LLM_MODEL, LLM_HOST, LLM_API_KEY, DISABLE_SSL_VERIFY
- model_config = SettingsConfigDict(
- env_file=".env",
- env_prefix="LLM_",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- binding: str = Field(
- default="openai",
- description="LLM service provider type (Supported types: openai, azure_openai, ollama, lollms, groq, openrouter, ollama-cloud).",
- )
-
- model: str = Field(
- default="qwen3:0.6b",
- description="LLM model name (make sure you use the correct model name which is supported by binding).",
- )
-
- host: str = Field(
- default="http://localhost:11434/v1/",
- description="LLM API endpoint URL (e.g. http://localhost:11434/v1/ is for Ollama hosted locally).",
- )
-
- api_key: str = Field(
- default="ollama",
- description="LLM API authentication key, for Ollama that is locally setup u can leave it empty",
- )
-
- disable_ssl_verify: bool = Field(
- default=False,
- description="If true, disables SSL verification (useful for self-signed certs).",
- validation_alias="DISABLE_SSL_VERIFY",
- )
-
-
-class EmbeddingSettings(BaseSettings):
- # Environment vars: EMBEDDING_BINDING, EMBEDDING_MODEL, EMBEDDING_DIMENSION, EMBEDDING_HOST, EMBEDDING_API_KEY
- model_config = SettingsConfigDict(
- env_prefix="EMBEDDING_",
- env_file=".env",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- binding: str = Field(
- default="openai",
- description="Embedding service provider type (e.g. openai, azure_openai, ollama, lollms).",
- )
-
- model: str = Field(
- default="qwen3-embedding:0.6b",
- description="Embedding model name (e.g. text-embedding-3-large from openai).",
- )
-
- dimension: int = Field(
- default=4096,
- description="Embedding vector dimension. Should check accordingly for selected embedding model",
- )
-
- host: str = Field(
- default="http://localhost:11434/v1/",
- description="Embedding API endpoint URL (e.g. http://localhost:11434/v1/ is for Ollama hosted locally).",
- )
-
- api_key: str = Field(
- default="ollama",
- description="Embedding API authentication key for ollama locally setup you can pass anything.",
- )
-
-
-class TTSSettings(BaseSettings):
- # Environment vars: TTS_MODEL, TTS_URL, TTS_API_KEY
- model_config = SettingsConfigDict(
- env_prefix="TTS_",
- env_file=".env",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- model: Optional[str] = Field(default=None, description="TTS model name")
-
- url: Optional[str] = Field(default=None, description="TTS API endpoint URL.")
-
- api_key: Optional[str] = Field(default=None, description="TTS API authentication key.")
-
-
-class WebSearchSettings(BaseSettings):
- # Environment var: PERPLEXITY_API_KEY
- model_config = SettingsConfigDict(
- env_prefix="PERPLEXITY_",
- env_file=".env",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- api_key: Optional[str] = Field(
- default=None,
- description="Perplexity API key for web search functionality.",
- validation_alias="PERPLEXITY_API_KEY",
- )
-
-
-class LoggingSettings(BaseSettings):
- # Environment vars: RAG_TOOL_MODULE_LOG_LEVEL
- model_config = SettingsConfigDict(
- env_prefix="LOGGING_",
- env_file=".env",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- rag_tool_module_log_level: str = Field(
- default="INFO", description="Log level for RAG tool module (DEBUG, INFO, WARNING, ERROR)."
- )
-
-
-class RagSettings(BaseSettings):
- # Environment vars: RAG_PROVIDER
- model_config = SettingsConfigDict(
- env_prefix="RAG_",
- env_file=".env",
- env_file_encoding="utf-8",
- extra="ignore",
- )
-
- rag_provider: str = Field(
- default="raganything",
- description="RAG provider identifier. Default is 'raganything' (RAG-Anything with MinerU + LightRAG).",
- )
-
-
-class Settings(BaseSettings):
- """
- Loads values from .env (env_file).
- """
-
- llm: LLMSettings = LLMSettings()
- embedding: EmbeddingSettings = EmbeddingSettings()
- tts: TTSSettings = TTSSettings()
- web_search: WebSearchSettings = WebSearchSettings()
- logging: LoggingSettings = LoggingSettings()
- rag: RagSettings = RagSettings()
-
-
-settings = Settings()
diff --git a/src/agents/base_agent.py b/src/agents/base_agent.py
index d3daa0b8f..11c5cad88 100644
--- a/src/agents/base_agent.py
+++ b/src/agents/base_agent.py
@@ -30,6 +30,7 @@ from src.services.config import get_agent_params
from src.services.llm import complete as llm_complete
from src.services.llm import get_llm_config, get_token_limit_kwargs
from src.services.llm import stream as llm_stream
+from src.services.llm import supports_response_format
from src.services.prompt import get_prompt_manager
@@ -105,7 +106,7 @@ class BaseAgent(ABC):
# Fallback if env config not available
self.api_key = api_key or os.getenv("LLM_API_KEY")
self.base_url = base_url or os.getenv("LLM_HOST")
- self.model = model or os.getenv("LLM_MODEL", "gpt-4o")
+ self.model = model or os.getenv("LLM_MODEL")
self.api_version = api_version or os.getenv("LLM_API_VERSION")
# Get Agent-specific configuration (if config provided)
@@ -311,6 +312,7 @@ class BaseAgent(ABC):
self,
user_prompt: str,
system_prompt: str,
+ messages: list[dict[str, str]] | None = None,
response_format: dict[str, str] | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
@@ -325,8 +327,9 @@ class BaseAgent(ABC):
(cloud or local) based on configuration.
Args:
- user_prompt: User prompt
- system_prompt: System prompt
+ user_prompt: User prompt (ignored if messages provided)
+ system_prompt: System prompt (ignored if messages provided)
+ messages: Pre-built messages array (optional, overrides prompt/system_prompt)
response_format: Response format (e.g., {"type": "json_object"})
temperature: Temperature parameter (optional, uses config by default)
max_tokens: Maximum tokens (optional, uses config by default)
@@ -353,8 +356,23 @@ class BaseAgent(ABC):
if max_tokens:
kwargs.update(get_token_limit_kwargs(model, max_tokens))
+ # Handle response_format with capability check
if response_format:
- kwargs["response_format"] = response_format
+ try:
+ config = get_llm_config()
+ binding = getattr(config, "binding", None) or "openai"
+ except Exception:
+ binding = "openai"
+
+ if supports_response_format(binding, model):
+ kwargs["response_format"] = response_format
+ else:
+ self.logger.debug(
+ f"response_format not supported for {binding}/{model}, skipping"
+ )
+
+ if messages:
+ kwargs["messages"] = messages
# Log input
stage_label = stage or self.agent_name
diff --git a/src/agents/co_writer/base_agent.py b/src/agents/co_writer/base_agent.py
deleted file mode 100644
index ed3f7a0c2..000000000
--- a/src/agents/co_writer/base_agent.py
+++ /dev/null
@@ -1,68 +0,0 @@
-#!/usr/bin/env python
-"""
-BaseCoWriterAgent - Base class for co_writer module agents.
-
-This provides a unified base class for co_writer agents that want to use
-the new unified BaseAgent architecture.
-
-Note: Existing EditAgent and NarratorAgent have not been migrated to inherit
-from this class as they have specialized initialization and business logic.
-New co_writer agents should consider using this base class.
-"""
-
-from pathlib import Path
-import sys
-from typing import Any
-
-# Add project root to path
-_project_root = Path(__file__).parent.parent.parent.parent
-if str(_project_root) not in sys.path:
- sys.path.insert(0, str(_project_root))
-
-# Import the unified BaseAgent
-from src.agents.base_agent import BaseAgent as UnifiedBaseAgent
-
-
-class BaseCoWriterAgent(UnifiedBaseAgent):
- """
- Base class for Co-Writer module agents.
-
- This class provides a unified interface for co_writer agents,
- wrapping the new unified BaseAgent with co_writer-specific defaults.
- """
-
- def __init__(
- self,
- agent_name: str = "co_writer_agent",
- language: str = "en",
- api_key: str | None = None,
- base_url: str | None = None,
- ):
- """
- Initialize base Agent.
-
- Args:
- agent_name: Agent name
- language: Language setting ('zh' | 'en')
- api_key: API key (optional, defaults to environment)
- base_url: API endpoint (optional, defaults to environment)
- """
- # Call unified BaseAgent init
- super().__init__(
- module_name="co_writer",
- agent_name=agent_name,
- api_key=api_key,
- base_url=base_url,
- language=language,
- )
-
- async def process(self, *args, **kwargs) -> Any:
- """
- Main processing logic.
-
- Subclasses should override this method.
- """
- raise NotImplementedError("Subclasses must implement process()")
-
-
-__all__ = ["BaseCoWriterAgent"]
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
index 6288c44a3..6a68441d7 100644
--- a/src/agents/co_writer/edit_agent.py
+++ b/src/agents/co_writer/edit_agent.py
@@ -1,68 +1,18 @@
"""
EditAgent - Co-writer editing agent.
-Uses unified PromptManager for prompt loading.
+Inherits from unified BaseAgent.
"""
from datetime import datetime
import json
-import logging
from pathlib import Path
-import sys
from typing import Any, Literal
import uuid
-# Add project root for imports
-_project_root = Path(__file__).parent.parent.parent.parent
-if str(_project_root) not in sys.path:
- sys.path.insert(0, str(_project_root))
-
-from src.logging import LLMStats, get_logger
-from src.services.config import get_agent_params, load_config_with_main
-from src.services.llm import complete as llm_complete
-from src.services.llm import get_llm_config
-from src.services.prompt import get_prompt_manager
+from src.agents.base_agent import BaseAgent
from src.tools.rag_tool import rag_search
from src.tools.web_search import web_search
-# Initialize logger with config
-try:
- config = load_config_with_main(
- "solve_config.yaml", _project_root
- ) # Use any config to get main.yaml
- log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
- "log_dir"
- )
- logger = get_logger("CoWriter", log_dir=log_dir)
-except Exception:
- # Fallback to standard logging
- logger = logging.getLogger(__name__)
-
-# Shared stats tracker for co_writer
-_co_writer_stats: LLMStats | None = None
-
-
-def get_stats() -> LLMStats:
- """Get or create shared stats tracker."""
- global _co_writer_stats
- if _co_writer_stats is None:
- _co_writer_stats = LLMStats(module_name="CoWriter")
- return _co_writer_stats
-
-
-def reset_stats():
- """Reset shared stats."""
- global _co_writer_stats
- if _co_writer_stats:
- _co_writer_stats.reset()
-
-
-def print_stats():
- """Print stats summary."""
- global _co_writer_stats
- if _co_writer_stats:
- _co_writer_stats.print_summary()
-
-
USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer"
HISTORY_FILE = USER_DIR / "history.json"
TOOL_CALLS_DIR = USER_DIR / "tool_calls"
@@ -81,7 +31,7 @@ def load_history() -> list:
try:
with open(HISTORY_FILE, encoding="utf-8") as f:
return json.load(f)
- except:
+ except Exception:
return []
return []
@@ -103,25 +53,16 @@ def save_tool_call(call_id: str, tool_type: str, data: dict[str, Any]) -> str:
return str(filepath)
-class EditAgent:
- def __init__(self, language: str = "en"):
- # Load agent parameters from unified config (agents.yaml)
- self._agent_params = get_agent_params("co_writer")
- self.language = language
+class EditAgent(BaseAgent):
+ """Co-writer editing agent using unified BaseAgent."""
- # Load prompts using unified PromptManager
- self._prompts = get_prompt_manager().load_prompts(
+ def __init__(self, language: str = "en"):
+ super().__init__(
module_name="co_writer",
agent_name="edit_agent",
language=language,
)
- try:
- self.llm_config = get_llm_config()
- except Exception as e:
- logger.error(f"Failed to load LLM config: {e}")
- self.llm_config = None
-
async def process(
self,
text: str,
@@ -138,15 +79,6 @@ class EditAgent:
- edited_text: Edited text
- operation_id: Operation ID
"""
- # Always refresh LLM config before starting to avoid stale credentials
- try:
- self.llm_config = get_llm_config()
- except Exception as e:
- logger.error(f"Failed to refresh LLM config: {e}")
-
- if not self.llm_config:
- raise ValueError("LLM configuration not available")
-
operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
context = ""
@@ -155,16 +87,16 @@ class EditAgent:
if source == "rag":
if not kb_name:
- logger.warning("RAG source selected but no kb_name provided, skipping RAG search")
+ self.logger.warning("RAG source selected but no kb_name provided, skipping RAG search")
source = None
else:
- logger.info(f"Searching RAG in KB: {kb_name} for: {instruction}")
+ self.logger.info(f"Searching RAG in KB: {kb_name} for: {instruction}")
try:
search_result = await rag_search(
query=instruction, kb_name=kb_name, mode="naive", only_need_context=True
)
context = search_result.get("answer", "")
- logger.info(f"RAG context found: {len(context)} chars")
+ self.logger.info(f"RAG context found: {len(context)} chars")
tool_call_data = {
"type": "rag",
@@ -178,15 +110,15 @@ class EditAgent:
}
tool_call_file = save_tool_call(operation_id, "rag", tool_call_data)
except Exception as e:
- logger.error(f"RAG search failed: {e}, continuing without context")
+ self.logger.error(f"RAG search failed: {e}, continuing without context")
source = None
elif source == "web":
- logger.info(f"Searching Web for: {instruction}")
+ self.logger.info(f"Searching Web for: {instruction}")
try:
search_result = web_search(instruction)
context = search_result.get("answer", "")
- logger.info(f"Web context found: {len(context)} chars")
+ self.logger.info(f"Web context found: {len(context)} chars")
tool_call_data = {
"type": "web_search",
@@ -200,56 +132,44 @@ class EditAgent:
}
tool_call_file = save_tool_call(operation_id, "web", tool_call_data)
except Exception as e:
- logger.error(f"Web search failed: {e}, continuing without context")
+ self.logger.error(f"Web search failed: {e}, continuing without context")
source = None
- # 2. Construct Prompt
- system_prompt = self._prompts.get(
+ # Build prompts
+ system_prompt = self.get_prompt(
"system", "You are an expert editor and writing assistant."
)
action_verbs = {"rewrite": "Rewrite", "shorten": "Shorten", "expand": "Expand"}
action_verb = action_verbs.get(action, "Rewrite")
- action_template = self._prompts.get(
+ action_template = self.get_prompt(
"action_template",
"{action_verb} the following text based on the user's instruction.\n\nUser Instruction: {instruction}\n\n",
)
user_prompt = action_template.format(action_verb=action_verb, instruction=instruction)
if context:
- context_template = self._prompts.get(
+ context_template = self.get_prompt(
"context_template", "Reference Context:\n{context}\n\n"
)
user_prompt += context_template.format(context=context)
- text_template = self._prompts.get(
+ text_template = self.get_prompt(
"user_template",
"Target Text to Edit:\n{text}\n\nOutput only the edited text, without quotes or explanations.",
)
user_prompt += text_template.format(text=text)
- # 3. Call LLM
- logger.info(f"Calling LLM for {action}...")
- model = self.llm_config.model
- response = await llm_complete(
- binding=self.llm_config.binding,
- model=model,
- prompt=user_prompt,
+ # Call LLM using inherited method
+ self.logger.info(f"Calling LLM for {action}...")
+ response = await self.call_llm(
+ user_prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config.api_key,
- base_url=self.llm_config.base_url,
- temperature=self._agent_params["temperature"],
- max_tokens=self._agent_params["max_tokens"],
- )
-
- # Track token usage
- stats = get_stats()
- stats.add_call(
- model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ stage=f"edit_{action}",
)
- # 4. Record operation history
+ # Record operation history
history = load_history()
operation_record = {
"id": operation_id,
@@ -260,12 +180,12 @@ class EditAgent:
"input": {"original_text": text, "instruction": instruction},
"output": {"edited_text": response},
"tool_call_file": tool_call_file,
- "model": self.llm_config.model,
+ "model": self.get_model(),
}
history.append(operation_record)
save_history(history)
- logger.info(f"Operation {operation_id} recorded successfully")
+ self.logger.info(f"Operation {operation_id} recorded successfully")
return {"edited_text": response, "operation_id": operation_id}
@@ -278,40 +198,19 @@ class EditAgent:
- marked_text: Text with annotations
- operation_id: Operation ID
"""
- # Always refresh LLM config before starting to avoid stale credentials
- try:
- self.llm_config = get_llm_config()
- except Exception as e:
- logger.error(f"Failed to refresh LLM config: {e}")
-
- if not self.llm_config:
- raise ValueError("LLM configuration not available")
-
operation_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]
- system_prompt = self._prompts.get("auto_mark_system", "")
- user_template = self._prompts.get(
+ system_prompt = self.get_prompt("auto_mark_system", "")
+ user_template = self.get_prompt(
"auto_mark_user_template", "Process the following text:\n{text}"
)
user_prompt = user_template.format(text=text)
- logger.info("Calling LLM for auto-mark...")
- model = self.llm_config.model
- response = await llm_complete(
- binding=self.llm_config.binding,
- model=model,
- prompt=user_prompt,
+ self.logger.info("Calling LLM for auto-mark...")
+ response = await self.call_llm(
+ user_prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config.api_key,
- base_url=self.llm_config.base_url,
- temperature=self._agent_params["temperature"],
- max_tokens=self._agent_params["max_tokens"],
- )
-
- # Track token usage
- stats = get_stats()
- stats.add_call(
- model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ stage="auto_mark",
)
# Record operation history
@@ -325,11 +224,27 @@ class EditAgent:
"input": {"original_text": text, "instruction": "AI Auto Mark"},
"output": {"edited_text": response},
"tool_call_file": None,
- "model": self.llm_config.model,
+ "model": self.get_model(),
}
history.append(operation_record)
save_history(history)
- logger.info(f"Auto-mark operation {operation_id} recorded successfully")
+ self.logger.info(f"Auto-mark operation {operation_id} recorded successfully")
return {"marked_text": response, "operation_id": operation_id}
+
+
+# Legacy compatibility - export get_stats pointing to BaseAgent's stats
+def get_stats():
+ """Get shared stats tracker for co_writer module."""
+ return BaseAgent.get_stats("co_writer")
+
+
+def reset_stats():
+ """Reset shared stats for co_writer module."""
+ BaseAgent.reset_stats("co_writer")
+
+
+def print_stats():
+ """Print stats summary for co_writer module."""
+ BaseAgent.print_stats("co_writer")
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
index 240ac8de6..6099f89c0 100644
--- a/src/agents/co_writer/narrator_agent.py
+++ b/src/agents/co_writer/narrator_agent.py
@@ -2,53 +2,28 @@
# -*- coding: utf-8 -*-
"""
NarratorAgent - Note narration agent.
-Uses unified PromptManager for prompt loading.
+Inherits from unified BaseAgent with special TTS configuration.
"""
from datetime import datetime
import json
-import logging
+import os
from pathlib import Path
import re
-import sys
from typing import Any
from urllib.parse import urlparse
import uuid
-from openai import AsyncOpenAI
+from openai import AsyncAzureOpenAI, AsyncOpenAI
-# Add project root for imports
-_project_root = Path(__file__).parent.parent.parent.parent
-if str(_project_root) not in sys.path:
- sys.path.insert(0, str(_project_root))
-
-from src.logging import get_logger
-from src.services.config import get_agent_params, load_config_with_main
-from src.services.llm import complete as llm_complete
-from src.services.llm import get_llm_config
-from src.services.prompt import get_prompt_manager
+from src.agents.base_agent import BaseAgent
+from src.services.config import load_config_with_main
from src.services.tts import get_tts_config
-# Initialize logger with config
-try:
- config = load_config_with_main(
- "solve_config.yaml", _project_root
- ) # Use any config to get main.yaml
- log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
- "log_dir"
- )
- logger = get_logger("Narrator", log_dir=log_dir)
-except Exception:
- # Fallback to standard logging
- logger = logging.getLogger(__name__)
-
-# Import shared stats from edit_agent
+# Import shared stats from edit_agent for legacy compatibility
from .edit_agent import get_stats
# Define storage path (unified under user/co-writer/ directory)
-# Notes:
-# - Consistent with EditAgent's history records, both use user/co-writer as root directory
-# - Audio files are stored separately in audio subdirectory for static access via /api/outputs
USER_DIR = Path(__file__).parent.parent.parent.parent / "data" / "user" / "co-writer" / "audio"
@@ -57,35 +32,39 @@ def ensure_dirs():
USER_DIR.mkdir(parents=True, exist_ok=True)
-class NarratorAgent:
+class NarratorAgent(BaseAgent):
"""Note Narration Agent - Generate narration script and convert to audio"""
def __init__(self, language: str = "en"):
- # Load agent parameters from unified config (agents.yaml)
- self._agent_params = get_agent_params("narrator")
- self.language = language
-
- # Load prompts using unified PromptManager
- self._prompts = get_prompt_manager().load_prompts(
+ # Use "narrator" as module_name to get independent temperature/max_tokens config
+ super().__init__(
+ module_name="narrator",
+ agent_name="narrator_agent",
+ language=language,
+ )
+
+ # Override prompts to load from co_writer module
+ # (narrator_agent prompts are stored under co_writer/prompts/)
+ from src.services.prompt import get_prompt_manager
+ self.prompts = get_prompt_manager().load_prompts(
module_name="co_writer",
agent_name="narrator_agent",
language=language,
)
+
+ # Load TTS-specific configuration
+ self._load_tts_config()
- try:
- self.llm_config = get_llm_config()
- except Exception as e:
- logger.error(f"Failed to load LLM config: {e}")
- self.llm_config = None
-
+ def _load_tts_config(self):
+ """Load TTS-specific configuration."""
# Load main config file to get TTS default settings
try:
- config = load_config_with_main("solve_config.yaml", _project_root)
+ config = load_config_with_main("solve_config.yaml")
self.tts_settings = config.get("tts", {})
self.default_voice = self.tts_settings.get("default_voice", "alloy")
- logger.info(f"TTS settings loaded from config: voice={self.default_voice}")
+ self.logger.info(f"TTS settings loaded from config: voice={self.default_voice}")
except Exception as e:
- logger.warning(f"Failed to load TTS settings from config, using defaults: {e}")
+ self.logger.warning(f"Failed to load TTS settings from config, using defaults: {e}")
self.default_voice = "alloy"
try:
@@ -93,7 +72,7 @@ class NarratorAgent:
# Validate TTS configuration
self._validate_tts_config()
except Exception as e:
- logger.error(f"Failed to load TTS config: {e}", exc_info=True)
+ self.logger.error(f"Failed to load TTS config: {e}", exc_info=True)
self.tts_config = None
def _validate_tts_config(self):
@@ -143,11 +122,26 @@ class NarratorAgent:
# Log configuration info (hide sensitive information)
api_key_preview = f"{api_key[:8]}...{api_key[-4:]}" if len(api_key) > 12 else "*" * 10
- logger.info("TTS Configuration Loaded (OpenAI API):")
- logger.info(f" Model: {model}")
- logger.info(f" Base URL: {base_url}")
- logger.info(f" API Key: {api_key_preview}")
- logger.info(f" Default Voice: {self.default_voice}")
+ self.logger.info("TTS Configuration Loaded (OpenAI API):")
+ self.logger.info(f" Model: {model}")
+ self.logger.info(f" Base URL: {base_url}")
+ self.logger.info(f" API Key: {api_key_preview}")
+ self.logger.info(f" Default Voice: {self.default_voice}")
+
+ async def process(self, content: str, style: str = "friendly", voice: str = None, skip_audio: bool = False) -> dict[str, Any]:
+ """
+ Main processing method - alias for narrate().
+
+ Args:
+ content: Note content
+ style: Narration style
+ voice: Voice role
+ skip_audio: Whether to skip audio generation
+
+ Returns:
+ Dict containing script info and optionally audio info
+ """
+ return await self.narrate(content, style, voice, skip_audio)
async def generate_script(self, content: str, style: str = "friendly") -> dict[str, Any]:
"""
@@ -162,70 +156,47 @@ class NarratorAgent:
- script: Narration script text
- key_points: List of extracted key points
"""
- # Always refresh LLM config before starting to avoid stale credentials
- try:
- self.llm_config = get_llm_config()
- except Exception as e:
- logger.error(f"Failed to refresh LLM config: {e}")
-
- if not self.llm_config:
- raise ValueError("LLM configuration not available")
-
# Estimate target length: OpenAI TTS supports up to 4096 characters
- # We target 4000 characters to leave some margin
- target_length = 4000
is_long_content = len(content) > 5000
style_prompts = {
- "friendly": self._prompts.get("style_friendly", ""),
- "academic": self._prompts.get("style_academic", ""),
- "concise": self._prompts.get("style_concise", ""),
+ "friendly": self.get_prompt("style_friendly", ""),
+ "academic": self.get_prompt("style_academic", ""),
+ "concise": self.get_prompt("style_concise", ""),
}
length_instruction = (
- self._prompts.get("length_instruction_long", "")
+ self.get_prompt("length_instruction_long", "")
if is_long_content
- else self._prompts.get("length_instruction_short", "")
+ else self.get_prompt("length_instruction_short", "")
)
- system_template = self._prompts.get("generate_script_system_template", "")
+ system_template = self.get_prompt("generate_script_system_template", "")
system_prompt = system_template.format(
style_prompt=style_prompts.get(style, style_prompts["friendly"]),
length_instruction=length_instruction,
)
if is_long_content:
- user_template = self._prompts.get("generate_script_user_long", "")
+ user_template = self.get_prompt("generate_script_user_long", "")
user_prompt = user_template.format(content=content[:8000] + "...")
else:
- user_template = self._prompts.get("generate_script_user_short", "")
+ user_template = self.get_prompt("generate_script_user_short", "")
user_prompt = user_template.format(content=content)
- logger.info(f"Generating narration script with style: {style}")
+ self.logger.info(f"Generating narration script with style: {style}")
- model = self.llm_config.model
- response = await llm_complete(
- binding=self.llm_config.binding,
- model=model,
- prompt=user_prompt,
+ # Use inherited call_llm method
+ response = await self.call_llm(
+ user_prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config.api_key,
- base_url=self.llm_config.base_url,
- api_version=getattr(self.llm_config, "api_version", None),
- max_tokens=self._agent_params["max_tokens"],
- temperature=self._agent_params["temperature"],
- )
-
- # Track token usage
- stats = get_stats()
- stats.add_call(
- model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ stage="generate_script",
)
# Clean and truncate response, ensure it doesn't exceed 4000 characters
script = response.strip()
if len(script) > 4000:
- logger.warning(
+ self.logger.warning(
f"Generated script length {len(script)} exceeds 4000 limit. Truncating..."
)
truncated = script[:3997]
@@ -254,34 +225,18 @@ class NarratorAgent:
async def _extract_key_points(self, content: str) -> list:
"""Extract key points from notes"""
- if not self.llm_config:
- return []
-
- system_prompt = self._prompts.get("extract_key_points_system", "")
- user_template = self._prompts.get(
+ system_prompt = self.get_prompt("extract_key_points_system", "")
+ user_template = self.get_prompt(
"extract_key_points_user",
"Please extract key points from the following notes:\n\n{content}",
)
user_prompt = user_template.format(content=content[:4000])
try:
- model = self.llm_config.model
- response = await llm_complete(
- binding=self.llm_config.binding,
- model=model,
- prompt=user_prompt,
+ response = await self.call_llm(
+ user_prompt=user_prompt,
system_prompt=system_prompt,
- api_key=self.llm_config.api_key,
- base_url=self.llm_config.base_url,
- api_version=getattr(self.llm_config, "api_version", None),
- max_tokens=self._agent_params["max_tokens"],
- temperature=self._agent_params["temperature"],
- )
-
- # Track token usage
- stats = get_stats()
- stats.add_call(
- model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
+ stage="extract_key_points",
)
# Try to parse JSON
@@ -290,7 +245,7 @@ class NarratorAgent:
return json.loads(json_match.group())
return []
except Exception as e:
- logger.warning(f"Failed to extract key points: {e}")
+ self.logger.warning(f"Failed to extract key points: {e}")
return []
async def generate_audio(self, script: str, voice: str = None) -> dict[str, Any]:
@@ -326,7 +281,7 @@ class NarratorAgent:
# Truncate overly long scripts (OpenAI TTS supports up to 4096 characters)
original_script_length = len(script)
if len(script) > 4096:
- logger.warning(f"Script length {len(script)} exceeds 4096 limit. Truncating...")
+ self.logger.warning(f"Script length {len(script)} exceeds 4096 limit. Truncating...")
truncated = script[:4093]
last_period = max(
truncated.rfind("。"),
@@ -340,7 +295,7 @@ class NarratorAgent:
script = truncated[: last_period + 1]
else:
script = truncated + "..."
- logger.info(
+ self.logger.info(
f"Script truncated from {original_script_length} to {len(script)} characters"
)
@@ -348,14 +303,9 @@ class NarratorAgent:
audio_filename = f"narration_{audio_id}.mp3"
audio_path = USER_DIR / audio_filename
- logger.info(f"Starting TTS audio generation - ID: {audio_id}, Voice: {voice}")
+ self.logger.info(f"Starting TTS audio generation - ID: {audio_id}, Voice: {voice}")
try:
- # Check for Azure OpenAI TTS
- import os
-
- from openai import AsyncAzureOpenAI
-
binding = os.getenv("TTS_BINDING", "openai")
api_version = self.tts_config.get("api_version")
@@ -381,7 +331,7 @@ class NarratorAgent:
# Save audio to file
await response.stream_to_file(audio_path)
- logger.info(f"Audio saved to: {audio_path}")
+ self.logger.info(f"Audio saved to: {audio_path}")
# Use correct path: co-writer/audio (matching the actual storage directory)
relative_path = f"co-writer/audio/{audio_filename}"
@@ -395,7 +345,7 @@ class NarratorAgent:
}
except Exception as e:
- logger.error(f"TTS generation failed: {type(e).__name__}: {e}", exc_info=True)
+ self.logger.error(f"TTS generation failed: {type(e).__name__}: {e}", exc_info=True)
raise ValueError(f"TTS generation failed: {type(e).__name__}: {e}")
async def narrate(
@@ -420,10 +370,8 @@ class NarratorAgent:
# Refresh TTS config before starting to avoid stale credentials
try:
self.tts_config = get_tts_config()
- # Also refresh LLM config since narrate calls generate_script
- self.llm_config = get_llm_config()
except Exception as e:
- logger.error(f"Failed to refresh configs: {e}")
+ self.logger.error(f"Failed to refresh TTS config: {e}")
script_result = await self.generate_script(content, style)
@@ -452,7 +400,7 @@ class NarratorAgent:
}
)
except Exception as e:
- logger.error(f"Audio generation failed: {e}")
+ self.logger.error(f"Audio generation failed: {e}")
result["has_audio"] = False
result["audio_error"] = str(e)
else:
diff --git a/src/agents/guide/agents/base_guide_agent.py b/src/agents/guide/agents/base_guide_agent.py
deleted file mode 100644
index 770783df6..000000000
--- a/src/agents/guide/agents/base_guide_agent.py
+++ /dev/null
@@ -1,167 +0,0 @@
-#!/usr/bin/env python
-"""
-BaseGuideAgent - Base class for guided learning agents.
-Uses unified PromptManager for prompt loading.
-"""
-
-from abc import ABC, abstractmethod
-import os
-from pathlib import Path
-import sys
-from typing import Any
-
-# Add project root to path
-_project_root = Path(__file__).parent.parent.parent.parent
-if str(_project_root) not in sys.path:
- sys.path.insert(0, str(_project_root))
-
-from src.logging import LLMStats, get_logger
-from src.services.config import get_agent_params, load_config_with_main
-from src.services.llm import complete as llm_complete
-from src.services.llm import get_token_limit_kwargs
-from src.services.prompt import get_prompt_manager
-
-
-class BaseGuideAgent(ABC):
- """Base class for Guided Learning Agents."""
-
- # Shared stats tracker for all guide agents
- _shared_stats: LLMStats | None = None
-
- def __init__(
- self,
- api_key: str,
- base_url: str,
- agent_name: str,
- language: str = "zh",
- binding: str = "openai",
- ):
- """
- Initialize base Agent.
-
- Args:
- api_key: API key
- base_url: API endpoint
- agent_name: Agent name
- language: Language setting ('zh' | 'en')
- binding: LLM provider binding
- """
- self.api_key = api_key
- self.base_url = base_url
- self.agent_name = agent_name
- self.language = language
- self.binding = binding
-
- # Load agent parameters from unified config (agents.yaml)
- self._agent_params = get_agent_params("guide")
-
- # Initialize logger (from config)
- try:
- config = load_config_with_main("guide_config.yaml", _project_root)
- log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get(
- "log_dir"
- )
- self.logger = get_logger(f"Guide.{agent_name}", log_dir=log_dir)
- except Exception:
- # Fallback logger
- self.logger = get_logger(f"Guide.{agent_name}")
-
- # Load prompts using unified PromptManager
- self.prompts = get_prompt_manager().load_prompts(
- module_name="guide",
- agent_name=self.agent_name,
- language=self.language,
- )
- if self.prompts:
- self.logger.info(f"Loaded prompts: {self.agent_name} ({self.language})")
-
- @classmethod
- def get_stats(cls) -> LLMStats:
- """Get or create shared stats tracker."""
- if cls._shared_stats is None:
- cls._shared_stats = LLMStats(module_name="GuidedLearning")
- return cls._shared_stats
-
- @classmethod
- def reset_stats(cls):
- """Reset shared stats."""
- if cls._shared_stats:
- cls._shared_stats.reset()
-
- @classmethod
- def print_stats(cls):
- """Print stats summary."""
- if cls._shared_stats:
- cls._shared_stats.print_summary()
-
- def get_model(self) -> str:
- """Get model name."""
- model = os.getenv("LLM_MODEL")
- if not model:
- raise ValueError("Environment variable LLM_MODEL not set")
- return model
-
- async def call_llm(
- self,
- user_prompt: str,
- system_prompt: str,
- response_format: dict[str, str] | None = None,
- temperature: float | None = None,
- max_tokens: int | None = None,
- ) -> str:
- """
- Unified LLM call interface.
-
- Args:
- user_prompt: User prompt
- system_prompt: System prompt
- response_format: Response format
- temperature: Temperature parameter (uses config default if None)
- max_tokens: Maximum tokens (uses config default if None)
-
- Returns:
- LLM response text
- """
- model = self.get_model()
-
- # Use parameters from unified config (agents.yaml) if not explicitly provided
- if temperature is None:
- temperature = self._agent_params["temperature"]
- if max_tokens is None:
- max_tokens = self._agent_params["max_tokens"]
-
- kwargs = {
- "model": model,
- "prompt": user_prompt,
- "system_prompt": system_prompt,
- "api_key": self.api_key,
- "base_url": self.base_url,
- "temperature": temperature,
- "binding": self.binding,
- }
-
- if max_tokens:
- kwargs.update(get_token_limit_kwargs(model, max_tokens))
-
- if response_format:
- kwargs["response_format"] = response_format
-
- response = await llm_complete(**kwargs)
-
- # Track token usage
- stats = self.get_stats()
- stats.add_call(
- model=model, system_prompt=system_prompt, user_prompt=user_prompt, response=response
- )
-
- return response
-
- def get_prompt(self, prompt_type: str = "system") -> str | None:
- """Get prompt"""
- if self.prompts and prompt_type in self.prompts:
- return self.prompts[prompt_type]
- return None
-
- @abstractmethod
- async def process(self, *args, **kwargs) -> Any:
- """Main processing logic of the agent (must be implemented by subclasses)"""
diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py
index f189b037b..ca93be2c3 100644
--- a/src/agents/question/agents/base_agent.py
+++ b/src/agents/question/agents/base_agent.py
@@ -2,6 +2,11 @@
# -*- coding: utf-8 -*-
"""
Base Agent class - Implements the ReAct (Reasoning + Acting) paradigm.
+
+Uses the unified LLM Factory for all LLM calls, supporting:
+- Cloud providers (OpenAI, Anthropic, DeepSeek, etc.)
+- Local providers (Ollama, LM Studio, vLLM, etc.)
+- Automatic retry with exponential backoff
"""
from abc import ABC, abstractmethod
@@ -24,6 +29,9 @@ sys.path.insert(0, str(project_root))
from src.logging import get_logger
from src.services.config import get_agent_params
+from src.services.llm import complete as llm_complete
+from src.services.llm.capabilities import supports_response_format
+from src.services.llm.config import get_llm_config
# Module logger
_logger = get_logger("QuestionAgent")
@@ -97,33 +105,40 @@ class BaseAgent(ABC):
# Load agent parameters from unified config (agents.yaml)
self._agent_params = get_agent_params("question")
- if not api_key:
- api_key = os.getenv("LLM_API_KEY")
- if not base_url:
- base_url = os.getenv("LLM_HOST")
- if not api_version:
- api_version = os.getenv("LLM_API_VERSION")
-
- if model is None:
- model = os.getenv("LLM_MODEL", "gpt-4o")
- self.model = model
-
- # For local LLM servers, use placeholder key if none provided
- client_api_key = api_key or "sk-no-key-required"
+ # Load LLM configuration via unified config system
+ try:
+ llm_config = get_llm_config()
+ self.api_key = api_key or llm_config.api_key
+ self.base_url = base_url or llm_config.base_url
+ self.api_version = api_version or llm_config.api_version
+ self.binding = llm_config.binding or "openai"
+ self.model = model or llm_config.model
+ except Exception:
+ # Fallback to environment variables
+ self.api_key = api_key or os.getenv("LLM_API_KEY")
+ self.base_url = base_url or os.getenv("LLM_HOST")
+ self.api_version = api_version or os.getenv("LLM_API_VERSION")
+ self.binding = os.getenv("LLM_BINDING", "openai")
+ self.model = model or os.getenv("LLM_MODEL")
+
+ if not self.model:
+ from src.services.llm.exceptions import LLMConfigError
+ raise LLMConfigError(
+ "LLM_MODEL not configured. Please set it in .env or activate a provider."
+ )
- binding = os.getenv("LLM_BINDING", "openai")
- if binding == "azure_openai" or api_version:
+ # Initialize OpenAI client for direct API calls
+ if self.binding == "azure":
self.client = AsyncAzureOpenAI(
- api_key=client_api_key,
- azure_endpoint=base_url,
- api_version=api_version,
+ api_key=self.api_key,
+ azure_endpoint=self.base_url,
+ api_version=self.api_version or "2024-02-15-preview",
)
else:
- self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
-
- self.api_key = api_key
- self.base_url = base_url
- self.api_version = api_version
+ self.client = AsyncOpenAI(
+ api_key=self.api_key,
+ base_url=self.base_url,
+ )
self.thought_history: list[str] = []
self.action_history: list[Action] = []
@@ -323,32 +338,37 @@ Output JSON format:
5. History can be referenced, but if it's a new round, must re-execute key steps
"""
- response = await self.client.chat.completions.create(
+ # Build kwargs for LLM Factory
+ llm_kwargs = {
+ "temperature": self._agent_params["temperature"],
+ "max_tokens": self._agent_params["max_tokens"],
+ }
+
+ # Only add response_format if the provider supports it
+ if supports_response_format(self.binding, self.model):
+ llm_kwargs["response_format"] = {"type": "json_object"}
+
+ # Call LLM via unified Factory (supports all providers with retry)
+ response_content = await llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
model=self.model,
- messages=[
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ],
- temperature=self._agent_params["temperature"],
- max_tokens=self._agent_params["max_tokens"],
- response_format={"type": "json_object"},
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
+ **llm_kwargs,
)
- # Extract response content
- response_content = response.choices[0].message.content
-
# Update token statistics if callback is available
- input_tokens = 0
- output_tokens = 0
- cost = 0.0
- if hasattr(response, "usage") and response.usage:
- input_tokens = response.usage.prompt_tokens
- output_tokens = response.usage.completion_tokens
- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
- if self.token_stats_callback:
- self.token_stats_callback(
- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
- )
+ # Note: Factory doesn't return token counts, estimate based on response
+ if self.token_stats_callback:
+ # Rough estimation: ~4 chars per token
+ input_tokens = (len(system_prompt) + len(user_prompt)) // 4
+ output_tokens = len(response_content) // 4
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
# Log LLM call with detailed information
_logger.log_llm_call(
@@ -358,9 +378,9 @@ Output JSON format:
user_prompt=user_prompt,
response=response_content,
agent_name=self.agent_name,
- input_tokens=input_tokens,
- output_tokens=output_tokens,
- cost=cost,
+ input_tokens=0, # Not available from factory
+ output_tokens=0,
+ cost=0.0,
level="DEBUG",
)
diff --git a/src/agents/question/tools/question_extractor.py b/src/agents/question/tools/question_extractor.py
index 808bdc34c..6d1097a17 100644
--- a/src/agents/question/tools/question_extractor.py
+++ b/src/agents/question/tools/question_extractor.py
@@ -5,9 +5,15 @@ Extract question information from MinerU-parsed exam papers
This script reads MinerU-parsed markdown files and content_list.json,
uses LLM to analyze and extract all questions, including question content and related images.
+
+Uses the unified LLM Factory for all LLM calls, supporting:
+- Cloud providers (OpenAI, Anthropic, DeepSeek, etc.)
+- Local providers (Ollama, LM Studio, vLLM, etc.)
+- Automatic retry with exponential backoff
"""
import argparse
+import asyncio
from datetime import datetime
import json
from pathlib import Path
@@ -17,10 +23,10 @@ from typing import Any
project_root = Path(__file__).parent.parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from openai import AzureOpenAI, OpenAI
-
from src.services.config import get_agent_params
-from src.services.llm import get_llm_config
+from src.services.llm import complete as llm_complete
+from src.services.llm.capabilities import supports_response_format
+from src.services.llm.config import get_llm_config
def load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, Path]:
@@ -76,6 +82,7 @@ def extract_questions_with_llm(
base_url: str,
model: str,
api_version: str | None = None,
+ binding: str | None = None,
) -> list[dict[str, Any]]:
"""
Use LLM to analyze markdown content and extract questions
@@ -88,6 +95,7 @@ def extract_questions_with_llm(
base_url: API endpoint URL
model: Model name
api_version: API version for Azure OpenAI (optional)
+ binding: Provider binding type (optional)
Returns:
Question list, each question contains:
@@ -99,15 +107,7 @@ def extract_questions_with_llm(
"""
import os
- binding = os.getenv("LLM_BINDING", "openai")
- if binding == "azure_openai" or api_version:
- client = AzureOpenAI(
- api_key=api_key,
- azure_endpoint=base_url,
- api_version=api_version,
- )
- else:
- client = OpenAI(api_key=api_key, base_url=base_url)
+ binding = binding or os.getenv("LLM_BINDING", "openai")
image_list = []
if images_dir.exists():
@@ -170,19 +170,31 @@ Please analyze the above exam paper content, extract all question information, a
# Get agent parameters from unified config
agent_params = get_agent_params("question")
+ # Build kwargs for LLM Factory
+ llm_kwargs = {
+ "temperature": agent_params["temperature"],
+ "max_tokens": agent_params["max_tokens"],
+ }
+
+ # Only add response_format if the provider supports it
+ if supports_response_format(binding, model):
+ llm_kwargs["response_format"] = {"type": "json_object"}
+
try:
- response = client.chat.completions.create(
- model=model,
- messages=[
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": user_prompt},
- ],
- temperature=agent_params["temperature"],
- max_tokens=agent_params["max_tokens"],
- response_format={"type": "json_object"},
+ # Call LLM via unified Factory (async, so we need to run in event loop)
+ result_text = asyncio.run(
+ llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ api_version=api_version,
+ binding=binding,
+ **llm_kwargs,
+ )
)
- result_text = response.choices[0].message.content
result = json.loads(result_text)
questions = result.get("questions", [])
@@ -281,6 +293,7 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
base_url=llm_config.base_url,
model=llm_config.model,
api_version=getattr(llm_config, "api_version", None),
+ binding=getattr(llm_config, "binding", None),
)
if not questions:
diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py
index bd1dfc0a6..1494ddacb 100644
--- a/src/agents/question/validation_workflow.py
+++ b/src/agents/question/validation_workflow.py
@@ -2,7 +2,11 @@
# -*- coding: utf-8 -*-
"""
Question Validation Workflow: retrieve -> validate -> return.
-Uses unified PromptManager for prompt loading.
+
+Uses unified LLM Factory for all LLM calls, supporting:
+- Cloud providers (OpenAI, Anthropic, DeepSeek, etc.)
+- Local providers (Ollama, LM Studio, vLLM, etc.)
+- Automatic retry with exponential backoff
"""
from collections.abc import Callable
@@ -12,14 +16,15 @@ from pathlib import Path
import sys
from typing import Any
-from openai import AsyncAzureOpenAI, AsyncOpenAI
-
# Add project root to path
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
from src.logging import get_logger
from src.services.config import get_agent_params, load_config_with_main
+from src.services.llm import complete as llm_complete
+from src.services.llm.capabilities import supports_response_format
+from src.services.llm.config import get_llm_config
from src.services.prompt import get_prompt_manager
from src.tools.rag_tool import rag_search
@@ -52,33 +57,28 @@ class QuestionValidationWorkflow:
token_stats_callback: Callback function to update token statistics
language: Language for prompts ("en" or "zh")
"""
- # API configuration
- if not api_key:
- api_key = os.getenv("LLM_API_KEY")
- if not base_url:
- base_url = os.getenv("LLM_HOST")
- if not api_version:
- api_version = os.getenv("LLM_API_VERSION")
- if model is None:
- model = os.getenv("LLM_MODEL", "gpt-4o")
-
- # For local LLM servers, use placeholder key if none provided
- client_api_key = api_key or "sk-no-key-required"
-
- binding = os.getenv("LLM_BINDING", "openai")
- if binding == "azure_openai" or api_version:
- self.client = AsyncAzureOpenAI(
- api_key=client_api_key,
- azure_endpoint=base_url,
- api_version=api_version,
+ # Load LLM configuration via unified config system
+ try:
+ llm_config = get_llm_config()
+ self.api_key = api_key or llm_config.api_key
+ self.base_url = base_url or llm_config.base_url
+ self.api_version = api_version or llm_config.api_version
+ self.binding = llm_config.binding or "openai"
+ self.model = model or llm_config.model
+ except Exception:
+ # Fallback to environment variables
+ self.api_key = api_key or os.getenv("LLM_API_KEY")
+ self.base_url = base_url or os.getenv("LLM_HOST")
+ self.api_version = api_version or os.getenv("LLM_API_VERSION")
+ self.binding = os.getenv("LLM_BINDING", "openai")
+ self.model = model or os.getenv("LLM_MODEL")
+
+ if not self.model:
+ from src.services.llm.exceptions import LLMConfigError
+ raise LLMConfigError(
+ "LLM_MODEL not configured. Please set it in .env or activate a provider."
)
- else:
- self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
- self.api_key = api_key
- self.base_url = base_url
- self.api_version = api_version
- self.model = model
self.kb_name = kb_name
self.token_stats_callback = token_stats_callback
self.language = language
@@ -151,6 +151,8 @@ class QuestionValidationWorkflow:
options = question.get("options", {})
correct_answer = question.get("correct_answer", "")
+ system_prompt = "You are a professional knowledge retrieval expert."
+
prompt = f"""Analyze the following question and generate a concise retrieval query to retrieve relevant knowledge from the knowledge base to validate this question.
Question information:
@@ -175,42 +177,40 @@ Requirements:
Output the retrieval query directly, no additional content.
"""
- response = await self.client.chat.completions.create(
+ # Call LLM via unified Factory (supports all providers with retry)
+ response_content = await llm_complete(
+ prompt=prompt,
+ system_prompt=system_prompt,
model=self.model,
- messages=[
- {"role": "system", "content": "You are a professional knowledge retrieval expert."},
- {"role": "user", "content": prompt},
- ],
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
temperature=0.3,
)
- # Extract response content
- response_content = response.choices[0].message.content.strip()
+ response_content = response_content.strip()
# Update token statistics if callback is available
- input_tokens = 0
- output_tokens = 0
- cost = 0.0
- if hasattr(response, "usage") and response.usage:
- input_tokens = response.usage.prompt_tokens
- output_tokens = response.usage.completion_tokens
- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
- if self.token_stats_callback:
- self.token_stats_callback(
- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
- )
+ if self.token_stats_callback:
+ # Rough estimation: ~4 chars per token
+ input_tokens = (len(system_prompt) + len(prompt)) // 4
+ output_tokens = len(response_content) // 4
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
# Log LLM call with detailed information
logger.log_llm_call(
model=self.model,
stage="generate_query",
- system_prompt="You are a professional knowledge retrieval expert.",
+ system_prompt=system_prompt,
user_prompt=prompt,
response=response_content,
agent_name="QuestionValidationWorkflow",
- input_tokens=input_tokens,
- output_tokens=output_tokens,
- cost=cost,
+ input_tokens=0,
+ output_tokens=0,
+ cost=0.0,
level="DEBUG",
)
@@ -279,48 +279,51 @@ Output the retrieval query directly, no additional content.
validation_knowledge=knowledge_str,
)
+ system_prompt = "You are a professional question validation expert who strictly validates questions based on knowledge base content."
+
try:
- response = await self.client.chat.completions.create(
+ # Build kwargs for LLM Factory
+ llm_kwargs = {
+ "temperature": self._agent_params["temperature"],
+ "max_tokens": self._agent_params["max_tokens"],
+ }
+
+ # Only add response_format if the provider supports it
+ if supports_response_format(self.binding, self.model):
+ llm_kwargs["response_format"] = {"type": "json_object"}
+
+ # Call LLM via unified Factory (supports all providers with retry)
+ response_content = await llm_complete(
+ prompt=prompt,
+ system_prompt=system_prompt,
model=self.model,
- messages=[
- {
- "role": "system",
- "content": "You are a professional question validation expert who strictly validates questions based on knowledge base content.",
- },
- {"role": "user", "content": prompt},
- ],
- temperature=self._agent_params["temperature"],
- max_tokens=self._agent_params["max_tokens"],
- response_format={"type": "json_object"},
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
+ **llm_kwargs,
)
- # Extract response content
- response_content = response.choices[0].message.content
-
# Update token statistics if callback is available
- input_tokens = 0
- output_tokens = 0
- cost = 0.0
- if hasattr(response, "usage") and response.usage:
- input_tokens = response.usage.prompt_tokens
- output_tokens = response.usage.completion_tokens
- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
- if self.token_stats_callback:
- self.token_stats_callback(
- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
- )
+ if self.token_stats_callback:
+ # Rough estimation: ~4 chars per token
+ input_tokens = (len(system_prompt) + len(prompt)) // 4
+ output_tokens = len(response_content) // 4
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
# Log LLM call with detailed information
logger.log_llm_call(
model=self.model,
stage="validate",
- system_prompt="You are a professional question validation expert who strictly validates questions based on knowledge base content.",
+ system_prompt=system_prompt,
user_prompt=prompt,
response=response_content,
agent_name="QuestionValidationWorkflow",
- input_tokens=input_tokens,
- output_tokens=output_tokens,
- cost=cost,
+ input_tokens=0,
+ output_tokens=0,
+ cost=0.0,
level="DEBUG",
)
@@ -407,6 +410,8 @@ Output the retrieval query directly, no additional content.
if len(context_str) > 4000:
context_str = context_str[:4000] + "...[truncated]"
+ system_prompt = "You are an educational content analyst specializing in identifying knowledge connections and learning extensions."
+
prompt = f"""Analyze how the following question relates to and extends from the knowledge base content.
Question:
@@ -431,30 +436,32 @@ Guidelines:
Output only the JSON, no additional text."""
try:
- response = await self.client.chat.completions.create(
+ # Build kwargs for LLM Factory
+ llm_kwargs = {"temperature": 0.3}
+
+ # Only add response_format if the provider supports it
+ if supports_response_format(self.binding, self.model):
+ llm_kwargs["response_format"] = {"type": "json_object"}
+
+ # Call LLM via unified Factory (supports all providers with retry)
+ response_content = await llm_complete(
+ prompt=prompt,
+ system_prompt=system_prompt,
model=self.model,
- messages=[
- {
- "role": "system",
- "content": "You are an educational content analyst specializing in identifying knowledge connections and learning extensions.",
- },
- {"role": "user", "content": prompt},
- ],
- temperature=0.3,
- response_format={"type": "json_object"},
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
+ **llm_kwargs,
)
- response_content = response.choices[0].message.content
-
# Update token statistics
- if hasattr(response, "usage") and response.usage:
- input_tokens = response.usage.prompt_tokens
- output_tokens = response.usage.completion_tokens
- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
- if self.token_stats_callback:
- self.token_stats_callback(
- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
- )
+ if self.token_stats_callback:
+ input_tokens = (len(system_prompt) + len(prompt)) // 4
+ output_tokens = len(response_content) // 4
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
result = json.loads(response_content)
@@ -504,6 +511,8 @@ Output only the JSON, no additional text."""
if len(context_str) > 4000:
context_str = context_str[:4000] + "...[truncated]"
+ system_prompt = "You are an educational content analyst specializing in analyzing the relationship between exam questions and knowledge base content."
+
prompt = f"""Analyze the relevance between the following exam question and the knowledge base content.
Question:
@@ -536,44 +545,44 @@ For extension_points (only when relevance is "partial"):
Output only the JSON, no additional text."""
try:
- response = await self.client.chat.completions.create(
+ # Build kwargs for LLM Factory
+ llm_kwargs = {"temperature": 0.3}
+
+ # Only add response_format if the provider supports it
+ if supports_response_format(self.binding, self.model):
+ llm_kwargs["response_format"] = {"type": "json_object"}
+
+ # Call LLM via unified Factory (supports all providers with retry)
+ response_content = await llm_complete(
+ prompt=prompt,
+ system_prompt=system_prompt,
model=self.model,
- messages=[
- {
- "role": "system",
- "content": "You are an educational content analyst specializing in analyzing the relationship between exam questions and knowledge base content.",
- },
- {"role": "user", "content": prompt},
- ],
- temperature=0.3,
- response_format={"type": "json_object"},
+ api_key=self.api_key,
+ base_url=self.base_url,
+ api_version=self.api_version,
+ binding=self.binding,
+ **llm_kwargs,
)
- response_content = response.choices[0].message.content
-
# Update token statistics
- input_tokens = 0
- output_tokens = 0
- if hasattr(response, "usage") and response.usage:
- input_tokens = response.usage.prompt_tokens
- output_tokens = response.usage.completion_tokens
- cost = input_tokens * 0.00000015 + output_tokens * 0.0000006
- if self.token_stats_callback:
- self.token_stats_callback(
- input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
- )
+ if self.token_stats_callback:
+ input_tokens = (len(system_prompt) + len(prompt)) // 4
+ output_tokens = len(response_content) // 4
+ self.token_stats_callback(
+ input_tokens=input_tokens, output_tokens=output_tokens, model=self.model
+ )
# Log LLM call
logger.log_llm_call(
model=self.model,
stage="analyze_relevance",
- system_prompt="Educational content analyst for relevance analysis",
+ system_prompt=system_prompt,
user_prompt=prompt,
response=response_content,
agent_name="QuestionValidationWorkflow",
- input_tokens=input_tokens,
- output_tokens=output_tokens,
- cost=input_tokens * 0.00000015 + output_tokens * 0.0000006,
+ input_tokens=0,
+ output_tokens=0,
+ cost=0.0,
level="DEBUG",
)
diff --git a/src/api/routers/solve.py b/src/api/routers/solve.py
index 4a7c216d0..3ec312416 100644
--- a/src/api/routers/solve.py
+++ b/src/api/routers/solve.py
@@ -21,7 +21,8 @@ from src.api.utils.task_id_manager import TaskIDManager
_project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(_project_root))
from src.logging import get_logger
-from src.services.config import get_llm_config, load_config_with_main
+from src.services.config import load_config_with_main
+from src.services.llm import get_llm_config
# Initialize logger with config
project_root = Path(__file__).parent.parent.parent.parent
diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.py
index dae3c2883..0b82a6937 100644
--- a/src/services/llm/__init__.py
+++ b/src/services/llm/__init__.py
@@ -16,15 +16,29 @@ Architecture:
CloudProvider LocalProvider
(cloud_provider) (local_provider)
+Features:
+- Unified interface for all LLM providers (cloud + local)
+- Automatic retry with exponential backoff
+- Smart routing based on URL/configuration
+- Provider capability detection
+
Usage:
- # Simple completion
+ # Simple completion (with automatic retry)
from src.services.llm import complete, stream
response = await complete("Hello!", system_prompt="You are helpful.")
- # Streaming
+ # Streaming (with automatic retry on connection)
async for chunk in stream("Hello!", system_prompt="You are helpful."):
print(chunk, end="")
+ # Custom retry configuration
+ response = await complete(
+ "Hello!",
+ max_retries=5,
+ retry_delay=2.0,
+ exponential_backoff=True,
+ )
+
# Configuration
from src.services.llm import get_llm_config, LLMConfig
config = get_llm_config()
@@ -42,6 +56,18 @@ Usage:
# Also expose the providers for direct access if needed
from . import cloud_provider, local_provider
+from .capabilities import (
+ DEFAULT_CAPABILITIES,
+ MODEL_OVERRIDES,
+ PROVIDER_CAPABILITIES,
+ get_capability,
+ has_thinking_tags,
+ requires_api_version,
+ supports_response_format,
+ supports_streaming,
+ supports_tools,
+ system_in_messages,
+)
from .client import LLMClient, get_llm_client, reset_llm_client
from .config import (
LLMConfig,
@@ -49,13 +75,25 @@ from .config import (
get_token_limit_kwargs,
uses_max_completion_tokens,
)
+from .exceptions import (
+ LLMAPIError,
+ LLMAuthenticationError,
+ LLMConfigError,
+ LLMError,
+ LLMModelNotFoundError,
+ LLMProviderError,
+ LLMRateLimitError,
+ LLMTimeoutError,
+)
from .factory import (
API_PROVIDER_PRESETS,
+ DEFAULT_EXPONENTIAL_BACKOFF,
+ DEFAULT_MAX_RETRIES,
+ DEFAULT_RETRY_DELAY,
LOCAL_PROVIDER_PRESETS,
LLMMode,
complete,
fetch_models,
- get_effective_config,
get_llm_mode,
get_mode_info,
get_provider_presets,
@@ -67,7 +105,14 @@ from .provider import (
ProviderType,
provider_manager,
)
-from .utils import is_local_llm_server, sanitize_url
+from .utils import (
+ build_auth_headers,
+ build_chat_url,
+ clean_thinking_tags,
+ extract_response_content,
+ is_local_llm_server,
+ sanitize_url,
+)
__all__ = [
# Client (legacy, prefer factory functions)
@@ -79,10 +124,29 @@ __all__ = [
"get_llm_config",
"uses_max_completion_tokens",
"get_token_limit_kwargs",
+ # Capabilities
+ "PROVIDER_CAPABILITIES",
+ "MODEL_OVERRIDES",
+ "DEFAULT_CAPABILITIES",
+ "get_capability",
+ "supports_response_format",
+ "supports_streaming",
+ "system_in_messages",
+ "has_thinking_tags",
+ "supports_tools",
+ "requires_api_version",
+ # Exceptions
+ "LLMError",
+ "LLMConfigError",
+ "LLMProviderError",
+ "LLMAPIError",
+ "LLMTimeoutError",
+ "LLMRateLimitError",
+ "LLMAuthenticationError",
+ "LLMModelNotFoundError",
# Factory (main API)
"LLMMode",
"get_llm_mode",
- "get_effective_config",
"get_mode_info",
"complete",
"stream",
@@ -90,6 +154,10 @@ __all__ = [
"get_provider_presets",
"API_PROVIDER_PRESETS",
"LOCAL_PROVIDER_PRESETS",
+ # Retry configuration
+ "DEFAULT_MAX_RETRIES",
+ "DEFAULT_RETRY_DELAY",
+ "DEFAULT_EXPONENTIAL_BACKOFF",
# Providers
"cloud_provider",
"local_provider",
@@ -101,4 +169,8 @@ __all__ = [
# Utils
"sanitize_url",
"is_local_llm_server",
+ "build_chat_url",
+ "build_auth_headers",
+ "clean_thinking_tags",
+ "extract_response_content",
]
diff --git a/src/services/llm/capabilities.py b/src/services/llm/capabilities.py
new file mode 100644
index 000000000..53877fb8d
--- /dev/null
+++ b/src/services/llm/capabilities.py
@@ -0,0 +1,313 @@
+"""
+Provider Capabilities
+=====================
+
+Centralized configuration for LLM provider capabilities.
+This replaces scattered hardcoded checks throughout the codebase.
+
+Usage:
+ from src.services.llm.capabilities import get_capability, supports_response_format
+
+ # Check if a provider supports response_format
+ if supports_response_format(binding, model):
+ kwargs["response_format"] = {"type": "json_object"}
+
+ # Generic capability check
+ if get_capability(binding, "streaming", default=True):
+ # use streaming
+"""
+
+from typing import Any, Optional
+
+
+# Provider capabilities configuration
+# Keys are binding names (lowercase), values are capability dictionaries
+PROVIDER_CAPABILITIES: dict[str, dict[str, Any]] = {
+ # OpenAI and OpenAI-compatible providers
+ "openai": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True, # System prompt goes in messages array
+ "newer_models_use_max_completion_tokens": True,
+ },
+ "azure_openai": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ "newer_models_use_max_completion_tokens": True,
+ "requires_api_version": True,
+ },
+ # Anthropic
+ "anthropic": {
+ "supports_response_format": False, # Anthropic uses different format
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": False, # System is a separate parameter
+ "has_thinking_tags": False,
+ },
+ "claude": { # Alias for anthropic
+ "supports_response_format": False,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": False,
+ "has_thinking_tags": False,
+ },
+ # DeepSeek
+ "deepseek": {
+ "supports_response_format": False, # DeepSeek doesn't support strict JSON schema yet
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ "has_thinking_tags": True, # DeepSeek reasoner has thinking tags
+ },
+ # OpenRouter (aggregator, generally OpenAI-compatible)
+ "openrouter": {
+ "supports_response_format": True, # Depends on underlying model
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ },
+ # Groq (fast inference)
+ "groq": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ },
+ # Together AI
+ "together": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ },
+ "together_ai": { # Alias
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ },
+ # Mistral
+ "mistral": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": True,
+ "system_in_messages": True,
+ },
+ # Local providers (generally OpenAI-compatible)
+ "ollama": {
+ "supports_response_format": True, # Ollama supports JSON mode
+ "supports_streaming": True,
+ "supports_tools": False, # Limited tool support
+ "system_in_messages": True,
+ },
+ "lm_studio": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": False,
+ "system_in_messages": True,
+ },
+ "vllm": {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": False,
+ "system_in_messages": True,
+ },
+ "llama_cpp": {
+ "supports_response_format": True, # llama.cpp server supports JSON grammar
+ "supports_streaming": True,
+ "supports_tools": False,
+ "system_in_messages": True,
+ },
+}
+
+# Default capabilities for unknown providers (assume OpenAI-compatible)
+DEFAULT_CAPABILITIES: dict[str, Any] = {
+ "supports_response_format": True,
+ "supports_streaming": True,
+ "supports_tools": False,
+ "system_in_messages": True,
+ "has_thinking_tags": False,
+}
+
+# Model-specific overrides
+# Format: {model_pattern: {capability: value}}
+# Patterns are matched with case-insensitive startswith
+MODEL_OVERRIDES: dict[str, dict[str, Any]] = {
+ "deepseek": {
+ "supports_response_format": False,
+ "has_thinking_tags": True,
+ },
+ "deepseek-reasoner": {
+ "supports_response_format": False,
+ "has_thinking_tags": True,
+ },
+ "qwen": {
+ # Qwen models may have thinking tags
+ "has_thinking_tags": True,
+ },
+ "qwq": {
+ # QwQ is Qwen's reasoning model with thinking tags
+ "has_thinking_tags": True,
+ },
+ # Claude models through OpenRouter or other providers
+ "claude": {
+ "supports_response_format": False,
+ "system_in_messages": False,
+ },
+ # Anthropic models
+ "anthropic/": {
+ "supports_response_format": False,
+ "system_in_messages": False,
+ },
+}
+
+
+def get_capability(
+ binding: str,
+ capability: str,
+ model: Optional[str] = None,
+ default: Any = None,
+) -> Any:
+ """
+ Get a capability value for a provider/model combination.
+
+ Checks in order:
+ 1. Model-specific overrides (matched by prefix)
+ 2. Provider/binding capabilities
+ 3. Default capabilities for unknown providers
+ 4. Explicit default value
+
+ Args:
+ binding: Provider binding name (e.g., "openai", "anthropic", "deepseek")
+ capability: Capability name (e.g., "supports_response_format")
+ model: Optional model name for model-specific overrides
+ default: Default value if capability is not defined
+
+ Returns:
+ Capability value or default
+ """
+ binding_lower = (binding or "openai").lower()
+
+ # 1. Check model-specific overrides first
+ if model:
+ model_lower = model.lower()
+ for pattern, overrides in MODEL_OVERRIDES.items():
+ if model_lower.startswith(pattern):
+ if capability in overrides:
+ return overrides[capability]
+
+ # 2. Check provider capabilities
+ provider_caps = PROVIDER_CAPABILITIES.get(binding_lower, {})
+ if capability in provider_caps:
+ return provider_caps[capability]
+
+ # 3. Check default capabilities for unknown providers
+ if capability in DEFAULT_CAPABILITIES:
+ return DEFAULT_CAPABILITIES[capability]
+
+ # 4. Return explicit default
+ return default
+
+
+def supports_response_format(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if the provider/model supports response_format parameter.
+
+ This is a convenience function for the most common capability check.
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name for model-specific overrides
+
+ Returns:
+ True if response_format is supported
+ """
+ return get_capability(binding, "supports_response_format", model, default=True)
+
+
+def supports_streaming(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if the provider/model supports streaming responses.
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name
+
+ Returns:
+ True if streaming is supported
+ """
+ return get_capability(binding, "supports_streaming", model, default=True)
+
+
+def system_in_messages(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if system prompt should be in messages array (OpenAI style)
+ or as a separate parameter (Anthropic style).
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name
+
+ Returns:
+ True if system prompt goes in messages array
+ """
+ return get_capability(binding, "system_in_messages", model, default=True)
+
+
+def has_thinking_tags(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if the model output may contain thinking tags (<think>...</think>).
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name
+
+ Returns:
+ True if thinking tags should be filtered
+ """
+ return get_capability(binding, "has_thinking_tags", model, default=False)
+
+
+def supports_tools(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if the provider/model supports function calling / tools.
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name
+
+ Returns:
+ True if tools/function calling is supported
+ """
+ return get_capability(binding, "supports_tools", model, default=False)
+
+
+def requires_api_version(binding: str, model: Optional[str] = None) -> bool:
+ """
+ Check if the provider requires an API version parameter (e.g., Azure OpenAI).
+
+ Args:
+ binding: Provider binding name
+ model: Optional model name
+
+ Returns:
+ True if api_version is required
+ """
+ return get_capability(binding, "requires_api_version", model, default=False)
+
+
+__all__ = [
+ "PROVIDER_CAPABILITIES",
+ "MODEL_OVERRIDES",
+ "DEFAULT_CAPABILITIES",
+ "get_capability",
+ "supports_response_format",
+ "supports_streaming",
+ "system_in_messages",
+ "has_thinking_tags",
+ "supports_tools",
+ "requires_api_version",
+]
diff --git a/src/services/llm/client.py b/src/services/llm/client.py
index d0f9b1d23..b182b0373 100644
--- a/src/services/llm/client.py
+++ b/src/services/llm/client.py
@@ -3,12 +3,16 @@ LLM Client
==========
Unified LLM client for all DeepTutor services.
+
+Note: This is a legacy interface. Prefer using the factory functions directly:
+ from src.services.llm import complete, stream
"""
from typing import Any, Dict, List, Optional
from src.logging import get_logger
+from .capabilities import system_in_messages
from .config import LLMConfig, get_llm_config
@@ -16,7 +20,8 @@ class LLMClient:
"""
Unified LLM client for all services.
- Wraps the underlying LLM API (OpenAI-compatible) with a consistent interface.
+ Wraps the LLM Factory with a class-based interface.
+ Prefer using factory functions (complete, stream) directly for new code.
"""
def __init__(self, config: Optional[LLMConfig] = None):
@@ -37,7 +42,7 @@ class LLMClient:
**kwargs: Any,
) -> str:
"""
- Call LLM completion.
+ Call LLM completion via Factory.
Args:
prompt: User prompt
@@ -48,16 +53,17 @@ class LLMClient:
Returns:
LLM response text
"""
- from lightrag.llm.openai import openai_complete_if_cache
+ from . import factory
- return await openai_complete_if_cache(
- self.config.model,
- prompt,
- system_prompt=system_prompt,
- history_messages=history or [],
+ # Delegate to factory for unified routing and retry handling
+ return await factory.complete(
+ prompt=prompt,
+ system_prompt=system_prompt or "You are a helpful assistant.",
+ model=self.config.model,
api_key=self.config.api_key,
base_url=self.config.base_url,
api_version=getattr(self.config, "api_version", None),
+ binding=getattr(self.config, "binding", "openai"),
**kwargs,
)
@@ -100,6 +106,34 @@ class LLMClient:
Returns:
Callable that can be used as llm_model_func
"""
+ binding = getattr(self.config, "binding", "openai")
+
+ # Use capabilities to determine if provider uses OpenAI-style messages
+ uses_openai_style = system_in_messages(binding, self.config.model)
+
+ # For non-OpenAI-compatible providers (e.g., Anthropic), use Factory
+ if not uses_openai_style:
+ from . import factory
+
+ def llm_model_func_via_factory(
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history_messages: Optional[List[Dict]] = None,
+ **kwargs: Any,
+ ):
+ return factory.complete(
+ prompt=prompt,
+ system_prompt=system_prompt or "You are a helpful assistant.",
+ model=self.config.model,
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ binding=binding,
+ **kwargs,
+ )
+
+ return llm_model_func_via_factory
+
+ # OpenAI-compatible bindings use lightrag (has caching)
from lightrag.llm.openai import openai_complete_if_cache
def llm_model_func(
@@ -128,6 +162,38 @@ class LLMClient:
Returns:
Callable that can be used as vision_model_func
"""
+ binding = getattr(self.config, "binding", "openai")
+
+ # Use capabilities to determine if provider uses OpenAI-style messages
+ uses_openai_style = system_in_messages(binding, self.config.model)
+
+ # For non-OpenAI-compatible providers, use Factory
+ if not uses_openai_style:
+ from . import factory
+
+ def vision_model_func_via_factory(
+ prompt: str,
+ system_prompt: Optional[str] = None,
+ history_messages: Optional[List[Dict]] = None,
+ image_data: Optional[str] = None,
+ messages: Optional[List[Dict]] = None,
+ **kwargs: Any,
+ ):
+ # Use factory for unified handling
+ return factory.complete(
+ prompt=prompt,
+ system_prompt=system_prompt or "You are a helpful assistant.",
+ model=self.config.model,
+ api_key=self.config.api_key,
+ base_url=self.config.base_url,
+ binding=binding,
+ messages=messages,
+ **kwargs,
+ )
+
+ return vision_model_func_via_factory
+
+ # OpenAI-compatible bindings
from lightrag.llm.openai import openai_complete_if_cache
def vision_model_func(
diff --git a/src/services/llm/cloud_provider.py b/src/services/llm/cloud_provider.py
index ca2c01c4d..bae516705 100644
--- a/src/services/llm/cloud_provider.py
+++ b/src/services/llm/cloud_provider.py
@@ -7,13 +7,21 @@ Provides both complete() and stream() methods.
"""
import os
-import re
from typing import AsyncGenerator, Dict, List, Optional
import aiohttp
from lightrag.llm.openai import openai_complete_if_cache
-from .utils import sanitize_url
+from .capabilities import supports_response_format
+from .config import get_token_limit_kwargs
+from .exceptions import LLMAPIError, LLMAuthenticationError, LLMConfigError
+from .utils import (
+ build_auth_headers,
+ build_chat_url,
+ clean_thinking_tags,
+ extract_response_content,
+ sanitize_url,
+)
async def complete(
@@ -64,6 +72,7 @@ async def complete(
api_key=api_key,
base_url=base_url,
api_version=api_version,
+ binding=binding_lower,
**kwargs,
)
@@ -117,6 +126,7 @@ async def stream(
api_key=api_key,
base_url=base_url,
api_version=api_version,
+ binding=binding_lower,
messages=messages,
**kwargs,
):
@@ -130,6 +140,7 @@ async def _openai_complete(
api_key: Optional[str],
base_url: Optional[str],
api_version: Optional[str] = None,
+ binding: str = "openai",
**kwargs,
) -> str:
"""OpenAI-compatible completion."""
@@ -137,10 +148,9 @@ async def _openai_complete(
if base_url:
base_url = sanitize_url(base_url, model)
- # 1. MODEL-SPECIFIC: Handle API Parameter Compatibility
- # Only remove response_format for DeepSeek because they don't support the strict schema yet.
- # We WANT to keep it for OpenAI/Azure because it improves reliability.
- if model and "deepseek" in model.lower():
+ # Handle API Parameter Compatibility using capabilities
+ # Remove response_format for providers that don't support it (e.g., DeepSeek)
+ if not supports_response_format(binding, model):
kwargs.pop("response_format", None)
content = None
@@ -160,22 +170,11 @@ async def _openai_complete(
# Fallback: Direct aiohttp call
if not content and base_url:
- url = base_url.rstrip("/")
- if not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- if api_version:
- if "?" not in url:
- url += f"?api-version={api_version}"
- else:
- url += f"&api-version={api_version}"
-
- headers = {"Content-Type": "application/json"}
- if api_key:
- if api_version:
- headers["api-key"] = api_key
- else:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build URL using unified utility (use binding for Azure detection)
+ url = build_chat_url(base_url, api_version, binding)
+
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key, binding)
data = {
"model": model,
@@ -184,10 +183,13 @@ async def _openai_complete(
{"role": "user", "content": prompt},
],
"temperature": kwargs.get("temperature", 0.7),
- "max_tokens": kwargs.get("max_tokens", 4096),
}
- # Include response_format if present in kwargs (for non-DeepSeek models)
+ # Handle max_tokens / max_completion_tokens based on model
+ max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens") or 4096
+ data.update(get_token_limit_kwargs(model, max_tokens))
+
+ # Include response_format if present in kwargs
if "response_format" in kwargs:
data["response_format"] = kwargs["response_format"]
@@ -198,27 +200,21 @@ async def _openai_complete(
result = await resp.json()
if "choices" in result and result["choices"]:
msg = result["choices"][0].get("message", {})
- content = msg.get("content", "")
- if not content:
- content = (
- msg.get("reasoning_content")
- or msg.get("reasoning")
- or msg.get("thought")
- or ""
- )
+ # Use unified response extraction
+ content = extract_response_content(msg)
else:
error_text = await resp.text()
- raise Exception(f"OpenAI API error: {resp.status} - {error_text}")
+ raise LLMAPIError(
+ f"OpenAI API error: {error_text}",
+ status_code=resp.status,
+ provider=binding or "openai",
+ )
if content is not None:
- # 2. CONTENT-SPECIFIC: Handle Reasoning Tags (Generic/Safe)
- # We apply this to ANY model output. If the tag isn't there,
- # this block is skipped instantly (safe for OpenAI).
- if content and "<think>" in content:
- content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL).strip()
- return content
+ # Clean thinking tags from response using unified utility
+ return clean_thinking_tags(content, binding, model)
- raise Exception("Cloud completion failed: no valid configuration")
+ raise LLMConfigError("Cloud completion failed: no valid configuration")
async def _openai_stream(
@@ -228,6 +224,7 @@ async def _openai_stream(
api_key: Optional[str],
base_url: Optional[str],
api_version: Optional[str] = None,
+ binding: str = "openai",
messages: Optional[List[Dict[str, str]]] = None,
**kwargs,
) -> AsyncGenerator[str, None]:
@@ -238,28 +235,16 @@ async def _openai_stream(
if base_url:
base_url = sanitize_url(base_url, model)
- # 1. MODEL-SPECIFIC: Handle API Parameter Compatibility
- if model and "deepseek" in model.lower():
+ # Handle API Parameter Compatibility using capabilities
+ if not supports_response_format(binding, model):
kwargs.pop("response_format", None)
- url = (base_url or "https://api.openai.com/v1").rstrip("/")
- if api_version:
- if not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- if "?" not in url:
- url += f"?api-version={api_version}"
- else:
- url += f"&api-version={api_version}"
- elif not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- headers = {"Content-Type": "application/json"}
- if api_key:
- if api_version:
- headers["api-key"] = api_key
- else:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build URL using unified utility
+ effective_base = base_url or "https://api.openai.com/v1"
+ url = build_chat_url(effective_base, api_version, binding)
+
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key, binding)
# Build messages
if messages:
@@ -276,10 +261,13 @@ async def _openai_stream(
"temperature": kwargs.get("temperature", 0.7),
"stream": True,
}
- if kwargs.get("max_tokens"):
- data["max_tokens"] = kwargs["max_tokens"]
- # Include response_format if present in kwargs (for non-DeepSeek models)
+ # Handle max_tokens / max_completion_tokens based on model
+ max_tokens = kwargs.get("max_tokens") or kwargs.get("max_completion_tokens")
+ if max_tokens:
+ data.update(get_token_limit_kwargs(model, max_tokens))
+
+ # Include response_format if present in kwargs
if "response_format" in kwargs:
data["response_format"] = kwargs["response_format"]
@@ -288,7 +276,15 @@ async def _openai_stream(
async with session.post(url, headers=headers, json=data) as resp:
if resp.status != 200:
error_text = await resp.text()
- raise Exception(f"OpenAI stream error: {resp.status} - {error_text}")
+ raise LLMAPIError(
+ f"OpenAI stream error: {error_text}",
+ status_code=resp.status,
+ provider=binding or "openai",
+ )
+
+ # Track thinking block state for streaming
+ in_thinking_block = False
+ thinking_buffer = ""
async for line in resp.content:
line_str = line.decode("utf-8").strip()
@@ -305,7 +301,23 @@ async def _openai_stream(
delta = chunk_data["choices"][0].get("delta", {})
content = delta.get("content")
if content:
- yield content
+ # Handle thinking tags in streaming
+ if "<think>" in content:
+ in_thinking_block = True
+ thinking_buffer = content
+ continue
+ elif in_thinking_block:
+ thinking_buffer += content
+ if "</think>" in thinking_buffer:
+ # End of thinking block, clean and yield
+ cleaned = clean_thinking_tags(thinking_buffer, binding, model)
+ if cleaned:
+ yield cleaned
+ in_thinking_block = False
+ thinking_buffer = ""
+ continue
+ else:
+ yield content
except json.JSONDecodeError:
continue
@@ -316,30 +328,37 @@ async def _anthropic_complete(
system_prompt: str,
api_key: Optional[str],
base_url: Optional[str],
+ messages: Optional[List[Dict[str, str]]] = None,
**kwargs,
) -> str:
"""Anthropic (Claude) API completion."""
api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not api_key:
- raise ValueError("Anthropic API key is missing.")
+ raise LLMAuthenticationError("Anthropic API key is missing.", provider="anthropic")
+
+ # Build URL using unified utility
+ effective_base = base_url or "https://api.anthropic.com/v1"
+ url = build_chat_url(effective_base, binding="anthropic")
- if not base_url:
- url = "https://api.anthropic.com/v1/messages"
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key, binding="anthropic")
+
+ # Build messages - handle pre-built messages array
+ if messages:
+ # Filter out system messages for Anthropic (system is a separate parameter)
+ msg_list = [m for m in messages if m.get("role") != "system"]
+ system_content = next(
+ (m["content"] for m in messages if m.get("role") == "system"),
+ system_prompt,
+ )
else:
- url = base_url.rstrip("/")
- if not url.endswith("/messages"):
- url += "/messages"
-
- headers = {
- "x-api-key": api_key,
- "anthropic-version": "2023-06-01",
- "content-type": "application/json",
- }
+ msg_list = [{"role": "user", "content": prompt}]
+ system_content = system_prompt
data = {
"model": model,
- "system": system_prompt,
- "messages": [{"role": "user", "content": prompt}],
+ "system": system_content,
+ "messages": msg_list,
"max_tokens": kwargs.get("max_tokens", 4096),
"temperature": kwargs.get("temperature", 0.7),
}
@@ -349,7 +368,11 @@ async def _anthropic_complete(
async with session.post(url, headers=headers, json=data) as response:
if response.status != 200:
error_text = await response.text()
- raise Exception(f"Anthropic API error: {response.status} - {error_text}")
+ raise LLMAPIError(
+ f"Anthropic API error: {error_text}",
+ status_code=response.status,
+ provider="anthropic",
+ )
result = await response.json()
return result["content"][0]["text"]
@@ -369,20 +392,14 @@ async def _anthropic_stream(
api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not api_key:
- raise ValueError("Anthropic API key is missing.")
+ raise LLMAuthenticationError("Anthropic API key is missing.", provider="anthropic")
- if not base_url:
- url = "https://api.anthropic.com/v1/messages"
- else:
- url = base_url.rstrip("/")
- if not url.endswith("/messages"):
- url += "/messages"
-
- headers = {
- "x-api-key": api_key,
- "anthropic-version": "2023-06-01",
- "content-type": "application/json",
- }
+ # Build URL using unified utility
+ effective_base = base_url or "https://api.anthropic.com/v1"
+ url = build_chat_url(effective_base, binding="anthropic")
+
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key, binding="anthropic")
# Build messages
if messages:
@@ -410,7 +427,11 @@ async def _anthropic_stream(
async with session.post(url, headers=headers, json=data) as response:
if response.status != 200:
error_text = await response.text()
- raise Exception(f"Anthropic stream error: {response.status} - {error_text}")
+ raise LLMAPIError(
+ f"Anthropic stream error: {error_text}",
+ status_code=response.status,
+ provider="anthropic",
+ )
async for line in response.content:
line_str = line.decode("utf-8").strip()
@@ -452,13 +473,10 @@ async def fetch_models(
binding = binding.lower()
base_url = base_url.rstrip("/")
- headers = {}
- if api_key:
- if binding in ["anthropic", "claude"]:
- headers["x-api-key"] = api_key
- headers["anthropic-version"] = "2023-06-01"
- else:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key, binding)
+ # Remove Content-Type for GET request
+ headers.pop("Content-Type", None)
timeout = aiohttp.ClientTimeout(total=30)
async with aiohttp.ClientSession(timeout=timeout) as session:
diff --git a/src/services/llm/config.py b/src/services/llm/config.py
index f550ce03c..b15a883aa 100644
--- a/src/services/llm/config.py
+++ b/src/services/llm/config.py
@@ -19,6 +19,8 @@ from typing import Literal, Optional
from dotenv import load_dotenv
+from .exceptions import LLMConfigError
+
# Load environment variables
PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
@@ -51,9 +53,11 @@ def _strip_value(value: Optional[str]) -> Optional[str]:
return value.strip().strip("\"'")
-def get_llm_mode() -> str:
+def _get_llm_mode_str() -> str:
"""
- Get the current LLM deployment mode from environment.
+ Get the current LLM deployment mode from environment (internal use).
+
+ For external use, import get_llm_mode from factory.py which returns LLMMode enum.
Returns:
str: 'api', 'local', or 'hybrid' (default)
@@ -80,7 +84,7 @@ def get_llm_config() -> LLMConfig:
Raises:
ValueError: If required configuration is missing
"""
- mode = get_llm_mode()
+ mode = _get_llm_mode_str()
# 1. Try to get active provider from provider manager
try:
@@ -121,8 +125,8 @@ def get_llm_config() -> LLMConfig:
# Validate required configuration
if not model:
- raise ValueError(
- "Error: LLM_MODEL not set, please configure it in .env file or activate a provider"
+ raise LLMConfigError(
+ "LLM_MODEL not set, please configure it in .env file or activate a provider"
)
# Determine provider type from base_url
@@ -136,12 +140,12 @@ def get_llm_config() -> LLMConfig:
)
if requires_key and not api_key:
- raise ValueError(
- "Error: LLM_API_KEY not set, please configure it in .env file or activate a provider"
+ raise LLMConfigError(
+ "LLM_API_KEY not set, please configure it in .env file or activate a provider"
)
if not base_url:
- raise ValueError(
- "Error: LLM_HOST not set, please configure it in .env file or activate a provider"
+ raise LLMConfigError(
+ "LLM_HOST not set, please configure it in .env file or activate a provider"
)
return LLMConfig(
@@ -215,7 +219,6 @@ def get_token_limit_kwargs(model: str, max_tokens: int) -> dict:
__all__ = [
"LLMConfig",
"get_llm_config",
- "get_llm_mode",
"uses_max_completion_tokens",
"get_token_limit_kwargs",
"LLM_MODE_API",
diff --git a/src/services/llm/exceptions.py b/src/services/llm/exceptions.py
new file mode 100644
index 000000000..9f2196ea9
--- /dev/null
+++ b/src/services/llm/exceptions.py
@@ -0,0 +1,165 @@
+"""
+LLM Service Exceptions
+======================
+
+Custom exception classes for the LLM service.
+Provides a consistent exception hierarchy for better error handling.
+
+Usage:
+ from src.services.llm.exceptions import LLMError, LLMConfigError, LLMAPIError
+
+ try:
+ response = await complete(...)
+ except LLMConfigError as e:
+ # Handle configuration errors (missing API key, etc.)
+ logger.error(f"Configuration error: {e}")
+ except LLMAPIError as e:
+ # Handle API errors (rate limits, invalid requests, etc.)
+ logger.error(f"API error: {e.status_code} - {e.message}")
+ except LLMError as e:
+ # Handle all other LLM-related errors
+ logger.error(f"LLM error: {e}")
+"""
+
+from typing import Optional
+
+
+class LLMError(Exception):
+ """Base exception for all LLM-related errors."""
+
+ def __init__(self, message: str, details: Optional[dict] = None):
+ super().__init__(message)
+ self.message = message
+ self.details = details or {}
+
+ def __str__(self) -> str:
+ if self.details:
+ return f"{self.message} (details: {self.details})"
+ return self.message
+
+
+class LLMConfigError(LLMError):
+ """
+ Raised when there's an error in LLM configuration.
+
+ Examples:
+ - Missing API key
+ - Missing model name
+ - Invalid base URL
+ - Missing required environment variables
+ """
+
+ pass
+
+
+class LLMProviderError(LLMError):
+ """
+ Raised when there's an error with the LLM provider.
+
+ Examples:
+ - Provider not found
+ - Provider not configured
+ - Provider activation failed
+ """
+
+ pass
+
+
+class LLMAPIError(LLMError):
+ """
+ Raised when an API call to an LLM provider fails.
+
+ Attributes:
+ status_code: HTTP status code from the API (if available)
+ provider: Name of the provider that returned the error
+ """
+
+ def __init__(
+ self,
+ message: str,
+ status_code: Optional[int] = None,
+ provider: Optional[str] = None,
+ details: Optional[dict] = None,
+ ):
+ super().__init__(message, details)
+ self.status_code = status_code
+ self.provider = provider
+
+ def __str__(self) -> str:
+ parts = []
+ if self.provider:
+ parts.append(f"[{self.provider}]")
+ if self.status_code:
+ parts.append(f"HTTP {self.status_code}")
+ parts.append(self.message)
+ return " ".join(parts)
+
+
+class LLMTimeoutError(LLMAPIError):
+ """
+ Raised when an API call times out.
+ """
+
+ def __init__(
+ self,
+ message: str = "Request timed out",
+ timeout: Optional[float] = None,
+ provider: Optional[str] = None,
+ ):
+ super().__init__(message, status_code=408, provider=provider)
+ self.timeout = timeout
+
+
+class LLMRateLimitError(LLMAPIError):
+ """
+ Raised when rate limited by the API.
+ """
+
+ def __init__(
+ self,
+ message: str = "Rate limit exceeded",
+ retry_after: Optional[float] = None,
+ provider: Optional[str] = None,
+ ):
+ super().__init__(message, status_code=429, provider=provider)
+ self.retry_after = retry_after
+
+
+class LLMAuthenticationError(LLMAPIError):
+ """
+ Raised when authentication fails (invalid API key, etc.).
+ """
+
+ def __init__(
+ self,
+ message: str = "Authentication failed",
+ provider: Optional[str] = None,
+ ):
+ super().__init__(message, status_code=401, provider=provider)
+
+
+class LLMModelNotFoundError(LLMAPIError):
+ """
+ Raised when the requested model is not found or not available.
+ """
+
+ def __init__(
+ self,
+ message: str = "Model not found",
+ model: Optional[str] = None,
+ provider: Optional[str] = None,
+ ):
+ super().__init__(message, status_code=404, provider=provider)
+ self.model = model
+
+
+__all__ = [
+ "LLMError",
+ "LLMConfigError",
+ "LLMProviderError",
+ "LLMAPIError",
+ "LLMTimeoutError",
+ "LLMRateLimitError",
+ "LLMAuthenticationError",
+ "LLMModelNotFoundError",
+]
diff --git a/src/services/llm/factory.py b/src/services/llm/factory.py
index 23c5ad599..002c97f73 100644
--- a/src/services/llm/factory.py
+++ b/src/services/llm/factory.py
@@ -23,19 +23,133 @@ OpenAI/DeepSeek/etc LM Studio/Ollama/etc
Deployment Modes (LLM_MODE env var):
- api: Only use cloud API providers
- local: Only use local/self-hosted LLM servers
-- hybrid: Use whatever is active (default)0
+- hybrid: Use whatever is active (default)
+
+Retry Mechanism:
+- Automatic retry with exponential backoff for transient errors
+- Configurable max_retries, retry_delay, and exponential_backoff
+- Only retries on retriable errors (timeout, rate limit, server errors)
"""
+import asyncio
from enum import Enum
import os
from typing import Any, AsyncGenerator, Dict, List, Optional
from . import cloud_provider, local_provider
from .config import LLMConfig, get_llm_config
+from .exceptions import (
+ LLMAPIError,
+ LLMAuthenticationError,
+ LLMRateLimitError,
+ LLMTimeoutError,
+)
from .provider import provider_manager
from .utils import is_local_llm_server
+# Default retry configuration
+DEFAULT_MAX_RETRIES = 3
+DEFAULT_RETRY_DELAY = 1.0 # seconds
+DEFAULT_EXPONENTIAL_BACKOFF = True
+
+
+def _is_retriable_error(error: Exception) -> bool:
+ """
+ Check if an error is retriable.
+
+ Retriable errors:
+ - Timeout errors
+ - Rate limit errors (429)
+ - Server errors (5xx)
+
+ Non-retriable errors:
+ - Authentication errors (401)
+ - Bad request (400)
+ - Not found (404)
+
+ Args:
+ error: The exception to check
+
+ Returns:
+ True if the error is retriable
+ """
+ if isinstance(error, LLMTimeoutError):
+ return True
+ if isinstance(error, LLMRateLimitError):
+ return True
+ if isinstance(error, LLMAuthenticationError):
+ return False # Don't retry auth errors
+
+ if isinstance(error, LLMAPIError):
+ status_code = error.status_code
+ if status_code:
+ # Retry on server errors (5xx) and rate limits (429)
+ if status_code >= 500 or status_code == 429:
+ return True
+ # Don't retry on client errors (4xx except 429)
+ if 400 <= status_code < 500:
+ return False
+ return True # Retry by default for unknown API errors
+
+ # For other exceptions (network errors, etc.), retry
+ return True
+
+
+async def _execute_with_retry(
+ func,
+ max_retries: int = DEFAULT_MAX_RETRIES,
+ retry_delay: float = DEFAULT_RETRY_DELAY,
+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,
+ **kwargs,
+):
+ """
+ Execute a function with retry logic.
+
+ Args:
+ func: Async function to execute
+ max_retries: Maximum number of retry attempts
+ retry_delay: Initial delay between retries (seconds)
+ exponential_backoff: Whether to use exponential backoff
+ **kwargs: Arguments to pass to the function
+
+ Returns:
+ Result from the function
+
+ Raises:
+ The last exception if all retries fail
+ """
+ last_exception = None
+ delay = retry_delay
+
+ for attempt in range(max_retries + 1):
+ try:
+ return await func(**kwargs)
+ except Exception as e:
+ last_exception = e
+
+ # Check if we should retry
+ if attempt >= max_retries or not _is_retriable_error(e):
+ raise
+
+ # Calculate delay for next attempt
+ if exponential_backoff:
+ current_delay = delay * (2**attempt)
+ else:
+ current_delay = delay
+
+ # Special handling for rate limit errors with retry_after
+ if isinstance(e, LLMRateLimitError) and e.retry_after:
+ current_delay = max(current_delay, e.retry_after)
+
+ # Wait before retrying
+ await asyncio.sleep(current_delay)
+
+ # Should not reach here, but just in case
+ if last_exception:
+ raise last_exception
+
+
class LLMMode(str, Enum):
"""LLM deployment mode."""
@@ -59,46 +173,6 @@ def get_llm_mode() -> LLMMode:
return LLMMode.HYBRID
-def get_effective_config() -> LLMConfig:
- """
- Get the effective LLM configuration based on deployment mode.
-
- For hybrid mode: Use active provider if available, else env config
- For api mode: Use active API provider or env config
- For local mode: Use active local provider or env config
-
- Returns:
- LLMConfig: The effective configuration to use
- """
- mode = get_llm_mode()
- active_provider = provider_manager.get_active_provider()
- env_config = get_llm_config()
-
- # If we have an active provider, check if it matches the mode
- if active_provider:
- provider_is_local = active_provider.provider_type == "local"
-
- # Check mode compatibility
- if mode == LLMMode.API and provider_is_local:
- # In API mode but active provider is local - use env config
- return env_config
- elif mode == LLMMode.LOCAL and not provider_is_local:
- # In local mode but active provider is API - use env config
- return env_config
- else:
- # Mode matches or hybrid mode - use active provider
- return LLMConfig(
- model=active_provider.model,
- api_key=active_provider.api_key,
- base_url=active_provider.base_url,
- api_version=getattr(active_provider, "api_version", None),
- binding=active_provider.binding,
- )
-
- # No active provider - use env config
- return env_config
-
-
def _should_use_local(base_url: Optional[str]) -> bool:
"""
Determine if we should use the local provider based on URL and mode.
@@ -132,9 +206,13 @@ def get_mode_info() -> Dict[str, Any]:
"""
mode = get_llm_mode()
active_provider = provider_manager.get_active_provider()
- env_config = get_llm_config()
-
- env_configured = bool(env_config.model and (env_config.base_url or env_config.api_key))
+
+ try:
+ env_config = get_llm_config()
+ env_configured = bool(env_config.model and (env_config.base_url or env_config.api_key))
+ except ValueError:
+ env_config = None
+ env_configured = False
# Determine effective source
effective_source = "env"
@@ -173,12 +251,16 @@ async def complete(
api_version: Optional[str] = None,
binding: Optional[str] = None,
messages: Optional[List[Dict[str, str]]] = None,
+ max_retries: int = DEFAULT_MAX_RETRIES,
+ retry_delay: float = DEFAULT_RETRY_DELAY,
+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,
**kwargs,
) -> str:
"""
- Unified LLM completion function.
+ Unified LLM completion function with automatic retry.
Routes to cloud_provider or local_provider based on configuration.
+ Includes automatic retry with exponential backoff for transient errors.
Args:
prompt: The user prompt
@@ -189,42 +271,57 @@ async def complete(
api_version: API version for Azure OpenAI (optional)
binding: Provider binding type (optional)
messages: Pre-built messages array (optional)
+ max_retries: Maximum number of retry attempts (default: 3)
+ retry_delay: Initial delay between retries in seconds (default: 1.0)
+ exponential_backoff: Whether to use exponential backoff (default: True)
**kwargs: Additional parameters (temperature, max_tokens, etc.)
Returns:
str: The LLM response
"""
- # Get effective config if parameters not provided
+ # Get config if parameters not provided
if not model or not base_url:
- config = get_effective_config()
+ config = get_llm_config()
model = model or config.model
api_key = api_key if api_key is not None else config.api_key
base_url = base_url or config.base_url
api_version = api_version or config.api_version
binding = binding or config.binding or "openai"
- # Route to appropriate provider
- if _should_use_local(base_url):
- return await local_provider.complete(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- messages=messages,
- **kwargs,
- )
- else:
- return await cloud_provider.complete(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- binding=binding or "openai",
- **kwargs,
- )
+ # Determine which provider to use
+ use_local = _should_use_local(base_url)
+
+ # Define the actual completion function
+ async def _do_complete(**call_kwargs):
+ if use_local:
+ return await local_provider.complete(**call_kwargs)
+ else:
+ return await cloud_provider.complete(**call_kwargs)
+
+ # Build call kwargs
+ call_kwargs = {
+ "prompt": prompt,
+ "system_prompt": system_prompt,
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ "messages": messages,
+ **kwargs,
+ }
+
+ # Add cloud-specific kwargs if not local
+ if not use_local:
+ call_kwargs["api_version"] = api_version
+ call_kwargs["binding"] = binding or "openai"
+
+ # Execute with retry
+ return await _execute_with_retry(
+ _do_complete,
+ max_retries=max_retries,
+ retry_delay=retry_delay,
+ exponential_backoff=exponential_backoff,
+ **call_kwargs,
+ )
async def stream(
@@ -236,12 +333,19 @@ async def stream(
api_version: Optional[str] = None,
binding: Optional[str] = None,
messages: Optional[List[Dict[str, str]]] = None,
+ max_retries: int = DEFAULT_MAX_RETRIES,
+ retry_delay: float = DEFAULT_RETRY_DELAY,
+ exponential_backoff: bool = DEFAULT_EXPONENTIAL_BACKOFF,
**kwargs,
) -> AsyncGenerator[str, None]:
"""
- Unified LLM streaming function.
+ Unified LLM streaming function with automatic retry.
Routes to cloud_provider or local_provider based on configuration.
+ Includes automatic retry with exponential backoff for connection errors.
+
+ Note: Retry only applies to initial connection errors. Once streaming
+ starts, errors during streaming will not be automatically retried.
Args:
prompt: The user prompt
@@ -252,45 +356,80 @@ async def stream(
api_version: API version for Azure OpenAI (optional)
binding: Provider binding type (optional)
messages: Pre-built messages array (optional)
+ max_retries: Maximum number of retry attempts (default: 3)
+ retry_delay: Initial delay between retries in seconds (default: 1.0)
+ exponential_backoff: Whether to use exponential backoff (default: True)
**kwargs: Additional parameters (temperature, max_tokens, etc.)
Yields:
str: Response chunks
"""
- # Get effective config if parameters not provided
+ # Get config if parameters not provided
if not model or not base_url:
- config = get_effective_config()
+ config = get_llm_config()
model = model or config.model
api_key = api_key if api_key is not None else config.api_key
base_url = base_url or config.base_url
api_version = api_version or config.api_version
binding = binding or config.binding or "openai"
- # Route to appropriate provider
- if _should_use_local(base_url):
- async for chunk in local_provider.stream(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- messages=messages,
- **kwargs,
- ):
- yield chunk
- else:
- async for chunk in cloud_provider.stream(
- prompt=prompt,
- system_prompt=system_prompt,
- model=model,
- api_key=api_key,
- base_url=base_url,
- api_version=api_version,
- binding=binding or "openai",
- messages=messages,
- **kwargs,
- ):
- yield chunk
+ # Determine which provider to use
+ use_local = _should_use_local(base_url)
+
+ # Build call kwargs
+ call_kwargs = {
+ "prompt": prompt,
+ "system_prompt": system_prompt,
+ "model": model,
+ "api_key": api_key,
+ "base_url": base_url,
+ "messages": messages,
+ **kwargs,
+ }
+
+ # Add cloud-specific kwargs if not local
+ if not use_local:
+ call_kwargs["api_version"] = api_version
+ call_kwargs["binding"] = binding or "openai"
+
+ # Retry logic for streaming (retry on connection errors)
+ last_exception = None
+ delay = retry_delay
+
+ for attempt in range(max_retries + 1):
+ try:
+ # Route to appropriate provider
+ if use_local:
+ async for chunk in local_provider.stream(**call_kwargs):
+ yield chunk
+ else:
+ async for chunk in cloud_provider.stream(**call_kwargs):
+ yield chunk
+ # If we get here, streaming completed successfully
+ return
+ except Exception as e:
+ last_exception = e
+
+ # Check if we should retry
+ if attempt >= max_retries or not _is_retriable_error(e):
+ raise
+
+ # Calculate delay for next attempt
+ if exponential_backoff:
+ current_delay = delay * (2**attempt)
+ else:
+ current_delay = delay
+
+ # Special handling for rate limit errors with retry_after
+ if isinstance(e, LLMRateLimitError) and e.retry_after:
+ current_delay = max(current_delay, e.retry_after)
+
+ # Wait before retrying
+ await asyncio.sleep(current_delay)
+
+ # Should not reach here, but just in case
+ if last_exception:
+ raise last_exception
async def fetch_models(
@@ -388,7 +527,6 @@ def get_provider_presets() -> Dict[str, Any]:
__all__ = [
"LLMMode",
"get_llm_mode",
- "get_effective_config",
"get_mode_info",
"complete",
"stream",
@@ -396,4 +534,8 @@ __all__ = [
"get_provider_presets",
"API_PROVIDER_PRESETS",
"LOCAL_PROVIDER_PRESETS",
+ # Retry configuration defaults
+ "DEFAULT_MAX_RETRIES",
+ "DEFAULT_RETRY_DELAY",
+ "DEFAULT_EXPONENTIAL_BACKOFF",
]
diff --git a/src/services/llm/local_provider.py b/src/services/llm/local_provider.py
index f8b6cea06..43147245d 100644
--- a/src/services/llm/local_provider.py
+++ b/src/services/llm/local_provider.py
@@ -12,40 +12,23 @@ Key features:
"""
import json
-import re
from typing import AsyncGenerator, Dict, List, Optional
import aiohttp
-from .utils import sanitize_url
+from .exceptions import LLMAPIError, LLMConfigError
+from .utils import (
+ build_auth_headers,
+ build_chat_url,
+ clean_thinking_tags,
+ extract_response_content,
+ sanitize_url,
+)
# Extended timeout for local servers (may be slower than cloud)
DEFAULT_TIMEOUT = 300 # 5 minutes
-def _clean_thinking_tags(content: str) -> str:
- """
- Remove thinking tags from model output.
-
- Some reasoning models (Qwen, etc.) include <think>...</think> blocks
- that should be stripped from the final response.
-
- Args:
- content: Raw model output
-
- Returns:
- Cleaned content without thinking tags
- """
- if not content:
- return content
-
- # Remove <think>...</think> blocks
- if "<think>" in content and "</think>" in content:
- content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)
-
- return content.strip()
-
-
async def complete(
prompt: str,
system_prompt: str = "You are a helpful assistant.",
@@ -73,19 +56,14 @@ async def complete(
str: The LLM response
"""
if not base_url:
- raise ValueError("base_url is required for local LLM provider")
+ raise LLMConfigError("base_url is required for local LLM provider")
- # Sanitize URL
+ # Sanitize URL and build chat endpoint
base_url = sanitize_url(base_url, model or "")
+ url = build_chat_url(base_url)
- url = base_url.rstrip("/")
- if not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- # Build headers
- headers = {"Content-Type": "application/json"}
- if api_key:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key)
# Build messages
if messages:
@@ -114,25 +92,20 @@ async def complete(
async with session.post(url, json=data, headers=headers) as response:
if response.status != 200:
error_text = await response.text()
- raise Exception(f"Local LLM error: {response.status} - {error_text}")
+ raise LLMAPIError(
+ f"Local LLM error: {error_text}",
+ status_code=response.status,
+ provider="local",
+ )
result = await response.json()
if "choices" in result and result["choices"]:
msg = result["choices"][0].get("message", {})
- content = msg.get("content", "")
-
- # Handle reasoning models that return content in different fields
- if not content:
- content = (
- msg.get("reasoning_content")
- or msg.get("reasoning")
- or msg.get("thought")
- or ""
- )
-
- # Clean thinking tags
- content = _clean_thinking_tags(content)
+ # Use unified response extraction
+ content = extract_response_content(msg)
+ # Clean thinking tags using unified utility
+ content = clean_thinking_tags(content)
return content
return ""
@@ -166,19 +139,14 @@ async def stream(
str: Response chunks
"""
if not base_url:
- raise ValueError("base_url is required for local LLM provider")
+ raise LLMConfigError("base_url is required for local LLM provider")
- # Sanitize URL
+ # Sanitize URL and build chat endpoint
base_url = sanitize_url(base_url, model or "")
+ url = build_chat_url(base_url)
- url = base_url.rstrip("/")
- if not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- # Build headers
- headers = {"Content-Type": "application/json"}
- if api_key:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key)
# Build messages
if messages:
@@ -206,9 +174,12 @@ async def stream(
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.post(url, json=data, headers=headers) as response:
if response.status != 200:
- # Streaming failed, fall back to non-streaming
error_text = await response.text()
- raise Exception(f"Streaming error: {response.status} - {error_text}")
+ raise LLMAPIError(
+ f"Local LLM stream error: {error_text}",
+ status_code=response.status,
+ provider="local",
+ )
# Track if we're inside a thinking block
in_thinking_block = False
@@ -236,7 +207,6 @@ async def stream(
if content:
# Handle thinking tags in streaming
- # Buffer content that might be in a thinking block
if "<think>" in content:
in_thinking_block = True
thinking_buffer = content
@@ -245,7 +215,7 @@ async def stream(
thinking_buffer += content
if "</think>" in thinking_buffer:
# End of thinking block, clean and yield
- cleaned = _clean_thinking_tags(thinking_buffer)
+ cleaned = clean_thinking_tags(thinking_buffer)
if cleaned:
yield cleaned
in_thinking_block = False
@@ -271,6 +241,8 @@ async def stream(
except json.JSONDecodeError:
pass
+ except LLMAPIError:
+ raise # Re-raise LLM errors as-is
except Exception as e:
# Streaming failed, fall back to non-streaming
print(f"⚠️ Streaming failed ({e}), falling back to non-streaming")
@@ -288,7 +260,10 @@ async def stream(
if content:
yield content
except Exception as e2:
- raise Exception(f"Local LLM failed: streaming={e}, non-streaming={e2}")
+ raise LLMAPIError(
+ f"Local LLM failed: streaming={e}, non-streaming={e2}",
+ provider="local",
+ )
async def fetch_models(
@@ -311,9 +286,10 @@ async def fetch_models(
"""
base_url = base_url.rstrip("/")
- headers = {}
- if api_key:
- headers["Authorization"] = f"Bearer {api_key}"
+ # Build headers using unified utility
+ headers = build_auth_headers(api_key)
+ # Remove Content-Type for GET request
+ headers.pop("Content-Type", None)
timeout = aiohttp.ClientTimeout(total=30)
diff --git a/src/services/llm/utils.py b/src/services/llm/utils.py
index 0d828bd62..52da888b5 100644
--- a/src/services/llm/utils.py
+++ b/src/services/llm/utils.py
@@ -1,10 +1,133 @@
"""
-LLM URL Utilities
-=================
+LLM Utilities
+=============
-Utility functions for handling LLM API URLs, especially for local servers.
+Utility functions for LLM service:
+- URL handling for local and cloud servers
+- Response content extraction
+- Thinking tags cleaning
"""
+import re
+from typing import Any, Optional
+
+# Known cloud provider domains (should never be treated as local)
+CLOUD_DOMAINS = [
+ ".openai.com",
+ ".anthropic.com",
+ ".deepseek.com",
+ ".openrouter.ai",
+ ".azure.com",
+ ".googleapis.com",
+ ".cohere.ai",
+ ".mistral.ai",
+ ".together.ai",
+ ".fireworks.ai",
+ ".groq.com",
+ ".perplexity.ai",
+]
+
+# Common local server ports
+LOCAL_PORTS = [
+ ":1234", # LM Studio
+ ":11434", # Ollama
+ ":8000", # vLLM
+ ":8080", # llama.cpp
+ ":5000", # Common dev port
+ ":3000", # Common dev port
+ ":8001", # Alternative vLLM
+ ":5001", # Alternative dev port
+]
+
+# Local hostname indicators
+LOCAL_HOSTS = [
+ "localhost",
+ "127.0.0.1",
+ "0.0.0.0",
+]
+
+# Ports that need /v1 suffix for OpenAI compatibility
+V1_SUFFIX_PORTS = {
+ ":11434", # Ollama
+ ":1234", # LM Studio
+ ":8000", # vLLM
+ ":8001", # Alternative vLLM
+ ":8080", # llama.cpp
+}
+
+
+def is_local_llm_server(base_url: str) -> bool:
+ """
+ Check if the given URL points to a local LLM server.
+
+ Detects local servers by:
+ 1. Checking for local hostnames (localhost, 127.0.0.1, 0.0.0.0)
+ 2. Checking for common local LLM server ports
+ 3. Excluding known cloud provider domains
+
+ Args:
+ base_url: The base URL to check
+
+ Returns:
+ True if the URL appears to be a local LLM server
+ """
+ if not base_url:
+ return False
+
+ base_url_lower = base_url.lower()
+
+ # First, exclude known cloud providers
+ for domain in CLOUD_DOMAINS:
+ if domain in base_url_lower:
+ return False
+
+ # Check for local hostname indicators
+ for host in LOCAL_HOSTS:
+ if host in base_url_lower:
+ return True
+
+ # Check for common local server ports
+ for port in LOCAL_PORTS:
+ if port in base_url_lower:
+ return True
+
+ return False
+
+
+def _needs_v1_suffix(url: str) -> bool:
+ """
+ Check if the URL needs /v1 suffix for OpenAI compatibility.
+
+ Most local LLM servers (Ollama, LM Studio, vLLM, llama.cpp) expose
+ OpenAI-compatible endpoints at /v1.
+
+ Args:
+ url: The URL to check
+
+ Returns:
+ True if /v1 should be appended
+ """
+ if not url:
+ return False
+
+ url_lower = url.lower()
+
+ # Skip if already has /v1
+ if url_lower.endswith("/v1"):
+ return False
+
+ # Only add /v1 for local servers with known ports that need it
+ if not is_local_llm_server(url):
+ return False
+
+ # Check if URL contains any port that needs /v1 suffix
+ # Also check for "ollama" in URL (but not ollama.com cloud service)
+ is_ollama = "ollama" in url_lower and "ollama.com" not in url_lower
+ if is_ollama:
+ return True
+
+ return any(port in url_lower for port in V1_SUFFIX_PORTS)
+
def sanitize_url(base_url: str, model: str = "") -> str:
"""
@@ -13,6 +136,8 @@ def sanitize_url(base_url: str, model: str = "") -> str:
Handles:
- Ollama (port 11434)
- LM Studio (port 1234)
+ - vLLM (port 8000)
+ - llama.cpp (port 8080)
- Other localhost OpenAI-compatible servers
Args:
@@ -40,39 +165,169 @@ def sanitize_url(base_url: str, model: str = "") -> str:
url = url[: -len(suffix)]
url = url.rstrip("/")
- # Special handling for local LLM servers that require /v1:
- # - Ollama (port 11434)
- # - LM Studio (port 1234)
- is_local_ollama = ":11434" in url or (
- "ollama" in url.lower() and "ollama.com" not in url.lower()
- )
- is_lm_studio = ":1234" in url
-
# For local LLM servers, ensure /v1 is present for OpenAI compatibility
- if (is_local_ollama or is_lm_studio) and not url.endswith("/v1"):
+ if _needs_v1_suffix(url):
url = url.rstrip("/") + "/v1"
return url
-def is_local_llm_server(base_url: str) -> bool:
+def clean_thinking_tags(
+ content: str,
+ binding: Optional[str] = None,
+ model: Optional[str] = None,
+) -> str:
"""
- Check if the given URL points to a local LLM server.
+ Remove thinking tags from model output.
+
+ Some reasoning models (DeepSeek, Qwen, etc.) include <think>...</think> blocks
+ that should be stripped from the final response.
Args:
- base_url: The base URL to check
+ content: Raw model output
+ binding: Provider binding name (optional, for capability check)
+ model: Model name (optional, for capability check)
Returns:
- True if the URL appears to be a local LLM server
+ Cleaned content without thinking tags
+ """
+ if not content:
+ return content
+
+ # Check if model produces thinking tags (if binding/model provided)
+ if binding:
+ # Lazy import to avoid circular dependency
+ from .capabilities import has_thinking_tags
+
+ if not has_thinking_tags(binding, model):
+ return content
+
+ # Remove <think>...</think> blocks
+ if "<think>" in content:
+ content = re.sub(r"<think>.*?</think>", "", content, flags=re.DOTALL)
+
+ return content.strip()
+
+
+def build_chat_url(
+ base_url: str,
+ api_version: Optional[str] = None,
+ binding: Optional[str] = None,
+) -> str:
+ """
+ Build the full chat completions endpoint URL.
+
+ Handles:
+ - Adding /chat/completions suffix for OpenAI-compatible endpoints
+ - Adding /messages suffix for Anthropic endpoints
+ - Adding api-version query parameter for Azure OpenAI
+
+ Args:
+ base_url: Base URL (should be sanitized first)
+ api_version: API version for Azure OpenAI (optional)
+ binding: Provider binding name (optional, for Anthropic detection)
+
+ Returns:
+ Full endpoint URL
"""
if not base_url:
- return False
+ return base_url
- base_url_lower = base_url.lower()
- return any(
- indicator in base_url_lower
- for indicator in ["localhost", "127.0.0.1", "0.0.0.0", ":1234", ":11434"]
- )
+ url = base_url.rstrip("/")
+
+ # Anthropic uses /messages endpoint
+ binding_lower = (binding or "").lower()
+ if binding_lower in ["anthropic", "claude"]:
+ if not url.endswith("/messages"):
+ url += "/messages"
+ else:
+ # OpenAI-compatible endpoints use /chat/completions
+ if not url.endswith("/chat/completions"):
+ url += "/chat/completions"
+
+ # Add api-version for Azure OpenAI
+ if api_version:
+ separator = "&" if "?" in url else "?"
+ url += f"{separator}api-version={api_version}"
+
+ return url
+
+
+def extract_response_content(message: dict[str, Any]) -> str:
+ """
+ Extract content from LLM response message.
+
+ Handles different response formats from various models:
+ - Standard content field
+ - Reasoning models that use reasoning_content, reasoning, or thought fields
+
+ Args:
+ message: Message dict from LLM response (e.g., choices[0].message)
+
+ Returns:
+ Extracted content string
+ """
+ if not message:
+ return ""
+
+ content = message.get("content", "")
+
+ # Handle reasoning models that return content in different fields
+ if not content:
+ content = (
+ message.get("reasoning_content")
+ or message.get("reasoning")
+ or message.get("thought")
+ or ""
+ )
+
+ return content
+
+
+def build_auth_headers(
+ api_key: Optional[str],
+ binding: Optional[str] = None,
+) -> dict[str, str]:
+ """
+ Build authentication headers for LLM API requests.
+
+ Args:
+ api_key: API key
+ binding: Provider binding name (for provider-specific headers)
+
+ Returns:
+ Headers dict
+ """
+ headers = {"Content-Type": "application/json"}
+
+ if not api_key:
+ return headers
+
+ binding_lower = (binding or "").lower()
+
+ if binding_lower in ["anthropic", "claude"]:
+ headers["x-api-key"] = api_key
+ headers["anthropic-version"] = "2023-06-01"
+ elif binding_lower == "azure_openai":
+ headers["api-key"] = api_key
+ else:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ return headers
-__all__ = ["sanitize_url", "is_local_llm_server"]
+__all__ = [
+ # URL utilities
+ "sanitize_url",
+ "is_local_llm_server",
+ "build_chat_url",
+ "build_auth_headers",
+ # Content utilities
+ "clean_thinking_tags",
+ "extract_response_content",
+ # Constants
+ "CLOUD_DOMAINS",
+ "LOCAL_PORTS",
+ "LOCAL_HOSTS",
+ "V1_SUFFIX_PORTS",
+]
diff --git a/src/tools/tex_chunker.py b/src/tools/tex_chunker.py
index 2f97bc15d..674b802fa 100644
--- a/src/tools/tex_chunker.py
+++ b/src/tools/tex_chunker.py
@@ -30,11 +30,15 @@ class TexChunker:
"""
# Read model configuration from environment variables
if model is None:
- model = os.getenv("LLM_MODEL", "gpt-4o")
+ model = os.getenv("LLM_MODEL")
try:
- self.encoder = tiktoken.encoding_for_model(model)
- except:
+ if model:
+ self.encoder = tiktoken.encoding_for_model(model)
+ else:
+ # Use cl100k_base as default encoding if no model specified
+ self.encoder = tiktoken.get_encoding("cl100k_base")
+ except Exception:
# If model not supported, use cl100k_base (GPT-4 encoding)
self.encoder = tiktoken.get_encoding("cl100k_base")
diff --git a/web/.env.local b/web/.env.local
index 8840a64d6..0b6543af3 100644
--- a/web/.env.local
+++ b/web/.env.local
@@ -3,7 +3,7 @@
# ============================================
# This file is automatically updated based on config/main.yaml
# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)
-#
+#
# To configure for remote access, set in your .env file:
# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001
# ============================================