Run a model with an agent

Run a model with an agent

Keep a model where it runs today. A Kaimei agent beside it connects out, takes the work Kaimei has for the model and answers with the real model.

Some models are not run by Kaimei: they are too large for it, they need a GPU, their code is your own, or their weights may not leave your network. An agent is a small loop from the Python client that you start beside the model. It connects out to the API and waits. When a prediction, an explanation or a look inside the model is asked for, the API hands it a job; the agent runs the real model and sends the answer back. Nothing is opened on your side and no weights are uploaded.

Register the model with inference: {"type": "agent"}, its features, task and outputs, as for any other model, then start the agent. Predictions, explanations, analyses and generation of the model are then scored through it. A structure is optional: upload one, even with weights="summary", and the model is drawn as well.

kaimei.agent.serve(client, model, ...)

predictcallableoptional

A function from a list of rows to (rows,) values or (rows, classes) probabilities. A row is {feature: value}: a number, a flag or a category; a list of token ids for text; a float32 NumPy array for a picture (height × width × channels, in the feature's own units), a series or a tensor. predict_with(estimator, feature_names) makes one for a scikit-learn-style estimator or a torch.nn.Module; a classifier without predict_proba answers with its decision_function, marked as the model's own scores.

module / onnxoptional

The model itself, so the agent also answers traces and activations: see looking inside.

tokenizeroptional

The model's tokenizer, so the agent splits text for a model whose tokenizer Kaimei only has the vocabulary of: a Hugging Face tokenizer, a SentencePiece processor, a tiktoken encoding, or any function from a text to its ids. A dict of them by feature for several text features.

label, capabilitiesoptional

What the agent is called on the model's page, and what it answers if not everything it can (predict, trace, activations, tokenize). The model's profile lists what its connected agents offer in agent_capabilities, and offers only the views and methods they can answer.

structureExtraction | dictoptional

The structure that was uploaded (the Extraction, or its spec). The agent then answers only for the steps that structure holds and reads the prediction where its head does: see what an agent sends.

session_memoryintoptionaldefault 2 GiB

With onnx=: how many bytes the ONNX Runtime sessions kept ready between looks inside the model may take. --session-memory MIB from a shell.

serve blocks until Ctrl+C, SIGTERM, or a stop event you pass is set, and closes its session. While no agent is connected, a request for the model answers 502 agent_offline; client.models.agent_status(model) says whether one is. An agent is connected while it asks for work at least every 45 seconds, or is busy with a job. The client's agent works on one job at a time; start several for more. Its API key needs models:write.

A model may have 32 agents connected (429 too_many_agent_sessions) and 32 requests for work waiting (429 too_many_agent_polls), and an organization may register 60 agents an hour on Free, more on paid plans. Closing a session deletes it; a session not heard from in an hour is removed.

An agent belongs to the organization whose key started it. A model transferred to another organization leaves its agents behind: there it has none connected, and the old organization's agents get none of its work and cannot answer for it. Start the agent again with a key of the new organization. A fork is a new model and needs an agent of its own.

from kaimei import Kaimei
from kaimei.agent import predict_with, serve

client = Kaimei()
client.models.create(
    name="Churn (in our VPC)", task="binary_classification",
    features=[{"name": "tenure", "type": "numeric"}, {"name": "seats", "type": "numeric"}],
    outputs={"labels": ["stays", "leaves"]},
    inference={"type": "agent"},
)
serve(client, "churn-in-our-vpc", predict=predict_with(estimator, ["tenure", "seats"]))   # blocks
# KAIMEI_API_KEY (and KAIMEI_BASE_URL when self-hosted) from the environment
python -m kaimei.agent --model churn-in-our-vpc --predict mypackage.scoring:predict
python -m kaimei.agent --model encoder --onnx encoder.onnx --tokenizer mypackage.text:tokenizer
python -m kaimei.agent --model encoder --onnx encoder.onnx \
  --providers CUDAExecutionProvider,CPUExecutionProvider --label gpu-box-1
GET /v1/models/{model}/agentclient.models.agent_status
{
  "object": "model.agent",
  "model_id": "mdl_fe3d094de8e20e090aea",
  "connected": true,
  "capabilities": ["predict"],
  "sessions": [
    {
      "id": "agt_bc9f6510c1a9da7d6b0e",
      "label": "laptop",
      "capabilities": ["predict"],
      "info": {"framework": "sklearn"},
      "created_at": "2026-11-22T19:41:36.571816Z",
      "last_seen_at": "2026-11-22T19:41:36.590933Z"
    }
  ]
}

#Looking inside a model through its agent

An agent that runs the model itself, not a function written around it, also answers trace and activations requests. When the API cannot run the model's structure (it is too large, its weights were sent as a summary, a step has no kernel), the model's page then shows live values all the same: traces and activations come from the agent and say source: "agent", and the profile says live_values: "agent".

Give the agentIt runs the model withWhat it reports
onnx= the model's ONNX file (a path, bytes or an onnx.ModelProto)ONNX Runtime; providers= picks a GPUEvery step of a structure read from that file that the file computes from its input. save_onnx= on the upload writes the file.
module= the torch.nn.ModuleForward hooksA step only where a module's output is that step's: not the arithmetic a forward writes between modules, nor the inside of an attention layer.

Either way the agent sends the model's own output and says so (raw: true), and Kaimei reads it as the structure's head does: scores go through its softmax or sigmoid, and a language model is read at the last token it was given. A predict function of your own is taken to return probabilities, or the value. The file's inputs are fed the obvious way (a table's columns in order, a text's ids and mask, a picture channels first where the file has it so); structure= says how every input is fed, and inputs= says otherwise for the inputs it names (also beside structure=: every other input is still fed as the structure says). An encoder-decoder kept as an ONNX file is read by saying which input is what it has written so far: inputs={"decoder_input_ids": {"generated": True}}.

An agent sends what the model computes, never the model. The structure that names a model's steps is kept on Kaimei, so the agent does not take its word for what a step is. A step is sent only where its values are computed from the row: weights, constants and anything worked out from those alone are left out, whatever the structure calls them, and so is what follows from the input's shape alone (the embedding of each position) or from an input that is the same for every row (a text's segment ids). With onnx= that is read off the file's graph; with module= the run is followed one operation at a time (PyTorch 1.13 or later). A step's values are laid out only in the shape its tensor has. Started with structure=, an agent answers only for the steps that structure holds, which is the setting to use when the weights must stay home (weights="summary"). A step that is kept back is named with its reason under withheld in the agent's answer and once in its log. What stays visible is the model at work: whoever can ask a model for predictions and look inside it sees what its steps compute for the inputs they choose, and from enough such answers a model can be worked out. That comes with answering at all; an agent does not prevent it.

A step the agent keeps back is named in the answer with its reason: the trace and the activations carry withheld, a list of node_id and reason, and the console shows that reason on the step in place of its values.

For this release the same small models were registered twice, once run by the API and once by their agent, and every trace frame, activation stage and prediction compared. With onnx= the agent reported every step computed from the input, and kept back the steps that hold only the model's own numbers (its position embeddings, for example). Everything it sent equalled the API's own run to float32 rounding.

The views that watch a prediction pass through the model (Sight, Attention, Sequence) work with an agent. The ones that rerun the model with parts of it changed (Contrast, Effect, Votes, and silencing a stage) need the API to run the structure. A look inside a very large model through onnx= reads its steps a few hundred at a time, running the model once for each lot, so name the steps you want with nodes. It keeps an ONNX Runtime session for each lot, so the next look is quicker, as far as session_memory= allows (2 GiB unless said): a look that does not fit makes again only the sessions there is no room for, and the session that gives a prediction is always kept.

model = client.models.upload(
    net, name="Encoder", task="binary_classification", sample=ids, tokenizer=tokenizer,
    weights="summary",                 # shapes and statistics: nothing the API could run
    inference={"type": "agent"},
    save_onnx="encoder.onnx",          # the file the structure was read from, written here
)
serve(client, model.id, onnx="encoder.onnx", tokenizer=tokenizer)    # ONNX Runtime
# or: serve(client, model.id, module=net, tokenizer=tokenizer)       # forward hooks

# from anywhere else, while it runs:
trace = client.models.trace_structure(model.id, input={"review": "the film was wonderful"})
print(trace.source)                    # agent

#Jobs, rows and answers

Each thing an agent is asked is a job. Requests for the model make them; the agent takes them with POST …/agent/sessions/{id}/poll and answers with POST …/agent/jobs/{id}/result. The client's agent does both; the agent routes are for writing one of your own.

JobMade byPayload → answer
predictPredictions, explanations, analyses and generation of the model{"rows": [...]} → {"predictions": [[...], ...]}, one list of numbers for each row
trace, activationsTraces and activations, when the API cannot run the structure{"input": row, "nodes": [...], ...} → frames or stages, as the API gives its own, with prediction; an activations job carries the caller's channels and channel_start
tokenizeAny text sent for a model whose tokenizer is pieces{"feature", "text", "max_length"} → {"ids": [...]}: the ids the model reads, special tokens included
  • Rows are checked first. A row is read by the model's features before any job is made, so a wrong input is refused at once. A number, a flag or a category is itself. Text is its token ids, always, split with the model's tokenizer (text written back from ids and split again need not give the same ids). A picture, a series or a tensor is {"$b64": little-endian float32, "dtype": "f32", "shape": [...]}. A job carries about 400,000 numbers at most, so table rows go 64 at a time and pictures one or two, and asks for at most 1,000,000 back: rows are counted by the width of the answer too, so a language model with a vocabulary of 128,256 tokens is sent 7 rows a job.
  • An answer is an upload like any other. It is checked before it is used, and its prediction is named by the API with the model's labels, threshold and units, as POST …/predict names its own. Frames and stages are kept only for steps the structure has, one entry for each, and only the fields the API's own have, so nothing that draws a stage has to tell an agent's from the API's. An answer with more than 60,000 frames or stages is 400 agent_answer_too_large, one with a whole number beyond a float's range 400 invalid_agent_answer; a summary with a negative size makes the request 502 invalid_agent_answer.
  • Raw outputs. With raw: true the numbers are the model's own output, read as the structure's head reads them. With no structure to say, they are read the same way for every row: as the owner declared them (outputs.kind: logits or probabilities), else as the answer says ("link": softmax, sigmoid, or none for probabilities already), else as scores: through a softmax across classes or tokens, and through a sigmoid for each label of a multi-label model. One raw number from a binary model is its second label's, as a structure's head gives it, whichever label is the positive one. The client's agent says none for a model that ends in a softmax or a sigmoid. Running a scikit-learn classifier converted to ONNX, it sends the model's probabilities as they are; a classifier without them (an SVC, an SGDClassifier, a perceptron) gives scores, which are sent so that Kaimei reads from them the class the model predicts: one margin for two classes (its decision_function), the scores for more, or the class itself where the scores do not give it (an SVC of three classes or more decides by votes, which can tie).
  • Nothing is kept. A job holds the rows that were asked about, and its answer. Both are deleted as soon as the answer is read, or when the caller stops waiting, and any job older than 6 minutes is removed; an answer that arrives after that is 404 agent_job_not_found, which an agent notes and moves on from.
  • Waiting. A request waits for the agent's answer up to the model's inference.timeout_s (60 seconds unless set, at most 300), then answers 502 agent_timeout. An agent that says it could not do the work makes it 502 agent_failed, and one that does not answer that kind of job 502 agent_cannot. A waiting request holds no database connection, and each API process lets 16 requests wait for agents at once, 6 of them for one organization's models: past either, a request is 429 agent_busy at once, with Retry-After: 5 and details {limit, scope}, and a background analysis waits for a place instead, up to five minutes. An agent's request for work is held open up to 25 seconds, holds nothing on the server while it waits, and is woken as soon as a job arrives. An agent busy with a job counts as connected for up to 10 minutes.
POST …/agent/sessions/{id}/pollthe job, inside {object: model.agent.work, job}
{
  "id": "job_d5dd998a02d842625ff6",
  "kind": "predict",
  "payload": {
    "rows": [
      {"tenure": 3.0, "seats": 2.0}
    ]
  }
}
POST …/agent/jobs/{id}/resultthe agent's answer
{
  "ok": true,
  "result": {
    "predictions": [[0.31, 0.69]]
  }
}
502 Bad Gatewaya request with no agent connected
{
  "error": {
    "type": "upstream_error",
    "code": "agent_offline",
    "message": "This model is run by an agent in its owner's environment, and no agent is connected. Start one with the Kaimei client: kaimei.agent.serve(...)."
  }
}
429 Too Many RequestsRetry-After: 5
{
  "error": {
    "type": "rate_limit_error",
    "code": "agent_busy",
    "message": "This organization already has 6 requests waiting for its models' agents to answer, as many as may wait at once. Try again in a few seconds.",
    "details": {"limit": 6, "scope": "organization"}
  }
}