Back to Blog

Build AI Apps with Python: Multi-Turn Conversations — Chatbot with Memory | Episode 3

Celest KimCelest Kim

Video: Build AI Apps with Python: Multi-Turn Conversations — Chatbot with Memory | Episode 3 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build AI Apps with Python: Multi-Turn Conversations — Chatbot with Memory

In this tutorial, we build a Python chatbot that remembers previous messages by maintaining a conversation history. By storing both user and assistant messages in a list and sending the entire history with each API call, the chatbot can hold context across multiple turns without repeating information.

Code

import openai

# Initialize conversation history with system prompt
conversation_history = [
  {"role": "system", "content": "You are a helpful assistant."}
]

def chat():
  while True:
    user_input = input("User: ")
    if user_input.lower() in {"exit", "quit"}:
      print("Goodbye!")
      break

    # Append user message to conversation history
    conversation_history.append({"role": "user", "content": user_input})

    # Call the OpenAI API with full conversation history for context
    response = openai.ChatCompletion.create(
      model="claude-v1",
      messages=conversation_history
    )

    assistant_message = response.choices[0].message["content"]
    print("Assistant:", assistant_message)

    # Append assistant response to conversation history to maintain memory
    conversation_history.append({"role": "assistant", "content": assistant_message})

if __name__ == "__main__":
  chat()

Key Points

  • Store all user and assistant messages in a list to maintain conversation context.
  • Send the full conversation history with each API call to enable multi-turn memory.
  • Use a loop to interactively collect user input and respond dynamically.
  • Appending assistant responses to history is crucial for continuous context retention.
  • Exiting the chat gracefully allows for a smooth user experience.