Skip to main content

Flow

Enum Flow 

Source
#[non_exhaustive]
pub enum Flow { Continue, Terminate { reason: String, }, Skip { reason: String, }, RewriteArgs { args: Value, }, RewriteResult { result: String, }, PatchRequest { patch: RequestPatch, }, Fail, Retry { feedback: String, }, Repair { tool_name: String, }, }
Expand description

Control-flow result returned by AgentHook::on_event.

Each StepEvent honors a specific subset of variants (documented on each event). The runner is fail-closed: an action an event cannot honor never silently proceeds — it terminates the run with a diagnostic error. In particular, a blocking action such as Flow::Fail returned for a StepEvent::ToolCall stops the run rather than letting the tool execute. Returning Flow::Continue is always the way to “do nothing”.

Flow is PartialEq but not Eq, because Flow::PatchRequest carries a RequestPatch whose temperature is an f64.

Variants (Non-exhaustive)§

This enum is marked as non-exhaustive
Non-exhaustive enums could have additional variants added in future. Therefore, when matching against variants of non-exhaustive enums, an extra wildcard arm must be added to account for any future variants.
§

Continue

Proceed normally.

§

Terminate

Terminate the agent run early, surfacing reason.

Fields

§reason: String

Why the run is being terminated.

§

Skip

Skip the action: for StepEvent::ToolCall, return reason as the tool result without executing the tool; for StepEvent::InvalidToolCall, record reason as a synthetic result for the invalid call.

Fields

§reason: String

The message returned to the model in place of the tool result. It is delivered verbatim, so it doubles as a prompt: state that the tool did not run and, unless you want the model to try again, tell it not to retry — a bare "denied" often makes the model re-emit the same call.

§

RewriteArgs

StepEvent::ToolCall only: rewrite the tool-call arguments, then execute the tool with the replacement. This is the steering action for guardrails that normalize, clamp, redirect, or inject scoped parameters before a tool runs.

The rewritten arguments are what the tool is invoked with, what the following StepEvent::ToolResult reports, and what the gen_ai.tool.call.arguments span field records.

This rewrites only what the tool executes against, not the model’s transcript: the assistant message that recorded the original tool call is unchanged and keeps the model’s original arguments. It is therefore an execution-args rewrite (inject defaults, clamp a range, redirect a path), not a history redactor — it does not scrub a value the model already emitted from the conversation.

Across a HookStack, rewrites chain: the rewritten arguments are threaded into the next hook’s ToolCall event, so several hooks can each refine the arguments in registration order.

Fields

§args: Value

The JSON arguments the tool is invoked with, in place of the ones the model emitted.

§

RewriteResult

StepEvent::ToolResult only: replace the tool’s result with this string before the model sees it. The post-execution counterpart of RewriteArgs — for guardrails that redact, truncate, or normalize a tool’s output.

The replacement is what the model receives as the tool result and what the gen_ai.tool.call.result span field records. As with RewriteArgs, this changes only what the model sees: the tool still ran and produced its real output (which the first hook’s ToolResult event observed before this replacement is applied). It does not scrub the tool’s output from logs.

The replacement is delivered to the model verbatim — it is not re-parsed as structured/multimodal tool output, so a JSON-shaped replacement reaches the model as literal text.

Across a HookStack, rewrites chain: the replacement is threaded into the next hook’s ToolResult event, so a redaction hook and a truncation hook can compose in registration order.

Fields

§result: String

The result delivered to the model in place of the tool’s actual output.

§

PatchRequest

StepEvent::CompletionCall only: patch fields of the model request for this turn before it is sent. The per-turn request-steering action — for hooks that adjust the system prompt, sampling, tool choice, the advertised tool set, or inject context documents from run state (force a tool on the first turn, lower the temperature on a critical step, add RAG context).

The patch is partial (RequestPatch): each set field replaces (or, for additional_params/extra_context, merges onto) the agent’s configured value; unset fields are inherited. It applies to this turn only and does not change the agent’s baseline — the next turn re-fires CompletionCall and re-resolves from it.

Across a HookStack, patches from all hooks accumulate and merge in registration order (see RequestPatch and the module docs); this action therefore does not short-circuit later hooks.

Fields

§patch: RequestPatch

The partial request patch applied to this turn.

§

Fail

StepEvent::InvalidToolCall only: fail the run fast (the default for invalid tool calls).

§

Retry

StepEvent::InvalidToolCall only: retry the model turn with corrective feedback.

Fields

§feedback: String

Feedback appended to the conversation before re-prompting.

§

Repair

StepEvent::InvalidToolCall only: rewrite the emitted tool name, which is then revalidated against the allowed tools.

Fields

§tool_name: String

The corrected tool name.

Implementations§

Source§

impl Flow

Source

pub fn cont() -> Self

Continue the agent loop as normal.

Source

pub fn terminate(reason: impl Into<String>) -> Self

Terminate the agent run early with a reason.

Source

pub fn skip(reason: impl Into<String>) -> Self

Skip the current tool call (or invalid call) with the provided reason.

reason is delivered to the model verbatim as the tool result, so it doubles as a prompt — tell the model the tool did not run and whether to retry, or it may re-emit the identical call:

Flow::skip("Not executed (denied by policy). Do not retry unless the user asks.")
Source

pub fn rewrite_args(args: impl Into<Value>) -> Self

Rewrite a tool call’s arguments, then execute the tool with the replacement (tool calls only).

Accepts anything convertible into a serde_json::Value — most often the serde_json::json! macro or a value built from the parsed original arguments. To rewrite from a typed value instead, use try_rewrite_args.

// Inject a scoped parameter the model never sees, leaving the rest intact.
let mut args: serde_json::Value = serde_json::from_str(emitted_args)?;
args["account_id"] = serde_json::json!(session.account_id);
Flow::rewrite_args(args)
Source

pub fn try_rewrite_args<T: Serialize>(value: &T) -> Result<Self, Error>

Rewrite a tool call’s arguments from a serializable value (tool calls only), serializing it to JSON.

This is the typed convenience over rewrite_args for callers that hold a Rust args struct. It only fails if the value cannot be serialized to JSON; a hook typically maps that error to Flow::terminate:

Flow::try_rewrite_args(&new_args).unwrap_or_else(|e| Flow::terminate(e.to_string()))
Source

pub fn rewrite_result(result: impl Into<String>) -> Self

Replace a tool’s result with result before the model sees it (tool results only).

The post-execution counterpart of rewrite_args, for guardrails that redact, truncate, or normalize a tool’s output:

// Redact a secret from the tool output before it reaches the model.
Flow::rewrite_result(redact(tool_output))
Source

pub fn patch_request(patch: RequestPatch) -> Self

Patch fields of the model request for this turn (completion calls only). See RequestPatch for the partial-patch, per-turn, mergeable semantics.

Source

pub fn fail() -> Self

Fail fast on an invalid tool call (the default).

Source

pub fn retry(feedback: impl Into<String>) -> Self

Retry the model turn with corrective feedback (invalid tool calls only).

A common recovery is to let the model self-correct by naming the valid tools, built from the diagnostics in InvalidToolCallContext:

// On the `StepEvent::InvalidToolCall(ctx)` arm of `on_event`:
Flow::retry(format!(
    "`{}` is not a valid tool. Call one of: [{}].",
    ctx.tool_name,
    ctx.available_tools.join(", "),
))

Without such a hook the invalid-call default stays fail-closed (Flow::Continue is treated as Flow::fail).

Source

pub fn repair(tool_name: impl Into<String>) -> Self

Repair the emitted tool name (invalid tool calls only).

Trait Implementations§

Source§

impl Clone for Flow

Source§

fn clone(&self) -> Flow

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Flow

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Flow

Source§

fn eq(&self, other: &Flow) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Flow

Auto Trait Implementations§

§

impl Freeze for Flow

§

impl RefUnwindSafe for Flow

§

impl Send for Flow

§

impl Sync for Flow

§

impl Unpin for Flow

§

impl UnsafeUnpin for Flow

§

impl UnwindSafe for Flow

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneDebuggableStorage for T

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> CloneableStorage for T
where T: Any + Send + Sync + Clone,

Source§

impl<T> DebuggableStorage for T
where T: Any + Send + Sync + Debug,

Source§

impl<T> DynClone for T
where T: Clone,

Source§

fn __clone_box(&self, _: Private) -> *mut ()

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WasmCompatSend for T
where T: Send,

Source§

impl<T> WasmCompatSync for T
where T: Sync,

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more