pub struct AgentRun { /* private fields */ }Expand description
The sans-IO agent loop state machine. See the module docs for the driving protocol.
Implementations§
Source§impl AgentRun
impl AgentRun
Sourcepub fn new(prompt: impl Into<Message>) -> Self
pub fn new(prompt: impl Into<Message>) -> Self
Create a run for one prompt with no input history, a one-model-call budget, and no invalid tool-call retries.
Sourcepub fn with_history(self, history: Vec<Message>) -> Self
pub fn with_history(self, history: Vec<Message>) -> Self
Set the input chat history preceding the prompt.
Sourcepub fn max_turns(self, max_turns: usize) -> Self
pub fn max_turns(self, max_turns: usize) -> Self
Set the total model-call budget, including the initial call and every
retry or continuation. A budget of zero emits no model calls. Exceeding
the budget makes AgentRun::next_step return
PromptError::MaxTurnsError.
Sourcepub fn with_output_validation(
self,
output_schema: Option<Value>,
max_output_retries: usize,
) -> Self
pub fn with_output_validation( self, output_schema: Option<Value>, max_output_retries: usize, ) -> Self
Configure Tool output-mode validation (#1928): the JSON schema the output-tool arguments should satisfy, and how many times to re-prompt the model — when it finalizes without calling the output tool, or calls it with arguments missing required fields — before finalizing best-effort.
Sourcepub fn max_invalid_tool_call_retries(self, retries: usize) -> Self
pub fn max_invalid_tool_call_retries(self, retries: usize) -> Self
Set the retry budget for InvalidToolCallAction::Retry
resolutions. Invalid tool-call retries also consume the total model-call
budget.
Sourcepub fn with_tool_choice(self, tool_choice: ToolChoice) -> Self
pub fn with_tool_choice(self, tool_choice: ToolChoice) -> Self
Set the tool choice active for this run. Used to reject
InvalidToolCallAction::Skip resolutions under
ToolChoice::None and reported in invalid tool-call contexts.
Sourcepub fn with_output_tool_name(self, name: impl Into<String>) -> Self
pub fn with_output_tool_name(self, name: impl Into<String>) -> Self
Set the synthetic output-tool name for Tool output mode (see #1928). When a model turn calls this tool, the run finalizes with the call’s arguments (serialized JSON) as the response.
Sourcepub fn completion_calls(&self) -> &[CompletionCall]
pub fn completion_calls(&self) -> &[CompletionCall]
Details for each completed model call so far.
Sourcepub fn messages(&self) -> &[Message]
pub fn messages(&self) -> &[Message]
Messages accumulated by this run (the prompt plus all assistant turns and tool results), excluding the input history.
Sourcepub fn retry_model_turn(
&mut self,
request: RetryRequest,
) -> Result<(), PromptError>
pub fn retry_model_turn( &mut self, request: RetryRequest, ) -> Result<(), PromptError>
Reject the accepted, tool-free model turn and prepare another model call.
RetryRequest::Repeat discards the rejected assistant response and
reuses the same prompt and preceding history with fresh request
preparation. RetryRequest::Feedback records the rejected response
followed by corrective user feedback. Canonical empty assistant turns
are omitted from history, matching normal turn advancement. Both modes
preserve completion-call and usage accounting, and the next call consumes
the existing total model-call budget.
Tool-bearing turns cannot be retried through this operation because preserving them without matching tool results would create invalid provider-visible history. Use tool-call hooks to steer those turns.
Sourcepub fn full_history(&self) -> Vec<Message>
pub fn full_history(&self) -> Vec<Message>
The full conversation: input history followed by Self::messages.
Sourcepub fn is_done(&self) -> bool
pub fn is_done(&self) -> bool
Whether the run reached AgentRunStep::Done.
Sourcepub fn response(&self) -> Option<&PromptResponse>
pub fn response(&self) -> Option<&PromptResponse>
The final response once the run is done, without cloning it.
AgentRun::next_step in the done state returns an owned clone
(including the full accumulated message history); prefer this when
only inspecting the result.
Sourcepub fn cancel_error(&self, reason: impl Into<String>) -> PromptError
pub fn cancel_error(&self, reason: impl Into<String>) -> PromptError
Build the cancellation error a driver should return when one of its hooks terminates the run, carrying the current full history.
Sourcepub fn pending_invalid_tool_call(&self) -> Option<InvalidToolCallContext>
pub fn pending_invalid_tool_call(&self) -> Option<InvalidToolCallContext>
The invalid tool call currently awaiting
AgentRun::resolve_invalid_tool_call, if any. Useful to re-derive
the resolution context after deserializing a suspended run.
Sourcepub fn next_step(&mut self) -> Result<AgentRunStep, PromptError>
pub fn next_step(&mut self) -> Result<AgentRunStep, PromptError>
Advance the machine and return the next action for the driver.
§Errors
PromptError::MaxTurnsErrorwhen the total model-call budget is exhausted.PromptError::PromptCancelledwhen the machine is driven out of protocol (for example, calling this while a model response is pending).
Sourcepub fn model_response(
&mut self,
turn: ModelTurn,
) -> Result<ModelTurnOutcome, PromptError>
pub fn model_response( &mut self, turn: ModelTurn, ) -> Result<ModelTurnOutcome, PromptError>
Feed the model’s response for the pending AgentRunStep::CallModel.
Records the completion call and aggregates usage, then validates the
turn’s tool calls against the advertised tool names. See
ModelTurnOutcome for what the driver must do next.
Sourcepub fn resolve_invalid_tool_call(
&mut self,
action: InvalidToolCallAction,
) -> Result<ModelTurnOutcome, PromptError>
pub fn resolve_invalid_tool_call( &mut self, action: InvalidToolCallAction, ) -> Result<ModelTurnOutcome, PromptError>
Answer a pending ModelTurnOutcome::NeedsResolution.
Applies the agent loop’s recovery semantics:
InvalidToolCallAction::Failfails the run withPromptError::UnknownToolCall.InvalidToolCallAction::Retryrolls the turn back with corrective feedback while budget remains, consuming the total model-call budget.InvalidToolCallAction::Repairrenames the tool call; the repaired name is revalidated against the allowed tools.InvalidToolCallAction::Stopcancels the run withPromptError::prompt_cancelledand the supplied reason.InvalidToolCallAction::Skiprecords a synthetic tool result and suppresses execution of every tool call in the turn. Rejected underToolChoice::None.
Sourcepub fn tool_results(
&mut self,
results: Vec<UserContent>,
) -> Result<(), PromptError>
pub fn tool_results( &mut self, results: Vec<UserContent>, ) -> Result<(), PromptError>
Feed the tool results for the pending AgentRunStep::CallTools.
Results may be in any order; they are appended as a single user message, matching what providers expect for parallel tool calls. Each result must be a tool result answering one of the pending calls, and every pending call must be answered — exactly what providers require to accept the next request.
Sourcepub fn record_streamed_completion_call(
&mut self,
usage: Usage,
) -> Result<CompletionCall, PromptError>
pub fn record_streamed_completion_call( &mut self, usage: Usage, ) -> Result<CompletionCall, PromptError>
Record one provider completion call for a streamed turn.
Streamed turns learn usage from the provider’s final stream event —
including for turns abandoned by invalid tool-call recovery, where the
stream is drained for usage after the rollback — so recording is
decoupled from turn ingestion. Valid while a model response is pending
or between a turn rollback and the next AgentRunStep::CallModel;
aggregates usage into the run total. Zero-valued usage means the
provider reported no usage metrics.
Sourcepub fn streamed_invalid_tool_call_context(
&self,
partial: &PartialStreamedTurn,
invalid: &StreamedInvalidToolCall,
) -> InvalidToolCallContext
pub fn streamed_invalid_tool_call_context( &self, partial: &PartialStreamedTurn, invalid: &StreamedInvalidToolCall, ) -> InvalidToolCallContext
The recovery-hook context for an invalid tool call surfaced
mid-stream by a streamed::StreamedTurnAssembler.
Sourcepub fn resolve_streamed_invalid_tool_call(
&mut self,
partial: &PartialStreamedTurn,
invalid: &StreamedInvalidToolCall,
action: InvalidToolCallAction,
) -> Result<StreamedResolution, PromptError>
pub fn resolve_streamed_invalid_tool_call( &mut self, partial: &PartialStreamedTurn, invalid: &StreamedInvalidToolCall, action: InvalidToolCallAction, ) -> Result<StreamedResolution, PromptError>
Resolve an invalid tool call surfaced mid-stream.
Applies the same recovery semantics as
AgentRun::resolve_invalid_tool_call, but rollback messages are
assembled from the partial streamed turn — exactly what the model has
produced so far — and a successful retry or skip abandons the turn
(see StreamedResolution) instead of finishing it.
Sourcepub fn streamed_turn(&mut self, turn: StreamedTurn) -> Result<(), PromptError>
pub fn streamed_turn(&mut self, turn: StreamedTurn) -> Result<(), PromptError>
Feed the assembled streamed turn for the pending
AgentRunStep::CallModel.
Remaining tool calls are validated fail-fast — mid-stream resolution
already had recovery-hook access — and the turn then advances through
AgentRun::next_step exactly like a non-streamed one.