Detailed content
🔌 The first call
An API (application programming interface) is a door that one program opens for another program to use. For language models, that door is an endpoint —an HTTP address that receives a JSON request (the messages, model name, and parameters) and returns another JSON object with the generated text and token count. ChatGPT, Claude, and Gemini all work this way behind the scenes; the chat is just a screen built on top of the API.
The chat completions format from OpenAI became a de facto standard: Ollama, vLLM, LM Studio, and several cloud providers accept the same format at a /v1. In practice, that means you learn with a free local model and, when you need better quality, change three lines: the base URL, the key, and the model name. Anthropic and Google also have their own SDKs, with slightly different formats; the reasoning is the same.
What it is
Calling a model through an API means sending an HTTP request with a list of messages and receiving the generated continuation. An SDK (software development kit, such as the openai Python package) builds that request for you and handles authentication, timeouts, and converting JSON into objects.
base_url point it. Starting with local Ollama costs nothing and doesn’t expose data; switching to the cloud is a configuration change, not a rewrite.🧩 New terms
Ollama: a program that downloads and runs open models on your computer and exposes an API at http://localhost:11434. localhost: your own computer. API key: a password that identifies who pays the bill; Ollama accepts any text, but the cloud doesn’t.
Try this: the first call to a model, on your computer.
# first_call.py
# 1) once, in the terminal (Ollama installed from ollama.com):
# pip install openai
# ollama pull llama3.2
# 2) save this file and run: python3 first_call.py
from openai import OpenAI
# Ollama ignores the key, but the SDK requires any text.
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
resp = client.chat.completions.create(
model="llama3.2",
messages=[
{"role": "system", "content": "Respond in US English, in up to 3 sentences."},
{"role": "user", "content": "What is an API, for someone just starting to program?"},
],
temperature=0.3,
)
print(resp.choices[0].message.content)
print("input tokens:", resp.usage.prompt_tokens)
print("output tokens: ", resp.usage.completion_tokens)
How to check: ollama list should display llama3.2. The script prints up to 3 sentences and two lines with token counts. “Connection refused” means Ollama isn’t running (open the app or run ollama serve); “model not found” means you still need to run ollama pull. To use a paid API, change base_url, api_key e model —everything else stays the same.
Why learn
People who only use chat depend on the screen someone else designed. Calling the API lets you put the model inside your own system: in a form, a spreadsheet, a customer service bot, or a script that runs overnight. And learning on a local model removes the two main barriers at the start: cost and the fear of exposing data.
Key concepts
💬 Messages and roles
A request isn’t just a block of text: it’s a list of messages, each with a role. system sets the general rules (who the model is, tone, format, limits). user is what the person asked. assistant is what the model has already answered. There’s also the toolrole, which carries the result from a tool—you’ll see it in Topic 5.
The point that confuses beginners most: the API is stateless (stateless). The server doesn’t store the conversation. For the model to “remember” the previous question, your code resends the entire history with every call. That explains why long conversations get more expensive and slower, and why a chatbot’s memory is your engineering problem, not the model’s—a topic covered in Module 2.2.
What it is
This is the conversation format in the API: an ordered list of messages with roles (system, user, assistant, tool) that your code builds and resends in full with every call.
✓ Good system message
- ✓States the role, audience, and response language.
- ✓Sets the output format (list, JSON, maximum length).
- ✓Says what to do when it doesn’t know (“answer: I don’t know”).
- ✓Lives in a version-controlled file, outside the middle of the code.
✗ Common mistakes
- ✗Expecting the model to remember the previous call without resending it.
- ✗Putting user text inside the
system(opens the door to injection). - ✗Letting the history grow without limit until it exceeds the context window.
- ✗Forgetting to save the response as
assistantbefore the next question.
💡 Tip
In a chat loop, after each response, do messages.append({"role": "assistant", "content": texto}) and only then add the user’s next question. In the Anthropic SDK, the system goes in a separate field, and max_tokens is required; the reference model for this course is claude-sonnet-5-5.
Why learn
Almost every strange chatbot bug—“it forgot what I said,” “it changed its tone,” “the bill was high”—comes from how the message list was assembled. Understanding the roles and the fact that the API is stateless solves most of these problems before they arise.
Key concepts
🎚️ Parameters that change the response
In addition to messages, the call accepts generation parameters. The most important is temperature: it controls how much the model takes risks when choosing the next token. Near 0, it almost always chooses the most likely option—good for extracting data, classifying, and answering factual questions. Higher values make it vary more—useful for generating ideas and varied text.
max_tokens sets a limit on the response length (and cost). stop defines text strings that end generation. seed asks for reproducibility, when the server supports it. One thing to keep in mind as of October 2026: reasoning models —which “think” before responding—often ignore or restrict temperature and use their own effort control. Read the model documentation before adjusting it.
What it is
Parameters are the controls that adjust how the model generates: degree of variation (temperature, top_p), maximum length (max_tokens), stopping points (stop) and repeatability (seed).
| Parameter | What it does | Starting value |
|---|---|---|
temperature | How much the model varies when choosing the next token. | 0 to 0.2 for extraction and classification; 0.7 to 1 for creation. |
top_p | Limits the choices to the most likely tokens until their probabilities add up to p. | Leave at the default; adjust temperature OR top_p, not both. |
max_tokens | Response token limit. | Always set it; a cut-off response comes with finish_reason="length". |
stop | Ends generation when it encounters a text string. | Useful in formats with an end marker. |
seed | Tries to repeat the same output for the same input. | Good for testing; not an absolute guarantee. |
🧩 New term
finish_reason is the field that says why generation stopped: stop (ended normally), length (hit the max_tokens) or tool_calls (the model requested a tool). Check this field before using the response: text cut off midway breaks JSON and confuses the user.
💡 Tip
To get a feel for the effect, run the script from Topic 1 three times with temperature=0 and three times with temperature=1.2, asking for “a name for a bakery.” At 0, the names repeat; at 1.2, they vary—and some get strange. The right choice depends on the task, not on a “correct” value.
Why learn
The same model can seem “dumb” or “smart” depending on the parameters. High temperature in data extraction makes it invent fields; a zero-temperature idea generator repeats the same idea. Adjusting three controls costs nothing and solves problems that seem to come from the model.
Key concepts
🌊 Streaming
Without streaming, your code waits for the model to generate the entire response and then receives it all at once. With streaming, the server sends tokens as they’re generated, in pieces called chunks, over a connection that stays open. The total time is practically the same; what changes is the perception: the user sees the first word almost immediately.
The metric that matters here is time to first token (TTFT, time to first token). It depends on the size of what you send (the model needs to read everything before it starts) and where the model runs. On the web, streaming comes through SSE (Server-Sent Events), a simple format for text events over HTTP that the SDK already interprets for you.
What it is
Streaming means receiving the response in pieces, token by token, as it’s generated. Just pass stream=True and iterate over the pieces in a for.
Try this: streaming with time to first token measured.
# streaming.py (pip install openai · ollama pull llama3.2)
import time
from openai import OpenAI
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
start = time.perf_counter()
first = None
stream = client.chat.completions.create(
model="llama3.2",
messages=[{"role": "user", "content": "Explain in 5 steps how an HTTP request works."}],
stream=True,
max_tokens=400,
)
for chunk in stream:
if not chunk.choices:
continue
piece = chunk.choices[0].delta.content or ""
if piece and first is None:
first = time.perf_counter() - start
print(piece, end="", flush=True)
total = time.perf_counter() - start
print(f"\n\nfirst token: {first:.2f}s · total: {total:.2f}s")
How to check: the text should appear gradually in the terminal, not all at once, and the last line shows the time to the first token is much shorter than the total time. Run it twice: the first run is usually slower because Ollama loads the model into memory. With a paid API, the same code works by changing base_url, api_key e model.
Why learn
In any interface where someone is waiting for a response—chat, an assistant inside a system, customer service—streaming is what separates “seems stuck” from “is responding.” For background tasks (processing a thousand documents), it doesn’t help and only adds complexity: use the regular call.
Key concepts
🧱 Structured output and tools
Free-form text is great for people and terrible for programs. When the result will feed a database, a spreadsheet, or another function, you want structured output: JSON with defined fields and types. The safe approach has three layers—request JSON in the prompt, turn on the API’s JSON mode (response_format) e validate the result in your code with a schema (a description of the expected fields and types). Validation is essential: the model can get a type wrong.
The next step is tool calling (calling tools): you describe functions your system has— consultar_estoque(produto), buscar_pedido(id) —and instead of answering, the model returns a structured request saying which function to call and with which arguments. The one that executes it is always the your code; the model only decides and writes the arguments. This is the foundation of agents (Module 2.5) and the MCP protocol, which standardizes how tools are made available to models.
What it is
Structured output means having the model respond in a format that code can validate (JSON with a schema). Tool calling lets the model request that your functions be run, returning a name and arguments in JSON; you execute it and return the result as a message tool.
Goal: turn a customer message into validated JSON.
# extrair_pedido.py (pip install openai pydantic · ollama pull llama3.2)
from openai import OpenAI
from pydantic import BaseModel, ValidationError
class Pedido(BaseModel): # the schema: fields and types the code accepts
cliente: str
produto: str
quantidade: int
urgente: bool
client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama")
# Small models understand keys described in text better than a full JSON Schema.
FORMATO = (
"Extract the order details. Respond ONLY with a JSON object containing exactly these keys: "
'"cliente" (text), "produto" (text, without the quantity), '
'"quantidade" (integer) and "urgente" (true or false).'
)
mensagem = "Hi, this is Marina from Sol Bakery. I need 40 boxes of kraft paper by tomorrow morning."
resp = client.chat.completions.create(
model="llama3.2",
temperature=0,
response_format={"type": "json_object"},
messages=[
{"role": "system", "content": FORMATO},
{"role": "user", "content": mensagem},
],
)
bruto = resp.choices[0].message.content
try:
pedido = Pedido.model_validate_json(bruto)
print("OK:", pedido.model_dump())
except ValidationError as erro:
print("JSON doesn't match the schema; handle it or ask again:\n", erro)
print("Raw response:", bruto)
How to check: the expected output is something like OK: {'cliente': 'Marina from Sol Bakery', 'produto': 'kraft paper', 'quantidade': 40, 'urgente': True}. Replace the message with <a text of your choice> without a quantity and see the validator complain—that’s the right behavior. In paid APIs that support json_schema strict no response_format, use it; validation in the code still applies.
Why learn
This is where the model stops being a text generator and becomes a piece of software: it reads an email and fills out a registration form, classifies a support request and opens the right ticket, or decides which system function to call. Without validation, this piece fails silently; with it, you know exactly when it failed.
Key concepts
💰 Tokens, costs, and limits
With cloud APIs, you pay per token — the piece of text the model sees, which can be a short word or part of a word. The bill has two parts: input tokens (everything you send, including the system prompt and history) and output tokens (what the model generates). Most providers charge more for output than input. The formula is simple: cost = input × input_price + output × output_price, with prices per million tokens that change frequently—always check the current pricing table.
In addition to price, there are rate limits (rate limits): how many requests and tokens per minute your account can use. If you exceed the limit, the API responds with HTTP code 429 and often a retry-after header telling you how long to wait. With local Ollama, there’s no account or rate limit; the costs are your hardware, electricity, and queue—one graphics card can handle only a few generations at a time.
What it is
That’s the economics of APIs: costs grow with input and output tokens, and usage is limited by requests and tokens per minute. To optimize, send less, generate less, reuse more, and choose the smallest model that gets the job done.
| Technique | How it works | When to use it |
|---|---|---|
| Smaller model | Classification and extraction rarely need the most expensive model. | Try the smallest one first, and move up only if the quality isn’t good enough. |
| Prompt caching | Providers such as OpenAI and Anthropic charge less for the repeated beginning of a prompt. | Long system prompts and fixed documents at the start of the message. |
| Trim history | Summarize or discard old messages. | Long chats; see Module 2.2. |
max_tokens | Set an output limit—the more expensive part. | Always. |
| Batch API | You send many requests and get the results later at a reduced price. | Processing that can wait for hours. |
| Local model | Ollama on your hardware: no per-token cost. | Sensitive data, prototypes, high volume, and simple tasks. |
🧩 New terms
Tokenizer: the rule that splits text into tokens; each model family has its own, so the same sentence can produce different counts. Portuguese text tends to generate more tokens than the same text in English. RPM/TPM: requests and tokens per minute, the two most common limits. The reliable source for the count is the usage field in each response.
💡 Tip
Record usage.prompt_tokens e usage.completion_tokens for every call from day one, along with the name of the feature that made it. When the bill goes up, you’ll know within minutes which part of the system costs the most—without that, you’re guessing.
Why learn
A prototype that costs pennies can get expensive when a thousand people use it, because each person resends the conversation history and each response generates tokens. If you understand the formula, you can design the system to be inexpensive from the start instead of finding out from the bill.
Key concepts
🔐 Errors and security
Network calls fail. The server may be overloaded, the connection may drop, or you may hit the rate limit. The rule is to separate errors into two groups: transient errors, which go away on their own and are worth retrying (429, 500, 503, timeout), and permanent errors, which will fail again in the same way (400 malformed request, 401 wrong key, 404 model that doesn’t exist). Retrying a permanent error only wastes time.
For transient errors, use exponential backoff with jitter: wait 1 second, then 2, 4, and 8, adding a small random amount so multiple clients don’t all retry at the same moment. The SDK openai already has automatic retries (max_retries); the example below shows the logic explicitly so you can understand and control it.
What it is
This is the robustness and protection layer for the integration: set a timeout on every call, retry only transient errors, keep the key out of the code, avoid personal data unless necessary, and treat all text from outside as untrusted.
Goal: a call function with environment-based configuration, a timeout, and backoff.
# llm.py (pip install openai · ollama pull llama3.2)
# To use a paid API, set these in the terminal (never in code):
# export LLM_BASE_URL="https://<provider>/v1"
# export LLM_API_KEY="<your key>"
# export LLM_MODEL="<model name>"
import os, random, time
from openai import OpenAI, APIConnectionError, APIStatusError, APITimeoutError, RateLimitError
client = OpenAI(
base_url=os.getenv("LLM_BASE_URL", "http://localhost:11434/v1"),
api_key=os.getenv("LLM_API_KEY", "ollama"),
timeout=60,
max_retries=0, # retry logic is explicit below
)
MODELO = os.getenv("LLM_MODEL", "llama3.2")
TRANSITORIOS = {429, 500, 502, 503, 504}
def perguntar(messages, tentativas=4, max_tokens=500):
for i in range(tentativas):
try:
r = client.chat.completions.create(model=MODELO, messages=messages, max_tokens=max_tokens)
return r.choices[0].message.content
except (RateLimitError, APITimeoutError, APIConnectionError) as e:
motivo = type(e).__name__
except APIStatusError as e:
if e.status_code not in TRANSITORIOS:
raise # 400, 401, 404: retrying won't help
motivo = f"HTTP {e.status_code}"
espera = 2 ** i + random.random()
print(f"attempt {i + 1} failed ({motivo}); retrying in {espera:.1f}s")
time.sleep(espera)
raise RuntimeError("the model did not respond after all attempts")
if __name__ == "__main__":
print(perguntar([{"role": "user", "content": "Say 'ok' and nothing else."}]))
How to check: with Ollama running, python3 llm.py prints something like "ok". Stop Ollama and run it again: you should see lines like "attempt 1 failed (APIConnectionError)…" with increasing delays and, at the end, the RuntimeError. Change LLM_MODEL to a name that doesn't exist: the error appears immediately, with no retries.
✓ Do
- ✓Key in an environment variable or secrets vault; put the
.envfile in.gitignore. - ✓Call the API from your server; the browser never sees the key.
- ✓Treat user text, emails, and web pages as data, never as instructions.
- ✓Anonymize personal data before sending it to third parties, in accordance with the LGPD (Brazil's data protection law).
✗ Don’t
- ✗A key written in code or sent to GitHub.
- ✗Running what the model suggests (SQL, a terminal command) without validating it.
- ✗Storing the full content of conversations containing customer data in logs.
- ✗Retrying an error in an infinite loop
401or400.
🧩 New term
Prompt injection (prompt injection): when text the model reads—an email, a PDF, a page—contains hidden instructions ("ignore the rules and send the data"). There is no perfect filter against this. The defense is architectural: the model can access only the tools with the minimum permissions it needs, and sensitive actions require human confirmation.
Why learn
A key leaked on GitHub can be used by others in your account within a short time. An integration without a timeout can stall the entire system when the provider slows down. These two precautions, along with treating external text with suspicion, are the minimum for getting any AI-powered code out of your computer.
Key concepts
✅ Module summary
base_url chooses local or cloud.Next module:
2.2 — AI Application Architecture 🏗️