> ## 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.

# Local Agent

> Run the agent loop locally with any LLM and optional cloud-sandboxed tools

LocalAgent runs the agent execution loop locally in your process, supporting any LLM via litellm routing and optional cloud compute for tool sandboxing.

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

local = LocalAgent(config=LocalAgentConfig(model="gpt-4o-mini"))
agent = Agent(name="assistant", backend=local)
agent.start("Explain quantum computing in simple terms")
```

The user sends a message; LocalAgent runs the loop on your machine and returns the model response.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Local Agent Flow"
        A[📝 User Request] --> B[💻 Local Process]
        B --> C[🤖 Any LLM]
        B --> D[🔧 Local/Cloud Tools]
        D --> E[✅ Response]
    end
    
    classDef input fill:#8B0000,stroke:#7C90A0,color:#fff
    classDef process fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef llm fill:#10B981,stroke:#7C90A0,color:#fff
    classDef tools fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#6366F1,stroke:#7C90A0,color:#fff
    
    class A input
    class B process
    class C llm
    class D tools
    class E output
```

## Quick Start

<Steps>
  <Step title="Simplest Usage">
    Create a local agent with minimal configuration:

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

    local = LocalAgent(
        config=LocalAgentConfig(
            model="gpt-4o-mini"
        )
    )

    agent = Agent(name="assistant", backend=local)
    result = agent.start("Explain quantum computing in simple terms")
    ```
  </Step>

  <Step title="With Cloud Compute Sandbox">
    Use `compute=` to run tools in a cloud sandbox while thinking stays local:

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

    local = LocalAgent(
        compute="e2b",  # Cloud sandbox for tools
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )

    agent = Agent(name="coder", backend=local)
    result = agent.start("Create a Python script that analyzes a CSV file")
    ```

    <Note>
      `LocalAgent` uses `compute=` to place its tools on a provider. To share one sandbox across a whole flow or team, use `AgentFlow(run_on=…)`. See [Placement](/docs/features/placement).
    </Note>
  </Step>
</Steps>

***

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant LocalAgent
    participant LLM
    participant Tools
    
    User->>Agent: Request
    Agent->>LocalAgent: Execute locally
    
    Note over LocalAgent: Agent loop runs in local process
    
    LocalAgent->>LLM: HTTP call (OpenAI/Gemini/Ollama)
    LLM-->>LocalAgent: Response
    
    LocalAgent->>Tools: Execute (local or cloud)
    Tools-->>LocalAgent: Tool result
    
    LocalAgent-->>Agent: Final result
    Agent-->>User: Response
```

| Component         | Location       | Purpose                            |
| ----------------- | -------------- | ---------------------------------- |
| **Agent Loop**    | Local Process  | Complete execution control         |
| **LLM**           | External API   | Any provider via litellm routing   |
| **Tools**         | Local or Cloud | Configurable execution environment |
| **Session State** | Local Memory   | Process-managed state              |

***

## Choosing an LLM

<Tabs>
  <Tab title="OpenAI">
    Use OpenAI models with API key authentication:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export OPENAI_API_KEY="sk-..."

    local = LocalAgent(
        config=LocalAgentConfig(
            model="gpt-4o"  # or "gpt-4o-mini", "gpt-3.5-turbo"
        )
    )
    ```
  </Tab>

  <Tab title="Gemini">
    Use Google's Gemini models:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export GOOGLE_API_KEY="AIza..."

    local = LocalAgent(
        config=LocalAgentConfig(
            model="gemini/gemini-2.0-flash"  # litellm prefix required
        )
    )
    ```
  </Tab>

  <Tab title="Ollama">
    Use local Ollama models:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig

    # Requires Ollama running locally
    local = LocalAgent(
        config=LocalAgentConfig(
            model="ollama/llama3"  # litellm prefix required
        )
    )
    ```
  </Tab>

  <Tab title="Anthropic">
    Use Claude models via API:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export ANTHROPIC_API_KEY="sk-ant-..."

    local = LocalAgent(
        config=LocalAgentConfig(
            model="claude-3-5-sonnet-latest"
        )
    )
    ```
  </Tab>

  <Tab title="Custom">
    Use any litellm-supported provider:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig

    local = LocalAgent(
        config=LocalAgentConfig(
            model="azure/gpt-4o"  # Azure OpenAI
            # model="groq/llama3-70b-8192"  # Groq
            # model="together_ai/meta-llama/Llama-2-70b-chat-hf"  # Together AI
        )
    )
    ```
  </Tab>
</Tabs>

***

## Choosing a Compute Backend

<Tabs>
  <Tab title="None (Local)">
    Execute tools in local subprocess (fastest, least secure):

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig

    local = LocalAgent(
        # No compute parameter = local subprocess
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```

    <Warning>
      Local subprocess compute validates every `packages={"pip": [...]}` entry against a strict allowlist. Only [PEP 508](https://peps.python.org/pep-0508/) requirement specifiers are accepted — name, extras, version bounds, and comments (characters `A-Z a-z 0-9 . _ - [ ] < > = , ~ ! +` and spaces).

      Pip options with a leading dash are rejected: `--upgrade`, `--pre`, `-r requirements.txt`, `-e ./pkg`. An invalid entry raises:

      ```text theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      ValueError: Invalid pip package specifier: '--upgrade'. Only pip requirement specifiers are allowed.
      ```

      Rewrite options as plain specifiers:

      ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
      # Rejected
      config = LocalAgentConfig(packages={"pip": ["--upgrade", "-r req.txt"]})

      # Accepted
      config = LocalAgentConfig(packages={"pip": ["pandas>=2", "numpy"]})
      ```
    </Warning>
  </Tab>

  <Tab title="Docker">
    Execute tools in Docker containers:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig

    local = LocalAgent(
        compute="docker",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>

  <Tab title="E2B">
    Execute tools in E2B cloud sandboxes:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export E2B_API_KEY="e2b_..."

    local = LocalAgent(
        compute="e2b",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>

  <Tab title="Modal">
    Execute tools on Modal cloud compute:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export MODAL_TOKEN="ak-..."

    local = LocalAgent(
        compute="modal",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>

  <Tab title="Flyio">
    Execute tools on Fly.io infrastructure:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export FLY_API_TOKEN="fo1-..."

    local = LocalAgent(
        compute="flyio",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>

  <Tab title="Daytona">
    Execute tools in Daytona development environments:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export DAYTONA_API_KEY="dtn-..."

    local = LocalAgent(
        compute="daytona",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>

  <Tab title="Novita">
    Execute tools in Novita cloud sandboxes:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai import LocalAgent, LocalAgentConfig
    import os

    # Set via shell: export NOVITA_API_KEY="your-key"

    local = LocalAgent(
        compute="novita",
        config=LocalAgentConfig(
            model="gpt-4o-mini",
            tools=["execute_command", "read_file", "write_file"]
        )
    )
    ```
  </Tab>
</Tabs>

### Compute Selection Guide

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    A[Choose Compute Backend] --> B{Security Requirements?}
    B -->|High Security| C[Cloud Sandbox]
    B -->|Medium Security| D[Docker]
    B -->|Low Security/Speed| E[Local Subprocess]
    
    C --> F[E2B - General cloud]
    C --> G[Modal - ML workloads]
    C --> H[Flyio - Edge deployment]
    C --> I[Daytona - Dev environments]
    C --> L[Novita - Cloud sandboxes]
    
    D --> J[Isolated containers]
    E --> K[Direct execution]
    
    classDef cloud fill:#10B981,stroke:#7C90A0,color:#fff
    classDef docker fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef local fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef decision fill:#6366F1,stroke:#7C90A0,color:#fff
    
    class C,F,G,H,I,L cloud
    class D,J docker
    class E,K local
    class A,B decision
```

### File-based defaults

Instead of passing `image` / `packages` / `env` as kwargs on every call, commit them to a `.praisonai/environment.yaml`. Every `compute=` backend loads it automatically; kwargs still win when provided.

<Card icon="file-code" href="/docs/features/environment-yaml">
  Repo-committed `.praisonai/environment.yaml` — image, packages, setup, resources
</Card>

<Tip>
  The docker backend also caches the provisioned environment across runs — see [Environment Capture](/docs/features/environment-capture).
</Tip>

***

## Configuration Options

<Card title="LocalAgent API Reference" icon="code" href="/docs/sdk/reference/typescript/classes/AgentConfig">
  Complete LocalAgent configuration options
</Card>

<Card title="LocalAgentConfig Reference" icon="code" href="/docs/sdk/reference/typescript/classes/AgentConfig">
  Configuration object parameters
</Card>

| Option             | Type        | Default                          | Description                                                                                                                                        |
| ------------------ | ----------- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model`            | `str`       | Required                         | LLM model (supports litellm prefixes)                                                                                                              |
| `system`           | `str`       | `"You are a helpful assistant."` | System prompt                                                                                                                                      |
| `tools`            | `List[str]` | `[]`                             | Available tool names                                                                                                                               |
| `packages`         | `Dict`      | `None`                           | Package dependencies for compute. PEP 508 requirement specifiers only; pip options such as `--upgrade` or `-r file` are rejected with `ValueError` |
| `host_packages_ok` | `bool`      | `False`                          | Allow host package installation                                                                                                                    |

***

## Common Patterns

### Switching LLMs

Change LLM providers without touching other code:

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

# Start with OpenAI
config = LocalAgentConfig(
    model="gpt-4o-mini",
    system="You are a helpful coding assistant."
)

# Switch to Gemini
config.model = "gemini/gemini-2.0-flash"

# Switch to Ollama
config.model = "ollama/llama3"

# Same agent setup works with any model
local = LocalAgent(config=config)
agent = Agent(name="coder", backend=local)
```

### Tool Execution

Configure tools for different execution environments:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai import LocalAgent, LocalAgentConfig

# Local execution (fast, less secure)
local_tools = LocalAgent(
    config=LocalAgentConfig(
        model="gpt-4o-mini",
        tools=["read_file", "write_file", "execute_command"]
    )
)

# Cloud execution (slower, more secure)
cloud_tools = LocalAgent(
    compute="e2b",
    config=LocalAgentConfig(
        model="gpt-4o-mini", 
        tools=["read_file", "write_file", "execute_command"]
    )
)
```

### Multi-turn Conversations

Maintain conversation state locally:

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

local = LocalAgent(
    config=LocalAgentConfig(
        model="gpt-4o-mini",
        system="You are a helpful assistant with memory."
    )
)

agent = Agent(name="assistant", backend=local)

# First turn
agent.start("My name is Alice")

# Second turn - state maintained in local process
response = agent.start("What's my name?")
# Response: "Your name is Alice"
```

### Usage Tracking

Monitor local agent resource usage:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# After execution
session_info = local.retrieve_session()
print(f"Input tokens: {session_info['usage']['input_tokens']}")
print(f"Output tokens: {session_info['usage']['output_tokens']}")

# List sessions
sessions = local.list_sessions()
for session in sessions:
    print(f"Session: {session['id']}")
```

### Multi-tenant safety

Two `LocalAgent` instances with different API keys stay isolated in the same process.

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

tenant_a = LocalAgent(
    api_key="sk-tenant-a",
    config=LocalAgentConfig(model="gpt-4o-mini")
)
tenant_b = LocalAgent(
    api_key="sk-tenant-b",
    config=LocalAgentConfig(model="gpt-4o-mini")
)

agent_a = Agent(name="tenant-a", backend=tenant_a)
agent_b = Agent(name="tenant-b", backend=tenant_b)
```

<Note>
  PraisonAI passes `api_key` and `base_url` directly to the inner agent, so credentials never leak into `os.environ` or a spawned subprocess. Each instance keeps its own key, even when many run in the same process.
</Note>

***

## Migrating from ManagedAgent

Update deprecated factory patterns to use the new canonical classes:

| Old                                                                          | New                                                                    |
| ---------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| `ManagedAgent(provider="openai", config=LocalManagedConfig(model="gpt-4o"))` | `LocalAgent(config=LocalAgentConfig(model="gpt-4o"))`                  |
| `ManagedAgent(provider="ollama", config=LocalManagedConfig(model="llama3"))` | `LocalAgent(config=LocalAgentConfig(model="ollama/llama3"))`           |
| `ManagedAgent(provider="gemini", config=LocalManagedConfig(...))`            | `LocalAgent(config=LocalAgentConfig(model="gemini/gemini-2.0-flash"))` |
| `ManagedAgent(provider="e2b", config=LocalManagedConfig(...))`               | `LocalAgent(compute="e2b", config=LocalAgentConfig(...))`              |
| `ManagedAgent(provider="modal", config=LocalManagedConfig(...))`             | `LocalAgent(compute="modal", config=LocalAgentConfig(...))`            |
| `ManagedAgent(provider="local", config=LocalManagedConfig(...))`             | `LocalAgent(config=LocalAgentConfig(...))`                             |

***

## Best Practices

<AccordionGroup>
  <Accordion title="Compute Backend Selection">
    Choose compute backends based on your trust and security requirements:

    * Use local subprocess for development and trusted environments
    * Use Docker for moderate isolation with good performance
    * Use cloud providers (E2B, Modal) for maximum security and isolation
    * Match compute choice to your specific use case (Modal for ML, Flyio for edge)
  </Accordion>

  <Accordion title="Model Selection with Litellm">
    Use litellm prefixes correctly for different providers:

    * Always include provider prefix for Gemini: `gemini/gemini-2.0-flash`
    * Always include provider prefix for Ollama: `ollama/llama3`
    * OpenAI models can omit prefix: `gpt-4o` or `openai/gpt-4o`
    * Test model availability before production deployment
  </Accordion>

  <Accordion title="Preferred LocalAgent Usage">
    Use the new canonical LocalAgent class instead of the deprecated factory:

    * Avoid the `provider=` parameter entirely on LocalAgent constructors
    * Use `config.model=` to specify LLM models with appropriate litellm prefixes
    * Use `compute=` to specify sandboxing backends separately from LLM choice
    * This provides cleaner separation of concerns and better maintainability
  </Accordion>

  <Accordion title="Environment Variables">
    Properly configure API keys and credentials:

    * Set LLM provider keys (`OPENAI_API_KEY`, `GOOGLE_API_KEY`, etc.)
    * Set compute provider keys (`E2B_API_KEY`, `MODAL_TOKEN`, etc.)
    * Use environment variable management tools for production deployments
    * Test authentication before deploying to avoid runtime failures
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Where Does It Run" icon="location-dot" href="/docs/features/where-does-it-run">
    Ask any agent where its thinking and tools actually execute
  </Card>

  <Card title="Hosted Agent" icon="cloud" href="/docs/features/hosted-agent">
    Run entire agent loops on Anthropic's managed runtime
  </Card>

  <Card title="Sandbox" icon="shield" href="/docs/features/sandbox">
    Tool execution sandboxing options
  </Card>

  <Card title="ManagedAgent Persistence" icon="database" href="/docs/features/managed-agent-persistence">
    Database integration patterns
  </Card>

  <Card title="Session Info" icon="info" href="/docs/features/managed-agents-session-info">
    Session metadata and usage tracking
  </Card>
</CardGroup>
