Agents
An agent is a model that calls your tools in a loop until the job is done. @meghjs/ai runs that loop on your queues, so it fits in a web app:
- No long requests.
agents.start()saves the run and returns its ID at once. The run happens on a worker. - Steps are saved. Each step (one model call, then the tool calls it asked for) is one queue job, and the run is saved after every step. If a worker dies, the job is retried and the run continues from the last saved step.
- No new rights. Tools run as the user who started the run, through the route's authentication,
@Authorized, validation and rate limits. An agent can only call the tools you list for it. - Hard limits. Model calls, tokens, time and tool calls are capped per run. A run that reaches a limit fails, with the limit's name as the reason.
Install
npm install @meghjs/ai @anthropic-ai/sdk # or: openaiThe provider SDK is only loaded when an agent first calls the model. Without it, the run fails with an error that names the package to install.
Define an agent
npx megh make:agent SupportTriage --tags orders,ticketsimport { Agent, MeghAgent } from "@meghjs/ai";
@Agent({
model: { provider: "anthropic", id: "claude-sonnet-5-5" },
system: "You triage support tickets. Look up the order before you answer.",
tools: { tags: ["orders", "tickets"] },
limits: { steps: 20, tokens: 200_000, duration: "15m", toolCalls: 50 },
queue: "agents",
})
export class SupportTriageAgent extends MeghAgent<{ ticketId: string }> {
// The first message of the run. Optional: by default a string input is sent
// as it is, and anything else as JSON.
prompt(input: { ticketId: string }) {
return `Triage ticket ${input.ticketId}.`;
}
}| Option | Meaning |
|---|---|
model | Required. { provider, id }, plus optional maxTokens per call (default 16 000), baseURL and apiKey. |
system | The system prompt. |
tools | Which @Tool routes the agent may call, by tags or names. Without it the agent has no tools. |
limits | steps (model calls, default 20), tokens (input plus output, default 200 000), duration (default '15m'), toolCalls (default 50). |
queue | The queue its steps run on. Default agents. |
name | The name in runs and logs. Defaults to the class name in kebab case: support-triage. |
attempts | Attempts per step, for provider errors and crashed workers. Default 3. |
Register your agents once:
app.useAgents([SupportTriageAgent]);The steps run on a queue like any other, so they use the queue transport you configured: memory in development, Redis or RabbitMQ in production. useAgents([...], { worker: false }) starts runs without running steps in this process.
Start a run
Inject AgentRunner and start a run from a controller, an event listener or a scheduled task:
import { AgentRunner } from "@meghjs/ai";
@Controller("/tickets")
export class TicketController {
constructor(private readonly agents: AgentRunner) {}
@Post("/:id/triage")
@Authorized()
async triage(@Param("id") id: string, @AuthUser() user: User) {
const run = await this.agents.start(SupportTriageAgent, { ticketId: id }, { user });
return { runId: run.id, status: run.status }; // "queued"
}
@Get("/runs/:runId")
@Authorized()
async run(@Param("runId") runId: string) {
return this.agents.get(runId); // status, steps, usage, output, error
}
}user defaults to the signed-in user of the current request. A run started from a task or listener has no user unless you pass one, so its tools run anonymously.
| Method | Does |
|---|---|
start(Agent, input, { user, model }) | Saves the run and queues its first step. model replaces the agent's model for this run. |
get(runId) | The run, or undefined. |
cancel(runId, { user }) | Stops the run. The call in progress finishes; nothing more runs. |
list({ agent, status, limit }) | Recent runs, newest first. |
A run has id, agent, status, input, output (the final answer), error, usage (inputTokens, outputTokens), steps, messages and toolCalls. Sending a run in a response leaves out the user.
The status is one of queued, running, succeeded, failed or cancelled. (waiting_approval and expired are reserved for approvals, which are coming later.)
How a run executes
- The model gets the system prompt, the conversation so far and the agent's tools.
- If it answers without tool calls, the run
succeededand itsoutputis the answer. - Otherwise each tool call runs through
tools.call(name, args, { user }): an HTTP request to the route, inside the process, as the run's user. A 403 or a validation error goes back to the model as a tool error, so it can try something else. The run doesn't crash. - The results are saved, and the next step is queued.
Each tool request carries an idempotency-key header (<runId>:<stepIndex>) that a route can use to ignore a repeated call.
Limits and failures
A failed run has error: { reason, message }. The reasons are:
reason | When |
|---|---|
steps, tokens, duration, toolCalls | The run reached that limit. There's no "one more step". |
approval | The model called a confirm: true tool. The message starts with "approval needed". |
interrupted | A worker died while a tool with side effects was running. It may have run, so it isn't run again. |
error | The model call kept failing (provider error, missing SDK) after every attempt. |
agent | The worker has no agent with the run's name (it isn't in useAgents). |
Approval isn't supported yet. A run that reaches a confirm: true tool fails with "approval needed", and the tool doesn't run. Waiting for a person to approve the call is coming in a later version. Until then, leave confirm tools out of an agent's tags, or give the agent read-only tools.
Crashes. Before a tool runs, its step is saved as started. If the worker dies there, the retried job runs a read-only (GET) tool again, and fails the run with interrupted for any other tool rather than risk a second refund or a second email.
Models
provider | Needs | Notes |
|---|---|---|
anthropic | @anthropic-ai/sdk | Messages API. Reads ANTHROPIC_API_KEY unless you set apiKey. |
openai | openai | Chat Completions. Reads OPENAI_API_KEY unless you set apiKey. |
For an OpenAI-compatible server, such as Ollama or vLLM, use openai with a baseURL:
@Agent({
model: { provider: "openai", id: "llama3.1", baseURL: "http://localhost:11434/v1", apiKey: "ollama" },
tools: { tags: ["orders"] },
})
export class LocalAgent extends MeghAgent<string> {}To use your own client (a proxy, custom retries) or another provider, pass an adapter by name. An adapter is an object with provider and generate(request):
import Anthropic from "@anthropic-ai/sdk";
import { AgentModel } from "@meghjs/ai";
app.useAgents([SupportTriageAgent], {
models: { anthropic: AgentModel.anthropic({ client: new Anthropic({ maxRetries: 4 }) }) },
});Where runs are kept
By default runs are kept in memory, in the process that started them. That works for development and tests, and for one process with the memory queue transport. With Redis or RabbitMQ, workers in other processes can't see those runs, so Megh logs a warning. Pass your own store, an object with create, get, update, saveStep, list and prune (see AgentRunStore):
app.useAgents([SupportTriageAgent], { store: new MyAgentRunStore() });A database store with migrations is coming later.
Testing
AgentModel.fake() answers every model call from a script, like Mailer.fake(): no network calls, and assertions on what happened. Run the queues in memory and wait for them:
import { setQueueTransport, waitForMemoryQueues, resetMemoryQueues } from "@meghjs/core";
import { AgentModel } from "@meghjs/ai";
beforeAll(() => setQueueTransport("memory"));
afterEach(() => {
AgentModel.restore();
resetMemoryQueues();
});
it("looks up the order", async () => {
const model = AgentModel.fake([
{ toolCalls: [{ name: "order_find", args: { id: "42" } }] },
{ text: "Order 42 shipped yesterday." },
]);
const run = await agents.start(SupportTriageAgent, { ticketId: "t1" }, { user });
await waitForMemoryQueues();
run.assertStatus("succeeded");
run.assertToolCalled("order_find", (args) => args.id === "42");
model.assertCalledTimes(2);
expect(model.requests[1].messages.at(-1)).toMatchObject({ role: "tool", isError: false });
});A scripted answer can also set usage (to test the token limit), delay (to test the duration limit) or error (to test retries). In the process that runs it, a run follows its own progress, so assertions after waitForMemoryQueues() see the final state. Elsewhere, call run.refresh() or agents.get(id).
Coming later
- Approval:
waiting_approval,agents.approve()andagents.reject(), and expiry. - A database store, with migrations and retention.
agents.stream(runId)over SSE and Socket.IO.megh agent:list.