Agent Build智能体搭建 Tutor教程
Map地图 / Module模块 1 / labs/m01_*

Inference engineering推理工程

Serve models on fixed hardware and know what each second costs.在固定硬件上部署模型,并弄清每一秒花在哪里。

What it is and why it exists它是什么,为什么需要它

What是什么

Inference engineering turns model weights into a dependable endpoint. You decide which models run, how they share memory, how long they stay loaded, how many requests run at once, and how much context each request may use.推理工程把模型权重变成一个可靠的服务端点。你要决定运行哪些模型、它们如何共享内存、空闲多久后卸载、同时处理多少请求,以及每个请求可以使用多少上下文。

Why为什么

Every other layer calls this one. Retrieval calls it to embed. The harness calls it to plan and to answer. The evaluator calls it to judge. If one call takes 70 seconds because a model was evicted, no prompt change above it will fix that.其他每一层都要调用这一层。检索用它做向量化,Harness 用它做规划和回答,评估用它做裁判。如果因为模型被换出内存,一次调用要 70 秒,上层怎么改提示词都没用。

How it works工作原理

Where it sits in the build order它在搭建顺序中的位置

Needs first前置模块

Nothing. You can start here.没有。可以从这里开始。

Unlocks解锁

  • API and gatewayAPI 与网关A gateway forwards to an engine. Its timeouts and limits are set from measured load times and generation rates.网关要把请求转发给引擎。它的超时和限额根据测得的加载时间和生成速率来设定。
  • RAG and knowledge graphRAG 与知识图谱Search needs an embedding call at index time and at query time. The vector width is fixed by that model, so the model choice comes first.索引和查询时都需要调用 embedding。向量维度由该模型决定,所以要先选定模型。
  • Harness engineeringHarness 工程The planner is a model call. Round budgets and output caps are set from measured rates.规划节点就是一次模型调用。轮次预算和输出上限根据测得的速率设定。
  • Operations and deployment运维与部署The engine is the first service to supervise, and its memory limits decide what may run at the same time.引擎是第一个需要守护的服务,它的内存上限决定了哪些东西可以同时运行。

In the reference build在参考系统中

Path路径Role作用
ollama-env.shServing settings: loaded-model cap, keep-alive, parallelism, context length.服务参数:驻留模型上限、keep-alive、并发数、上下文长度。
apps/agent-server/model_router.pyPicks a model per request. Two mechanisms: tag swap and base-URL swap.为每个请求选模型。两种机制:换 tag 和换 base URL。
apps/agent-server/model_catalog.jsonThe lineup: which model serves default, fast, and vision work.模型阵容:哪个模型负责默认、快速、视觉任务。
apps/agent-server/bench_latency.pyMeasures time to first token and tokens per second from real requests.从真实请求测量首 token 时间和每秒 token 数。

Process map流程图

What happens to one request at the engine一个请求在引擎里经历了什么

  1. 1
    Request arrives请求到达OpenAI-style JSON with a model name, messages, and max tokens.OpenAI 格式的 JSON,包含模型名、消息和最大 token 数。
  2. 2
    Is the model resident?模型在内存里吗?If yes, go to prompt evaluation. If no, the engine must load it and may evict another.在,就直接处理提示词。不在,引擎必须先加载,可能要换出别的模型。
  3. 3
    Cold load冷加载Tens of seconds for a 20 to 60 GB model. The largest avoidable cost.20 到 60 GB 的模型需要几十秒。这是最大的可避免开销。
  4. 4
    Prompt evaluation处理提示词Cost grows with prompt size. Tool schemas and system prompts count on every turn.开销随提示词长度增长。工具 schema 和系统提示词每一轮都要计入。
  5. 5
    Generation生成Output tokens at a steady rate. Time is tokens divided by rate.以稳定速率输出 token。时间等于 token 数除以速率。
  6. 6
    Stream out流式输出Tokens leave as they are produced, so the first one arrives early.token 一边生成一边发出,所以第一个 token 很早就到。

Build steps搭建步骤

Follow them in order the first time. Each step names what it uses from earlier steps and what it leaves for later ones. Code is read from the lab files, and output is what the lab printed when it was run.第一次请按顺序做。每一步都写明它用到前面步骤的什么成果,又为后面的步骤留下什么。代码直接读取自 lab 文件,输出是 lab 实际运行时打印的内容。

  1. 1Write the memory budget before you choose models先写内存预算,再选模型
  2. 2Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上
  3. 3Set the serving parameters on purpose有意识地设定服务参数
  4. 4Call the endpoint the way every later layer will用后续各层都会用的方式调用端点
  5. 5Write one client function and use it everywhere写一个客户端函数,全系统共用
  6. 6Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
  7. 7Add a second runtime only where it earns its place只在值得的地方增加第二个运行时
  8. 8Route by task type, and fail safe按任务类型路由,并且失败时不出错
  9. 9Cut latency where it is actually spent在真正耗时的地方降低延迟
  10. 10Keep the engine private让引擎保持私有
01Write the memory budget before you choose models先写内存预算,再选模型
Why this step is here为什么这一步排在这里The budget decides the lineup. A lineup chosen first often cannot be resident together, and you find out in production as reload delays.预算决定阵容。先选模型的话,常常发现它们无法同时驻留,而且是在生产环境里通过加载延迟才发现。
Uses用到Nothing from earlier steps.不依赖之前的任何步骤。

Do this操作

  1. Find usable model memory: unified memory minus the OS and your services on Apple silicon, or VRAM per card on a GPU server.算出可用于模型的内存:Apple 芯片是统一内存减去系统和服务占用;GPU 服务器是每张卡的显存。
  2. For each candidate, write its resident size: weights at your quantization plus headroom for context.为每个候选模型写下驻留大小:所选量化精度下的权重,加上上下文的余量。
  3. Run the lab with your own numbers. Read which pairs fit and what each cold load costs.把你自己的数字填进 lab 运行。看哪些组合能同时驻留,以及每个模型冷加载要多久。
  4. Decide which models must be warm together. That pair is your default path.决定哪些模型必须同时保持热状态。这一对就是你的默认路径。
labs/m01_inference/budget.py · budget
def plan(usable_gb: float, models: dict, load_gb_per_s: float = 1.5) -> dict:
    """models maps name -> resident size in GB (weights plus context headroom)."""
    fits_alone = {m: size <= usable_gb for m, size in models.items()}
    pairs = {}
    for a, b in combinations(models, 2):
        total = models[a] + models[b]
        pairs[(a, b)] = {"total_gb": round(total, 1), "fits": total <= usable_gb}
    cold_load_s = {m: round(size / load_gb_per_s) for m, size in models.items()}
    return {"fits_alone": fits_alone, "pairs": pairs, "cold_load_s": cold_load_s}
run
python3 -m labs.m01_inference.budget
Recorded output / 记录的输出 · m01.budget
usable 77.8 GB
  workhorse-35b  + vision-27b     =  51.3 GB  fits
  workhorse-35b  + reasoner-120b  =  83.2 GB  DOES NOT FIT
  workhorse-35b  + embedder       =  22.6 GB  fits
  vision-27b     + reasoner-120b  =  89.9 GB  DOES NOT FIT
  vision-27b     + embedder       =  29.3 GB  fits
  reasoner-120b  + embedder       =  61.2 GB  fits
cold load estimate (s): {'workhorse-35b': 15, 'vision-27b': 19, 'reasoner-120b': 41, 'embedder': 0}
You are done when完成标志For any two models you can say whether they fit together and what a swap costs in seconds.对任意两个模型,你都能说出它们能否共存,以及切换一次要多少秒。
Produces产出A budget table: sizes, pairs that fit, cold-load cost.一张预算表:大小、可共存的组合、冷加载耗时。
02Install the engine and put weights on a dedicated volume安装引擎,把权重放到专用卷上Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里It follows the budget because you now know which models to pull. Weights are large and reproducible, so they live apart from the boot disk and from backups.它排在预算之后,因为现在才知道该下载哪些模型。权重很大且可以重新下载,所以要和系统盘、备份分开存放。

Do this操作

  1. Install the engine with your package manager.用包管理器安装引擎。
  2. Set the model directory to the data volume before the first pull.第一次拉取模型之前,把模型目录指向数据卷。
  3. Pull the workhorse model and the embedding model from your budget.按预算拉取主力模型和 embedding 模型。
bash
brew install ollama                      # Linux: curl -fsSL https://ollama.com/install.sh | sh
export AI_DATA=/Volumes/DATA             # your data volume
export OLLAMA_MODELS="$AI_DATA/models/ollama"
ollama serve &
ollama pull <workhorse-model>
ollama pull nomic-embed-text
ollama list

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志`ollama list` shows both models and the files sit under your data volume.`ollama list` 列出两个模型,文件位于数据卷下。
Produces产出A running engine with models on the data volume.一个运行中的引擎,模型存放在数据卷上。
03Set the serving parameters on purpose有意识地设定服务参数Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里Defaults assume one user and one model. An agent makes many calls per question, so defaults cause evictions and queueing that look like a slow model.默认值假设只有一个用户、一个模型。智能体每回答一个问题要调用很多次,默认值会导致模型被换出和排队,看起来像模型慢。

Do this操作

  1. Cap loaded models at what the budget allows.把驻留模型上限设为预算允许的数量。
  2. Set keep-alive longer than the normal gap between requests.把 keep-alive 设得比请求之间的正常间隔更长。
  3. Set parallel slots to the concurrency you expect. Each slot reserves context memory.按预期并发设定并行槽位。每个槽位都会预留上下文内存。
  4. Set context length explicitly, send one request, and read the engine log to confirm the real prompt size.明确设定上下文长度,发一个请求,然后读引擎日志确认真实的提示词大小。
ollama-env.sh
export OLLAMA_MAX_LOADED_MODELS=2   # at most 2 models resident
export OLLAMA_KEEP_ALIVE=30m        # unload after 30 idle minutes
export OLLAMA_NUM_PARALLEL=4        # concurrent requests per model
export OLLAMA_CONTEXT_LENGTH=49152  # tokens of context per slot
export OLLAMA_FLASH_ATTENTION=1     # less memory for long contexts

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志The engine log line for your request reports the prompt size you expect.引擎日志里该请求的提示词大小与你的预期一致。
Produces产出An environment file that every start script sources.一个环境变量文件,所有启动脚本都引用它。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
04Call the endpoint the way every later layer will用后续各层都会用的方式调用端点Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里The OpenAI-compatible chat endpoint is the contract for the whole stack. Fix it now and you can swap engines, machines, or providers later by changing a URL.OpenAI 兼容的 chat 接口是整个系统的契约。现在把它定下来,以后换引擎、换机器、换供应商都只需要改一个 URL。

Do this操作

  1. Call the endpoint with curl before adding any library.在引入任何库之前,先用 curl 调用端点。
  2. Confirm the response has `choices` and a `usage` block.确认响应里有 `choices` 和 `usage` 字段。
  3. Export `LAB_BASE_URL` and `LAB_MODEL`. Every lab from here on uses your real model when these are set.导出 `LAB_BASE_URL` 和 `LAB_MODEL`。设置之后,后面所有 lab 都会使用你的真实模型。
bash
curl -s http://127.0.0.1:11434/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{"model": "<workhorse-model>",
       "messages": [{"role": "user", "content": "Reply with the word ready."}],
       "max_tokens": 16}' | python3 -m json.tool

export LAB_BASE_URL=http://127.0.0.1:11434/v1
export LAB_MODEL=<workhorse-model>

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志You get a JSON completion. Unset the two variables and the labs fall back to the fake model.你得到一个 JSON 回复。取消这两个变量后,lab 会退回到假模型。
Produces产出A verified base URL and model name. This is what every later module calls.一个验证过的 base URL 和模型名。后面每个模块都调用它。
05Write one client function and use it everywhere写一个客户端函数,全系统共用
Why this step is here为什么这一步排在这里It comes right after the contract because it is the contract in code. One function means one place to change the URL, the timeout, or the provider.它紧跟在契约之后,因为它就是契约的代码形式。只有一个函数,改 URL、超时或供应商时就只需改一处。

Do this操作

  1. Read the function below. It returns the same response shape from a real endpoint or from the fake model.阅读下面的函数。无论调用真实端点还是假模型,它返回的响应结构都相同。
  2. Note what the fake model is: a deterministic test double. It proves plumbing and nothing about quality.注意假模型是什么:一个确定性的测试替身。它只能证明管道通了,证明不了质量。
labs/common/llm.py · chat
def chat(messages: list, tools: Optional[list] = None, model: Optional[str] = None,
         max_tokens: int = 512, policy: Optional[Policy] = None) -> dict:
    """Send messages, get an OpenAI-shaped completion back."""
    base = os.environ.get("LAB_BASE_URL", "").rstrip("/")
    if not base:
        message = (policy or default_policy)(messages, tools)
        return _wrap(message, messages)
    body = {"model": model or os.environ.get("LAB_MODEL", ""), "messages": messages,
            "max_tokens": max_tokens, "stream": False}
    if tools:
        body["tools"] = tools
    req = urllib.request.Request(
        base + "/chat/completions", data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json",
                 "Authorization": "Bearer " + os.environ.get("LAB_API_KEY", "none")})
    with urllib.request.urlopen(req, timeout=float(os.environ.get("LAB_TIMEOUT", "180"))) as r:
        return json.loads(r.read())
You are done when完成标志You can explain what changes when `LAB_BASE_URL` is set, and what does not.你能解释设置 `LAB_BASE_URL` 后什么变了、什么没变。
Produces产出`chat()` and `embed()`: the only model calls in the stack.`chat()` 和 `embed()`:全系统唯一的模型调用入口。
06Measure time to first token and tokens per second测量首 token 时间和每秒 token 数
Why this step is here为什么这一步排在这里Measure before tuning. These two numbers explain almost every latency complaint, and each has a different fix.先测量再优化。这两个数字能解释几乎所有延迟问题,而且各自的解法不同。

Do this操作

  1. Run the bench twice in a row against your endpoint.对你的端点连续运行两次基准测试。
  2. Compare the first call with the second. A large gap in time to first token is a cold load.对比第一次和第二次。首 token 时间差距大,就是冷加载。
  3. Check that total time is close to first-token time plus tokens divided by rate.检查总时间是否接近 首 token 时间 + token 数 ÷ 速率。
labs/m01_inference/bench.py · bench
def bench_stream(base_url: str, model: str, prompt: str, max_tokens: int = 200) -> dict:
    """Stream one completion and time it. Works against any OpenAI-compatible server."""
    body = json.dumps({"model": model, "stream": True, "max_tokens": max_tokens,
                       "messages": [{"role": "user", "content": prompt}]}).encode()
    req = urllib.request.Request(base_url.rstrip("/") + "/chat/completions", data=body,
                                 headers={"Content-Type": "application/json",
                                          "Authorization": "Bearer " + os.environ.get("LAB_API_KEY", "none")})
    t0 = time.time()
    first = None
    pieces = 0
    with urllib.request.urlopen(req, timeout=600) as resp:
        for raw in resp:
            line = raw.decode().strip()
            if not line.startswith("data:") or line.endswith("[DONE]"):
                continue
            delta = json.loads(line[5:])["choices"][0].get("delta", {})
            if delta.get("content"):
                first = first or time.time()
                pieces += 1                      # one streamed piece is roughly one token
    end = time.time()
    gen = max(end - (first or end), 1e-6)
    return {"ttft_s": round((first or end) - t0, 2), "total_s": round(end - t0, 2),
            "tokens": pieces, "tok_per_s": round(pieces / gen, 1)}
run
python3 -m labs.m01_inference.bench
Recorded output / 记录的输出 · m01.bench
no LAB_BASE_URL set, showing a worked example with fixed numbers
cold : first token after 41.2 s, 200 tokens at 72.0 tok/s, total 43.98 s. Predicted total = ttft + tokens / rate = 43.98 s
warm : first token after 0.6 s, 200 tokens at 72.0 tok/s, total 3.38 s. Predicted total = ttft + tokens / rate = 3.38 s
same model, same rate. The 40 s difference is the cold load.
You are done when完成标志You have a tok/s figure and a warm first-token time for each model in the lineup.阵容里每个模型都有了 token/秒 和热状态下的首 token 时间。
Produces产出Per-model rate and first-token numbers. Round budgets and timeouts are set from these.每个模型的速率和首 token 数据。轮次预算和超时都据此设定。
07Add a second runtime only where it earns its place只在值得的地方增加第二个运行时Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里A small fast model handles cheap jobs such as triage, question writing, and judging. It must not compete with the workhorse for a resident slot, which is why it comes after the budget and the measurements.小而快的模型处理分流、出题、裁判这类便宜的任务。它不能和主力模型抢驻留名额,所以要在预算和测量之后再加。

Do this操作

  1. Start the small model in its own process on its own port.在独立进程、独立端口上启动小模型。
  2. Note the difference: this runtime serves one model per process, so you select it by URL and not by model name.注意区别:这个运行时一个进程只服务一个模型,所以靠 URL 来选它,而不是靠模型名。
bash
# Apple silicon. One process, one model, its own port.
mlx_lm.server --model mlx-community/<small-model>-4bit --port 8082
# NVIDIA: vllm serve <model> --port 8082

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志The curl from the contract step works against the second port.契约那一步的 curl 命令在第二个端口上也能用。
Produces产出A second base URL for fast, cheap calls.第二个 base URL,用于快速、便宜的调用。
08Route by task type, and fail safe按任务类型路由,并且失败时不出错
Why this step is here为什么这一步排在这里Routing comes after the endpoints exist and are measured. A router over unmeasured models sends work to the wrong place with confidence.路由要等端点都存在并测量过之后再做。对没测过的模型做路由,只会自信地把任务送错地方。

Do this操作

  1. Classify each request: default, fast, or vision.给每个请求分类:默认、快速、视觉。
  2. Map the class to a catalog entry. An entry has either a model tag or a base URL.把类别映射到目录条目。条目要么是模型 tag,要么是 base URL。
  3. On anything unknown, missing, or failing, return nothing so the request runs as it would have.遇到未知、缺失或出错的情况,返回空值,让请求按原样执行。
labs/m01_inference/router.py · router
def resolve_for_request(payload: dict, catalog: Optional[dict] = None) -> Optional[dict]:
    """Return {'model': tag} or {'base_url': url}, or None to leave the request untouched."""
    try:
        if payload.get("model"):                 # the caller chose: do nothing
            return None
        entry = (CATALOG if catalog is None else catalog).get(detect_task(payload))
        if not entry:
            return None                          # unknown task: do nothing
        if entry.get("base_url"):
            return {"base_url": entry["base_url"]}
        if entry.get("tag"):
            return {"model": entry["tag"]}
        return None                              # incomplete entry: do nothing
    except Exception:
        return None                              # any error: do nothing
run
python3 -m labs.m01_inference.router
Recorded output / 记录的输出 · m01.router
text    -> {'model': 'workhorse-35b'}
image   -> {'model': 'vision-27b'}
short   -> {'base_url': 'http://127.0.0.1:8082/v1'}
explicit-> None
no catalog -> None
You are done when完成标志With an empty catalog the router returns None and a request still succeeds.目录为空时路由返回 None,请求依然成功。
Produces产出`resolve_for_request()`: called by the gateway before forwarding.`resolve_for_request()`:网关转发前调用它。
09Cut latency where it is actually spent在真正耗时的地方降低延迟Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里This needs logs from real requests, so it comes after measurement. Tuning earlier usually targets model speed, which is rarely the problem.这一步需要真实请求的日志,所以排在测量之后。过早优化往往盯着模型速度,而那很少是问题所在。

Do this操作

  1. Set a default max-tokens value and ask for shorter answers in the system prompt. Output volume dominates.设一个默认的 max_tokens,并在系统提示词里要求简短回答。输出量是主要因素。
  2. Stream responses and reuse one pooled HTTP client.使用流式响应,并复用一个 HTTP 连接池。
  3. Keep prompts small. Tool schemas, the system prompt, and memory are charged on every turn.保持提示词精简。工具 schema、系统提示词和记忆每一轮都要计费。
  4. List every model your request path can load, including the embedder. Remove avoidable loads.列出请求路径上可能加载的所有模型,包括 embedding 模型。去掉可以避免的加载。

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志Median latency in your own request log moves, and the engine log shows fewer cold loads.你自己的请求日志里中位延迟下降,引擎日志里冷加载次数减少。
Produces产出Default output cap and keep-alive values used by the harness.Harness 使用的默认输出上限和 keep-alive 值。
Feeds供给No later step consumes this directly.没有后续步骤直接使用它。
10Keep the engine private让引擎保持私有Not executed in the labslab 中未执行
Why this step is here为什么这一步排在这里The engine has no authentication. Anything outside your machine must go through the gateway, which is the next module.引擎本身没有身份验证。机器外部的任何访问都必须经过网关,也就是下一个模块。

Do this操作

  1. Bind the engine to localhost or a private network interface.把引擎绑定到 localhost 或私有网络接口。
  2. From another device on a different network, confirm the engine port does not answer.从另一个网络的设备上确认引擎端口没有响应。

This step describes work on your own machine or account. Its commands were not run when the labs were tested.这一步描述的是在你自己的机器或账号上的操作。测试 lab 时没有运行这些命令。

Checked on the reference machine在参考机器上的检查结果Not checked on a machine yet. On your own machine run the command below. It only reads, and it writes the result here when you add --write.还没有在机器上检查过。在你自己的机器上运行下面的命令。它只做读取操作;加上 --write 后会把结果写到这里。
run
python3 labs/machine/check.py --write
You are done when完成标志The engine answers on 127.0.0.1 and nowhere else.引擎只在 127.0.0.1 上响应。
Produces产出A rule: the only public door is the gateway.一条规则:唯一对外的门是网关。
Feeds供给

How it works with the other parts它如何与其他部分协作

What went wrong in the real build真实搭建中踩过的坑

2026-08

A context setting that was present but not in effect配置写了,但没有生效

What happened发生了什么
A context cap was configured for a coding client. Requests still sent far larger prompts and timed out after 15 minutes.给编程客户端配置了上下文上限,但请求仍然发送大得多的提示词,15 分钟后超时。
Fix修复
Read the engine log for the real prompt size on each request before touching anything else.先读引擎日志里每个请求的真实提示词大小,再动别的。
Lesson教训
A configured value is a claim. The log line is the evidence.配置值只是声明,日志才是证据。
2026-09

The embedder evicted the chat modelembedding 模型挤掉了聊天模型

What happened发生了什么
With a cap of two resident models, a knowledge search loaded the embedding model and pushed the chat model out. The next answer paid a 35 to 70 second reload.驻留上限为两个模型时,一次知识检索加载了 embedding 模型,把聊天模型挤了出去。下一次回答要等 35 到 70 秒重新加载。
Fix修复
Route definition questions to a full-text lookup that loads no model.把定义类问题路由到不加载任何模型的全文检索。
Lesson教训
Count every model your request path can load, including the small ones.把请求路径上可能加载的每个模型都算进去,小模型也算。
2026-07

Latency blamed on model speed把延迟归咎于模型速度

What happened发生了什么
Median latency was 26 seconds and p90 was 89 seconds. The generation rate was a healthy 72 tokens per second.中位延迟 26 秒,p90 为 89 秒。而生成速率是正常的 72 token/秒。
Fix修复
Cap default output tokens, stream, and extend keep-alive.限制默认输出 token 数,使用流式,延长 keep-alive。
Lesson教训
Latency is tokens divided by rate. Check the numerator first.延迟等于 token 数除以速率。先检查分子。

The same idea on other platforms同样的思路在其他平台上

Platform平台How this module maps本模块如何对应
DatabricksHosted model endpoints replace the engine, and Unity Gateway (formerly AI Gateway) gives one API across models. Your memory budget becomes a throughput and cost budget. The endpoint is OpenAI-compatible, so the contract step carries over.托管的模型端点取代引擎,Unity Gateway(原 AI Gateway)用一套 API 访问各种模型。内存预算变成吞吐量和成本预算。端点兼容 OpenAI,所以契约那一步原样适用。
IBM watsonxwatsonx.ai hosts foundation models behind an inference API, with on-demand deployments for dedicated capacity. Model choice is a catalog decision. You still measure rate and first-token time per model.watsonx.ai 通过推理 API 托管基础模型,并可按需部署专用容量。选模型变成在目录里做选择。你仍然要逐个模型测量速率和首 token 时间。
CodexCodex is a client of an inference endpoint. It uses hosted models by default and can be pointed at another provider in its config, including a local OpenAI-compatible server.Codex 是推理端点的客户端。默认使用托管模型,也可以在配置里指向其他供应商,包括本地的 OpenAI 兼容服务。
CursorCursor consumes inference. It can override the OpenAI base URL to reach your own endpoint for some features. Serving decisions are made wherever that endpoint runs.Cursor 是推理的使用方。部分功能可以覆盖 OpenAI base URL 来访问你自己的端点。服务层面的决策在端点所在的地方做。
Claude Code / Agent SDKClaude Code and the Agent SDK call a hosted model, or a compatible gateway you configure. Context budgets still apply and are charged on every turn.Claude Code 和 Agent SDK 调用托管模型,或你配置的兼容网关。上下文预算依然存在,而且每一轮都计费。
Another machineOn an NVIDIA machine use vLLM or llama.cpp in place of the Mac runtimes. The budget is VRAM per card. Use systemd in place of launchd. Every step from the contract onward is identical.在 NVIDIA 机器上用 vLLM 或 llama.cpp 代替 Mac 上的运行时。预算是每张卡的显存。用 systemd 代替 launchd。从契约那一步开始,其余完全相同。

Step-by-step guides per platform各平台的分步指南

Explain it back讲给自己听

Answer aloud first. Then open the answer and compare.先自己说一遍答案,再展开对照。

Why does the memory budget come before model selection?为什么内存预算要排在选模型之前?
A strong answer参考答案Residency is what makes responses fast, and residency is limited by memory. A lineup chosen without the budget can require a model swap on a common path, and each swap costs tens of seconds to minutes.模型驻留才能让响应快,而驻留受内存限制。不看预算就选阵容,可能在常用路径上就需要切换模型,每次切换要几十秒到几分钟。
A request is slow. What do you look at first, and why?一个请求很慢。你先看什么?为什么?
A strong answer参考答案The engine log for that request: whether a model was loaded, the real prompt size, and the output token count. Those three explain almost all latency, and each has a different fix.该请求的引擎日志:是否加载了模型、真实提示词大小、输出 token 数。这三项能解释几乎所有延迟,而且各自的解法不同。
Why are there two routing mechanisms?为什么有两种路由机制?
A strong answer参考答案The main engine serves many models on one port and selects by the model field. The second runtime serves one model per process and has no model selection, so reaching it means calling a different base URL.主引擎在一个端口上服务多个模型,靠 model 字段选择。第二个运行时一个进程只服务一个模型,没有模型选择,所以要访问它只能换 base URL。
You want to build retrieval before this module. What do you stub?你想在这个模块之前先做检索。需要用什么替代?
A strong answer参考答案The embedding call. Any function that returns a fixed-length vector for a string lets you build and test ingestion and search plumbing. The labs ship one. You replace it with the real embedder later.替代 embedding 调用。任何能把字符串变成定长向量的函数,都足以让你搭建并测试入库和检索的管道。lab 里自带一个。之后再换成真正的 embedding 模型。

Terms术语

Resident驻留Loaded in memory and ready to generate without a load delay.已加载在内存中,无需等待加载即可生成。
Keep-aliveKeep-aliveHow long an idle model stays resident before the engine unloads it.空闲模型在被引擎卸载前保持驻留的时长。
TTFTTTFT(首 token 时间)Time to first token. What the user feels as responsiveness.从请求到第一个 token 的时间。用户感受到的响应速度。
Quantization量化Storing weights at lower precision to cut memory, with some quality cost.用更低精度存储权重以节省内存,会损失一些质量。

From the live build来自实时构建

Recent changes and files the sync job filed under this module. These lines are in English as written in the build.同步任务归到本模块下的近期变更和文件。这些内容保留了构建系统中的英文原文。

Ask the tutor about this module就本模块向导师提问