# Your first inference service: put a model function behind HTTP

> Run a local inference endpoint, send JSON, and interpret status codes. Follow the model function, runtime, server, and client before learning streaming and deployment.

- URL: https://dmxsf.com/en/wiki/inference/first-inference-service/
- [DMXSF](https://dmxsf.com/en/about/)
- Beginner
- Updated: 2026-11-22
- Tags: Inference, Serving

## After this page you will be able to

- Describe the roles of model files, runtimes, servers, and clients.
- Read an HTTP address, method, path, JSON body, and status code.
- Run a local endpoint and check a success and an error.
- Distinguish observations for complete and streamed responses.

Inference turns input into a model result. An inference service lets another program request that result and identify errors. In this lesson a tiny transition table stands in for a model while you send a real HTTP request on your own machine. It needs the Python standard library and runs without weights or an internet service.

## Understand inference as a function

Imagine a function that receives text and a token budget, then returns generated tokens. A model runtime typically tokenizes the input, calculates scores, selects a next token, and repeats until a stop condition or output limit. A real tokenizer may split a word into multiple pieces. Here we split on spaces and use a fixed transition table so each step can be traced.

Model files contain weights, and a runtime may also need configuration and a tokenizer. The weights are numbers. The runtime reads their format, allocates memory, and executes operations. The same request interface can call a toy function or a compatible runtime. Pin weights or the transition table, tokenizer, and sampling settings when you want to investigate an interface problem.

## Put a protocol around the function

A client sends a request and a server responds. An HTTP address contains a host, a port, and a path. This example uses `127.0.0.1`, the local machine, and asks the operating system to choose an available port. The `/generate` path reaches the generation handler. A `POST` request includes a JSON body containing `prompt` and `max_tokens`.

| Stage | Work | What you can observe |
| --- | --- | --- |
| Client assembly | Convert parameters to JSON and connect | Request content and timeout |
| Interface parsing | Locate the route and validate JSON and fields | A status code such as 200, 400, or 404 |
| Inference | Process prompt tokens and respect the budget | Generated tokens and stop condition |
| Response | Encode JSON and let the client read it | Status and response body |

A 200 response means the interface handled the request, even when the token list is empty. A 400 means the client provided an invalid request, such as a Boolean output budget. A 404 means the path does not exist in this example. Distinguishing the outcomes lets a caller show a relevant error and fix the request before retrying.

## Experiment: send an actual local HTTP request

[Open the local HTTP request lab](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/first-inference-service/run.py)

Save the following code and run it. It starts a loopback-only server, sends requests, prints the results, and shuts the server down. The toy function follows `one` with `two` and `three`. The requests stay on the local machine. The example ran on an Apple M2 Max with Python 3.12.14.

```python
from __future__ import annotations

import json
from http.client import HTTPConnection
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread

TRANSITIONS = {"one": "two", "two": "three", "three": None}

def generate(prompt: str, limit: int) -> list[str]:
    """Decode a toy transition table until stop or the output budget."""
    tokens = prompt.split()
    if not tokens or type(limit) is not int or not 1 <= limit <= 8:
        raise ValueError("need text and an integer limit from 1 to 8")
    current = tokens[-1]
    output = []
    for _ in range(limit):
        following = TRANSITIONS.get(current)
        if following is None:
            break
        output.append(following)
        current = following
    return output

class GenerateHandler(BaseHTTPRequestHandler):
    def do_POST(self) -> None:
        if self.path != "/generate":
            self.respond(404, {"error": "unknown route"})
            return
        try:
            size = int(self.headers.get("Content-Length", "-1"))
            if not 1 <= size <= 4096:
                raise ValueError("invalid body length")
            obj = json.loads(self.rfile.read(size))
            prompt = obj.get("prompt") if isinstance(obj, dict) else None
            if not isinstance(prompt, str):
                raise ValueError("prompt must be a string")
            output = generate(prompt, obj.get("max_tokens", 2))
        except (ValueError, UnicodeError):
            self.respond(400, {"error": "invalid request"})
            return
        self.respond(200, {"tokens": output})

    def respond(self, status: int, payload: dict) -> None:
        body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json; charset=utf-8")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *_args: object) -> None:
        pass

def make_server(port: int = 0) -> ThreadingHTTPServer:
    """Bind to loopback only; port zero asks the OS to choose a free port."""
    return ThreadingHTTPServer(("127.0.0.1", port), GenerateHandler)

def request(port, path, payload):
    client = HTTPConnection("127.0.0.1", port, timeout=3)
    try:
        client.request(
            "POST", path, json.dumps(payload),
            {"Content-Type": "application/json"},
        )
        response = client.getresponse()
        return response.status, json.loads(response.read())
    finally:
        client.close()

with make_server() as server:
    worker = Thread(
        target=server.serve_forever,
        kwargs={"poll_interval": 0.01},
    )
    worker.start()
    try:
        port = server.server_port
        ok = request(port, "/generate", {"prompt": "one", "max_tokens": 2})
        bad_payload = {"prompt": "one", "max_tokens": True}
        invalid = request(port, "/generate", bad_payload)
        unknown = request(port, "/other", {"prompt": "one"})
    finally:
        server.shutdown()
        worker.join()
assert ok == (200, {"tokens": ["two", "three"]})
assert invalid[0] == 400 and unknown[0] == 404
print("success:", *ok)
print("invalid limit:", invalid[0])
print("unknown route:", unknown[0])
```

```text
success: 200 {'tokens': ['two', 'three']}
invalid limit: 400
unknown route: 404
```

The widget below re-implements this toy endpoint in the browser: assemble a request, send it, and follow it through assembly, interface validation, decoding and response, then read back the status code and body. The page's three printed requests and the exercise's three requests all replay here.

On a first pass, treat `generate` as a ready-made model. Read how `request` sends the two fields and reads the status. Then find the single call to `generate` in `do_POST`. Keeping these functions separate makes it possible to test inference and HTTP behavior independently.

## Measure before adding deployment complexity

The example sends one response after generation ends. A streaming interface sends pieces as they become available. Measure the wait for the first piece, gaps between pieces, and total time. Test what happens when the client disconnects so the server can stop work and release resources. [Inference serving](https://dmxsf.com/en/wiki/inference/serving/) shows how to measure first-token and output latency.

The local demonstration covers a bounded interface. Multi-user deployments also need queues, concurrency limits, request cancellation, access controls, and observability. The entry point validates and queues requests, the runtime generates, and the client receives and presents the output. Run fixed requests as a baseline, then change concurrency and measure throughput, queue time, and timeouts. For the application layer, [Your first agent](https://dmxsf.com/en/wiki/applications/first-agent/) shows how action requests become tool calls.

## Summary and exercises

- Inference produces a result. The surrounding service accepts, checks, and returns messages.
- Track request inputs, model results, and failure causes separately.
- Understand a fixed request before measuring streaming or concurrency.

### Quick self-check

**1. What sends request fields into the runtime?**

- [x] The request handler.
- [ ] The model weights file.

> The handler knows the route and request fields.

**2. What happens when the example receives an unknown path?**

- [ ] It returns 200 and an empty token list.
- [x] It returns 404.

> Routing fails before generation starts.

**3. What can users notice with streaming?**

- [x] The wait for the first chunk, gaps between chunks, and the total time.
- [ ] Only loading before the server starts.

> Each chunk affects when the user sees new text.

**4. What does max_tokens limit here?**

- [ ] The size of the JSON request in bytes.
- [x] The number of newly generated tokens.

> Those limits belong to different stages.

### Predict three responses

Set `max_tokens` to one. Then try prompt `three`. Finally send a request to `/other`. Predict the status and response for each.

<details>
<summary>Worked answer</summary>

With `one`, a limit of one produces 200 and `two`. Prompt `three` reaches the end of the table and yields 200 with an empty list. The undefined route yields 404. The second result is a normal stopping case. The third occurs at the interface boundary.

</details>

## Further reading

- [Python http.server documentation](https://docs.python.org/3/library/http.server.html) for the local demonstration server.
- [HTTP Semantics, RFC 9110](https://www.rfc-editor.org/rfc/rfc9110.html).
- Continue with [decoding and sampling](https://dmxsf.com/en/wiki/inference/decoding-and-sampling/) and [inference serving](https://dmxsf.com/en/wiki/inference/serving/).

## Companion code

[First inference service: a local HTTP endpoint](https://github.com/dmxsf/dmxsf/tree/main/labs/inference/first-inference-service): Send real local HTTP requests to a toy decoder and check success and errors.

- Run it in the companion repository (add --quick for a fast pass): `uv run dmxsf run inference/first-inference-service`
- [View the lab script](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/first-inference-service/run.py)
- [Lab write-up](https://github.com/dmxsf/dmxsf/blob/main/labs/inference/first-inference-service/README.en.md)
- [`first_service.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/inference/first_service.py)
- [Find this lab in the catalog](https://dmxsf.com/en/code/#first-inference-service)

## FAQ

### Do I need to download weights?

This example implements deterministic next-token transitions and real loopback HTTP with the Python standard library.

### What does a successful response with no tokens mean?

The input reached a normal stop condition in this example. Interpret the body using the endpoint contract and status.

### Why does the server listen on loopback only?

The standard-library example is for learning the interface. A deployment needs access controls, limits, concurrency, cancellation, and observability.
