New cohort: Agentic AI & LLM Engineering remote internship. Limited seats.Apply now
Lesson 06 of 21 25 minFree

Building Text Generation Applications

Turn prompts into a real app: call an LLM API from Python, control it with temperature, max_tokens and streaming, and build a worksheet generator.

By the end of this lesson you will be able to:

  • Explain what happens between your code and the model when you call an LLM API.
  • Write a Python request with the right settings: model, messages, temperature, max_tokens and stream.
  • Build prompt templates that turn user input into reliable output.
  • Handle the response safely, including cut-off answers and streamed tokens.

From chatting with AI to building with AI

So far you have written prompts by hand. A text generation application does the same thing from code: it takes input from a user or a database, wraps it in a well-engineered prompt, sends it to a model through an API, and uses the reply inside a product.

Our study-buddy startup wants its first real feature: a worksheet generator. A teacher picks a subject, a class and a topic. The app returns 5 practice questions with answers, ready to print. No chat window, just a form and a result. That's a text generation app.

What happens when you call the API

Your request travels to the provider's servers. There, the model turns your messages into tokens and runs them through dozens of Transformer layers. It produces scores for the next token, picks one, and repeats until it hits a stop condition. Watch it happen below, one token at a time.

Simplified on purpose: real models have billions of connections and look at every earlier token at once (called attention). The idea is the same: tokens in, scores out, one token at a time.

Your first API call

Most providers (OpenAI, Azure OpenAI, and many others that copy the same format) accept a request with a model name and a list of messages. Here is the pattern in Python with the official openai library. Run this on your own computer after pip install openai and setting your API key as an environment variable. Never paste a key directly into your code.

import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])   # key comes from the environment

response = client.chat.completions.create(
    model="gpt-4o-mini",          # use any chat model your account has
    temperature=0.3,
    max_tokens=400,
    messages=[
        {"role": "system", "content": "You create school worksheets for Indian teachers."},
        {"role": "user", "content": "5 questions on fractions for Class 5, with answers."},
    ],
)
print(response.choices[0].message.content)

For Azure OpenAI the code is almost identical: create an AzureOpenAI client with your endpoint and API version, and use your deployment name as the model. The messages and settings don't change.

The settings that matter

Change the settings below and send the request. Watch how the JSON changes, how the reply streams in, and what happens when max_tokens is too small.

  • model: which model answers. Start with a smaller, cheaper one and upgrade only if quality isn't good enough.
  • messages: the system message (rules) plus the user message (the request), as in Lesson 4.
  • temperature: low (0–0.3) for worksheets, facts and JSON. Higher for stories and brainstorming.
  • max_tokens: the maximum length of the reply, which also caps the cost. Too small and the answer stops mid-sentence. The API tells you this happened with finish_reason = "length".
  • stream: send tokens as they are generated instead of all at the end. The total time is the same, but users see words appear immediately, which feels much faster.
  • stop: text that ends generation early, for example "\n\n" to get just one paragraph.

Prompt templates: the heart of the app

The teacher fills in three fields. Your code turns them into a full, engineered prompt. This is where Lessons 4 and 5 pay off:

TEMPLATE = """Create a worksheet for Class {grade} {subject} on "{topic}".
- Exactly {n} questions, increasing in difficulty.
- Use Indian names, places and rupees in word problems.
- After the questions, add an "Answer key" section.
Reply ONLY with JSON: {{"questions": [{{"q": str, "answer": str}}]}}"""

prompt = TEMPLATE.format(grade=5, subject="Maths", topic="Fractions", n=5)

Because the template asks for JSON, your app can lay the questions out nicely, print the answer key on a separate page, or save the worksheet to a database.

Good template habits: validate inputs before you call the API (is "grade" really 1–12?), keep the template in one place so you can improve it, log the prompt and response for debugging (without personal data), and set a low temperature so the same inputs give consistent worksheets.

Handling the response

  1. Check finish_reason: "stop" means a complete answer, while "length" means it was cut off. Retry with a larger max_tokens or ask for less.
  2. Parse and validate the content (Lesson 5): extract the JSON and check every field.
  3. Handle errors: network failures, rate limits (HTTP 429) and timeouts happen. Lesson 7 shows retries.
  4. Track usage: the response includes token counts. Log them so you know what each feature costs.

Hands-on

These exercises use a fake model so they run in your browser without an API key. The app code you write is exactly what you would use with a real API.

Your task: bad inputs waste money and cause errors. Complete build_request() so it raises a ValueError if grade isn't 1–12, and clamps max_tokens to the range 50–1000 (anything bigger becomes 1000). When both work, the last line is ✓ All checks passed.

def build_request(subject, grade, topic, max_tokens=400):
    # TODO 1: if grade is not between 1 and 12, raise ValueError("grade must be 1-12")
    # TODO 2: clamp max_tokens into the range 50..1000
    prompt = f"Create 5 questions for Class {grade} {subject} on {topic}, with answers."
    return {
        "model": "your-model-name",
        "temperature": 0.3,
        "max_tokens": max_tokens,
        "messages": [
            {"role": "system", "content": "You create school worksheets for Indian teachers."},
            {"role": "user", "content": prompt},
        ],
    }

req = build_request("Maths", 5, "Fractions")
print(f"Request OK: temperature={req['temperature']}, max_tokens={req['max_tokens']}")
print("Clamped:", build_request("Maths", 5, "Fractions", max_tokens=99999)["max_tokens"])
ok = build_request("Maths", 5, "Fractions", max_tokens=99999)["max_tokens"] == 1000
try:
    build_request("Maths", 15, "Fractions")
    print("Problem: grade 15 was accepted!")
    ok = False
except ValueError as err:
    print("Rejected bad input:", err)
print("✓ All checks passed" if ok else "Not yet: check both TODOs")
Show solution
    if not 1 <= grade <= 12:
        raise ValueError("grade must be 1-12")
    max_tokens = max(50, min(1000, max_tokens))

Your task: a streamed reply arrives as small chunks. The last chunk carries a finish_reason. Join the chunks into the full text, then print Answer was cut off if the finish reason is "length", or Answer complete if it's "stop".

import time

chunks = [
    {"delta": "Q1. Riya ate 2/8 of a pizza"},
    {"delta": " and Aman ate 3/8."},
    {"delta": " What fraction is left?"},
    {"delta": "\nQ2. Which is bigger, 3/4 or", "finish_reason": "length"},
]

full_text = ""
for chunk in chunks:
    print(chunk["delta"], end="", flush=True)   # what the user sees appear
    time.sleep(0.2)
    full_text += chunk["delta"]
print("\n---")

finish_reason = chunks[-1].get("finish_reason")
# TODO: print "Answer was cut off" when finish_reason == "length", else "Answer complete"
Show solution
if finish_reason == "length":
    print("Answer was cut off")
else:
    print("Answer complete")

Check your understanding

Your worksheet reply ends mid-question with finish_reason: "length". What happened?

  1. The model crashed
  2. The temperature was too high
  3. max_tokens was too small for the answer
  4. The API key is wrong

"length" means generation stopped because it reached max_tokens. Raise the limit or ask for less.

Why do chat apps usually turn on stream?

  1. It makes the model smarter
  2. Users see words immediately, so it feels faster
  3. It's cheaper per token
  4. It removes the need for max_tokens

Streaming doesn't change quality or price. It shows tokens as they're generated, which greatly improves how fast the app feels.

Where should your API key live?

  1. In an environment variable or secret store, never in the code
  2. Hard-coded at the top of the script
  3. In the system message
  4. In a public GitHub repo for safekeeping

Keys in code end up in git history and screenshots. Load them from the environment or a secrets manager.

Key takeaways

  • A text generation app = input → prompt template → API call → validated output.
  • Know your settings: model, messages, temperature, max_tokens, stream and stop.
  • Validate inputs before calling, and check finish_reason and the content after.
  • Keep API keys out of your code.

Next: chat applications, where the app has to remember the conversation.

Your progress is saved in this browser.

Adapted from Lesson 6 of Microsoft's "Generative AI for Beginners" (MIT License), rewritten and extended by Aiprojects4U. View source