NestJS
02 Setup Anvia
Create injectable Anvia services for NestJS.
In NestJS, wrap Anvia in services. Controllers should depend on methods like runSupport(...), not construct provider clients directly.
1. Create src/ai/support-agent.service.ts
import { Injectable } from "@nestjs/common";
import { AgentBuilder, createTool, type Agent } from "@anvia/core";
import { OpenAIClient } from "@anvia/openai";
import { z } from "zod";
@Injectable()
export class SupportAgentService {
private readonly agent: Agent;
constructor() {
const apiKey = process.env.OPENAI_API_KEY;
if (!apiKey) {
throw new Error("OPENAI_API_KEY is required");
}
const client = new OpenAIClient({ apiKey });
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] };
},
});
this.agent = new AgentBuilder("support", model)
.name("Support Agent")
.instructions("Answer clearly. Use tools when policy detail is needed.")
.tool(lookupPolicy)
.defaultMaxTurns(3)
.build();
}
async runSupport(message: string) {
return this.agent.prompt(message).send();
}
streamSupport(message: string) {
return this.agent.prompt(message).readableStream();
}
getAgent() {
return this.agent;
}
}2. Export The Service From A Module
import { Module } from "@nestjs/common";
import { SupportAgentService } from "./support-agent.service";
@Module({
providers: [SupportAgentService],
exports: [SupportAgentService],
})
export class AnviaModule {}3. Swap Providers Later
import { OpenAICompatibleClient } from "@anvia/openai";
const client = new OpenAICompatibleClient({
apiKey: process.env.OPENROUTER_API_KEY,
baseURL: "https://openrouter.ai/api/v1",
});Next
Expose the service through a controller in Route Handler. Related guides: Creating Agents and Tools.
