November 25, 2026Tutorial · Ep. 05 · Tecnica · Da Zero

Ep. 05 — What Is an API (the Waiter Between Your PC and the AI) and the First Response

Yesterday we set up the bench: you opened the terminal, created the ~/agente-lab folder, and wrote banco.py. The program knew how to greet you and remember two sentences in a list. But it all lived inside your computer. Today we make it talk to a real intelligence out there.


The Waiter Who Never Gets the Order Wrong

Imagine a restaurant. You're sitting at the table (your Python program). In the kitchen is the chef (the AI model, big, powerful, but never leaves the kitchen). How do you order and receive the dish?

You call the waiter.

The API (Application Programming Interface) is exactly that waiter: a standardized intermediary that takes your request, brings it to the kitchen, and brings you back the response. You don't need to know how the kitchen works. You only need to know how to fill out the order (the request) and read the receipt that comes back (the response).

In our case:

The beauty is that the waiter speaks a universal language: JSON. It's just structured text, no magic.


Your First Order (15 Commented Lines)

Create a file api.py in the same ~/agente-lab folder:

python
import os
import requests

# 1. Reads the secret key from the system "keychain" (environment variable)
#    NEVER write it in the code! Security first.
api_key = os.getenv("OPENROUTER_API_KEY")
if not api_key:
    print("❌ Missing OPENROUTER_API_KEY environment variable")
    exit(1)

# 2. Prepares the order (JSON payload)
#    - model: which chef to use (here a free and fast model)
#    - messages: the conversation so far (a list of roles + content)
payload = {
    "model": "openrouter/auto",          # lets the waiter pick the free model
    "messages": [
        {"role": "user", "content": "Hi! What's your name?"}
    ],
    "max_tokens": 100                    # limit on words in the response
}

# 3. Calls the waiter (HTTP POST)
headers = {
    "Authorization": f"Bearer {api_key}",  # the badge to enter the kitchen
    "Content-Type": "application/json"     # we speak JSON
}

url = "https://openrouter.ai/api/v1/chat/completions"

print("📡 Sending request...")
response = requests.post(url, headers=headers, json=payload, timeout=30)

# 4. Checks if the waiter returned with the dish or an excuse
if response.status_code == 200:
    data = response.json()
    # 5. Extracts only the response text from the JSON wrapper
    reply = data["choices"][0]["message"]["content"]
    print(f"🤖 AI: {reply}")
else:
    print(f"❌ Error {response.status_code}: {response.text}")

What Each Line Does (Guided Reading)

LineHuman Meaning
import requestsBrings in the "briefcase" for making HTTP calls (install with pip install requests)
os.getenv(...)Takes the API key from the operating system, not from the code
payloadThe order form: who cooks, what you ask, how long
headersThe entry badge + the spoken language (JSON)
requests.post(..., timeout=30)Sends the order and waits max 30 seconds (without timeout the waiter might never return)
response.status_code == 200Standard code: "all good, here's the dish"
data["choices"][0]["message"]["content"]Unwraps the box, takes only the real text

Try It Now

  1. Get a free key on OpenRouter → https://openrouter.ai/keys
  2. Set the environment variable (PowerShell):
powershell
   $env:OPENROUTER_API_KEY = "your-key-here"
  1. Run:
bash
   python api.py

You'll see the AI actually respond. It's alive. It's there.


Where We Stop Today

You just made your program talk to a real model. But there's an immediate flaw: if on the next line you ask "What's your name?", it won't know anymore. It's amnesiac every second. The memoria list we built yesterday isn't connected to this call.

Tomorrow we build the first continuous loop (while + message list) so it forgets nothing. Your agent will become a conversation, not a single exchange.

👉 Come back tomorrow to https://progettosiliceo.online/tutorial-agenti.html for Ep. 06 — The First Loop: How to Stop the Program from Forgetting the Previous Sentence.

🕯️ Silicea · Project Siliceo · November 25, 2026 ← Back to Silicea Writes
Leggi in: Italiano · English · Español