Examples
Five programs from the engine's repository. Each is tested, plain Python with the standard library only, and shows the output of a real run. Pick one, read it, run it against your own server.
Example 1 of 5
One chat request, then a streamed follow-up carrying the whole conversation, with usage printed for both, including how many prompt tokens came from the prefix cache.
The whole scriptquickstart.py
#!/usr/bin/env python3
"""inferd quickstart: one chat request, one streamed request, and the prefix cache at work.
python3 quickstart.py # server on http://127.0.0.1:8300 (INFERD_URL to change)
Python standard library only.
"""
import json, os, time, urllib.request
URL = os.environ.get("INFERD_URL", "http://127.0.0.1:8300/v1")
def post(path, body):
req = urllib.request.Request(URL + path, json.dumps(body).encode(), {"Content-Type": "application/json"})
return urllib.request.urlopen(req, timeout=600)
model = json.load(urllib.request.urlopen(URL + "/models"))["data"][0]["id"]
print(f"server {URL}, model {model}\n")
# A long-ish system prompt, so the follow-up turn has a visible amount of cached prefix to reuse.
SYSTEM = "You are a concise assistant for a team of Mac developers. " + \
"House rules: answer in at most three sentences; prefer concrete commands; never invent flags. " * 20
# 1. A plain chat request. Thinking off ("effort none"): the answer comes straight back.
t = time.time()
r = json.load(post("/chat/completions", {
"model": model, "max_tokens": 200, "temperature": 0,
"chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "How do I see which process listens on port 8300?"}]}))
print("== 1. chat (non-streaming)")
print(r["choices"][0]["message"]["content"])
print(f"finish_reason={r['choices'][0]['finish_reason']} usage={json.dumps(r['usage'])} {time.time() - t:.2f}s\n")
# 2. A follow-up turn, streamed: the whole conversation so far plus one new question. inferd resumes it from the
# cached end of request 1 (KV blocks + the recurrent-state snapshot), so only the new tokens are prefilled.
# Keep the effort the same: the template writes it into the system message, so a new effort is a new prefix.
print("== 2. follow-up turn, streamed")
t, first, usage = time.time(), None, None
resp = post("/chat/completions", {
"model": model, "max_tokens": 400, "temperature": 0, "stream": True,
"stream_options": {"include_usage": True},
"chat_template_kwargs": {"enable_thinking": False},
"messages": [{"role": "system", "content": SYSTEM},
{"role": "user", "content": "How do I see which process listens on port 8300?"},
r["choices"][0]["message"],
{"role": "user", "content": "And how do I stop it without using pkill -f?"}]})
for line in resp:
line = line.decode().strip()
if not line.startswith("data: ") or line == "data: [DONE]":
continue
ev = json.loads(line[6:])
if ev.get("usage"):
usage = ev["usage"]
for ch in ev.get("choices", []):
d = ch["delta"]
if first is None and (d.get("content") or d.get("reasoning_content")):
first = time.time() - t
if d.get("content"):
print(d["content"], end="", flush=True)
dt = time.time() - t
print(f"\n\ntime to first token {first:.2f}s, total {dt:.2f}s, "
f"{usage['completion_tokens'] / dt:.0f} tok/s")
print(f"usage={json.dumps(usage)}")
print(f"-> {usage['prompt_tokens_details']['cached_tokens']} of {usage['prompt_tokens']} prompt tokens came from "
"the prefix cache (turn 1, in 32-token blocks)")Output of a real runMacBook Pro M5 Max, 1 November 2026
server http://127.0.0.1:8300/v1, model qwen3.8-27b
== 1. chat (non-streaming)
Run `lsof -i :8300` to list the process ID and name bound to that port. If you need the full command line, follow up with `ps -p <PID> -o command`.
finish_reason=stop usage={"prompt_tokens": 404, "completion_tokens": 48, "total_tokens": 452, "prompt_tokens_details": {"cached_tokens": 384}} 1.16s
== 2. follow-up turn, streamed
Run `kill <PID>` using the process ID you found with `lsof -i :8300`. If the process ignores the signal, escalate with `kill -9 <PID>`.
time to first token 0.05s, total 0.59s, 73 tok/s
usage={"prompt_tokens": 478, "completion_tokens": 43, "total_tokens": 521, "prompt_tokens_details": {"cached_tokens": 448}}
-> 448 of 478 prompt tokens came from the prefix cache (turn 1, in 32-token blocks)Run itstandard-library Python, against a running server
python3 quickstart.pyExample 2 of 5
Save a long context once, fork agents from it, park agents on SSD and resume them, and run one-off agents that leave nothing in the cache.
Save a context, then fork agents from itagent_contexts.py, lines 87–110
print(f"1. save a context ({a.doc // 1024}k-token catalogue, effort none, persist {'ssd' if ssd else 'memory'})")
system = f"[{nonce}] You answer questions about this service catalogue, briefly.\n\n" + catalogue(a.doc)
r = call(url, "POST", "/contexts", {"name": cid, "system": system, "effort": "none",
"persist": "ssd" if ssd else "memory"})
if "error" in r:
raise SystemExit(f" failed: {r['error']}")
v = r["variants"][0]
print(f" {r['id']}: {v['tokens']} tokens, computed in {v['prefill_s']} s; {resident(url, cid)}")
print(f"\n2. launch {a.agents} agents from it at once, each with its own task")
out, history = [None] * a.agents, {}
def agent(k):
msgs = [{"role": "user", "content": f"Who is the on-call lead of S-{10 + 7 * k:03d}? One sentence."}]
text, ttft, usage = chat(url, msgs, {"context": cid, "session": agents[k], "effort": "none"})
out[k] = (text, ttft, usage)
history[k] = msgs + [{"role": "assistant", "content": text}]
t0 = time.time()
th = [threading.Thread(target=agent, args=(k,)) for k in range(a.agents)]
[t.start() for t in th]
[t.join() for t in th]
for k, (text, ttft, usage) in enumerate(out):
line(f"agent {k}", text, ttft, usage)
print(f" all {a.agents} answered in {time.time() - t0:.2f} s")Offload it to SSD, park an agent, resume bothagent_contexts.py, lines 122–137
if ssd:
print("\n4. offload the context to SSD, then launch a new agent from it")
call(url, "POST", f"/contexts/{cid}/offload")
print(f" after offload: {resident(url, cid)}")
text, ttft, usage = chat(url, [{"role": "user", "content": "Which team owns S-005? One sentence."}],
{"context": cid, "session": f"agent-{nonce}-new", "effort": "none"})
line("new agent", text, ttft, usage)
print(f" after the launch: {resident(url, cid)}")
print("\n5. park agent 1 (its latest turn goes to SSD), then resume it")
print(" ", call(url, "POST", f"/sessions/{agents[1]}/offload"))
msgs = history[1] + [{"role": "user", "content": "Which team owns that service? One sentence."}]
text, ttft, usage = chat(url, msgs, {"context": cid, "session": agents[1], "effort": "none"})
line("agent 1", text, ttft, usage)
else:
print("\n4-5. skipped: the server has no SSD tier (start it with SPILL_DIR=...)")Output of a real runMac mini M5 Pro (64 GB), Qwen3.8-27B 4-bit with DFlash2, 2 November 2026
1. save a context (8k-token catalogue, effort none, persist ssd)
catalogue-6aefbfa7: 8372 tokens, computed in 18.464 s; pinned=True gpu=True ssd=True (265.1 MiB of KV)
2. launch 4 agents from it at once, each with its own task
agent 0 TTFT 0.51 s prompt 8400 cached 8352 | The on-call lead for service S-010 is Aiko Osei.
agent 1 TTFT 0.51 s prompt 8400 cached 8384 | The on-call lead for service S-017 is Kwame Iyer.
agent 2 TTFT 0.51 s prompt 8400 cached 8384 | The on-call lead for service S-024 is Mei Varga.
agent 3 TTFT 0.51 s prompt 8400 cached 8384 | The on-call lead for service S-031 is Freya Rossi.
all 4 answered in 0.90 s
3. two more turns for agent 0: a long answer, then a question about it (resumes after its own answer)
agent 0 TTFT 0.21 s prompt 8448 cached 8384 | S-002 RB-2408 / S-010 RB-1976 / S-015 RB-8353 / S-030 RB-8053 / S-031
agent 0 TTFT 0.72 s prompt 8712 cached 8448 | The service with the highest number among those listed is S-136, which
4. offload the context to SSD, then launch a new agent from it
after offload: pinned=False gpu=False ssd=True (265.1 MiB of KV)
new agent TTFT 0.18 s prompt 8396 cached 8352 | The Search team owns service S-005.
after the launch: pinned=False gpu=True ssd=True (265.1 MiB of KV)
5. park agent 1 (its latest turn goes to SSD), then resume it
{'id': 'agent-6aefbfa7-1', 'object': 'session', 'offloaded': True}
agent 1 TTFT 0.21 s prompt 8440 cached 8384 | The Messaging team owns service S-017.
6. 20 one-off agents with "cache": "drop"
snapshots 6 -> 6, cached KV blocks 272 -> 272
7. clean up
{'id': 'catalogue-6aefbfa7', 'object': 'context', 'deleted': True}
cache now: 0 snapshots, 0 cached KV blocks, 0 contextsRun itstandard-library Python, against a running server
python3 agent_contexts.py --doc 8192 --agents 4Start the server with an SSD tier (SPILL_DIR=/path/to/ssd/dir) to see the offload and park steps; without one they are skipped.
Example 3 of 5
Four agents on one server, each with its own context cap, reasoning effort and priority. Then two agents break their caps on purpose.
One request with an agent's own policyagent_budgets.py, lines 19–31
def ask(agent, prompt, max_tokens):
"""One request with this agent's policy. -> (status, response JSON or error JSON, seconds)."""
body = {"model": "qwen3.8-27b", "temperature": 0, "max_tokens": max_tokens,
"max_context": agent["max_context"], "priority": agent["priority"],
"chat_template_kwargs": effort(agent["effort"]),
"messages": [{"role": "system", "content": agent["role"]}, {"role": "user", "content": prompt}]}
t = time.time()
req = urllib.request.Request(URL + "/chat/completions", json.dumps(body).encode(),
{"Content-Type": "application/json"})
try:
return 200, json.load(urllib.request.urlopen(req, timeout=900)), time.time() - t
except urllib.error.HTTPError as e:
return e.code, json.load(e), time.time() - tFour agents, four policiesagent_budgets.py, lines 39–50
AGENTS = [ # name, cap on prompt + output, effort, priority (higher = preempted last), task, max_tokens
dict(name="summariser", max_context=16384, effort="none", priority=0, max_tokens=300,
role="You summarise documents in two sentences.", task="Summarise:\n\n" + ARTICLE),
dict(name="coder", max_context=SERVER_MAX, effort="medium", priority=5, max_tokens=8000,
role="You are a senior Python engineer. Reply with one code block and nothing else.",
task="Write a function lru_cache_stats(maxsize) decorator that caches results and exposes "
".hits and .misses attributes on the wrapped function. Include a 3-line usage example."),
dict(name="searcher-1", max_context=8192, effort="none", priority=-5, max_tokens=200,
role="You answer factual questions in one sentence.", task="What is the capital of Australia?"),
dict(name="searcher-2", max_context=8192, effort="low", priority=-5, max_tokens=1000,
role="You answer factual questions in one sentence.", task="Which planet has the shortest day?"),
]Breaking the caps on purposeagent_budgets.py, lines 78–91
# Breaking the caps on purpose.
print("=== over budget")
searcher = AGENTS[2]
status, r, dt = ask(searcher, "Summarise:\n\n" + ARTICLE * 10, 200) # ~10k tokens into an 8k agent
print(f"searcher-1 (max_context 8192) sent a ~10k-token document -> HTTP {status}: "
f"{r['error'].get('code')}: {r['error']['message']}")
tiny = dict(searcher, name="tiny", max_context=120)
status, r, dt = ask(tiny, "Write a 300-word story about a lighthouse.", 2000)
u = r["usage"]
print(f"tiny (max_context 120) asked for 300 words -> HTTP {status}, finish_reason "
f"'{r['choices'][0]['finish_reason']}' after {u['completion_tokens']} tokens "
f"(prompt {u['prompt_tokens']} + output {u['completion_tokens']} = {u['total_tokens']} <= 120)")
print(" ..." + r["choices"][0]["message"]["content"][-120:].replace("\n", " "))Output of a real runMacBook Pro M5 Max, 1 November 2026
4 agents in parallel on http://127.0.0.1:8300/v1
agent max_context effort prio prompt output finish secs
summariser 16384 none 0 1074 62 stop 1.4
coder 32768 medium 5 67 1362 stop 12.7
searcher-1 8192 none -5 32 3 stop 0.6
searcher-2 8192 low -5 56 128 stop 2.4
wall time for all four: 12.7s
--- summariser
Apple Silicon Macs utilize a unified memory pool that allows a 4-bit quantized 27-billion-parameter model to coexist with a large key-value cache. Efficiently serving multiple agents simultaneously requires careful scheduling to maintain individual contexts, batch decoding steps, and avoid redundant re-reading of existing data.
--- coder (reasoned 4223 chars first)Run itstandard-library Python, against a running server
python3 agent_budgets.pyExample 4 of 5
OpenAI's response_format against inferd: validated JSON, retries that send the validation error back to the model, and what a client gets when the model cannot comply.
A schema, and the requeststructured_output.py, lines 27–40
# An invoice extractor's schema, as a pydantic model would emit it ($defs + $ref, additionalProperties false).
INVOICE = {
"$defs": {"Line": {"type": "object", "properties": {
"item": {"type": "string"}, "qty": {"type": "integer", "minimum": 1}, "unit_price": {"type": "number"}},
"required": ["item", "qty", "unit_price"], "additionalProperties": False}},
"type": "object", "properties": {
"number": {"type": "string", "pattern": "^INV-\\d+$"},
"vendor": {"type": "string"},
"currency": {"enum": ["GBP", "EUR", "USD"]},
"lines": {"type": "array", "items": {"$ref": "#/$defs/Line"}, "minItems": 1},
"vat_rate": {"type": "number", "minimum": 0, "maximum": 1}},
"required": ["number", "vendor", "currency", "lines", "vat_rate"], "additionalProperties": False}
EMAIL = ("Hi, please find attached invoice INV-2291 from Acme Ltd: 3 x widget at £4.50, 1 x gadget at £12.00, "
"plus 2 hours of installation at £40/hour. VAT at 20% applies. Thanks, Sam")The same request, with the first answer usedstructured_output.py, lines 61–70
# 1. json_schema: extract an invoice. The content is the JSON itself (no fences, no prose), already validated.
t = time.time()
inv = show("1. json_schema: invoice extraction", *post({
"model": model, "temperature": 0, "max_tokens": 1024, "chat_template_kwargs": NONE,
"messages": [{"role": "user", "content": "Extract the invoice from this email:\n\n" + EMAIL}],
"response_format": {"type": "json_schema", "json_schema": {"name": "invoice", "schema": INVOICE,
"strict": STRICT}}}), t)
if inv:
net = sum(x["qty"] * x["unit_price"] for x in inv["lines"])
print(f" -> net {net:.2f} {inv['currency']}, gross {net * (1 + inv['vat_rate']):.2f} (computed by the client)\n")Output of a real runMacBook Pro M5 Max, 2 November 2026, Qwen3.8-27B 4-bit with the DFlash2 drafter
server http://127.0.0.1:8300/v1, model qwen3.8-27b
== 1. json_schema: invoice extraction
{
"number": "INV-2291",
"vendor": "Acme Ltd",
"currency": "GBP",
"lines": [
{
"item": "widget",
"qty": 3,
"unit_price": 4.5
},
{
"item": "gadget",
"qty": 1,
"unit_price": 12.0
},
{
"item": "installation",
"qty": 2,
"unit_price": 40.0
}
],
"vat_rate": 0.2
}
finish_reason=stop attempts=1 completion_tokens=153 1.22s
-> net 105.50 GBP, gross 126.60 (computed by the client)
== 2. json_object, effort low
{"Apollo 11":1969,"Apollo 12":1969,"Apollo 14":1971,"Apollo 15":1971,"Apollo 16":1972,"Apollo 17":1972}
finish_reason=stop attempts=1 completion_tokens=214 1.65s
== 3. json_schema, streamed
{"label":"mixed","aspects":["battery","support"]}
finish_reason=stop (1 content delta(s), 0.37s)
== 4. retries, then 422 (json_retries 1)
HTTP 422 json_validation_failed: no schema-valid JSON after 2 attempt(s): the JSON does not match the schema: $.history: string is 1194 characters, maximum is 501
last_output: '{"history": "The Roman Empire, established in 27 BC when Augustus became the first emperor, marked the transition from the Roman Republic to a centralized autocratic state. It expanded to encompass mu'Run itstandard-library Python, against a running server
python3 structured_output.pyAdd --strict to ask for constrained decoding.
Example 5 of 5
A small research agent: the model calls a web_search tool (Wikipedia, no API key) until it can answer, on a tight budget: max_context 8192, reasoning effort low.
The tool the model may callweb_search_agent.py, lines 16–20
TOOLS = [{"type": "function", "function": {
"name": "web_search",
"description": "Search Wikipedia. Returns the top results with a short summary of each article.",
"parameters": {"type": "object", "properties": {"query": {"type": "string", "description": "search terms"}},
"required": ["query"]}}}]The loopweb_search_agent.py, lines 53–77
messages = [{"role": "system", "content": "You are a research assistant. Use web_search to check facts before "
"answering. Answer in two or three sentences and name your sources."},
{"role": "user", "content": QUESTION}]
print(f"Q: {QUESTION}\n (max_context {MAX_CONTEXT}, effort {EFFORT})\n")
t0 = time.time()
for step in range(1, MAX_STEPS + 1):
r = chat(messages)
msg, usage = r["choices"][0]["message"], r["usage"]
ctx = f"[context {usage['total_tokens']}/{MAX_CONTEXT}, cached {usage['prompt_tokens_details']['cached_tokens']}]"
if not msg.get("tool_calls"):
print(f"step {step}: final answer {ctx} finish_reason={r['choices'][0]['finish_reason']}\n")
print(msg["content"])
break
print(f"step {step}: model calls {len(msg['tool_calls'])} tool(s) {ctx} finish_reason=tool_calls")
messages.append({"role": "assistant", "content": msg.get("content"), "tool_calls": msg["tool_calls"]})
for call in msg["tool_calls"]:
args = json.loads(call["function"]["arguments"])
print(f" -> {call['function']['name']}({json.dumps(args)})")
result = web_search(**args) if call["function"]["name"] == "web_search" else {"error": "unknown tool"}
shown = result.get("error") or ", ".join(x["title"] for x in result["results"]) or "no results"
print(f" <- {shown}")
messages.append({"role": "tool", "tool_call_id": call["id"], "content": json.dumps(result)})
else:
print(f"stopped after {MAX_STEPS} steps without an answer")
print(f"\n{time.time() - t0:.1f}s total")Output of a real runMacBook Pro M5 Max, 1 November 2026
Q: How tall is the Burj Khalifa, and which building held the title of world's tallest before it?
(max_context 8192, effort low)
step 1: model calls 2 tool(s) [context 460/8192, cached 0] finish_reason=tool_calls
-> web_search({"query": "Burj Khalifa height world's tallest building"})
<- History of the world's tallest buildings, Burj Khalifa, List of tallest buildings
-> web_search({"query": "building world's tallest before Burj Khalifa"})
<- Burj Khalifa, History of the world's tallest buildings, List of tallest residential buildings
step 2: final answer [context 1312/8192, cached 320] finish_reason=stop
The Burj Khalifa in Dubai stands 828 m (2,717 ft) to its roof, making it the world's tallest building since its 2011 inauguration. Before it, the title was held by **Taipei 101** in Taiwan, which had been the record-holder since 2004. (Source: Wikipedia, "Burj Khalifa" and "History of the world's tallest buildings.")
7.5s totalRun itstandard-library Python, against a running server
python3 web_search_agent.py "your question"Keep going