Calling a Model API

Updated · 9 min read
mediumPython 3.13aiapipythonllm-apillm

A model API is a web service that lets your code send text to a hosted AI model and get its reply back. It is used to build AI into your own applications: a chat assistant, an email classifier or a document summarizer. Instead of typing into a chat window, your program sends a request and receives a response, usually as JSON.

This chapter builds Campus Helper's question answering in Python. Most providers, and the model servers you can run on your own computer, accept the same request format, called chat completions. So the course uses one small file, model_api.py, that works with any of them: you choose the provider with three settings, and every example in the course stays the same.

Request and Response

One request, one response
PartDescription
modelIt is used to choose which model answers, by the name your provider gives it
max_tokensIt is used to cap the length of the reply, in tokens
systemIt is used to give standing instructions and facts the model should follow
messagesIt is used to send the conversation, as a list of user and assistant turns
textThe reply
finish_reasonWhy the reply ended: stop (finished), length (cut off) or tool_calls (it wants a tool)
usageThe input and output tokens counted, which decide the cost

Getting Ready

StepCommand or actionDescription
1. Installpip install httpxIt is used to install the library that sends web requests
2. Get a keyCreate an API key in your provider's consoleIt is used to prove your requests come from your account
3. Set three variablesMODEL_API_URL, MODEL_API_KEY, MODEL_NAMEIt is used to tell the code where to send requests, with which key, to which model

Where to point it. These are example settings as of November 2026; check your provider's documentation, because addresses and model names change.

ProviderMODEL_API_URLNote
Anthropichttps://api.anthropic.com/v1Compatible endpoint; the provider recommends its own SDK for production
Google Geminihttps://generativelanguage.googleapis.com/v1beta/openaiCompatible endpoint, marked beta
OpenAIhttps://api.openai.com/v1The format's original provider
Ollama, on your own computerhttp://localhost:11434/v1Free and private; any key works; small models give weaker answers

Compatible endpoints don't always support every feature. Structured output, tool calls and token counts in streams vary by provider. When a feature doesn't work, check the provider's compatibility notes, or use its own SDK with the same ideas.

The Helper File

Save this file once. Every model example in the course imports it. It sends the request with httpx and turns the JSON response into a simple Reply.

model_api.py
"""model_api.py: a small client for chat model APIs that works with many providers.

Most hosted model providers, and local model servers, accept the same "chat completions"
request over HTTPS. This file sends that request and returns a simple Reply.
Set MODEL_API_URL, MODEL_API_KEY and MODEL_NAME before you run it.
"""
import json
import os
from dataclasses import dataclass, field
 
import httpx
 
@dataclass
class ToolCall:
    id: str
    name: str
    arguments: dict
 
@dataclass
class Reply:
    text: str
    finish_reason: str              # "stop" (finished), "length" (cut off) or "tool_calls"
    input_tokens: int
    output_tokens: int
    tool_calls: list = field(default_factory=list)
    message: dict = field(default_factory=dict)   # the model's turn, to add to the conversation
 
class Stream:
    """Yields the reply text piece by piece; after the loop, .reply holds the finished Reply."""
 
    def __init__(self, http, url, body):
        self.http, self.url, self.body, self.reply = http, url, body, None
 
    def __iter__(self):
        text, finish, usage = [], None, {}
        with self.http.stream("POST", self.url, json=self.body) as response:
            response.raise_for_status()
            for line in response.iter_lines():
                if not line.startswith("data: ") or line == "data: [DONE]":
                    continue
                chunk = json.loads(line[6:])
                usage = chunk.get("usage") or usage
                for choice in chunk.get("choices", []):
                    piece = (choice.get("delta") or {}).get("content")
                    if piece:
                        text.append(piece)
                        yield piece
                    finish = choice.get("finish_reason") or finish
        self.reply = Reply("".join(text), finish, usage.get("prompt_tokens", 0), usage.get("completion_tokens", 0))
 
class ModelClient:
    def __init__(self, url=None, key=None, model=None, timeout=60):
        self.url = (url or os.environ["MODEL_API_URL"]).rstrip("/") + "/chat/completions"
        self.model = model or os.environ["MODEL_NAME"]
        self.http = httpx.Client(timeout=timeout,
                                 headers={"Authorization": f"Bearer {key or os.environ['MODEL_API_KEY']}"})
 
    def _body(self, messages, system, max_tokens, **extra):
        turns = ([{"role": "system", "content": system}] if system else []) + messages
        return {"model": self.model, "max_tokens": max_tokens, "messages": turns, **extra}
 
    def chat(self, messages, system=None, max_tokens=500, tools=None, **settings):
        """Sends one request and waits for the whole reply."""
        extra = dict(settings)
        if tools:
            extra["tools"] = [{"type": "function", "function": tool} for tool in tools]
        response = self.http.post(self.url, json=self._body(messages, system, max_tokens, **extra))
        response.raise_for_status()
        data = response.json()
        choice, usage = data["choices"][0], data.get("usage", {})
        message = choice["message"]
        calls = [ToolCall(c["id"], c["function"]["name"], json.loads(c["function"]["arguments"] or "{}"))
                 for c in message.get("tool_calls") or []]
        return Reply(message.get("content") or "", choice["finish_reason"],
                     usage.get("prompt_tokens", 0), usage.get("completion_tokens", 0), calls, message)
 
    def parse(self, messages, schema, system=None, max_tokens=500):
        """Asks for JSON that matches a Pydantic model; returns (object or None, Reply)."""
        reply = self.chat(messages, system, max_tokens, response_format={
            "type": "json_schema", "json_schema": {"name": schema.__name__, "schema": schema.model_json_schema()}})
        try:
            return schema.model_validate_json(reply.text), reply
        except ValueError:
            return None, reply
 
    def stream(self, messages, system=None, max_tokens=500):
        """Starts a streamed request; iterate over it to get the text as it arrives."""
        body = self._body(messages, system, max_tokens, stream=True, stream_options={"include_usage": True})
        return Stream(self.http, self.url, body)
 
def tool_result(call, output):
    """The message that sends a tool's output back to the model."""
    return {"role": "tool", "tool_call_id": call.id, "content": str(output)}

Explanation: ModelClient() reads the three settings from the environment. chat() puts the system prompt first, sends one request and waits for the whole reply. The Reply keeps only what you need: the text, the finish_reason, the token counts, any tool_calls, and the model's message so you can continue the conversation. Later lessons use parse() for structured output and stream() for replies that arrive piece by piece.

Example: Your First Call

Python
from model_api import ModelClient
 
client = ModelClient()  # reads MODEL_API_URL, MODEL_API_KEY and MODEL_NAME
 
reply = client.chat(
    system=(
        "You are Campus Helper, a school assistant. Answer in one or two sentences, "
        "using only these facts. Fees: lab $45, due September 30; field trip $30, "
        "due October 15; library $15, due September 30."
    ),
    messages=[{"role": "user", "content": "When is the lab fee due, and how much is it?"}],
    max_tokens=500,
)
 
print(reply.text)
print("Finish reason:", reply.finish_reason)
print("Tokens in:", reply.input_tokens, "| out:", reply.output_tokens)

Example output. The reply and token counts below were produced by an AI model on November 16, 2026, to show their shape. This code wasn't run against a live API for the lesson, and your reply will be worded differently.

Output
The lab fee is $45, and it's due by September 30.
Finish reason: stop
Tokens in: 96 | out: 17

Explanation: client.chat() sends one request and waits for the full reply. The system prompt holds the fee facts, because the model doesn't know your school's fees unless you send them. Token counts depend on the model, so yours will differ.

Common Mistakes

Assuming the model knows your data. Send the facts it needs, or connect it to them (later chapters cover retrieval).

Ignoring finish_reason. A reply that ends with length is incomplete, even if it looks finished.

Ignoring errors. Networks fail and limits are reached; raise_for_status() turns an error response into an exception you can catch, and the "Tokens, Cost and Rate Limits" lesson shows how to handle them.

Interview Corner

What does a model API request contain?

The model name, a maximum output length, the conversation as messages, and usually a system prompt, plus optional settings such as tools or an output format.

What does finish_reason tell you?

Why the reply ended: stop means the model finished; length means it hit the length cap; tool_calls means it wants to call a tool.

Why write a small helper instead of using one provider's SDK everywhere?

So the application doesn't depend on one provider. The helper is the only code that knows the request format; switching provider means changing three settings, and the rest of the code stays the same.

Practice

Exercise: ask about another fee. Change the question to ask about the library fee, then ask about a fee that isn't listed, such as parking. Does the reply admit it doesn't know? If not, add "If the answer isn't in these facts, say so" to the system prompt.

Check your understanding:

  1. What is the system prompt used for?
  2. Why does the example put the fees in the system prompt?
  3. What does usage report?

Quick check: calling a model API

4 questions
1What is a model API?
2Where should your API key be kept?
3What does finish_reason "length" mean?
4Why does the example list the fees in the system prompt?

Key Takeaways

Quick reference

NeedCode
Clientclient = ModelClient()
Callreply = client.chat(messages=[...], system=..., max_tokens=...)
Reply textreply.text
Why it endedreply.finish_reason
Tokens usedreply.input_tokens, reply.output_tokens

Was this tutorial helpful?

Lesson 83 of 186