PolyAgent implements a modern, pattern-based multi-agent workflow system that enables sophisticated AI reasoning through composable patterns. The architecture follows a clean three-layer design that eliminates code duplication while providing flexibility for complex agent orchestration.
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Orchestrator Router β
β (Query decomposition, complexity analysis, routing) β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β Strategy Workflows β
β (DAG, React, Research, Exploratory, Scientific) β
βββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββΌββββββββββββββββββββββββββββββββββββββββ
β Patterns Library β
β (Execution: Parallel/Sequential/Hybrid) β
β (Reasoning: React/Reflection/CoT/Debate/ToT) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
The entry point for all queries, responsible for:
- Query Decomposition: Analyzes query complexity and breaks down into subtasks
- Complexity Scoring: Determines if query is simple (< 0.3) or complex
- Strategy Selection: Routes to appropriate workflow based on cognitive strategy
- Budget Management: Enforces token limits via middleware
High-level workflows that compose patterns for specific approaches:
- Handles general task decomposition and multi-agent coordination
- Supports parallel, sequential, and hybrid (dependency-based) execution
- Applies reflection pattern for quality improvement
- Implements Reason-Act-Observe loops for iterative problem solving
- Best for tasks requiring tool use and environmental feedback
- Maintains observation window for context
- Optimized for information gathering and synthesis
- Uses React pattern for simple research, parallel agents for complex
- Applies reflection for comprehensive results
- Systematic exploration using Tree-of-Thoughts pattern
- Falls back to Debate pattern when confidence is low
- Applies Reflection for final quality check
- Hypothesis generation using Chain-of-Thought
- Hypothesis testing via multi-agent Debate
- Implications exploration with Tree-of-Thoughts
- Final synthesis with Reflection
Reusable, composable patterns for agent behaviors:
- Parallel: Concurrent agent execution with semaphore control
- Sequential: Step-by-step execution with result passing
- Hybrid: Dependency graph execution with topological sorting
- React (
react.go): Reason-Act-Observe loops with tool integration - Reflection (
reflection.go): Iterative quality improvement through self-evaluation - Chain-of-Thought (
chain_of_thought.go): Step-by-step reasoning with confidence tracking - Debate (
debate.go): Multi-agent debate for exploring perspectives - Tree-of-Thoughts (
tree_of_thoughts.go): Systematic exploration with branching and pruning
Workflows compose multiple patterns to achieve sophisticated reasoning:
// Example: Scientific Workflow Composition
1. Chain-of-Thought β Generate hypotheses
2. Debate β Test competing hypotheses
3. Tree-of-Thoughts β Explore implications
4. Reflection β Final quality synthesisgraph TD
A[Query Input] --> B{Decompose & Analyze}
B --> C{Complexity Score}
C -->|< 0.3| D[Simple Task]
C -->|>= 0.3| E{Cognitive Strategy}
D --> F[ExecuteSimpleTask]
E -->|exploratory| G[ExploratoryWorkflow]
E -->|scientific| H[ScientificWorkflow]
E -->|react| I[ReactWorkflow]
E -->|research| J[ResearchWorkflow]
E -->|default| K[DAGWorkflow]
G --> L[Tree-of-Thoughts + Debate + Reflection]
H --> M[CoT + Debate + ToT + Reflection]
I --> N[Reason-Act-Observe Loop]
J --> O[React or Parallel + Reflection]
K --> P[Parallel/Sequential/Hybrid + Reflection]
Each pattern supports configuration through dedicated config structs:
// Example: TreeOfThoughtsConfig
type TreeOfThoughtsConfig struct {
MaxDepth int // Maximum tree depth
BranchingFactor int // Number of branches per node (2-4)
EvaluationMethod string // "scoring", "voting", "llm"
PruningThreshold float64 // Minimum score to continue branch
ExplorationBudget int // Max total thoughts to explore
BacktrackEnabled bool // Allow backtracking to promising branches
ModelTier string // Model tier for thought generation
}Workflows are configured via activities.WorkflowConfig:
ExploratoryMaxIterations: Maximum exploration roundsExploratoryConfidenceThreshold: Confidence targetScientificMaxHypotheses: Number of hypotheses to generateScientificMaxIterations: Maximum testing rounds
All workflows respect token budgets through:
- Middleware:
middleware_budget.goenforces limits - Pattern Options:
BudgetAgentMaxfield in pattern options - Activity Budgets:
ExecuteAgentWithBudgetActivityfor controlled execution
| Workflow | Best For | Example Queries |
|---|---|---|
| Simple | Direct questions, single-step tasks | "What is the capital of France?" |
| DAG | Multi-step tasks with clear subtasks | "Build a REST API with authentication" |
| React | Tool-using tasks, iterative problem solving | "Debug this Python code" |
| Research | Information gathering, comparison | "Compare React vs Vue frameworks" |
| Exploratory | Open-ended discovery, unknown solution space | "How can we optimize our database?" |
| Scientific | Hypothesis testing, systematic analysis | "Test if caching improves performance by 50%" |
- Use Reflection when quality matters more than speed
- Use Chain-of-Thought for problems requiring explicit reasoning steps
- Use Debate when multiple perspectives strengthen the answer
- Use Tree-of-Thoughts for complex problems with multiple solution paths
- Use React when environmental feedback is needed
- Start simple: Use single patterns before composing
- Layer gradually: Add patterns based on confidence thresholds
- Monitor tokens: Complex compositions can be expensive
- Test empirically: Measure quality improvements from each pattern
- Create pattern file in
patterns/ - Implement pattern function with standard signature:
func YourPattern(ctx workflow.Context, query string, context map[string]interface{}, sessionID string, history []string, config YourConfig, opts Options) (*YourResult, error)
- Register in pattern registry (optional)
- Compose in existing or new strategy workflows
- Create strategy file in
strategies/ - Implement workflow function:
func YourWorkflow(ctx workflow.Context, input TaskInput) (TaskResult, error)
- Compose patterns as needed
- Add routing logic in
orchestrator_router.go - Create wrapper in
cognitive_wrappers.gofor test compatibility
- Workflow start/completion counters by type
- Pattern usage frequency
- Token consumption by pattern
- Quality scores from reflection
- Confidence levels from reasoning patterns
- Structured logging at each layer
- Pattern selection reasoning
- Quality improvement tracking
- Token budget consumption
- Workflow visualization
- Activity timings
- Retry tracking
- Error investigation
- Simple tasks bypass complex patterns
- Reflection only triggers below quality threshold
- Parallel execution maximizes throughput
- Caching prevents redundant operations
- Semaphore-controlled parallelism (max 5 concurrent agents)
- Dependency-aware scheduling
- Circuit breakers for failing services
- Graceful degradation under load
- Identify core logic in legacy workflow
- Map to appropriate patterns
- Create strategy workflow composing patterns
- Add test wrapper for compatibility
- Update router to use new strategy
- Delete legacy implementation
- Extract common logic into helper functions
- Create pattern with configuration options
- Replace inline logic with pattern calls
- Test pattern in isolation
- Compose in workflows
- Self-Consistency: Multiple reasoning paths with voting
- Least-to-Most: Problem decomposition from simple to complex
- ReAct++: Enhanced React with planning
- Constitutional AI: Value-aligned reasoning
- Dynamic pattern selection based on query analysis
- Pattern performance tracking and auto-tuning
- Cross-pattern context sharing
- Pattern marketplace for community contributions
PolyAgent's multi-agent workflow architecture provides a flexible, extensible foundation for sophisticated AI reasoning. By composing reusable patterns, developers can create powerful workflows without code duplication while maintaining clean separation of concerns.
The pattern-based approach aligns with modern frameworks like LangGraph, AutoGen, and CrewAI, making PolyAgent familiar to developers while providing unique capabilities through its Temporal-based orchestration and comprehensive pattern library.