Express
02 Setup Anvia
Create a reusable Anvia agent module for Express.
Create provider clients and shared tools outside route handlers. Express routes should call an already configured agent.
1. Create src/ai/support-agent.ts
import { AgentBuilder, createTool } from "@anvia/core";
import { OpenAIClient } from "@anvia/openai";
import { z } from "zod";
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("OPENAI_API_KEY is required");
}
const client = new OpenAIClient({ apiKey });
export const model = client.completionModel("gpt-5.5");
const lookupPolicy = createTool({
name: "lookup_policy",
description: "Look up a support policy by key.",
input: z.object({
key: z.enum(["password_reset", "priority_support"]),
}),
output: z.object({
text: z.string(),
}),
async execute({ key }) {
const policies = {
password_reset: "Password reset links expire after 30 minutes.",
priority_support: "Enterprise customers receive priority support.",
};
return { text: policies[key] };
},
});
export const supportAgent = new AgentBuilder("support", model)
.name("Support Agent")
.instructions("Answer clearly. Use tools when policy detail is needed.")
.tool(lookupPolicy)
.defaultMaxTurns(3)
.build();2. Keep Route State Out Of The Agent
The shared agent can hold provider configuration and static tools. Request-local auth, database records, and retrieval results should be attached inside routes or route-specific tool factories.
3. Swap Providers Later
import { MistralClient } from "@anvia/mistral";
const client = new MistralClient({ apiKey: process.env.MISTRAL_API_KEY });
const model = client.completionModel("mistral-large-latest");Next
Expose the agent through an Express router in Route Handler. Related guides: Creating Agents and Tools.
