Skip to main content

Module tool_loop

Module tool_loop 

Source
Available on crate feature tool-loop only.
Expand description

Tool calling: a model, the tools it may call, and the bounded loop between them, run as an A2A task (ADR 0022; feature tool-loop).

A2A has no tool concept. It carries messages, tasks and artifacts between agents; tool calling happens inside one task, between the executor and its model. This module is that layer:

 A2A client ──SendMessage──→ ToolLoopExecutor           one A2A task
                                  │
                                  ▼
                             ToolLoop::run               many model turns
                           ┌──────┴───────┐
                   model turn N   ──→  tool calls? ──no──→ answer + trace
                           ▲              │ yes
                           └── results ── ToolSet
  • ToolModel: one completion turn, provider-neutral. OpenAiChatModel is the bundled one, for the chat-completions API (OpenAI, llama.cpp’s llama-server, vLLM, Ollama).
  • Tool and ToolSet: what the model may call. Each call carries an idempotency key, and a call repeated within a run to a tool that is not read-only is answered from the first (ADR 0026).
  • ToolLoop: turns until the model answers without a call, bounded by with_max_turns, with a tool’s error sent back to the model as that call’s result, and a call written as text recovered as a call.
  • InferenceLimit and LimitedModel: at most so many turns in flight at one provider, shared by every loop that uses it; and ModelRetry, a rate-limited turn sent again after the provider’s Retry-After, inside the caller’s budget (ADR 0048).
  • ToolLoopExecutor: the loop as an AgentExecutor, with the answer and a tool-trace artifact.

Each model turn and each tool call has its own span, named as the OpenTelemetry GenAI conventions name them (chat {model}, execute_tool {name}) and opened inside the executor’s invoke_agent span. They record no prompt, argument or result.

use std::future::Future;
use std::pin::Pin;
use a2a_protocol_server::tool_loop::{
    OpenAiChatModel, Tool, ToolError, ToolInvocation, ToolLoop, ToolLoopExecutor, ToolSet,
};
use a2a_protocol_server::RequestHandlerBuilder;

struct Clock;
impl Tool for Clock {
    fn name(&self) -> &str { "utc_now" }
    fn description(&self) -> &str { "The current UTC time, RFC 3339." }
    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({"type": "object", "properties": {}})
    }
    fn read_only(&self) -> bool { true }
    fn call<'a>(
        &'a self,
        _call: ToolInvocation,
    ) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>> {
        Box::pin(async { Ok("2026-10-20T12:00:00Z".to_owned()) })
    }
}

let model = OpenAiChatModel::new("http://127.0.0.1:8080/v1", "qwen3:1.7b")?;
let tools = ToolSet::new().with(Clock)?;
let executor = ToolLoopExecutor::new(
    ToolLoop::new(model, tools).with_preamble("Call the tools yourself to answer."),
);
let handler = RequestHandlerBuilder::new(executor).without_agent_card().build()?;

Structs§

ActionReceipt
One call’s record.
Answer
What a run produced.
ApprovalNeeded
A call a person has to approve before the run can go on.
AuditedPolicy
A ToolPolicy that records every call before it runs.
ChatRequest
Everything one turn is asked with.
DuplicateTool
Two tools in one ToolSet with the same name.
FinalAnswer
What a finished run answered.
InMemoryStepJournal
A journal in this process’s memory, for tests and for a deployment that keeps a run on one replica and accepts losing it with the process.
InferenceLimit
How many turns may be in flight at once at one model provider.
JournalEntry
One run as a StepJournal stores it. The journal reads revision, owner, completed and updated_at_ms; body is opaque to it.
LimitedModel
A ToolModel that takes a slot of an InferenceLimit for each turn and gives it back when the turn ends, however it ends.
ModelRetry
How a loop retries a turn the provider refused as rate limited (ModelError::RateLimited); set with ToolLoop::with_model_retry.
ModelTurn
What one turn produced.
OpenAiChatModel
A ToolModel that sends each turn as POST {base}/chat/completions.
PendingApproval
A call parked for a person’s decision.
Pins
What a run was begun with, which a resume must still be.
PolicyRequest
One call, as a ToolPolicy is asked about it: the tool and arguments the model chose, and the request’s identity, taken from the authenticated request and not from anything the model wrote.
PostgresStepJournal
Checkpoints in a PostgreSQL table, a2a_run_journal, created if absent.
RunCheckpoint
Everything a run needs to carry on.
RunOwner
Whose run an entry is: from the authenticated request, never from what the model wrote. What StepJournal::runs_of and StepJournal::erase find a run by.
RunSummary
What StepJournal::runs_of lists of a run: everything but its content.
SqliteStepJournal
Checkpoints in a SQLite table, a2a_run_journal, created if absent.
TextSink
Where a streaming turn sends its text as it arrives: see ToolModel::complete_streaming. Cheap to call for every piece; a piece sent after the run ended is dropped.
TokenUsage
The tokens one turn used, as the provider reported them.
ToolCall
One call a model asked for.
ToolInvocation
One call, as a Tool is given it.
ToolLoop
A model, the tools it may call, and the bounded loop between them.
ToolLoopExecutor
An AgentExecutor that answers each message by running a ToolLoop.
ToolSet
The tools a ToolLoop offers its model, in the order they were added. Names are unique: a model asking for a name two tools share could not be answered.
ToolSpec
What the model is told about one tool.
TrustedIdentity
The authenticated request’s identity, handed to the loop by its executor.

Enums§

ArgumentCheck
Whether, and how strictly, a call’s arguments are checked against the tool’s schema (Tool::parameters); see ToolLoop::with_argument_check.
ChatMessage
One message of the conversation a ToolModel is given.
JournalError
Why a journal did not do what it was asked.
LoopError
Why a run produced no answer.
ModelError
Why a turn produced nothing. Each is the provider’s failure, not the model’s: a model’s mistakes are fed back to it by the loop.
PolicyDecision
The policy’s answer.
ReceiptState
Where a call stands.
TextCallRecovery
Whether a reply that is exactly one JSON object naming a tool in the set is run as that call (see ToolLoop::with_text_call_recovery).
ToolError
Why a call produced no result.
TraceContent
What a run’s trace, the artifact the caller reads, carries for each call.

Constants§

ANSWER_ARTIFACT_ID
The id of the artifact carrying the answer.
CHECKPOINT_VERSION
The checkpoint format’s version. A checkpoint of another version is refused.
DEFAULT_CHECKPOINT_LIMIT
The bytes of one checkpoint body: 32 MiB.
DEFAULT_MAX_CALLS_PER_TURN
The tool calls one model reply may make when none is set.
DEFAULT_MAX_RESPONSE_BYTES
The most of a response body read when no cap is set. A chat completion is kilobytes; the cap exists so an endpoint does not get to choose how much memory a turn takes.
DEFAULT_MAX_TURNS
The turn bound when none is set.
DEFAULT_REQUEST_LIMIT
The bytes one model request may hold: 8 MiB, the size the bundled adapter accepts back from a provider (DEFAULT_MAX_RESPONSE_BYTES).
DEFAULT_RESULT_LIMIT
The bytes of one tool result the model is shown: 1 MiB.
DEFAULT_TIMEOUT
How long one turn may take, request and whole response, by default.
ERROR_BODY_LIMIT
The most of an error response’s body kept in ModelError::Status.
FINISH_REASON_LENGTH
The finish_reason of a reply that stopped at the model’s output limit.
FINISH_REASON_METADATA_KEY
The metadata key that marks an answer cut off at the output limit.
FLUSH_AFTER
How long text waits before it is appended, however little there is.
FLUSH_BYTES
The fewest bytes one append carries, unless FLUSH_AFTER has passed.
SEALED_CHECKPOINT_PREFIX
The prefix of a checkpoint body sealed by the loop’s journal cipher.
TRACE_ARTIFACT_ID
The id of the artifact carrying the tool trace.
TRACE_LINE_LIMIT
The most bytes of one trace line: name, arguments and result together.

Traits§

StepJournal
Where a run’s checkpoints are kept.
Tool
Something a model may call.
ToolModel
One completion turn of a model that can call tools.
ToolPolicy
Asked before every tool call runs, whatever kind it is (native, recovered from text, or repeated after a retry), and able to refuse it. Install with ToolLoop::with_policy.

Functions§

call_digest
sha256:<hex> of a call as an action: the tool, its arguments in canonical form, and who it is for (tenant, requester, task).
draft_artifact_id
The id of the artifact turn’s text streams to: draft-1 for the first.

Type Aliases§

JournalFuture
What a journal’s methods return.