Skip to content

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

better handling and management of .env variables

kushal garge5fdf27adc25
diff --git a/.env.example b/.env.example
index a22ba0a68..ab1a77201 100644
--- a/.env.example
+++ b/.env.example
@@ -19,10 +19,10 @@ LLM_BINDING=openai
LLM_MODEL=
# LLM API endpoint URL
-LLM_BINDING_HOST=
+LLM_HOST=
# LLM API authentication key
-LLM_BINDING_API_KEY=
+LLM_API_KEY=
# Disable SSL certificate verification (set 'true' for self-signed certificates)
DISABLE_SSL_VERIFY=false
@@ -42,13 +42,13 @@ EMBEDDING_BINDING=openai
EMBEDDING_MODEL=text-embedding-3-large
# Embedding vector dimension
-EMBEDDING_DIM=3072
+EMBEDDING_DIMENSION=3072
# Embedding API endpoint URL
-EMBEDDING_BINDING_HOST=
+EMBEDDING_HOST=
# Embedding API authentication key
-EMBEDDING_BINDING_API_KEY=
+EMBEDDING_API_KEY=
# ============================================================================
# TTS (Text-to-Speech) Configuration (Optional)
@@ -69,10 +69,27 @@ TTS_API_KEY=
# Web Search Configuration
# ============================================================================
# Configure external search APIs for research features.
+
+# Search provider to use for web search
+# Options: perplexity, baidu
+# Default: perplexity
+SEARCH_PROVIDER=perplexity
+
+# ----------------------------------------------------------------------------
+# Perplexity AI Search Configuration
+# ----------------------------------------------------------------------------
# Perplexity API key for web search functionality
# Get your API key at: https://www.perplexity.ai/settings/api
PERPLEXITY_API_KEY=
+# ----------------------------------------------------------------------------
+# 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
+# Format: bce-v3/ALTAK-xxx/xxx or the full API key
+BAIDU_API_KEY=
+
# ============================================================================
# Logging Configuration
# ============================================================================
diff --git a/settings.py b/settings.py
new file mode 100644
index 000000000..9d1c40fed
--- /dev/null
+++ b/settings.py
@@ -0,0 +1,154 @@
+from typing import Optional
+from pydantic import Field
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+
+class LLMSettings(BaseSettings):
+ # Environment vars: LLM_BINDING, LLM_MODEL, LLM_HOST, LLM_API_KEY, DISABLE_SSL_VERIFY
+ model_config = SettingsConfigDict(
+ env_file= ".env",
+ env_prefix= "LLM_",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ binding: str = Field(
+ default = "openai",
+ description = "LLM service provider type (Supported types: openai, azure_openai, ollama, lollms, groq, openrouter, ollama-cloud)."
+ )
+
+ model: str = Field(
+ default = "qwen3:0.6b",
+ description = "LLM model name (make sure you use the correct model name which is supported by binding)."
+ )
+
+ host: str = Field(
+ default="http://localhost:11434/v1/",
+ description="LLM API endpoint URL (e.g. http://localhost:11434/v1/ is for Ollama hosted locally)."
+ )
+
+ api_key: str = Field(
+ default="ollama",
+ description="LLM API authentication key, for Ollama that is locally setup u can leave it empty"
+ )
+
+ disable_ssl_verify: bool = Field(
+ default=False,
+ description="If true, disables SSL verification (useful for self-signed certs).",
+ validation_alias="DISABLE_SSL_VERIFY"
+ )
+
+class EmbeddingSettings(BaseSettings):
+ # Environment vars: EMBEDDING_BINDING, EMBEDDING_MODEL, EMBEDDING_DIMENSION, EMBEDDING_HOST, EMBEDDING_API_KEY
+ model_config = SettingsConfigDict(
+ env_prefix="EMBEDDING_",
+ env_file= ".env",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ binding: str = Field(
+ default="openai",
+ description="Embedding service provider type (e.g. openai, azure_openai, ollama, lollms)."
+ )
+
+ model: str = Field(
+ default="qwen3-embedding:0.6b",
+ description="Embedding model name (e.g. text-embedding-3-large from openai)."
+ )
+
+ dimension: int = Field(
+ default=4096,
+ description="Embedding vector dimension. Should check accordingly for selected embedding model"
+ )
+
+ host: str = Field(
+ default="http://localhost:11434/v1/",
+ description="Embedding API endpoint URL (e.g. http://localhost:11434/v1/ is for Ollama hosted locally)."
+ )
+
+ api_key: str = Field(
+ default="ollama",
+ description="Embedding API authentication key for ollama locally setup you can pass anything."
+ )
+
+class TTSSettings(BaseSettings):
+ # Environment vars: TTS_MODEL, TTS_URL, TTS_API_KEY
+ model_config = SettingsConfigDict(
+ env_prefix="TTS_",
+ env_file= ".env",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ model: Optional[str] = Field(
+ default=None,
+ description="TTS model name"
+ )
+
+ url: Optional[str] = Field(
+ default=None,
+ description="TTS API endpoint URL."
+ )
+
+ api_key: Optional[str] = Field(
+ default=None,
+ description="TTS API authentication key."
+ )
+
+class WebSearchSettings(BaseSettings):
+ # Environment var: PERPLEXITY_API_KEY
+ model_config = SettingsConfigDict(
+ env_prefix="PERPLEXITY_",
+ env_file= ".env",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ api_key: Optional[str] = Field(
+ default=None,
+ description="Perplexity API key for web search functionality.",
+ validation_alias="PERPLEXITY_API_KEY"
+ )
+
+class LoggingSettings(BaseSettings):
+ # Environment vars: RAG_TOOL_MODULE_LOG_LEVEL
+ model_config = SettingsConfigDict(
+ env_prefix="LOGGING_",
+ env_file= ".env",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ rag_tool_module_log_level: str = Field(
+ default="INFO",
+ description="Log level for RAG tool module (DEBUG, INFO, WARNING, ERROR)."
+ )
+
+class RagSettings(BaseSettings):
+ # Environment vars: RAG_PROVIDER
+ model_config = SettingsConfigDict(
+ env_prefix="RAG_",
+ env_file= ".env",
+ env_file_encoding= "utf-8",
+ extra= "ignore",
+ )
+
+ rag_provider: str = Field(
+ default="lightrag",
+ description="RAG provider identifier (if applicable)."
+ )
+
+class Settings(BaseSettings):
+ """
+ Loads values from .env (env_file).
+ """
+ llm: LLMSettings = LLMSettings()
+ embedding: EmbeddingSettings = EmbeddingSettings()
+ tts: TTSSettings = TTSSettings()
+ web_search: WebSearchSettings = WebSearchSettings()
+ logging: LoggingSettings = LoggingSettings()
+ rag: RagSettings = RagSettings()
+
+
+settings = Settings()
\ No newline at end of file
diff --git a/src/api/routers/settings.py b/src/api/routers/settings.py
index 268478709..0b31a70df 100644
--- a/src/api/routers/settings.py
+++ b/src/api/routers/settings.py
@@ -24,7 +24,7 @@ config_manager = ConfigManager()
ENV_VAR_DEFINITIONS = {
# LLM Configuration
"LLM_BINDING": {
- "description": "LLM service provider type (e.g., openai, azure_openai, ollama)",
+ "description": "LLM service provider type (e.g., openai, anthropic, gemini, openrouter, ollama)",
"category": "llm",
"required": False,
"default": "openai",
@@ -37,14 +37,14 @@ ENV_VAR_DEFINITIONS = {
"default": "",
"sensitive": False,
},
- "LLM_BINDING_HOST": {
+ "LLM_HOST": {
"description": "LLM API endpoint URL (e.g., https://api.openai.com/v1)",
"category": "llm",
"required": True,
"default": "",
"sensitive": False,
},
- "LLM_BINDING_API_KEY": {
+ "LLM_API_KEY": {
"description": "LLM API authentication key",
"category": "llm",
"required": True,
@@ -66,21 +66,21 @@ ENV_VAR_DEFINITIONS = {
"default": "",
"sensitive": False,
},
- "EMBEDDING_DIM": {
+ "EMBEDDING_DIMENSION": {
"description": "Embedding vector dimension (e.g., 3072 for text-embedding-3-large)",
"category": "embedding",
"required": False,
"default": "3072",
"sensitive": False,
},
- "EMBEDDING_BINDING_HOST": {
+ "EMBEDDING_HOST": {
"description": "Embedding API endpoint URL",
"category": "embedding",
"required": True,
"default": "",
"sensitive": False,
},
- "EMBEDDING_BINDING_API_KEY": {
+ "EMBEDDING_API_KEY": {
"description": "Embedding API authentication key",
"category": "embedding",
"required": True,
@@ -457,22 +457,87 @@ async def get_env_var(key: str):
}
-async def update_env_config(update: EnvConfigUpdate):
- """
- Update environment variables at runtime.
- This updates the process environment variables immediately.
- The system will use the new values for subsequent operations.
+def _update_dot_env(updates: Dict[str, str], removals: list[str]):
+ """Update variables in .env file preserving comments and structure."""
+ env_path = Path(__file__).parent.parent.parent.parent / ".env"
+
+ if not env_path.exists():
+ # Create new if doesn't exist
+ with open(env_path, "w", encoding="utf-8") as f:
+ for k, v in updates.items():
+ if " " in v or "#" in v:
+ f.write(f'{k}="{v}"\n')
+ else:
+ f.write(f"{k}={v}\n")
+ return
+
+ # Read existing
+ try:
+ with open(env_path, "r", encoding="utf-8") as f:
+ lines = f.readlines()
+ except Exception as e:
+ print(f"Error reading .env: {e}")
+ return
+
+ new_lines = []
+ processed_keys = set()
+
+ for line in lines:
+ stripped = line.strip()
+ if not stripped or stripped.startswith("#"):
+ new_lines.append(line)
+ continue
+
+ # Parse key
+ if "=" in stripped:
+ key = stripped.split("=")[0].strip()
+
+ if key in removals:
+ continue # Skip/Remove this line
+
+ if key in updates:
+ # Update this line
+ val = updates[key]
+ # Simple quoting suggestion
+ if " " in val or "#" in val or '"' in val or "'" in val:
+ # minimal escape of double quotes
+ val = val.replace('"', '\\"')
+ new_lines.append(f'{key}="{val}"\n')
+ else:
+ new_lines.append(f"{key}={val}\n")
+ processed_keys.add(key)
+ continue
+
+ new_lines.append(line)
+
+ # Append new keys that weren't found
+ for k, v in updates.items():
+ if k not in processed_keys and k not in removals:
+ if " " in v or "#" in v or '"' in v or "'" in v:
+ val = v.replace('"', '\\"')
+ new_lines.append(f'\n{k}="{val}"\n')
+ else:
+ new_lines.append(f"\n{k}={v}\n")
+
+ # Write back
+ try:
+ with open(env_path, "w", encoding="utf-8") as f:
+ f.writelines(new_lines)
+ except Exception as e:
+ print(f"Error writing .env: {e}")
- Note: These changes are NOT persisted to .env file.
- On system restart, values will be loaded from .env again.
- Returns:
- Updated variables configuration
+async def update_env_config(update: EnvConfigUpdate):
+ """
+ Update environment variables at runtime and persist to .env.
"""
updated_vars = []
errors = []
+
+ env_updates = {}
+ env_removals = []
for var_update in update.variables:
key = var_update.key
@@ -493,12 +558,18 @@ async def update_env_config(update: EnvConfigUpdate):
# Update the environment variable
if value:
os.environ[key] = value
+ env_updates[key] = value
elif key in os.environ:
# If value is empty and variable exists, remove it
del os.environ[key]
+ env_removals.append(key)
updated_vars.append(key)
+ # Persist to .env
+ if env_updates or env_removals:
+ _update_dot_env(env_updates, env_removals)
+
if errors:
raise HTTPException(status_code=400, detail={"errors": errors, "updated": updated_vars})
@@ -506,7 +577,7 @@ async def update_env_config(update: EnvConfigUpdate):
return {
"success": True,
"updated": updated_vars,
- "message": f"Updated {len(updated_vars)} environment variables. Changes are active immediately but not persisted to .env file.",
+ "message": f"Updated {len(updated_vars)} environment variables.",
}
@@ -529,13 +600,15 @@ async def update_single_env_var(key: str, value: str):
# Update the environment variable
if value:
os.environ[key] = value
+ _update_dot_env({key: value}, [])
elif key in os.environ:
del os.environ[key]
+ _update_dot_env({}, [key])
return {
"success": True,
"key": key,
- "message": f"Environment variable {key} updated. Changes are active immediately.",
+ "message": f"Environment variable {key} updated.",
}