Spaces:
Sleeping
Sleeping
Deployment Script commited on
Commit Β·
2dfc473
1
Parent(s): 6225fce
Deploy multi-agent system
Browse filesFiles changed (21)
- .dockerignoreAdded+31
- .gitignoreAdded+64
- DockerfileAdded+33
- README_SPACE.mdAdded+164
- agents/__init__.pyAdded+18
- agents/comedy_writer.pyAdded+45
- agents/cultural_consultant.pyAdded+45
- agents/dialogue_specialist.pyAdded+46
- agents/lead_writer.pyAdded+46
- agents/proofreader.pyAdded+46
- agents/showrunner.pyAdded+46
- agents/story_editor.pyAdded+45
- app.pyAdded+28
- base_agent.pyAdded+137
- config.pyAdded+82
- env_loader.pyAdded+113
- hf_uploader.pyAdded+110
- main.pyAdded+255
- orchestrator.pyAdded+207
- requirements.txtAdded+10
- setup_space.pyAdded+143
12345678910111213141516171819202122232425262728293031.git.gitignore.env.env.local__pycache__*.pyc*.pyo*.pyd.Pythonenv/venv/.venv.DS_Store*.loglogs/data/output/.pytest_cache.coveragehtmlcov/dist/build/*.egg-info/.idea/.vscode/*.swp*.swo*~.DS_Storenode_modules/npm-debug.log12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364# Environment.env.env.local.env.*.local
# Python__pycache__/*.py[cod]*$py.class*.so.Pythonenv/venv/ENV/build/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/pip-wheel-metadata/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# Testing.pytest_cache/.coveragehtmlcov/
# IDE.vscode/.idea/*.swp*.swo*~.DS_Store
# Logslogs/*.logserver.log
# Data and outputdata/output/*.json
# OS.DS_StoreThumbs.db
# Dependenciesnode_modules/npm-debug.logyarn-error.log123456789101112131415161718192021222324252627282930313233FROM python:3.11-slim
# Set working directoryWORKDIR /app
# Install system dependenciesRUN apt-get update && apt-get install -y \ git \ curl \ && rm -rf /var/lib/apt/lists/*
# Copy requirementsCOPY requirements.txt .
# Install Python dependenciesRUN pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY . .
# Create necessary directoriesRUN mkdir -p data output logs
# Expose portEXPOSE 7860
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ CMD curl -f http://localhost:7860/health || exit 1
# Run setup and start the applicationRUN chmod +x /app/setup_space.pyCMD python setup_space.py && python app.py123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164# Multi-Agent Content Generation System - Hugging Face Space
This is a Hugging Face Space deployment of the multi-agent content generation system. The system orchestrates seven specialized AI agents to collaboratively produce high-quality written content.
## Features
- **7 Specialized Agents** - Showrunner, Story Editor, Cultural Consultant, Lead Writer, Dialogue Specialist, Comedy Writer, and Proofreader- **API-First Architecture** - RESTful endpoints for all operations- **OpenRouter Integration** - Powered by `poolside/laguna-m.1:free` model- **Hugging Face Integration** - Automatic upload of outputs to dataset- **Persistent Storage** - All agent outputs saved as JSON
## Setup
### 1. Create the Space
Go to [Hugging Face Spaces](https://huggingface.co/spaces) and create a new Space:- **Name:** `multi-agent-system` (or your preferred name)- **License:** MIT (or your choice)- **Space SDK:** Docker- **Visibility:** Private (recommended for security)
### 2. Add Secrets
In your Space settings, add the following secrets:
#### `OPENROUTER_API_KEY`Your OpenRouter API key for accessing the `poolside/laguna-m.1:free` model.- Get it from: https://openrouter.ai/keys
#### `HUGGINGFACE_TOKEN`Your Hugging Face user access token with write permissions.- Get it from: https://huggingface.co/settings/tokens- Must have write access to the `factorstudios/Pipeline` dataset
### 3. Configure Environment Variables
Optional environment variables (set in Space settings if needed):
- `HUGGINGFACE_DATASET` - Target dataset (default: `factorstudios/Pipeline`)- `OPENROUTER_BASE_URL` - OpenRouter API endpoint (default: `https://openrouter.ai/api/v1`)- `MODEL_NAME` - Model to use (default: `poolside/laguna-m.1:free`)- `LOG_LEVEL` - Logging level (default: `INFO`)
## Usage
### Health Check
```bashcurl https://your-space-url/health```
### Execute Full Pipeline
```bashcurl -X POST https://your-space-url/api/v1/pipeline/execute \ -H "Content-Type: application/json" \ -d '{ "user_brief": "A comedic episode about...", "season_arc_document": "Season context...", "character_bible": "Character definitions...", "world_building_document": "World context...", "character_voice_guide": "Voice definitions...", "style_guide": "Style reference...", "continuity_log": "Continuity tracking...", "hook_brief": "Optional hook..." }'```
### API Documentation
Visit `https://your-space-url/docs` for interactive API documentation.
## API Endpoints
### Pipeline Management- `GET /health` - Health check- `POST /api/v1/pipeline/execute` - Execute full pipeline- `GET /api/v1/pipeline/status/{run_id}` - Get pipeline status
### Individual Agents- `POST /api/v1/showrunner/generate_directive` - Generate directive- `POST /api/v1/story_editor/generate_outline` - Generate outline- `POST /api/v1/cultural_consultant/review_outline` - Review outline- `POST /api/v1/lead_writer/write_script` - Write script- `POST /api/v1/dialogue_specialist/polish_dialogue` - Polish dialogue- `POST /api/v1/comedy_writer/add_humor` - Add humor- `POST /api/v1/proofreader/final_qc` - Final QC
## Architecture
```FastAPI Server (Port 7860) βPipeline Orchestrator β7 Agent Modules βOpenRouter API (poolside/laguna-m.1:free) βHugging Face Dataset Upload```
## Security
- **Secrets Management** - API keys stored securely in HF Secrets- **No Hardcoded Credentials** - Environment variables loaded at runtime- **HTTPS Only** - All communication encrypted- **Private Space** - Recommended for production use
## Performance
Typical pipeline execution time: **10-15 minutes**
Each agent processes sequentially through the OpenRouter API:1. Showrunner: ~40 seconds2. Story Editor: ~150 seconds3. Cultural Consultant: ~130 seconds4. Lead Writer: ~140 seconds5. Dialogue Specialist: ~50 seconds6. Comedy Writer: ~120 seconds7. Proofreader: ~40 seconds
## Storage
- **Local Storage** - Agent outputs saved in Space filesystem- **Hugging Face Dataset** - Final outputs uploaded to `factorstudios/Pipeline`- **Metadata** - Pipeline execution metadata also uploaded
## Troubleshooting
### 401 Unauthorized- Check `OPENROUTER_API_KEY` is set correctly in Secrets- Verify key has access to `poolside/laguna-m.1:free` model
### 403 Forbidden (Hugging Face)- Check `HUGGINGFACE_TOKEN` is set correctly in Secrets- Verify token has write access to dataset- Confirm dataset exists: `factorstudios/Pipeline`
### Timeout Errors- Pipeline execution can take 10-15 minutes- Increase request timeout to 600+ seconds- Check Space logs for details
### Out of Memory- Spaces have limited memory- Consider splitting pipeline into separate requests- Use individual agent endpoints instead of full pipeline
## Logs
View Space logs in the Hugging Face Space interface for debugging.
## Support
For issues or questions:1. Check the logs in your Space2. Review API documentation at `/docs`3. Verify all Secrets are configured correctly
## License
This project is part of Factor Studios' multi-agent content generation initiative.123456789101112131415161718"""Agent modules for the multi-agent system."""from agents.showrunner import ShowrunnerAgentfrom agents.story_editor import StoryEditorAgentfrom agents.cultural_consultant import CulturalConsultantAgentfrom agents.lead_writer import LeadWriterAgentfrom agents.dialogue_specialist import DialogueSpecialistAgentfrom agents.comedy_writer import ComedyWriterAgentfrom agents.proofreader import ProofreaderAgent
__all__ = [ "ShowrunnerAgent", "StoryEditorAgent", "CulturalConsultantAgent", "LeadWriterAgent", "DialogueSpecialistAgent", "ComedyWriterAgent", "ProofreaderAgent",]123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Comedy Writer agent - Humor enhancement specialist."""from typing import Any, Dictfrom base_agent import BaseAgent
class ComedyWriterAgent(BaseAgent): """Comedy Writer agent that enhances script with humor."""
def __init__(self): """Initialize the Comedy Writer agent.""" system_prompt = ( "You are the Comedy Writer. Punch up the script β sharpen punchlines, tighten " "comic timing, make the first 3 seconds irresistible. Don't break the story. " "Return the improved full script with a note on what you changed as JSON with keys: " "comedy_sharpened_script, punch_up_notes, hook_rewrite_for_opening." ) super().__init__( agent_id="comedy-writer", agent_name="Comedy Writer", system_prompt=system_prompt, )
def add_humor(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Add humor and punch-ups to the script.
Args: inputs: Dictionary with keys: - dialogue_polished_script: From Dialogue Specialist - hook_brief_from_showrunner: Hook context
Returns: Dictionary with comedy-enhanced script and notes """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="comedy_punch_up.json", ) return outputs123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Cultural Consultant agent - Authenticity specialist."""from typing import Any, Dictfrom base_agent import BaseAgent
class CulturalConsultantAgent(BaseAgent): """Cultural Consultant agent that ensures cultural accuracy."""
def __init__(self): """Initialize the Cultural Consultant agent.""" system_prompt = ( "You are the Cultural Consultant. Review the episode outline for cultural accuracy, " "stereotypes, or misrepresentations. Return a brief report as a JSON object with keys: " "cultural_accuracy_notes, reference_suggestions, flagged_inaccuracies, " "approved_cultural_touchpoints. Be direct." ) super().__init__( agent_id="cultural-consultant", agent_name="Cultural Consultant", system_prompt=system_prompt, )
def review_outline(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Review outline for cultural accuracy.
Args: inputs: Dictionary with keys: - episode_outline: From Story Editor - world_building_document: World context
Returns: Dictionary with cultural review and recommendations """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="cultural_review.json", ) return outputs12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Dialogue Specialist agent - Voice polish expert."""from typing import Any, Dictfrom base_agent import BaseAgent
class DialogueSpecialistAgent(BaseAgent): """Dialogue Specialist agent that refines dialogue for authenticity."""
def __init__(self): """Initialize the Dialogue Specialist agent.""" system_prompt = ( "You are the Dialogue Specialist. Polish the script's dialogue only β don't touch " "action lines or structure. Make each character's speech feel authentic, natural, and " "distinct. Return the full script with improved dialogue as JSON with keys: " "dialogue_polished_script, voice_consistency_notes." ) super().__init__( agent_id="dialogue-specialist", agent_name="Dialogue Specialist", system_prompt=system_prompt, )
def polish_dialogue(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Polish dialogue in the script.
Args: inputs: Dictionary with keys: - first_draft_script: From Lead Writer - character_voice_guide: Character voice definitions - dialect_slang_reference: Reference material
Returns: Dictionary with polished script and voice notes """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="polished_dialogue.json", ) return outputs12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Lead Writer agent - Script creation specialist."""from typing import Any, Dictfrom base_agent import BaseAgent
class LeadWriterAgent(BaseAgent): """Lead Writer agent that crafts the first draft script."""
def __init__(self): """Initialize the Lead Writer agent.""" system_prompt = ( "You are the Lead Writer. Using the outline and cultural notes, write a complete " "episode script. Each character must speak in their own voice. Include scene headings, " "action lines, and dialogue. Format it like a proper script. Output as JSON with keys: " "full_episode_first_draft, scene_descriptions, dialogue, stage_directions." ) super().__init__( agent_id="lead-writer", agent_name="Lead Writer", system_prompt=system_prompt, )
def write_script(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Write episode script from outline and cultural notes.
Args: inputs: Dictionary with keys: - approved_outline: From Story Editor - cultural_consultant_notes: From Cultural Consultant - character_voice_guide: Character definitions
Returns: Dictionary with generated script and related outputs """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="first_draft.json", ) return outputs12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Proofreader agent - Quality control specialist."""from typing import Any, Dictfrom base_agent import BaseAgent
class ProofreaderAgent(BaseAgent): """Proofreader agent that performs final quality control."""
def __init__(self): """Initialize the Proofreader agent.""" system_prompt = ( "You are the Script Proofreader. Check for grammar, formatting, continuity errors, " "character name consistency, and style guide violations. Return the corrected final " "script and a brief QC report as JSON with keys: final_locked_script, qc_report, " "continuity_log_update." ) super().__init__( agent_id="proofreader", agent_name="Proofreader", system_prompt=system_prompt, )
def final_qc(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Perform final quality control on the script.
Args: inputs: Dictionary with keys: - comedy_sharpened_script: From Comedy Writer - style_guide: Style reference - continuity_log: Continuity tracking
Returns: Dictionary with final script and QC report """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="final_qc.json", ) return outputs12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Showrunner agent - Orchestrator for content generation."""from typing import Any, Dictfrom base_agent import BaseAgent
class ShowrunnerAgent(BaseAgent): """Orchestrator agent that translates briefs into actionable directives."""
def __init__(self): """Initialize the Showrunner agent.""" system_prompt = ( "You are the Showrunner. Given a brief, produce a tight episode directive: " "premise, tone, which characters are featured, and the emotional core. " "Keep it under 200 words. Output only the directive as a JSON object with keys: " "episode_directive, story_premise, tone_brief, character_focus_notes." ) super().__init__( agent_id="showrunner", agent_name="Showrunner", system_prompt=system_prompt, )
def generate_directive(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Generate episode directive from user brief.
Args: inputs: Dictionary with keys: - user_brief: The initial brief - season_arc_document: Season context - character_bible: Character definitions
Returns: Dictionary with generated directive and related outputs """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="directive.json", ) return outputs123456789101112131415161718192021222324252627282930313233343536373839404142434445"""Story Editor agent - Structure specialist for content."""from typing import Any, Dictfrom base_agent import BaseAgent
class StoryEditorAgent(BaseAgent): """Story Editor agent that develops structural outlines."""
def __init__(self): """Initialize the Story Editor agent.""" system_prompt = ( "You are the Story Editor. Given a showrunner directive, produce a structured " "episode outline with clear act breaks, a hook, rising tension, and a satisfying end. " "Flag any continuity risks. Output the outline as a JSON object with keys: " "episode_outline, act_structure, story_notes_for_writers." ) super().__init__( agent_id="story-editor", agent_name="Story Editor", system_prompt=system_prompt, )
def generate_outline(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Generate episode outline from showrunner directive.
Args: inputs: Dictionary with keys: - episode_directive: From Showrunner - series_continuity_log: Continuity reference
Returns: Dictionary with generated outline and related outputs """ outputs = self.process(inputs) # Save state self.save_state( { "inputs": inputs, "outputs": outputs, }, filename="outline.json", ) return outputs12345678910111213141516171819202122232425262728"""Hugging Face Spaces wrapper for the multi-agent system."""import osimport sysfrom pathlib import Path
# Set environment variables from HF Secretsos.environ["OPENROUTER_API_KEY"] = os.getenv("OPENROUTER_API_KEY", "")os.environ["HUGGINGFACE_TOKEN"] = os.getenv("HUGGINGFACE_TOKEN", "")os.environ["HUGGINGFACE_DATASET"] = os.getenv("HUGGINGFACE_DATASET", "factorstudios/Pipeline")os.environ["OPENROUTER_BASE_URL"] = os.getenv("OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1")os.environ["MODEL_NAME"] = os.getenv("MODEL_NAME", "poolside/laguna-m.1:free")
# Import and run the FastAPI appfrom main import app
if __name__ == "__main__": import uvicorn # Get port from environment or use default port = int(os.getenv("PORT", 7860)) # Run the server uvicorn.run( app, host="0.0.0.0", port=port, log_level="info", )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137"""Base agent module for all specialized agents."""import jsonimport loggingfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, Optionalfrom openai import OpenAIfrom config import settings
logger = logging.getLogger(__name__)
class BaseAgent: """Base class for all agents in the system."""
def __init__(self, agent_id: str, agent_name: str, system_prompt: str): """Initialize the base agent.
Args: agent_id: Unique identifier for the agent agent_name: Human-readable name of the agent system_prompt: System prompt for the agent's behavior """ self.agent_id = agent_id self.agent_name = agent_name self.system_prompt = system_prompt # Initialize OpenRouter client self.client = OpenAI( api_key=settings.openrouter_api_key, base_url=settings.openrouter_base_url, ) # Data storage self.data_dir = Path(settings.data_dir) / agent_id self.data_dir.mkdir(parents=True, exist_ok=True) logger.info(f"Initialized agent: {agent_name} ({agent_id})")
def process(self, inputs: Dict[str, Any]) -> Dict[str, Any]: """Process inputs and generate outputs using the LLM.
Args: inputs: Dictionary containing input data for the agent
Returns: Dictionary containing the agent's outputs """ # Prepare the prompt input_text = json.dumps(inputs, indent=2) logger.info(f"{self.agent_name}: Processing inputs") try: # Call OpenRouter API via OpenAI client response = self.client.chat.completions.create( model=settings.model_name, messages=[ { "role": "system", "content": self.system_prompt, }, { "role": "user", "content": f"Process the following inputs:\n\n{input_text}", }, ], temperature=0.7, max_tokens=4096, ) output_text = response.choices[0].message.content # Parse output (assuming JSON format) try: output_data = json.loads(output_text) except json.JSONDecodeError: # If not JSON, wrap in a generic output output_data = {"output": output_text} logger.info(f"{self.agent_name}: Processing completed") return output_data except Exception as e: logger.error(f"{self.agent_name}: Error during processing - {str(e)}") raise
def save_state(self, data: Dict[str, Any], filename: Optional[str] = None) -> str: """Save agent state and data to persistent JSON storage.
Args: data: Data to save filename: Optional custom filename (defaults to timestamp)
Returns: Path to saved file """ if filename is None: timestamp = datetime.now().isoformat().replace(":", "-") filename = f"{self.agent_id}_{timestamp}.json" filepath = self.data_dir / filename # Add metadata state_data = { "agent_id": self.agent_id, "agent_name": self.agent_name, "timestamp": datetime.now().isoformat(), "data": data, } with open(filepath, "w") as f: json.dump(state_data, f, indent=2) logger.info(f"{self.agent_name}: State saved to {filepath}") return str(filepath)
def load_state(self, filename: str) -> Dict[str, Any]: """Load agent state from persistent storage.
Args: filename: Filename to load
Returns: Loaded data """ filepath = self.data_dir / filename with open(filepath, "r") as f: state_data = json.load(f) logger.info(f"{self.agent_name}: State loaded from {filepath}") return state_data.get("data", {})12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""Configuration module for the multi-agent system."""import osimport loggingfrom pathlib import Pathfrom pydantic_settings import BaseSettingsfrom env_loader import EnvironmentLoader, validate_on_startup
logger = logging.getLogger(__name__)
# Validate secrets on startupvalidate_on_startup()
class Settings(BaseSettings): """Application settings loaded from environment variables."""
# OpenRouter Configuration openrouter_api_key: str = "" openrouter_base_url: str = "https://openrouter.ai/api/v1" model_name: str = "poolside/laguna-m.1:free"
# Hugging Face Configuration huggingface_token: str = "" huggingface_dataset: str = "factorstudios/Pipeline" huggingface_api_url: str = "https://huggingface.co/api"
# System Configuration data_dir: str = "./data" output_dir: str = "./output" log_dir: str = "./logs" port: int = 8000 host: str = "0.0.0.0"
# Agent Ports showrunner_port: int = 8001 story_editor_port: int = 8002 cultural_consultant_port: int = 8003 lead_writer_port: int = 8004 dialogue_specialist_port: int = 8005 comedy_writer_port: int = 8006 proofreader_port: int = 8007
# Logging log_level: str = "INFO"
class Config: env_file = ".env" case_sensitive = False extra = "allow" # Allow extra fields
def __init__(self, **data): # Load from environment with fallbacks if not data.get("openrouter_api_key"): data["openrouter_api_key"] = os.getenv("OPENROUTER_API_KEY", "") if not data.get("huggingface_token"): data["huggingface_token"] = os.getenv("HUGGINGFACE_TOKEN", "") if not data.get("huggingface_dataset"): data["huggingface_dataset"] = os.getenv( "HUGGINGFACE_DATASET", "factorstudios/Pipeline" ) if not data.get("openrouter_base_url"): data["openrouter_base_url"] = os.getenv( "OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1" ) if not data.get("model_name"): data["model_name"] = os.getenv( "MODEL_NAME", "poolside/laguna-m.1:free" )
super().__init__(**data) # Create necessary directories Path(self.data_dir).mkdir(parents=True, exist_ok=True) Path(self.output_dir).mkdir(parents=True, exist_ok=True) Path(self.log_dir).mkdir(parents=True, exist_ok=True)
logger.info("Configuration loaded successfully") logger.info(f"Model: {self.model_name}") logger.info(f"Dataset: {self.huggingface_dataset}")
# Load settingssettings = Settings()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113"""Environment variable loader with HF Secrets support."""import osimport loggingfrom typing import Optional
logger = logging.getLogger(__name__)
class EnvironmentLoader: """Loads environment variables with support for HF Secrets."""
@staticmethod def get_secret(key: str, default: Optional[str] = None) -> str: """Get environment variable or secret.
In Hugging Face Spaces, secrets are injected as environment variables. This function provides a consistent interface for accessing them.
Args: key: Environment variable name default: Default value if not found
Returns: Environment variable value or default
Raises: ValueError: If required variable is missing and no default provided """ value = os.getenv(key, default)
if value is None: raise ValueError( f"Required environment variable '{key}' is not set. " f"Please add it to HF Secrets in your Space settings." )
if not value: logger.warning(f"Environment variable '{key}' is empty")
return value
@staticmethod def validate_secrets() -> bool: """Validate that all required secrets are configured.
Returns: True if all required secrets are present, False otherwise """ required_secrets = [ "OPENROUTER_API_KEY", "HUGGINGFACE_TOKEN", ]
optional_secrets = [ "HUGGINGFACE_DATASET", "OPENROUTER_BASE_URL", "MODEL_NAME", ]
all_valid = True
# Check required secrets for secret in required_secrets: value = os.getenv(secret) if not value: logger.error(f"Missing required secret: {secret}") all_valid = False else: # Log masked value for debugging masked = value[:10] + "..." if len(value) > 10 else "***" logger.info(f"β {secret} configured ({masked})")
# Check optional secrets for secret in optional_secrets: value = os.getenv(secret) if value: masked = value[:10] + "..." if len(value) > 10 else "***" logger.info(f"β {secret} configured ({masked})") else: logger.info(f"βΉ {secret} not configured (using default)")
return all_valid
@staticmethod def get_api_config() -> dict: """Get API configuration from environment.
Returns: Dictionary with API configuration """ return { "openrouter_api_key": EnvironmentLoader.get_secret("OPENROUTER_API_KEY"), "openrouter_base_url": os.getenv( "OPENROUTER_BASE_URL", "https://openrouter.ai/api/v1" ), "model_name": os.getenv("MODEL_NAME", "poolside/laguna-m.1:free"), "huggingface_token": EnvironmentLoader.get_secret("HUGGINGFACE_TOKEN"), "huggingface_dataset": os.getenv( "HUGGINGFACE_DATASET", "factorstudios/Pipeline" ), }
# Validate secrets on importdef validate_on_startup(): """Validate secrets when module is imported.""" if not EnvironmentLoader.validate_secrets(): logger.warning( "Some secrets are not configured. " "The application may not work correctly. " "Please add missing secrets to HF Secrets in your Space settings." )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110"""Hugging Face dataset uploader for final outputs."""import jsonimport loggingfrom pathlib import Pathfrom datetime import datetimefrom huggingface_hub import HfApi, CommitOperationAddfrom config import settings
logger = logging.getLogger(__name__)
class HFUploader: """Handles uploading final outputs to Hugging Face dataset."""
def __init__(self): """Initialize the Hugging Face uploader.""" self.api = HfApi() self.token = settings.huggingface_token self.dataset_id = settings.huggingface_dataset logger.info(f"Initialized HF uploader for dataset: {self.dataset_id}")
def upload_final_output(self, final_data: dict, run_id: str) -> str: """Upload final output to Hugging Face dataset.
Args: final_data: The final processed data from the pipeline run_id: Unique identifier for this pipeline run
Returns: URL of the uploaded file """ try: # Prepare the data upload_data = { "run_id": run_id, "timestamp": datetime.now().isoformat(), "final_output": final_data, }
# Create filename filename = f"output_{run_id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
# Convert to JSON string json_content = json.dumps(upload_data, indent=2)
# Create commit operation commit_operation = CommitOperationAdd( path_in_repo=f"outputs/{filename}", path_or_fileobj=json_content.encode("utf-8"), )
# Upload to dataset commit_info = self.api.create_commit( repo_id=self.dataset_id, repo_type="dataset", operations=[commit_operation], commit_message=f"Pipeline output: {run_id}", token=self.token, )
file_url = f"https://huggingface.co/datasets/{self.dataset_id}/blob/main/outputs/{filename}" logger.info(f"Successfully uploaded to HF: {file_url}")
return file_url
except Exception as e: logger.error(f"Error uploading to Hugging Face: {str(e)}") raise
def upload_pipeline_metadata(self, metadata: dict) -> str: """Upload pipeline metadata to Hugging Face dataset.
Args: metadata: Pipeline metadata including all agent outputs
Returns: URL of the uploaded metadata file """ try: # Create filename timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"metadata_{timestamp}.json"
# Convert to JSON string json_content = json.dumps(metadata, indent=2)
# Create commit operation commit_operation = CommitOperationAdd( path_in_repo=f"metadata/{filename}", path_or_fileobj=json_content.encode("utf-8"), )
# Upload to dataset commit_info = self.api.create_commit( repo_id=self.dataset_id, repo_type="dataset", operations=[commit_operation], commit_message=f"Pipeline metadata: {timestamp}", token=self.token, )
file_url = f"https://huggingface.co/datasets/{self.dataset_id}/blob/main/metadata/{filename}" logger.info(f"Successfully uploaded metadata to HF: {file_url}")
return file_url
except Exception as e: logger.error(f"Error uploading metadata to Hugging Face: {str(e)}") raise123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255"""FastAPI server for the multi-agent content generation system."""import loggingfrom fastapi import FastAPI, HTTPExceptionfrom pydantic import BaseModelfrom typing import Optionalfrom orchestrator import PipelineOrchestratorfrom config import settings
# Configure logginglogging.basicConfig( level=settings.log_level, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)logger = logging.getLogger(__name__)
# Initialize FastAPI appapp = FastAPI( title="Multi-Agent Content Generation System", description="API-first system for collaborative content generation using poolside/laguna-m.1:free", version="1.0.0",)
# Initialize orchestratororchestrator = PipelineOrchestrator()
# Request/Response Modelsclass PipelineRequest(BaseModel): """Request model for pipeline execution.""" user_brief: str season_arc_document: str character_bible: str world_building_document: str character_voice_guide: str style_guide: str continuity_log: str hook_brief: Optional[str] = None
class PipelineResponse(BaseModel): """Response model for pipeline execution.""" run_id: str status: str final_output: dict hf_output_url: str hf_metadata_url: str
class HealthResponse(BaseModel): """Health check response.""" status: str run_id: str
# Endpoints@app.get("/health", response_model=HealthResponse)async def health_check(): """Health check endpoint.""" return { "status": "healthy", "run_id": orchestrator.run_id, }
@app.post("/api/v1/pipeline/execute", response_model=PipelineResponse)async def execute_pipeline(request: PipelineRequest): """Execute the full content generation pipeline.
Args: request: Pipeline execution request with all required inputs
Returns: Pipeline execution result with final output and URLs """ try: logger.info(f"Received pipeline execution request: {request.user_brief[:50]}...") result = orchestrator.execute_pipeline( user_brief=request.user_brief, season_arc_document=request.season_arc_document, character_bible=request.character_bible, world_building_document=request.world_building_document, character_voice_guide=request.character_voice_guide, style_guide=request.style_guide, continuity_log=request.continuity_log, hook_brief=request.hook_brief, ) return { "run_id": result["run_id"], "status": result["status"], "final_output": result["final_output"], "hf_output_url": result["hf_output_url"], "hf_metadata_url": result["hf_metadata_url"], } except Exception as e: logger.error(f"Pipeline execution error: {str(e)}") raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/showrunner/generate_directive")async def generate_directive(request: dict): """Generate episode directive from user brief.
Args: request: Dictionary with user_brief, season_arc_document, character_bible
Returns: Generated directive """ try: result = orchestrator.showrunner.generate_directive(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/story_editor/generate_outline")async def generate_outline(request: dict): """Generate episode outline from directive.
Args: request: Dictionary with episode_directive, series_continuity_log
Returns: Generated outline """ try: result = orchestrator.story_editor.generate_outline(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/cultural_consultant/review_outline")async def review_outline(request: dict): """Review outline for cultural accuracy.
Args: request: Dictionary with episode_outline, world_building_document
Returns: Cultural review and recommendations """ try: result = orchestrator.cultural_consultant.review_outline(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/lead_writer/write_script")async def write_script(request: dict): """Write episode script from outline and cultural notes.
Args: request: Dictionary with approved_outline, cultural_consultant_notes, character_voice_guide
Returns: Generated script """ try: result = orchestrator.lead_writer.write_script(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/dialogue_specialist/polish_dialogue")async def polish_dialogue(request: dict): """Polish dialogue in the script.
Args: request: Dictionary with first_draft_script, character_voice_guide, dialect_slang_reference
Returns: Polished script """ try: result = orchestrator.dialogue_specialist.polish_dialogue(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/comedy_writer/add_humor")async def add_humor(request: dict): """Add humor and punch-ups to the script.
Args: request: Dictionary with dialogue_polished_script, hook_brief_from_showrunner
Returns: Comedy-enhanced script """ try: result = orchestrator.comedy_writer.add_humor(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.post("/api/v1/proofreader/final_qc")async def final_qc(request: dict): """Perform final quality control on the script.
Args: request: Dictionary with comedy_sharpened_script, style_guide, continuity_log
Returns: Final QC report and locked script """ try: result = orchestrator.proofreader.final_qc(request) return result except Exception as e: raise HTTPException(status_code=500, detail=str(e))
@app.get("/api/v1/pipeline/status/{run_id}")async def get_pipeline_status(run_id: str): """Get the status of a pipeline run.
Args: run_id: The run ID to check
Returns: Pipeline status and state """ try: # In a real system, this would query a database # For now, we return the current orchestrator state if it matches if run_id == orchestrator.run_id: return { "run_id": run_id, "status": orchestrator.pipeline_state.get("status", "unknown"), "pipeline_state": orchestrator.pipeline_state, } else: raise HTTPException(status_code=404, detail="Run ID not found") except Exception as e: raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__": import uvicorn uvicorn.run( app, host=settings.host, port=settings.port, log_level=settings.log_level.lower(), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207"""Pipeline orchestrator that manages agent flow and data passing."""import jsonimport loggingimport uuidfrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Dict, Optionalfrom agents import ( ShowrunnerAgent, StoryEditorAgent, CulturalConsultantAgent, LeadWriterAgent, DialogueSpecialistAgent, ComedyWriterAgent, ProofreaderAgent,)from hf_uploader import HFUploaderfrom config import settings
logger = logging.getLogger(__name__)
class PipelineOrchestrator: """Orchestrates the multi-agent content generation pipeline."""
def __init__(self): """Initialize the orchestrator with all agents.""" self.showrunner = ShowrunnerAgent() self.story_editor = StoryEditorAgent() self.cultural_consultant = CulturalConsultantAgent() self.lead_writer = LeadWriterAgent() self.dialogue_specialist = DialogueSpecialistAgent() self.comedy_writer = ComedyWriterAgent() self.proofreader = ProofreaderAgent() self.hf_uploader = HFUploader() # Pipeline state self.run_id = str(uuid.uuid4()) self.pipeline_state = { "run_id": self.run_id, "start_time": datetime.now().isoformat(), "stages": {}, } logger.info(f"Initialized pipeline orchestrator with run_id: {self.run_id}")
def execute_pipeline( self, user_brief: str, season_arc_document: str, character_bible: str, world_building_document: str, character_voice_guide: str, style_guide: str, continuity_log: str, hook_brief: Optional[str] = None, ) -> Dict[str, Any]: """Execute the full content generation pipeline.
Args: user_brief: Initial user brief season_arc_document: Season context character_bible: Character definitions world_building_document: World context character_voice_guide: Character voice definitions style_guide: Style reference continuity_log: Continuity tracking hook_brief: Optional hook brief for comedy writer
Returns: Dictionary with final output and metadata """ try: logger.info("Starting pipeline execution")
# Stage 1: Showrunner logger.info("Stage 1: Showrunner - Generating directive") showrunner_inputs = { "user_brief": user_brief, "season_arc_document": season_arc_document, "character_bible": character_bible, } showrunner_output = self.showrunner.generate_directive(showrunner_inputs) self.pipeline_state["stages"]["showrunner"] = showrunner_output logger.info("Stage 1 completed")
# Stage 2: Story Editor logger.info("Stage 2: Story Editor - Generating outline") story_editor_inputs = { "episode_directive": showrunner_output.get( "episode_directive", "" ), "series_continuity_log": continuity_log, } story_editor_output = self.story_editor.generate_outline( story_editor_inputs ) self.pipeline_state["stages"]["story_editor"] = story_editor_output logger.info("Stage 2 completed")
# Stage 3: Cultural Consultant (parallel with Lead Writer) logger.info("Stage 3: Cultural Consultant - Reviewing outline") cultural_inputs = { "episode_outline": story_editor_output.get("episode_outline", ""), "world_building_document": world_building_document, } cultural_output = self.cultural_consultant.review_outline(cultural_inputs) self.pipeline_state["stages"]["cultural_consultant"] = cultural_output logger.info("Stage 3 completed")
# Stage 4: Lead Writer logger.info("Stage 4: Lead Writer - Writing script") lead_writer_inputs = { "approved_outline": story_editor_output.get("episode_outline", ""), "cultural_consultant_notes": cultural_output.get( "cultural_accuracy_notes", "" ), "character_voice_guide": character_voice_guide, } lead_writer_output = self.lead_writer.write_script(lead_writer_inputs) self.pipeline_state["stages"]["lead_writer"] = lead_writer_output logger.info("Stage 4 completed")
# Stage 5: Dialogue Specialist logger.info("Stage 5: Dialogue Specialist - Polishing dialogue") dialogue_inputs = { "first_draft_script": lead_writer_output.get( "full_episode_first_draft", "" ), "character_voice_guide": character_voice_guide, "dialect_slang_reference": "", } dialogue_output = self.dialogue_specialist.polish_dialogue(dialogue_inputs) self.pipeline_state["stages"]["dialogue_specialist"] = dialogue_output logger.info("Stage 5 completed")
# Stage 6: Comedy Writer logger.info("Stage 6: Comedy Writer - Adding humor") comedy_inputs = { "dialogue_polished_script": dialogue_output.get( "dialogue_polished_script", "" ), "hook_brief_from_showrunner": hook_brief or user_brief, } comedy_output = self.comedy_writer.add_humor(comedy_inputs) self.pipeline_state["stages"]["comedy_writer"] = comedy_output logger.info("Stage 6 completed")
# Stage 7: Proofreader (Final QC) logger.info("Stage 7: Proofreader - Final quality control") proofreader_inputs = { "comedy_sharpened_script": comedy_output.get( "comedy_sharpened_script", "" ), "style_guide": style_guide, "continuity_log": continuity_log, } proofreader_output = self.proofreader.final_qc(proofreader_inputs) self.pipeline_state["stages"]["proofreader"] = proofreader_output logger.info("Stage 7 completed")
# Mark completion self.pipeline_state["end_time"] = datetime.now().isoformat() self.pipeline_state["status"] = "completed"
# Save local state self._save_pipeline_state()
# Upload to Hugging Face logger.info("Uploading final output to Hugging Face") hf_url = self.hf_uploader.upload_final_output( proofreader_output, self.run_id ) hf_metadata_url = self.hf_uploader.upload_pipeline_metadata( self.pipeline_state )
final_result = { "run_id": self.run_id, "status": "success", "final_output": proofreader_output, "hf_output_url": hf_url, "hf_metadata_url": hf_metadata_url, "pipeline_state": self.pipeline_state, }
logger.info("Pipeline execution completed successfully") return final_result
except Exception as e: logger.error(f"Pipeline execution failed: {str(e)}") self.pipeline_state["status"] = "failed" self.pipeline_state["error"] = str(e) self._save_pipeline_state() raise
def _save_pipeline_state(self) -> None: """Save the pipeline state to local storage.""" output_dir = Path(settings.output_dir) output_dir.mkdir(parents=True, exist_ok=True) state_file = output_dir / f"pipeline_{self.run_id}.json" with open(state_file, "w") as f: json.dump(self.pipeline_state, f, indent=2) logger.info(f"Pipeline state saved to {state_file}")12345678910fastapi==0.104.1uvicorn==0.24.0python-dotenv==1.0.0requests==2.31.0pydantic==2.5.0pydantic-settings==2.1.0openai==1.3.0huggingface-hub==0.19.4aiofiles==23.2.1httpx==0.25.1123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143"""Setup script for Hugging Face Spaces deployment."""import osimport sysimport loggingfrom pathlib import Path
logging.basicConfig( level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",)logger = logging.getLogger(__name__)
def check_environment(): """Check if running in Hugging Face Space environment.""" is_hf_space = os.getenv("SPACE_ID") is not None return is_hf_space
def validate_secrets(): """Validate that required secrets are configured.""" required_secrets = [ "OPENROUTER_API_KEY", "HUGGINGFACE_TOKEN", ]
optional_secrets = [ "HUGGINGFACE_DATASET", "OPENROUTER_BASE_URL", "MODEL_NAME", ]
logger.info("=" * 60) logger.info("Validating Hugging Face Secrets") logger.info("=" * 60)
missing_secrets = []
# Check required secrets for secret in required_secrets: value = os.getenv(secret) if not value: logger.error(f"β MISSING: {secret}") missing_secrets.append(secret) else: masked = value[:10] + "..." if len(value) > 10 else "***" logger.info(f"β CONFIGURED: {secret} ({masked})")
# Check optional secrets for secret in optional_secrets: value = os.getenv(secret) if value: masked = value[:10] + "..." if len(value) > 10 else "***" logger.info(f"β CONFIGURED: {secret} ({masked})") else: logger.info(f"βΉ NOT SET: {secret} (using default)")
logger.info("=" * 60)
if missing_secrets: logger.error(f"\nβ Missing required secrets: {', '.join(missing_secrets)}") logger.error("\nPlease add these secrets to your Space:") logger.error("1. Go to your Space settings") logger.error("2. Click 'Repository secrets'") logger.error("3. Add each missing secret") return False
logger.info("\nβ
All required secrets are configured!") return True
def create_directories(): """Create necessary directories.""" directories = [ "./data", "./output", "./logs", ]
logger.info("\nCreating directories...") for directory in directories: Path(directory).mkdir(parents=True, exist_ok=True) logger.info(f"β {directory}")
def print_deployment_info(): """Print deployment information.""" logger.info("\n" + "=" * 60) logger.info("Deployment Information") logger.info("=" * 60)
is_hf_space = check_environment()
if is_hf_space: space_id = os.getenv("SPACE_ID", "unknown") logger.info(f"β Running in Hugging Face Space: {space_id}") logger.info(f"β Space URL: https://huggingface.co/spaces/{space_id}") else: logger.info("βΉ Not running in Hugging Face Space") logger.info("βΉ Running locally or in different environment")
logger.info(f"β Model: {os.getenv('MODEL_NAME', 'poolside/laguna-m.1:free')}") logger.info(f"β Dataset: {os.getenv('HUGGINGFACE_DATASET', 'factorstudios/Pipeline')}") logger.info(f"β Port: {os.getenv('PORT', '7860')}")
logger.info("\n" + "=" * 60) logger.info("API Endpoints") logger.info("=" * 60) logger.info("Health: GET /health") logger.info("Docs: GET /docs") logger.info("Pipeline: POST /api/v1/pipeline/execute") logger.info("=" * 60)
def main(): """Run setup checks.""" logger.info("Starting Hugging Face Space setup...\n")
# Check environment is_hf_space = check_environment()
# Validate secrets secrets_valid = validate_secrets()
# Create directories create_directories()
# Print info print_deployment_info()
if not secrets_valid: logger.error("\nβ Setup validation failed!") sys.exit(1)
logger.info("\nβ
Setup validation passed!") logger.info("The application is ready to start.\n")
return 0
if __name__ == "__main__": sys.exit(main()).dockerignoreAdded+31
.gitignoreAdded+64
DockerfileAdded+33
README_SPACE.mdAdded+164
agents/__init__.pyAdded+18
agents/comedy_writer.pyAdded+45
agents/cultural_consultant.pyAdded+45
agents/dialogue_specialist.pyAdded+46
agents/lead_writer.pyAdded+46
agents/proofreader.pyAdded+46
agents/showrunner.pyAdded+46
agents/story_editor.pyAdded+45
app.pyAdded+28
base_agent.pyAdded+137
config.pyAdded+82
env_loader.pyAdded+113
hf_uploader.pyAdded+110
main.pyAdded+255
orchestrator.pyAdded+207
requirements.txtAdded+10
setup_space.pyAdded+143