SproutStackSproutStack home

Making Your First LLM API Call

8 min readBeginner-friendlyFree to read

Read a little, play a little. No scary maths, and no rush.

Share:

Your first 20 lines of AI engineering

Everything in this track reduces to one loop: build messages, call the API, handle the reply. Let's run it for real — this is the same shape every chatbot, RAG system, and agent uses underneath.

import os
from openai import OpenAI

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
out = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "Be concise. Answer only from context."},
        {"role": "user", "content": "Summarize RAG in 2 lines."},
    ],
    temperature=0.2,
)
print(out.choices[0].message.content)

The three roles, explained like a play

  • system: the director's instructions — tone, rules, grounding contract. Users never see it; the model never forgets it (mostly).
  • user: the current line of dialogue — the actual ask.
  • assistant: previous replies, fed back in so multi-turn chats have memory (the API itself is stateless — you supply the history).

Keys live on servers, never in browsers

os.getenv("OPENAI_API_KEY") is the whole security story at this level: keys in server environment variables, never in frontend JavaScript, never committed to git. A leaked key means someone else's tokens on your bill — treat it like a password, because it is one.

What comes back

The response is more than the text. Three fields are worth checking on every call:

  • choices[0].message.content: the reply itself.
  • choices[0].finish_reason: why generation stopped. stop means the model finished naturally. length means it hit your token cap mid-thought, so the answer is cut off and should not be trusted as complete.
  • usage: how many tokens went in (prompt_tokens) and came out (completion_tokens). This is what you are billed for, so log it from day one.

A conversation in code

Because the API is stateless, a chat is just a list you keep growing and resending:

history = [{"role": "system", "content": "You are a friendly tutor."}]

def ask(text):
    history.append({"role": "user", "content": text})
    out = client.chat.completions.create(model="gpt-4o-mini", messages=history)
    reply = out.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

ask("What is a token?")
ask("Give me an example.")   # works because the first exchange is resent

The second question only makes sense because the first question and answer travel with it. Delete the history and the model has no idea what "an example" refers to.

When the first call fails

  • 401 Unauthorized: the key is missing or wrong. Check that the environment variable is set in the terminal you are running from.
  • 404 or "model not found": usually a typo in the model name, or a model your account cannot use.
  • 429 Too Many Requests: you hit a rate or spending limit. Wait and retry, or check your account's limits.
  • A long hang: no timeout was set and the network stalled. Set one.

Streaming: showing the answer as it is written

By default you wait for the whole reply before seeing any of it, which can take several seconds for a long answer. Passing stream=True makes the API send the reply in small pieces as the model generates them, and your code prints each piece as it arrives. The total time is about the same, but the user sees words within a fraction of a second instead of staring at a spinner. This is why chat interfaces appear to type. The trade-off is slightly more code: you assemble the full text yourself, and token usage arrives at the end of the stream rather than with the first piece.

Production manners (add these next)

Timeouts (don't hang forever), retries on 429/5xx with backoff, and logging token usage per call. Then tune temperature and top-p — the subject of our next chapter.

Remember this

  • Messages in, reply out; system directs, user asks, history is your job.
  • Keys server-side, always. Timeouts and retries before you ship.

Check your understanding

5 questions · first-try answers earn the most XP

1. Why does the chapter insist that an API key must never appear in frontend JavaScript?
2. What is the purpose of the system message in a chat request?
3. The chat completion API is described as stateless. What follows for multi-turn conversations?
4. Which three things should you add before this code runs in production?
5. Why does the chapter set a low temperature on a first LLM API call?

My notes

Saved in this browser. Highlight a line above and save it, or write it in your own words.

Nothing saved yet. Your highlights will live here.

References

Finished reading?

Ticking it here also ticks the chapter in the sidebar, the section count and your streak — it is all one number.

Related chapters

Spotted a mistake or want a topic covered? Report an issue

📬 An occasional email when new lessons land

New lessons and showdowns, no more than a few times a month. No spam, unsubscribe anytime. We store your email only to send the newsletter.