TExcelTAD
Home › Generative AI & LLMs › Using LLM APIs

Using LLM APIs

Applications reach hosted LLMs through an HTTP API: you send a JSON request with the model name, the messages and some parameters, and you receive a JSON response with the generated content and token usage. Providers differ in details, but the shape is very similar everywhere. The examples use the Anthropic Messages API; other providers' chat APIs follow the same pattern.

Note: API calls need an account, an API key and network access, so the API code in this lesson is shown in non-runnable blocks. The runnable playgrounds work with the request and response data structures, using a hand-written sample response.

A first request with the Python SDK

bash
pip install anthropic
export ANTHROPIC_API_KEY="sk-..."      # never hard-code keys in source files
python
import anthropic

client = anthropic.Anthropic()          # picks up ANTHROPIC_API_KEY

response = client.messages.create(
    model="claude-sonnet-5-5",
    max_tokens=200,
    system="You are a concise assistant.",
    messages=[
        {"role": "user", "content": "Give me three tips for naming variables."},
    ],
)
print(response.content[0].text)
print(response.usage.input_tokens, response.usage.output_tokens)

The reply text sits in response.content[0].text: content is a list of blocks, because a response can also contain other block types (for example tool calls). A typical answer here is three short tips such as "use descriptive names", "follow your language's conventions" and "avoid unclear abbreviations". usage reports how many input and output tokens were billed.

The same request over raw HTTP

bash
curl https://api.anthropic.com/v1/messages \
  -H "x-api-key: $ANTHROPIC_API_KEY" \
  -H "anthropic-version: 2023-06-01" \
  -H "content-type: application/json" \
  -d '{
    "model": "claude-sonnet-5-5",
    "max_tokens": 200,
    "messages": [{"role": "user", "content": "Give me three tips for naming variables."}]
  }'

Request parameters

Parameter Meaning
model which model to use — e.g. claude-opus-5-5 (most capable), claude-sonnet-5-5 (balanced), claude-haiku-5-5 (fastest, cheapest)
max_tokens upper limit on output tokens; generation stops when it is reached
system the system prompt
messages the conversation: alternating user / assistant messages
temperature randomness of sampling (see Sampling); some models restrict which sampling parameters can be set
stop_sequences strings that end generation early when produced
stream send tokens as they are generated (see Streaming)
tools functions the model may call (see Tool Use)

Building the request as a plain dictionary lets you validate it before sending:

python · try it yourself
import json

def build_request(user_text, system=None, model="claude-sonnet-5-5", max_tokens=300, **extra):
    if not user_text.strip():
        raise ValueError("empty message")
    if not 1 <= max_tokens <= 64_000:
        raise ValueError("max_tokens out of range for this app")
    request = {"model": model, "max_tokens": max_tokens,
               "messages": [{"role": "user", "content": user_text}]}
    if system:
        request["system"] = system
    request.update(extra)
    return request

req = build_request("Translate 'good morning' into Spanish.", system="Reply with the translation only.",
                    temperature=0.2)
print(json.dumps(req, indent=2))
{
  "model": "claude-sonnet-5-5",
  "max_tokens": 300,
  "messages": [
    {
      "role": "user",
      "content": "Translate 'good morning' into Spanish."
    }
  ],
  "system": "Reply with the translation only.",
  "temperature": 0.2
}

Reading the response

A response looks roughly like the sample below (hand-written to show the structure; real IDs and numbers differ). The important fields are content, stop_reason and usage:

python · try it yourself
import json

sample_response = json.loads("""{
  "id": "msg_example123",
  "type": "message",
  "role": "assistant",
  "model": "claude-sonnet-5-5",
  "content": [{"type": "text", "text": "Buenos días"}],
  "stop_reason": "end_turn",
  "usage": {"input_tokens": 21, "output_tokens": 6}
}""")

text = "".join(block["text"] for block in sample_response["content"] if block["type"] == "text")
print("reply:", text)
print("stop reason:", sample_response["stop_reason"])
u = sample_response["usage"]
print(f"tokens: {u['input_tokens']} in + {u['output_tokens']} out = {u['input_tokens'] + u['output_tokens']}")
reply: Buenos días
stop reason: end_turn
tokens: 21 in + 6 out = 27

stop_reason tells you why generation ended, and your code should check it:

stop_reason Meaning What to do
end_turn the model finished naturally use the reply
max_tokens hit your output limit — reply is cut off raise max_tokens or ask for shorter output
stop_sequence produced one of your stop strings expected if you set them
tool_use the model wants to call a tool run the tool, send back the result

Handling errors

Network calls fail. Your code should handle at least: rate limiting (HTTP 429), temporary server overload (5xx / "overloaded"), timeouts, and invalid requests (400, which you should fix rather than retry). The standard pattern for temporary errors is retry with exponential backoff and jitter. The official SDKs already retry some errors automatically; this sketch shows the idea with a fake API that fails twice:

python · try it yourself
import random

class TemporaryError(Exception):
    pass

calls = {"n": 0}
def flaky_api():
    calls["n"] += 1
    if calls["n"] < 3:
        raise TemporaryError("429 rate limited")
    return "ok"

def with_retries(fn, max_attempts=5, base_delay=0.5, rng=random.Random(1)):
    for attempt in range(1, max_attempts + 1):
        try:
            return fn()
        except TemporaryError as e:
            if attempt == max_attempts:
                raise
            delay = base_delay * 2 ** (attempt - 1) * (0.5 + rng.random())   # backoff + jitter
            print(f"attempt {attempt} failed ({e}); would wait {delay:.2f}s")
            # time.sleep(delay) in real code
    return None

print("result:", with_retries(flaky_api))
attempt 1 failed (429 rate limited); would wait 0.32s
attempt 2 failed (429 rate limited); would wait 1.35s
result: ok

Keys and safety basics

  • Keep API keys in environment variables or a secrets manager, never in code or in front-end JavaScript (anyone could read them in the browser).
  • Call the API from your backend; the browser talks to your backend.
  • Set max_tokens and per-user limits so a bug or abuse can't run up a large bill.
  • Log requests and responses (minus sensitive data) so you can debug and evaluate.

Test yourself

Where is the reply text in an Anthropic Messages API response?

  1. response.text
  2. response.content[0].text (content is a list of blocks)
  3. response.messages[-1]
  4. response.choices

The stop_reason is max_tokens. What does that mean?

  1. The model finished normally
  2. The reply was cut off because it reached the output limit
  3. The prompt was too long
  4. The API key is invalid

Why should a web app not call the LLM API directly from browser JavaScript with its key?

  1. Browsers can't send JSON
  2. Anyone could read the API key from the page and use it
  3. It is slower
  4. APIs only accept curl