How to Build a customer support Agent Using AutoGen in TypeScript for payments
A customer support agent for payments handles the repetitive, high-volume questions that hit your support queue every day: failed card charges, refund status, chargeback timelines, and payment method verification. It matters because payments support is not generic support — every answer has compliance, auditability, and customer trust implications.
Architecture
- •
User-facing API layer
- •Receives support requests from chat, email, or an internal console.
- •Normalizes the input into a structured ticket object.
- •
AutoGen agent
- •Uses
AssistantAgentto classify the issue, gather missing details, and draft a response. - •Stays constrained to support-only actions.
- •Uses
- •
Payments tools layer
- •Exposes narrow functions like
lookupTransaction,getRefundStatus, andgetChargebackWindow. - •Keeps the model away from raw payment rails.
- •Exposes narrow functions like
- •
Policy/guardrail layer
- •Blocks sensitive data leakage.
- •Enforces PCI scope boundaries and escalation rules.
- •
Audit/logging layer
- •Stores prompts, tool calls, outputs, and final decisions.
- •Needed for dispute handling and internal review.
- •
Human escalation path
- •Routes ambiguous or high-risk cases to a human agent.
- •Required for refunds above thresholds, fraud indicators, or identity mismatches.
Implementation
1) Install AutoGen and define the payment support contract
Use the TypeScript package that exposes AssistantAgent and the OpenAI client integration. Keep your tools small and deterministic; this agent should explain status, not move money.
npm install @autogenai/autogen openai zod
import { z } from "zod";
export const SupportTicketSchema = z.object({
customerId: z.string(),
issueType: z.enum(["card_failed", "refund_status", "chargeback", "payment_method"]),
transactionId: z.string().optional(),
message: z.string(),
});
export type SupportTicket = z.infer<typeof SupportTicketSchema>;
export type PaymentLookupResult = {
transactionId: string;
status: "succeeded" | "failed" | "pending";
amount: number;
currency: string;
last4?: string;
};
2) Implement narrow payment tools
These functions should call your internal payments services or read-only database views. Do not expose raw PANs, CVVs, or full bank account numbers to the agent.
export async function lookupTransaction(transactionId: string): Promise<PaymentLookupResult> {
// Replace with your real payments service call.
return {
transactionId,
status: "failed",
amount: 4999,
currency: "USD",
last4: "4242",
};
}
export async function getRefundStatus(transactionId: string): Promise<string> {
return `Refund for ${transactionId} is pending settlement and usually completes in 5-10 business days.`;
}
export async function getChargebackWindow(countryCode: string): Promise<string> {
if (countryCode === "US") return "Card chargebacks can typically be initiated within 120 days.";
return "Chargeback windows vary by issuer and region.";
}
3) Create the AutoGen assistant with function calling enabled
This is the core pattern. The assistant gets a strict system prompt, a small toolset, and an output path that can be audited. Use temperature low enough to keep responses stable.
import { OpenAIChatCompletionClient } from "@autogenai/autogen";
import { AssistantAgent } from "@autogenai/autogen";
import { lookupTransaction, getRefundStatus, getChargebackWindow } from "./tools";
const modelClient = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
});
const paymentSupportAgent = new AssistantAgent({
name: "payment_support_agent",
modelClient,
systemMessage: `
You are a customer support agent for payments.
Rules:
- Never request or store full card numbers, CVV, PINs, or bank login credentials.
- Only use provided tools for transaction/refund/chargeback questions.
- If fraud is suspected or identity is unclear, escalate to a human.
- Keep answers concise, factual, and auditable.
`,
});
paymentSupportAgent.registerFunction(
{
name: "lookupTransaction",
description: "Look up a payment transaction by ID.",
parameters: {
type: "object",
properties: {
transactionId: { type: "string" },
},
required: ["transactionId"],
additionalProperties: false,
},
execute: async ({ transactionId }: { transactionId: string }) => lookupTransaction(transactionId),
}
);
paymentSupportAgent.registerFunction(
{
name: "getRefundStatus",
description: "Get refund status for a transaction.",
parameters: {
type: "object",
properties: {
transactionId: { type: "string" },
},
required: ["transactionId"],
additionalProperties: false,
},
execute: async ({ transactionId }: { transactionId: string }) => getRefundStatus(transactionId),
}
);
paymentSupportAgent.registerFunction(
{
name: "getChargebackWindow",
description: "Get chargeback timeline by country code.",
parameters: {
type: "object",
properties: {
countryCode": { type": "string" }
},
required": ["countryCode"],
additionalProperties": false
},
execute": async ({ countryCode }: { countryCode": string }) => getChargebackWindow(countryCode),
);
4) Run a support turn and return an auditable response
The agent should produce a response that your backend can log alongside ticket metadata. In production, persist the transcript and tool calls before sending the reply to the customer.
import { SupportTicketSchema } from "./schema";
async function handleSupportRequest(input: unknown) {
const ticket = SupportTicketSchema.parse(input);
const prompt = `
Customer message:
${ticket.message}
Known context:
customerId=${ticket.customerId}
issueType=${ticket.issueType}
transactionId=${ticket.transactionId ?? "missing"}
`;
import { OpenAIChatCompletionClient } from "@autogenai/autogen";
import { AssistantAgent } from "@autogenai/autogen";
const result = await paymentSupportAgent.run(prompt);
return {
responseText:
result.messages[result.messages.length -1]?.content ??
"No response generated",
ticket,
};
}
If you need stricter orchestration across classification + resolution + escalation, wrap this agent in a small workflow service. Keep one path for normal cases and one path that creates a human handoff record when risk flags are present.
Production Considerations
- •
Data residency
- •Keep transcripts and tool logs in-region if you process EU or UK customers.
- •Make sure your model endpoint region matches your storage policy.
- •
Compliance boundaries
- •Do not let the agent collect PANs or authentication secrets.
- •Mask identifiers in logs before persistence.
- •Treat anything involving disputes or fraud as regulated workflow data.
- •
Monitoring
- •Track tool-call rate, escalation rate, hallucination rate, and average resolution time.
- •Alert on repeated requests for sensitive fields or unsupported actions like “issue refund now.”
- •
Guardrails
- •Add allowlisted tools only.
- •Reject responses that mention full card details or promise irreversible actions without backend confirmation.
- •Require human approval for refunds above threshold amounts or chargeback advice that could be interpreted as legal guidance.
Common Pitfalls
- •
Letting the model infer too much from free text
- •Fix it by forcing structured inputs with Zod validation and explicit issue types.
- •Payments support gets messy fast when every ticket is treated as open-ended chat.
- •
Exposing write-capable payment actions to the agent
- •Don’t register tools that capture cards, create refunds directly, or change settlement state unless you have hard approval gates.
- •Start with read-only lookups plus escalation.
- •
Ignoring audit trails
- •Store prompt version, tool inputs/outputs, final answer, customer ID hash, timestamp, and operator overrides.
- •In disputes you need to explain exactly why the agent said what it said.
- •
Treating compliance as prompt text only
- •A system message is not a control boundary.
- •Enforce PCI scope reduction in code with redaction middleware, region-aware storage rules, and backend authorization checks before any tool executes.
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