Examples
========

Real-world examples demonstrating PyGEAI Orchestration patterns.

Content Creation Pipeline
--------------------------

Using multiple patterns for high-quality content generation.

.. code-block:: python

    from pygeai_orchestration import (
        GEAIAgent, AgentConfig,
        ReActPattern, ReflectionPattern,
        MultiAgentPattern, AgentRole
    )

    # Create specialized agents
    researcher = GEAIAgent(AgentConfig(
        name="researcher",
        model="gpt-4",
        system_prompt="You are an expert researcher."
    ))

    writer = GEAIAgent(AgentConfig(
        name="writer",
        model="gpt-4",
        system_prompt="You are a professional content writer."
    ))

    editor = GEAIAgent(AgentConfig(
        name="editor",
        model="gpt-4",
        system_prompt="You are an experienced editor."
    ))

    # Step 1: Research with ReAct
    research_pattern = ReActPattern(
        agent=researcher,
        tools=[search_tool, web_scraper_tool]
    )
    research_result = await research_pattern.execute(
        "Research latest trends in AI for 2026"
    )

    # Step 2: Write with reflection
    writing_pattern = ReflectionPattern(agent=writer, max_iterations=2)
    draft = await writing_pattern.execute(
        f"Write article based on: {research_result.output}"
    )

    # Step 3: Multi-agent review
    review_pattern = MultiAgentPattern()
    review_pattern.add_agent(writer, AgentRole.WRITER)
    review_pattern.add_agent(editor, AgentRole.CRITIC)

    final = await review_pattern.execute(
        f"Review and finalize: {draft.output}"
    )

    print(final.output)

Data Analysis Workflow
----------------------

Combining tools and planning for data analysis.

.. code-block:: python

    from pygeai_orchestration import (
        PlanningPattern, ToolUsePattern,
        BaseTool, ToolConfig, ToolResult
    )

    # Create data tools
    class DataLoaderTool(BaseTool):
        def __init__(self):
            config = ToolConfig(
                name="data_loader",
                description="Loads data from CSV files"
            )
            super().__init__(config)

        async def execute(self, **kwargs):
            filepath = kwargs.get("filepath")
            data = load_csv(filepath)
            return ToolResult(success=True, result=data)

        def validate_parameters(self, parameters):
            return "filepath" in parameters

    class StatsTool(BaseTool):
        def __init__(self):
            config = ToolConfig(
                name="statistics",
                description="Calculates statistics on data"
            )
            super().__init__(config)

        async def execute(self, **kwargs):
            data = kwargs.get("data")
            stats = calculate_stats(data)
            return ToolResult(success=True, result=stats)

        def validate_parameters(self, parameters):
            return "data" in parameters

    # Use planning pattern for analysis
    agent = GEAIAgent(AgentConfig(name="analyst", model="gpt-4"))
    pattern = PlanningPattern(agent=agent)

    result = await pattern.execute(
        "Analyze sales data: load data.csv, calculate statistics, identify trends"
    )

    print(result.output)

Customer Support Bot
--------------------

Using ReAct for interactive problem-solving.

.. code-block:: python

    from pygeai_orchestration import ReActPattern

    # Create support tools
    class KnowledgeBaseTool(BaseTool):
        async def execute(self, **kwargs):
            query = kwargs.get("query")
            results = search_knowledge_base(query)
            return ToolResult(success=True, result=results)

    class TicketTool(BaseTool):
        async def execute(self, **kwargs):
            action = kwargs.get("action")
            ticket_id = kwargs.get("ticket_id")
            result = manage_ticket(action, ticket_id)
            return ToolResult(success=True, result=result)

    # Create support agent
    support_agent = GEAIAgent(AgentConfig(
        name="support",
        model="gpt-4",
        system_prompt="You are a helpful customer support agent."
    ))

    pattern = ReActPattern(
        agent=support_agent,
        tools=[KnowledgeBaseTool(), TicketTool()]
    )

    # Handle customer query
    result = await pattern.execute(
        "Customer asks: My order #12345 hasn't arrived yet"
    )

    print(result.output)

Research Assistant
------------------

Multi-agent system for comprehensive research.

.. code-block:: python

    from pygeai_orchestration import MultiAgentPattern, AgentRole

    # Create research team
    literature_reviewer = GEAIAgent(AgentConfig(
        name="reviewer",
        model="gpt-4",
        system_prompt="You review academic literature."
    ))

    data_analyst = GEAIAgent(AgentConfig(
        name="analyst",
        model="gpt-4",
        system_prompt="You analyze data and statistics."
    ))

    synthesizer = GEAIAgent(AgentConfig(
        name="synthesizer",
        model="gpt-4",
        system_prompt="You synthesize findings into reports."
    ))

    # Coordinate research
    pattern = MultiAgentPattern()
    pattern.add_agent(literature_reviewer, AgentRole.RESEARCHER)
    pattern.add_agent(data_analyst, AgentRole.EXECUTOR)
    pattern.add_agent(synthesizer, AgentRole.WRITER)

    result = await pattern.execute(
        "Research the impact of remote work on productivity"
    )

    print(result.output)

Code Review System
------------------

Using reflection for iterative code improvement.

.. code-block:: python

    from pygeai_orchestration import ReflectionPattern

    code_agent = GEAIAgent(AgentConfig(
        name="coder",
        model="gpt-4",
        system_prompt="You are an expert software engineer."
    ))

    pattern = ReflectionPattern(
        agent=code_agent,
        max_iterations=3,
        reflection_prompt=(
            "Review this code for: "
            "1) correctness, "
            "2) performance, "
            "3) readability, "
            "4) best practices. "
            "Suggest improvements."
        )
    )

    result = await pattern.execute(
        "Write a Python function to efficiently find prime numbers up to n"
    )

    print("Final code:")
    print(result.output)

Error Handling Example
----------------------

Robust error handling with retries.

.. code-block:: python

    from pygeai_orchestration import (
        ToolUsePattern,
        ErrorHandler,
        RetryHandler,
        ToolExecutionError
    )

    pattern = ToolUsePattern(agent=agent)
    pattern.register_tool(unreliable_api_tool)

    retry_handler = RetryHandler(
        max_attempts=3,
        initial_delay=1.0,
        backoff_factor=2.0
    )

    async def execute_with_retry():
        try:
            result = await pattern.execute(
                "Fetch data from external API"
            )
            return result
        except ToolExecutionError as e:
            ErrorHandler.handle_error(
                e,
                context={"tool": "api", "operation": "fetch"}
            )
            raise

    try:
        result = await retry_handler.retry_async(execute_with_retry)
        print(f"Success: {result.output}")
    except Exception as e:
        print(f"Failed after retries: {e}")

Stateful Conversation
---------------------

Using state and memory for multi-turn interactions.

.. code-block:: python

    from pygeai_orchestration import (
        ReflectionPattern,
        State, StateStatus,
        Memory
    )

    # Initialize state and memory
    state = State()
    memory = Memory(max_size=100)

    agent = GEAIAgent(AgentConfig(name="assistant", model="gpt-4"))
    pattern = ReflectionPattern(agent=agent)

    async def process_turn(user_input: str):
        # Update state
        state.set("turn", state.get("turn", 0) + 1)
        state.update_status(StateStatus.RUNNING)

        # Store user input in memory
        memory.store(f"user_turn_{state.get('turn')}", user_input)

        # Get conversation context
        recent = memory.get_recent(limit=5)
        context = "\n".join([f"{e.key}: {e.value}" for e in recent])

        # Execute with context
        result = await pattern.execute(
            f"Context:\n{context}\n\nUser: {user_input}"
        )

        # Store assistant response
        memory.store(f"assistant_turn_{state.get('turn')}", result.output)

        state.update_status(StateStatus.COMPLETED)
        return result.output

    # Simulate conversation
    response1 = await process_turn("Tell me about Python")
    print(response1)

    response2 = await process_turn("What are its main features?")
    print(response2)

    response3 = await process_turn("Show me an example")
    print(response3)
