Quick answer: Useful generative AI practice problems train the code around a language model: estimating tokens, filling prompt templates, trimming chat history, pulling JSON out of a reply, checking it, retrying failed calls, chunking documents, cosine similarity search, scoring a test set, estimating cost and running tool calls safely. The 12 problems below use plain Python, need no API key and come with worked solutions.
These generative AI practice problems focus on the part of an AI app that you write yourself. The model is a service you call. Everything before the call (the prompt, the context, the budget) and after it (parsing, checking, testing) is ordinary Python, and that is where most bugs live.
Every solution here runs offline. If you have not built a GenAI app before, read the generative AI tutorial first.
How to use these generative AI practice problems
Treat these generative AI problems and solutions as hands-on generative AI exercises, not reading material. Give each problem 15 to 20 minutes before you look at the answer. Then:
- Run the solution yourself.
- Add one input that might break it.
- Say in one sentence what would go wrong in a real app without this code.
Pro tip: Keep all your answers in one GitHub repository with a short note per problem. By the end you will have a small toolkit and a set of interview stories.
Level 1: Prompts and token budgets
1. Estimate tokens and check the budget
Models limit input by tokens, not characters. A rough rule for English is about four characters per token. Write a function that estimates tokens and says whether a prompt fits, keeping room for the reply.
def estimate_tokens(text):
return max(1, round(len(text) / 4))
def fits(prompt, max_input_tokens, reserve_for_reply=200):
return estimate_tokens(prompt) + reserve_for_reply <= max_input_tokens
note = "Placement drive on Friday. Bring two copies of your resume. " * 20
print(estimate_tokens(note)) # 300
print(fits(note, 400)) # False
print(fits(note, 1000)) # True
This is only an estimate. Telugu, Hindi and code often use more tokens per character. For exact counts, use the token counter your provider offers.
2. Fill a prompt template safely
A template with a missing value can silently send {reader} to the model. Raise a clear error instead.
import string
def fill_template(template, values):
needed = {name for _, name, _, _ in string.Formatter().parse(template) if name}
missing = sorted(needed - values.keys())
if missing:
raise ValueError(f"Missing values: {missing}")
return template.format(**values)
template = "Summarise this {doc_type} for a {reader} in {limit} words:\n{text}"
try:
fill_template(template, {"doc_type": "notice"})
except ValueError as err:
print(err) # Missing values: ['limit', 'reader', 'text']
string.Formatter().parse lists the field names in the template, so the check stays correct when someone edits the wording.
3. Trim chat history to fit
A chat app resends earlier messages each turn. Keep the system message and as many of the latest messages as fit.
def trim_history(messages, max_tokens):
def cost(m):
return max(1, round(len(m["content"]) / 4))
system, rest = messages[0], messages[1:]
kept = []
budget = max_tokens - cost(system)
for message in reversed(rest):
if cost(message) > budget:
break
kept.append(message)
budget -= cost(message)
return [system] + list(reversed(kept))
chat = [
{"role": "system", "content": "You answer questions about the hostel."},
{"role": "user", "content": "What time is dinner?" * 10},
{"role": "assistant", "content": "Dinner is from 7 to 9 pm." * 10},
{"role": "user", "content": "And breakfast?"},
]
for m in trim_history(chat, 80):
print(m["role"], "|", m["content"][:30])
Output:
system | You answer questions about the
assistant | Dinner is from 7 to 9 pm.Dinne
user | And breakfast?
The loop walks backwards so the newest messages win. Notice the kept assistant reply has lost the question it answered. A better version drops messages in user/assistant pairs, or summarises older turns.
Level 2: Handle the model's reply
4. Pull JSON out of a chatty reply
Models sometimes wrap JSON in text or code fences. Extract the object, or return None.
import json
import re
def extract_json(reply):
match = re.search(r"\{.*\}", reply, re.DOTALL)
if not match:
return None
try:
return json.loads(match.group(0))
except json.JSONDecodeError:
return None
reply = 'Here is the result:\n```json\n{"name": "Ravi", "branch": "ECE"}\n```'
print(extract_json(reply)) # {'name': 'Ravi', 'branch': 'ECE'}
print(extract_json("No JSON here")) # None
print(extract_json('{"name": "Ravi",}')) # None
re.DOTALL lets . match new lines. The trailing comma in the last case is invalid JSON, so the function refuses it rather than guessing.
5. Check the JSON against a schema
Parsing is not enough. Check required keys, types and unexpected keys.
SCHEMA = {"name": str, "cgpa": float, "skills": list}
def validate(data, schema):
errors = []
for key, expected in schema.items():
if key not in data:
errors.append(f"missing {key}")
elif not isinstance(data[key], expected):
errors.append(f"{key} should be {expected.__name__}")
for key in data.keys() - schema.keys():
errors.append(f"unexpected {key}")
return errors
print(validate({"name": "Sita", "cgpa": 8.1, "skills": ["Python"]}, SCHEMA)) # []
print(validate({"name": "Sita", "cgpa": "8.1", "age": 21}, SCHEMA))
# ['cgpa should be float', 'missing skills', 'unexpected age']
Edge case to think about: a CGPA of 8 is an int, so this check rejects it. Decide whether to accept (int, float). In real projects, libraries such as Pydantic do this work.
6. Retry a busy model with backoff
API calls fail now and then because of load or rate limits. Retry a few times, waiting longer each time, and give up cleanly.
import time
class TemporaryError(Exception):
pass
def call_with_retry(ask_model, prompt, tries=3, wait=0.5):
for attempt in range(1, tries + 1):
try:
return ask_model(prompt)
except TemporaryError:
if attempt == tries:
raise
time.sleep(wait * 2 ** (attempt - 1))
calls = {"count": 0}
def flaky_model(prompt):
calls["count"] += 1
if calls["count"] < 3:
raise TemporaryError("busy")
return "OK on try 3"
print(call_with_retry(flaky_model, "hello", wait=0.01)) # OK on try 3
print(calls["count"]) # 3
Retry only temporary errors. A bad request or a wrong API key will fail every time, so retrying it wastes time and money. Official SDKs usually have built-in retries; know what yours does before adding your own.
Level 3: Retrieval
7. Chunk a document by sentences
Before search, long documents are split into chunks. Keep whole sentences and cap each chunk's length.
import re
def chunk_sentences(text, max_words=12):
sentences = re.split(r"(?<=[.!?])\s+", text.strip())
chunks, current = [], []
for sentence in sentences:
words = sentence.split()
if current and len(current) + len(words) > max_words:
chunks.append(" ".join(current))
current = []
current.extend(words)
if current:
chunks.append(" ".join(current))
return chunks
doc = ("Fees can be paid in two parts. The first part is due at admission. "
"Hostel rooms are shared. Each room has two beds. Wi-Fi is free.")
for c in chunk_sentences(doc):
print(c)
Output:
Fees can be paid in two parts.
The first part is due at admission. Hostel rooms are shared.
Each room has two beds. Wi-Fi is free.
Real systems use chunks of a few hundred tokens. A single sentence longer than max_words still becomes one chunk here; handling it is a good extension.
8. Write cosine similarity
Embeddings are lists of numbers. Cosine similarity measures how closely two lists point in the same direction: 1 is the same direction, 0 is unrelated.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
if norm_a == 0 or norm_b == 0:
return 0.0
return round(dot / (norm_a * norm_b), 3)
print(cosine([1, 2, 0], [2, 4, 0])) # 1.0
print(cosine([1, 0, 0], [0, 1, 0])) # 0.0
print(cosine([1, 1, 0], [1, 0, 0])) # 0.707
The first pair has different lengths but the same direction, so the score is 1.0. The zero check avoids division by zero.
9. Return the top matches above a threshold
Using cosine from problem 8, return the best chunks for a query, but drop weak matches.
# toy 3-number "embeddings": [money, food, exams]
chunks = {
"Fees can be paid in two parts.": [0.9, 0.1, 0.0],
"The mess serves lunch at 1 pm.": [0.1, 0.9, 0.0],
"Mid exams start in week eight.": [0.0, 0.0, 1.0],
}
def top_k(query_vec, chunks, k=2, min_score=0.5):
scored = [(cosine(query_vec, vec), text) for text, vec in chunks.items()]
scored.sort(reverse=True)
return [(s, t) for s, t in scored[:k] if s >= min_score]
print(top_k([0.8, 0.2, 0.0], chunks))
# [(0.991, 'Fees can be paid in two parts.')]
The lunch chunk scores about 0.35, so the threshold removes it even though k=2. Without a threshold, weak chunks enter the prompt and the model may use them. Real embeddings have hundreds of numbers and come from an embedding model.
Level 4: Test, cost and tools
10. Score a test set
Each test lists words the reply must contain and words it must not contain.
def score(tests, app):
results = {"pass": 0, "fail": []}
for question, must_have, must_not_have in tests:
reply = app(question).lower()
ok = all(w.lower() in reply for w in must_have) and \
not any(w.lower() in reply for w in must_not_have)
if ok:
results["pass"] += 1
else:
results["fail"].append(question)
return results
tests = [
("Library fine?", ["rs 2"], []),
("Hostel curfew?", ["i do not know"], ["10 pm"]),
]
def app(question):
return {"Library fine?": "Rs 2 per day.",
"Hostel curfew?": "Curfew is 10 pm."}[question]
print(score(tests, app)) # {'pass': 1, 'fail': ['Hostel curfew?']}
The curfew test fails because the app invented a time that is not in its notes. "Must not contain" checks catch this kind of hallucination.
11. Estimate the monthly cost
Providers charge per million input and output tokens. Estimate a month's bill.
def monthly_cost(requests_per_day, input_tokens, output_tokens,
input_price_per_million, output_price_per_million, days=30):
per_request = (input_tokens * input_price_per_million +
output_tokens * output_price_per_million) / 1_000_000
return round(per_request * requests_per_day * days, 2)
# example prices in dollars per million tokens; check your provider's price page
print(monthly_cost(500, 1500, 300, 1.00, 4.00)) # 40.5
print(monthly_cost(500, 600, 300, 1.00, 4.00)) # 27.0
Cutting the prompt from 1,500 to 600 tokens lowers the bill by a third. Sending fewer, better chunks is often the cheapest fix.
12. Run a tool call safely
In tool calling, the model replies with the name of a function and its arguments. Your code decides whether to run it.
import json
def get_attendance(roll_no):
data = {"21A01": 82, "21A02": 68}
return data.get(roll_no)
TOOLS = {"get_attendance": get_attendance}
def run_tool_call(reply):
try:
call = json.loads(reply)
name, args = call["tool"], call["args"]
except (json.JSONDecodeError, KeyError, TypeError):
return "Error: bad tool call"
if name not in TOOLS:
return f"Error: unknown tool {name}"
if not isinstance(args, dict):
return "Error: args must be an object"
try:
return TOOLS[name](**args)
except TypeError:
return "Error: wrong arguments"
print(run_tool_call('{"tool": "get_attendance", "args": {"roll_no": "21A02"}}')) # 68
print(run_tool_call('{"tool": "delete_student", "args": {"roll_no": "21A02"}}'))
# Error: unknown tool delete_student
Only functions in the TOOLS allow-list can run. Never use eval on model output. Actions that change data, such as sending mail, should also ask a person to confirm.
Common mistake: Trusting a reply because it looks right. Problems 4, 5, 10 and 12 all exist because model output must be checked like user input.
Turn this generative AI coding practice into a project
| Project part | Problems |
|---|---|
| Prepare the prompt | 1, 2, 3 |
| Read and check the reply | 4, 5, 6 |
| Search your notes | 7, 8, 9 |
| Measure and plan | 10, 11 |
| Let the model use a tool | 12 |
Build a help bot over your college notices using these parts, then compare your design with the ideas in 12 generative AI projects. Revise the theory with generative AI interview questions. If Python itself slowed you down, go back to Python practice problems. The AI engineer roadmap shows what to learn next, and our artificial intelligence course guide explains how a full course covers these skills.
Frequently asked questions
Do I need an API key to solve these generative AI problems?
No. All 12 problems use plain Python and fake model functions. They practise the code you write around a model, which is where most bugs in real apps appear. You can connect a real model later by replacing one function.
What Python level do I need before starting?
You should be comfortable with functions, loops, lists, dictionaries, string methods and try/except. If those still feel slow, solve basic Python problems for two or three weeks first.
Are these questions asked in AI interviews?
The exact questions vary by company. Topics such as tokens and context limits, structured output, retries, embeddings and cosine similarity, retrieval, evaluation and cost come up often in generative AI interviews and take-home tasks for freshers.
How should I practise these problems?
Try each one for 15 to 20 minutes before reading the solution. Then run the solution, add one input that might break it and explain in one sentence why a real app needs that check.
What should I build after solving them?
Join several solutions into one small question-answering app over your own notes: chunk the notes, search them, build the prompt, check the reply and run a test set after every change.
Want a clear order for what to learn next? Follow the AI engineer roadmap, or book a free demo class to see how the Artificial Intelligence course builds these skills through projects.
