Agent error handling
Genkit agent failures have different recovery paths depending on when they happen. A request can be rejected before an invocation starts, a turn can fail after state has been loaded, or a tool can return a domain-level result that the model can handle.
Failure categories
Section titled “Failure categories”- Rejected init returns a non-nil Go error from
Connect,Run,RunText, orRunDetachedbefore any turn runs. Fix the caller or the selected resume source. - Failed turns return an
AgentOutputwhoseFinishReasonisAgentFinishReasonFailedand whoseErroris non-nil. The tool rounds the turn completed are kept, and the output names the resume point:SnapshotIDfor a server-managed agent,Statefor a client-managed one. - Stopped runs return the error that stopped them together with an
AgentOutputwhoseFinishReasonisAgentFinishReasonAbortedand whoseErrorcarries the same stop, classified. A cancelled context, an expired deadline, a closed transport, a limit such asai.WithMaxTurns, andAborton a detached run all count. The snapshot keeps the turns that finished. - Background failures appear as snapshot status
failed,aborted, orexpired. The first two resume like their foreground counterparts. An expired run is lost; restart it from the snapshot’sParentID. - Tool domain problems should return structured tool output when the orchestrator or model can recover.
An unrecognized sessionId is not an error. The agent starts a new conversation under that ID and every snapshot it writes carries it, so there is no ErrSessionNotFound sentinel. aix.ErrSnapshotNotFound applies only to an unknown snapshotId.
The rejected-init cases from Run, RunText, and Connect are narrow: sending a sessionId to a client-managed agent (one defined without WithSessionStore) is a status.FailedPrecondition, and sending state to a store-backed agent is rejected the same way. ai/exp ships three sentinels in total: aix.ErrSnapshotNotFound, aix.ErrSessionStoreNotConfigured, and aix.ErrSessionIDRequired.
Check both error channels
Section titled “Check both error channels”An agent reports failure through two channels. A non-nil Go error means the invocation was rejected, could not produce an output, or was stopped by its caller. A failed turn is in-band, so the output carries the resume point. A stopped run sets both, so read out before acting on err.
AgentOutput.Error is a *status.Error from github.com/firebase/genkit/go/core/status, and it is nil in the ordinary case. Its Status keeps the classification the failure was raised with, so branch on that rather than on message text. See Error types for the status vocabulary and the sentinels each package ships.
import ( aix "github.com/firebase/genkit/go/ai/exp" "github.com/firebase/genkit/go/core/status")out, err := agent.RunText(ctx, "Look up order 123.")if err != nil { if out != nil { // The caller stopped the run. out.SnapshotID is the resume point. return fmt.Errorf("agent stopped at %s: %w", out.SnapshotID, err) } return fmt.Errorf("agent invocation did not start: %w", err)}
if out.FinishReason == aix.AgentFinishReasonFailed && out.Error != nil { switch out.Error.Status { case status.Unavailable, status.ResourceExhausted: // Overloaded. Re-attempt the turn from out.SnapshotID in a moment. return nil case status.InvalidArgument: // The model or a tool rejected the request. Rephrase it. return nil default: return fmt.Errorf("agent turn failed: %s: %s", out.Error.Status, out.Error.Message) }}
fmt.Println(out.Message.Text())Return from each recovery arm rather than falling through. A failed turn may have ended before any model response, in which case out.Message is nil. Message.Text() is nil-safe and returns "", so falling through prints a blank line instead of the answer the caller expected.
What the rest of AgentOutput holds depends on how the invocation finished:
FinishReason | Error | SnapshotID | State | Message |
|---|---|---|---|---|
failed | non-nil | The failed turn’s own snapshot: the tool rounds it completed, ending at a turn seam. Resumable. | What the turn committed. | May be nil. |
aborted | non-nil | The aborted snapshot, holding the turns that finished before the stop. Resumable. | Last-good client-managed state. | May be nil. |
detached | nil | The pending snapshot. | Nil; detach needs a store. | May be nil. |
| anything else | nil | The most recent turn-end snapshot, or empty with no store. | Client-managed final state. | The last model message. |
A turn rejected before it reaches the model, such as an invalid input or a render failure, commits nothing: the resume point stays the turn before it, and SnapshotID reports that. Either way the newest snapshot of the session is the latest resumable state. The basic-agents sample drives the same switch from its CLI, suggesting a different recovery per status.
Snapshot and store failures
Section titled “Snapshot and store failures”Reads and aborts classify too. Match them with errors.Is against the sentinels in ai/exp rather than by inspecting the message:
if _, err := agent.GetSnapshot(ctx, snapshotID); err != nil { switch { case errors.Is(err, aix.ErrSnapshotNotFound): // Nothing was ever written under that ID. case errors.Is(err, aix.ErrSessionStoreNotConfigured): // The agent is client-managed, so there is no snapshot to read. }}Resume after a failure or a stop
Section titled “Resume after a failure or a stop”A failed or aborted snapshot ends at a turn seam, so the model can be called on it again. Send an input with no payload to re-attempt the turn as it stood. The turn runs again on the committed messages, so the tool calls that already succeeded are not repeated:
retried, err := agent.Run(ctx, &aix.AgentInput{}, aix.WithSnapshotID[OrderState](out.SnapshotID),)Send a new message on the same snapshot to change course instead, or resume from the snapshot’s ParentID to rewind past the turn altogether:
retry, err := agent.RunText(ctx, "Try order 456.", aix.WithSnapshotID[OrderState](out.SnapshotID),)For client-managed agents the failed output’s State is the same resume point inline. Pass it back with aix.WithState, with an empty input or a new message:
retry, err := agent.RunText(ctx, "Try order 456.", aix.WithState(out.State),)Whether a failure is worth another attempt is the caller’s decision. The runtime records the status on the row and never classifies it: a RESOURCE_EXHAUSTED wants a wait, an INVALID_ARGUMENT wants a different message, and a FAILED_PRECONDITION from a tool guard may want neither.
Three statuses are not resume points. pending and aborting describe work that is still settling, so wait for it. expired means the worker died; resume from the row’s ParentID. A custom agent commits a failed turn only when it opts in, as described in Custom orchestration.
Tool errors
Section titled “Tool errors”Return a Go error when the tool cannot safely produce a meaningful result. Classify it once, where the failure mode is known, with status.Errorf and a sentinel; add context further up with fmt.Errorf and %w, which preserves the classification.
// A subtype keeps its parent's status and matches errors.Is at either// granularity: ErrOrderNotFound for this failure, status.ErrNotFound for any.var ErrOrderNotFound = status.ErrNotFound.Subtype("order not found")
func lookupOrder(ctx *ai.ToolContext, input LookupOrderInput) (LookupOrderOutput, error) { order, err := db.LookupOrder(ctx, input.OrderID) if err != nil { // The lookup itself failed (e.g. the database is unreachable); this is // a tool failure, distinct from a found-but-empty result below. return LookupOrderOutput{}, fmt.Errorf("could not look up order %q: %w", input.OrderID, err) } if order == nil { return LookupOrderOutput{}, status.Errorf(ErrOrderNotFound, "order %q not found", input.OrderID) } return LookupOrderOutput{OK: true, Order: order}, nil}A tool error fails the turn. The round it belonged to is discarded whole, including the model message that requested it and any sibling tools that succeeded, because a conversation cannot end on an unanswered tool request. The rounds before it are what the failed snapshot keeps. The basic-errors sample works the whole pattern through, including what reaches an HTTP client and what stays in the server log.
Return structured output when the model should recover:
if order == nil { return LookupOrderOutput{ OK: false, Reason: "ORDER_NOT_FOUND", Message: "Ask the user to check the order ID.", }, nil}Transform failures
Section titled “Transform failures”State and stream transforms fail closed. If a transform returns an error, the read or invocation fails instead of exposing unredacted data. Use this behavior for authorization-dependent redaction where returning raw state would leak sensitive information.