Your first API call: keys, messages, roles and the response
LLM Fundamentals & Prompting · 10 questions
Short notes
Key idea
An API call sends messages to a model and gets a response back. You need an API key (kept secret), a model name, and the contents; the reply has the text plus usage details.
Syntax
from google import genai
client = genai.Client() # reads GEMINI_API_KEY from the environment
r = client.models.generate_content(
model="gemini-3.5-flash-lite",
contents="In one sentence, what is a refund?",
)
print(r.text)
print(r.usage_metadata) # tokens in and out
- Roles:
user(the person),model(earlier replies); a system instruction sets behaviour. - To continue a chat, send the whole history as a list of contents.
Example
Ask for a one-line refund definition, print r.text, then check usage_metadata to see how many tokens it cost. Run it twice: the wording differs because generation involves sampling.
Traps
- Never put the key in code or Git. Use an environment variable or a
.envfile listed in.gitignore. - The model doesn't remember the last call; resend history.
- Calls can fail (rate limits, timeouts); handle errors.
- Model names change; keep the name in one constant.
Want the full lesson with step-by-step examples, a project and a certificate? LLM Fundamentals & Prompting course, ₹180 →
- Question 1easy
Where should your Gemini API key live in a project you'll push to GitHub?
- Question 2easy
response = client.models.generate_content(...). Which attribute holds the model's answer as a string? - Question 3medium
A response's finish reason is MAX_TOKENS. What does that mean?
- Question 4easy
The practice model counts one token per word and punctuation mark. What does this print?
from practice_llm import ScriptedModel model = ScriptedModel(["Order 57 has shipped."]) reply = model.generate([{"role": "user", "content": "Where is order 57?"}]) print(reply.usage["output_tokens"]) - Question 5hard
modelfails once with a rate limit, then answers. Callmodel.generate(messages)up to 3 times, catchingRateLimitErrorand trying again. Store the reply text inresultand the number of attempts used inattempts.Store your answer in
result.
Your first API call: keys, messages, roles and the response
Your first API call: keys, messages, roles and the response
Your first API call: keys, messages, roles and the response
Your first API call: keys, messages, roles and the response
Your first API call: keys, messages, roles and the response
5 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.