---
question: How do I write an agent class in a module?
kind: task
via_web: available
via_cli: available
via_python: available
via_api: available
via_config: na
ref_web: Settings › Agents
ref_cli: abi new agent
ref_python: IntentAgent
ref_api: POST /api/agents/
prereq: The CLI and Python steps need a module of your project. No module yet? See [Creating a Module](/capabilities/build/modules/creating-a-module).
next:
  - /capabilities/build/agents/give-it-tools
  - /capabilities/build/agents/enable-in-a-workspace
  - /capabilities/build/agents/test-an-agent
---

# Create an agent

An agent binds a chat model to a system prompt and to the tools it can call. In a module, an agent is an SDK `IntentAgent` (`naas_abi_sdk.agents`), built by an async `create_agent(...)` function. The module declares it with an `AgentDescriptor` and binds it when it starts, and discovery publishes it: Nexus lists it while the module runs.

A Nexus workspace can also hold agents of its own: a name, a system prompt and a model, stored in the workspace. The Web UI and the REST API create those. They have no tools. For tools, write the agent in a module with the CLI or Python.

## Web UI

This creates a workspace agent. It does not write a class.

### Open the agent list

In the workspace, open Settings, then Agents.

### Add the agent

Click **Add Agent**. Fill in **Name** (required), **Icon**, **Description** and **System Prompt**, then click **Add Agent**.

![Workspace Settings on Agents: the Add New Agent form](/abi/Screenshot_Add_Agent.png)

*Settings › Agents › Add Agent: name, icon, description and system prompt.*

### Turn it on

The new agent starts off. Check **Enabled** on its row: see [Enable in a workspace](/capabilities/build/agents/enable-in-a-workspace).

### Set its model

Click the row to open **Edit Agent**, fill in **Model ID** with the provider's own model id (for OpenRouter, `google/gemma-4-26b-a4b-it`), then click **Save**. See [Edit prompt & model](/capabilities/build/agents/edit-prompt-and-model).

:::note Which provider answers
A workspace agent answers through the provider stored on its record (`openrouter`, `openai`, `anthropic`, `mistral`, `google` or `xai`), with that provider's key from Settings › Secrets (`OPENROUTER_API_KEY`, ...). The form and **Save** do not store a provider: set `provider` when you create the agent with the REST API. Without one, the chat falls back to a local Ollama server when one runs.
:::

## CLI

### Scaffold the agent

From the module's folder:

```bash
cd src/research
abi new agent Reviewer agents
```

It writes `agents/ReviewerAgent.py`, an SDK agent, and prints how to publish it. The arguments are `<name> [path]`; the path defaults to the current directory. `abi new module` already scaffolds a first agent, named after the module. The command is [`abi new agent`](/user-guide/reference/cli#abi-new-agent).

### Publish it

Declare the agent in `ABIModule.agents` and bind it in `on_initialized`, as in the Python steps. Then restart the module:

```bash
abi dev down --service research
abi dev up -d --service research
abi dev logs research -f    # "... READY: registered in discovery"
```

Once the module is `READY`, the agent shows in Settings › Agents and in the chat's agent picker. `abi chat` cannot open it: it opens the agents the engine loads itself. Chat with it in Nexus: see [Chat with an agent](/capabilities/build/agents/chat-with-an-agent).

## Python

### Write the agent

`abi new agent` writes a module-level `create_agent` that asks the engine for its models over NATS and keeps the agent's conversations in the engine's Document Service:

```python title="agents/ReviewerAgent.py"
from __future__ import annotations

from typing import Any

from naas_abi_sdk.agents import AgentConfiguration, IntentAgent
from naas_abi_sdk.agents.hosting import agent_memory_id, document_memory

NAME = "Reviewer"
DESCRIPTION = "Reviews documents and answers questions about them."
SYSTEM_PROMPT = """<role>
You are Reviewer, a careful reviewer.
</role>

<objective>
Help the user review their documents.
</objective>

<constraints>
- Answer briefly and factually.
- Say so when you do not know.
</constraints>
"""


async def create_agent(
    engine: Any, module_id: str, *, chat_model: str = "", tools: list[Any] | None = None
) -> IntentAgent:
    registry = engine.services.model_registry
    chat = await (
        registry.get_chat_model(chat_model)
        if chat_model
        else registry.get_default_chat_model()
    )
    embeddings = await registry.get_default_embedding_model()
    return IntentAgent(
        name=NAME,
        description=DESCRIPTION,
        chat_model=chat.model,
        embedding_model=embeddings.model,
        tools=tools or [],
        memory=await document_memory(
            engine.services.document, agent_memory_id(module_id, NAME)
        ),
        configuration=AgentConfiguration(system_prompt=SYSTEM_PROMPT),
    )
```

`engine` is the module's `self.engine`. The model is the engine's default chat model (`services.model_registry.default_chat_model` in `config.yaml`), or the canonical id you pass as `chat_model`, such as `gemma-4-26b-a4b-it`. No provider key reaches the module. The agent needs the `naas-abi-sdk[agent]` extra.

### Declare and bind it

In the module's `__init__.py`, add an `AgentDescriptor` to `agents` and bind the agent in `on_initialized`. The module must declare the `model_registry` and `document` services:

```python title="src/research/__init__.py"
from naas_abi_sdk import AgentDescriptor, BaseModule, ModuleDependencies

from research.agents import ReviewerAgent

AGENT_INVOKE = ("agent.invoke.v1",)


class ABIModule(BaseModule[ResearchConfiguration]):
    dependencies = ModuleDependencies(services=("model_registry", "document", "triple_store"))
    agents = (
        AgentDescriptor(NAME, DESCRIPTION, capabilities=AGENT_INVOKE),
        AgentDescriptor(ReviewerAgent.NAME, ReviewerAgent.DESCRIPTION, capabilities=AGENT_INVOKE),
    )

    async def on_initialized(self) -> None:
        ...
        reviewer = await ReviewerAgent.create_agent(self.engine, MODULE_ID)
        self.expose_agent(ReviewerAgent.NAME, reviewer.as_handler())
```

`expose_agent` refuses a name that has no descriptor with the `agent.invoke.v1` capability. Bind every declared agent in `on_initialized`: the module becomes `READY` right after, and discovery then publishes its agents. Any object with an async `invoke(prompt, context)` (and optionally `stream_invoke`) can be exposed as an agent too.

### Restart the module

The module builds its agents once, when it starts. Restart it (`abi dev down --service research`, then `abi dev up -d --service research`) to publish the change.

## REST API

There is no HTTP call that writes an agent class. The Nexus API creates a workspace agent.

### Create a workspace agent

```http
POST /api/agents/
```

Body: `workspace_id` and `name`, plus optional `description`, `system_prompt`, `model_id`, `provider`, `logo_url` and `enabled` (off by default). Auth: a Nexus user session with access to the workspace.

### Turn it on

```http
PATCH /api/agents/{id}
```

Send `enabled: true`. Its prompt and model are on [Edit prompt & model](/capabilities/build/agents/edit-prompt-and-model).

A module's agent has no route of its own: reach it through the Nexus chat API (`POST /api/chat/stream`, selecting the agent by its id). See [Chat with an agent](/capabilities/build/agents/chat-with-an-agent?via=api).

## Config

Not applicable. `config.yaml` does not define an agent: the module declares it in its code. `config.yaml` sets [which agents a workspace shows](/capabilities/build/agents/enable-in-a-workspace?via=config).

## Routing with intents

An `IntentAgent` matches the user's message to intents with an embedding model and routes it to the tool the intent names, or answers it directly. Pass a list of `Intent` objects:

```python
from naas_abi_sdk.agents import Intent, IntentType

INTENTS = [
    Intent(
        intent_value="review a document",
        intent_type=IntentType.TOOL,        # TOOL, AGENT or RAW
        intent_target="review_document",    # the tool name
    ),
]

# in create_agent():
return IntentAgent(
    name=NAME,
    description=DESCRIPTION,
    chat_model=chat.model,
    embedding_model=embeddings.model,
    tools=tools or [],
    intents=INTENTS,
    memory=...,
    configuration=AgentConfiguration(system_prompt=SYSTEM_PROMPT),
)
```

A `RAW` intent answers with its `intent_target` text, without calling the model. An `AGENT` intent other than `call_model` falls back to the model: an agent in a module has no local sub-agents (see [Add sub-agents](/capabilities/build/agents/add-sub-agents)). The agent also gets a few default intents; `enable_default_intents=False` leaves them out.

## Tools

An agent takes its tools when it is built. Pass them to `create_agent`:

```python
# in on_initialized():
await self.build_processes()
tools = self.get_workflow_instance("customers_workflow").as_tools()
reviewer = await ReviewerAgent.create_agent(self.engine, MODULE_ID, tools=tools)
```

Workflows, pipelines, other modules' agents and any LangChain tool work: see [Give it tools](/capabilities/build/agents/give-it-tools).

## Persistent memory

`document_memory(engine.services.document, agent_memory_id(module_id, NAME))` checkpoints each conversation thread in the engine's Document Service. History survives restarts of the module and is shared by its replicas. The memory is keyed by the module id and the agent's name (`<module_id>.<name>.v1`): renaming either starts a new memory.

An agent built with `memory=None` keeps its threads in the process only, and loses them when the module restarts.
