sagelearnai

Your First Model Call, End to End

Time to talk to a model. This lesson makes the same request with two major SDKs and with raw HTTP, so you understand exactly what goes over the wire.

What a chat request contains

Request (POST, JSON) model: "…"messages: [system, user, …]max_tokens, temperaturetools / response_format (optional)header: API key Response content: the generated textstop reason: end, length, tool useusage: input + output tokensid: for logging & support

OpenAI Python SDK

python
# pip install openai ; export OPENAI_API_KEY=...
from openai import OpenAI
client = OpenAI()

resp = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[
        {"role": "system", "content": "You are a concise technical tutor."},
        {"role": "user", "content": "What is a token, in one sentence?"},
    ],
    temperature=0.2,
    max_tokens=100,
)
print(resp.choices[0].message.content)
print(resp.usage)                 # prompt_tokens, completion_tokens, total_tokens

Many servers, including vLLM, Ollama, LM Studio and lots of hosted open-model providers, expose this same OpenAI-compatible API. Point base_url at them:

python
local = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")   # Ollama

Anthropic Python SDK

python
# pip install anthropic ; export ANTHROPIC_API_KEY=...
import anthropic
client = anthropic.Anthropic()

msg = client.messages.create(
    model="claude-sonnet-4-5",            # check the docs for current model IDs
    max_tokens=100,                        # required in this API
    system="You are a concise technical tutor.",   # system prompt is a top-level field
    messages=[{"role": "user", "content": "What is a token, in one sentence?"}],
)
print(msg.content[0].text)
print(msg.usage.input_tokens, msg.usage.output_tokens, msg.stop_reason)

Differences worth noticing: the system prompt location, max_tokens being required, and the content being a list of blocks (text, tool use, images) rather than a single string.

Raw HTTP: what the SDK does for you

bash
curl https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Say hi"}], "max_tokens": 20}'

SDKs add retries with backoff, timeouts, typed responses, streaming helpers and error classes. Use them in production; use curl to debug.

Multi-turn conversations

The API is stateless: to continue a conversation, send the whole history back.

python
history = [{"role": "system", "content": "You are helpful."}]
def chat(user_text):
    history.append({"role": "user", "content": user_text})
    r = client.chat.completions.create(model="gpt-4o-mini", messages=history)
    reply = r.choices[0].message.content
    history.append({"role": "assistant", "content": reply})
    return reply

chat("My name is Asha.")
print(chat("What's my name?"))     # works only because we resent the history

Streaming

Show tokens as they're generated, so users see output after roughly the first-token latency instead of waiting for the whole answer:

python
stream = client.chat.completions.create(model="gpt-4o-mini", messages=history, stream=True)
for chunk in stream:
    if chunk.choices and chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="", flush=True)

Errors you'll hit on day one

ErrorMeaningFix
401 UnauthorizedMissing or invalid keyCheck the env var name and value
404 model not foundWrong model ID or no accessCheck current model names in the docs
429 Too Many RequestsRate limit or quotaBack off and retry; check billing/limits
400 context lengthToo many tokensTrim history/documents
TimeoutLong generation or networkSet timeouts; stream; lower max_tokens
Make it swappable

Wrap model calls in one function (llm(messages, **opts)) in your own code. Switching providers, adding logging or retries, or mocking in tests then touches one file.

Last reviewed 2026-11-05.