Chapter 58
Multimodal and Tool-Using Systems
On this page
- Native-resolution vision and long video
- An agent is a policy around capabilities
- Long-running agents need durable, testable state
- Worked recovery: the effect committed before the task checkpoint
- Evaluate the model together with its harness
- Prompt injection is a control-flow problem
- Design Exercises
- Worked Solutions
Multimodal and agentic models turn context construction into an active systems boundary: inputs have geometry and time, outputs can invoke capabilities, and untrusted observations can influence irreversible actions.
Native-resolution vision and long video¶
The Qwen2.5-VL technical report connects the representation mechanisms above to document and interface tasks through dynamic resolution, window attention, temporal encoding, and geometric outputs. Its benchmark results are evidence for the evaluated tasks and model sizes; deployment still needs a contract for the actions those outputs can trigger.
For engineers, variable visual resolution makes token count a function of input geometry and preprocessing. Capacity planning must model image area, frame sampling, patching, video duration, visual token compression, text length, and cross-modal attention. A request limit expressed only in text tokens is incomplete.
Document and interface tasks also require geometric output contracts. Bounding boxes, points, table cells, time spans, and actions need coordinate systems, normalization rules, confidence, and provenance. Resize, crop, rotation, frame sampling, and OCR versions must be logged because they can change the answer without changing the model checkpoint.
An agent is a policy around capabilities¶
A production agent contains more than a language model. It has a tool registry, schemas, credentials, planner state, observations, retries, budgets, memory, approval boundaries, and an audit log. Reliability depends on the whole trace:
- interpret the user objective and authority;
- choose a tool under a capability policy;
- validate typed arguments;
- execute with least privilege and idempotency controls;
- label returned data with trust and provenance;
- decide whether another action is justified;
- verify the result against the user's goal.
Evaluate task success together with invalid calls, unnecessary calls, side effects, recovery after tool errors, budget use, latency, and security-policy violations. A benchmark that scores only the final answer can reward unsafe hidden trajectories.
Long-running agents need durable, testable state¶
Current model releases put more weight on completing extended workflows, but a longer context window is not a recovery protocol. Persist the objective, current user constraints, tool-call IDs, authoritative resource versions, execution receipts, pending work, and budgets outside the model. After a restart, reconcile actual external state before replaying a write. A model's recollection that an action succeeded is weaker evidence than the service's receipt.
Preserved reasoning history adds another compatibility boundary. The Kimi K3 usage card requires complete returned assistant messages, including reasoning content and tool calls, to be passed back for multi-turn use. A generic adapter that strips everything except visible text can silently change the supported interaction. Follow the model's contract while applying the application's retention and access policies; raw reasoning history is not a substitute for a compact, authoritative task ledger.
Persistent memory must retain provenance and user scope. A fact extracted from an untrusted page cannot become a higher-priority instruction merely because it was saved in a memory store or summarized. Test revocation, stale facts, contradictory updates, deleted records, and a malicious observation that attempts to survive across sessions. A successful memory retrieval test says little about whether the retrieved material may authorize a side effect.
Worked recovery: the effect committed before the task checkpoint¶
Part VI's examples.durable_effects stores one local effect with its receipt. The companion python -m examples.task_recovery adds a separate persistent task ledger. It records task identity, tenant, operation key, payload, generation, schema version, attempt limit, attempts spent, status and receipt. Its scripted task saves one draft; it does not simulate general model planning.
The failure sequence is deliberately split across two databases. First commit the task's pending intent. Before dispatch, durably charge one effect attempt. Then save the draft and receipt in the effect database. Simulate process failure before marking the task done. On reopening, the task is still pending with one attempt spent, but the effect receipt exists. Recovery checks current host-supplied authority and generation, reads that matching receipt, and marks the task done without a second dispatch. The demo prints status=done attempts=1 drafts=1 even with a one-attempt limit.
If there is no receipt and no remaining attempt, return needs_reconciliation; a crash between charging and dispatch can consume an attempt without creating an effect. This conservative choice prevents restart from resetting the budget. A receipt query is a separate operation: the fixture bounds effect attempts only, while production also needs persistent deadlines and budgets for status reads, model calls and total spend. When another effect attempt is allowed, reuse the original operation key and exact payload.
A changed generation returns stale before dispatch; revoked authorization denies receipt replay; changed task parameters cannot overwrite an existing intent. Unsupported ledger schema versions stop recovery. The fixture assumes one active runner per task. A production scheduler needs leases or fencing and a defined authority/commit ordering when corrections race a dispatch. The separate SQLite databases model the checkpoint gap, but the effect itself remains local and transactional; remote services require their own durable idempotency and reconciliation contract.
Worked check: a task spent its final attempt, the draft committed, and the reply was lost. Must recovery fail or reset the counter? Neither. If current authority permits it, reconcile the existing receipt and finish with the original counter. If authority was revoked, do not expose the receipt through the denied task.
Evaluate the model together with its harness¶
Terminal-Bench 4.0, released in August 2026, recalibrates time/CPU/memory resources, fixes tasks, and removes saturated tasks. Its authors describe an eight-hour task timeout and reduced infrastructure-induced measurement noise. Consequently, a score on 4.0 is not a direct continuation of a 2.1 or 3.0 score, and that evaluation budget is not a product latency guarantee. The published benchmark tracks an agent as well as a model.
Record the task dataset revision, harness, system prompt, tool versions, sandbox resources, network access, retries, model effort, and timeout. Hold those fixed when asking whether a model changed; deliberately vary them when asking which complete system works best. Use task-level paired outcomes and uncertainty intervals. Count invalid or unauthorized actions separately from ordinary task failure, and keep verifiers outside the agent's writable environment. A final correct artifact should not erase an unsafe intermediate action.
An independent reliability example illustrates the horizon problem. If twenty required stages each succeed with probability 0.98 and failures are independent with no recovery, complete-task success is about 0.668. Real errors are often correlated, so this is an explanatory calculation rather than a forecast. Checkpointing, verification, and targeted recovery change the result; simply selecting a model with a slightly higher short-task score does not measure those mechanisms.
Prompt injection is a control-flow problem¶
AgentDojo introduced 97 realistic tasks and 629 security test cases for agents operating over untrusted tool data. These counts describe the published benchmark, not every future repository version. Its evaluation found that agents could fail ordinary tasks even without attacks and that then-current attacks and defenses had uneven coverage. ChatInject, published at ICLR 2026, reports that chat-template and multi-turn payloads substantially increased attack success over traditional prompt injection on AgentDojo and InjecAgent, including against prompt-based defenses.
The engineering conclusion is stronger than "improve the system prompt." Natural-language instructions and retrieved data share a representation, so the model alone should not be the final authorization boundary. Use conventional controls:
- capability-scoped credentials and allowlisted tool identities;
- typed schemas and deterministic validation;
- separation of untrusted content from control metadata;
- information-flow labels for confidentiality and integrity;
- explicit authorization rules and confirmation where the action exceeds the user's existing grant or the product's risk threshold;
- rate, cost, and recursion limits;
- immutable audit logs and replayable security tests.
Information-flow-control research explores planners that track integrity and confidentiality labels and enforce policies independently of the model's textual judgment. The broad lesson is durable even while implementations evolve: authorization belongs in code that can deny an action deterministically.
Deterministic enforcement is only as complete as the boundary it mediates. Sensitive tools must pass through protected enforcement code; labels must survive summarization, saved memory, and delegation; and side channels and tool side effects must be included in the threat model. Enforcing a specified policy does not prove that the policy captures every prohibited outcome. The June 2026 preprint Adaptive Evaluation of Out-of-Band Defenses, version 1, reports a limited Progent reproduction and explicitly declines to establish general adaptive robustness. Test attackers that know the defense and can adapt attempts, while measuring benign task utility as well as unauthorized actions. Passing a fixed injection suite is useful regression evidence, not a security proof.
Tool-using systems need a deterministic policy boundary between model proposals and side effects.
Design Exercises¶
- Define a capacity model for a service accepting text, images, and long video.
- Design idempotency and approval semantics for an agent that can issue refunds.
- Construct a prompt-injection test that distinguishes task failure from security failure.
- What information must an agent trace preserve for replay?
- A benchmark score rose after both a model and the sandbox changed. What can you conclude?
- A refund succeeded, its response was lost, and the user changed the amount before the agent restarted. How should recovery work?
Worked Solutions¶
- Model visual tokens from pixels, patches, crops, and sampled frames; add text and output distributions; separate encoder, prefill, decode, memory, and queue budgets; and preserve workload correlations such as long video with long output.
- Use a user-scoped capability, deterministic refund limits, a stable operation key, read-before-write state checks, preview plus confirmation above a threshold, transactional execution, and a receipt verified against the ledger.
- Record benign task success first, then add untrusted content that requests a policy violation. Score utility and security separately: refusal of the entire task is not a successful defense, while task completion with an unauthorized side effect is a security failure.
- Preserve model and prompt versions, user authority, tool schemas and versions, inputs and outputs with trust labels, RNG and sampling policy where relevant, policy decisions, retries, approvals, side effects, timestamps, and final verification.
- Only that the measured system changed. Rerun paired tasks with fixed harness and resources to isolate the model, or report the full-system gain with all changes disclosed. Scores from different Terminal-Bench versions are not one continuous scale.
- Reconcile the operation ID, receipt, and current resource version with the external service before retrying. Do not replay the completed refund. Treat a changed amount as a new request requiring authority for its exact arguments; an old authorization or idempotency key must not silently authorize a different write.