← CS Lab AI & Machine Learning / LLM API Integration
LLM API Integration — card 1 of 4
LLM API Integration — card 2 of 4
LLM API Integration — card 3 of 4
LLM API Integration — card 4 of 4

Calling an LLM is one HTTPS request: you send a list of messages, the model sends back text. No model runs on your machine — you POST JSON to a hosted endpoint and read the reply, like talking to any web service.

Where you meet it

What it does

It turns a conversation into a completion. You hand the model the whole exchange so far — each turn tagged with a role — plus a few knobs, and it returns the next assistant turn. The API is stateless: it remembers nothing between calls, so you carry the history.

The API remembers nothing — every call ships the full transcript, and every token, both ways, lands on your bill.

How it works

The request body is JSON: a model id, a messages array, and parameters like max_tokens (a hard cap on the reply) and temperature (higher = more random). Each message has a roleuser and assistant alternate; the system instruction sets behaviour up front (Anthropic puts it in a top-level system field; OpenAI-style APIs put it as the first message). The API key rides in a header, never in the body.

POST https://api.anthropic.com/v1/messages
x-api-key: $ANTHROPIC_API_KEY        # secret, server-side only
anthropic-version: 2023-06-01
content-type: application/json

{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "temperature": 0.7,
  "system": "You are a terse assistant.",
  "messages": [
    {"role": "user",      "content": "Name one Scottish island."},
    {"role": "assistant", "content": "Skye."},
    {"role": "user",      "content": "And one more?"}
  ]
}

The reply is JSON: the generated content, a stop_reason, and a usage block with input/output token counts. Because there's no server-side memory, the third turn only works if you resend turns one and two — every call ships the full transcript. Set "stream": true and the response arrives as server-sent events (SSE): small token deltas you concatenate and render live, instead of blocking until the whole answer is done.

Watch out

  • Never ship the key. API keys belong on a server or in env vars — never in frontend code, a public repo, or a git history. A leaked key is someone else's bill. Call the API from your backend and proxy.
  • Stateless means you own the context. Resending the whole history each turn grows the token count fast — trim, summarise, or window old turns to stay under the context limit and the budget.
  • Rate limits are real. Cross the per-minute request (RPM) or token (TPM) ceiling and you get 429. Retry with exponential backoff (1s, 2s, 4s, with jitter); also handle 529/overloaded and 500.
  • Validate the output. The model is non-deterministic and can change between versions — parse defensively, pin a model id, and don't eval() what comes back.
  • You pay per token, both ways. Input and output are billed, and output usually costs more — read usage on every call and watch the total.

Go deeper

Eine LLM aufzurufen ist ein einziger HTTPS-Request: Du schickst eine Liste von Nachrichten, das Modell schickt Text zurück. Es läuft kein Modell auf deiner Maschine — du POSTest JSON an einen gehosteten Endpoint und liest die Antwort, wie bei jedem Webservice.

Wo es vorkommt

Was es tut

Es macht aus einer Konversation eine Completion. Du übergibst dem Modell den bisherigen Verlauf — jeder Turn mit einer Rolle markiert — plus ein paar Stellschrauben, und es liefert den nächsten assistant-Turn. Die API ist stateless: Sie merkt sich zwischen Calls nichts, also trägst du die History.

Die API merkt sich nichts — jeder Call schickt das ganze Transkript mit, und jedes Token, in beide Richtungen, landet auf deiner Rechnung.

Wie es funktioniert

Der Request-Body ist JSON: eine model-ID, ein messages-Array und Parameter wie max_tokens (harte Obergrenze für die Antwort) und temperature (höher = zufälliger). Jede Message hat eine roleuser und assistant wechseln sich ab; die system-Anweisung legt das Verhalten vorab fest (Anthropic in einem Top-Level-Feld system, OpenAI-artige APIs als erste Message). Der API-Key steckt im Header, nie im Body.

POST https://api.anthropic.com/v1/messages
x-api-key: $ANTHROPIC_API_KEY        # geheim, nur serverseitig
anthropic-version: 2023-06-01
content-type: application/json

{
  "model": "claude-sonnet-4-5",
  "max_tokens": 1024,
  "temperature": 0.7,
  "system": "Du bist ein knapper Assistent.",
  "messages": [
    {"role": "user",      "content": "Nenne eine schottische Insel."},
    {"role": "assistant", "content": "Skye."},
    {"role": "user",      "content": "Und noch eine?"}
  ]
}

Die Antwort ist JSON: der erzeugte content, ein stop_reason und ein usage-Block mit den Token-Zahlen für Input und Output. Weil es kein serverseitiges Gedächtnis gibt, funktioniert der dritte Turn nur, wenn du Turn eins und zwei mitschickst — jeder Call transportiert das ganze Transkript. Mit "stream": true kommt die Antwort als Server-Sent Events (SSE): kleine Token-Deltas, die du zusammensetzt und live renderst, statt zu blockieren, bis die ganze Antwort fertig ist.

Worauf achten

  • Den Key niemals ausliefern. API-Keys gehören auf einen Server oder in Env-Variablen — nie in Frontend-Code, ein öffentliches Repo oder die Git-History. Ein geleakter Key ist die Rechnung von jemand anderem. Ruf die API vom Backend aus auf und proxye.
  • Stateless heißt: Kontext ist deine Sache. Die ganze History pro Turn mitzuschicken treibt die Token-Zahl schnell hoch — alte Turns kürzen, zusammenfassen oder fenstern, um unter Kontext-Limit und Budget zu bleiben.
  • Rate-Limits sind echt. Über das Minuten-Limit für Requests (RPM) oder Tokens (TPM) gibt's 429. Retry mit exponentiellem Backoff (1s, 2s, 4s, mit Jitter); auch 529/overloaded und 500 behandeln.
  • Output validieren. Das Modell ist nicht-deterministisch und kann sich zwischen Versionen ändern — defensiv parsen, eine Modell-ID pinnen und nichts eval()en, was zurückkommt.
  • Du zahlst pro Token, in beide Richtungen. Input und Output werden abgerechnet, Output meist teurer — bei jedem Call usage lesen und die Summe im Blick behalten.

Mehr dazu

Next up
AI & Machine LearningFine-Tuning Overview AI & Machine LearningLocal & Open Models All concepts →