Pick a depth. Each prompt opens in your AI pre-loaded with the lesson. Click a row to preview the prompt.
Generation has to stop somewhere, and how it stops is a serving concern with cost and correctness implications. The model stops on an end-of-sequence token, a max-token limit, or a custom stop string — and each has gotchas. A too-low max_tokens truncates answers mid-sentence (finish_reason: length); a missing stop sequence lets the model ramble (wasting tokens and money); a stop string that appears in legitimate output cuts answers short. Controlling stop conditions well is how you bound cost per request and avoid the truncation failures from the error taxonomy.
The demo shows the three stop mechanisms and the finish_reason that tells you which fired — essential for handling truncation (raise max_tokens or continue) vs. clean completion.
# --- Pick your provider (set the matching API key env var) ---
# Anthropic: from anthropic import Anthropic; client = Anthropic() # ANTHROPIC_API_KEY
# OpenAI: from openai import OpenAI; client = OpenAI() # OPENAI_API_KEY
# Gemini: from google import genai; client = genai.Client() # GEMINI_API_KEY
from anthropic import Anthropic
client = Anthropic()
r = client.messages.create(model="claude-sonnet-4-6", max_tokens=20, # deliberately tiny
messages=[{"role": "user", "content": "List 50 country capitals."}])
print("stop_reason:", r.stop_reason) # 'max_tokens' -> the answer was TRUNCATED
# Handle it: raise max_tokens, or continue generation, or tell the user it's partial.
r2 = client.messages.create(model="claude-sonnet-4-6", max_tokens=500,
stop_sequences=["\n\nEND"], # custom stop string
messages=[{"role": "user", "content": "Write a haiku then output \n\nEND"}])
print("stop_reason:", r2.stop_reason) # 'stop_sequence'python3 main.py