<!-- source: https://deepwiki.com/MervinPraison/PraisonAI/14.1-python-examples -->

# Python Examples

- README.md
- api.md
- src/praisonai/README.md

## Purpose and Scope

This document provides practical Python code examples for using the PraisonAI Agents framework programmatically. It covers the core API usage patterns including single agents, multi-agent systems, workflow orchestration, custom tools, memory integration, and advanced features like planning mode and autonomous execution.

For command-line usage examples, see [CLI Examples](/MervinPraison/PraisonAI/14.3-cli-examples). For deployment-specific examples, see [Deployment Examples](/MervinPraison/PraisonAI/14.4-deployment-examples). For TypeScript/JavaScript examples, see [TypeScript Examples](/MervinPraison/PraisonAI/14.2-typescript-examples). For comprehensive API documentation, see [Python API Reference](/MervinPraison/PraisonAI/12.1-python-api-reference).

## Basic Agent Usage

### Single Agent Pattern

The most fundamental pattern in PraisonAI is the single `Agent` class instantiation and execution.

```

```

**Core Components:**

**Basic Example Pattern:**

The agent initialization follows this signature: `Agent(name=None, role=None, goal=None, instructions=None, tools=None, llm=None, memory=False)`. The `instructions` parameter defines the agent's behavior, while `start(prompt)` executes a task.

**Sources:** [README.md522-534](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L522-L534) [praisonaiagents/agent/agent.py1-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L1-L100)

### Multi-Agent Coordination

Multi-agent systems use the `Agents` (or `AgentTeam`) class to coordinate multiple agents with task dependencies.

```

```

**Multi-Agent Architecture:**

**Task Context Flow:**

When multiple agents execute sequentially, each agent receives the previous agent's output via the `context` parameter. The `Task.depends_on` property enables dependency management [praisonaiagents/task/task.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/task/task.py#L50-L100)

**Sources:** [README.md536-551](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L536-L551) [praisonaiagents/agent/agents.py1-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agents.py#L1-L200) [praisonaiagents/agent/agent_team.py1-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent_team.py#L1-L300)

## Workflow Orchestration

### Workflow Class Architecture

The `Workflow` class provides deterministic pipeline execution with advanced control flow patterns.

```

```

**Workflow Components:**

**Sources:** [README.md775-877](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L775-L877) [praisonaiagents/workflows/workflow.py1-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflow.py#L1-L400)

### Routing Pattern

The `route()` pattern implements conditional branching based on a classifier agent's output.

```

```

**Implementation Pattern:**

```

```

The routing logic is implemented in [praisonaiagents/workflows/workflows.py100-150](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L100-L150) where the `Route.execute()` method evaluates the previous step's output against the route keys.

**Sources:** [README.md813-828](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L813-L828) [praisonaiagents/workflows/workflows.py100-150](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L100-L150)

### Parallel Execution Pattern

The `parallel()` pattern executes multiple agents concurrently and aggregates results.

```

```

**Implementation Pattern:**

```

```

The parallel execution uses `ThreadPoolExecutor` for concurrent agent execution [praisonaiagents/workflows/workflows.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L50-L100)

**Sources:** [README.md830-838](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L830-L838) [praisonaiagents/workflows/workflows.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L50-L100)

### Loop Pattern

The `loop()` pattern iterates over a list or CSV file, executing an agent for each item.

```

```

**Implementation Pattern:**

```

```

The loop implementation supports both list iteration and CSV file iteration with `from_csv` parameter [praisonaiagents/workflows/workflows.py150-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L150-L200)

**Sources:** [README.md840-847](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L840-L847) [praisonaiagents/workflows/workflows.py150-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L150-L200)

### Repeat Pattern (Evaluator-Optimizer)

The `repeat()` pattern implements iterative refinement with a termination condition.

```

```

**Implementation Pattern:**

```

```

The repeat logic is implemented in [praisonaiagents/workflows/workflows.py200-250](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L200-L250) where the `Repeat.execute()` method evaluates the until condition.

**Sources:** [README.md849-856](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L849-L856) [praisonaiagents/workflows/workflows.py200-250](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/workflows.py#L200-L250)

## Specialized Agents

### Agent Type Hierarchy

```

```

**Specialized Agent Classes:**

**Sources:** [README.md220-331](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L220-L331) [praisonaiagents/agent/deep_research_agent.py1-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/deep_research_agent.py#L1-L100) [praisonaiagents/agent/query_rewriter_agent.py1-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/query_rewriter_agent.py#L1-L100)

### DeepResearchAgent

The `DeepResearchAgent` provides automated research with real-time streaming and structured citations.

```

```

**Key Methods:**

**Usage Pattern:**

The agent automatically detects the provider from the model name. OpenAI models starting with `o` (o3, o4-mini, etc.) use OpenAI's client, models containing "deep-research" use Gemini, otherwise LiteLLM is used [praisonaiagents/agent/deep_research_agent.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/deep_research_agent.py#L50-L100)

**Sources:** [README.md580-617](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L580-L617) [praisonaiagents/agent/deep_research_agent.py1-500](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/deep_research_agent.py#L1-L500)

### QueryRewriterAgent

The `QueryRewriterAgent` transforms user queries using multiple strategies to improve retrieval quality.

```

```

**Rewrite Strategies:**

**Custom Abbreviations:**

The agent supports custom abbreviations via `add_abbreviation()` and `add_abbreviations()` methods [praisonaiagents/agent/query_rewriter_agent.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/query_rewriter_agent.py#L50-L100)

**Sources:** [README.md618-652](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L618-L652) [praisonaiagents/agent/query_rewriter_agent.py1-500](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/query_rewriter_agent.py#L1-L500)

## Tools and Integration

### Tool System Architecture

```

```

**Tool Components:**

**Sources:** [praisonaiagents/tools/base.py1-250](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/base.py#L1-L250) [praisonaiagents/tools/decorator.py1-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/decorator.py#L1-L200)

### Custom Tool Creation

Custom tools can be created using either the `@tool` decorator or by subclassing `BaseTool`.

```

```

**Decorator Pattern:**

```

```

The `@tool` decorator automatically generates the JSON schema from the function signature and docstring [praisonaiagents/tools/decorator.py1-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/decorator.py#L1-L100)

**Class Pattern:**

```

```

The `BaseTool` class provides `safe_run()` for error handling and `get_schema()` for JSON schema generation [praisonaiagents/tools/base.py1-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/base.py#L1-L200)

**Sources:** [README.md2194-2246](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L2194-L2246) [praisonaiagents/tools/decorator.py1-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/decorator.py#L1-L100) [praisonaiagents/tools/base.py1-200](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/tools/base.py#L1-L200)

### MCP Integration

Model Context Protocol (MCP) allows agents to consume external tools from MCP servers.

```

```

**MCP Components:**

**Transport Support:**

- stdio : Local processes via NPX/UVX commands
- HTTP : Production servers with streamable HTTP
- WebSocket : Real-time bidirectional communication
- SSE : Legacy compatibility with Server-Sent Events

**Usage Patterns:**

```

```

The MCP client automatically detects the transport type from the command/URL format [praisonaiagents/mcp/mcp.py50-150](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/mcp/mcp.py#L50-L150)

**Sources:** [README.md1407-1482](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L1407-L1482) [praisonaiagents/mcp/mcp.py1-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/mcp/mcp.py#L1-L300)

## Memory and State Management

### Memory System Architecture

```

```

**Memory Components:**

**Quality Scoring:**

The memory system supports quality scoring for long-term memories using four metrics: completeness, relevance, clarity, and accuracy. These are combined using configurable weights to compute a final quality score [praisonaiagents/memory/memory.py200-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/memory/memory.py#L200-L300)

**Sources:** [README.md653-709](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L653-L709) [praisonaiagents/memory/memory.py1-800](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/memory/memory.py#L1-L800) [praisonaiagents/memory/file.py1-600](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/memory/file.py#L1-L600)

### Session Management

Sessions provide state persistence and resumability across agent executions.

```

```

**Session API:**

**Auto-save Pattern:**

```

```

The `auto_save` parameter triggers automatic session persistence after each execution [praisonaiagents/agent/agent.py300-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L300-L400)

**Sources:** [README.md1901-1955](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L1901-L1955) [praisonaiagents/session/api.py1-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/session/api.py#L1-L300)

## Advanced Patterns

### Planning Mode

Planning mode enables agents to create and execute multi-step plans before taking action.

```

```

**Planning Components:**

**Tool Restrictions:**

The planning system categorizes tools into restricted and read-only sets. Restricted tools require explicit approval, while read-only tools are always allowed during planning [praisonaiagents/planning/planner.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/planning/planner.py#L50-L100)

**Sources:** [README.md553-579](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L553-L579) [praisonaiagents/planning/planner.py1-500](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/planning/planner.py#L1-L500) [praisonaiagents/planning/plan.py1-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/planning/plan.py#L1-L400)

### Handoff System

The handoff system enables agent-to-agent delegation with context transfer and cycle detection.

```

```

**Handoff Components:**

**Context Policies:**

- FULL : Transfer complete context including tools and history
- MESSAGES_ONLY : Transfer only message history
- NONE : No context transfer, clean slate

**Input Filters:**

The `handoff_filters` class provides pre-built filters:

- remove_system_messages() : Strip system messages from context
- remove_all_tools() : Remove tool definitions
- keep_last_n_messages(n) : Limit message history

**Sources:** [praisonaiagents/agent/handoff.py1-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/handoff.py#L1-L400)

### Autonomous Execution

Autonomous mode enables agents to execute iteratively until a completion condition is met.

```

```

**Autonomous Execution:**

**Doom Loop Detection:**

The autonomous execution system detects "doom loops" (repeating patterns) by comparing recent outputs. If the same output appears multiple times consecutively, it raises an error [praisonaiagents/agent/agent.py850-900](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L850-L900)

**Completion Promise:**

The `completion_promise` parameter accepts a string that the LLM should include in its output when the task is complete. For example: `completion_promise="TASK_COMPLETE"`.

**Sources:** [praisonaiagents/agent/agent.py800-1000](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L800-L1000)

### Evaluation Loop (run_until)

The `run_until()` method implements iterative refinement with quality evaluation.

```

```

**Evaluation Loop Components:**

**Modes:**

- optimize : Generate improvements and retry with feedback
- evaluate : Only evaluate, don't generate improvements

**Evaluation Process:**

The evaluation uses an LLM call to score the output based on the provided criteria. The prompt template is: `"Evaluate the following output based on this criteria: {criteria}. Rate from 0-10."` [praisonaiagents/agent/agent.py1050-1100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L1050-L1100)

**Sources:** [praisonaiagents/agent/agent.py1000-1400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L1000-L1400)

### Structured Output

Agents can produce structured output using JSON schema or Pydantic models.

```

```

**Structured Output Usage:**

```

```

The structured output is enforced via the LLM's `response_format` parameter (for OpenAI-compatible models) or through prompt engineering for other providers [praisonaiagents/llm/llm.py200-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/llm/llm.py#L200-L300)

**Sources:** [praisonaiagents/agent/agent.py400-500](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/agent/agent.py#L400-L500) [praisonaiagents/llm/llm.py200-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/llm/llm.py#L200-L300)

## YAML Configuration

### YAML Workflow Structure

YAML workflows provide declarative configuration for complex multi-agent systems.

```

```

**YAML Components:**

**Sources:** [README.md882-1042](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L882-L1042)

### YAML Parser and Loader

The YAML workflow parser converts YAML configuration into executable `Workflow` objects.

```

```

**YAML Components:**

**Loading Patterns:**

```

```

**Sources:** [README.md950-971](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L950-L971) [praisonaiagents/workflows/yaml_parser.py1-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/workflows/yaml_parser.py#L1-L400)

## Integration Examples

### Knowledge Base Integration

The `Knowledge` class provides document ingestion and retrieval for RAG pipelines.

```

```

**Knowledge Components:**

**Chunking Strategies:**

The chunking system is configurable via `ChunkingStrategy` enum [praisonaiagents/knowledge/chunking.py50-100](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/knowledge/chunking.py#L50-L100)

**Sources:** [praisonaiagents/knowledge/knowledge.py1-600](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/knowledge/knowledge.py#L1-L600) [praisonaiagents/knowledge/chunking.py1-400](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/knowledge/chunking.py#L1-L400)

### RAG Pipeline

The `RAG` class implements retrieval-augmented generation with hybrid retrieval and reranking.

```

```

**RAG Components:**

**Retrieval Policies:**

- ALWAYS : Always retrieve, regardless of query
- SMART : LLM decides when retrieval is needed
- NEVER : Never retrieve, pure LLM generation

The retrieval policy is determined by `RetrievalConfig.should_retrieve()` [praisonaiagents/rag/retrieval_config.py100-150](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/rag/retrieval_config.py#L100-L150)

**Sources:** [praisonaiagents/rag/pipeline.py1-700](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/rag/pipeline.py#L1-L700) [praisonaiagents/rag/models.py1-250](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/rag/models.py#L1-L250)

### LLM Provider Integration

The `LLM` class abstracts over 100+ LLM providers via LiteLLM.

```

```

**LLM Components:**

**Model Capabilities:**

The `ModelCapabilities` class detects provider-specific features:

- Tool calling support
- JSON mode support
- Vision support
- Context window size
- Streaming support

**Provider Configuration:**

Models are specified using the format `provider/model-name`. LiteLLM automatically routes to the correct provider [praisonaiagents/llm/llm.py50-150](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/llm/llm.py#L50-L150)

**Sources:** [praisonaiagents/llm/llm.py1-800](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/llm/llm.py#L1-L800) [praisonaiagents/llm/capabilities.py1-300](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/praisonaiagents/llm/capabilities.py#L1-L300)

## Summary

This document covered the core Python API patterns for PraisonAI:

**Basic Patterns:**

- Single Agent instantiation and execution
- Multi-agent coordination with Agents / AgentTeam
- Workflow orchestration with deterministic control flow

**Workflow Patterns:**

- route() for conditional branching
- parallel() for concurrent execution
- loop() for iteration over collections
- repeat() for evaluator-optimizer patterns

**Specialized Agents:**

- DeepResearchAgent for research with citations
- QueryRewriterAgent for query transformation
- ImageAgent for image generation
- ContextAgent for codebase analysis

**Integration Layers:**

- Custom tools via @tool decorator or BaseTool
- MCP protocol for external tool consumption
- Memory system with multiple backends
- Knowledge base with chunking and retrieval
- RAG pipeline with hybrid retrieval

**Advanced Features:**

- Planning mode with approval gates
- Handoff system for agent delegation
- Autonomous execution with doom loop detection
- Evaluation loops with quality scoring
- Structured output with JSON/Pydantic

For CLI usage patterns, see [CLI Examples](/MervinPraison/PraisonAI/14.3-cli-examples). For production deployment, see [Deployment Examples](/MervinPraison/PraisonAI/14.4-deployment-examples).

**Sources:** [README.md520-2246](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/README.md?plain=1#L520-L2246) [api.md1-5000](https://github.com/MervinPraison/PraisonAI/blob/ab80807b/api.md?plain=1#L1-L5000)
