Keep state out of the prompt: a state machine for a Telegram bot
Published · 3 min read
The last workflow in my n8n agent is a mentor. You tell it what you want to learn and your level. It drafts a plan of topics and concepts, waits for you to confirm, then sends one short lesson at a time, never repeating one, until the plan is done and it asks what's next.
That is a multi-step conversation, and the obvious way to build it is to describe all the steps in the system prompt and let conversation memory do the rest. It mostly works. "Mostly" is the problem.
Why memory alone isn't enough
Conversation memory is a window of recent messages. The model reads it and infers where the user is: did they confirm the plan, which lesson was last, is the plan finished? Every message, it re-derives that from text.
That inference can fail in small, annoying ways: sending the same lesson twice, treating "ok" as confirmation one day and not the next, losing the plan once enough messages have scrolled out of the window. None of these are prompt bugs you can fully fix, because the model is guessing at state that was never written down.
Write the state down
The fix is to keep the state explicitly, outside the model, and let code decide what happens next.
n8n gives every workflow a small persistent store, $getWorkflowStaticData('global'), which is
enough for a bot with a few users. Each chat gets an entry:
const storage = $getWorkflowStaticData('global');
const userId = input.chatId;
if (!storage[userId]) {
storage[userId] = {
step: 1, // 1 ask goal, 2 ask level, 3 plan ready, 4 sending lessons, 5 done
goal: '',
lessons: [],
current: 0,
};
}From there, each incoming message moves the user through explicit steps:
- Ask the goal. Store whatever they answer.
- Ask the level. Store it, then ask the model for a plan.
- Plan ready. Keep the topics, reset the lesson counter, ask for a "yes".
- Send lessons. On confirmation, send lesson
current, then increment it. A lesson can't repeat, because the counter only moves forward. - Done. Congratulate, ask what's next, and clear the user's entry.
// The bot speaks Russian: "да" means "yes".
if (user.step === 4 && userMsg === 'да') {
const lesson = user.lessons[user.current];
user.current++;
response = { action: 'send_lesson', message: `Lesson ${user.current}: ${lesson}` };
if (user.current >= user.lessons.length) user.step = 5;
}The model still does what it is good at: drafting the plan and writing each lesson, with Tavily web search so the material is current. It just no longer decides where the conversation is. That's an integer now.
Small things that matter
- Key everything by chat ID. Telegram gives you one per conversation; use it for both state and memory, or users will see each other's plans.
- Cap the store. Static data lives inside the workflow, so the code drops the oldest entry once there are more than fifty users. Crude, but it keeps the workflow from growing without bound.
- Make confirmations exact. The bot waits for a specific word. Fuzzy intent detection is a model job; "has this user said yes?" shouldn't be.
When to move on from static data
Static data is perfect for a personal bot. It isn't a database. It has no expiry, it is only as safe as the workflow itself, and it is shared by every execution. For more than a handful of users I'd move the same state shape into Postgres or Redis, with a TTL per user. The state machine itself doesn't change; only where it is saved.
A side note on tool calls
When I built this, the GigaChat 2 model behind n8n's OpenAI-compatible node couldn't make native
tool calls. The course material describes a workaround that's useful with any model in that
position: tell the model to answer with a plain-text instruction such as tavily(query="...")
instead of an answer, detect that pattern in a Code node, call the search API yourself with an HTTP
Request node, and pass the results to a second model call to write the reply. It's tool calling,
done by hand, and it's the same idea as everything above: let the model express intent, and let code
do the doing.
The takeaway
If a conversation has steps, the steps are state, and state belongs in code. Prompts are for language. Integers are for knowing which lesson comes next.