Skip to content

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

fix: llm providers, frontend

Bingxi Zhaodf034d854b6f
diff --git a/.env.example b/.env.example
index 6678e00fb..116a41d1e 100644
--- a/.env.example
+++ b/.env.example
@@ -1,8 +1,9 @@
-# ============================================================================
+# ============================================================================
# Deep-Tutor Environment Configuration
+# ============================================================================
# Copy this file to .env and fill in your API keys and settings.
# All API keys should be kept confidential and never committed to version control.
-# You can adjust the max_token parameters in DeepTutor\config\agents.yaml.
+# You can adjust the max_token parameters in DeepTutor/config/agents.yaml.
# ============================================================================
# ============================================================================
@@ -24,23 +25,55 @@
# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001 (optional)
+# ============================================================================
+# LLM Deployment Mode Configuration
+# ============================================================================
+# Control how DeepTutor selects LLM providers.
+#
+# Options:
+# - hybrid (default): Use both API and Local providers. Active provider takes priority.
+# - api: Only use cloud API providers (OpenAI, Anthropic, DeepSeek, etc.)
+# - local: Only use local/self-hosted providers (Ollama, LM Studio, vLLM, etc.)
+#
+# In hybrid mode, you can add both API and local providers via the Settings UI,
+# and switch between them by setting one as "active".
+
+LLM_MODE=hybrid
+
# ============================================================================
# LLM (Large Language Model) Configuration
# ============================================================================
# Configure the main AI model used for reasoning, generation, and conversation.
# Supports OpenAI-compatible APIs (OpenAI, Azure OpenAI, DeepSeek, Qwen, etc.)
+# and local servers (Ollama, LM Studio, vLLM, llama.cpp).
+#
+# Note: These environment variables serve as the default/fallback configuration.
+# You can also add providers via the Settings UI, which takes priority when active.
# LLM service provider type
-# Options: openai, azure_openai, ollama, lollms
+# Options: openai, azure_openai, ollama, anthropic
LLM_BINDING=openai
# Model name for the LLM
+# Cloud examples: gpt-4o, gpt-4o-mini, deepseek-chat, claude-3-5-sonnet-20241022
+# Local examples: llama3.2, qwen2.5, mistral-nemo, deepseek-r1
LLM_MODEL=
# LLM API endpoint URL
+# Cloud examples:
+# - OpenAI: https://api.openai.com/v1
+# - DeepSeek: https://api.deepseek.com
+# - Anthropic: https://api.anthropic.com/v1
+# Local examples:
+# - Ollama: http://localhost:11434/v1
+# - LM Studio: http://localhost:1234/v1
+# - vLLM: http://localhost:8000/v1
+# - llama.cpp: http://localhost:8080/v1
LLM_HOST=
# LLM API authentication key
+# Required for cloud APIs, optional for local deployment
+# For Ollama, you can use any string (e.g., "ollama")
LLM_API_KEY=
# Disable SSL certificate verification (set 'true' for self-signed certificates)
@@ -57,28 +90,36 @@ DISABLE_SSL_VERIFY=false
EMBEDDING_BINDING=openai
# Embedding model name
-# Examples: text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002
+# Cloud examples: text-embedding-3-large, text-embedding-3-small, text-embedding-ada-002
+# Local examples (Ollama): nomic-embed-text, mxbai-embed-large
EMBEDDING_MODEL=text-embedding-3-large
# Embedding vector dimension
+# text-embedding-3-large: 3072
+# text-embedding-3-small: 1536
+# nomic-embed-text: 768
+# mxbai-embed-large: 1024
EMBEDDING_DIMENSION=3072
# Embedding API endpoint URL
+# Cloud: https://api.openai.com/v1
+# Local (Ollama): http://localhost:11434
EMBEDDING_HOST=
# Embedding API authentication key
+# Required for cloud providers, not needed for Ollama
EMBEDDING_API_KEY=
# ============================================================================
# TTS (Text-to-Speech) Configuration (Optional)
# ============================================================================
-# Configure voice synthesis for the Co-Writer(Interactive IdeaGen) narration feature.
-# Also remember to choose a voice in DeepTutor\config\main.yaml.
+# Configure voice synthesis for the Co-Writer (Interactive IdeaGen) narration feature.
+# Also remember to choose a voice in DeepTutor/config/main.yaml.
-# TTS model name
+# TTS model name (e.g., tts-1, tts-1-hd)
TTS_MODEL=
-# TTS API endpoint URL
+# TTS API endpoint URL (e.g., https://api.openai.com/v1)
TTS_URL=
# TTS API authentication key
@@ -102,7 +143,7 @@ SEARCH_PROVIDER=perplexity
PERPLEXITY_API_KEY=
# ----------------------------------------------------------------------------
-# Baidu AI Search Configuration (鐧惧害AI鎼滅储)
+# Baidu AI Search Configuration (百度AI搜索)
# ----------------------------------------------------------------------------
# Baidu API Key for intelligent search and generation
# Get your API key at: https://console.bce.baidu.com/ai_apaas/resource
diff --git a/src/agents/base_agent.py b/src/agents/base_agent.py
index ad36ebe5e..a13895f8d 100644
--- a/src/agents/base_agent.py
+++ b/src/agents/base_agent.py
@@ -18,18 +18,18 @@ import os
from pathlib import Path
import sys
import time
-from typing import Any
+from typing import Any, AsyncGenerator
# Add project root to path
_project_root = Path(__file__).parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
-from lightrag.llm.openai import openai_complete_if_cache
-
from src.logging import LLMStats, get_logger
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.prompt import get_prompt_manager
@@ -316,7 +316,10 @@ class BaseAgent(ABC):
stage: str | None = None,
) -> str:
"""
- Unified interface for calling LLM.
+ Unified interface for calling LLM (non-streaming).
+
+ Uses the LLM factory to route calls to the appropriate provider
+ (cloud or local) based on configuration.
Args:
user_prompt: User prompt
@@ -338,13 +341,8 @@ class BaseAgent(ABC):
# Record call start time
start_time = time.time()
- # Build kwargs
+ # Build kwargs for LLM factory
kwargs = {
- "model": model,
- "prompt": user_prompt,
- "system_prompt": system_prompt,
- "api_key": self.api_key,
- "base_url": self.base_url,
"temperature": temperature,
}
@@ -366,10 +364,17 @@ class BaseAgent(ABC):
metadata={"model": model, "temperature": temperature, "max_tokens": max_tokens},
)
- # Call LLM
+ # Call LLM via factory (routes to cloud or local provider)
response = None
try:
- response = await openai_complete_if_cache(**kwargs)
+ response = await llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ model=model,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ **kwargs,
+ )
except Exception as e:
self.logger.error(f"LLM call failed: {e}")
raise
@@ -401,6 +406,105 @@ class BaseAgent(ABC):
return response
+ async def stream_llm(
+ self,
+ user_prompt: str,
+ system_prompt: str,
+ messages: list[dict[str, str]] | None = None,
+ temperature: float | None = None,
+ max_tokens: int | None = None,
+ model: str | None = None,
+ stage: str | None = None,
+ ) -> AsyncGenerator[str, None]:
+ """
+ Unified interface for streaming LLM responses.
+
+ Uses the LLM factory to route calls to the appropriate provider
+ (cloud or local) based on configuration.
+
+ Args:
+ 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)
+ temperature: Temperature parameter (optional, uses config by default)
+ max_tokens: Maximum tokens (optional, uses config by default)
+ model: Model name (optional, uses config by default)
+ stage: Stage marker for logging
+
+ Yields:
+ Response chunks as strings
+ """
+ model = model or self.get_model()
+ temperature = temperature if temperature is not None else self.get_temperature()
+ max_tokens = max_tokens if max_tokens is not None else self.get_max_tokens()
+
+ # Build kwargs
+ kwargs = {
+ "temperature": temperature,
+ }
+
+ # Handle token limit for newer OpenAI models
+ if max_tokens:
+ kwargs.update(get_token_limit_kwargs(model, max_tokens))
+
+ # Log input
+ stage_label = stage or self.agent_name
+ if hasattr(self.logger, "log_llm_input"):
+ self.logger.log_llm_input(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ metadata={"model": model, "temperature": temperature, "streaming": True},
+ )
+
+ # Track start time
+ start_time = time.time()
+ full_response = ""
+
+ try:
+ # Stream via factory (routes to cloud or local provider)
+ async for chunk in llm_stream(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ model=model,
+ api_key=self.api_key,
+ base_url=self.base_url,
+ messages=messages,
+ **kwargs,
+ ):
+ full_response += chunk
+ yield chunk
+
+ # Track token usage after streaming completes
+ self._track_tokens(
+ model=model,
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response=full_response,
+ stage=stage_label,
+ )
+
+ # Log output
+ call_duration = time.time() - start_time
+ if hasattr(self.logger, "log_llm_output"):
+ self.logger.log_llm_output(
+ agent_name=self.agent_name,
+ stage=stage_label,
+ response=full_response[:200] + "..."
+ if len(full_response) > 200
+ else full_response,
+ metadata={
+ "length": len(full_response),
+ "duration": call_duration,
+ "streaming": True,
+ },
+ )
+
+ except Exception as e:
+ self.logger.error(f"LLM streaming failed: {e}")
+ raise
+
# -------------------------------------------------------------------------
# Prompt Helpers
# -------------------------------------------------------------------------
diff --git a/src/agents/chat/chat_agent.py b/src/agents/chat/chat_agent.py
index f41dc8c95..041f8f324 100644
--- a/src/agents/chat/chat_agent.py
+++ b/src/agents/chat/chat_agent.py
@@ -7,6 +7,8 @@ This agent provides:
- Token-based context truncation
- Optional RAG and Web Search augmentation
- Streaming response generation
+
+Uses the unified LLM factory from BaseAgent for both cloud and local LLM support.
"""
from pathlib import Path
@@ -18,10 +20,7 @@ _project_root = Path(__file__).parent.parent.parent.parent
if str(_project_root) not in sys.path:
sys.path.insert(0, str(_project_root))
-from openai import AsyncOpenAI
-
from src.agents.base_agent import BaseAgent
-from src.services.llm import get_llm_config
from src.tools import rag_search, web_search
@@ -33,7 +32,7 @@ class ChatAgent(BaseAgent):
- Conversation history management with token limits
- RAG (Retrieval-Augmented Generation) support
- Web search integration
- - Streaming response generation
+ - Streaming response generation via BaseAgent.stream_llm()
"""
# Default token limit for conversation history
@@ -68,12 +67,7 @@ class ChatAgent(BaseAgent):
"max_history_tokens", self.DEFAULT_MAX_HISTORY_TOKENS
)
- # Initialize async OpenAI client for streaming
- llm_config = get_llm_config()
- self._async_client = AsyncOpenAI(
- api_key=llm_config.api_key,
- base_url=llm_config.base_url,
- )
+ self.logger.info(f"ChatAgent initialized: model={self.model}, base_url={self.base_url}")
def count_tokens(self, text: str) -> int:
"""
@@ -281,61 +275,90 @@ class ChatAgent(BaseAgent):
"""
Generate streaming response from LLM.
+ Uses BaseAgent.stream_llm() which routes to the appropriate provider
+ (cloud or local) based on configuration.
+
Args:
messages: Messages array for OpenAI API
Yields:
Response chunks as strings
"""
- try:
- response = await self._async_client.chat.completions.create(
- model=self.get_model(),
- messages=messages,
- temperature=self.get_temperature(),
- stream=True,
- )
+ # Extract system prompt from messages
+ system_prompt = ""
+ user_prompt = ""
+ for msg in messages:
+ if msg.get("role") == "system":
+ system_prompt = msg.get("content", "")
+ break
- async for chunk in response:
- if chunk.choices[0].delta.content:
- yield chunk.choices[0].delta.content
+ # Get the last user message as user_prompt (for logging/tracking)
+ for msg in reversed(messages):
+ if msg.get("role") == "user":
+ user_prompt = msg.get("content", "")
+ break
- except Exception as e:
- self.logger.error(f"Streaming generation failed: {e}")
- raise
+ # Use BaseAgent's stream_llm which routes through the factory
+ async for chunk in self.stream_llm(
+ user_prompt=user_prompt,
+ system_prompt=system_prompt,
+ messages=messages,
+ stage="chat_stream",
+ ):
+ yield chunk
async def generate(self, messages: list[dict[str, str]]) -> str:
"""
Generate complete response from LLM (non-streaming).
+ Uses BaseAgent.call_llm() which routes to the appropriate provider
+ (cloud or local) based on configuration.
+
Args:
messages: Messages array for OpenAI API
Returns:
Complete response string
"""
- try:
- response = await self._async_client.chat.completions.create(
- model=self.get_model(),
- messages=messages,
- temperature=self.get_temperature(),
- )
+ # Extract system prompt from messages
+ system_prompt = ""
+ user_prompt = ""
+ for msg in messages:
+ if msg.get("role") == "system":
+ system_prompt = msg.get("content", "")
+ break
- content = response.choices[0].message.content or ""
+ # Get the last user message
+ for msg in reversed(messages):
+ if msg.get("role") == "user":
+ user_prompt = msg.get("content", "")
+ break
- # Track token usage
- self._track_tokens(
- model=self.get_model(),
- system_prompt=messages[0]["content"] if messages else "",
- user_prompt=messages[-1]["content"] if messages else "",
- response=content,
- stage="chat",
- )
+ # Use BaseAgent's call_llm which routes through the factory
+ # Note: call_llm expects simple prompt/system_prompt, but for multi-turn
+ # we need to use the factory directly with messages
+ from src.services.llm import complete as llm_complete
+
+ response = await llm_complete(
+ prompt=user_prompt,
+ system_prompt=system_prompt,
+ model=self.get_model(),
+ api_key=self.api_key,
+ base_url=self.base_url,
+ messages=messages,
+ temperature=self.get_temperature(),
+ )
- return content
+ # Track token usage
+ self._track_tokens(
+ model=self.get_model(),
+ system_prompt=system_prompt,
+ user_prompt=user_prompt,
+ response=response,
+ stage="chat",
+ )
- except Exception as e:
- self.logger.error(f"Generation failed: {e}")
- raise
+ return response
async def process(
self,
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
index 5bc4f1f6b..6288c44a3 100644
--- a/src/agents/co_writer/edit_agent.py
+++ b/src/agents/co_writer/edit_agent.py
@@ -16,9 +16,9 @@ _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.core.llm_factory import llm_complete
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.tools.rag_tool import rag_search
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
index fddc93df5..877e6fc96 100644
--- a/src/agents/co_writer/narrator_agent.py
+++ b/src/agents/co_writer/narrator_agent.py
@@ -22,9 +22,9 @@ _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.core.llm_factory import llm_complete
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.services.tts import get_tts_config
diff --git a/src/agents/guide/agents/base_guide_agent.py b/src/agents/guide/agents/base_guide_agent.py
index 7aa1927b5..770783df6 100644
--- a/src/agents/guide/agents/base_guide_agent.py
+++ b/src/agents/guide/agents/base_guide_agent.py
@@ -15,10 +15,11 @@ _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.core.core import get_agent_params, get_token_limit_kwargs, load_config_with_main
-from src.core.llm_factory import llm_complete
-from src.core.logging import LLMStats, get_logger
-from src.core.prompt_manager import get_prompt_manager
+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):
diff --git a/src/agents/question/agents/base_agent.py b/src/agents/question/agents/base_agent.py
index fb143da5c..7bc14d433 100644
--- a/src/agents/question/agents/base_agent.py
+++ b/src/agents/question/agents/base_agent.py
@@ -105,7 +105,9 @@ class BaseAgent(ABC):
model = os.getenv("LLM_MODEL", "gpt-4o")
self.model = model
- self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
+ # For local LLM servers, use placeholder key if none provided
+ client_api_key = api_key or "sk-no-key-required"
+ self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
self.api_key = api_key
self.base_url = base_url
diff --git a/src/agents/question/agents/generation_agent.py b/src/agents/question/agents/generation_agent.py
index 4d0740215..674cc5434 100644
--- a/src/agents/question/agents/generation_agent.py
+++ b/src/agents/question/agents/generation_agent.py
@@ -232,9 +232,7 @@ class QuestionGenerationAgent(BaseAgent):
)
_logger.error(error_msg)
return Observation(
- success=False,
- result=None,
- message=f"Failed to parse question JSON: {e}"
+ success=False, result=None, message=f"Failed to parse question JSON: {e}"
)
# Automatically submit after generation
@@ -304,20 +302,14 @@ class QuestionGenerationAgent(BaseAgent):
error_msg = f"[refine_question] LLM API call failed: {type(e).__name__}: {e}"
_logger.error(error_msg)
return Observation(
- success=False,
- result=None,
- message=f"Failed to refine question: {e}"
+ success=False, result=None, message=f"Failed to refine question: {e}"
)
# Validate response structure
if not response or not response.choices:
error_msg = "[refine_question] LLM returned empty response or no choices"
_logger.error(error_msg)
- return Observation(
- success=False,
- result=None,
- message="LLM returned empty response"
- )
+ return Observation(success=False, result=None, message="LLM returned empty response")
# Extract response content with validation
response_content = response.choices[0].message.content
@@ -326,20 +318,12 @@ class QuestionGenerationAgent(BaseAgent):
if response_content is None:
error_msg = f"[refine_question] LLM returned None content. Response: {response}"
_logger.error(error_msg)
- return Observation(
- success=False,
- result=None,
- message="LLM returned None content"
- )
+ return Observation(success=False, result=None, message="LLM returned None content")
if not response_content.strip():
error_msg = f"[refine_question] LLM returned empty string. Response: {response}"
_logger.error(error_msg)
- return Observation(
- success=False,
- result=None,
- message="LLM returned empty string"
- )
+ return Observation(success=False, result=None, message="LLM returned empty string")
# Log successful response
_logger.debug(
@@ -385,9 +369,7 @@ class QuestionGenerationAgent(BaseAgent):
)
_logger.error(error_msg)
return Observation(
- success=False,
- result=None,
- message=f"Failed to parse question JSON: {e}"
+ success=False, result=None, message=f"Failed to parse question JSON: {e}"
)
# Remove the processed feedback message
diff --git a/src/agents/question/coordinator.py b/src/agents/question/coordinator.py
index 9822ec79d..5c925e10a 100644
--- a/src/agents/question/coordinator.py
+++ b/src/agents/question/coordinator.py
@@ -250,24 +250,24 @@ class AgentCoordinator:
def _extract_json_from_markdown(self, content: str) -> str:
"""Extract JSON from markdown code blocks.
-
+
LLMs often wrap JSON in ```json ... ``` blocks. This method strips
the markdown formatting and any surrounding text.
"""
if not content:
return content
-
+
# Remove leading explanatory text (look for the first ```json or ```)
import re
-
+
# Try to find JSON code block
- json_block_pattern = r'```(?:json)?\s*\n?(.*?)```'
+ json_block_pattern = r"```(?:json)?\s*\n?(.*?)```"
matches = re.findall(json_block_pattern, content, re.DOTALL)
-
+
if matches:
# Return the content inside the first code block
return matches[0].strip()
-
+
# If no code blocks found, return as-is (might already be valid JSON)
return content.strip()
@@ -321,16 +321,14 @@ class AgentCoordinator:
# Validate content is not None or empty
if response_content is None:
error_msg = (
- f"[{stage or 'coordinator'}] LLM returned None content. "
- f"Response: {response}"
+ f"[{stage or 'coordinator'}] LLM returned None content. Response: {response}"
)
self.logger.error(error_msg)
raise ValueError(error_msg)
if not response_content.strip():
error_msg = (
- f"[{stage or 'coordinator'}] LLM returned empty string. "
- f"Response object: {response}"
+ f"[{stage or 'coordinator'}] LLM returned empty string. Response object: {response}"
)
self.logger.error(error_msg)
raise ValueError(error_msg)
@@ -1735,7 +1733,7 @@ class AgentCoordinator:
content = await self._call_llm(
system_prompt=system_prompt, user_prompt=user_prompt, stage="generate_question_plan"
)
-
+
# Validate content before JSON parsing
if not content or content.strip() == "":
self.logger.error("LLM returned empty content for question plan generation")
@@ -1952,7 +1950,7 @@ class AgentCoordinator:
user_prompt=user_prompt,
stage=f"generate_question_{question_id}",
)
-
+
# Validate content before JSON parsing
if not content or content.strip() == "":
self.logger.error(f"LLM returned empty content for question {question_id}")
@@ -1961,7 +1959,7 @@ class AgentCoordinator:
"success": False,
"error": "LLM returned empty response",
}
-
+
try:
# Extract JSON from markdown code blocks if present
json_content = self._extract_json_from_markdown(content)
diff --git a/src/agents/question/validation_workflow.py b/src/agents/question/validation_workflow.py
index 0c231edaf..c30a95848 100644
--- a/src/agents/question/validation_workflow.py
+++ b/src/agents/question/validation_workflow.py
@@ -58,7 +58,9 @@ class QuestionValidationWorkflow:
if model is None:
model = os.getenv("LLM_MODEL", "gpt-4o")
- self.client = AsyncOpenAI(api_key=api_key, base_url=base_url)
+ # For local LLM servers, use placeholder key if none provided
+ client_api_key = api_key or "sk-no-key-required"
+ self.client = AsyncOpenAI(api_key=client_api_key, base_url=base_url)
self.api_key = api_key
self.base_url = base_url
self.model = model
diff --git a/src/agents/solve/main_solver.py b/src/agents/solve/main_solver.py
index 6b1048898..c26f57611 100644
--- a/src/agents/solve/main_solver.py
+++ b/src/agents/solve/main_solver.py
@@ -141,9 +141,17 @@ class MainSolver:
except ValueError as e:
raise ValueError(f"LLM config error: {e!s}")
- if not api_key:
+ # Check if API key is required
+ # Local LLM servers (Ollama, LM Studio, etc.) don't need API keys
+ from src.services.llm import is_local_llm_server
+
+ if not api_key and not is_local_llm_server(base_url):
raise ValueError("API key not set. Provide api_key param or set LLM_API_KEY in .env")
+ # For local servers, use a placeholder key if none provided
+ if not api_key and is_local_llm_server(base_url):
+ api_key = "sk-no-key-required"
+
self.api_key = api_key
self.base_url = base_url
self.kb_name = kb_name
diff --git a/src/api/routers/llm_provider.py b/src/api/routers/llm_provider.py
index 3fceeee93..9de2eb076 100644
--- a/src/api/routers/llm_provider.py
+++ b/src/api/routers/llm_provider.py
@@ -1,9 +1,19 @@
-from typing import Any, Dict, List
+from typing import Any, Dict, List, Literal
from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
-from src.core.llm_factory import llm_complete, llm_fetch_models
+from src.services.llm import (
+ complete as llm_complete,
+)
+from src.services.llm import (
+ fetch_models as llm_fetch_models,
+)
+from src.services.llm import (
+ get_mode_info,
+ get_provider_presets,
+ sanitize_url,
+)
from src.services.llm.provider import LLMProvider, provider_manager
router = APIRouter()
@@ -15,6 +25,7 @@ class TestConnectionRequest(BaseModel):
api_key: str
model: str
requires_key: bool = True # Default to True for backward compatibility
+ provider_type: Literal["api", "local"] = "local" # New field
@router.get("/", response_model=List[LLMProvider])
@@ -76,21 +87,9 @@ async def set_active_provider(name_payload: Dict[str, str]):
async def test_connection(request: TestConnectionRequest):
"""Test connection to an LLM provider."""
try:
- # Sanitize Base URL
- # Users often paste full endpoints like http://.../v1/chat/completions
- # OpenAI client needs just the base (e.g., http://.../v1)
- base_url = request.base_url.rstrip("/")
-
- # Special handling for Ollama: if it ends in /api, it's likely wrong for completion but ok for tags
- # But here we want the completion base.
- if "/api" in base_url and not base_url.endswith("/v1"):
- # If user has http://localhost:11434/api -> change to http://localhost:11434/v1
- if ":11434" in base_url or "ollama" in base_url.lower():
- base_url = base_url.replace("/api", "/v1")
-
- for suffix in ["/chat/completions", "/completions"]:
- if base_url.endswith(suffix):
- base_url = base_url[: -len(suffix)]
+ # Use unified sanitize_url for consistent URL handling
+ # Handles Ollama, LM Studio, and other local servers
+ base_url = sanitize_url(request.base_url)
# Simple test prompt
if not request.requires_key and not request.api_key:
@@ -118,15 +117,8 @@ async def test_connection(request: TestConnectionRequest):
async def fetch_available_models(request: TestConnectionRequest):
"""Fetch available models from the provider."""
try:
- # Sanitize Base URL (same as test_connection)
- base_url = request.base_url.rstrip("/")
- if "/api" in base_url and not base_url.endswith("/v1"):
- if ":11434" in base_url or "ollama" in base_url.lower():
- base_url = base_url.replace("/api", "/v1")
-
- for suffix in ["/chat/completions", "/completions"]:
- if base_url.endswith(suffix):
- base_url = base_url[: -len(suffix)]
+ # Use unified sanitize_url for consistent URL handling
+ base_url = sanitize_url(request.base_url)
models = await llm_fetch_models(
binding=request.binding,
@@ -136,3 +128,34 @@ async def fetch_available_models(request: TestConnectionRequest):
return {"success": True, "models": models}
except Exception as e:
return {"success": False, "message": f"Failed to fetch models: {str(e)}"}
+
+
+# ==================== LLM Mode Endpoints ====================
+
+
[email protected]("/mode/", response_model=Dict[str, Any])
+async def get_llm_mode_info():
+ """
+ Get information about the current LLM configuration mode.
+
+ Returns:
+ Dict containing:
+ - mode: Current deployment mode ('api', 'local', or 'hybrid')
+ - active_provider: Active provider info (if any)
+ - env_configured: Whether env vars are properly configured
+ - effective_source: Which config source is being used ('env' or 'provider')
+ """
+ return get_mode_info()
+
+
[email protected]("/presets/", response_model=Dict[str, Any])
+async def get_presets():
+ """
+ Get provider presets for API and Local providers.
+
+ Returns:
+ Dict containing:
+ - api: API provider presets (OpenAI, Anthropic, DeepSeek, etc.)
+ - local: Local provider presets (Ollama, LM Studio, vLLM, etc.)
+ """
+ return get_provider_presets()
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
index 675d08b60..36f75fb23 100644
--- a/src/api/routers/settings.py
+++ b/src/api/routers/settings.py
@@ -24,80 +24,80 @@ config_manager = ConfigManager()
# These variables can be modified at runtime without restarting the server
ENV_VAR_DEFINITIONS = {
- # LLM Configuration
+ # LLM Mode Configuration
+ "LLM_MODE": {
+ "description": "LLM deployment mode: 'api' (cloud only), 'local' (self-hosted only), 'hybrid' (both, use active provider)",
+ "category": "llm",
+ "required": False,
+ "default": "hybrid",
+ "sensitive": False,
+ },
+ # LLM Configuration (supports both cloud and local)
"LLM_BINDING": {
- "description": "LLM service provider type (e.g., openai, anthropic, gemini, openrouter, ollama)",
+ "description": "LLM protocol type: openai (for OpenAI-compatible APIs including Ollama, vLLM), anthropic (for Claude)",
"category": "llm",
"required": False,
"default": "openai",
"sensitive": False,
},
"LLM_MODEL": {
- "description": "LLM model name (e.g., gpt-4o, deepseek-chat, qwen-plus)",
+ "description": "Model name. Cloud: gpt-4o, deepseek-chat. Local: llama3.2, qwen2.5, mistral-nemo",
"category": "llm",
"required": True,
"default": "",
"sensitive": False,
},
"LLM_HOST": {
- "description": "LLM API endpoint URL (e.g., https://api.openai.com/v1)",
+ "description": "API endpoint. Cloud: https://api.openai.com/v1. Local: http://localhost:11434/v1 (Ollama), http://localhost:1234/v1 (LM Studio)",
"category": "llm",
"required": True,
"default": "",
"sensitive": False,
},
"LLM_API_KEY": {
- "description": "LLM API authentication key",
+ "description": "API key (required for cloud, optional for local - use 'ollama' or any string for Ollama)",
"category": "llm",
"required": True,
"default": "",
"sensitive": True,
},
- # Embedding Configuration
+ # Embedding Configuration (supports both cloud and local)
"EMBEDDING_BINDING": {
- "description": "Embedding service provider type (openai, ollama, lm_studio, azure_openai, jina, cohere, huggingface)",
+ "description": "Embedding provider: openai, ollama, lm_studio, azure_openai, jina, cohere, huggingface",
"category": "embedding",
"required": False,
"default": "openai",
"sensitive": False,
},
"EMBEDDING_MODEL": {
- "description": "Embedding model name (e.g., text-embedding-3-large, text-embedding-ada-002)",
+ "description": "Model name. Cloud: text-embedding-3-large. Local: nomic-embed-text, mxbai-embed-large",
"category": "embedding",
"required": True,
"default": "",
"sensitive": False,
},
"EMBEDDING_DIMENSION": {
- "description": "Embedding vector dimension (e.g., 3072 for text-embedding-3-large)",
+ "description": "Vector dimension: 3072 (text-embedding-3-large), 768 (nomic-embed-text), 1024 (mxbai)",
"category": "embedding",
"required": False,
"default": "3072",
"sensitive": False,
},
"EMBEDDING_HOST": {
- "description": "Embedding API endpoint URL",
+ "description": "API endpoint. Cloud: https://api.openai.com/v1. Local: http://localhost:11434 (Ollama)",
"category": "embedding",
"required": True,
"default": "",
"sensitive": False,
},
"EMBEDDING_API_KEY": {
- "description": "Embedding API authentication key",
+ "description": "API key (required for cloud providers, not needed for Ollama/local)",
"category": "embedding",
- "required": False, # Conditional: not required for Ollama/local providers
+ "required": False,
"default": "",
"sensitive": True,
"conditional": "Required for cloud providers (OpenAI, Jina, Cohere, etc.). Not needed for Ollama or local models.",
},
- # RAG Configuration
- "RAG_PROVIDER": {
- "description": "RAG provider to use (lightrag, chromadb, pinecone, etc.)",
- "category": "rag",
- "required": False,
- "default": "lightrag",
- "sensitive": False,
- },
# TTS Configuration (OpenAI compatible API)
"TTS_MODEL": {
"description": "OpenAI TTS model (tts-1 for speed, tts-1-hd for quality)",
@@ -135,55 +135,30 @@ ENV_VAR_DEFINITIONS = {
"default": "",
"sensitive": True,
},
- # System Configuration
- "DISABLE_SSL_VERIFY": {
- "description": "Disable SSL certificate verification (set 'true' for self-signed certs)",
- "category": "system",
- "required": False,
- "default": "false",
- "sensitive": False,
- },
- "RAG_TOOL_MODULE_LOG_LEVEL": {
- "description": "Log level for RAG tool module (DEBUG, INFO, WARNING, ERROR)",
- "category": "system",
- "required": False,
- "default": "INFO",
- "sensitive": False,
- },
}
# Categories for organizing the UI
ENV_CATEGORIES = {
"llm": {
"name": "LLM Configuration",
- "description": "Large Language Model settings for AI reasoning and generation",
+ "description": "LLM settings for AI reasoning. Supports cloud APIs (OpenAI, DeepSeek) and local servers (Ollama, LM Studio).",
"icon": "brain",
},
"embedding": {
"name": "Embedding Configuration",
- "description": "Text embedding model settings for semantic search and RAG",
+ "description": "Embedding settings for RAG. Supports cloud (OpenAI) and local (Ollama with nomic-embed-text).",
"icon": "database",
},
- "rag": {
- "name": "RAG Configuration",
- "description": "Retrieval-Augmented Generation provider settings",
- "icon": "search",
- },
"tts": {
"name": "TTS Configuration",
- "description": "Text-to-Speech settings. Currently only supports Alibaba Cloud DashScope.",
+ "description": "Text-to-Speech settings (OpenAI-compatible API).",
"icon": "volume",
},
"search": {
"name": "Web Search Configuration",
- "description": "External search API settings",
+ "description": "External search API settings (Perplexity)",
"icon": "search",
},
- "system": {
- "name": "System Configuration",
- "description": "General system settings",
- "icon": "settings",
- },
}
# Settings file path (for local client/UI prefs not appropriate for main.yaml)
@@ -679,6 +654,103 @@ async def test_env_config():
return results
[email protected]("/env/test/{service}")
+async def test_single_service(service: Literal["llm", "embedding", "tts"]):
+ """
+ Test a single service configuration with actual API call.
+
+ Args:
+ service: The service to test (llm, embedding, tts)
+
+ Returns:
+ Test result with status, model info, and response time.
+ """
+ import time
+
+ result = {
+ "status": "unknown",
+ "model": None,
+ "error": None,
+ "response_time_ms": None,
+ "message": None,
+ }
+
+ start_time = time.time()
+
+ if service == "llm":
+ try:
+ from src.services.llm import complete as llm_complete
+
+ llm_config = get_llm_config()
+ result["model"] = llm_config.model
+
+ # Actually test the LLM with a simple prompt
+ response = await llm_complete(
+ model=llm_config.model,
+ prompt="Say 'OK' if you can hear me.",
+ system_prompt="You are a test assistant. Reply with just 'OK'.",
+ api_key=llm_config.api_key,
+ base_url=llm_config.base_url,
+ binding=llm_config.binding,
+ max_tokens=10,
+ )
+ result["status"] = "success"
+ result["message"] = (
+ f"Response: {response[:50]}..." if len(response) > 50 else f"Response: {response}"
+ )
+ except ValueError as e:
+ result["status"] = "not_configured"
+ result["error"] = str(e)
+ except Exception as e:
+ result["status"] = "error"
+ result["error"] = str(e)
+
+ elif service == "embedding":
+ try:
+ from src.services.embedding import get_embedding_client
+
+ embedding_config = get_embedding_config()
+ result["model"] = embedding_config.model
+
+ # Actually test embedding with a simple text
+ embedding_client = get_embedding_client()
+ embeddings = await embedding_client.embed(["Test embedding"])
+ if embeddings and len(embeddings) > 0:
+ result["status"] = "success"
+ result["message"] = f"Dimension: {len(embeddings[0])}"
+ else:
+ result["status"] = "error"
+ result["error"] = "Empty embedding returned"
+ except ValueError as e:
+ result["status"] = "not_configured"
+ result["error"] = str(e)
+ except Exception as e:
+ result["status"] = "error"
+ result["error"] = str(e)
+
+ elif service == "tts":
+ try:
+ tts_config = get_tts_config()
+ result["model"] = tts_config.get("model")
+
+ # For TTS, just check if config is valid (actual audio test is expensive)
+ if tts_config.get("model") and tts_config.get("base_url"):
+ result["status"] = "success"
+ result["message"] = f"Voice: {tts_config.get('voice', 'alloy')}"
+ else:
+ result["status"] = "not_configured"
+ result["error"] = "Missing model or base_url"
+ except ValueError as e:
+ result["status"] = "not_configured"
+ result["error"] = str(e)
+ except Exception as e:
+ result["status"] = "error"
+ result["error"] = str(e)
+
+ result["response_time_ms"] = int((time.time() - start_time) * 1000)
+ return result
+
+
# ==================== RAG Provider Configuration ====================
diff --git a/src/api/routers/system.py b/src/api/routers/system.py
index 073d23d7b..48e00feb6 100644
--- a/src/api/routers/system.py
+++ b/src/api/routers/system.py
@@ -9,8 +9,8 @@ import time
from fastapi import APIRouter
from pydantic import BaseModel
-from src.core.llm_factory import llm_complete
from src.services.embedding import get_embedding_client, get_embedding_config
+from src.services.llm import complete as llm_complete
from src.services.llm import get_llm_config, get_token_limit_kwargs
from src.services.tts import get_tts_config
diff --git a/src/core/__init__.py b/src/core/__init__.py
deleted file mode 100644
index 2c8f96905..000000000
--- a/src/core/__init__.py
+++ /dev/null
@@ -1,21 +0,0 @@
-"""
-Core Module - LLM Factory
-=========================
-
-This module provides the LLM factory for creating completion functions
-across different providers.
-"""
-
-from .llm_factory import (
- LLMFactory,
- llm_complete,
- llm_fetch_models,
- sanitize_url,
-)
-
-__all__ = [
- "LLMFactory",
- "llm_complete",
- "llm_fetch_models",
- "sanitize_url",
-]
diff --git a/src/core/llm_factory.py b/src/core/llm_factory.py
deleted file mode 100644
index b16cd1902..000000000
--- a/src/core/llm_factory.py
+++ /dev/null
@@ -1,325 +0,0 @@
-import os
-from typing import Callable, List, Optional
-
-import aiohttp
-from lightrag.llm.openai import openai_complete_if_cache
-
-
-class LLMFactory:
- """
- Factory for creating LLM completion functions for various providers.
- Provides a unified interface for calling different LLM APIs.
- """
-
- @staticmethod
- async def anthropic_complete(
- model: str,
- prompt: str,
- system_prompt: str = "You are a helpful assistant.",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- **kwargs,
- ) -> str:
- """
- Wrapper for Anthropic (Claude) API.
- """
- api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
- if not api_key:
- raise ValueError("Anthropic API key is missing.")
-
- # Default Anthropic API URL if not provided
- 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",
- }
-
- data = {
- "model": model,
- "system": system_prompt,
- "messages": [{"role": "user", "content": prompt}],
- "max_tokens": kwargs.get("max_tokens", 4096),
- "temperature": kwargs.get("temperature", 0.7),
- }
-
- async with aiohttp.ClientSession() as session:
- 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}")
-
- result = await response.json()
- # Anthropic returns a list of content blocks
- return result["content"][0]["text"]
-
- @staticmethod
- def get_completion_function(binding: str) -> Callable:
- """
- Returns the appropriate completion function based on the provider binding.
- """
- binding = binding.lower()
-
- if binding == "anthropic" or binding == "claude":
- return LLMFactory.anthropic_complete
-
- # For ollama-cloud, we usually treat it as OpenAI compatible or use a specific endpoint
- # If it's just a hosted Ollama, it's often OpenAI compatible (/v1)
- if binding == "ollama-cloud":
- # For now, treat it as OpenAI compatible
- return openai_complete_if_cache
-
- # Default to OpenAI-compatible for most (openai, azure_openai, ollama local, openrouter, deepseek, gemini)
- return openai_complete_if_cache
-
- @staticmethod
- async def fetch_models(binding: str, base_url: str, api_key: Optional[str] = None) -> List[str]:
- """
- Fetch available models from the provider.
- """
- binding = binding.lower()
- base_url = base_url.rstrip("/")
-
- headers = {}
- if api_key:
- if binding in ["anthropic", "claude"]:
- headers["x-api-key"] = api_key
- else:
- headers["Authorization"] = f"Bearer {api_key}"
-
- async with aiohttp.ClientSession() as session:
- try:
- # Strategy 1: Local Ollama /api/tags
- # Try this for anything that looks like local Ollama or specifically has 'ollama' in binding/url
- # but NOT if it's explicitly 'ollama.com' (cloud) unless it's a fallback
- is_likely_local_ollama = (
- (binding == "ollama" or "ollama" in base_url.lower())
- and "ollama.com" not in base_url.lower()
- or ":11434" in base_url
- )
-
- if is_likely_local_ollama:
- url = base_url.rstrip("/").replace("/v1", "") + "/api/tags"
- try:
- async with session.get(url, headers=headers) as resp:
- if resp.status == 200:
- data = await resp.json()
- if "models" in data:
- return [m["name"] for m in data.get("models", [])]
- except Exception:
- pass # Try Strategy 2 if this fails
-
- # Strategy 2: Standard OpenAI /models (also used by Ollama Cloud)
- url = f"{base_url.rstrip('/')}/models"
- async with session.get(url, headers=headers) as resp:
- if resp.status == 200:
- data = await resp.json()
- # Handle standard OpenAI format: {"data": [{"id": "model-id"}, ...]}
- if "data" in data and isinstance(data["data"], list):
- return [
- m.get("id") or m.get("name")
- for m in data["data"]
- if m.get("id") or m.get("name")
- ]
- # Handle some providers that use {"models": ["model1", ...]}
- elif "models" in data and isinstance(data["models"], list):
- if data["models"] and isinstance(data["models"][0], dict):
- return [
- m.get("id") or m.get("name")
- for m in data["models"]
- if m.get("id") or m.get("name")
- ]
- else:
- return [str(m) for m in data["models"]]
- # Handle raw list response
- elif isinstance(data, list):
- if data and isinstance(data[0], dict):
- return [
- m.get("id") or m.get("name")
- for m in data
- if m.get("id") or m.get("name")
- ]
- else:
- return [str(m) for m in data]
-
- # Fallback Strategy: If it's ollama.com but /models failed, try /api/tags as well
- if "ollama.com" in base_url:
- url = base_url.rstrip("/").replace("/v1", "") + "/api/tags"
- try:
- async with session.get(url, headers=headers) as resp:
- if resp.status == 200:
- data = await resp.json()
- return [m["name"] for m in data.get("models", [])]
- except Exception:
- pass
-
- return []
- except Exception as e:
- print(f"Error fetching models from {base_url}: {e}")
- return []
-
-
-# Unified interface for agents
-def sanitize_url(base_url: str, model: str = "") -> str:
- """
- Sanitize base URL for OpenAI-compatible APIs, with special handling for Ollama.
- """
- if not base_url:
- return base_url
-
- url = base_url.rstrip("/")
-
- # Ensure URL has a protocol (default to http for local/ollama)
- if url and not url.startswith(("http://", "https://")):
- url = "http://" + url
-
- # Standard OpenAI client library is strict about URLs:
- # - No trailing slashes
- # - No /chat/completions or /completions/messages/embeddings suffixes (it adds these automatically)
- for suffix in ["/chat/completions", "/completions", "/messages", "/embeddings"]:
- if url.endswith(suffix):
- url = url[: -len(suffix)]
- url = url.rstrip("/")
-
- # Special handling for Ollama: local/self-hosted Ollama requires /v1
- # for OpenAI compatibility. If it's port 11434 or has 'ollama' in URL
- # and it's not the cloud version (ollama.com), ensure it ends in /v1.
- if ":11434" in url or ("ollama" in url.lower() and "ollama.com" not in url.lower()):
- if not url.endswith("/v1"):
- url = url.rstrip("/") + "/v1"
-
- return url
-
-
-async def llm_complete(
- model: str,
- prompt: str,
- system_prompt: str = "You are a helpful assistant.",
- binding: str = "openai",
- api_key: Optional[str] = None,
- base_url: Optional[str] = None,
- **kwargs,
-) -> str:
- """
- Call the appropriate LLM provider based on binding.
- Includes a direct aiohttp fallback for reasoning models and OpenAI-compatible services.
- """
- complete_fn = LLMFactory.get_completion_function(binding)
-
- # Sanitize base_url for OpenAI-compatible endpoints
- # The OpenAI client library is strict about URLs:
- # - No trailing slashes
- # - No /chat/completions or /completions suffixes (it adds these automatically)
- if base_url and (complete_fn == openai_complete_if_cache or binding in ["openai", "ollama"]):
- original_url = base_url
- base_url = sanitize_url(base_url, model)
-
- if original_url != base_url:
- print(f"🔧 URL Sanitized: {original_url} -> {base_url}")
- print(f"🚀 LLM Call: model={model}, binding={binding}, base_url={base_url}")
-
- try:
- # 1. Attempt using standard driver
- if complete_fn == openai_complete_if_cache:
- response = await complete_fn(
- model=model,
- prompt=prompt,
- system_prompt=system_prompt,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
- else:
- response = await complete_fn(
- model=model,
- prompt=prompt,
- system_prompt=system_prompt,
- api_key=api_key,
- base_url=base_url,
- **kwargs,
- )
-
- # If response is empty, it might be a reasoning model that lightrag can't parse
- if not response:
- raise ValueError("Empty response from standard driver")
-
- return response
-
- except Exception as e:
- # 2. Fallback to direct aiohttp call for OpenAI-compatible bindings
- # This is useful for reasoning models (DeepSeek R1, Kimi) that might
- # return empty content but have reasoning in other fields.
- is_openai_compatible = binding.lower() in [
- "openai",
- "ollama",
- "ollama-cloud",
- "deepseek",
- "openrouter",
- "gemini",
- ]
-
- if is_openai_compatible and base_url:
- try:
- url = base_url.rstrip("/")
- if not url.endswith("/chat/completions"):
- url += "/chat/completions"
-
- print(f"🔄 Fallback Direct Call: {url}")
-
- headers = {
- "Content-Type": "application/json",
- "Authorization": f"Bearer {api_key}" if api_key else "",
- }
-
- data = {
- "model": model,
- "messages": [
- {"role": "system", "content": system_prompt},
- {"role": "user", "content": prompt},
- ],
- "temperature": kwargs.get("temperature", 0.7),
- "max_tokens": kwargs.get("max_tokens", 4096),
- }
-
- async with aiohttp.ClientSession() as session:
- async with session.post(url, headers=headers, json=data) as resp:
- if resp.status == 200:
- result = await resp.json()
- if "choices" in result and result["choices"]:
- msg = result["choices"][0].get("message", {})
- content = msg.get("content", "")
-
- # If content is empty, look for reasoning/thinking fields
- if not content:
- content = (
- msg.get("reasoning_content")
- or msg.get("reasoning")
- or msg.get("thought")
- or ""
- )
-
- if content:
- return content
- else:
- error_text = await resp.text()
- print(
- f"❌ Fallback call failed with status={resp.status}: {error_text}"
- )
- except Exception as e2:
- print(f"❌ Fallback direct call failed: {e2}")
-
- # If fallback also fails or isn't applicable, re-raise original
- raise e
-
-
-async def llm_fetch_models(binding: str, base_url: str, api_key: Optional[str] = None) -> List[str]:
- """
- Fetch available models from the provider.
- """
- return await LLMFactory.fetch_models(binding, base_url, api_key)
diff --git a/src/services/llm/__init__.py b/src/services/llm/__init__.py
index cd91f564d..dae3c2883 100644
--- a/src/services/llm/__init__.py
+++ b/src/services/llm/__init__.py
@@ -2,24 +2,46 @@
LLM Service
===========
-Unified LLM client for all DeepTutor modules.
+Unified LLM service for all DeepTutor modules.
+
+Architecture:
+ Agents (ChatAgent, GuideAgent, etc.)
+ ↓
+ BaseAgent.call_llm() / stream_llm()
+ ↓
+ LLM Factory (complete / stream)
+ ↓
+ ┌─────────┴─────────┐
+ ↓ ↓
+CloudProvider LocalProvider
+(cloud_provider) (local_provider)
Usage:
- from src.services.llm import get_llm_client, LLMClient, LLMConfig
+ # Simple completion
+ from src.services.llm import complete, stream
+ response = await complete("Hello!", system_prompt="You are helpful.")
- # Get singleton client
- client = get_llm_client()
- response = await client.complete("Hello, world!")
+ # Streaming
+ async for chunk in stream("Hello!", system_prompt="You are helpful."):
+ print(chunk, end="")
- # Or create custom client
- config = LLMConfig(model="gpt-4o", api_key="...", base_url="...")
- client = LLMClient(config)
+ # Configuration
+ from src.services.llm import get_llm_config, LLMConfig
+ config = get_llm_config()
# Provider management
from src.services.llm import provider_manager, LLMProvider
providers = provider_manager.list_providers()
+
+ # URL utilities for local LLM servers
+ from src.services.llm import sanitize_url, is_local_llm_server
+
+ # Mode information
+ from src.services.llm import LLMMode, get_llm_mode, get_mode_info
"""
+# Also expose the providers for direct access if needed
+from . import cloud_provider, local_provider
from .client import LLMClient, get_llm_client, reset_llm_client
from .config import (
LLMConfig,
@@ -27,14 +49,28 @@ from .config import (
get_token_limit_kwargs,
uses_max_completion_tokens,
)
+from .factory import (
+ API_PROVIDER_PRESETS,
+ LOCAL_PROVIDER_PRESETS,
+ LLMMode,
+ complete,
+ fetch_models,
+ get_effective_config,
+ get_llm_mode,
+ get_mode_info,
+ get_provider_presets,
+ stream,
+)
from .provider import (
LLMProvider,
LLMProviderManager,
+ ProviderType,
provider_manager,
)
+from .utils import is_local_llm_server, sanitize_url
__all__ = [
- # Client
+ # Client (legacy, prefer factory functions)
"LLMClient",
"get_llm_client",
"reset_llm_client",
@@ -43,8 +79,26 @@ __all__ = [
"get_llm_config",
"uses_max_completion_tokens",
"get_token_limit_kwargs",
- # Provider
+ # Factory (main API)
+ "LLMMode",
+ "get_llm_mode",
+ "get_effective_config",
+ "get_mode_info",
+ "complete",
+ "stream",
+ "fetch_models",
+ "get_provider_presets",
+ "API_PROVIDER_PRESETS",
+ "LOCAL_PROVIDER_PRESETS",
+ # Providers
+ "cloud_provider",
+ "local_provider",
+ # Provider Management
+ "ProviderType",
"LLMProvider",
"LLMProviderManager",
"provider_manager",
+ # Utils
+ "sanitize_url",
+ "is_local_llm_server",
]
diff --git a/src/services/llm/cloud_provider.py b/src/services/llm/cloud_provider.py
new file mode 100644
index 000000000..c6ebbbf56
--- /dev/null
+++ b/src/services/llm/cloud_provider.py
@@ -0,0 +1,438 @@
+"""
+Cloud LLM Provider
+==================
+
+Handles all cloud API LLM calls (OpenAI, DeepSeek, Anthropic, etc.)
+Provides both complete() and stream() methods.
+"""
+
+import os
+from typing import Any, AsyncGenerator, Dict, List, Optional
+
+import aiohttp
+from lightrag.llm.openai import openai_complete_if_cache
+
+from .utils import sanitize_url
+
+
+async def complete(
+ prompt: str,
+ system_prompt: str = "You are a helpful assistant.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ binding: str = "openai",
+ **kwargs,
+) -> str:
+ """
+ Complete a prompt using cloud API providers.
+
+ Supports OpenAI-compatible APIs and Anthropic.
+
+ Args:
+ prompt: The user prompt
+ system_prompt: System prompt for context
+ model: Model name
+ api_key: API key
+ base_url: Base URL for the API
+ binding: Provider binding type (openai, anthropic)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Returns:
+ str: The LLM response
+ """
+ binding_lower = (binding or "openai").lower()
+
+ if binding_lower in ["anthropic", "claude"]:
+ return await _anthropic_complete(
+ model=model,
+ prompt=prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ **kwargs,
+ )
+
+ # Default to OpenAI-compatible endpoint
+ return await _openai_complete(
+ model=model,
+ prompt=prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ **kwargs,
+ )
+
+
+async def stream(
+ prompt: str,
+ system_prompt: str = "You are a helpful assistant.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ binding: str = "openai",
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> AsyncGenerator[str, None]:
+ """
+ Stream a response from cloud API providers.
+
+ Args:
+ prompt: The user prompt (ignored if messages provided)
+ system_prompt: System prompt for context
+ model: Model name
+ api_key: API key
+ base_url: Base URL for the API
+ binding: Provider binding type (openai, anthropic)
+ messages: Pre-built messages array (optional, overrides prompt/system_prompt)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Yields:
+ str: Response chunks
+ """
+ binding_lower = (binding or "openai").lower()
+
+ if binding_lower in ["anthropic", "claude"]:
+ async for chunk in _anthropic_stream(
+ model=model,
+ prompt=prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ messages=messages,
+ **kwargs,
+ ):
+ yield chunk
+ else:
+ async for chunk in _openai_stream(
+ model=model,
+ prompt=prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ messages=messages,
+ **kwargs,
+ ):
+ yield chunk
+
+
+async def _openai_complete(
+ model: str,
+ prompt: str,
+ system_prompt: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ **kwargs,
+) -> str:
+ """OpenAI-compatible completion."""
+ # Sanitize URL
+ if base_url:
+ base_url = sanitize_url(base_url, model)
+
+ try:
+ # Try using lightrag's openai_complete_if_cache first (has caching)
+ response = await openai_complete_if_cache(
+ model=model,
+ prompt=prompt,
+ system_prompt=system_prompt,
+ api_key=api_key,
+ base_url=base_url,
+ **kwargs,
+ )
+ if response:
+ return response
+ except Exception:
+ pass # Fall through to direct call
+
+ # Fallback: Direct aiohttp call
+ if base_url:
+ url = base_url.rstrip("/")
+ if not url.endswith("/chat/completions"):
+ url += "/chat/completions"
+
+ headers = {"Content-Type": "application/json"}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ data = {
+ "model": model,
+ "messages": [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": prompt},
+ ],
+ "temperature": kwargs.get("temperature", 0.7),
+ "max_tokens": kwargs.get("max_tokens", 4096),
+ }
+
+ timeout = aiohttp.ClientTimeout(total=120)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ async with session.post(url, headers=headers, json=data) as resp:
+ if resp.status == 200:
+ 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 ""
+ )
+ return content
+ else:
+ error_text = await resp.text()
+ raise Exception(f"OpenAI API error: {resp.status} - {error_text}")
+
+ raise Exception("Cloud completion failed: no valid configuration")
+
+
+async def _openai_stream(
+ model: str,
+ prompt: str,
+ system_prompt: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> AsyncGenerator[str, None]:
+ """OpenAI-compatible streaming."""
+ import json
+
+ # Sanitize URL
+ if base_url:
+ base_url = sanitize_url(base_url, model)
+
+ url = (base_url or "https://api.openai.com/v1").rstrip("/")
+ if not url.endswith("/chat/completions"):
+ url += "/chat/completions"
+
+ headers = {"Content-Type": "application/json"}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ # Build messages
+ if messages:
+ msg_list = messages
+ else:
+ msg_list = [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": prompt},
+ ]
+
+ data = {
+ "model": model,
+ "messages": msg_list,
+ "temperature": kwargs.get("temperature", 0.7),
+ "stream": True,
+ }
+ if kwargs.get("max_tokens"):
+ data["max_tokens"] = kwargs["max_tokens"]
+
+ timeout = aiohttp.ClientTimeout(total=300)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ 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}")
+
+ async for line in resp.content:
+ line_str = line.decode("utf-8").strip()
+ if not line_str or not line_str.startswith("data:"):
+ continue
+
+ data_str = line_str[5:].strip()
+ if data_str == "[DONE]":
+ break
+
+ try:
+ chunk_data = json.loads(data_str)
+ if "choices" in chunk_data and chunk_data["choices"]:
+ delta = chunk_data["choices"][0].get("delta", {})
+ content = delta.get("content")
+ if content:
+ yield content
+ except json.JSONDecodeError:
+ continue
+
+
+async def _anthropic_complete(
+ model: str,
+ prompt: str,
+ system_prompt: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ **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.")
+
+ 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",
+ }
+
+ data = {
+ "model": model,
+ "system": system_prompt,
+ "messages": [{"role": "user", "content": prompt}],
+ "max_tokens": kwargs.get("max_tokens", 4096),
+ "temperature": kwargs.get("temperature", 0.7),
+ }
+
+ timeout = aiohttp.ClientTimeout(total=120)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ 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}")
+
+ result = await response.json()
+ return result["content"][0]["text"]
+
+
+async def _anthropic_stream(
+ model: str,
+ prompt: str,
+ system_prompt: str,
+ api_key: Optional[str],
+ base_url: Optional[str],
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> AsyncGenerator[str, None]:
+ """Anthropic (Claude) API streaming."""
+ import json
+
+ api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
+ if not api_key:
+ raise ValueError("Anthropic API key is missing.")
+
+ 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 messages
+ if messages:
+ # Filter out system messages for Anthropic
+ 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:
+ msg_list = [{"role": "user", "content": prompt}]
+ system_content = system_prompt
+
+ data = {
+ "model": model,
+ "system": system_content,
+ "messages": msg_list,
+ "max_tokens": kwargs.get("max_tokens", 4096),
+ "temperature": kwargs.get("temperature", 0.7),
+ "stream": True,
+ }
+
+ timeout = aiohttp.ClientTimeout(total=300)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ 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}")
+
+ async for line in response.content:
+ line_str = line.decode("utf-8").strip()
+ if not line_str or not line_str.startswith("data:"):
+ continue
+
+ data_str = line_str[5:].strip()
+ if not data_str:
+ continue
+
+ try:
+ chunk_data = json.loads(data_str)
+ event_type = chunk_data.get("type")
+ if event_type == "content_block_delta":
+ delta = chunk_data.get("delta", {})
+ text = delta.get("text")
+ if text:
+ yield text
+ except json.JSONDecodeError:
+ continue
+
+
+async def fetch_models(
+ base_url: str,
+ api_key: Optional[str] = None,
+ binding: str = "openai",
+) -> List[str]:
+ """
+ Fetch available models from cloud provider.
+
+ Args:
+ base_url: API endpoint URL
+ api_key: API key
+ binding: Provider type (openai, anthropic)
+
+ Returns:
+ List of available model names
+ """
+ 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}"
+
+ timeout = aiohttp.ClientTimeout(total=30)
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ try:
+ url = f"{base_url}/models"
+ async with session.get(url, headers=headers) as resp:
+ if resp.status == 200:
+ data = await resp.json()
+ if "data" in data and isinstance(data["data"], list):
+ return [
+ m.get("id") or m.get("name")
+ for m in data["data"]
+ if m.get("id") or m.get("name")
+ ]
+ elif isinstance(data, list):
+ return [
+ m.get("id") or m.get("name") if isinstance(m, dict) else str(m)
+ for m in data
+ ]
+ return []
+ except Exception as e:
+ print(f"Error fetching models from {base_url}: {e}")
+ return []
+
+
+__all__ = [
+ "complete",
+ "stream",
+ "fetch_models",
+]
+
diff --git a/src/services/llm/config.py b/src/services/llm/config.py
index 3ded46d09..7c38a6dd4 100644
--- a/src/services/llm/config.py
+++ b/src/services/llm/config.py
@@ -4,13 +4,18 @@ LLM Configuration
=================
Configuration management for LLM services.
+
+Supports multiple deployment modes:
+- api: Cloud API providers only (OpenAI, Anthropic, etc.)
+- local: Local/self-hosted LLM servers only (Ollama, LM Studio, etc.)
+- hybrid: Both API and local, uses active provider (default)
"""
from dataclasses import dataclass
import os
from pathlib import Path
import re
-from typing import Optional
+from typing import Literal, Optional
from dotenv import load_dotenv
@@ -19,6 +24,11 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)
load_dotenv(PROJECT_ROOT / ".env", override=False)
+# LLM deployment modes
+LLM_MODE_API = "api"
+LLM_MODE_LOCAL = "local"
+LLM_MODE_HYBRID = "hybrid"
+
@dataclass
class LLMConfig:
@@ -30,6 +40,7 @@ class LLMConfig:
binding: str = "openai"
max_tokens: int = 4096
temperature: float = 0.7
+ provider_type: Literal["api", "local"] = "api" # Track if this is API or local config
def _strip_value(value: Optional[str]) -> Optional[str]:
@@ -39,12 +50,27 @@ def _strip_value(value: Optional[str]) -> Optional[str]:
return value.strip().strip("\"'")
+def get_llm_mode() -> str:
+ """
+ Get the current LLM deployment mode from environment.
+
+ Returns:
+ str: 'api', 'local', or 'hybrid' (default)
+ """
+ return os.getenv("LLM_MODE", LLM_MODE_HYBRID).lower()
+
+
def get_llm_config() -> LLMConfig:
"""
Load LLM configuration from environment variables or provider manager.
+ The behavior depends on the LLM_MODE environment variable:
+ - hybrid (default): Use active provider if available, else env config
+ - api: Only use API providers (active API provider or env config)
+ - local: Only use local providers (active local provider or env config)
+
Priority:
- 1. Active provider from llm_providers.json
+ 1. Active provider from llm_providers.json (if mode compatible)
2. Environment variables (.env)
Returns:
@@ -53,6 +79,8 @@ def get_llm_config() -> LLMConfig:
Raises:
ValueError: If required configuration is missing
"""
+ mode = get_llm_mode()
+
# 1. Try to get active provider from provider manager
try:
from .provider import provider_manager
@@ -60,12 +88,25 @@ def get_llm_config() -> LLMConfig:
active_provider = provider_manager.get_active_provider()
if active_provider:
- return LLMConfig(
- binding=active_provider.binding,
- model=active_provider.model,
- api_key=active_provider.api_key,
- base_url=active_provider.base_url,
- )
+ provider_is_local = getattr(active_provider, "provider_type", "local") == "local"
+
+ # Check mode compatibility
+ use_provider = False
+ if mode == LLM_MODE_HYBRID:
+ use_provider = True
+ elif mode == LLM_MODE_API and not provider_is_local:
+ use_provider = True
+ elif mode == LLM_MODE_LOCAL and provider_is_local:
+ use_provider = True
+
+ if use_provider:
+ return LLMConfig(
+ binding=active_provider.binding,
+ model=active_provider.model,
+ api_key=active_provider.api_key,
+ base_url=active_provider.base_url,
+ provider_type=getattr(active_provider, "provider_type", "local"),
+ )
except Exception as e:
print(f"⚠️ Failed to load active provider: {e}")
@@ -81,8 +122,15 @@ def get_llm_config() -> LLMConfig:
"Error: LLM_MODEL not set, please configure it in .env file or activate a provider"
)
- # Check if API key is required
- requires_key = os.getenv("LLM_API_KEY_REQUIRED", "true").lower() == "true"
+ # Determine provider type from base_url
+ from .utils import is_local_llm_server
+
+ provider_type: Literal["api", "local"] = "local" if is_local_llm_server(base_url) else "api"
+
+ # Check if API key is required (not required for local providers)
+ requires_key = (
+ provider_type == "api" or os.getenv("LLM_API_KEY_REQUIRED", "false").lower() == "true"
+ )
if requires_key and not api_key:
raise ValueError(
@@ -96,8 +144,9 @@ def get_llm_config() -> LLMConfig:
return LLMConfig(
binding=binding,
model=model,
- api_key=api_key,
+ api_key=api_key or "",
base_url=base_url,
+ provider_type=provider_type,
)
@@ -162,6 +211,10 @@ 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",
+ "LLM_MODE_LOCAL",
+ "LLM_MODE_HYBRID",
]
diff --git a/src/services/llm/factory.py b/src/services/llm/factory.py
new file mode 100644
index 000000000..6c93e748a
--- /dev/null
+++ b/src/services/llm/factory.py
@@ -0,0 +1,390 @@
+"""
+LLM Factory - Central Hub for LLM Calls
+=======================================
+
+This module serves as the central hub for all LLM calls in DeepTutor.
+It provides a unified interface for agents to call LLMs, routing requests
+to the appropriate provider (cloud or local) based on configuration.
+
+Architecture:
+ Agents (ChatAgent, GuideAgent, etc.)
+ ↓
+ BaseAgent.call_llm() / stream_llm()
+ ↓
+ LLM Factory (this module)
+ ↓
+ ┌─────────┴─────────┐
+ ↓ ↓
+CloudProvider LocalProvider
+(cloud_provider) (local_provider)
+ ↓ ↓
+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
+"""
+
+import os
+from enum import Enum
+from typing import Any, AsyncGenerator, Dict, List, Optional
+
+from . import cloud_provider, local_provider
+from .config import LLMConfig, get_llm_config
+from .provider import provider_manager
+from .utils import is_local_llm_server, sanitize_url
+
+
+class LLMMode(str, Enum):
+ """LLM deployment mode."""
+
+ API = "api" # Cloud API only
+ LOCAL = "local" # Local/self-hosted only
+ HYBRID = "hybrid" # Both, use active provider
+
+
+def get_llm_mode() -> LLMMode:
+ """
+ Get the current LLM deployment mode from environment.
+
+ Returns:
+ LLMMode: Current deployment mode (defaults to hybrid)
+ """
+ mode = os.getenv("LLM_MODE", "hybrid").lower()
+ if mode == "api":
+ return LLMMode.API
+ elif mode == "local":
+ return LLMMode.LOCAL
+ 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,
+ 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.
+
+ Args:
+ base_url: The base URL to check
+
+ Returns:
+ True if local provider should be used
+ """
+ mode = get_llm_mode()
+
+ if mode == LLMMode.API:
+ return False
+ elif mode == LLMMode.LOCAL:
+ return True
+ else: # HYBRID
+ return is_local_llm_server(base_url) if base_url else False
+
+
+def get_mode_info() -> Dict[str, Any]:
+ """
+ Get information about the current LLM configuration mode.
+
+ Returns:
+ Dict containing:
+ - mode: Current deployment mode
+ - active_provider: Active provider info (if any)
+ - env_configured: Whether env vars are properly configured
+ - effective_source: Which config source is being used
+ """
+ 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))
+
+ # Determine effective source
+ effective_source = "env"
+ if active_provider:
+ provider_is_local = active_provider.provider_type == "local"
+ if mode == LLMMode.HYBRID:
+ effective_source = "provider"
+ elif mode == LLMMode.API and not provider_is_local:
+ effective_source = "provider"
+ elif mode == LLMMode.LOCAL and provider_is_local:
+ effective_source = "provider"
+
+ return {
+ "mode": mode.value,
+ "active_provider": (
+ {
+ "name": active_provider.name,
+ "model": active_provider.model,
+ "provider_type": active_provider.provider_type,
+ "binding": active_provider.binding,
+ }
+ if active_provider
+ else None
+ ),
+ "env_configured": env_configured,
+ "effective_source": effective_source,
+ }
+
+
+async def complete(
+ prompt: str,
+ system_prompt: str = "You are a helpful assistant.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ binding: Optional[str] = None,
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> str:
+ """
+ Unified LLM completion function.
+
+ Routes to cloud_provider or local_provider based on configuration.
+
+ Args:
+ prompt: The user prompt
+ system_prompt: System prompt for context
+ model: Model name (optional, uses effective config if not provided)
+ api_key: API key (optional)
+ base_url: Base URL for the API (optional)
+ binding: Provider binding type (optional)
+ messages: Pre-built messages array (optional)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Returns:
+ str: The LLM response
+ """
+ # Get effective config if parameters not provided
+ if not model or not base_url:
+ config = get_effective_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
+ 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,
+ binding=binding or "openai",
+ **kwargs,
+ )
+
+
+async def stream(
+ prompt: str,
+ system_prompt: str = "You are a helpful assistant.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ binding: Optional[str] = None,
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> AsyncGenerator[str, None]:
+ """
+ Unified LLM streaming function.
+
+ Routes to cloud_provider or local_provider based on configuration.
+
+ Args:
+ prompt: The user prompt
+ system_prompt: System prompt for context
+ model: Model name (optional, uses effective config if not provided)
+ api_key: API key (optional)
+ base_url: Base URL for the API (optional)
+ binding: Provider binding type (optional)
+ messages: Pre-built messages array (optional)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Yields:
+ str: Response chunks
+ """
+ # Get effective config if parameters not provided
+ if not model or not base_url:
+ config = get_effective_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
+ 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,
+ binding=binding or "openai",
+ messages=messages,
+ **kwargs,
+ ):
+ yield chunk
+
+
+async def fetch_models(
+ binding: str,
+ base_url: str,
+ api_key: Optional[str] = None,
+) -> List[str]:
+ """
+ Fetch available models from the provider.
+
+ Routes to cloud_provider or local_provider based on URL.
+
+ Args:
+ binding: Provider type (openai, ollama, etc.)
+ base_url: API endpoint URL
+ api_key: API key (optional for local providers)
+
+ Returns:
+ List of available model names
+ """
+ if is_local_llm_server(base_url):
+ return await local_provider.fetch_models(base_url, api_key)
+ else:
+ return await cloud_provider.fetch_models(base_url, api_key, binding)
+
+
+# API Provider Presets
+API_PROVIDER_PRESETS = {
+ "openai": {
+ "name": "OpenAI",
+ "base_url": "https://api.openai.com/v1",
+ "requires_key": True,
+ "models": ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-3.5-turbo"],
+ },
+ "anthropic": {
+ "name": "Anthropic",
+ "base_url": "https://api.anthropic.com/v1",
+ "requires_key": True,
+ "binding": "anthropic",
+ "models": ["claude-3-5-sonnet-20241022", "claude-3-haiku-20240307"],
+ },
+ "deepseek": {
+ "name": "DeepSeek",
+ "base_url": "https://api.deepseek.com",
+ "requires_key": True,
+ "models": ["deepseek-chat", "deepseek-reasoner"],
+ },
+ "openrouter": {
+ "name": "OpenRouter",
+ "base_url": "https://openrouter.ai/api/v1",
+ "requires_key": True,
+ "models": [], # Dynamic
+ },
+}
+
+# Local Provider Presets
+LOCAL_PROVIDER_PRESETS = {
+ "ollama": {
+ "name": "Ollama",
+ "base_url": "http://localhost:11434/v1",
+ "requires_key": False,
+ "default_key": "ollama",
+ },
+ "lm_studio": {
+ "name": "LM Studio",
+ "base_url": "http://localhost:1234/v1",
+ "requires_key": False,
+ "default_key": "lm-studio",
+ },
+ "vllm": {
+ "name": "vLLM",
+ "base_url": "http://localhost:8000/v1",
+ "requires_key": False,
+ "default_key": "vllm",
+ },
+ "llama_cpp": {
+ "name": "llama.cpp",
+ "base_url": "http://localhost:8080/v1",
+ "requires_key": False,
+ "default_key": "llama-cpp",
+ },
+}
+
+
+def get_provider_presets() -> Dict[str, Any]:
+ """
+ Get all provider presets for frontend display.
+ """
+ return {
+ "api": API_PROVIDER_PRESETS,
+ "local": LOCAL_PROVIDER_PRESETS,
+ }
+
+
+__all__ = [
+ "LLMMode",
+ "get_llm_mode",
+ "get_effective_config",
+ "get_mode_info",
+ "complete",
+ "stream",
+ "fetch_models",
+ "get_provider_presets",
+ "API_PROVIDER_PRESETS",
+ "LOCAL_PROVIDER_PRESETS",
+]
diff --git a/src/services/llm/local_provider.py b/src/services/llm/local_provider.py
new file mode 100644
index 000000000..28046db21
--- /dev/null
+++ b/src/services/llm/local_provider.py
@@ -0,0 +1,373 @@
+"""
+Local LLM Provider
+==================
+
+Handles all local/self-hosted LLM calls (LM Studio, Ollama, vLLM, llama.cpp, etc.)
+Uses aiohttp instead of httpx for better compatibility with local servers.
+
+Key features:
+- Uses aiohttp (httpx has known 502 issues with some local servers like LM Studio)
+- Handles thinking tags (<think>) from reasoning models like Qwen
+- Extended timeouts for potentially slower local inference
+"""
+
+import json
+import re
+from typing import AsyncGenerator, Dict, List, Optional
+
+import aiohttp
+
+from .utils import 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.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> str:
+ """
+ Complete a prompt using local LLM server.
+
+ Uses aiohttp for better compatibility with local servers.
+
+ Args:
+ prompt: The user prompt (ignored if messages provided)
+ system_prompt: System prompt for context
+ model: Model name
+ api_key: API key (optional for most local servers)
+ base_url: Base URL for the local server
+ messages: Pre-built messages array (optional)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Returns:
+ str: The LLM response
+ """
+ if not base_url:
+ raise ValueError("base_url is required for local LLM provider")
+
+ # Sanitize URL
+ base_url = sanitize_url(base_url, model or "")
+
+ 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 messages
+ if messages:
+ msg_list = messages
+ else:
+ msg_list = [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": prompt},
+ ]
+
+ # Build request data
+ data = {
+ "model": model or "default",
+ "messages": msg_list,
+ "temperature": kwargs.get("temperature", 0.7),
+ "stream": False,
+ }
+
+ # Add optional parameters
+ if kwargs.get("max_tokens"):
+ data["max_tokens"] = kwargs["max_tokens"]
+
+ timeout = aiohttp.ClientTimeout(total=kwargs.get("timeout", DEFAULT_TIMEOUT))
+
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ 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}")
+
+ 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)
+ return content
+
+ return ""
+
+
+async def stream(
+ prompt: str,
+ system_prompt: str = "You are a helpful assistant.",
+ model: Optional[str] = None,
+ api_key: Optional[str] = None,
+ base_url: Optional[str] = None,
+ messages: Optional[List[Dict[str, str]]] = None,
+ **kwargs,
+) -> AsyncGenerator[str, None]:
+ """
+ Stream a response from local LLM server.
+
+ Uses aiohttp for better compatibility with local servers.
+ Falls back to non-streaming if streaming fails.
+
+ Args:
+ prompt: The user prompt (ignored if messages provided)
+ system_prompt: System prompt for context
+ model: Model name
+ api_key: API key (optional for most local servers)
+ base_url: Base URL for the local server
+ messages: Pre-built messages array (optional)
+ **kwargs: Additional parameters (temperature, max_tokens, etc.)
+
+ Yields:
+ str: Response chunks
+ """
+ if not base_url:
+ raise ValueError("base_url is required for local LLM provider")
+
+ # Sanitize URL
+ base_url = sanitize_url(base_url, model or "")
+
+ 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 messages
+ if messages:
+ msg_list = messages
+ else:
+ msg_list = [
+ {"role": "system", "content": system_prompt},
+ {"role": "user", "content": prompt},
+ ]
+
+ # Build request data
+ data = {
+ "model": model or "default",
+ "messages": msg_list,
+ "temperature": kwargs.get("temperature", 0.7),
+ "stream": True,
+ }
+
+ if kwargs.get("max_tokens"):
+ data["max_tokens"] = kwargs["max_tokens"]
+
+ timeout = aiohttp.ClientTimeout(total=kwargs.get("timeout", DEFAULT_TIMEOUT))
+
+ try:
+ 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}")
+
+ # Track if we're inside a thinking block
+ in_thinking_block = False
+ thinking_buffer = ""
+
+ async for line in response.content:
+ line_str = line.decode("utf-8").strip()
+
+ # Skip empty lines
+ if not line_str:
+ continue
+
+ # Handle SSE format
+ if line_str.startswith("data:"):
+ data_str = line_str[5:].strip()
+
+ if data_str == "[DONE]":
+ break
+
+ try:
+ chunk_data = json.loads(data_str)
+ if "choices" in chunk_data and chunk_data["choices"]:
+ delta = chunk_data["choices"][0].get("delta", {})
+ content = delta.get("content")
+
+ 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
+ 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)
+ if cleaned:
+ yield cleaned
+ in_thinking_block = False
+ thinking_buffer = ""
+ continue
+ else:
+ yield content
+
+ except json.JSONDecodeError:
+ # Non-JSON response, might be raw text
+ if data_str and not data_str.startswith("{"):
+ yield data_str
+
+ # Some servers don't use SSE format
+ elif line_str.startswith("{"):
+ try:
+ chunk_data = json.loads(line_str)
+ if "choices" in chunk_data and chunk_data["choices"]:
+ delta = chunk_data["choices"][0].get("delta", {})
+ content = delta.get("content")
+ if content:
+ yield content
+ except json.JSONDecodeError:
+ pass
+
+ except Exception as e:
+ # Streaming failed, fall back to non-streaming
+ print(f"⚠️ Streaming failed ({e}), falling back to non-streaming")
+
+ try:
+ content = await complete(
+ prompt=prompt,
+ system_prompt=system_prompt,
+ model=model,
+ api_key=api_key,
+ base_url=base_url,
+ messages=messages,
+ **kwargs,
+ )
+ if content:
+ yield content
+ except Exception as e2:
+ raise Exception(f"Local LLM failed: streaming={e}, non-streaming={e2}")
+
+
+async def fetch_models(
+ base_url: str,
+ api_key: Optional[str] = None,
+) -> List[str]:
+ """
+ Fetch available models from local LLM server.
+
+ Supports:
+ - Ollama (/api/tags)
+ - OpenAI-compatible (/models)
+
+ Args:
+ base_url: Base URL for the local server
+ api_key: API key (optional)
+
+ Returns:
+ List of available model names
+ """
+ base_url = base_url.rstrip("/")
+
+ headers = {}
+ if api_key:
+ headers["Authorization"] = f"Bearer {api_key}"
+
+ timeout = aiohttp.ClientTimeout(total=30)
+
+ async with aiohttp.ClientSession(timeout=timeout) as session:
+ # Try Ollama /api/tags first
+ is_ollama = ":11434" in base_url or "ollama" in base_url.lower()
+ if is_ollama:
+ try:
+ ollama_url = base_url.replace("/v1", "") + "/api/tags"
+ async with session.get(ollama_url, headers=headers) as resp:
+ if resp.status == 200:
+ data = await resp.json()
+ if "models" in data:
+ return [m["name"] for m in data.get("models", [])]
+ except Exception:
+ pass
+
+ # Try OpenAI-compatible /models
+ try:
+ models_url = f"{base_url}/models"
+ async with session.get(models_url, headers=headers) as resp:
+ if resp.status == 200:
+ data = await resp.json()
+
+ # Handle different response formats
+ if "data" in data and isinstance(data["data"], list):
+ return [
+ m.get("id") or m.get("name")
+ for m in data["data"]
+ if m.get("id") or m.get("name")
+ ]
+ elif "models" in data and isinstance(data["models"], list):
+ if data["models"] and isinstance(data["models"][0], dict):
+ return [
+ m.get("id") or m.get("name")
+ for m in data["models"]
+ if m.get("id") or m.get("name")
+ ]
+ return [str(m) for m in data["models"]]
+ elif isinstance(data, list):
+ return [
+ m.get("id") or m.get("name") if isinstance(m, dict) else str(m)
+ for m in data
+ ]
+ except Exception as e:
+ print(f"Error fetching models from {base_url}: {e}")
+
+ return []
+
+
+__all__ = [
+ "complete",
+ "stream",
+ "fetch_models",
+]
+
diff --git a/src/services/llm/provider.py b/src/services/llm/provider.py
index 9486524bb..c4925bd18 100644
--- a/src/services/llm/provider.py
+++ b/src/services/llm/provider.py
@@ -3,11 +3,13 @@ LLM Provider Management
=======================
Manages LLM provider configurations, persisting them to a JSON file.
+Supports both API (cloud) and Local (self-hosted) providers.
"""
+from enum import Enum
import json
from pathlib import Path
-from typing import Any, Dict, List, Optional
+from typing import Any, Dict, List, Literal, Optional
from pydantic import BaseModel, Field
@@ -16,17 +18,34 @@ USER_DATA_DIR = Path("./data/user")
PROVIDERS_FILE = USER_DATA_DIR / "llm_providers.json"
+class ProviderType(str, Enum):
+ """Type of LLM provider."""
+
+ API = "api" # Cloud API providers (OpenAI, Anthropic, DeepSeek, etc.)
+ LOCAL = "local" # Local/self-hosted (Ollama, LM Studio, vLLM, etc.)
+
+
class LLMProvider(BaseModel):
"""
Configuration model for a single LLM provider.
+
+ Supports both API (cloud) and Local (self-hosted) providers.
"""
name: str = Field(..., description="Unique name for the provider configuration")
binding: str = Field(..., description="Provider type (e.g., openai, azure_openai, ollama)")
base_url: str = Field(..., description="API endpoint URL")
- api_key: str = Field(..., description="API Key")
+ api_key: str = Field(default="", description="API Key (optional for local providers)")
model: str = Field(..., description="Model name to use")
is_active: bool = Field(default=False, description="Whether this provider is currently active")
+ provider_type: Literal["api", "local"] = Field(
+ default="local",
+ description="Provider type: 'api' for cloud services, 'local' for self-hosted",
+ )
+ requires_key: bool = Field(
+ default=False,
+ description="Whether this provider requires an API key",
+ )
class Config:
populate_by_name = True
@@ -168,6 +187,7 @@ provider_manager = LLMProviderManager()
__all__ = [
+ "ProviderType",
"LLMProvider",
"LLMProviderManager",
"provider_manager",
diff --git a/src/services/llm/utils.py b/src/services/llm/utils.py
new file mode 100644
index 000000000..9f6e25afb
--- /dev/null
+++ b/src/services/llm/utils.py
@@ -0,0 +1,79 @@
+"""
+LLM URL Utilities
+=================
+
+Utility functions for handling LLM API URLs, especially for local servers.
+"""
+
+
+def sanitize_url(base_url: str, model: str = "") -> str:
+ """
+ Sanitize base URL for OpenAI-compatible APIs, with special handling for local LLM servers.
+
+ Handles:
+ - Ollama (port 11434)
+ - LM Studio (port 1234)
+ - Other localhost OpenAI-compatible servers
+
+ Args:
+ base_url: The base URL to sanitize
+ model: Optional model name (unused, kept for API compatibility)
+
+ Returns:
+ Sanitized URL string
+ """
+ if not base_url:
+ return base_url
+
+ url = base_url.rstrip("/")
+
+ # Ensure URL has a protocol (default to http for local servers)
+ if url and not url.startswith(("http://", "https://")):
+ url = "http://" + url
+
+ # Standard OpenAI client library is strict about URLs:
+ # - No trailing slashes
+ # - No /chat/completions or /completions/messages/embeddings suffixes
+ # (it adds these automatically)
+ for suffix in ["/chat/completions", "/completions", "/messages", "/embeddings"]:
+ if url.endswith(suffix):
+ 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"):
+ url = url.rstrip("/") + "/v1"
+
+ return url
+
+
+def is_local_llm_server(base_url: str) -> bool:
+ """
+ Check if the given URL points to a local LLM server.
+
+ 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()
+ return any(
+ indicator in base_url_lower
+ for indicator in ["localhost", "127.0.0.1", "0.0.0.0", ":1234", ":11434"]
+ )
+
+
+__all__ = ["sanitize_url", "is_local_llm_server"]
+
diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsx
index 7634bd710..919e453ff 100644
--- a/web/app/settings/page.tsx
+++ b/web/app/settings/page.tsx
@@ -129,10 +129,24 @@ interface LLMProvider {
api_key: string;
model: string;
is_active: boolean;
+ provider_type: "api" | "local";
+ requires_key: boolean;
+}
+
+interface LLMModeInfo {
+ mode: "api" | "local" | "hybrid";
+ active_provider: {
+ name: string;
+ model: string;
+ provider_type: "api" | "local";
+ binding: string;
+ } | null;
+ env_configured: boolean;
+ effective_source: "env" | "provider";
}
// Tab types
-type SettingsTab = "general" | "environment" | "llm_providers";
+type SettingsTab = "general" | "environment" | "local_models";
export default function SettingsPage() {
const { uiSettings, refreshSettings } = useGlobal();
@@ -168,10 +182,11 @@ export default function SettingsPage() {
help_text?: string;
}
+ // Local deployment presets only - cloud providers should use Environment Variables tab
const PROVIDER_PRESETS: ProviderPreset[] = [
{
id: "ollama",
- name: "Ollama (Local / Cloud)",
+ name: "Ollama",
binding: "openai",
base_url: "http://localhost:11434/v1",
default_model: "llama3.2",
@@ -179,101 +194,58 @@ export default function SettingsPage() {
"llama3.2",
"llama3.3",
"qwen2.5",
+ "qwen3",
"mistral-nemo",
"deepseek-r1",
- "kimi-k2-thinking",
- "qwen3-next:80b",
+ "gemma2",
+ "phi3",
],
- requires_key: true,
+ requires_key: false,
help_text:
- "Uses the OpenAI-compatible protocol. For Local: http://localhost:11434/v1. For Cloud: https://ollama.com/v1.",
- },
- {
- id: "openai",
- name: "OpenAI",
- binding: "openai",
- base_url: "https://api.openai.com/v1",
- default_model: "gpt-4o",
- models: ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "o1-preview"],
- requires_key: true,
- help_text: "Requires an OpenAI API Key.",
- },
- {
- id: "anthropic",
- name: "Anthropic (Claude)",
- binding: "anthropic",
- base_url: "https://api.anthropic.com/v1/messages",
- default_model: "claude-3-5-sonnet-latest",
- models: [
- "claude-3-5-sonnet-latest",
- "claude-3-5-haiku-latest",
- "claude-3-opus-latest",
- ],
- requires_key: true,
- help_text: "Anthropic uses its own custom protocol (Native Binding).",
- },
- {
- id: "gemini",
- name: "Google Gemini",
- binding: "openai",
- base_url: "https://generativelanguage.googleapis.com/v1beta/openai",
- default_model: "gemini-1.5-pro",
- models: ["gemini-1.5-pro", "gemini-1.5-flash", "gemini-2.0-flash-exp"],
- requires_key: true,
- help_text: "Google Gemini uses the OpenAI-compatible framework.",
+ "Ollama runs models locally. Default: http://localhost:11434/v1. Run 'ollama serve' first.",
},
{
- id: "openrouter",
- name: "OpenRouter",
+ id: "lmstudio",
+ name: "LM Studio",
binding: "openai",
- base_url: "https://openrouter.ai/api/v1",
- default_model: "anthropic/claude-3.5-sonnet",
- models: [
- "anthropic/claude-3.5-sonnet",
- "google/gemini-2.0-flash-thinking-exp:free",
- "deepseek/deepseek-chat",
- ],
- requires_key: true,
+ base_url: "http://127.0.0.1:1234",
+ default_model: "local-model",
+ models: [],
+ requires_key: false,
help_text:
- "OpenRouter uses the OpenAI-compatible framework to access any model.",
+ "LM Studio provides a local OpenAI-compatible API. Default port: 1234. Use 'Refresh Models' to auto-detect loaded models.",
},
{
- id: "deepseek",
- name: "DeepSeek",
+ id: "llamacpp",
+ name: "llama.cpp Server",
binding: "openai",
- base_url: "https://api.deepseek.com",
- default_model: "deepseek-chat",
- models: ["deepseek-chat", "deepseek-reasoner"],
- requires_key: true,
- help_text: "DeepSeek uses the OpenAI-compatible framework.",
+ base_url: "http://localhost:8080/v1",
+ default_model: "local-model",
+ models: [],
+ requires_key: false,
+ help_text:
+ "llama.cpp server with OpenAI-compatible API. Default port: 8080.",
},
{
- id: "groq",
- name: "Groq",
+ id: "vllm",
+ name: "vLLM",
binding: "openai",
- base_url: "https://api.groq.com/openai/v1",
- default_model: "llama-3.3-70b-versatile",
- models: [
- "llama-3.3-70b-versatile",
- "llama-3.1-70b-versatile",
- "llama-3.1-8b-instant",
- "mixtral-8x7b-32768",
- "gemma2-9b-it",
- ],
- requires_key: true,
- help_text:
- "Groq uses the OpenAI-compatible framework for ultra-fast inference.",
+ base_url: "http://localhost:8000/v1",
+ default_model: "local-model",
+ models: [],
+ requires_key: false,
+ help_text: "vLLM high-throughput inference server. Default port: 8000.",
},
{
- id: "lmstudio",
- name: "LM Studio (Local)",
+ id: "custom",
+ name: "Custom Local Server",
binding: "openai",
- base_url: "http://localhost:1234/v1",
- default_model: "uploaded-model",
+ base_url: "http://localhost:8000/v1",
+ default_model: "",
models: [],
requires_key: false,
help_text:
- "LM Studio uses the OpenAI-compatible framework locally. Standard port: 1234.",
+ "Any OpenAI-compatible local server. Configure the URL and model manually.",
},
];
@@ -290,6 +262,22 @@ export default function SettingsPage() {
const [envError, setEnvError] = useState("");
const [testResults, setTestResults] = useState<TestResults | null>(null);
const [testing, setTesting] = useState(false);
+ // Individual service testing states
+ const [testingService, setTestingService] = useState<Record<string, boolean>>(
+ {},
+ );
+ const [serviceTestResults, setServiceTestResults] = useState<
+ Record<
+ string,
+ {
+ status: string;
+ model: string | null;
+ error: string | null;
+ response_time_ms: number | null;
+ message: string | null;
+ }
+ >
+ >({});
// LLM Providers state
const [providers, setProviders] = useState<LLMProvider[]>([]);
@@ -313,6 +301,12 @@ export default function SettingsPage() {
string | null
>(null);
+ // LLM Mode state
+ const [llmModeInfo, setLlmModeInfo] = useState<LLMModeInfo | null>(null);
+ const [providerTypeFilter, setProviderTypeFilter] = useState<
+ "all" | "api" | "local"
+ >("all");
+
// Create debounced theme save function
const debouncedSaveTheme = useRef(
debounce(async (themeValue: "light" | "dark", uiSettings: UISettings) => {
@@ -345,11 +339,24 @@ export default function SettingsPage() {
fetchSettings();
fetchEnvConfig();
fetchRagProviders();
- if (activeTab === "llm_providers") {
+ fetchLLMMode();
+ if (activeTab === "local_models") {
fetchProviders();
}
}, [uiSettings, activeTab]);
+ const fetchLLMMode = async () => {
+ try {
+ const res = await fetch(apiUrl("/api/v1/config/llm/mode/"));
+ if (res.ok) {
+ const data = await res.json();
+ setLlmModeInfo(data);
+ }
+ } catch (err) {
+ console.error("Failed to fetch LLM mode:", err);
+ }
+ };
+
const fetchProviders = async () => {
setLoadingProviders(true);
try {
@@ -700,6 +707,48 @@ export default function SettingsPage() {
}
};
+ // Test a single service (llm, embedding, tts)
+ const testSingleService = async (service: "llm" | "embedding" | "tts") => {
+ setTestingService((prev) => ({ ...prev, [service]: true }));
+ try {
+ const res = await fetch(apiUrl(`/api/v1/settings/env/test/${service}`), {
+ method: "POST",
+ });
+ if (res.ok) {
+ const result = await res.json();
+ setServiceTestResults((prev) => ({ ...prev, [service]: result }));
+ // Also update testResults for status icons
+ setTestResults((prev) =>
+ prev
+ ? {
+ ...prev,
+ [service]: {
+ status:
+ result.status === "success" ? "configured" : result.status,
+ model: result.model,
+ error: result.error,
+ },
+ }
+ : null,
+ );
+ }
+ } catch (err) {
+ console.error(`Failed to test ${service}:`, err);
+ setServiceTestResults((prev) => ({
+ ...prev,
+ [service]: {
+ status: "error",
+ model: null,
+ error: "Connection failed",
+ response_time_ms: null,
+ message: null,
+ },
+ }));
+ } finally {
+ setTestingService((prev) => ({ ...prev, [service]: false }));
+ }
+ };
+
const getCategoryIcon = (iconName: string) => {
switch (iconName) {
case "brain":
@@ -923,7 +972,7 @@ export default function SettingsPage() {
</div>
{/* Tab Navigation */}
- <div className="flex items-center gap-1 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-6">
+ <div className="flex items-center gap-1 p-1 bg-slate-100 dark:bg-slate-800 rounded-xl mb-4">
<button
onClick={() => setActiveTab("general")}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${
@@ -962,18 +1011,265 @@ export default function SettingsPage() {
)}
</button>
<button
- onClick={() => setActiveTab("llm_providers")}
+ onClick={() => setActiveTab("local_models")}
className={`flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all ${
- activeTab === "llm_providers"
+ activeTab === "local_models"
? "bg-white dark:bg-slate-700 text-blue-600 dark:text-blue-400 shadow-sm"
: "text-slate-600 dark:text-slate-400 hover:text-slate-900 dark:hover:text-slate-200"
}`}
>
- <Brain className="w-4 h-4" />
- LLM Providers
+ <Server className="w-4 h-4" />
+ {t("LLM Providers")}
+ {llmModeInfo && (
+ <span
+ className={`ml-1 px-1.5 py-0.5 text-[9px] rounded font-medium ${
+ llmModeInfo.mode === "hybrid"
+ ? "bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400"
+ : llmModeInfo.mode === "api"
+ ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"
+ : "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"
+ }`}
+ >
+ {llmModeInfo.mode.toUpperCase()}
+ </span>
+ )}
</button>
</div>
+ {/* Configuration Status Panel - Quick Test */}
+ <div className="mb-6 bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
+ <div className="px-4 py-2.5 border-b border-slate-100 dark:border-slate-700 bg-gradient-to-r from-slate-50 to-blue-50/30 dark:from-slate-800/50 dark:to-blue-900/20 flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <Cpu className="w-4 h-4 text-blue-500 dark:text-blue-400" />
+ <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
+ {t("Configuration Status")}
+ </h2>
+ </div>
+ <span className="text-[10px] text-slate-500 dark:text-slate-400">
+ {t("Click each card to test")}
+ </span>
+ </div>
+ <div className="p-3">
+ <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
+ {/* LLM Status */}
+ <div
+ className={`p-3 rounded-lg border transition-all ${
+ serviceTestResults.llm?.status === "success" ||
+ testResults?.llm?.status === "configured"
+ ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"
+ : serviceTestResults.llm?.status === "error" ||
+ testResults?.llm?.status === "error"
+ ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
+ : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <Brain className="w-4 h-4 text-purple-500" />
+ <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">
+ LLM
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {serviceTestResults.llm?.response_time_ms && (
+ <span className="text-[9px] text-slate-400">
+ {serviceTestResults.llm.response_time_ms}ms
+ </span>
+ )}
+ {(serviceTestResults.llm || testResults?.llm) &&
+ getStatusIcon(
+ serviceTestResults.llm?.status === "success"
+ ? "configured"
+ : serviceTestResults.llm?.status ||
+ testResults?.llm?.status ||
+ "unknown",
+ )}
+ </div>
+ </div>
+ <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">
+ {serviceTestResults.llm?.model ||
+ testResults?.llm?.model ||
+ editedEnvVars["LLM_MODEL"] ||
+ t("Not configured")}
+ </p>
+ <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">
+ {editedEnvVars["LLM_HOST"]
+ ? editedEnvVars["LLM_HOST"].includes("localhost") ||
+ editedEnvVars["LLM_HOST"].includes("127.0.0.1")
+ ? `🏠 ${editedEnvVars["LLM_HOST"]}`
+ : `☁️ ${editedEnvVars["LLM_HOST"]}`
+ : t("No endpoint")}
+ </p>
+ {serviceTestResults.llm?.message && (
+ <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">
+ {serviceTestResults.llm.message}
+ </p>
+ )}
+ {serviceTestResults.llm?.error && (
+ <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">
+ {serviceTestResults.llm.error}
+ </p>
+ )}
+ <button
+ onClick={() => testSingleService("llm")}
+ disabled={testingService.llm}
+ className="w-full py-1.5 text-[10px] font-medium text-purple-600 dark:text-purple-400 bg-purple-50 dark:bg-purple-900/30 hover:bg-purple-100 dark:hover:bg-purple-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-purple-200 dark:border-purple-800 disabled:opacity-50"
+ >
+ {testingService.llm ? (
+ <Loader2 className="w-3 h-3 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3 h-3" />
+ )}
+ {testingService.llm ? t("Testing...") : t("Test LLM")}
+ </button>
+ </div>
+
+ {/* Embedding Status */}
+ <div
+ className={`p-3 rounded-lg border transition-all ${
+ serviceTestResults.embedding?.status === "success" ||
+ testResults?.embedding?.status === "configured"
+ ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"
+ : serviceTestResults.embedding?.status === "error" ||
+ testResults?.embedding?.status === "error"
+ ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
+ : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <Database className="w-4 h-4 text-indigo-500" />
+ <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">
+ Embedding
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {serviceTestResults.embedding?.response_time_ms && (
+ <span className="text-[9px] text-slate-400">
+ {serviceTestResults.embedding.response_time_ms}ms
+ </span>
+ )}
+ {(serviceTestResults.embedding || testResults?.embedding) &&
+ getStatusIcon(
+ serviceTestResults.embedding?.status === "success"
+ ? "configured"
+ : serviceTestResults.embedding?.status ||
+ testResults?.embedding?.status ||
+ "unknown",
+ )}
+ </div>
+ </div>
+ <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">
+ {serviceTestResults.embedding?.model ||
+ testResults?.embedding?.model ||
+ editedEnvVars["EMBEDDING_MODEL"] ||
+ t("Not configured")}
+ </p>
+ <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">
+ {editedEnvVars["EMBEDDING_HOST"]
+ ? editedEnvVars["EMBEDDING_HOST"].includes("localhost") ||
+ editedEnvVars["EMBEDDING_HOST"].includes("127.0.0.1")
+ ? `🏠 ${editedEnvVars["EMBEDDING_HOST"]}`
+ : `☁️ ${editedEnvVars["EMBEDDING_HOST"]}`
+ : t("No endpoint")}
+ </p>
+ {serviceTestResults.embedding?.message && (
+ <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">
+ {serviceTestResults.embedding.message}
+ </p>
+ )}
+ {serviceTestResults.embedding?.error && (
+ <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">
+ {serviceTestResults.embedding.error}
+ </p>
+ )}
+ <button
+ onClick={() => testSingleService("embedding")}
+ disabled={testingService.embedding}
+ className="w-full py-1.5 text-[10px] font-medium text-indigo-600 dark:text-indigo-400 bg-indigo-50 dark:bg-indigo-900/30 hover:bg-indigo-100 dark:hover:bg-indigo-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-indigo-200 dark:border-indigo-800 disabled:opacity-50"
+ >
+ {testingService.embedding ? (
+ <Loader2 className="w-3 h-3 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3 h-3" />
+ )}
+ {testingService.embedding
+ ? t("Testing...")
+ : t("Test Embedding")}
+ </button>
+ </div>
+
+ {/* TTS Status */}
+ <div
+ className={`p-3 rounded-lg border transition-all ${
+ serviceTestResults.tts?.status === "success" ||
+ testResults?.tts?.status === "configured"
+ ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"
+ : serviceTestResults.tts?.status === "error" ||
+ testResults?.tts?.status === "error"
+ ? "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
+ : "bg-slate-50 dark:bg-slate-700/50 border-slate-200 dark:border-slate-600"
+ }`}
+ >
+ <div className="flex items-center justify-between mb-2">
+ <div className="flex items-center gap-2">
+ <Volume2 className="w-4 h-4 text-rose-500" />
+ <span className="text-xs font-semibold text-slate-700 dark:text-slate-200">
+ TTS
+ </span>
+ </div>
+ <div className="flex items-center gap-1.5">
+ {serviceTestResults.tts?.response_time_ms && (
+ <span className="text-[9px] text-slate-400">
+ {serviceTestResults.tts.response_time_ms}ms
+ </span>
+ )}
+ {(serviceTestResults.tts || testResults?.tts) &&
+ getStatusIcon(
+ serviceTestResults.tts?.status === "success"
+ ? "configured"
+ : serviceTestResults.tts?.status ||
+ testResults?.tts?.status ||
+ "unknown",
+ )}
+ </div>
+ </div>
+ <p className="text-[10px] text-slate-600 dark:text-slate-400 font-mono truncate mb-1">
+ {serviceTestResults.tts?.model ||
+ testResults?.tts?.model ||
+ editedEnvVars["TTS_MODEL"] ||
+ t("Not configured")}
+ </p>
+ <p className="text-[10px] text-slate-500 dark:text-slate-500 truncate mb-2">
+ {editedEnvVars["TTS_URL"] || t("No endpoint")}
+ </p>
+ {serviceTestResults.tts?.message && (
+ <p className="text-[9px] text-green-600 dark:text-green-400 truncate mb-2">
+ {serviceTestResults.tts.message}
+ </p>
+ )}
+ {serviceTestResults.tts?.error && (
+ <p className="text-[9px] text-red-600 dark:text-red-400 truncate mb-2">
+ {serviceTestResults.tts.error}
+ </p>
+ )}
+ <button
+ onClick={() => testSingleService("tts")}
+ disabled={testingService.tts}
+ className="w-full py-1.5 text-[10px] font-medium text-rose-600 dark:text-rose-400 bg-rose-50 dark:bg-rose-900/30 hover:bg-rose-100 dark:hover:bg-rose-900/50 rounded flex items-center justify-center gap-1.5 transition-colors border border-rose-200 dark:border-rose-800 disabled:opacity-50"
+ >
+ {testingService.tts ? (
+ <Loader2 className="w-3 h-3 animate-spin" />
+ ) : (
+ <RefreshCw className="w-3 h-3" />
+ )}
+ {testingService.tts ? t("Testing...") : t("Test TTS")}
+ </button>
+ </div>
+ </div>
+ </div>
+ </div>
+
{error && (
<div className="mb-6 p-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-xl flex items-center gap-3 text-red-700 dark:text-red-400 font-medium">
<AlertCircle className="w-5 h-5" />
@@ -1323,78 +1619,6 @@ export default function SettingsPage() {
{/* Environment Variables Tab */}
{activeTab === "environment" && envConfig && (
<div className="space-y-4">
- {/* Status Overview */}
- <section className="bg-white dark:bg-slate-800 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700 overflow-hidden">
- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-slate-50/50 dark:bg-slate-800/50 flex items-center justify-between">
- <div className="flex items-center gap-2">
- <Cpu className="w-4 h-4 text-blue-500 dark:text-blue-400" />
- <h2 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
- {t("Configuration Status")}
- </h2>
- </div>
- <button
- onClick={testEnvConfig}
- disabled={testing}
- className="px-2.5 py-1 text-xs font-medium text-slate-600 dark:text-slate-300 bg-slate-100 dark:bg-slate-700 hover:bg-slate-200 dark:hover:bg-slate-600 rounded-md flex items-center gap-1.5 transition-colors"
- >
- {testing ? (
- <Loader2 className="w-3 h-3 animate-spin" />
- ) : (
- <RefreshCw className="w-3 h-3" />
- )}
- {t("Refresh Status")}
- </button>
- </div>
-
- <div className="p-4">
- {/* Info Banner */}
- <div className="mb-3 p-2.5 bg-blue-50 dark:bg-blue-900/20 border border-blue-100 dark:border-blue-800 rounded-lg text-[11px] text-blue-700 dark:text-blue-300 flex items-start gap-2">
- <Info className="w-3.5 h-3.5 mt-0.5 flex-shrink-0" />
- <p>
- <span className="font-medium">
- {t("Runtime Configuration")}:
- </span>{" "}
- <code className="bg-blue-100 dark:bg-blue-800 px-1 rounded text-[10px]">
- .env
- </code>{" "}
- {t("file on startup")}.{" "}
- {t(
- "Changes made here take effect immediately but are not saved to file",
- )}
- .
- </p>
- </div>
-
- {/* Test Results */}
- {testResults && (
- <div className="grid grid-cols-3 gap-2">
- {Object.entries(testResults).map(([key, result]) => (
- <div
- key={key}
- className={`p-2.5 rounded-lg border ${
- result.status === "configured"
- ? "bg-green-50 dark:bg-green-900/20 border-green-200 dark:border-green-800"
- : result.status === "not_configured"
- ? "bg-amber-50 dark:bg-amber-900/20 border-amber-200 dark:border-amber-800"
- : "bg-red-50 dark:bg-red-900/20 border-red-200 dark:border-red-800"
- }`}
- >
- <div className="flex items-center gap-1.5 mb-1">
- {getStatusIcon(result.status)}
- <span className="text-xs font-semibold uppercase text-slate-700 dark:text-slate-200">
- {key}
- </span>
- </div>
- <p className="text-[10px] text-slate-600 dark:text-slate-400 truncate font-mono">
- {result.model || result.error || "Not configured"}
- </p>
- </div>
- ))}
- </div>
- )}
- </div>
- </section>
-
{/* Environment Variables by Category - 2-column layout */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
{envConfig.categories.map((category) => {
@@ -1515,16 +1739,96 @@ export default function SettingsPage() {
)}
{/* LLM Providers Tab */}
- {activeTab === "llm_providers" && (
+ {activeTab === "local_models" && (
<div className="space-y-4">
+ {/* LLM Mode Status Banner */}
+ {llmModeInfo && (
+ <div
+ className={`p-4 rounded-xl border ${
+ llmModeInfo.mode === "hybrid"
+ ? "bg-purple-50 dark:bg-purple-900/20 border-purple-200 dark:border-purple-800"
+ : llmModeInfo.mode === "api"
+ ? "bg-blue-50 dark:bg-blue-900/20 border-blue-200 dark:border-blue-800"
+ : "bg-emerald-50 dark:bg-emerald-900/20 border-emerald-200 dark:border-emerald-800"
+ }`}
+ >
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-3">
+ <div
+ className={`p-2 rounded-lg ${
+ llmModeInfo.mode === "hybrid"
+ ? "bg-purple-100 dark:bg-purple-800/30"
+ : llmModeInfo.mode === "api"
+ ? "bg-blue-100 dark:bg-blue-800/30"
+ : "bg-emerald-100 dark:bg-emerald-800/30"
+ }`}
+ >
+ <Cpu
+ className={`w-5 h-5 ${
+ llmModeInfo.mode === "hybrid"
+ ? "text-purple-600 dark:text-purple-400"
+ : llmModeInfo.mode === "api"
+ ? "text-blue-600 dark:text-blue-400"
+ : "text-emerald-600 dark:text-emerald-400"
+ }`}
+ />
+ </div>
+ <div>
+ <div className="flex items-center gap-2">
+ <h3 className="text-sm font-semibold text-slate-900 dark:text-slate-100">
+ {t("LLM Mode")}:{" "}
+ <span className="uppercase">{llmModeInfo.mode}</span>
+ </h3>
+ <span
+ className={`px-2 py-0.5 text-[10px] rounded-full font-medium ${
+ llmModeInfo.effective_source === "provider"
+ ? "bg-green-100 dark:bg-green-900/30 text-green-700 dark:text-green-300"
+ : "bg-slate-100 dark:bg-slate-700 text-slate-600 dark:text-slate-400"
+ }`}
+ >
+ {llmModeInfo.effective_source === "provider"
+ ? t("Using Provider")
+ : t("Using ENV")}
+ </span>
+ </div>
+ <p className="text-xs text-slate-600 dark:text-slate-400 mt-0.5">
+ {llmModeInfo.mode === "hybrid"
+ ? t(
+ "Both API and Local providers available. Active provider takes priority.",
+ )
+ : llmModeInfo.mode === "api"
+ ? t("Only API (cloud) providers are used.")
+ : t("Only Local (self-hosted) providers are used.")}
+ </p>
+ </div>
+ </div>
+ {llmModeInfo.active_provider && (
+ <div className="text-right">
+ <p className="text-[10px] text-slate-500 dark:text-slate-400 uppercase tracking-wider">
+ {t("Active")}
+ </p>
+ <p className="text-sm font-semibold text-slate-900 dark:text-slate-100">
+ {llmModeInfo.active_provider.name}
+ </p>
+ <p className="text-xs text-slate-500 dark:text-slate-400 font-mono">
+ {llmModeInfo.active_provider.model}
+ </p>
+ </div>
+ )}
+ </div>
+ </div>
+ )}
+
{/* Header & Add Button */}
<div className="flex justify-between items-center bg-white dark:bg-slate-800 px-4 py-3 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
<div>
<h2 className="text-sm font-semibold text-slate-900 dark:text-slate-100">
- LLM Service Providers
+ {t("LLM Providers")}
</h2>
<p className="text-xs text-slate-500 dark:text-slate-400">
- Configure and manage multiple LLM backends.
+ {t(
+ "Manage both API and Local LLM providers. Set LLM_MODE in Environment Variables to control which type is used.",
+ )}
</p>
</div>
<button
@@ -1537,6 +1841,8 @@ export default function SettingsPage() {
api_key: "",
model: defaultPreset.default_model,
is_active: false,
+ provider_type: "local",
+ requires_key: defaultPreset.requires_key,
});
setOriginalProviderName(null);
setSelectedPresetId(defaultPreset.id);
@@ -1544,117 +1850,171 @@ export default function SettingsPage() {
setShowProviderForm(true);
setTestProviderResult(null);
}}
- className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg flex items-center gap-1.5 text-xs font-medium transition-colors"
+ className="px-3 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg flex items-center gap-1.5 text-xs font-medium transition-colors"
>
- <SettingsIcon className="w-3.5 h-3.5" />
- Add Provider
+ <Server className="w-3.5 h-3.5" />
+ {t("Add Provider")}
</button>
</div>
+ {/* Provider Type Filter */}
+ <div className="flex items-center gap-2 bg-white dark:bg-slate-800 px-4 py-2 rounded-xl shadow-sm border border-slate-200 dark:border-slate-700">
+ <span className="text-xs text-slate-500 dark:text-slate-400">
+ {t("Filter")}:
+ </span>
+ <div className="flex bg-slate-100 dark:bg-slate-700 p-0.5 rounded-lg">
+ {(["all", "api", "local"] as const).map((filter) => (
+ <button
+ key={filter}
+ onClick={() => setProviderTypeFilter(filter)}
+ className={`px-3 py-1 rounded-md text-xs font-medium transition-all ${
+ providerTypeFilter === filter
+ ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ {filter === "all"
+ ? t("All")
+ : filter === "api"
+ ? t("API (Cloud)")
+ : t("Local")}
+ </button>
+ ))}
+ </div>
+ </div>
+
{/* Provider List */}
{loadingProviders ? (
<div className="flex justify-center p-6">
- <Loader2 className="w-6 h-6 animate-spin text-blue-500" />
+ <Loader2 className="w-6 h-6 animate-spin text-emerald-500" />
</div>
- ) : providers.length === 0 ? (
+ ) : providers.filter(
+ (p) =>
+ providerTypeFilter === "all" ||
+ p.provider_type === providerTypeFilter,
+ ).length === 0 ? (
<div className="text-center p-8 bg-slate-50 dark:bg-slate-800/50 rounded-xl border border-dashed border-slate-300 dark:border-slate-700">
- <Brain className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-2" />
+ <Server className="w-10 h-10 text-slate-300 dark:text-slate-600 mx-auto mb-2" />
<p className="text-sm text-slate-500 dark:text-slate-400">
- No providers configured yet.
+ {providerTypeFilter === "all"
+ ? t("No providers configured yet.")
+ : providerTypeFilter === "api"
+ ? t("No API providers configured.")
+ : t("No local providers configured.")}
+ </p>
+ <p className="text-xs text-slate-400 dark:text-slate-500 mt-1">
+ {t("Add providers to manage your LLM configurations.")}
</p>
</div>
) : (
<div className="grid gap-3">
- {providers.map((provider) => (
- <div
- key={provider.name}
- className={`bg-white dark:bg-slate-800 px-4 py-3 rounded-xl shadow-sm border transition-all ${provider.is_active ? "border-blue-500 ring-1 ring-blue-500/20" : "border-slate-200 dark:border-slate-700"}`}
- >
- <div className="flex justify-between items-center">
- <div className="flex items-center gap-3 min-w-0 flex-1">
- <div
- className={`p-2 rounded-lg flex-shrink-0 ${provider.is_active ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400"}`}
- >
- <Server className="w-4 h-4" />
- </div>
- <div className="min-w-0 flex-1">
- <div className="flex items-center gap-2 flex-wrap">
- <h3 className="font-semibold text-slate-900 dark:text-slate-100 text-sm">
- {provider.name}
- </h3>
- {provider.is_active && (
- <span className="px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-[10px] rounded font-medium">
- Active
- </span>
- )}
- <span className="text-[10px] bg-slate-100 dark:bg-slate-700 px-1.5 py-0.5 rounded border border-slate-200 dark:border-slate-600 uppercase tracking-wider font-semibold text-slate-500">
- {provider.binding}
- </span>
+ {providers
+ .filter(
+ (p) =>
+ providerTypeFilter === "all" ||
+ p.provider_type === providerTypeFilter,
+ )
+ .map((provider) => (
+ <div
+ key={provider.name}
+ className={`bg-white dark:bg-slate-800 px-4 py-3 rounded-xl shadow-sm border transition-all ${provider.is_active ? "border-blue-500 ring-1 ring-blue-500/20" : "border-slate-200 dark:border-slate-700"}`}
+ >
+ <div className="flex justify-between items-center">
+ <div className="flex items-center gap-3 min-w-0 flex-1">
+ <div
+ className={`p-2 rounded-lg flex-shrink-0 ${provider.is_active ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400" : "bg-slate-100 dark:bg-slate-700 text-slate-500 dark:text-slate-400"}`}
+ >
+ <Server className="w-4 h-4" />
</div>
- <div className="flex items-center gap-2 mt-0.5 text-xs text-slate-500 dark:text-slate-400">
- <span className="font-medium text-slate-600 dark:text-slate-300">
- {provider.model}
- </span>
- <span className="text-slate-300 dark:text-slate-600">
- •
- </span>
- <span className="font-mono truncate text-[10px]">
- {provider.base_url}
- </span>
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <h3 className="font-semibold text-slate-900 dark:text-slate-100 text-sm">
+ {provider.name}
+ </h3>
+ {provider.is_active && (
+ <span className="px-1.5 py-0.5 bg-blue-100 dark:bg-blue-900/30 text-blue-700 dark:text-blue-300 text-[10px] rounded font-medium">
+ Active
+ </span>
+ )}
+ <span
+ className={`text-[10px] px-1.5 py-0.5 rounded font-medium ${
+ provider.provider_type === "api"
+ ? "bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400"
+ : "bg-emerald-100 dark:bg-emerald-900/30 text-emerald-600 dark:text-emerald-400"
+ }`}
+ >
+ {provider.provider_type === "api"
+ ? "☁️ API"
+ : "🏠 Local"}
+ </span>
+ <span className="text-[10px] bg-slate-100 dark:bg-slate-700 px-1.5 py-0.5 rounded border border-slate-200 dark:border-slate-600 uppercase tracking-wider font-semibold text-slate-500">
+ {provider.binding}
+ </span>
+ </div>
+ <div className="flex items-center gap-2 mt-0.5 text-xs text-slate-500 dark:text-slate-400">
+ <span className="font-medium text-slate-600 dark:text-slate-300">
+ {provider.model}
+ </span>
+ <span className="text-slate-300 dark:text-slate-600">
+ •
+ </span>
+ <span className="font-mono truncate text-[10px]">
+ {provider.base_url}
+ </span>
+ </div>
</div>
</div>
- </div>
- <div className="flex items-center gap-1 flex-shrink-0 ml-2">
- {!provider.is_active && (
+ <div className="flex items-center gap-1 flex-shrink-0 ml-2">
+ {!provider.is_active && (
+ <button
+ onClick={() =>
+ handleActivateProvider(provider.name)
+ }
+ className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-md transition-colors"
+ title="Set as Active"
+ >
+ <CheckCircle className="w-4 h-4" />
+ </button>
+ )}
<button
- onClick={() =>
- handleActivateProvider(provider.name)
- }
- className="p-1.5 text-slate-400 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900/20 rounded-md transition-colors"
- title="Set as Active"
+ onClick={() => handleTestProvider(provider)}
+ className="p-1.5 text-slate-400 hover:text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-md transition-colors"
+ title="Test Connection"
>
- <CheckCircle className="w-4 h-4" />
+ <RefreshCw className="w-4 h-4" />
</button>
- )}
- <button
- onClick={() => handleTestProvider(provider)}
- className="p-1.5 text-slate-400 hover:text-green-600 hover:bg-green-50 dark:hover:bg-green-900/20 rounded-md transition-colors"
- title="Test Connection"
- >
- <RefreshCw className="w-4 h-4" />
- </button>
- <button
- onClick={() => {
- setEditingProvider({ ...provider });
- setOriginalProviderName(provider.name);
- const preset =
- PROVIDER_PRESETS.find(
- (p) =>
- p.base_url &&
- provider.base_url.includes(p.base_url),
- ) ||
- PROVIDER_PRESETS.find((p) => p.id === "custom");
- if (preset) setSelectedPresetId(preset.id);
- setFetchedModels([]);
- setShowProviderForm(true);
- setTestProviderResult(null);
- }}
- className="p-1.5 text-slate-400 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded-md transition-colors"
- title="Edit"
- >
- <Sliders className="w-4 h-4" />
- </button>
- <button
- onClick={() => handleDeleteProvider(provider.name)}
- className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors"
- title="Delete"
- >
- <XCircle className="w-4 h-4" />
- </button>
+ <button
+ onClick={() => {
+ setEditingProvider({ ...provider });
+ setOriginalProviderName(provider.name);
+ const preset =
+ PROVIDER_PRESETS.find(
+ (p) =>
+ p.base_url &&
+ provider.base_url.includes(p.base_url),
+ ) ||
+ PROVIDER_PRESETS.find((p) => p.id === "custom");
+ if (preset) setSelectedPresetId(preset.id);
+ setFetchedModels([]);
+ setShowProviderForm(true);
+ setTestProviderResult(null);
+ }}
+ className="p-1.5 text-slate-400 hover:text-amber-600 hover:bg-amber-50 dark:hover:bg-amber-900/20 rounded-md transition-colors"
+ title="Edit"
+ >
+ <Sliders className="w-4 h-4" />
+ </button>
+ <button
+ onClick={() => handleDeleteProvider(provider.name)}
+ className="p-1.5 text-slate-400 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900/20 rounded-md transition-colors"
+ title="Delete"
+ >
+ <XCircle className="w-4 h-4" />
+ </button>
+ </div>
</div>
</div>
- </div>
- ))}
+ ))}
</div>
)}
@@ -1662,9 +2022,12 @@ export default function SettingsPage() {
{showProviderForm && editingProvider && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
<div className="bg-white dark:bg-slate-800 rounded-xl shadow-xl w-full max-w-md overflow-hidden flex flex-col max-h-[85vh]">
- <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 flex justify-between items-center">
- <h3 className="font-semibold text-sm text-slate-900 dark:text-slate-100">
- {editingProvider.name ? "Edit Provider" : "Add Provider"}
+ <div className="px-4 py-3 border-b border-slate-100 dark:border-slate-700 bg-emerald-50/50 dark:bg-emerald-900/20 flex justify-between items-center">
+ <h3 className="font-semibold text-sm text-slate-900 dark:text-slate-100 flex items-center gap-2">
+ <Server className="w-4 h-4 text-emerald-600 dark:text-emerald-400" />
+ {editingProvider.name
+ ? t("Edit Provider")
+ : t("Add Provider")}
</h3>
<button
onClick={() => setShowProviderForm(false)}
@@ -1674,9 +2037,69 @@ export default function SettingsPage() {
</button>
</div>
<div className="p-4 overflow-y-auto space-y-3">
+ {/* Provider Type Selection */}
+ <div>
+ <label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">
+ {t("Provider Type")}
+ </label>
+ <div className="flex bg-slate-100 dark:bg-slate-700 p-0.5 rounded-lg">
+ <button
+ type="button"
+ onClick={() =>
+ setEditingProvider((prev) =>
+ prev
+ ? {
+ ...prev,
+ provider_type: "local",
+ requires_key: false,
+ }
+ : null,
+ )
+ }
+ className={`flex-1 py-1.5 px-3 rounded-md text-xs font-medium flex items-center justify-center gap-1.5 transition-all ${
+ editingProvider.provider_type === "local"
+ ? "bg-white dark:bg-slate-600 text-emerald-600 dark:text-emerald-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ 🏠 {t("Local")}
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ setEditingProvider((prev) =>
+ prev
+ ? {
+ ...prev,
+ provider_type: "api",
+ requires_key: true,
+ }
+ : null,
+ )
+ }
+ className={`flex-1 py-1.5 px-3 rounded-md text-xs font-medium flex items-center justify-center gap-1.5 transition-all ${
+ editingProvider.provider_type === "api"
+ ? "bg-white dark:bg-slate-600 text-blue-600 dark:text-blue-400 shadow-sm"
+ : "text-slate-500 dark:text-slate-400 hover:text-slate-700 dark:hover:text-slate-200"
+ }`}
+ >
+ ☁️ {t("API (Cloud)")}
+ </button>
+ </div>
+ <p className="mt-1 text-[10px] text-slate-500 dark:text-slate-400">
+ {editingProvider.provider_type === "local"
+ ? t(
+ "Local servers (Ollama, LM Studio, vLLM) running on your machine.",
+ )
+ : t(
+ "Cloud API providers (OpenAI, Anthropic, DeepSeek, etc.).",
+ )}
+ </p>
+ </div>
+
<div>
<label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">
- Provider Service
+ {t("Server Preset")}
</label>
<select
value={selectedPresetId}
@@ -1694,6 +2117,7 @@ export default function SettingsPage() {
preset.base_url || editingProvider.base_url,
model:
preset.default_model || editingProvider.model,
+ requires_key: preset.requires_key,
});
setCustomModelInput(preset.models.length === 0);
setFetchedModels([]);
@@ -1767,16 +2191,69 @@ export default function SettingsPage() {
prev ? { ...prev, base_url: e.target.value } : null,
)
}
- placeholder="https://api.openai.com/v1"
- className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg font-mono text-xs"
+ placeholder={
+ selectedPresetId === "lmstudio"
+ ? "http://127.0.0.1:1234"
+ : selectedPresetId === "ollama"
+ ? "http://localhost:11434/v1"
+ : "http://localhost:8080/v1"
+ }
+ className={`w-full p-2 bg-slate-50 dark:bg-slate-700 border rounded-lg font-mono text-xs ${
+ editingProvider.base_url.includes(
+ "/chat/completions",
+ ) || editingProvider.base_url.includes("/models/")
+ ? "border-red-400 dark:border-red-500 ring-1 ring-red-400/30"
+ : "border-slate-200 dark:border-slate-600"
+ }`}
/>
+ {/* Base URL validation warning */}
+ {(editingProvider.base_url.includes(
+ "/chat/completions",
+ ) ||
+ editingProvider.base_url.includes("/models/")) && (
+ <div className="mt-1.5 p-2 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg">
+ <p className="text-[11px] text-red-600 dark:text-red-400 font-medium flex items-center gap-1">
+ <AlertCircle className="w-3 h-3" />
+ {t("Invalid URL format detected")}
+ </p>
+ <p className="text-[10px] text-red-500 dark:text-red-400/80 mt-0.5">
+ {t(
+ "Base URL should NOT include '/chat/completions' or '/models/'. The system will append these automatically.",
+ )}
+ </p>
+ <p className="text-[10px] text-red-500 dark:text-red-400/80 mt-0.5">
+ {t("Example")}:{" "}
+ <code className="bg-red-100 dark:bg-red-800/30 px-1 rounded">
+ http://127.0.0.1:1234
+ </code>{" "}
+ {t("or")}{" "}
+ <code className="bg-red-100 dark:bg-red-800/30 px-1 rounded">
+ http://127.0.0.1:1234/v1
+ </code>
+ </p>
+ </div>
+ )}
+ {/* Normal help text */}
+ {!editingProvider.base_url.includes(
+ "/chat/completions",
+ ) &&
+ !editingProvider.base_url.includes("/models/") && (
+ <p className="mt-1 text-[10px] text-slate-500 dark:text-slate-400">
+ {t(
+ "Only enter the base URL. '/chat/completions' will be appended automatically.",
+ )}
+ </p>
+ )}
</div>
{PROVIDER_PRESETS.find((p) => p.id === selectedPresetId)
- ?.requires_key !== false && (
+ ?.requires_key && (
<div>
<label className="block text-xs font-medium text-slate-700 dark:text-slate-300 mb-1">
- API Key
+ {t("API Key")}{" "}
+ <span className="text-slate-400">
+ ({t("optional for local")})
+ </span>
</label>
<input
type="password"
@@ -1788,7 +2265,9 @@ export default function SettingsPage() {
: null,
)
}
- placeholder="sk-..."
+ placeholder={t(
+ "Usually not required for local servers",
+ )}
className="w-full p-2 bg-slate-50 dark:bg-slate-700 border border-slate-200 dark:border-slate-600 rounded-lg font-mono text-xs"
/>
</div>
@@ -1937,12 +2416,12 @@ export default function SettingsPage() {
<button
onClick={() => handleProviderSave(editingProvider)}
disabled={savingProvider}
- className="px-4 py-1.5 bg-blue-600 hover:bg-blue-700 text-white rounded-lg text-xs font-medium shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
+ className="px-4 py-1.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-lg text-xs font-medium shadow-sm disabled:opacity-50 disabled:cursor-not-allowed flex items-center gap-1.5"
>
{savingProvider && (
<Loader2 className="w-3 h-3 animate-spin" />
)}
- {savingProvider ? "Saving..." : "Save Provider"}
+ {savingProvider ? t("Saving...") : t("Save Server")}
</button>
</div>
</div>