Initial commit: AI Shell v0.1.0
- AI-powered shell command generator using DeepSeek V3 - Support for natural language to shell command conversion - Secure configuration management with .env files - Package structure with uv tool installation support - Chinese and English language support - Configuration validation and error handling
This commit is contained in:
77
ai_shell/config.py
Normal file
77
ai_shell/config.py
Normal file
@ -0,0 +1,77 @@
|
||||
"""
|
||||
Configuration module for AI Shell
|
||||
"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = None
|
||||
|
||||
# Load .env file if it exists
|
||||
def load_env_file() -> None:
|
||||
"""Load environment variables from .env file"""
|
||||
if load_dotenv is None:
|
||||
return
|
||||
|
||||
# Try to find .env file in current directory or package directory
|
||||
env_paths = [
|
||||
Path.cwd() / ".env",
|
||||
Path(__file__).parent.parent / ".env",
|
||||
Path.home() / ".ai-shell" / ".env",
|
||||
]
|
||||
|
||||
for env_path in env_paths:
|
||||
if env_path.exists():
|
||||
load_dotenv(env_path)
|
||||
break
|
||||
|
||||
# Load .env file on import
|
||||
load_env_file()
|
||||
|
||||
# Default API configuration (fallback values)
|
||||
DEFAULT_API_KEY = "your_api_key_here"
|
||||
DEFAULT_BASE_URL = "https://api.openai.com/v1/"
|
||||
DEFAULT_MODEL = "gpt-3.5-turbo"
|
||||
|
||||
def get_api_key() -> str:
|
||||
"""Get API key from environment or use default"""
|
||||
api_key = os.getenv("AI_SHELL_API_KEY", DEFAULT_API_KEY)
|
||||
if api_key == DEFAULT_API_KEY:
|
||||
raise ValueError(
|
||||
"API key not configured. Please set AI_SHELL_API_KEY in .env file or environment variable."
|
||||
)
|
||||
return api_key
|
||||
|
||||
def get_base_url() -> str:
|
||||
"""Get base URL from environment or use default"""
|
||||
return os.getenv("AI_SHELL_BASE_URL", DEFAULT_BASE_URL)
|
||||
|
||||
def get_model() -> str:
|
||||
"""Get model name from environment or use default"""
|
||||
return os.getenv("AI_SHELL_MODEL", DEFAULT_MODEL)
|
||||
|
||||
def get_timeout() -> int:
|
||||
"""Get request timeout from environment"""
|
||||
return int(os.getenv("AI_SHELL_TIMEOUT", "30"))
|
||||
|
||||
def get_max_retries() -> int:
|
||||
"""Get max retries from environment"""
|
||||
return int(os.getenv("AI_SHELL_MAX_RETRIES", "3"))
|
||||
|
||||
def setup_environment() -> None:
|
||||
"""Setup environment variables for OpenAI client"""
|
||||
os.environ["OPENAI_API_KEY"] = get_api_key()
|
||||
os.environ["OPENAI_BASE_URL"] = get_base_url()
|
||||
|
||||
def validate_config() -> bool:
|
||||
"""Validate configuration"""
|
||||
try:
|
||||
get_api_key()
|
||||
get_base_url()
|
||||
get_model()
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
Reference in New Issue
Block a user