TECHNOLOGIESTieInn Technologies

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 .env file 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 →

Questions

Open in Code Lab5 free questions
5 questions

    Your first API call: keys, messages, roles and the response

  1. Question 1easy

    Where should your Gemini API key live in a project you'll push to GitHub?

  2. Your first API call: keys, messages, roles and the response

  3. Question 2easy

    response = client.models.generate_content(...). Which attribute holds the model's answer as a string?

  4. Your first API call: keys, messages, roles and the response

  5. Question 3medium

    A response's finish reason is MAX_TOKENS. What does that mean?

  6. Your first API call: keys, messages, roles and the response

  7. 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"])
  8. Your first API call: keys, messages, roles and the response

  9. Question 5hard

    model fails once with a rate limit, then answers. Call model.generate(messages) up to 3 times, catching RateLimitError and trying again. Store the reply text in result and the number of attempts used in attempts.

    Store your answer in result.

5 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.