how i write code buttter import json
import time
import logging
from typing import Dict, List, Any, Optional
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry

# Configure logging with both console and file handlers
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler("bedtime_story.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class Agent:
    def __init__(self, name: str) -> None:
        self.name: str = name
        self.tasks: List[Dict[str, Any]] = []
        self.tools: List[Dict[str, str]] = []

    def assign_task(self, task: Dict[str, Any]) -> None:
        """Assigns a task to the agent."""
        self.tasks.append(task)
        logger.info(f"Task {task['id']} assigned to Agent {self.name}")

    def add_tool(self, tool: Dict[str, str]) -> None:
        """Adds a tool to the agent's toolkit."""
        self.tools.append(tool)
        logger.info(f"Tool {tool['name']} added to Agent {self.name}")

    def execute_task(self, task: Dict[str, Any]) -> None:
        """Executes a task assigned to the agent."""
        if task in self.tasks:
            logger.info(f"Agent {self.name} executing Task {task['id']}")
            # Simulate task execution
            time.sleep(2)  # Replace with actual task execution logic
            logger.info(f"Task {task['id']} completed by Agent {self.name}")
        else:
            logger.warning(f"Agent {self.name} does not have Task {task['id']} assigned")

class Crew:
    def __init__(self, name: str) -> None:
        self.name: str = name
        self.agents: List[Agent] = []

    def add_agent(self, agent: Agent) -> None:
        """Adds an agent to the crew."""
        self.agents.append(agent)
        logger.info(f"Agent {agent.name} added to Crew {self.name}")

    def assign_task(self, task: Dict[str, Any]) -> None:
        """Assigns a task to the appropriate agent in the crew."""
        for agent in self.agents:
            if 'role' in task and task['role'] == agent.name:
                agent.assign_task(task)

    def execute_tasks(self) -> None:
        """Executes all tasks assigned to the agents in the crew."""
        for agent in self.agents:
            for task in agent.tasks:
                agent.execute_task(task)

def get_api_config() -> Dict[str, str]:
    """Load API configuration from a JSON file."""
    try:
        with open('config.json') as config_file:
            config = json.load(config_file)
        if 'ollama_api_url' not in config or 'model_name' not in config:
            raise ValueError("Config file is missing required fields.")
        return config
    except FileNotFoundError:
        logger.error("Config file not found. Please ensure 'config.json' exists.")
        raise
    except json.JSONDecodeError:
        logger.error("Invalid JSON in config file. Please check 'config.json' formatting.")
        raise
    except ValueError as ve:
        logger.error(f"Configuration error: {ve}")
        raise

def configure_retry_session(retries: int = 3, backoff_factor: float = 0.3) -> requests.Session:
    """Configure a requests session with retry logic."""
    session = requests.Session()
    retry_strategy = Retry(
        total=retries,
        read=retries,
        connect=retries,
        backoff_factor=backoff_factor,
        status_forcelist=[500, 502, 503, 504],
    )
    adapter = HTTPAdapter(max_retries=retry_strategy)
    session.mount("http://", adapter)
    session.mount("https://", adapter)
    return session

def generate_story(prompt: str, model_name: str, session: requests.Session) -> Optional[str]:
    """Generate a story using the API with retry logic."""
    api_config = get_api_config()
    try:
        response = session.post(
            api_config["ollama_api_url"],
            json={"prompt": prompt, "model": model_name},
            timeout=30