---
title: "Agent"
description: "API reference for the Agent class"
---

The `Agent` class is an Actor-based stateful AI agent that maintains persistent memory, identity, and handles sequential message processing.

## Import

```python
from ai_query.agents import Agent
```

## Constructor

```python
Agent(
    id: str,
    *,
    model: LanguageModel | None = None,
    system: str = "You are a helpful assistant.",
    tools: ToolSet | None = None,
    storage: Storage | None = None,
    initial_state: StateT | None = None,
    stop_when: StopCondition | list[StopCondition] | None = None,
    provider_options: ProviderOptions | None = None,
)
```

### Typed State (Optional)

`Agent` supports **Pydantic** for typed state. To use it, subclass `Agent` and set `state_model`:

```python
class MyState(BaseModel):
    count: int = 0

class MyAgent(Agent[MyState]):
    state_model = MyState
```

### Parameters

<ParamField path="id" type="str" required>
  Unique identifier for this agent instance. Used as a key prefix for storage.
</ParamField>

<ParamField path="model" type="LanguageModel">
  The language model to use. Created with provider functions like
  `openai("gpt-4o")`.
</ParamField>

<ParamField path="storage" type="Storage">
  Storage backend for persistence. Defaults to `MemoryStorage()`.
</ParamField>

## Methods

### chat

```python
async def chat(
    self,
    message: str | list[ContentPart],
    *,
    signal: AbortSignal | None = None,
) -> str
```

Send a message and get a response. Automatically persists history.

### emit

```python
async def emit(self, event: str, data: dict[str, Any]) -> int
```

Emit an event to connected clients. Returns the unique event ID.
See the [Events Guide](/core/events) for a deep dive on persistence and replay.

### Parameters

<ParamField path="event" type="str" required>
  The type of event (e.g., "status", "chunk").
</ParamField>

<ParamField path="data" type="dict" required>
  The event payload.
</ParamField>

### call

```python
async def call(
    self,
    agent_id: str,
    method: str,
    *,
    timeout: float = 30.0,
    **kwargs: Any
) -> Any
```

Call another agent's method via the transport layer (requires `AgentServer`). This can be an `@action` or a legacy `on_call_*` handler.

### @action

```python
@action
async def my_action(self, param1: str) -> dict:
```

Decorator to mark a method as a callable RPC action. See the [Agent RPC & Actions](/core/agent-rpc) guide for details.

## Lifecycle Hooks

Override these methods in a subclass:

- `async def on_start(self)`
- `async def on_stop(self)`
- `async def on_connect(self, connection, ctx)`
- `async def on_message(self, connection, message)`
- `async def on_call_{method}(self, **kwargs)`
