OverviewFilesCommitsIssuesDocsReleasesPeers

ollama_semantic_function_calling / ollamatools-new / ollamatools / config / loader.py

108 lines · python ref:
"""
Core configuration management for OllamaTools.

This module contains the Config class, which handles configuration settings for
the OllamaTools library.
"""

import json
import os
from typing import Optional, Dict, Any

from pydantic import BaseModel, validator, Field


class Config(BaseModel):
    """
    Configuration class for OllamaTools.
    
    This class manages configuration settings for the OllamaTools library using
    Pydantic for validation. It provides methods for loading and saving configuration
    to a file.
    """
    
    model: str = "llama3.1"
    host: str = "http://localhost:11434"
    permission_prompts: bool = True
    sudo_always_prompt: bool = True
    timeout_seconds: int = 60
    max_file_size: Optional[int] = None
    
    @validator('timeout_seconds')
    def validate_timeout(cls, v):
        """Validate that timeout is positive."""
        if v <= 0:
            raise ValueError("Timeout must be positive")
        return v
    
    @validator('max_file_size')
    def validate_max_file_size(cls, v):
        """Validate that max_file_size is positive if provided."""
        if v is not None and v <= 0:
            raise ValueError("Max file size must be positive")
        return v
    
    @classmethod
    def load_from_file(cls, file_path: str) -> "Config":
        """
        Load configuration from a JSON file.
        
        Args:
            file_path: Path to the configuration file
            
        Returns:
            Config: Configuration object
            
        Raises:
            FileNotFoundError: If the file does not exist
            json.JSONDecodeError: If the file contains invalid JSON
            ValueError: If the configuration is invalid
        """
        if not os.path.exists(file_path):
            raise FileNotFoundError(f"Configuration file not found: {file_path}")
        
        with open(file_path, 'r') as f:
            try:
                config_data = json.load(f)
                return cls(**config_data)
            except json.JSONDecodeError:
                raise json.JSONDecodeError(f"Invalid JSON in configuration file: {file_path}", "", 0)
    
    def save_to_file(self, file_path: str) -> None:
        """
        Save configuration to a JSON file.
        
        Args:
            file_path: Path to the configuration file
            
        Raises:
            PermissionError: If the file cannot be written
        """
        try:
            # Create directory if it doesn't exist
            os.makedirs(os.path.dirname(os.path.abspath(file_path)), exist_ok=True)
            
            with open(file_path, 'w') as f:
                json.dump(self.dict(), f, indent=2)
        except PermissionError:
            raise PermissionError(f"Cannot write to configuration file: {file_path}")
    
    def to_dict(self) -> Dict[str, Any]:
        """
        Convert configuration to a dictionary.
        
        Returns:
            Dict[str, Any]: Configuration as a dictionary
        """
        return self.dict(exclude_none=True)
    
    @classmethod
    def default_config_path(cls) -> str:
        """
        Get the default configuration file path.
        
        Returns:
            str: Default configuration file path
        """
        return os.path.expanduser("~/.config/ollamatools/config.json")