# Agent

> Define named, reusable personas with instructions, purpose, and metadata.

Source: https://maincode.com/docs/python-agent-sdk-agent
Section: Agent SDK · Matilda documentation

---

An `Agent` is a named, reusable persona with optional instructions, context, purpose, and metadata. You can pass a plain `dict` with the same keys anywhere an `Agent` is accepted — the SDK normalises it.

## `Agent` class

```python
from matilda_agent_sdk import Agent

reviewer = Agent(
    name="code-reviewer",
    purpose="code",
    instructions="Review code for correctness, security, and readability.",
    context="Project: matilda-core\nLanguage: Python",
    metadata={"team": "platform"},
)
```

The `Agent` is reusable — construct once, run many times.

### Constructor parameters

| Field | Type | Description |
| - | - | - |
| `name` | `str` | Agent name. Must be non-empty (raises ValueError otherwise). Required. |
| `instructions` | `AgentInstructions` | Static string or dynamic callable (see below). |
| `context` | `str \| None` | Additional context appended to instructions under a Context: header. |
| `purpose` | `AgentPurpose` | Controls the default response\_mode and how the server routes the request. Defaults to 'code'. |
| `response_mode` | `str \| None` | Override the response mode. If omitted, derived from purpose. |
| `metadata` | `dict` | Custom data available to dynamic instructions. Defaults to {}. |

## `AgentPurpose`

```python
AgentPurpose = Literal["code", "analysis", "general"]
```

| Purpose | `response_mode` default |
| - | - |
| `'code'` | `'auto'` |
| `'analysis'` | `'deep'` |
| `'general'` | `'auto'` |

## Dynamic instructions

Instructions can be a callable that receives a runtime context dict, letting you customise behaviour per-call (async callables are awaited):

```python
from matilda_agent_sdk import Agent, run


def reviewer_instructions(ctx):
    lang = ctx["metadata"].get("language", "auto-detect")
    strictness = ctx["metadata"].get("strictness", "normal")
    return "\n".join(
        [
            "Review the following code.",
            f"Language: {lang}",
            f"Strictness: {strictness}",
            "Focus on: correctness, security, and readability.",
        ]
    )


agent = Agent(name="code-reviewer", purpose="code", instructions=reviewer_instructions)


async def main():
    result = await run(
        agent,
        "def add(a, b): return a + b",
        metadata={"language": "Python", "strictness": "strict"},
    )
    print(result.final_output)
```

### `AgentInstructions`

```python
AgentInstructions = str | Callable[[dict], str | Awaitable[str]]
```

The context dict passed to the callable:

```python
{
    "agent_name": agent.name,
    "input": trimmed_prompt,
    "purpose": purpose,
    "metadata": merged_metadata,
}
```

## How agent messages are constructed

The SDK packs the agent's identity, instructions, context, and the user's prompt into a single user message with labelled sections:

```text
Agent: code-reviewer

Instructions:
Review the following code.
Language: Python
...

Context:
Project: matilda-core

Code task:
def add(a, b): return a + b
```

## `build_agent_chat_request(...)`

Low-level async builder that constructs the chat request dict without executing it. Useful for testing, logging, or custom execution paths.

```python
import asyncio

from matilda_agent_sdk import build_agent_chat_request


async def main():
    request = await build_agent_chat_request(
        prompt="Fix the failing test",
        agent={"name": "helper", "purpose": "code"},
        instructions="Be specific.",
        context="Project root: /repo",
        conversation_id="conv-1",
        file_ids=["file-1"],
        client_tools=[{"name": "read_file", "description": "Read a file", "parameters": {"type": "object"}}],
    )

    # request["messages"], request["responseMode"], request["conversation_id"], ...
```

### Parameters

| Field | Type | Description |
| - | - | - |
| `prompt` | `str` | The user's message. Required. |
| `agent` | `Agent \| dict \| None` | Optional agent to use. Defaults to a generic agent. |
| `purpose` | `AgentPurpose \| None` | Fallback purpose if agent doesn't specify one. |
| `instructions` | `AgentInstructions \| None` | Override the agent's instructions. |
| `context` | `str \| None` | Override the agent's context. |
| `metadata` | `dict \| None` | Merge with agent's metadata. |
| `conversation_id` | `str \| None` | Associate with a conversation thread. |
| `file_ids` | `list[str] \| None` | File IDs to attach. |
| `client_tools` | `list[dict] \| None` | Client tools to advertise. |
| `response_mode` | `str \| None` | Override response mode. |
| `response_schema` | `str \| None` | Raw JSON Schema string to constrain output. |
| `history` | `list[dict] \| None` | Prior-transcript messages replayed ahead of this turn. |

Returns a `dict` shaped like a chat request (`messages`, `responseMode`, optional `conversation_id` / `fileIds` / `clientTools` / `responseSchema`).
