Build Your First Generative AI Application

A small, complete chat application with a system prompt, history and streaming, before adding retrieval.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 0 · Lesson 8 of 9 · Beginner

Build Your First Generative AI Application

A small, complete chat application with a system prompt, history and streaming, before adding retrieval.

Before adding retrieval, it helps to build a plain generative AI application and understand its moving parts: a system prompt, a conversation history, streaming output and error handling. In this lesson you build a small command-line chat assistant in about 40 lines. In the next modules you will give it knowledge by adding retrieval.

What you will learn

  • How a chat application keeps conversation history
  • How a system prompt shapes the assistant's behaviour
  • How to stream responses for a responsive user experience
  • Why this assistant still needs RAG to answer questions about your data

Prerequisites

How a chat application works

Language model APIs are stateless: the model remembers nothing between requests. A chat application creates the illusion of memory by sending the whole conversation so far with every new message:

  1. The user types a message; the app appends it to a messages list with role user.
  2. The app sends the system prompt and the full list to the model.
  3. The model's reply is shown and appended with role assistant.
  4. Repeat.

The complete application

chat_app.py
"""A minimal streaming chat assistant.  Run: python chat_app.py"""
from dotenv import load_dotenv
import anthropic

load_dotenv()
client = anthropic.Anthropic()          # reads ANTHROPIC_API_KEY
MODEL = "claude-opus-5-5"
SYSTEM = ("You are StudyBuddy, a friendly tutor for Python beginners. "
          "Explain simply, use short code examples, and ask a follow-up question "
          "when the student's question is unclear.")
MAX_TURNS = 20                          # keep the last 20 messages to limit cost

def reply(messages: list[dict]) -> str:
    with client.messages.stream(
        model=MODEL,
        max_tokens=2000,
        output_config={"effort": "low"},
        system=SYSTEM,
        messages=messages[-MAX_TURNS:],
    ) as stream:
        for text in stream.text_stream:
            print(text, end="", flush=True)
        final = stream.get_final_message()
    print()
    if final.stop_reason == "max_tokens":
        print("[The answer was cut off.]")
    return "".join(b.text for b in final.content if b.type == "text")

def main() -> None:
    messages: list[dict] = []
    print("StudyBuddy is ready. Type 'quit' to exit.")
    while True:
        user = input("\nYou: ").strip()
        if user.lower() in {"quit", "exit"}:
            break
        if not user:
            continue
        messages.append({"role": "user", "content": user})
        print("StudyBuddy: ", end="")
        try:
            answer = reply(messages)
        except anthropic.APIError as error:
            print(f"\n[Error talking to the model: {error}]")
            messages.pop()               # forget the failed turn
            continue
        messages.append({"role": "assistant", "content": answer})

if __name__ == "__main__":
    main()

Run it

python chat_app.py
StudyBuddy is ready. Type 'quit' to exit.

You: what is a list comprehension
StudyBuddy: A list comprehension is a short way to build a list from another sequence...
    squares = [n * n for n in range(5)]   # [0, 1, 4, 9, 16]
Would you like to see how to add a condition, like only even numbers?

You: yes please
StudyBuddy: Add an if at the end: evens = [n for n in range(10) if n % 2 == 0] ...

The second answer understands "yes please" because the history was sent along with it.

Explanation of the code

  • SYSTEM defines the assistant's role and style. Changing it changes the personality of the whole app.
  • messages[-MAX_TURNS:] keeps only recent history. Long histories cost more and are slower; production apps summarise older turns (Conversational RAG with Memory).
  • Streaming prints text as it arrives, so the user sees the answer start within moments.
  • Stop reason: max_tokens means the answer was cut off; the app tells the user.
  • Error handling: a failed request removes the unanswered user message, so the history stays consistent.

The limitation: it only knows what it learned

Ask StudyBuddy about your college's exam timetable or your company's leave policy, and it cannot know. It will either say so or, worse, guess. That is the problem RAG solves: retrieving the right documents and adding them to the prompt. Continue with What is RAG? and then Build a Minimal RAG System from Scratch.

Common errors and troubleshooting

  • Authentication error: the .env file is not in the folder you run the script from, or the key is wrong.
  • The assistant forgets earlier messages: check that the assistant's reply is appended to messages.
  • Error about roles: the first message must have role user, and roles should alternate.

Best practices

  • Keep the system prompt in one place and version it like code.
  • Limit history length and maximum output length to control cost.
  • Never put secrets or personal data in the system prompt.

Key takeaways

  • A chat app sends the system prompt and the full recent history on every request.
  • Streaming makes applications feel fast; always check the stop reason.
  • Without retrieval, the assistant only knows its training data, which is why RAG exists.

Frequently asked questions

Can I build this with OpenAI or a local model instead?

Yes. The structure is identical; only the API call changes. See the OpenAI API and Ollama lessons.

Why not keep the entire history forever?

Every token in the history is sent and billed on each request, and very long histories slow responses. Summaries or retrieval over past conversations scale better.

Practice exercises

  1. Add a /reset command that clears the history.
  2. Change the system prompt to create a strict SQL tutor that only answers SQL questions.
  3. Print the number of input and output tokens after each answer using final.usage.

Related tutorials