AutoGen Tutorial (TypeScript): building prompt templates for intermediate developers
This tutorial shows you how to build reusable prompt templates in AutoGen with TypeScript, then plug them into an agent workflow without hardcoding prompts everywhere. You need this when your team starts shipping multiple agents and you want consistent output, easier testing, and fewer prompt edits scattered across the codebase.
What You'll Need
- •Node.js 18+
- •A TypeScript project with
ts-nodeor a build step viatsc - •An OpenAI API key set as
OPENAI_API_KEY - •AutoGen for TypeScript installed:
- •
npm install @autogen-ai/autogen openai
- •
- •A
tsconfig.jsonthat supports modern ES modules - •Basic familiarity with AutoGen agents and message passing
Step-by-Step
- •Start by creating a small template helper instead of writing raw strings inline. The goal is to keep the prompt structure stable while allowing variables like role, domain, and output format to change per task.
type PromptVars = {
role: string;
domain: string;
task: string;
outputFormat: string;
};
export function buildPromptTemplate(vars: PromptVars): string {
return [
`You are a ${vars.role} working in ${vars.domain}.`,
`Task: ${vars.task}`,
`Output format: ${vars.outputFormat}`,
`Rules:`,
`- Be concise`,
`- Use numbered steps when helpful`,
`- Do not invent facts`,
].join("\n");
}
- •Next, wire that template into an AutoGen agent. This example uses a single assistant agent, but the same pattern works when you pass templated prompts into planner, critic, or domain-specific agents.
import { AssistantAgent } from "@autogen-ai/autogen";
import OpenAI from "openai";
import { buildPromptTemplate } from "./prompt-template.js";
const client = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
const agent = new AssistantAgent({
name: "template-agent",
modelClient: client,
});
const systemPrompt = buildPromptTemplate({
role: "claims analyst",
domain: "insurance operations",
task: "review the submitted claim summary and identify missing information",
outputFormat: "Return JSON with fields: missingFields, riskFlags, nextAction",
});
console.log(systemPrompt);
- •Now separate prompt construction from execution. In production, you want one function to build the prompt and another to send it so you can unit test the template without calling the model.
import { AssistantAgent } from "@autogen-ai/autogen";
import OpenAI from "openai";
import { buildPromptTemplate } from "./prompt-template.js";
async function main() {
const client = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const agent = new AssistantAgent({
name: "template-agent",
modelClient: client,
});
const systemPrompt = buildPromptTemplate({
role: "underwriter",
domain: "commercial lending",
task: "evaluate whether the borrower summary needs escalation",
outputFormat: "Return a short decision memo with recommendation and rationale.",
});
const result = await agent.run({
messages: [
{ role: "system", content: systemPrompt },
{
role: "user",
content:
"Borrower has two late payments in the last six months and recently changed industries.",
},
],
});
console.log(result.messages.at(-1)?.content);
}
main();
- •Add validation before rendering templates. Intermediate teams usually hit failures because a field is empty or malformed, so fail early instead of sending broken prompts to the model.
type PromptVars = {
role?: string;
domain?: string;
task?: string;
outputFormat?: string;
};
function assertPromptVars(vars: PromptVars): asserts vars is Required<PromptVars> {
for (const key of ["role", "domain", "task", "outputFormat"] as const) {
if (!vars[key] || vars[key]!.trim().length === 0) {
throw new Error(`Missing required prompt variable: ${key}`);
}
}
}
export function safeBuildPromptTemplate(vars: PromptVars): string {
assertPromptVars(vars);
return [
`You are a ${vars.role} working in ${vars.domain}.`,
`Task: ${vars.task}`,
`Output format: ${vars.outputFormat}`,
`Rules:`,
`- Be concise`,
`- Use numbered steps when helpful`,
`- Do not invent facts`,
].join("\n");
}
- •Finally, make templates reusable across different agent jobs by defining named prompt presets. This is the part that keeps your codebase maintainable when product wants three variants of the same workflow.
import { safeBuildPromptTemplate } from "./prompt-template.js";
const promptPresets = {
claimReview: safeBuildPromptTemplate({
role: "claims analyst",
domain: "insurance operations",
task: "review claim notes for missing evidence and suspicious patterns",
outputFormat:
"Return JSON with missingEvidence, suspiciousPatterns, and nextSteps.",
}),
underwritingMemo: safeBuildPromptTemplate({
role: "underwriter",
domain: "commercial insurance",
task: "summarize risk factors and recommend approve, review, or decline",
outputFormat:
"Return JSON with recommendation and three bullet-point reasons.",
}),
} as const;
console.log(promptPresets.claimReview);
console.log(promptPresets.underwritingMemo);
Testing It
Run the script once with a valid API key and confirm you get a response that follows the requested output format. Then change one template variable at a time, such as domain or outputFormat, and verify the response changes predictably.
For template testing without model calls, write plain TypeScript tests against buildPromptTemplate and assert on exact strings. That catches regressions when someone edits wording or removes a required rule.
If you use JSON outputs, validate them after generation with a schema library like Zod before passing results downstream. That matters in bank and insurance workflows where downstream services expect strict shapes.
Next Steps
- •Add Zod schemas for each prompt preset so your agent outputs are validated before use
- •Move templates into versioned files so product changes do not break old workflows
- •Build multi-agent flows where one agent generates from a template and another audits the result
Keep learning
- •The complete AI Agents Roadmap — my full 8-step breakdown
- •Free: The AI Agent Starter Kit — PDF checklist + starter code
- •Work with me — I build AI for banks and insurance companies
By Cyprian Aarons, AI Consultant at Topiax.
Want the complete 8-step roadmap?
Grab the free AI Agent Starter Kit — architecture templates, compliance checklists, and a 7-email deep-dive course.
Get the Starter Kit