AutoGen Tutorial (TypeScript): persisting agent state for intermediate developers
This tutorial shows how to persist AutoGen agent state in TypeScript so a conversation can survive process restarts. You need this when you want agents to remember prior work across deployments, resume interrupted workflows, or keep long-running tasks from starting over.
What You'll Need
- •Node.js 18+ and npm
- •A TypeScript project with
tsconfig.json - •
@autogenai/autogeninstalled - •An OpenAI API key exported as
OPENAI_API_KEY - •Basic familiarity with AutoGen agents, model clients, and async/await
- •A writable folder for saving state files
Step-by-Step
- •Start by installing the package and setting up a minimal TypeScript project. If you already have a project, you only need the dependency and the environment variable.
npm install @autogenai/autogen
export OPENAI_API_KEY="your-api-key"
- •Create a simple assistant agent and give it a persistent storage path. The key idea is that you serialize agent state after each meaningful interaction, then reload it before continuing.
import { AssistantAgent, OpenAIChatCompletionClient } from "@autogenai/autogen";
import { readFile, writeFile } from "node:fs/promises";
const modelClient = new OpenAIChatCompletionClient({
model: "gpt-4o-mini",
});
const agent = new AssistantAgent({
name: "support_agent",
modelClient,
systemMessage: "You are a concise support assistant.",
});
- •Add helpers to save and load state from disk. AutoGen agents expose serializable state, which makes this pattern straightforward for file-backed persistence.
const STATE_FILE = "./support_agent.state.json";
async function saveAgentState() {
const state = await agent.saveState();
await writeFile(STATE_FILE, JSON.stringify(state, null, 2), "utf8");
}
async function loadAgentState() {
const raw = await readFile(STATE_FILE, "utf8");
const state = JSON.parse(raw);
await agent.loadState(state);
}
- •Run one interaction, save the state, then simulate a restart by creating a fresh agent instance and loading the saved file. This is the part that proves persistence is not just in-memory behavior.
async function main() {
const reply1 = await agent.run("I need help resetting my account password.");
console.log("First reply:", reply1.messages.at(-1)?.content);
await saveAgentState();
const restartedAgent = new AssistantAgent({
name: "support_agent",
modelClient,
systemMessage: "You are a concise support assistant.",
});
const raw = await readFile(STATE_FILE, "utf8");
await restartedAgent.loadState(JSON.parse(raw));
const reply2 = await restartedAgent.run("What did I ask you earlier?");
console.log("Second reply:", reply2.messages.at(-1)?.content);
}
main().catch(console.error);
- •If your workflow uses multi-turn conversations, persist after each turn instead of waiting until the end. That reduces data loss if the process crashes mid-task.
async function chatTurn(input: string) {
const result = await agent.run(input);
await saveAgentState();
return result.messages.at(-1)?.content;
}
async function demoTurns() {
console.log(await chatTurn("Track my refund request."));
console.log(await chatTurn("Add that I contacted support yesterday."));
}
- •In production, keep state scoped per user or per case ID rather than one global file. That avoids cross-user contamination and makes recovery deterministic.
import { mkdir } from "node:fs/promises";
async function getStatePath(caseId: string) {
await mkdir("./agent-state", { recursive: true });
return `./agent-state/${caseId}.json`;
}
Testing It
Run the script once and confirm it writes a JSON file to disk. Then stop the process, rerun it, and verify the second agent instance continues from the saved conversation instead of starting fresh.
If the response to “What did I ask you earlier?” reflects prior context, persistence is working. If not, check that you are calling saveState() after the turn and loadState() before any new message is sent.
For a stricter test, delete the in-memory agent object entirely between turns and only rely on the serialized file. That catches bugs where state appears to work only because your process never actually restarted.
Next Steps
- •Persist conversation metadata alongside agent state, such as case ID, tenant ID, and timestamps.
- •Move from local files to durable storage like PostgreSQL or Redis for multi-instance deployments.
- •Extend this pattern to group chats or tool-using agents so both memory and workflow progress survive restarts.
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