본문으로 건너뛰기

P10 — Python for Real AI Services

About 100 min

Optional: real-model track (Levels 12–15). Complete the offline, deterministic Labs and projects without this module if you prefer. P10 adds the Python needed to read l13_mcp_client.py, l13_mcp_server.py, and l14_real_model_serving.py. Start with P8 for local environments and P9 for contracts. If you get every question below right, you can move to the next lesson. This guide and its Lab do not count toward progress.

Quick Check

1. What does await inside an async function do?
2. Which HTTP status indicates a service is not ready?
3. Where should a service token be stored?
4. Can two concurrent requests safely mutate the same dict without coordination?

0 of 4 questions answered.

Goal

Trace asynchronous calls, HTTP requests and handlers, environment-based configuration, synchronization and packaging choices in the optional Level 13 MCP and Level 14 real-serving scripts without mistaking a local service for a production deployment.

1. Read asyncio as a schedule of waiting work (20 minutes)​

An async def defines a coroutine. Calling it produces a coroutine object; await drives it inside an event loop. asyncio.run(main()) starts and closes an event loop in a normal script. async with runs asynchronous setup/cleanup, for example opening/closing an MCP client session.

import asyncio

async def retrieve(label):
await asyncio.sleep(0) # demonstration only: yields to other tasks
return {"source": label}

async def main():
results = await asyncio.gather(retrieve("A"), retrieve("B"))
print(results)

if __name__ == "__main__":
asyncio.run(main())

gather can overlap waiting operations, not magically run CPU-heavy Python work on several cores. Do not call asyncio.run() inside an already running event loop (such as some notebook environments). Never forget to await a coroutine whose result matters. Handle asyncio.TimeoutError and cancellation when real operations may hang.

Reading map: in l13_mcp_client.py, find async def run() → async with Client(mcp, raise_exceptions=True) → await client.list_tools() → await client.call_tool(...) → asyncio.run(run()). The SDK owns transport/session mechanics; your code still checks discovered tool names and result.is_error. In l13_mcp_server.py, identify the tool declaration and its bounded inputs. MCP negotiation is not a grant of broad authorization.

2. HTTP is requests, responses, and failure contracts (20 minutes)​

An HTTP request has a method, path, headers, and optionally a body; a response has a status, headers, and body. With Python's standard library:

import json
import urllib.request

request = urllib.request.Request(
"http://127.0.0.1:8000/health/live",
headers={"Accept": "application/json"},
method="GET",
)
with urllib.request.urlopen(request, timeout=5) as response:
payload = json.load(response)
print(response.status, payload)

Run that snippet only after starting your own trusted local service; nothing in P10 requires a live network. Real clients must use a timeout, restrict URLs/hosts, and distinguish network error, non-2xx HTTP response, and malformed JSON. A local development-only HTTP server can use BaseHTTPRequestHandler with ThreadingHTTPServer. A handler's do_GET chooses routes and writes status/body; do_POST validates a bounded request body before executing any action. Binding to 127.0.0.1 limits exposure to the local machine; do not treat this demo as an authenticated production API.

The browser Lab below will simulate the request/handler boundary without opening a port. To see the real standard-library HTTP server that the Level 14 script builds on, save the next example as health_demo.py and run python health_demo.py from a local terminal. It listens on 127.0.0.1 only, serves fixed data, and needs no model or downloaded package. In a second terminal, run the HTTP client code above; stop the server with Ctrl+C. Do not run this server inside the browser Lab.

import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer

class HealthHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/health/live":
status, data = 200, {"live": True}
elif self.path == "/health/ready":
status, data = 200, {"ready": True}
else:
status, data = 404, {"error": "not_found"}
body = json.dumps(data).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

if __name__ == "__main__":
server = ThreadingHTTPServer(("127.0.0.1", 8000), HealthHandler)
print("Serving at http://127.0.0.1:8000/health/live")
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()

The handler decides the route before writing the status and JSON bytes. If you request an unknown path, you get 404. This is intentionally not an authenticated or production-ready API. Its readiness answer is fixed; the real Level 14 script connects readiness to the model runtime.

Reading map: in l14_real_model_serving.py, follow ThreadingHTTPServer, BaseHTTPRequestHandler, the separate liveness/readiness endpoints, urllib.request client calls, and HTTP 503 for readiness failure. Follow the CLI --openai-base-url to find client-only benchmarking, which does not need model packages in the benchmark process.

3. Environment variables, secrets, and packages (15 minutes)​

import os

base_url = os.environ.get("MODEL_API_BASE", "http://127.0.0.1:8000")
token = os.environ.get("MODEL_API_TOKEN")
if token is None:
print("No API token configured; use only the local unauthenticated demo")

An environment variable is configuration, not a security boundary. Never hardcode credentials in source, commit .env, print tokens into traces, or expose them to the model prompt. Use your OS secret store or deployment secret manager when real credentials are required. Install packages inside a virtual environment, choosing only the dependencies needed for your exercise; pip packages are separate from your own modules. For MCP only, install python -m pip install "mcp>=2,<3"; it needs no model weights. For the HTTP benchmark client pointed at an already running server, Python's standard library is enough. Use the full requirements file only for model-backed scripts. See the optional real-model setup guide for separate commands. Use python -m pip freeze to inspect versions, and pin versions/model revisions for reproducible experiments. P10 needs no new required-course package.

A project can progress from a script to a package with pyproject.toml, an importable module directory, declared dependencies, and a documented CLI entry point. Relative imports and file paths depend on the invocation directory; P8 covers that distinction. Do not package credentials or downloaded weights into a source distribution.

4. Concurrency changes resource ownership (20 minutes)​

asyncio concurrency and OS threads are different tools. The Level 14 fallback HTTP server handles concurrent requests, but ModelRuntime._generation_lock serializes actual model generation. This intentional queue makes throughput and latency tradeoffs observable. It also keeps shared generation state from being driven simultaneously by several requests. A thread lock does not solve every race; use bounded queues/semaphores, limits on request size and generation length, timeouts, and explicit shutdown for a real service.

A readiness check answers "can this worker accept work now?" while liveness answers "is the process still running?" A worker that failed to generate should not keep reporting ready simply because its HTTP port remains open. Streams need a terminal condition and error path: a client disconnect or an exception must not silently report success.

Predict

The server accepts four HTTP requests concurrently but protects generation with one lock. How many generations can run inside that locked section at once?

5. Read the scripts, then experiment safely (25 minutes)​

  1. In l13_mcp_server.py, locate the server, tool decorator, input contract and returned fields. In l13_mcp_client.py, identify each await and the is_error check. The in-process client exercise downloads no model weights.
  2. In l14_real_model_serving.py, find --requests, --concurrency, the lock, /health/live and /health/ready, and the stream error case. Predict how queueing affects first_stream_ms versus whole-request latency.
  3. Run the offline browser Lab below first. Complete an HTTP route handler that returns 200, 503, 404 or 405; then await a fake asynchronous request callback and record responses in order. The callback completes immediately in the test runner, so no event loop, open port, real request or downloaded model is needed. The Lab deliberately uses sequential awaits; the asyncio.gather example above illustrates how independent waiting operations can overlap.
  4. Only if you opt in to the real-model track, use the real-model README, which includes Windows PowerShell setup, per-script commands, storage guidance and failure semantics. Model weights, network access and suitable RAM/disk are required for model-backed scripts.

Before editing the starter, predict the HTTP status for GET /health/ready when ready=False, for POST /health/live, and for GET /missing. The tests also check that your coroutine awaits a fake request function instead of returning an unfinished coroutine.

Loading lab…

Quick Check

1. Why does l13_mcp_client use async with for its SDK client?
2. A health/live endpoint returns 200, but health/ready returns 503. What should a caller conclude?
3. What matters when an asyncio task calls a blocking model.generate directly?
4. Which is an appropriate benchmark comparison?

0 of 4 questions answered.

Key Takeaways

  • async def/await express asynchronous waiting; async with manages async resources.
  • An HTTP server must validate requests and report liveness, readiness, and failures separately.
  • Secrets belong outside source/logs; virtual environments and pinned versions make experiments repeatable.
  • Concurrency needs explicit queues, locks, timeouts, and resource limits.
  • P10 and model downloads are optional, separate from all deterministic course requirements.

Next Lesson

If you choose the optional extension, first run the in-process MCP client, then inspect the Level 14 serving benchmark. You can return to the regular course at any point.