Template-Based Code Generation
==============================

PyGEAI provides a powerful template system that generates production-ready code for common AI development patterns. 
Templates help you quickly bootstrap new projects with best practices built-in.

Overview
--------

The template generation feature (``geai generate``) provides:

- **Instant Project Setup**: Generate complete, runnable projects in seconds
- **Best Practices**: Templates follow PyGEAI SDK patterns and conventions
- **Multiple Use Cases**: RAG assistants, Lab agents, multi-agent systems, APIs, and UIs
- **Interactive & Non-Interactive**: CLI prompts for parameters or pass them via flags
- **Production-Ready**: Generated code includes documentation, error handling, and cleanup logic

Available Templates
-------------------

RAG Templates
^^^^^^^^^^^^^

**rag-basic**
  Create a basic RAG (Retrieval-Augmented Generation) assistant with document knowledge.
  
  Generated files:
    - ``create_<name>.py`` - Creates the RAG assistant
    - ``chat_<name>.py`` - Interactive chat client
    - ``upload_documents.py`` - Document upload utility
    - ``README.md`` - Complete usage documentation
    - ``documents/`` - Directory for your documents
  
  Parameters:
    - ``--name``: Assistant name
    - ``--description``: Assistant description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template rag-basic \
          --name my_rag \
          --description "Support documentation assistant" \
          --output ./my_rag_project

**chat-rag-streaming**
  Interactive streaming chat interface for existing RAG assistants.
  
  Generated files:
    - ``chat_<name>.py`` - Streaming chat client with real-time responses
    - ``README.md`` - Usage instructions
  
  Parameters:
    - ``--name``: Existing RAG assistant name
    - ``--description``: Chat session description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template chat-rag-streaming \
          --name support_rag \
          --output ./rag_chat

Lab Agent Templates
^^^^^^^^^^^^^^^^^^^

**lab-agent-basic**
  Basic AI Lab agent with custom prompt and optional tools.
  
  Generated files:
    - ``create_<name>.py`` - Agent creation script
    - ``run_<name>.py`` - Agent execution script
    - ``README.md`` - Documentation and examples
  
  Parameters:
    - ``--name``: Agent name
    - ``--description``: Agent description
    - ``--instructions``: Agent system prompt/instructions
  
  Example:
    .. code-block:: shell
    
        geai generate create --template lab-agent-basic \
          --name code_reviewer \
          --description "Code review agent" \
          --instructions "You are an expert code reviewer. Focus on best practices and security."

**lab-agent-tools**
  AI Lab agent with custom tools for extended capabilities.
  
  Generated files:
    - ``create_tool_<tool_name>.py`` - Tool creation script
    - ``create_<agent_name>.py`` - Agent creation with tool binding
    - ``run_<agent_name>.py`` - Agent execution script
    - ``README.md`` - Tool and agent documentation
  
  Parameters:
    - ``--name``: Agent name
    - ``--description``: Agent description
    - ``--instructions``: Agent instructions
    - ``--tool-name``: Custom tool name
    - ``--tool-description``: Tool description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template lab-agent-tools \
          --name data_analyst \
          --instructions "Analyze data using calculator tool" \
          --tool-name calculator \
          --tool-description "Performs mathematical calculations"

**chat-agent-streaming**
  Interactive streaming chat with Lab agents.
  
  Generated files:
    - ``chat_<name>.py`` - Streaming chat interface
    - ``README.md`` - Usage guide
  
  Parameters:
    - ``--name``: Existing agent name
    - ``--description``: Chat description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template chat-agent-streaming \
          --name code_reviewer

Workflow Templates
^^^^^^^^^^^^^^^^^^

**lab-process-basic**
  Basic Lab agentic process with workflow orchestration.
  
  Generated files:
    - ``create_artifact_type.py`` - Artifact type definition
    - ``create_kb.py`` - Knowledge base creation
    - ``create_task.py`` - Task definition
    - ``create_process.py`` - Process orchestration
    - ``README.md`` - Complete workflow documentation
  
  Parameters:
    - ``--name``: Process name
    - ``--description``: Process description
    - ``--agent-name``: Existing agent to use
    - ``--task-name``: Task identifier
  
  Example:
    .. code-block:: shell
    
        geai generate create --template lab-process-basic \
          --name content_workflow \
          --agent-name writer_agent \
          --task-name write_article

**chat-flow-streaming**
  Interactive streaming chat with Lab agentic processes/flows.
  
  Generated files:
    - ``chat_<name>.py`` - Process chat interface
    - ``README.md`` - Usage documentation
  
  Parameters:
    - ``--name``: Existing process/flow name
    - ``--description``: Chat description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template chat-flow-streaming \
          --name content_workflow

**lab-multi-agent**
  Multi-agent system with specialized agents working together.
  
  Generated files:
    - ``create_agents.py`` - Creates researcher, writer, and reviewer agents
    - ``orchestrate_<name>.py`` - Sequential orchestration logic
    - ``README.md`` - Multi-agent workflow guide
  
  Parameters:
    - ``--name``: System name
    - ``--description``: Multi-agent system description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template lab-multi-agent \
          --name content_team \
          --description "Research, write, and review content"
  
  Workflow:
    1. Researcher agent gathers information
    2. Writer agent creates content based on research
    3. Reviewer agent provides feedback and improvements

Application Templates
^^^^^^^^^^^^^^^^^^^^^

**api-server**
  REST API server for Lab agents and RAG assistants using FastAPI.
  
  Generated files:
    - ``server.py`` - FastAPI application with endpoints
    - ``requirements.txt`` - Python dependencies
    - ``README.md`` - API documentation and examples
  
  Endpoints:
    - ``POST /chat/agent`` - Chat with Lab agents
    - ``POST /chat/rag`` - Chat with RAG assistants
    - ``GET /health`` - Health check
    - ``GET /docs`` - Interactive API documentation (Swagger UI)
  
  Parameters:
    - ``--name``: API server name
    - ``--description``: API description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template api-server \
          --name ai_api \
          --description "AI assistant API server"

**web-ui-gradio**
  Web UI for Lab agents and RAG assistants using Gradio.
  
  Generated files:
    - ``app.py`` - Gradio web application
    - ``requirements.txt`` - Dependencies including gradio
    - ``README.md`` - UI customization guide
  
  Features:
    - Tab-based interface for agents and RAG
    - Streaming responses
    - Chat history
    - Customizable UI theme
  
  Parameters:
    - ``--name``: Application name
    - ``--description``: UI description
  
  Example:
    .. code-block:: shell
    
        geai generate create --template web-ui-gradio \
          --name ai_studio \
          --description "AI assistant web interface"

Usage Guide
-----------

Listing Available Templates
^^^^^^^^^^^^^^^^^^^^^^^^^^^^

View all available templates:

.. code-block:: shell

    geai generate list

Output shows templates grouped by category (RAG, Lab, Workflow).

Interactive Mode
^^^^^^^^^^^^^^^^

Run without parameters for interactive prompts:

.. code-block:: shell

    geai generate create --template rag-basic

The CLI will prompt for required parameters:

.. code-block:: text

    Enter name: my_assistant
    Enter description: Customer support RAG assistant
    Enter output directory [./my_assistant]:

Non-Interactive Mode
^^^^^^^^^^^^^^^^^^^^^

Pass all parameters via flags:

.. code-block:: shell

    geai generate create --template lab-agent-basic \
      --name code_helper \
      --description "Coding assistant" \
      --instructions "You help developers write better code" \
      --output ./code_helper_project \
      --no-interactive

The ``--no-interactive`` flag prevents prompts and uses provided values or defaults.

Template Parameters
-------------------

Common Parameters
^^^^^^^^^^^^^^^^^

All templates support:

- ``--template``: Template identifier (required)
- ``--output``: Output directory path (default: ``./<name>``)
- ``--no-interactive``: Disable interactive prompts

Template-Specific Parameters
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Each template has unique parameters. View them with:

.. code-block:: shell

    geai generate create --template <template-name> --help

Example parameter combinations:

.. code-block:: shell

    # RAG with all parameters
    geai generate create --template rag-basic \
      --name support_docs \
      --description "Technical support knowledge base" \
      --output ~/projects/support_rag
    
    # Agent with custom instructions
    geai generate create --template lab-agent-basic \
      --name sql_expert \
      --description "SQL query assistant" \
      --instructions "You are a PostgreSQL expert. Write optimized queries."
    
    # Multi-agent system
    geai generate create --template lab-multi-agent \
      --name research_team \
      --description "Collaborative research and analysis"

Template Output Structure
--------------------------

Each template generates a self-contained project with:

1. **Python Scripts**: Executable code following PyGEAI patterns
2. **README.md**: Complete documentation with:
   
   - Overview and purpose
   - Prerequisites and setup
   - Step-by-step usage instructions
   - Customization options
   - Next steps and examples

3. **Supporting Files**: Requirements, configuration, data directories
4. **Best Practices**: Error handling, resource cleanup, logging

Example Generated Project
^^^^^^^^^^^^^^^^^^^^^^^^^^

After running:

.. code-block:: shell

    geai generate create --template rag-basic --name docs_rag

Directory structure:

.. code-block:: text

    docs_rag/
    ├── README.md                  # Complete usage guide
    ├── create_docs_rag.py         # Creates RAG assistant
    ├── chat_docs_rag.py           # Chat interface
    ├── upload_documents.py        # Document uploader
    └── documents/                 # Place your documents here
        └── sample.txt

Usage workflow:

.. code-block:: shell

    cd docs_rag
    
    # Step 1: Add documents
    cp ~/my_docs/* documents/
    
    # Step 2: Create assistant
    python create_docs_rag.py
    
    # Step 3: Upload documents
    python upload_documents.py
    
    # Step 4: Chat with your RAG
    python chat_docs_rag.py

Advanced Use Cases
------------------

Building a Complete AI Application
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Combine multiple templates for full-stack AI apps:

.. code-block:: shell

    # 1. Create RAG assistant
    geai generate create --template rag-basic \
      --name support_rag \
      --output ./support_app
    
    # 2. Add API server (in separate directory)
    geai generate create --template api-server \
      --name support_api \
      --output ./support_app/api
    
    # 3. Add Web UI (in separate directory)
    geai generate create --template web-ui-gradio \
      --name support_ui \
      --output ./support_app/ui

Result: Complete application with RAG backend, REST API, and web interface.

Multi-Agent Workflow
^^^^^^^^^^^^^^^^^^^^

Create specialized agents and orchestrate them:

.. code-block:: shell

    # Create individual agents
    geai generate create --template lab-agent-basic \
      --name researcher --instructions "Research topics thoroughly"
    
    geai generate create --template lab-agent-basic \
      --name writer --instructions "Write clear, engaging content"
    
    # Create orchestration workflow
    geai generate create --template lab-multi-agent \
      --name content_pipeline

Customizing Generated Code
---------------------------

Templates generate starting points that you can customize:

1. **Modify Agent Instructions**: Edit system prompts in ``create_*.py`` files
2. **Add Tools**: Extend tool definitions in ``create_tool_*.py``
3. **Adjust Workflows**: Customize orchestration logic in ``orchestrate_*.py``
4. **Enhance APIs**: Add endpoints to ``server.py``
5. **Style UIs**: Customize Gradio theme and layout in ``app.py``

Example customization:

.. code-block:: python

    # Original generated code
    agent = manager.create_agent(
        name="researcher",
        description="Research agent",
        instructions="You are a helpful researcher"
    )
    
    # Customized version
    agent = manager.create_agent(
        name="researcher",
        description="Academic research specialist",
        instructions="""You are an academic researcher specializing in AI and ML.
        
        Guidelines:
        - Cite sources with academic rigor
        - Focus on peer-reviewed publications
        - Summarize key findings clearly
        - Identify research gaps and opportunities
        """
    )

Best Practices
--------------

1. **Start with Templates**: Use templates for consistent project structure
2. **Read Generated READMEs**: Each template includes comprehensive documentation
3. **Version Control**: Initialize git repos for generated projects
4. **Test Before Customizing**: Verify template works before heavy modification
5. **Follow PyGEAI Patterns**: Generated code follows SDK best practices
6. **Resource Cleanup**: Templates include cleanup/deletion scripts where applicable
7. **Environment Variables**: Configure API keys via ``.env`` or environment

Integration with CI/CD
----------------------

Templates work well in automated workflows:

.. code-block:: yaml

    # GitHub Actions example
    - name: Generate AI Agent
      run: |
        geai generate create --template lab-agent-basic \
          --name ci_agent \
          --description "CI/CD assistant" \
          --instructions "Help with build and deployment" \
          --no-interactive \
          --output ./agent
    
    - name: Deploy Agent
      run: |
        cd agent
        python create_ci_agent.py

Troubleshooting
---------------

Common Issues
^^^^^^^^^^^^^

**Missing Parameters**

.. code-block:: text

    ERROR: Missing required parameter: --name
      → Provide the parameter or use interactive mode
      
      Example:
        geai generate create --template rag-basic --name my_rag

**Invalid Template**

.. code-block:: text

    ERROR: Template 'invalid-name' not found
      → Use 'geai generate list' to see available templates

**Output Directory Exists**

Templates won't overwrite existing directories by default. Use a different path or remove the existing directory.

Getting Help
^^^^^^^^^^^^

.. code-block:: shell

    # List all templates
    geai generate list
    
    # Help for generate command
    geai generate --help
    
    # Help for specific template
    geai generate create --template rag-basic --help

See Also
--------

- :doc:`cli` - Complete CLI reference
- :doc:`ai_lab` - AI Lab agents and processes
- :doc:`quickstart` - PyGEAI getting started guide
- :doc:`samples` - Additional code examples
