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

# Host Integration

> Embed PraisonAIUI in your own host application for seamless agent integration

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

agent = Agent(name="host-agent", instructions="Integrate with the host environment.")
agent.start("Connect to the host system and retrieve environment variables.")
```

Integrate PraisonAI agents directly into your application using the built-in host integration module.

<Tip>
  Just want a UI quickly? Use `UIPreset` + `build_ui_app()` — see [UI Presets](/docs/features/ui-presets).
</Tip>

The user interacts through the host app; PraisonAIUI bridges agent output into the host UI.

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph LR
    subgraph "Host Integration Flow"
        A[📋 Your App] --> B[⚙️ configure_host]
        B --> C[🔗 Bridges]
        C --> D[🎯 AIUI]
    end
    
    classDef app fill:#6366F1,stroke:#7C90A0,color:#fff
    classDef config fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef output fill:#10B981,stroke:#7C90A0,color:#fff
    
    class A app
    class B,C config
    class D output

```

## How It Works

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
sequenceDiagram
    participant User
    participant Agent
    participant Feature as Host Integration

    User->>Agent: Request
    Agent->>Feature: Process request
    Feature-->>Agent: Result    Agent-->>User: Response
```

## Quick Start

<Steps>
  <Step title="Simple Host">
    Create a host app with default settings:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai.integration import build_host_app

    app = build_host_app(
        title="My Agent App",
        pages=["chat", "agents", "sessions", "usage"],
    )
    # Run with: uvicorn main:app --host 0.0.0.0 --port 8000
    ```
  </Step>

  <Step title="Advanced Configuration">
    Configure with custom agents and settings:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai.integration import configure_host, create_host_app

    configure_host(
        title="Advanced Agent Platform",
        logo="🚀",
        pages=["chat", "agents", "memory", "knowledge", "sessions"],
        agents=[
            {
                "name": "Code Assistant",
                "instructions": "Help with coding tasks",
                "llm": "gpt-4o"
            }
        ],
        theme={"primary_color": "#3b82f6"}
    )

    app = create_host_app()
    ```
  </Step>
</Steps>

***

## When to Use `build_host_app` vs `build_ui_app`

Both APIs remain supported. Choose based on how much control you need:

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    A[Need a PraisonAI UI?] --> B{Want one config object?}
    B -->|Yes, minimal setup| C[UIPreset + build_ui_app]
    B -->|No, full control| D{Need custom callbacks?}
    D -->|Yes| E[configure_host + create_host_app]
    D -->|One-liner| F[build_host_app]

    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    classDef choice fill:#10B981,stroke:#7C90A0,color:#fff

    class A,B,D decision
    class C,E,F choice
```

| Pattern                              | Best for                                      |
| ------------------------------------ | --------------------------------------------- |
| `build_ui_app(UIPreset(...))`        | Chat/dashboard/bot UIs with sensible defaults |
| `build_host_app(...)`                | Quick host with keyword arguments             |
| `configure_host` + `create_host_app` | Custom bridges, agents list, theme hooks      |

***

## Integration Patterns

Choose your integration pattern based on your needs:

```mermaid theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
graph TB
    A[Need Integration?] --> B{Single Process?}
    B -->|Yes| C[Pattern B<br/>In-Process Host]
    B -->|No| D{WebSocket + REST?}
    D -->|Yes| E[Pattern C<br/>Integrated Gateway]
    D -->|No| F[Pattern D<br/>Platform API]
    
    classDef pattern fill:#189AB4,stroke:#7C90A0,color:#fff
    classDef decision fill:#F59E0B,stroke:#7C90A0,color:#fff
    
    class C,E,F pattern
    class A,B,D decision
```

***

## Configuration Options

| Option                 | Type             | Default       | Description                                                                                                                                                                                                                        |
| ---------------------- | ---------------- | ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pages`                | `Sequence[str]`  | `None`        | UI pages to include                                                                                                                                                                                                                |
| `title`                | `str`            | `"PraisonAI"` | Application title                                                                                                                                                                                                                  |
| `logo`                 | `str`            | `"🤖"`        | Logo or emoji                                                                                                                                                                                                                      |
| `sidebar`              | `bool`           | `True`        | Show navigation sidebar                                                                                                                                                                                                            |
| `page_header`          | `bool`           | `True`        | Show page header                                                                                                                                                                                                                   |
| `style`                | `str`            | `"dashboard"` | UI layout: `"dashboard"` or `"chat"`                                                                                                                                                                                               |
| `context_paths`        | `Sequence[str]`  | `None`        | Context file paths. `None` → walk-up auto-discovery from `context_cwd` (or process cwd). `[]` → authoritative "load nothing" sentinel; discovery is skipped. `["AGENTS.md", ...]` → load exactly those paths from cwd; no walk-up. |
| `no_context`           | `bool`           | `False`       | Skip all project-context loading. Honoured as a first-class param **and** when threaded through `agent_kwargs={"no_context": True}` (backward compat).                                                                             |
| `context_cwd`          | `Optional[str]`  | `None`        | Starting directory for walk-up discovery. Falls back to process cwd. Ignored when `context_paths` is explicitly provided.                                                                                                          |
| `context_token_budget` | `int`            | `8000`        | Maximum characters of discovered context to inject. Excess is truncated and `\n... [project context truncated]` is appended.                                                                                                       |
| `theme`                | `Dict[str, Any]` | `None`        | Custom theme settings                                                                                                                                                                                                              |
| `agents`               | `List[Any]`      | `None`        | Pre-configured agents                                                                                                                                                                                                              |
| `agent_kwargs`         | `Dict[str, Any]` | `None`        | Default agent parameters                                                                                                                                                                                                           |
| `gateway`              | `Any`            | `None`        | External gateway reference                                                                                                                                                                                                         |
| `modules`              | `Sequence[str]`  | `None`        | Additional modules to load                                                                                                                                                                                                         |

***

## API Reference

### Core Functions

<AccordionGroup>
  <Accordion title="configure_host()">
    Apply host settings and wire backends. Must be called before `create_host_app()`.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    configure_host(
        pages=["chat", "agents"],
        title="My App",
        agents=[{"name": "Assistant"}]
    )
    ```
  </Accordion>

  <Accordion title="create_host_app()">
    Return the Starlette app instance. Call after `configure_host()`.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    app = create_host_app()
    # Ready for uvicorn, gunicorn, etc.
    ```
  </Accordion>

  <Accordion title="build_host_app()">
    One-shot configuration and app creation. Simplest approach.

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    app = build_host_app(title="Quick Setup")
    ```
  </Accordion>

  <Accordion title="run_integrated_gateway()">
    Pattern C: Start gateway with integrated UI on single port. Sync wrapper for CLI and scripts.

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

    run_integrated_gateway(
        port=8765,
        title="Gateway App",
        style="dashboard",
        context_paths=["AGENTS.md"]
    )
    ```

    For async usage, use the async variant:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from praisonai.integration.gateway_host import run_integrated_gateway_async

    await run_integrated_gateway_async(
        port=8765,
        host="127.0.0.1",
        title="Gateway App"
    )
    ```
  </Accordion>
</AccordionGroup>

***

## Legacy Mode

<Warning>
  Set `PRAISONAI_HOST_LEGACY=1` to use callback-only mode without provider wiring. This skips automatic backend integration.
</Warning>

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
export PRAISONAI_HOST_LEGACY=1
```

In legacy mode, only `@aiui.reply` callbacks work - no automatic agent integration.

***

## Common Patterns

### Pattern B: In-Process Host

Embed the UI in your existing application:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.integration import build_host_app
from fastapi import FastAPI

# Your existing app
main_app = FastAPI()

# Create agent UI
agent_ui = build_host_app(
    title="Agent Dashboard",
    pages=["chat", "sessions"]
)

# Mount as subapp
main_app.mount("/agents", agent_ui)
```

### Pattern C via CLI

Use the integrated UI-Gateway command for quick setup:

```bash theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
# Basic UI-Gateway
praisonai serve ui-gateway

# With custom settings
praisonai serve ui-gateway --style chat --title "My App" --port 8765

# With agents file
praisonai serve ui-gateway --agents agents.yaml --style dashboard
```

### Pattern C: Integrated Gateway

Single process serving UI + API + WebSocket:

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

run_integrated_gateway(
    port=8765,
    host="0.0.0.0", 
    title="Agent Gateway",
    style="dashboard",
    agents=[{"name": "Assistant", "llm": "gpt-4o"}]
)
```

### Custom Bridges

Wire your own backend services:

```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
from praisonai.integration import configure_host, setup_bridges

configure_host(title="Custom App")
setup_bridges()  # Auto-wire available bridges

# Or set custom backends
import praisonaiui.backends as backends
backends.set_backend("usage_sink", my_custom_sink)
```

<Note>
  Bridge failures are now logged as warnings for non-ImportError exceptions (previously debug level). This improves visibility when optional services fail to initialize.
</Note>

***

## Best Practices

<AccordionGroup>
  <Accordion title="Environment Configuration">
    Use environment variables for configuration that changes between deployments:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    configure_host(
        title=os.getenv("APP_TITLE", "PraisonAI"),
        agents=[{
            "llm": os.getenv("PRAISONAI_MODEL", "gpt-4o-mini")
        }]
    )
    ```
  </Accordion>

  <Accordion title="Error Handling">
    Handle import errors gracefully for optional features:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    try:
        from praisonai.integration import build_host_app
        app = build_host_app()
    except ImportError:
        # Fallback for environments without UI
        from fastapi import FastAPI
        app = FastAPI()
    ```
  </Accordion>

  <Accordion title="Resource Cleanup">
    Use context managers for proper cleanup in long-running applications:

    ```python theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
    from contextlib import asynccontextmanager

    @asynccontextmanager
    async def lifespan(app):
        # Startup
        setup_bridges()
        yield
        # Cleanup - bridges handle themselves

    app = build_host_app()
    app.router.lifespan_context = lifespan
    ```
  </Accordion>
</AccordionGroup>

***

## Related

<CardGroup cols={2}>
  <Card title="Integration Patterns" icon="diagram-project" href="/docs/features/integration-patterns">
    Compare Pattern B vs C vs D
  </Card>

  <Card title="Backend Injection" icon="arrows-right-left" href="/docs/features/aiui-backends">
    Custom backend services
  </Card>
</CardGroup>
