Building With LLM APIs

Generative & Agentic AI · Working with LLMs · Intermediate · 15 min

Messages, roles, streaming, JSON output and costs: the daily work of an AI engineer.

A taxi meter that ticks for every word you say AND every word the driver says back. The driver forgets you after each ride, so you retell the whole story every time and the meter runs longer each ride.

The idea in everyday words

Calling an LLM API is like texting a genius consultant who bills per word. You send the conversation so far (they have no memory between texts), they reply, and you pay for every word in AND out. Clear, short messages save money.

The request shape (same idea for every provider)

POST https://api.provider.com/v1/messages
{
  "model": "claude-sonnet / gpt / gemini / llama",
  "system": "You are a helpful tutor.",
  "messages": [
    {"role": "user", "content": "What is RAG?"},
    {"role": "assistant", "content": "RAG means..."},
    {"role": "user", "content": "Give an example"}
  ],
  "max_tokens": 500,
  "temperature": 0.3
}

The API is stateless: you resend history each time. Long chats = more tokens = more cost.

Count the cost

price_in = 3.00    # $ per 1M input tokens (example)
price_out = 15.00  # $ per 1M output tokens (example)
requests_per_day = 10_000
tokens_in, tokens_out = 1_500, 300

daily = requests_per_day * (tokens_in * price_in + tokens_out * price_out) / 1_000_000
print("daily cost: 
quot;, round(daily, 2), " monthly:
quot;, round(daily * 30))

Cut cost: shorter prompts, prompt caching, smaller models for easy tasks, summarise old history.

Structured output & streaming

  • Ask for JSON (or use the provider's JSON/tool mode) and validate it: models sometimes break format.
  • Streaming sends tokens as they're generated → the user sees text instantly.
  • Handle 429 (rate limit) and 5xx with retries + backoff. Never put API keys in frontend code.
import json
reply = '{"topic": "RAG", "difficulty": 2, "tags": ["retrieval", "llm"]}'
data = json.loads(reply)
assert isinstance(data["difficulty"], int)
print("valid!", data["tags"])

Step by step

  1. Build:

    system + history + new user message

  2. Send:

    POST with API key in a server-side header

  3. Stream:

    tokens arrive → show them as they come

  4. Validate:

    parse JSON, retry if invalid

  5. Log:

    store tokens used for cost tracking

Code example

def build_messages(history, question, max_turns=4):
    trimmed = history[-max_turns * 2:]          # keep last N exchanges
    return trimmed + [{"role": "user", "content": question}]

history = [{"role": "user", "content": f"q{i}"} if i % 2 == 0 else {"role": "assistant", "content": f"a{i}"} for i in range(12)]
msgs = build_messages(history, "new question", max_turns=2)
for m in msgs:
    print(m["role"], ":", m["content"])

Interview tips

  • Explain stateless chat APIs and context management.

  • Discuss cost/latency trade-offs between model sizes.

  • Mention prompt caching, batching and streaming.

Challenge: Estimate Monthly LLM Cost

Return the monthly cost in dollars (30 days), rounded to 2 decimals: requests_per_day × (tokens_in × price_in + tokens_out × price_out) / 1,000,000 × 30 (prices are per 1M tokens).

Example: llm_cost(1000, 1000, 100, 3, 15) → 135.0

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Working with LLMs

Previous: Decoding: Greedy, Beam Search, Sampling & Structured Output · Next: Context Engineering & Prompt Caching