Orchestration Patterns Guide
============================

This guide provides detailed information about the five orchestration patterns available in PyGEAI Orchestration.

Overview
--------

Each pattern addresses different use cases:

* **Reflection**: Iterative self-improvement through critique and refinement
* **ReAct**: Reasoning and acting in cycles for complex problem-solving
* **Planning**: Multi-step planning and systematic execution
* **Tool Use**: Function calling and external tool integration
* **Multi-Agent**: Collaborative multi-agent workflows

Pattern Interface
-----------------

All patterns follow a consistent interface:

.. code-block:: python

    result = await pattern.execute(task, context=None)

All patterns return a ``PatternResult`` object with:

* ``success``: Boolean indicating if execution succeeded
* ``result``: The final result/answer
* ``iterations``: Number of iterations executed
* ``error``: Error message if failed
* ``metadata``: Additional pattern-specific metadata

Reflection Pattern
------------------

The Reflection pattern enables agents to critique and refine their outputs through multiple iterations.

When to Use
~~~~~~~~~~~

* Content creation requiring high quality
* Iterative refinement tasks
* Self-correcting analysis
* Code review and improvement

How It Works
~~~~~~~~~~~~

1. Agent generates initial response
2. Agent reflects on the response and identifies improvements
3. Agent generates improved response
4. Repeat until max iterations or convergence

Example
~~~~~~~

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent,
        AgentConfig,
        PatternConfig,
        PatternType,
        ReflectionPattern
    )

    async def main():
        # Create agent
        agent = GEAIAgent(config=AgentConfig(
            name="reflector",
            model="openai/gpt-4o-mini",
            temperature=0.7
        ))
        
        # Create pattern
        pattern_config = PatternConfig(
            name="reflection-example",
            pattern_type=PatternType.REFLECTION,
            max_iterations=5
        )
        
        pattern = ReflectionPattern(
            agent=agent,
            config=pattern_config
        )
        
        result = await pattern.execute("Explain machine learning")
        print(f"Success: {result.success}")
        print(f"Iterations: {result.iterations}")
        print(f"Result: {result.result}")

    asyncio.run(main())

Configuration Options
~~~~~~~~~~~~~~~~~~~~~

* ``max_iterations``: Maximum refinement cycles (default: 3)
* ``verbose``: Enable detailed logging (configure logger separately)

ReAct Pattern
-------------

The ReAct (Reasoning and Acting) pattern interleaves reasoning traces with task-specific actions.

When to Use
~~~~~~~~~~~

* Complex multi-step problems
* Research and analysis tasks
* Tasks requiring careful reasoning
* Dynamic exploration workflows

How It Works
~~~~~~~~~~~~

1. **Think**: Agent reasons about what to do next
2. **Act**: Agent takes an action (uses tool or provides answer)
3. **Observe**: Agent observes the result of the action
4. Repeat until task complete

Example
~~~~~~~

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent,
        AgentConfig,
        PatternConfig,
        PatternType,
        ReActPattern
    )

    async def main():
        # Create agent
        agent = GEAIAgent(config=AgentConfig(
            name="researcher",
            model="openai/gpt-4o-mini",
            temperature=0.7
        ))
        
        # Create pattern
        pattern_config = PatternConfig(
            name="react-example",
            pattern_type=PatternType.REACT,
            max_iterations=5
        )
        
        pattern = ReActPattern(agent=agent, config=pattern_config)
        
        result = await pattern.execute(
            "Research and summarize the benefits of renewable energy"
        )
        
        print(f"Success: {result.success}")
        print(f"Result: {result.result}")

    asyncio.run(main())

Response Format
~~~~~~~~~~~~~~~

Agents respond in this format::

    Thought: <reasoning about what to do>
    Action: <action to take>
    Observation: <what was learned>

Planning Pattern
----------------

The Planning pattern creates a step-by-step plan and executes each step systematically.

When to Use
~~~~~~~~~~~

* Project planning and execution
* Multi-phase tasks
* Systematic workflows
* Complex implementations

How It Works
~~~~~~~~~~~~

1. Agent creates detailed step-by-step plan
2. Each step is executed in sequence
3. Results from previous steps inform next steps
4. Final synthesis of all results

Example
~~~~~~~

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent,
        AgentConfig,
        PatternConfig,
        PatternType,
        PlanningPattern
    )

    async def main():
        # Create agent
        agent = GEAIAgent(config=AgentConfig(
            name="planner",
            model="openai/gpt-4o-mini",
            temperature=0.5
        ))
        
        # Create pattern
        pattern_config = PatternConfig(
            name="planning-example",
            pattern_type=PatternType.PLANNING,
            max_iterations=1
        )
        
        pattern = PlanningPattern(agent=agent, config=pattern_config)
        
        result = await pattern.execute("Create a project plan for building a REST API")
        
        print(f"Success: {result.success}")
        print(f"Result: {result.result}")

    asyncio.run(main())

Tool Use Pattern
----------------

The Tool Use pattern enables agents to dynamically select and execute tools based on task requirements.

When to Use
~~~~~~~~~~~

* Tasks requiring external data or APIs
* Calculations or data processing
* Dynamic tool selection
* Function calling workflows

How It Works
~~~~~~~~~~~~

1. Agent receives task and available tools
2. Agent decides which tool to use (or provides final answer)
3. Tool executes and returns result
4. Agent processes result and continues or finishes

Example
~~~~~~~

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent,
        AgentConfig,
        PatternConfig,
        PatternType,
        ToolUsePattern,
        BaseTool,
        ToolConfig,
        ToolResult,
        ToolCategory
    )

    class CalculatorTool(BaseTool):
        def __init__(self):
            super().__init__(ToolConfig(
                name="calculator",
                description="Performs mathematical calculations",
                category=ToolCategory.COMPUTATION,
                parameters_schema={
                    "operation": "string (add, subtract, multiply, divide, average)",
                    "values": "list of numbers"
                }
            ))
        
        def validate_parameters(self, parameters):
            return "operation" in parameters and "values" in parameters
        
        async def execute(self, operation, values, **kwargs):
            if operation == "average":
                result = sum(values) / len(values)
                return ToolResult(success=True, result=result)
            elif operation == "add":
                result = sum(values)
                return ToolResult(success=True, result=result)
            else:
                return ToolResult(success=False, error=f"Unknown operation: {operation}")

    async def main():
        # Create agent
        agent = GEAIAgent(config=AgentConfig(
            name="calculator-agent",
            model="openai/gpt-4o-mini"
        ))
        
        # Create pattern with tools
        pattern_config = PatternConfig(
            name="tool-use-example",
            pattern_type=PatternType.TOOL_USE,
            max_iterations=3
        )
        
        tools = [CalculatorTool()]
        pattern = ToolUsePattern(agent=agent, config=pattern_config, tools=tools)
        
        result = await pattern.execute("Calculate the average of 10, 20, 30, 40, 50")
        print(f"Result: {result.result}")

    asyncio.run(main())

Creating Custom Tools
~~~~~~~~~~~~~~~~~~~~~

All tools must:

1. Inherit from ``BaseTool``
2. Implement ``validate_parameters(parameters)`` method
3. Implement ``async execute(**kwargs)`` method
4. Use ``ToolConfig`` with ``parameters_schema`` field

Example:

.. code-block:: python

    from pygeai_orchestration import BaseTool, ToolConfig, ToolResult, ToolCategory

    class CustomTool(BaseTool):
        def __init__(self):
            config = ToolConfig(
                name="my_tool",
                description="Description of what the tool does",
                category=ToolCategory.CUSTOM,
                parameters_schema={
                    "param1": "string description",
                    "param2": "integer description"
                }
            )
            super().__init__(config)

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

        async def execute(self, param1, param2=0, **kwargs):
            # Tool implementation
            result = perform_operation(param1, param2)
            
            return ToolResult(
                success=True,
                result=result
            )

Multi-Agent Pattern
-------------------

The Multi-Agent pattern coordinates multiple specialized agents to collaborate on a task.

When to Use
~~~~~~~~~~~

* Complex collaborative tasks
* Tasks requiring diverse expertise
* Content creation workflows
* Peer review scenarios

How It Works
~~~~~~~~~~~~

1. Task is distributed to multiple agents
2. Each agent contributes based on their specialization
3. Agents can build on each other's work
4. Final result combines all contributions

Example
~~~~~~~

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent,
        AgentConfig,
        PatternConfig,
        PatternType,
        MultiAgentPattern,
        AgentRole
    )

    async def main():
        # Create specialized agents
        researcher = GEAIAgent(config=AgentConfig(
            name="researcher",
            model="openai/gpt-4o-mini",
            system_prompt="You are a research specialist. Gather and analyze information."
        ))
        
        writer = GEAIAgent(config=AgentConfig(
            name="writer",
            model="openai/gpt-4o-mini",
            system_prompt="You are a technical writer. Create clear and engaging content."
        ))
        
        coordinator = GEAIAgent(config=AgentConfig(
            name="coordinator",
            model="openai/gpt-4o-mini",
            system_prompt="You coordinate tasks and synthesize results."
        ))
        
        # Create agent roles
        agent_roles = [
            AgentRole(
                name="researcher",
                agent=researcher,
                role_description="Researches topics and gathers relevant information"
            ),
            AgentRole(
                name="writer",
                agent=writer,
                role_description="Writes reports and documentation"
            )
        ]
        
        # Create multi-agent pattern
        pattern_config = PatternConfig(
            name="collaboration-example",
            pattern_type=PatternType.MULTI_AGENT
        )
        
        pattern = MultiAgentPattern(
            agents=agent_roles,
            coordinator_agent=coordinator,
            config=pattern_config
        )
        
        result = await pattern.execute("Create a comprehensive report on AI in healthcare")
        
        print(f"Success: {result.success}")
        print(f"Result: {result.result}")

    asyncio.run(main())

Pattern Composition
-------------------

Patterns can be combined for more complex workflows:

.. code-block:: python

    import asyncio
    from pygeai_orchestration import (
        GEAIAgent, AgentConfig, PatternConfig, PatternType,
        PlanningPattern, ReflectionPattern
    )

    async def main():
        agent = GEAIAgent(config=AgentConfig(
            name="planner",
            model="openai/gpt-4o-mini"
        ))
        
        # First, create a plan
        planning = PlanningPattern(
            agent=agent,
            config=PatternConfig(
                name="planning",
                pattern_type=PatternType.PLANNING
            )
        )
        plan_result = await planning.execute("Build a web application")
        
        # Then, refine each step with reflection
        reflection = ReflectionPattern(
            agent=agent,
            config=PatternConfig(
                name="reflection",
                pattern_type=PatternType.REFLECTION,
                max_iterations=3
            )
        )
        refined_result = await reflection.execute(
            f"Refine this plan: {plan_result.result}"
        )
        
        print(f"Refined Plan: {refined_result.result}")

    asyncio.run(main())

Configuration Best Practices
-----------------------------

Iteration Limits
~~~~~~~~~~~~~~~~

Recommended values:

* **Reflection**: 3-5 iterations
* **Tool Use**: 3-5 iterations
* **ReAct**: 5-10 iterations
* **Planning**: 1-3 iterations

Temperature Settings
~~~~~~~~~~~~~~~~~~~~

* **Planning/Analysis**: 0.3-0.5 (more deterministic)
* **Creative Tasks**: 0.7-0.9 (more varied)
* **General Tasks**: 0.5-0.7 (balanced)

Model Selection
~~~~~~~~~~~~~~~

* **Quick tasks**: ``openai/gpt-4o-mini``
* **Complex reasoning**: ``openai/gpt-4o``
* **Long context**: Models with larger context windows

Logging
-------

Enable logging to see pattern execution details:

.. code-block:: python

    import logging

    # Configure the pygeai_orchestration logger
    logger = logging.getLogger("pygeai_orchestration")
    logger.setLevel(logging.INFO)
    handler = logging.StreamHandler()
    handler.setFormatter(logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    ))
    logger.addHandler(handler)

Working Examples
----------------

Complete working examples are available in the ``snippets/`` directory:

**Reflection Pattern**
  - ``reflection_explanation.py`` - Iterative explanation improvement
  - ``reflection_code_review.py`` - Code review with self-critique

**ReAct Pattern**
  - ``react_research.py`` - Structured research tasks
  - ``react_problem_solving.py`` - Step-by-step problem solving

**Planning Pattern**
  - ``planning_project.py`` - Project planning and breakdown
  - ``planning_analysis.py`` - Data analysis planning

**Tool Use Pattern**
  - ``tool_use_calculator.py`` - Mathematical operations with tools
  - ``tool_use_data_processing.py`` - Data validation and transformation

**Multi-Agent Pattern**
  - ``multi_agent_collaboration.py`` - Collaborative multi-agent workflow

Run any snippet::

    python snippets/reflection_explanation.py

Next Steps
----------

* Try the :doc:`quickstart` examples
* Explore :doc:`examples` for real-world use cases
* Check the :doc:`api/core` for complete API reference
