picogent-py/picogent/config.py

74 lines
2.7 KiB
Python

"""
Configuration management for PicoGent
"""
import json
import os
from dataclasses import dataclass
from typing import Optional, Dict, Any
@dataclass
class Config:
"""Configuration for PicoGent agent"""
provider: str = "anthropic"
model: str = "claude-sonnet-4-20250514"
api_key: str = "env:ANTHROPIC_API_KEY"
max_tokens: int = 8192
max_iterations: int = 20
workspace: str = "."
system_prompt: str = "You are a helpful coding assistant."
base_url: Optional[str] = None
@classmethod
def from_file(cls, config_path: str) -> "Config":
"""Load configuration from JSON file"""
import logging
logger = logging.getLogger("picogent.config")
logger.info(f"Loading config from: {os.path.abspath(config_path)}")
if not os.path.exists(config_path):
raise FileNotFoundError(f"Config file not found: {config_path}")
with open(config_path, 'r') as f:
data = json.load(f)
provider = data.get('provider', 'anthropic')
model = data.get('model', 'claude-sonnet-4-20250514')
base_url = data.get('base_url', None)
logger.info(f"Provider: {provider} | Model: {model} | Base URL: {base_url}")
# Resolve environment variables in API key
api_key = data.get('api_key', '')
if api_key.startswith('env:'):
env_var = api_key[4:] # Remove 'env:' prefix
logger.info(f"Resolving API key from env var: {env_var}")
api_key = os.getenv(env_var, '')
if not api_key:
raise ValueError(f"Environment variable {env_var} is not set")
logger.info(f"API key resolved: {api_key[:8]}...{api_key[-4:]} (len={len(api_key)})")
else:
logger.info(f"API key from config: {api_key[:8]}...{api_key[-4:]} (len={len(api_key)})" if len(api_key) > 12 else f"API key from config: *** (len={len(api_key)})")
return cls(
provider=provider,
model=model,
api_key=api_key,
max_tokens=data.get('max_tokens', 8192),
max_iterations=data.get('max_iterations', 20),
workspace=data.get('workspace', '.'),
system_prompt=data.get('system_prompt', 'You are a helpful coding assistant.'),
base_url=base_url
)
def to_dict(self) -> Dict[str, Any]:
"""Convert config to dictionary"""
return {
'provider': self.provider,
'model': self.model,
'api_key': self.api_key,
'max_tokens': self.max_tokens,
'max_iterations': self.max_iterations,
'workspace': self.workspace,
'system_prompt': self.system_prompt
}