Skip to content

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

updates in files to use settings.py and llm_factory for new updated providers

kushal garge61e2e9cf5c0
diff --git a/src/agents/co_writer/edit_agent.py b/src/agents/co_writer/edit_agent.py
index 1c8be1b8b..d5949f5f2 100644
--- a/src/agents/co_writer/edit_agent.py
+++ b/src/agents/co_writer/edit_agent.py
@@ -16,7 +16,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 lightrag.llm.openai import openai_complete_if_cache
+from src.core.llm_factory import llm_complete
from src.core.core import get_agent_params, get_llm_config, load_config_with_main
from src.core.logging import LLMStats, get_logger
@@ -138,6 +138,12 @@ class EditAgent:
- edited_text: Edited text
- operation_id: Operation ID
"""
+ # Always refresh LLM config before starting to avoid stale credentials
+ try:
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to refresh LLM config: {e}")
+
if not self.llm_config:
raise ValueError("LLM configuration not available")
@@ -226,7 +232,8 @@ class EditAgent:
# 3. Call LLM
logger.info(f"Calling LLM for {action}...")
model = self.llm_config["model"]
- response = await openai_complete_if_cache(
+ response = await llm_complete(
+ binding=self.llm_config["binding"],
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
@@ -271,6 +278,12 @@ class EditAgent:
- marked_text: Text with annotations
- operation_id: Operation ID
"""
+ # Always refresh LLM config before starting to avoid stale credentials
+ try:
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to refresh LLM config: {e}")
+
if not self.llm_config:
raise ValueError("LLM configuration not available")
@@ -284,7 +297,8 @@ class EditAgent:
logger.info("Calling LLM for auto-mark...")
model = self.llm_config["model"]
- response = await openai_complete_if_cache(
+ response = await llm_complete(
+ binding=self.llm_config["binding"],
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.py
index 7be457327..ef886f1ba 100644
--- a/src/agents/co_writer/narrator_agent.py
+++ b/src/agents/co_writer/narrator_agent.py
@@ -21,7 +21,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 lightrag.llm.openai import openai_complete_if_cache
+from src.core.llm_factory import llm_complete
from src.core.core import get_agent_params, get_llm_config, get_tts_config, load_config_with_main
from src.core.logging import get_logger
@@ -160,6 +160,12 @@ class NarratorAgent:
- script: Narration script text
- key_points: List of extracted key points
"""
+ # Always refresh LLM config before starting to avoid stale credentials
+ try:
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to refresh LLM config: {e}")
+
if not self.llm_config:
raise ValueError("LLM configuration not available")
@@ -196,7 +202,8 @@ class NarratorAgent:
logger.info(f"Generating narration script with style: {style}")
model = self.llm_config["model"]
- response = await openai_complete_if_cache(
+ response = await llm_complete(
+ binding=self.llm_config["binding"],
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
@@ -256,7 +263,8 @@ class NarratorAgent:
try:
model = self.llm_config["model"]
- response = await openai_complete_if_cache(
+ response = await llm_complete(
+ binding=self.llm_config["binding"],
model=model,
prompt=user_prompt,
system_prompt=system_prompt,
@@ -388,6 +396,14 @@ class NarratorAgent:
Returns:
Dict containing script info and optionally audio info
"""
+ # Refresh TTS config before starting to avoid stale credentials
+ try:
+ self.tts_config = get_tts_config()
+ # Also refresh LLM config since narrate calls generate_script
+ self.llm_config = get_llm_config()
+ except Exception as e:
+ logger.error(f"Failed to refresh configs: {e}")
+
script_result = await self.generate_script(content, style)
# Use default voice if not specified
diff --git a/src/agents/guide/agents/base_guide_agent.py b/src/agents/guide/agents/base_guide_agent.py
index 4fbd5b8ba..a20c456c6 100644
--- a/src/agents/guide/agents/base_guide_agent.py
+++ b/src/agents/guide/agents/base_guide_agent.py
@@ -15,7 +15,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 lightrag.llm.openai import openai_complete_if_cache
+from src.core.llm_factory import llm_complete
from src.core.core import get_agent_params, load_config_with_main
from src.core.logging import LLMStats, get_logger
@@ -28,7 +28,7 @@ class BaseGuideAgent(ABC):
# Shared stats tracker for all guide agents
_shared_stats: LLMStats | None = None
- def __init__(self, api_key: str, base_url: str, agent_name: str, language: str = "zh"):
+ def __init__(self, api_key: str, base_url: str, agent_name: str, language: str = "zh", binding: str = "openai"):
"""
Initialize base Agent.
@@ -37,11 +37,13 @@ class BaseGuideAgent(ABC):
base_url: API endpoint
agent_name: Agent name
language: Language setting ('zh' | 'en')
+ binding: LLM provider binding
"""
self.api_key = api_key
self.base_url = base_url
self.agent_name = agent_name
self.language = language
+ self.binding = binding
# Load agent parameters from unified config (agents.yaml)
self._agent_params = get_agent_params("guide")
@@ -129,12 +131,13 @@ class BaseGuideAgent(ABC):
"base_url": self.base_url,
"temperature": temperature,
"max_tokens": max_tokens,
+ "binding": self.binding,
}
if response_format:
kwargs["response_format"] = response_format
- response = await openai_complete_if_cache(**kwargs)
+ response = await llm_complete(**kwargs)
# Track token usage
stats = self.get_stats()
diff --git a/src/agents/guide/agents/chat_agent.py b/src/agents/guide/agents/chat_agent.py
index c2718743b..d6027d50e 100644
--- a/src/agents/guide/agents/chat_agent.py
+++ b/src/agents/guide/agents/chat_agent.py
@@ -12,9 +12,9 @@ from .base_guide_agent import BaseGuideAgent
class ChatAgent(BaseGuideAgent):
"""Learning Q&A agent"""
- def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ def __init__(self, api_key: str, base_url: str, language: str = "zh", binding: str = "openai"):
super().__init__(
- api_key=api_key, base_url=base_url, agent_name="chat_agent", language=language
+ api_key=api_key, base_url=base_url, agent_name="chat_agent", language=language, binding=binding
)
def _format_chat_history(self, history: list[dict[str, str]]) -> str:
diff --git a/src/agents/guide/agents/interactive_agent.py b/src/agents/guide/agents/interactive_agent.py
index ad0c2a72e..29e4e8df4 100644
--- a/src/agents/guide/agents/interactive_agent.py
+++ b/src/agents/guide/agents/interactive_agent.py
@@ -13,9 +13,9 @@ from .base_guide_agent import BaseGuideAgent
class InteractiveAgent(BaseGuideAgent):
"""Interactive page generation agent"""
- def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ def __init__(self, api_key: str, base_url: str, language: str = "zh", binding: str = "openai"):
super().__init__(
- api_key=api_key, base_url=base_url, agent_name="interactive_agent", language=language
+ api_key=api_key, base_url=base_url, agent_name="interactive_agent", language=language, binding=binding
)
def _extract_html(self, response: str) -> str:
diff --git a/src/agents/guide/agents/locate_agent.py b/src/agents/guide/agents/locate_agent.py
index e4e51ec13..d5cd79f3c 100644
--- a/src/agents/guide/agents/locate_agent.py
+++ b/src/agents/guide/agents/locate_agent.py
@@ -13,9 +13,9 @@ from .base_guide_agent import BaseGuideAgent
class LocateAgent(BaseGuideAgent):
"""Knowledge point location agent"""
- def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ def __init__(self, api_key: str, base_url: str, language: str = "zh", binding: str = "openai"):
super().__init__(
- api_key=api_key, base_url=base_url, agent_name="locate_agent", language=language
+ api_key=api_key, base_url=base_url, agent_name="locate_agent", language=language, binding=binding
)
def _format_records(self, records: list[dict[str, Any]]) -> str:
diff --git a/src/agents/guide/agents/summary_agent.py b/src/agents/guide/agents/summary_agent.py
index 634c8a9c6..07e71b4b7 100644
--- a/src/agents/guide/agents/summary_agent.py
+++ b/src/agents/guide/agents/summary_agent.py
@@ -12,9 +12,9 @@ from .base_guide_agent import BaseGuideAgent
class SummaryAgent(BaseGuideAgent):
"""Learning summary agent"""
- def __init__(self, api_key: str, base_url: str, language: str = "zh"):
+ def __init__(self, api_key: str, base_url: str, language: str = "zh", binding: str = "openai"):
super().__init__(
- api_key=api_key, base_url=base_url, agent_name="summary_agent", language=language
+ api_key=api_key, base_url=base_url, agent_name="summary_agent", language=language, binding=binding
)
def _format_knowledge_points(self, points: list[dict[str, Any]]) -> str:
diff --git a/src/agents/guide/guide_manager.py b/src/agents/guide/guide_manager.py
index 7eb66c0ac..6c92b2258 100644
--- a/src/agents/guide/guide_manager.py
+++ b/src/agents/guide/guide_manager.py
@@ -52,6 +52,7 @@ class GuideManager:
language: str | None = None,
output_dir: str | None = None,
config_path: str | None = None,
+ binding: str = "openai",
):
"""
Initialize manager
@@ -62,9 +63,11 @@ class GuideManager:
language: Language setting (if None, read from config file)
output_dir: Output directory
config_path: Configuration file path (if None, use default path)
+ binding: LLM provider binding
"""
self.api_key = api_key
self.base_url = base_url
+ self.binding = binding
if config_path is None:
project_root = Path(__file__).parent.parent.parent.parent
@@ -109,10 +112,10 @@ class GuideManager:
self.output_dir = project_root / "data" / "user" / "guide"
self.output_dir.mkdir(parents=True, exist_ok=True)
- self.locate_agent = LocateAgent(api_key, base_url, self.language)
- self.interactive_agent = InteractiveAgent(api_key, base_url, self.language)
- self.chat_agent = ChatAgent(api_key, base_url, self.language)
- self.summary_agent = SummaryAgent(api_key, base_url, self.language)
+ self.locate_agent = LocateAgent(api_key, base_url, self.language, binding=self.binding)
+ self.interactive_agent = InteractiveAgent(api_key, base_url, self.language, binding=self.binding)
+ self.chat_agent = ChatAgent(api_key, base_url, self.language, binding=self.binding)
+ self.summary_agent = SummaryAgent(api_key, base_url, self.language, binding=self.binding)
self._sessions: dict[str, GuidedSession] = {}
diff --git a/src/agents/ideagen/base_idea_agent.py b/src/agents/ideagen/base_idea_agent.py
index 38e142fdb..8c9b34e63 100644
--- a/src/agents/ideagen/base_idea_agent.py
+++ b/src/agents/ideagen/base_idea_agent.py
@@ -13,7 +13,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 lightrag.llm.openai import openai_complete_if_cache
+from src.core.llm_factory import llm_complete
from src.core.core import get_agent_params, get_llm_config, load_config_with_main
from src.core.logging import LLMStats, get_logger
@@ -48,6 +48,7 @@ class BaseIdeaAgent(ABC):
self.api_key = api_key or llm_config["api_key"]
self.base_url = base_url or llm_config["base_url"]
self.model = model or llm_config["model"]
+ self.binding = llm_config.get("binding", "openai")
except ValueError as e:
raise ValueError(f"LLM config error: {e!s}")
@@ -118,12 +119,13 @@ class BaseIdeaAgent(ABC):
"base_url": self.base_url,
"temperature": temperature,
"max_tokens": max_tokens,
+ "binding": self.binding,
}
if response_format:
kwargs["response_format"] = response_format
- response = await openai_complete_if_cache(**kwargs)
+ response = await llm_complete(**kwargs)
# Track token usage
stats = self.get_stats()
diff --git a/src/agents/research/agents/base_agent.py b/src/agents/research/agents/base_agent.py
index 3807cdf1a..e555a2ab5 100644
--- a/src/agents/research/agents/base_agent.py
+++ b/src/agents/research/agents/base_agent.py
@@ -14,9 +14,8 @@ from typing import Any
project_root = Path(__file__).parent.parent.parent.parent
sys.path.insert(0, str(project_root))
-from lightrag.llm.openai import openai_complete_if_cache
-
from src.core.core import get_agent_params, get_llm_config
+from src.core.llm_factory import llm_complete
from src.core.prompt_manager import get_prompt_manager
from ..utils.token_tracker import get_token_tracker
@@ -53,11 +52,13 @@ class BaseAgent(ABC):
self.api_key = api_key or env_llm.get("api_key")
self.base_url = base_url or env_llm.get("base_url")
self.default_model = env_llm.get("model")
+ self.binding = env_llm.get("binding", "openai")
except ValueError as e:
print(f"⚠️ Environment configuration error: {e}")
self.api_key = api_key
self.base_url = base_url
self.default_model = "gpt-4o"
+ self.binding = "openai"
# Get Agent-specific configuration
self.agent_config = config.get("agents", {}).get(agent_name, {})
@@ -137,7 +138,10 @@ class BaseAgent(ABC):
response = None
error = None
try:
- response = await openai_complete_if_cache(**kwargs)
+ response = await llm_complete(
+ binding=self.binding,
+ **kwargs
+ )
except Exception as e:
error = e
# Log error
diff --git a/src/api/routers/guide.py b/src/api/routers/guide.py
index 52948835a..5679034ad 100644
--- a/src/api/routers/guide.py
+++ b/src/api/routers/guide.py
@@ -70,10 +70,11 @@ def get_guide_manager():
llm_config = get_llm_config()
api_key = llm_config["api_key"]
base_url = llm_config["base_url"]
+ binding = llm_config.get("binding", "openai")
except Exception as e:
raise HTTPException(status_code=500, detail=f"LLM config error: {e!s}")
- return GuideManager(api_key=api_key, base_url=base_url, language=None) # Read from config file
+ return GuideManager(api_key=api_key, base_url=base_url, language=None, binding=binding) # Read from config file
# === REST API Endpoints ===
diff --git a/src/api/routers/system.py b/src/api/routers/system.py
index 8e5e078a1..2a754ac28 100644
--- a/src/api/routers/system.py
+++ b/src/api/routers/system.py
@@ -8,10 +8,11 @@ import re
import time
from fastapi import APIRouter
-from lightrag.llm.openai import openai_complete_if_cache, openai_embed
+from lightrag.llm.openai import openai_embed
from pydantic import BaseModel
from src.core.core import get_embedding_config, get_llm_config, get_tts_config
+from src.core.llm_factory import llm_complete
router = APIRouter()
@@ -124,7 +125,7 @@ async def get_system_status():
return result
[email protected]("/test/llm", response_model=TestResponse)
[email protected]("/test/llm/", response_model=TestResponse)
async def test_llm_connection():
"""
Test LLM model connection by sending a simple completion request
@@ -150,16 +151,18 @@ async def test_llm_connection():
api_key = "sk-no-key-required"
# Send a minimal test request with a prompt that guarantees output
- test_prompt = "Say 'OK' to confirm you are working."
- token_kwargs = _get_token_limit_kwargs(model, max_tokens=20)
- response = await openai_complete_if_cache(
+ test_prompt = "Say 'OK' to confirm you are working. Do not produce long output."
+ token_kwargs = _get_token_limit_kwargs(model, max_tokens=200)
+
+ response = await llm_complete(
model=model,
prompt=test_prompt,
system_prompt="You are a helpful assistant. Respond briefly.",
+ binding=llm_config.get("binding", "openai"),
api_key=api_key,
base_url=base_url,
temperature=0.1,
- **token_kwargs, # Use appropriate token param for model
+ **token_kwargs,
)
response_time = (time.time() - start_time) * 1000
@@ -190,7 +193,7 @@ async def test_llm_connection():
)
[email protected]("/test/embeddings", response_model=TestResponse)
[email protected]("/test/embeddings/", response_model=TestResponse)
async def test_embeddings_connection():
"""
Test Embeddings model connection by sending a simple embedding request
@@ -250,7 +253,7 @@ async def test_embeddings_connection():
)
[email protected]("/test/tts", response_model=TestResponse)
[email protected]("/test/tts/", response_model=TestResponse)
async def test_tts_connection():
"""
Test TTS model connection by checking configuration
diff --git a/src/core/core.py b/src/core/core.py
index d10156695..17084031d 100644
--- a/src/core/core.py
+++ b/src/core/core.py
@@ -10,6 +10,7 @@ from typing import Any
from dotenv import load_dotenv
import yaml
+from settings import settings
# PROJECT_ROOT points to the actual project root directory (DeepTutor/)
# Path(__file__) = src/core/core.py
@@ -46,30 +47,14 @@ def _strip_value(value: str | None) -> str | None:
def get_llm_config() -> dict:
"""
- Return complete environment configuration for LLM.
-
- Priority:
- 1. Active provider from llm_providers.json
- 2. Environment variables (.env)
-
- Returns:
- dict: Dictionary containing the following keys:
- - binding: LLM service provider
- - model: LLM model name
- - api_key: LLM API key
- - base_url: LLM API endpoint URL
-
- Raises:
- ValueError: If required configuration is missing
+ Return complete configuration for LLM.
+ Uses centralized settings singleton.
"""
# 1. Try to get active provider from new system
try:
from src.core.llm_provider import provider_manager
-
active_provider = provider_manager.get_active_provider()
-
if active_provider:
- # Map provider fields to config format
return {
"binding": active_provider.binding,
"model": active_provider.model,
@@ -79,74 +64,27 @@ def get_llm_config() -> dict:
except Exception as e:
print(f"⚠️ Failed to load active provider: {e}")
- # 2. Fallback to environment variables
- binding = _strip_value(os.getenv("LLM_BINDING", "openai"))
- model = _strip_value(os.getenv("LLM_MODEL"))
- api_key = _strip_value(os.getenv("LLM_BINDING_API_KEY"))
- base_url = _strip_value(os.getenv("LLM_BINDING_HOST"))
-
- # Validate required configuration
- if not model:
- raise ValueError(
- "Error: LLM_MODEL not set, please configure it in .env file or activate a provider"
- )
-
- # Check if API key is required (default to true for security/backward compatibility)
- requires_key = os.getenv("LLM_API_KEY_REQUIRED", "true").lower() == "true"
-
- if requires_key and not api_key:
- raise ValueError(
- "Error: LLM_BINDING_API_KEY not set, please configure it in .env file or activate a provider"
- )
- if not base_url:
- raise ValueError(
- "Error: LLM_BINDING_HOST not set, please configure it in .env file or activate a provider"
- )
-
+ # 2. Fallback to centralized settings
+ llm = settings.llm
return {
- "binding": binding,
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
+ "binding": llm.binding,
+ "model": llm.model,
+ "api_key": llm.api_key,
+ "base_url": llm.host,
+ "disable_ssl_verify": llm.disable_ssl_verify
}
def get_tts_config() -> dict:
"""
- Return complete environment configuration for TTS (Text-to-Speech).
-
- Returns:
- dict: Dictionary containing the following keys:
- - model: TTS model name
- - api_key: TTS API key
- - base_url: TTS API endpoint URL
- - voice: Default voice character
-
- Raises:
- ValueError: If required configuration is missing
+ Return complete configuration for TTS (Text-to-Speech).
"""
- model = _strip_value(os.getenv("TTS_MODEL"))
- api_key = _strip_value(os.getenv("TTS_API_KEY"))
- base_url = _strip_value(os.getenv("TTS_URL"))
- voice = _strip_value(os.getenv("TTS_VOICE", "alloy"))
-
- # Validate required configuration
- if not model:
- raise ValueError(
- "Error: TTS_MODEL not set, please configure it in .env file (e.g., tts-1 or tts-1-hd)"
- )
- if not api_key:
- raise ValueError("Error: TTS_API_KEY not set, please configure it in .env file")
- if not base_url:
- raise ValueError(
- "Error: TTS_URL not set, please configure it in .env file (e.g., https://api.openai.com/v1)"
- )
-
+ tts = settings.tts
return {
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
- "voice": voice,
+ "model": tts.model,
+ "api_key": tts.api_key,
+ "base_url": tts.url,
+ "voice": os.getenv("TTS_VOICE", "alloy"), # Still allowing voice from env if not in settings
}
@@ -206,50 +144,16 @@ def get_agent_params(module_name: str) -> dict:
def get_embedding_config() -> dict:
"""
- Return complete environment configuration for embedding models.
-
- Returns:
- dict: Dictionary containing the following keys:
- - binding: Embedding service provider
- - model: Embedding model name
- - api_key: Embedding API key
- - base_url: Embedding API endpoint URL
- - dim: Embedding dimension
- - max_tokens: Maximum tokens for embedding
-
- Raises:
- ValueError: If required configuration is missing
+ Return complete configuration for embedding models.
"""
- binding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))
- model = _strip_value(os.getenv("EMBEDDING_MODEL"))
- api_key = _strip_value(os.getenv("EMBEDDING_BINDING_API_KEY"))
- base_url = _strip_value(os.getenv("EMBEDDING_BINDING_HOST"))
-
- # Strict mode: All model configuration must come from .env, no automatic fallback or default inference
- if not model:
- raise ValueError("Error: EMBEDDING_MODEL not set, please configure it in .env file")
-
- # Check if API key is required (default to true for security/backward compatibility)
- requires_key = os.getenv("EMBEDDING_API_KEY_REQUIRED", "true").lower() == "true"
-
- if requires_key and not api_key:
- raise ValueError(
- "Error: EMBEDDING_BINDING_API_KEY not set, please configure it in .env file"
- )
- if not base_url:
- raise ValueError("Error: EMBEDDING_BINDING_HOST not set, please configure it in .env file")
-
- # Get optional configuration
- dim = _to_int(_strip_value(os.getenv("EMBEDDING_DIM")), 3072)
- max_tokens = _to_int(_strip_value(os.getenv("EMBEDDING_MAX_TOKENS")), 8192)
-
+ emb = settings.embedding
return {
- "binding": binding,
- "model": model,
- "api_key": api_key,
- "base_url": base_url,
- "dim": dim,
- "max_tokens": max_tokens,
+ "binding": emb.binding,
+ "model": emb.model,
+ "api_key": emb.api_key,
+ "base_url": emb.host,
+ "dim": emb.dimension,
+ "max_tokens": 8192, # Default
}
diff --git a/src/tools/rag_tool.py b/src/tools/rag_tool.py
index 2e3e722a5..0c615df33 100644
--- a/src/tools/rag_tool.py
+++ b/src/tools/rag_tool.py
@@ -20,6 +20,7 @@ from lightrag.utils import EmbeddingFunc
from raganything import RAGAnything, RAGAnythingConfig
from src.core.core import get_embedding_config, get_llm_config
+from src.core.llm_factory import llm_complete, sanitize_url
from src.core.logging import LightRAGLogContext
from src.knowledge.manager import KnowledgeBaseManager
@@ -124,10 +125,12 @@ async def rag_search(
raise Exception(f"Error: Unable to access knowledge base - {e!s}")
# Define LLM function
- def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
- return openai_complete_if_cache(
- llm_model,
- prompt,
+ async def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
+ # Use our centralized llm_complete for sanitization and fallback support
+ return await llm_complete(
+ binding="openai",
+ model=llm_model,
+ prompt=prompt,
system_prompt=system_prompt,
history_messages=history_messages,
api_key=llm_api_key,
@@ -135,7 +138,7 @@ async def rag_search(
**kwargs,
)
- def vision_model_func(
+ async def vision_model_func(
prompt,
system_prompt=None,
history_messages=[],
@@ -151,8 +154,9 @@ async def rag_search(
for k, v in kwargs.items()
if k not in ["messages", "prompt", "system_prompt", "history_messages"]
}
- return openai_complete_if_cache(
- llm_model,
+ return await llm_complete(
+ binding="openai",
+ model=llm_model,
prompt="", # Empty prompt when using messages
system_prompt=None,
history_messages=[],
@@ -169,8 +173,9 @@ async def rag_search(
for k, v in kwargs.items()
if k not in ["messages", "prompt", "system_prompt", "history_messages"]
}
- return openai_complete_if_cache(
- llm_model,
+ return await llm_complete(
+ binding="openai",
+ model=llm_model,
prompt="", # Empty prompt when using messages
system_prompt=None,
history_messages=[],
@@ -196,8 +201,11 @@ async def rag_search(
**clean_kwargs,
)
# Pure text format
- return llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+ return await llm_model_func(prompt, system_prompt, history_messages, **kwargs)
+ # Sanitize embedding URL
+ embedding_base_url_sanitized = sanitize_url(embedding_base_url, embedding_model)
+
# Define embedding function
# CRITICAL: Use openai_embed.func to avoid double decoration
# openai_embed is already decorated with @wrap_embedding_func_with_attrs
@@ -209,7 +217,7 @@ async def rag_search(
texts,
model=embedding_model,
api_key=embedding_api_key,
- base_url=embedding_base_url,
+ base_url=embedding_base_url_sanitized,
),
)