Fastify

02 Setup Anvia

Create a reusable Anvia agent module for Fastify.

Create provider clients and shared agents outside Fastify route handlers. Register request-local tools inside routes.

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 The Fastify Instance Separate

The agent module should not import FastifyInstance. This keeps it reusable from routes, jobs, Studio, and tests.

3. Swap Providers Later

import { GeminiClient } from "@anvia/gemini";

const client = new GeminiClient({ apiKey: process.env.GEMINI_API_KEY });
const model = client.completionModel("gemini-2.5-pro");

Next

Expose the agent through a Fastify plugin in Route Handler. Related guides: Creating Agents and Tools.