> ## Documentation Index
> Fetch the complete documentation index at: https://docs.junis.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Understanding the Agent System

> Master the four agent types and build complex AI workflows

## Agent System Overview

The Junis agent system is a set of **four composable agent types** — LLM, Sequential, Parallel, and Loop — that you combine into AI teams without writing code. An orchestrator routes every request to the right agent, and each agent can call tools, MCP integrations, and sub-agents. This guide explains each type, when to use it, and how to combine them.

***

## What are the four agent types?

<CardGroup cols={2}>
  <Card title="LLM Agent" icon="brain" color="#3b82f6">
    Uses language models to generate responses, make decisions, and execute tasks
  </Card>

  <Card title="Sequential Agent" icon="arrow-right-arrow-left" color="#a855f7">
    Executes agents in order, passing results from one to the next
  </Card>

  <Card title="Parallel Agent" icon="arrows-split-up-and-left" color="#10b981">
    Runs multiple agents simultaneously, combining their results
  </Card>

  <Card title="Loop Agent" icon="rotate" color="#f59e0b">
    Repeats agent execution until a condition is met or max iterations reached
  </Card>
</CardGroup>

***

## LLM Agent

### What It Does

LLM Agents are the **workhorses** of your AI system. They use language models (like Claude, gpt, or Gemini) to:

* Generate natural language responses
* Analyze and summarize text
* Make decisions based on input
* Call tools and APIs
* Query knowledge bases (RAG)

### When to Use

<Check>
  ✅ Answering user questions
  ✅ Content generation (blogs, emails, summaries)
  ✅ Data analysis and insights
  ✅ Decision-making tasks
  ✅ Any task requiring language understanding
</Check>

### Configuration Options

```yaml LLM Agent Settings theme={null}
name: My Agent
agent_type: LLM_AGENT
model: claude-haiku  # Or gpt, gemini, etc.

# Model Parameters
temperature: 0.7          # Creativity (0 = deterministic, 1 = creative)
max_output_tokens: 16000   # Response length limit
max_llm_calls: 3          # Max tool call iterations

# Instructions (System Prompt)
instruction: |
  You are a helpful assistant that answers questions about our product.
  Be concise, friendly, and accurate.

# Tools & Integrations
tools:
  - search_database
  - send_email
rag_tools:
  - rag_product_docs
mcp_platforms:
  - github
  - firecrawl

# Advanced
streaming_enabled: true      # Real-time response streaming
web_search_enabled: false    # Enable web search capabilities
output_key: null             # Extract specific field from response

# Extended Thinking (Claude models only)
enable_thinking: false       # Enable extended thinking mode
thinking_budget_tokens: 2048 # Token budget for thinking (min: 1024)
reasoning_effort: none       # "none", "low", "medium", "high"
```

### Example: Customer Support Agent

<Tabs>
  <Tab title="Configuration">
    ```yaml theme={null}
    name: Support Agent
    agent_type: LLM_AGENT
    model: claude-haiku
    temperature: 0.5
    instruction: |
      You are a customer support agent for Acme Corp.

      Responsibilities:
      1. Answer product questions using the knowledge base
      2. Troubleshoot common issues
      3. Escalate complex problems to human agents

      Always be empathetic and solution-oriented.

    rag_tools:
      - rag_product_documentation
      - rag_faq_database
    ```
  </Tab>

  <Tab title="Example Conversation">
    **User**: How do I reset my password?

    **Support Agent**: I'd be happy to help you reset your password! Here's how:

    1. Go to the login page at acme.com/login
    2. Click "Forgot Password?" below the login button
    3. Enter your registered email address
    4. Check your email for a reset link (arrives within 5 minutes)
    5. Click the link and create a new password

    If you don't receive the email, check your spam folder or contact us at [support@acme.com](mailto:support@acme.com).

    Is there anything else I can help you with?
  </Tab>
</Tabs>

***

## Sequential Agent

### What It Does

Sequential Agents execute a **series of agents in order**, where each agent's output becomes the next agent's input. Think of it as a pipeline or assembly line.

```mermaid theme={null}
graph LR
    A[Input] --> B[Agent 1]
    B --> C[Agent 2]
    C --> D[Agent 3]
    D --> E[Final Output]
```

### When to Use

<Check>
  ✅ Multi-step workflows (research → analyze → report)
  ✅ Data transformation pipelines
  ✅ Quality assurance (generate → review → refine)
  ✅ Complex decision trees
  ✅ When output of one task informs the next
</Check>

### Configuration Options

```yaml Sequential Agent Settings theme={null}
name: My Sequential Workflow
agent_type: SEQUENTIAL_AGENT

# Sub-Agents (executed in order)
sub_agents:
  - agent_id: researcher
    order_index: 1
    description: Gathers information from multiple sources

  - agent_id: analyzer
    order_index: 2
    description: Analyzes and synthesizes research findings

  - agent_id: writer
    order_index: 3
    description: Writes final report based on analysis

# Optional: Define output format
output_key: final_report
```

### Example: Content Creation Pipeline

<Tabs>
  <Tab title="Workflow Structure">
    ```yaml theme={null}
    name: Blog Post Generator
    agent_type: SEQUENTIAL_AGENT

    sub_agents:
      # Step 1: Research
      - agent: Topic Researcher
        order: 1
        role: Search web and knowledge base for relevant information

      # Step 2: Outline
      - agent: Content Outliner
        order: 2
        role: Create structured outline from research

      # Step 3: Writing
      - agent: Blog Writer
        order: 3
        role: Write engaging blog post following outline

      # Step 4: SEO Optimization
      - agent: SEO Optimizer
        order: 4
        role: Add keywords, meta description, headings
    ```
  </Tab>

  <Tab title="Execution Flow">
    **Input**: "Write a blog post about AI safety"

    **Step 1 (Topic Researcher)**:

    * Searches web for latest AI safety news
    * Queries knowledge base for expert opinions
    * Output: Comprehensive research notes (2000 words)

    **Step 2 (Content Outliner)**:

    * Reads research notes from Step 1
    * Creates structured outline with sections
    * Output: 5-section outline with key points

    **Step 3 (Blog Writer)**:

    * Follows outline from Step 2
    * Writes engaging 1500-word blog post
    * Output: Draft blog post with intro, body, conclusion

    **Step 4 (SEO Optimizer)**:

    * Analyzes draft from Step 3
    * Adds SEO metadata and formatting
    * **Final Output**: Publication-ready blog post

    <Info>
      Each step only sees the output from the previous step, keeping context focused and efficient.
    </Info>
  </Tab>
</Tabs>

### Best Practices

<AccordionGroup>
  <Accordion title="Keep Steps Focused" icon="target">
    * Each sub-agent should have ONE clear responsibility
    * Don't try to do too much in a single step
    * Break complex tasks into 3-5 discrete steps

    **Bad Example**: "Research, analyze, and write report" (one agent)
    **Good Example**: Research Agent → Analysis Agent → Writing Agent (three agents)
  </Accordion>

  <Accordion title="Use Output Keys" icon="key">
    When you need specific data from a step, use `output_key` to extract it:

    ```yaml theme={null}
    - agent: Data Extractor
      order: 1
      output_key: extracted_data  # Only pass this field to next step
    ```

    This prevents information overload in later steps.
  </Accordion>

  <Accordion title="Add Validation Steps" icon="check">
    Insert validation agents to ensure quality:

    ```yaml theme={null}
    sub_agents:
      - agent: Content Generator
        order: 1
      - agent: Quality Checker    # ← Validates output
        order: 2
      - agent: Formatter
        order: 3
    ```
  </Accordion>
</AccordionGroup>

***

## Parallel Agent

### What It Does

Parallel Agents run **multiple agents simultaneously** and combine their results. Perfect for gathering information from multiple sources or performing independent tasks concurrently.

```mermaid theme={null}
graph TD
    A[Input] --> B[Agent 1]
    A --> C[Agent 2]
    A --> D[Agent 3]
    B --> E[Combined Output]
    C --> E
    D --> E
```

### When to Use

<Check>
  ✅ Data collection from multiple sources
  ✅ Independent analyses that can run concurrently
  ✅ Speeding up workflows with parallelization
  ✅ Comparing different approaches
  ✅ Aggregating diverse perspectives
</Check>

### Configuration Options

```yaml Parallel Agent Settings theme={null}
name: My Parallel Workflow
agent_type: PARALLEL_AGENT

# Sub-Agents (executed simultaneously)
sub_agents:
  - agent_id: source_a_collector
    description: Fetches data from Source A

  - agent_id: source_b_collector
    description: Fetches data from Source B

  - agent_id: source_c_collector
    description: Fetches data from Source C

# Results are automatically combined
# Order doesn't matter for parallel execution
```

### Example: Multi-Source Data Aggregator

<Tabs>
  <Tab title="Workflow Structure">
    ```yaml theme={null}
    name: Market Research Aggregator
    agent_type: PARALLEL_AGENT

    sub_agents:
      # All run simultaneously
      - agent: Competitor Analysis Agent
        role: Analyze competitor websites and pricing

      - agent: Social Media Insights Agent
        role: Gather sentiment from Twitter, Reddit, LinkedIn

      - agent: Industry News Agent
        role: Summarize latest industry news and trends

      - agent: Customer Feedback Agent
        role: Analyze recent customer reviews and support tickets
    ```
  </Tab>

  <Tab title="Execution Timeline">
    ```
    t=0s:  All agents start simultaneously
           ├─ Competitor Analysis (15s)
           ├─ Social Media Insights (20s)
           ├─ Industry News (10s)
           └─ Customer Feedback (18s)

    t=20s: All agents complete
           Results are combined into single report

    Total Time: 20 seconds (vs 63 seconds if sequential)
    ```

    <Warning>
      Parallel execution requires sufficient API rate limits and resources. Monitor usage to avoid throttling.
    </Warning>
  </Tab>

  <Tab title="Combined Output">
    The Parallel Agent automatically combines results:

    ```json theme={null}
    {
      "competitor_analysis": "Our pricing is 15% lower than competitors...",
      "social_sentiment": "Positive sentiment at 68%, trending topics include...",
      "industry_news": "New regulations announced today...",
      "customer_feedback": "Top feature requests: mobile app, API access..."
    }
    ```

    <Info>
      You can add a **Compiler Agent** after the Parallel Agent to synthesize results into a cohesive narrative.
    </Info>
  </Tab>
</Tabs>

### Best Practices

<AccordionGroup>
  <Accordion title="Ensure Independence" icon="arrows-split-up-and-left">
    Parallel agents should NOT depend on each other's results:

    **Bad Example**: Agent A calculates total, Agent B calculates percentage of total
    **Good Example**: Agent A analyzes Dataset 1, Agent B analyzes Dataset 2 (independent)
  </Accordion>

  <Accordion title="Handle Failures Gracefully" icon="shield-check">
    If one parallel agent fails, others should still complete:

    ```yaml theme={null}
    # Enable fault tolerance
    parallel_agent:
      continue_on_error: true  # Don't stop if one agent fails
      timeout: 30              # Max wait time per agent (seconds)
    ```
  </Accordion>

  <Accordion title="Add a Compiler Step" icon="compress">
    After parallel execution, add a Sequential step to combine results:

    ```mermaid theme={null}
    graph TD
        A[Input] --> B[Parallel Agent]
        B --> C[Agent 1]
        B --> D[Agent 2]
        B --> E[Agent 3]
        C --> F[Compiler Agent]
        D --> F
        E --> F
        F --> G[Unified Output]
    ```

    The Compiler Agent synthesizes parallel results into a coherent response.
  </Accordion>
</AccordionGroup>

***

## Loop Agent

### What It Does

Loop Agents **repeat execution** until a condition is met or maximum iterations reached. Useful for iterative refinement, retry logic, and self-correcting workflows.

```mermaid theme={null}
graph TD
    A[Input] --> B[Agent Execution]
    B --> C{Condition Met?}
    C -->|No| B
    C -->|Yes| D[Final Output]
    C -->|Max Iterations| E[Exit with Error]
```

### When to Use

<Check>
  ✅ Iterative refinement (generate → evaluate → improve)
  ✅ Retry logic with exponential backoff
  ✅ Quality assurance loops
  ✅ Self-correcting systems
  ✅ Tasks requiring multiple attempts
</Check>

### Configuration Options

```yaml Loop Agent Settings theme={null}
name: My Loop Workflow
agent_type: LOOP_AGENT
max_llm_calls: 5  # Maximum iterations (prevents infinite loops)

# Sub-Agent to Loop
sub_agents:
  - agent_id: iterative_improver
    description: Improves output each iteration

# Exit Conditions (implicit)
# - Condition evaluates to true
# - Max iterations reached
# - Agent returns success signal
```

### Example: Code Review and Refinement

<Tabs>
  <Tab title="Workflow Structure">
    ```yaml theme={null}
    name: Code Quality Loop
    agent_type: LOOP_AGENT
    max_llm_calls: 3

    sub_agents:
      - agent: Code Generator
        role: Generate Python function based on requirements

      - agent: Code Reviewer
        role: |
          Review code for:
          - Correctness
          - Edge cases
          - Best practices
          - Security issues

          If issues found, provide specific feedback for next iteration.
          If code is acceptable, respond with "APPROVED".
    ```
  </Tab>

  <Tab title="Iteration Example">
    **Iteration 1**:

    * Generator creates initial code
    * Reviewer finds bug: "Missing null check on input"
    * Loop continues

    **Iteration 2**:

    * Generator adds null check
    * Reviewer finds issue: "Function doesn't handle empty lists"
    * Loop continues

    **Iteration 3**:

    * Generator handles empty lists
    * Reviewer responds: "APPROVED - Code meets quality standards"
    * **Loop exits** with final code

    <Check>
      Code quality improved through automated iterative review!
    </Check>
  </Tab>

  <Tab title="Max Iterations Handling">
    If max iterations (3) reached without approval:

    ```json theme={null}
    {
      "status": "max_iterations_reached",
      "iterations": 3,
      "final_output": "Latest code version",
      "reviewer_feedback": "Still has issues with error handling",
      "action": "Escalate to human review"
    }
    ```

    <Warning>
      Always set `max_llm_calls` to prevent infinite loops. Recommended: 3-5 iterations.
    </Warning>
  </Tab>
</Tabs>

### Best Practices

<AccordionGroup>
  <Accordion title="Define Clear Exit Conditions" icon="check-circle">
    The sub-agent should explicitly signal when to exit:

    ```yaml theme={null}
    instruction: |
      Review the output. If quality is acceptable, respond with:
      "EXIT: Quality standards met"

      Otherwise, provide specific improvement suggestions.
    ```
  </Accordion>

  <Accordion title="Set Reasonable Max Iterations" icon="gauge">
    * **2-3 iterations**: Quick refinement tasks
    * **3-5 iterations**: Moderate complexity
    * **5-10 iterations**: Complex optimization (rare)

    Higher values increase cost and latency. Most tasks converge in 2-3 iterations.
  </Accordion>

  <Accordion title="Track Iteration Count" icon="hashtag">
    Pass iteration count to the agent for context:

    ```yaml theme={null}
    instruction: |
      This is iteration {{iteration_count}} of {{max_iterations}}.
      Previous feedback: {{previous_feedback}}

      Improve the output based on feedback.
    ```
  </Accordion>

  <Accordion title="Implement Degradation Strategy" icon="triangle-exclamation">
    Handle max iterations gracefully:

    ```yaml theme={null}
    # After loop exits
    if iterations >= max_llm_calls:
      escalate_to_human_review()
      log_warning("Loop did not converge")
      return best_attempt
    ```
  </Accordion>
</AccordionGroup>

***

## Combining Agent Types

The real power of Junis comes from **combining different agent types** to build sophisticated workflows.

### Example: Full Blog Post System

```mermaid theme={null}
graph TD
    A[User Request] --> B[Orchestrator]
    B --> C[Sequential: Content Pipeline]
    C --> D[Parallel: Research Team]
    D --> E[Web Researcher]
    D --> F[Doc Researcher]
    D --> G[Expert Interview Agent]
    E --> H[Compiler]
    F --> H
    G --> H
    H --> I[Outline Agent]
    I --> J[Loop: Writer + Reviewer]
    J --> K{Approved?}
    K -->|No| J
    K -->|Yes| L[SEO Optimizer]
    L --> M[Final Blog Post]
```

<Steps>
  <Step title="Orchestrator Routes Request">
    User says: "Write a blog post about quantum computing"

    Orchestrator recognizes this as a content creation task and routes to **Content Pipeline** (Sequential Agent).
  </Step>

  <Step title="Sequential Agent Coordinates Workflow">
    Content Pipeline executes three stages:

    1. Research (Parallel Agent)
    2. Writing (Loop Agent)
    3. Optimization (LLM Agent)
  </Step>

  <Step title="Parallel Agent Gathers Research">
    Research Team runs three agents simultaneously:

    * **Web Researcher**: Latest quantum computing news
    * **Doc Researcher**: Academic papers from knowledge base
    * **Expert Interview Agent**: Queries interview transcripts

    Results feed into **Compiler Agent** that synthesizes a research brief.
  </Step>

  <Step title="Loop Agent Refines Content">
    **Writer + Reviewer Loop**:

    * Writer drafts blog post from research
    * Reviewer checks quality, accuracy, readability
    * Loop continues until approved (max 3 iterations)
  </Step>

  <Step title="Final Agent Optimizes for SEO">
    SEO Optimizer adds:

    * Meta description
    * Keywords
    * Heading structure
    * Internal links

    **Output**: Publication-ready blog post delivered in \~45 seconds.
  </Step>
</Steps>

***

## Which agent type should you use?

Not sure which agent type to use? Follow this decision tree:

```mermaid theme={null}
graph TD
    A[Start] --> B{Multiple steps?}
    B -->|Yes| C{Steps independent?}
    B -->|No| D{Need iteration?}
    C -->|Yes| E[Parallel Agent]
    C -->|No| F[Sequential Agent]
    D -->|Yes| G[Loop Agent]
    D -->|No| H[LLM Agent]
```

<Tabs>
  <Tab title="Decision Matrix">
    | Scenario                         | Agent Type   | Reason                    |
    | -------------------------------- | ------------ | ------------------------- |
    | Answer a question                | LLM Agent    | Single-step task          |
    | Research → Analyze → Report      | Sequential   | Multi-step, order matters |
    | Check 3 databases simultaneously | Parallel     | Independent, concurrent   |
    | Generate → Review → Improve      | Loop         | Iterative refinement      |
    | Route to appropriate handler     | Orchestrator | Dynamic dispatching       |
  </Tab>

  <Tab title="Complexity Guide">
    **Start Simple**: Begin with LLM Agents

    **Add Complexity As Needed**:

    1. **LLM Agent** (Day 1): Get basic functionality working
    2. **Sequential Agent** (Week 1): Add multi-step workflows
    3. **Parallel Agent** (Week 2): Optimize with parallelization
    4. **Loop Agent** (Week 3): Add self-correction and quality loops

    <Info>
      80% of use cases can be solved with LLM + Sequential Agents. Add Parallel and Loop only when needed.
    </Info>
  </Tab>
</Tabs>

***

## Common Patterns

<AccordionGroup>
  <Accordion title="Pattern: Research → Analyze → Report" icon="chart-line">
    **Use Case**: Generate insights from data

    ```yaml theme={null}
    Sequential Agent:
      - Parallel Research: Gather data from multiple sources
      - LLM Analysis: Identify trends and patterns
      - LLM Report Writer: Create executive summary
    ```
  </Accordion>

  <Accordion title="Pattern: Generate → Validate → Retry" icon="rotate-right">
    **Use Case**: Quality assurance

    ```yaml theme={null}
    Loop Agent:
      - LLM Generator: Create output
      - LLM Validator: Check against criteria
      - If invalid: Provide feedback and retry
      - If valid: Exit loop
    ```
  </Accordion>

  <Accordion title="Pattern: Triage → Route → Execute" icon="sitemap">
    **Use Case**: Smart routing

    ```yaml theme={null}
    Sequential Agent:
      - LLM Triage: Classify request
      - Orchestrator: Route to specialist agent
      - Specialist LLM: Handle request
    ```
  </Accordion>

  <Accordion title="Pattern: Parallel Comparison" icon="scale-balanced">
    **Use Case**: Evaluate multiple approaches

    ```yaml theme={null}
    Parallel Agent:
      - LLM Approach A: Conservative solution
      - LLM Approach B: Creative solution
      - LLM Approach C: Balanced solution

    Then:
      - LLM Evaluator: Pick best approach
    ```
  </Accordion>
</AccordionGroup>

***

## Performance Considerations

<CardGroup cols={2}>
  <Card title="Latency" icon="clock">
    * **LLM Agent**: 2-10 seconds
    * **Sequential Agent**: Sum of sub-agents
    * **Parallel Agent**: Max of sub-agents
    * **Loop Agent**: Iterations × agent time
  </Card>

  <Card title="Cost" icon="dollar-sign">
    * **LLM Agent**: 1 LLM call
    * **Sequential Agent**: N LLM calls
    * **Parallel Agent**: N LLM calls (concurrent)
    * **Loop Agent**: Up to max\_iterations × calls
  </Card>
</CardGroup>

### Optimization Tips

<Steps>
  <Step title="Use Faster Models">
    * **Development**: Claude Haiku (fast, cheap)
    * **Production**: Claude Sonnet (balanced)
    * **Complex Tasks Only**: Claude Opus / GPT-4

    Switching from Opus to Haiku can reduce latency by **5-10x** and costs by **60x**.
  </Step>

  <Step title="Enable Streaming">
    ```yaml theme={null}
    streaming_enabled: true  # Show tokens as they arrive
    ```

    Improves perceived performance even if total time is the same.
  </Step>

  <Step title="Limit Parallel Agents">
    * **2-3 parallel agents**: Optimal for most cases
    * **4-5 parallel agents**: Acceptable with monitoring
    * **6+ parallel agents**: Risk rate limiting and high costs

    Consider Sequential + Parallel hybrid instead of large Parallel groups.
  </Step>

  <Step title="Set Conservative max_llm_calls">
    ```yaml theme={null}
    Loop Agent:
      max_llm_calls: 3  # Rarely need more than 3 iterations
    ```

    Most loops converge in 2-3 iterations. Higher values rarely improve output quality.
  </Step>
</Steps>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Add Tools to Agents" icon="hammer" href="/guides/tools/overview">
    Connect agents to APIs and external services
  </Card>

  <Card title="MCP Integration" icon="plug" href="/guides/mcp/overview">
    Integrate GitHub, Firecrawl, and custom services
  </Card>

  <Card title="Tools Overview" icon="wrench" href="/guides/tools/overview">
    Let agents query your documents
  </Card>

  <Card title="Squad Collaboration" icon="people-arrows" href="/guides/orchestration/squad-collaboration">
    Let one squad's orchestrator ask another squad and relay the answer
  </Card>

  <Card title="Organization Wiki" icon="book-open" href="/guides/wiki-second-brain">
    Give every agent a shared second brain that persists across conversations
  </Card>
</CardGroup>

***

<Note>
  **Questions?** Contact us at [contact@junis.ai](mailto:contact@junis.ai) to discuss agent architectures and get expert guidance.
</Note>
