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

# Agent Module

> Documentation for the praisonaiagents.agent.agent module

# Agent

The core class for AI agents with tools, memory, knowledge, and handoffs.

## Param Cluster Map

| Cluster    | Legacy Params                                                                                                                 | Consolidated To | Status |
| ---------- | ----------------------------------------------------------------------------------------------------------------------------- | --------------- | ------ |
| Output     | `verbose`, `markdown`, `stream`, `metrics`, `reasoning_steps`                                                                 | `output=`       | ✅      |
| Execution  | `max_iter`, `max_rpm`, `max_execution_time`, `max_retry_limit`, `retry_initial_delay`, `retry_backoff_factor`, `retry_jitter` | `execution=`    | ✅      |
| Memory     | `memory`, `auto_memory`, `claude_memory`, `user_id`, `session_id`, `db`                                                       | `memory=`       | ✅      |
| Knowledge  | `knowledge`, `retrieval_config`, `embedder_config`                                                                            | `knowledge=`    | ✅      |
| Planning   | `planning`, `plan_mode`, `planning_tools`, `planning_reasoning`                                                               | `planning=`     | ✅      |
| Reflection | `self_reflect`, `max_reflect`, `min_reflect`, `reflect_llm`                                                                   | `reflection=`   | ✅      |
| Guardrails | `guardrail`, `max_guardrail_retries`, `policy`                                                                                | `guardrails=`   | ✅      |
| Web        | `web_search`, `web_fetch`                                                                                                     | `web=`          | ✅      |
| Templates  | `system_template`, `prompt_template`, `response_template`                                                                     | `templates=`    | ✅      |
| Caching    | `cache`, `prompt_caching`                                                                                                     | `caching=`      | ✅      |
| LLM        | `llm`, `llm_config`, `function_calling_llm`                                                                                   | `llm=`          | ✅      |

**Note:** `base_url` and `api_key` remain **separate** (connection/auth constraint).

## Precedence Ladder

`Instance > Config > Array > Dict > String > Bool > Default`

## Quick Start

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(instructions="You are a helpful assistant")
response = agent.start("Hello!")
```

## Parameters Table

### Core Identity

| Parameter      | Type  | Default | Description                                                            |
| -------------- | ----- | ------- | ---------------------------------------------------------------------- |
| `name`         | `str` | `None`  | Agent name for identification                                          |
| `role`         | `str` | `None`  | Role/job title defining expertise                                      |
| `goal`         | `str` | `None`  | Primary objective                                                      |
| `backstory`    | `str` | `None`  | Background context                                                     |
| `instructions` | `str` | `None`  | 💡 **Canonical** - Direct instructions (overrides role/goal/backstory) |

### LLM Configuration

| Parameter              | Type         | Default | Description                             |
| ---------------------- | ------------ | ------- | --------------------------------------- |
| `llm`                  | `str \| Any` | `None`  | ✅ Model name (`"gpt-4o"`) or LLM object |
| `model`                | `str \| Any` | `None`  | ✅ **Alias** for `llm=`                  |
| `base_url`             | `str`        | `None`  | Custom endpoint URL (kept separate)     |
| `api_key`              | `str`        | `None`  | API key (kept separate)                 |
| `function_calling_llm` | `Any`        | `None`  | ⚠️ **Deprecated** - use `llm=`          |
| `llm_config`           | `Dict`       | `None`  | ⚠️ **Deprecated** - use `llm=`          |

### Tools & Capabilities

| Parameter              | Type                     | Default  | Description                                                              |
| ---------------------- | ------------------------ | -------- | ------------------------------------------------------------------------ |
| `tools`                | `List[Any]`              | `None`   | Tools, functions, or MCP instances                                       |
| `handoffs`             | `List[Agent \| Handoff]` | `None`   | Agents for task delegation                                               |
| `allow_delegation`     | `bool`                   | `False`  | ⚠️ **Deprecated** — use `handoffs=`                                      |
| `allow_code_execution` | `bool`                   | `False`  | ⚠️ **Deprecated** — use `execution=ExecutionConfig(code_execution=True)` |
| `code_execution_mode`  | `"safe" \| "unsafe"`     | `"safe"` | ⚠️ **Deprecated** — use `execution=ExecutionConfig(code_mode=)`          |

### Deprecated Standalone Params

These still work for backward compatibility but emit `DeprecationWarning`. Use the consolidated config objects instead.

| Parameter            | Type                     | Default | Replacement                                         |
| -------------------- | ------------------------ | ------- | --------------------------------------------------- |
| `auto_save`          | `str`                    | `None`  | `memory=MemoryConfig(auto_save="name")`             |
| `rate_limiter`       | `Any`                    | `None`  | `execution=ExecutionConfig(rate_limiter=obj)`       |
| `verification_hooks` | `List[VerificationHook]` | `None`  | `autonomy=AutonomyConfig(verification_hooks=[...])` |

### Consolidated Feature Params

Each follows: `False`=disabled, `True`=defaults, `Config`=custom

| Parameter    | Type                                   | Default | Description                |
| ------------ | -------------------------------------- | ------- | -------------------------- |
| `memory`     | `bool \| MemoryConfig`                 | `None`  | Memory system              |
| `knowledge`  | `bool \| List[str] \| KnowledgeConfig` | `None`  | Knowledge sources          |
| `planning`   | `bool \| PlanningConfig`               | `False` | Planning mode              |
| `reflection` | `bool \| ReflectionConfig`             | `None`  | Self-reflection            |
| `guardrails` | `bool \| Callable \| GuardrailConfig`  | `None`  | Output validation          |
| `web`        | `bool \| WebConfig`                    | `None`  | Web search/fetch           |
| `context`    | `bool \| ContextConfig`                | `False` | Context management         |
| `autonomy`   | `bool \| Dict \| AutonomyConfig`       | `None`  | Autonomy settings          |
| `output`     | `str \| OutputConfig`                  | `None`  | Output preset or config    |
| `execution`  | `str \| ExecutionConfig`               | `None`  | Execution preset or config |
| `caching`    | `bool \| CachingConfig`                | `None`  | Caching settings           |
| `hooks`      | `List \| HooksConfig`                  | `None`  | Event hooks                |
| `skills`     | `List[str] \| SkillsConfig`            | `None`  | Agent skills               |
| `templates`  | `TemplateConfig`                       | `None`  | Template configuration     |

## Precedence Ladder

<Info>
  **Resolution Order**: Instance > Config > Array > Dict > String > Bool > Default

  When you pass a consolidated param, the resolver checks in this order:

  1. **Instance** - Already a config object? Use as-is
  2. **Config** - Dataclass instance? Use as-is
  3. **Array** - `["preset", {"override": value}]`? Apply overrides
  4. **Dict** - `{"key": value}`? Convert to config
  5. **String** - `"preset_name"` or URL? Look up preset or parse URL
  6. **Bool** - `True`? Use defaults. `False`? Disable
  7. **Default** - `None`? Use default value
</Info>

## Usage Forms Table

| Form                  | Example                                 | When to Use             |
| --------------------- | --------------------------------------- | ----------------------- |
| **Bool**              | `memory=True`                           | Enable with defaults    |
| **String preset**     | `output="verbose"`                      | Use predefined config   |
| **URL**               | `memory="redis://localhost"`            | Backend-specific config |
| **Dict**              | `memory={"backend": "redis"}`           | Custom config as dict   |
| **Array + overrides** | `output=["verbose", {"stream": False}]` | Preset + customization  |
| **Config instance**   | `memory=MemoryConfig(backend="redis")`  | Full control            |

### Examples for Each Form

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Bool - enable with defaults
agent = Agent(instructions="...", memory=True)

# String preset
agent = Agent(instructions="...", output="verbose")

# URL scheme
agent = Agent(instructions="...", memory="redis://localhost:6379")

# Dict
agent = Agent(instructions="...", memory={"backend": "postgres", "user_id": "u1"})

# Array with overrides
agent = Agent(instructions="...", output=["verbose", {"stream": False}])

# Config instance
from praisonaiagents import MemoryConfig
agent = Agent(instructions="...", memory=MemoryConfig(backend="redis"))
```

## Presets & Options

### Output Presets

| Preset      | Description                          | Example                                     |
| ----------- | ------------------------------------ | ------------------------------------------- |
| `"silent"`  | Zero output (default)                | —                                           |
| `"status"`  | Tool calls + response, no timestamps | `▸ get_weather → Sunny ✓`                   |
| `"trace"`   | Full trace with timestamps           | `[14:30:29] ▸ get_weather → Sunny [0.2s] ✓` |
| `"debug"`   | trace + metrics (no boxes)           | Timestamps + token counts, cost             |
| `"verbose"` | Rich panels with Markdown            | Task + Response panels                      |
| `"stream"`  | Real-time token streaming            | Tokens appear as generated                  |
| `"json"`    | JSONL events                         | `{"event": "tool_call", ...}`               |

**Aliases:** `"text"`, `"actions"` → `"status"` | `"plain"`, `"minimal"` → `"silent"` | `"normal"` → `"verbose"`

### Execution Presets

| Preset        | max\_iter | max\_retry\_limit |
| ------------- | --------- | ----------------- |
| `"fast"`      | 10        | 1                 |
| `"balanced"`  | 20        | 2                 |
| `"thorough"`  | 50        | 5                 |
| `"unlimited"` | 1000      | 10                |

### Memory Presets

| Preset       | Backend            |
| ------------ | ------------------ |
| `"file"`     | Local file storage |
| `"sqlite"`   | SQLite database    |
| `"redis"`    | Redis server       |
| `"postgres"` | PostgreSQL         |
| `"mongodb"`  | MongoDB            |

### Web Presets

| Preset          | search | fetch | provider   |
| --------------- | ------ | ----- | ---------- |
| `"duckduckgo"`  | ✅      | ✅     | DuckDuckGo |
| `"tavily"`      | ✅      | ✅     | Tavily     |
| `"google"`      | ✅      | ✅     | Google     |
| `"search_only"` | ✅      | ❌     | Default    |
| `"fetch_only"`  | ❌      | ✅     | Default    |

### Reflection Presets

| Preset       | min\_iterations | max\_iterations |
| ------------ | --------------- | --------------- |
| `"minimal"`  | 1               | 1               |
| `"standard"` | 1               | 3               |
| `"thorough"` | 2               | 5               |

### Guardrail Presets

| Preset         | max\_retries | on\_fail |
| -------------- | ------------ | -------- |
| `"strict"`     | 5            | raise    |
| `"permissive"` | 1            | skip     |
| `"safety"`     | 3            | retry    |

## Methods

### Execution Methods

| Method                          | Streams by Default | Display      | Use Case                        |
| ------------------------------- | ------------------ | ------------ | ------------------------------- |
| `start(prompt, **kwargs)`       | ✅ Yes (in TTY)     | ✅ Auto       | Interactive/terminal use        |
| `run(prompt, **kwargs)`         | ❌ No               | ❌ No         | Production/scripted use         |
| `iter_stream(prompt, **kwargs)` | ✅ Always           | ❌ No         | App integration (yields chunks) |
| `chat(prompt, ...)`             | Configurable       | Configurable | Low-level execution             |

### Async Execution Methods

| Method                     | Streams by Default | Use Case          |
| -------------------------- | ------------------ | ----------------- |
| `astart(prompt, **kwargs)` | ✅ Yes (in TTY)     | Async interactive |
| `arun(prompt, **kwargs)`   | ❌ No               | Async production  |
| `achat(prompt, ...)`       | Configurable       | Async low-level   |

### Other Methods

| Method                      | Description                     |
| --------------------------- | ------------------------------- |
| `query(question, **kwargs)` | Query knowledge base (RAG)      |
| `retrieve(query, **kwargs)` | Retrieve context from knowledge |
| `clear_history()`           | Clear chat history              |
| `execute_tool(name, args)`  | Execute a tool dynamically      |

### Class Methods

| Method                                          | Description                |
| ----------------------------------------------- | -------------------------- |
| `from_template(uri, config, offline, **kwargs)` | Create agent from template |

## Common Recipes

### Simple Agent with Instructions

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Assistant",
    instructions="You are a helpful AI assistant that provides concise, accurate answers."
)
response = agent.start("What is the capital of France?")
print(response)
```

### Agent with Tools

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent, tool

@tool
def get_weather(city: str) -> str:
    """Get the current weather for a city."""
    return f"Weather in {city}: Sunny, 22°C"

agent = Agent(
    name="Weather Assistant",
    instructions="Help users check the weather",
    tools=[get_weather]
)
response = agent.start("What's the weather in Paris?")
```

### Agent with Handoffs

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

billing_agent = Agent(name="Billing", instructions="Handle billing inquiries")
tech_agent = Agent(name="Tech Support", instructions="Solve technical issues")

main_agent = Agent(
    name="Customer Service",
    instructions="Route customers to the right department",
    handoffs=[billing_agent, tech_agent]
)
response = main_agent.start("I have a billing question")
```

### Agent with Knowledge Base

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Research Assistant",
    instructions="Answer questions using the knowledge base",
    knowledge=["research_papers/", "data.pdf"]
)
response = agent.start("Summarize the key findings")
```

### Agent with Streaming

Choose the right method based on your use case:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Story Writer",
    instructions="Write creative stories"
)

# Method 1: start() - streams automatically in terminal (TTY)
# Best for interactive/beginner use
for chunk in agent.start("Write a short story"):
    print(chunk, end="", flush=True)

# Method 2: iter_stream() - always streams, no display
# Best for app integration
full_response = ""
for chunk in agent.iter_stream("Write a short story"):
    full_response += chunk
    # Custom processing here

# Method 3: run() - silent, returns result directly
# Best for production/scripted use
result = agent.run("Write a short story")
print(result)

# Method 2: Use any preset + stream=True in start() (per-call control)
agent = Agent(
    name="Story Writer",
    instructions="Write creative stories",
    output="verbose"  # Any preset
)

for chunk in agent.start("Write a short story", stream=True):
    print(chunk, end="", flush=True)

# Method 3: Silent streaming (no verbose output, clean stream)
agent = Agent(
    name="Writer",
    instructions="You are concise",
    output="silent"
)

for chunk in agent.start("Write a haiku", stream=True):
    print(chunk, end="", flush=True)

# Method 4: Collect full response while streaming
chunks = []
for chunk in agent.start("List 3 tips"):
    chunks.append(chunk)
    print(chunk, end="", flush=True)
full_response = "".join(chunks)
```

<Info>
  **Streaming Precedence**: `start(stream=True/False)` overrides `OutputConfig.stream`.

  * `output="stream"` sets `stream=True` by default
  * `start(stream=False)` can disable streaming even with `output="stream"`
  * `start(stream=True)` enables streaming for any preset
</Info>

<Warning>
  **When to use which method:**

  * **`output="stream"`**: Agent always streams, no per-call control needed
  * **`start(stream=True)`**: Control streaming per-call, useful for conditional streaming
  * **`output="silent"` + `stream=True`**: Clean streaming without agent status messages
</Warning>

### Agent with Custom LLM

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

# Using Ollama
agent = Agent(
    name="Local Assistant",
    instructions="You are a helpful assistant",
    llm="ollama/llama3",
    base_url="http://localhost:11434"
)

# Using Anthropic
agent = Agent(
    name="Claude Assistant",
    instructions="You are a helpful assistant",
    llm="anthropic/claude-3-sonnet-20240229"
)
```

### Agent with Consolidated Config

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonaiagents import Agent

agent = Agent(
    name="Advanced Agent",
    instructions="You are an advanced assistant",
    output="verbose",           # Output preset
    execution="thorough",       # Execution preset
    memory=True,                # Enable memory with defaults
    planning=True,              # Enable planning mode
    reflection=True,            # Enable self-reflection
)
```

## Async Support

The Agent class provides full async support:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import asyncio
from praisonaiagents import Agent

async def main():
    agent = Agent(
        name="AsyncAgent",
        instructions="Handle async operations efficiently"
    )
    
    # Async chat
    result = await agent.achat("Process this request")
    print(result)
    
    # Async start
    result = await agent.astart("Another request")
    print(result)

asyncio.run(main())
```

## Multi-Agent Safe

Agents are designed to be multi-agent safe. Each agent maintains its own:

* Chat history
* Memory instance
* Knowledge base
* Session state

Multiple agents can run concurrently without interference.

## See Also

* [Agents Module](/docs/sdk/praisonaiagents/agents/agents) - Multi-agent orchestration
* [Handoff Module](/docs/sdk/praisonaiagents/handoff/handoff) - Agent-to-agent handoffs
* [Tools Module](/docs/sdk/praisonaiagents/tools/tools) - Tool system
* [Memory Module](/docs/sdk/praisonaiagents/memory/memory) - Memory management
* [Knowledge Module](/docs/sdk/praisonaiagents/knowledge/knowledge) - Knowledge bases
