The Chat Loop
the conversation loop
Part of: Persona Chatbot
You have the two ingredients: a persona string and a message list. Now wire them into the loop that turns them into a real conversation. This is the loop every chatbot runs on, and it's smaller than you'd think. One turn, end to end A single turn does five things in order: 1. Read the user's text. 2. Append it as a user turn to history. 3. Call the API with the same system prompt and the whole history. 4. Read the reply text off the response object. 5. Append it as an assistant turn, print it, and go back to step 1. Here's the real thing with the SDK: The invariant that keeps it alive The loop only works if you always append the assistant reply before the next user turn . Miss that append and you get two user turns in a row, which the API rejects, or worse, the model never sees its own last answer and repeats itself. The rule to burn in: every user append is eventually matched by an assistant append. History stays balanced, roles stay alternating. Reading the reply The response isn't a plain string. It's an object; the text lives at resp.content[0].text. Pull it out once, then work with the string. Storing the whole response object in history would break the next call, which expect
Challenge: Echo Loop