▣~/runthismodel▍
local AI explorer00:00:00Z
← Local AI: Zero to Hero

CHAPTER 06 OF 12

Turn the model into an application API

Make bounded requests, validate responses and handle errors.

In this chapter

From a terminal answer to a program

A local API lets an application send structured requests to a running model service. The application should decide which model is allowed, how much input to accept, how long to wait and how to validate the result. The model should not make those operational decisions by producing text that your program blindly executes.

The companion client uses a standard HTTP request with an explicit model, message list, context and output limit. It disables streaming for these small reproducibility labs so the entire response can be saved as one JSON object. A chat interface can stream instead, but must handle partial chunks, cancellation and a final completion signal. A disconnected stream should not be displayed as a complete answer.

Transport success and task success are separate. A 200 response may contain a wrong deadline. Conversely, a connection failure tells you nothing about model quality. Keep the two categories separate in logs and metrics.

Understand the request contract

The important fields are the model name, messages, streaming choice and runtime options. The response contains generated content and timing metadata. Client wall time includes more work than a token decoding measurement. Do not compare one model's wall time with another model's decoding rate and call that a fair speed result.

A structured output schema can help your parser by constraining the shape of the generated text. It does not prove that a date, citation or calculation is correct. Validate the parsed object, then apply the task rubric. Bound response handling and treat missing or unexpected fields as errors.

Prerequisites

Keep the local server from chapter 4 running and use the extracted companion directory. Python's standard library is sufficient for this lab. The client accepts only an HTTP loopback address; a remote machine requires the explicit tunnel described in chapter 9.

Steps

  1. Run the same extraction through the companion API client:

python3 rtm_lab.py extract --output api-response.json
  1. Open rtm_lab.py and find Client.chat. Follow the request from the message array through the HTTP call to the saved raw response. Notice the timeout and the completion check.

  2. Inspect the fields without printing an entire large report:

python3 - <<'PY'
import json
report = json.load(open('api-response.json'))
run = report['results']['extract']
print('Answer:', run['response'])
print('Task passed:', run['passed'])
print('Wall seconds:', run['wallSeconds'])
print('Output tokens:', run['raw']['eval_count'])
PY
  1. Stop only your lab server with Control-C, then rerun the extraction. Observe the connection error. Restart the same server before continuing.

  2. Change the application around this request, rather than copying runtime internals into every feature. A small wrapper is a useful place for timeouts, allowed-model checks, validation and redacted metrics.

Expected results

With the server running, the report contains an actual answer and runtime metadata. With it stopped, the request fails visibly; the companion client does not switch to a cloud endpoint. The stopped-server exercise is a procedure for you to perform, not a failure scenario measured in this edition's automated report.

Common failures

A client pointed at port 11434 will not talk to the lab server on 11435. Ambient HTTP proxies can misroute local requests; the companion uses a direct loopback opener. A request without an output bound can take far longer than intended. Retrying every failure immediately can amplify a busy server; production clients need bounded retries and clear handling of timeouts and cancellations.

Do not put unrestricted model management, file access or shell execution behind the same public endpoint as a chat box. The teaching gateway later exposes only a bounded answer request and health check.

Exercise

Write a small program that reads a fictional note, calls the client and stores a validated deadline with the model digest. Return a clear error if the answer violates the rubric. Then explain what your application should do when the runtime is unavailable.

Sources

Ollama's chat API defines request and response fields. This chapter's timeout and validation choices are application design decisions demonstrated by the companion implementation.