Documentation
¶
Overview ¶
Package adk provides core agent development kit utilities and types.
Index ¶
- Constants
- Variables
- func AddSessionValue(ctx context.Context, key string, value any)
- func AddSessionValues(ctx context.Context, kvs map[string]any)
- func AppendAddressSegment(ctx context.Context, segType AddressSegmentType, segID string) context.Context
- func ClearRunCtx(ctx context.Context) context.Context
- func DeleteRunLocalValue(ctx context.Context, key string) error
- func EnsureMessageID[M MessageType](msg M)
- func GenTransferMessages(_ context.Context, destAgentName string) (Message, Message)
- func GetImplSpecificOptions[T any](base *T, opts ...AgentRunOption) *T
- func GetMessage(e *AgentEvent) (Message, *AgentEvent, error)
- func GetMessageID[M MessageType](msg M) string
- func GetRunLocalValue(ctx context.Context, key string) (any, bool, error)
- func GetSessionValue(ctx context.Context, key string) (any, bool)
- func GetSessionValues(ctx context.Context) map[string]any
- func NewAgentTool(_ context.Context, agent Agent, options ...AgentToolOption) tool.BaseTool
- func NewAsyncIteratorPair[T any]() (*AsyncIterator[T], *AsyncGenerator[T])
- func NewTypedAgentTool[M MessageType](_ context.Context, agent TypedAgent[M], options ...AgentToolOption) tool.BaseTool
- func SendEvent(ctx context.Context, event *AgentEvent) error
- func SendToolGenAction(ctx context.Context, toolName string, action *AgentAction) error
- func SetLanguage(lang Language) error
- func SetRunLocalValue(ctx context.Context, key string, value any) error
- func TypedSendEvent[M MessageType](ctx context.Context, event *TypedAgentEvent[M]) error
- func WithCancel() (AgentRunOption, AgentCancelFunc)
- type Address
- type AddressSegment
- type AddressSegmentType
- type Agent
- type AgentAction
- type AgentCallbackInput
- type AgentCallbackOutput
- type AgentCancelFunc
- type AgentCancelInfo
- type AgentCancelOption
- type AgentEvent
- func CompositeInterrupt(ctx context.Context, info any, state any, ...) *AgentEvent
- func EventFromMessage(msg Message, msgStream *schema.StreamReader[Message], role schema.RoleType, ...) *AgentEvent
- func Interrupt(ctx context.Context, info any) *AgentEvent
- func StatefulInterrupt(ctx context.Context, info any, state any) *AgentEvent
- type AgentInput
- type AgentMiddlewaredeprecated
- type AgentOption
- type AgentOutput
- type AgentRunOption
- func WithAfterToolCallsHook(fn func(ctx context.Context) error) AgentRunOption
- func WithAgentToolRunOptions(opts map[string][]AgentRunOption) AgentRunOption
- func WithCallbacks(handlers ...callbacks.Handler) AgentRunOption
- func WithChatModelOptions(opts []model.Option) AgentRunOption
- func WithCheckPointID(id string) AgentRunOption
- func WithHistoryModifier(f func(context.Context, []Message) []Message) AgentRunOption
- func WithSessionValues(v map[string]any) AgentRunOption
- func WithSkipTransferMessages() AgentRunOption
- func WithToolOptions(opts []tool.Option) AgentRunOption
- func WrapImplSpecificOptFn[T any](optFn func(*T)) AgentRunOption
- type AgentToolOption
- type AgentToolOptions
- type AgenticMessage
- type AgenticMessageStream
- type AsyncGenerator
- type AsyncIterator
- type BaseChatModelAgentMiddleware
- type BreakLoopAction
- type CancelError
- type CancelHandle
- type CancelMode
- type ChatModelAgent
- type ChatModelAgentConfig
- type ChatModelAgentContext
- type ChatModelAgentInterruptInfo
- type ChatModelAgentMiddleware
- type ChatModelAgentResumeData
- type ChatModelAgentState
- type CheckPointDeleter
- type CheckPointStore
- type DeterministicTransferConfig
- type EnhancedInvokableToolCallEndpoint
- type EnhancedStreamableToolCallEndpoint
- type ExitTool
- type FailoverContext
- type GenInputResult
- type GenModelInput
- type GenResumeResult
- type HistoryEntry
- type HistoryRewriter
- type InterruptCtx
- type InterruptError
- type InterruptInfo
- type InterruptSignal
- type InvokableToolCallEndpoint
- type Language
- type LoopAgentConfig
- type Message
- type MessageStream
- type MessageType
- type MessageVariant
- type ModelContext
- type ModelFailoverConfig
- type ModelRetryConfig
- type OnSubAgents
- type ParallelAgentConfig
- type PushOption
- func WithPreempt[T any, M MessageType](safePoint SafePoint) PushOption[T, M]
- func WithPreemptDelay[T any, M MessageType](delay time.Duration) PushOption[T, M]
- func WithPreemptTimeout[T any, M MessageType](safePoint SafePoint, timeout time.Duration) PushOption[T, M]
- func WithPushStrategy[T any, M MessageType](fn func(ctx context.Context, tc *TurnContext[T, M]) []PushOption[T, M]) PushOption[T, M]
- type ResumableAgent
- func NewLoopAgent(ctx context.Context, config *LoopAgentConfig) (ResumableAgent, error)
- func NewParallelAgent(ctx context.Context, config *ParallelAgentConfig) (ResumableAgent, error)
- func NewSequentialAgent(ctx context.Context, config *SequentialAgentConfig) (ResumableAgent, error)
- func SetSubAgents(ctx context.Context, agent Agent, subAgents []Agent) (ResumableAgent, error)
- type ResumeInfo
- type ResumeParams
- type RetryContext
- type RetryDecision
- type RetryExhaustedError
- type RunStep
- type Runner
- type RunnerConfig
- type SafePoint
- type SequentialAgentConfig
- type Statedeprecated
- type StopOption
- type StreamCanceledError
- type StreamableToolCallEndpoint
- type ToolCallsContext
- type ToolContext
- type ToolsConfig
- type TransferToAgentAction
- type TurnContext
- type TurnLoop
- type TurnLoopConfig
- type TurnLoopExitState
- type TypedAgent
- type TypedAgentCallbackInput
- type TypedAgentCallbackOutput
- type TypedAgentEvent
- func EventFromAgenticMessage(msg AgenticMessage, msgStream AgenticMessageStream, ...) *TypedAgentEvent[AgenticMessage]
- func TypedCompositeInterrupt[M MessageType](ctx context.Context, info any, state any, ...) *TypedAgentEvent[M]
- func TypedGetMessage[M MessageType](e *TypedAgentEvent[M]) (M, *TypedAgentEvent[M], error)
- func TypedInterrupt[M MessageType](ctx context.Context, info any) *TypedAgentEvent[M]
- func TypedStatefulInterrupt[M MessageType](ctx context.Context, info any, state any) *TypedAgentEvent[M]
- type TypedAgentInput
- type TypedAgentOutput
- type TypedBaseChatModelAgentMiddleware
- func (b *TypedBaseChatModelAgentMiddleware[M]) AfterAgent(ctx context.Context, state *TypedChatModelAgentState[M]) (context.Context, error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) AfterModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], ...) (context.Context, *TypedChatModelAgentState[M], error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) BeforeAgent(ctx context.Context, runCtx *ChatModelAgentContext) (context.Context, *ChatModelAgentContext, error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) BeforeModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], ...) (context.Context, *TypedChatModelAgentState[M], error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedInvokableToolCall(_ context.Context, endpoint EnhancedInvokableToolCallEndpoint, _ *ToolContext) (EnhancedInvokableToolCallEndpoint, error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedStreamableToolCall(_ context.Context, endpoint EnhancedStreamableToolCallEndpoint, _ *ToolContext) (EnhancedStreamableToolCallEndpoint, error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) WrapInvokableToolCall(_ context.Context, endpoint InvokableToolCallEndpoint, _ *ToolContext) (InvokableToolCallEndpoint, error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) WrapModel(_ context.Context, m model.BaseModel[M], _ *TypedModelContext[M]) (model.BaseModel[M], error)
- func (b *TypedBaseChatModelAgentMiddleware[M]) WrapStreamableToolCall(_ context.Context, endpoint StreamableToolCallEndpoint, _ *ToolContext) (StreamableToolCallEndpoint, error)
- type TypedChatModelAgent
- func (a *TypedChatModelAgent[M]) Description(_ context.Context) string
- func (a *TypedChatModelAgent[M]) GetType() string
- func (a *TypedChatModelAgent[M]) Name(_ context.Context) string
- func (a *TypedChatModelAgent[M]) OnDisallowTransferToParent(_ context.Context) error
- func (a *TypedChatModelAgent[M]) OnSetAsSubAgent(_ context.Context, parent TypedAgent[M]) error
- func (a *TypedChatModelAgent[M]) OnSetSubAgents(_ context.Context, subAgents []TypedAgent[M]) error
- func (a *TypedChatModelAgent[M]) Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
- func (a *TypedChatModelAgent[M]) Run(ctx context.Context, input *TypedAgentInput[M], opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
- type TypedChatModelAgentConfig
- type TypedChatModelAgentMiddleware
- type TypedChatModelAgentState
- type TypedGenModelInput
- type TypedMessageVariant
- type TypedModelContext
- type TypedModelRetryConfig
- type TypedResumableAgent
- type TypedRetryContext
- type TypedRetryDecision
- type TypedRunner
- func (r *TypedRunner[M]) Query(ctx context.Context, query string, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
- func (r *TypedRunner[M]) Resume(ctx context.Context, checkPointID string, opts ...AgentRunOption) (*AsyncIterator[*TypedAgentEvent[M]], error)
- func (r *TypedRunner[M]) ResumeWithParams(ctx context.Context, checkPointID string, params *ResumeParams, ...) (*AsyncIterator[*TypedAgentEvent[M]], error)
- func (r *TypedRunner[M]) Run(ctx context.Context, messages []M, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
- type TypedRunnerConfig
- type WillRetryError
- type WorkflowInterruptInfo
Constants ¶
const ( TransferToAgentToolName = "transfer_to_agent" TransferToAgentToolDesc = "Transfer the question to another agent." TransferToAgentToolDescChinese = "将问题移交给其他 Agent。" )
const ( TransferToAgentInstruction = `` /* 268-byte string literal not displayed */ TransferToAgentInstructionChinese = `` /* 303-byte string literal not displayed */ )
const ComponentOfAgent components.Component = "Agent"
ComponentOfAgent is the component type identifier for ADK agents in callbacks. Use this to filter callback events to only agent-related events.
const ComponentOfAgenticAgent components.Component = "AgenticAgent"
ComponentOfAgenticAgent is the component type identifier for ADK agents that use *schema.AgenticMessage in callbacks.
Variables ¶
var ( // ErrCancelTimeout is returned by CancelHandle.Wait when the cancel operation timed out. ErrCancelTimeout = errors.New("cancel timed out") // ErrExecutionEnded is returned by CancelHandle.Wait when the agent ended // before the cancel took effect. "Ended" means the event stream was fully // drained without any interrupt — normal completion or a fatal error. // // Note: business interrupts that occur while cancel is active are absorbed // into CancelError (see CancelError doc), so they result in nil (cancel // succeeded), NOT ErrExecutionEnded. Only execution that completes with // no interrupt at all produces this error. ErrExecutionEnded = errors.New("execution already ended") // ErrStreamCanceled is the error sent through the stream when CancelImmediate aborts it. // It is a *StreamCanceledError so it can be gob-serialized during checkpoint save // (when stored as agentEventWrapper.StreamErr). ErrStreamCanceled error = &StreamCanceledError{} )
Sentinel errors for cancel outcomes.
var ErrExceedMaxIterations = errors.New("exceeds max iterations")
ErrExceedMaxIterations indicates the agent reached the maximum iterations limit.
var ( // ErrExceedMaxRetries is returned when the maximum number of retries has been exceeded. // Use errors.Is to check if an error is due to max retries being exceeded: // // if errors.Is(err, adk.ErrExceedMaxRetries) { // // handle max retries exceeded // } // // Use errors.As to extract the underlying RetryExhaustedError for the last error details: // // var retryErr *adk.RetryExhaustedError // if errors.As(err, &retryErr) { // fmt.Printf("last error was: %v\n", retryErr.LastErr) // } ErrExceedMaxRetries = errors.New("exceeds max retries") )
var ( ToolInfoExit = &schema.ToolInfo{ Name: "exit", Desc: "Exit the agent process and return the final result.", ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{ "final_result": { Desc: "the final result to return", Required: true, Type: schema.String, }, }), } )
Functions ¶
func AddSessionValue ¶
AddSessionValue sets a single session key-value pair for the current run.
func AddSessionValues ¶
AddSessionValues sets multiple session key-value pairs for the current run.
func AppendAddressSegment ¶ added in v0.7.0
func AppendAddressSegment(ctx context.Context, segType AddressSegmentType, segID string) context.Context
AppendAddressSegment adds an address segment for the current execution context.
func ClearRunCtx ¶
ClearRunCtx clears the run context of the multi-agents. This is particularly useful when a customized agent with a multi-agents inside it is set as a subagent of another multi-agents. In such cases, it's not expected to pass the outside run context to the inside multi-agents, so this function helps isolate the contexts properly.
func DeleteRunLocalValue ¶ added in v0.8.0
DeleteRunLocalValue removes a value that was set during the current agent Run() invocation.
This function can only be called from within a ChatModelAgentMiddleware during agent execution. Returns an error if called outside of an agent execution context.
func EnsureMessageID ¶ added in v0.9.0
func EnsureMessageID[M MessageType](msg M)
EnsureMessageID assigns a UUID v4 message ID if the message doesn't have one. Idempotent: if ID already set, no-op. Middleware authors should call this before SendEvent if they create messages.
func GenTransferMessages ¶
GenTransferMessages generates assistant and tool messages to instruct a transfer-to-agent tool call targeting the destination agent.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func GetImplSpecificOptions ¶
func GetImplSpecificOptions[T any](base *T, opts ...AgentRunOption) *T
GetImplSpecificOptions extract the implementation specific options from AgentRunOption list, optionally providing a base options with default values. e.g.
myOption := &MyOption{
Field1: "default_value",
}
myOption := model.GetImplSpecificOptions(myOption, opts...)
func GetMessage ¶
func GetMessage(e *AgentEvent) (Message, *AgentEvent, error)
GetMessage extracts the Message from an AgentEvent. For streaming output, it duplicates the stream and concatenates it into a single Message.
func GetMessageID ¶ added in v0.9.0
func GetMessageID[M MessageType](msg M) string
GetMessageID returns the eino-internal message ID from the given message, or "".
func GetRunLocalValue ¶ added in v0.8.0
GetRunLocalValue retrieves a value that was set during the current agent Run() invocation. The value is scoped to this specific execution and is not shared across different Run() calls or agent instances.
Values stored via SetRunLocalValue are compatible with interrupt/resume cycles - they will be serialized and restored when the agent is resumed. For custom types, you must register them using schema.RegisterName[T]() in an init() function to ensure proper serialization.
This function can only be called from within a ChatModelAgentMiddleware during agent execution. Returns the value and true if found, or nil and false if not found or if called outside of an agent execution context.
func GetSessionValue ¶
GetSessionValue retrieves a session value by key and reports whether it exists.
func GetSessionValues ¶
GetSessionValues returns all session key-value pairs for the current run.
func NewAgentTool ¶
NewAgentTool creates a tool that wraps an agent for invocation.
The agent must have a non-empty Name and Description, as they are used as the tool's name and description respectively. This is validated when Info() is called during tool setup.
Event Streaming: When EmitInternalEvents is enabled in ToolsConfig, the agent tool will emit AgentEvent from the inner agent to the parent agent's AsyncGenerator, allowing real-time streaming of the inner agent's output to the end-user via Runner.
Note that these forwarded events are NOT recorded in the parent agent's runSession. They are only emitted to the end-user and have no effect on the parent agent's state or checkpoint. The only exception is Interrupted action, which is propagated via CompositeInterrupt to enable proper interrupt/resume across agent boundaries.
Action Scoping: Actions emitted by the inner agent are scoped to the agent tool boundary:
- Interrupted: Propagated via CompositeInterrupt to allow proper interrupt/resume across boundaries
- Exit, TransferToAgent, BreakLoop: Ignored outside the agent tool; these actions only affect the inner agent's execution and do not propagate to the parent agent
This scoping ensures that nested agents cannot unexpectedly terminate or transfer control of their parent agent's execution flow.
func NewAsyncIteratorPair ¶
func NewAsyncIteratorPair[T any]() (*AsyncIterator[T], *AsyncGenerator[T])
NewAsyncIteratorPair returns a paired async iterator and generator that share the same underlying channel.
func NewTypedAgentTool ¶ added in v0.9.0
func NewTypedAgentTool[M MessageType](_ context.Context, agent TypedAgent[M], options ...AgentToolOption) tool.BaseTool
NewTypedAgentTool creates a new agent tool that wraps a TypedAgent as a tool.BaseTool.
func SendEvent ¶ added in v0.7.34
func SendEvent(ctx context.Context, event *AgentEvent) error
SendEvent sends a custom AgentEvent to the event stream during agent execution. This allows ChatModelAgentMiddleware implementations to emit custom events that will be received by the caller iterating over the agent's event stream.
This function can only be called from within a ChatModelAgentMiddleware during agent execution. Returns an error if called outside of an agent execution context.
func SendToolGenAction ¶
func SendToolGenAction(ctx context.Context, toolName string, action *AgentAction) error
SendToolGenAction attaches an AgentAction to the next tool event emitted for the current tool execution.
Where/when to use:
- Invoke within a tool's Run (Invokable/Streamable) implementation to include an action alongside that tool's output event.
- The action is scoped by the current tool call context: if a ToolCallID is available, it is used as the key to support concurrent calls of the same tool with different parameters; otherwise, the provided toolName is used.
- The stored action is ephemeral and will be popped and attached to the tool event when the tool finishes (including streaming completion).
Limitation:
- This function is intended for use within ChatModelAgent runs only. It relies on ChatModelAgent's internal State to store and pop actions, which is not available in other agent types.
func SetLanguage ¶ added in v0.8.0
SetLanguage sets the language for the ADK built-in prompts. The default language is English if not explicitly set.
func SetRunLocalValue ¶ added in v0.8.0
SetRunLocalValue sets a key-value pair that persists for the duration of the current agent Run() invocation. The value is scoped to this specific execution and is not shared across different Run() calls or agent instances.
Values stored here are compatible with interrupt/resume cycles - they will be serialized and restored when the agent is resumed. For custom types, you must register them using schema.RegisterName[T]() in an init() function to ensure proper serialization.
This function can only be called from within a ChatModelAgentMiddleware during agent execution. Returns an error if called outside of an agent execution context.
func TypedSendEvent ¶ added in v0.9.0
func TypedSendEvent[M MessageType](ctx context.Context, event *TypedAgentEvent[M]) error
TypedSendEvent sends a custom TypedAgentEvent to the event stream during agent execution. This allows TypedChatModelAgentMiddleware implementations to emit custom events that will be received by the caller iterating over the agent's event stream.
Note: TypedSendEvent is a pure transport — it does NOT auto-assign message IDs. Framework-created messages (model output, tool results) receive IDs automatically via internal wrapper layers. If your middleware constructs its own messages, call EnsureMessageID before sending to assign an ID.
This function can only be called from within a TypedChatModelAgentMiddleware during agent execution. Returns an error if called outside of an agent execution context.
func WithCancel ¶ added in v0.9.0
func WithCancel() (AgentRunOption, AgentCancelFunc)
WithCancel creates an AgentRunOption that enables cancellation for an agent run. It returns the option to pass to Run/Resume and a cancel function. Cancel options (mode, timeout) are passed to the returned AgentCancelFunc at call time.
Types ¶
type Address ¶ added in v0.7.0
Address represents the unique, hierarchical address of a component within an execution. It is a slice of AddressSegments, where each segment represents one level of nesting. This is a type alias for core.Address. See the core package for more details.
type AddressSegment ¶ added in v0.7.0
type AddressSegment = core.AddressSegment
type AddressSegmentType ¶ added in v0.7.0
type AddressSegmentType = core.AddressSegmentType
const ( AddressSegmentAgent AddressSegmentType = "agent" AddressSegmentTool AddressSegmentType = "tool" )
type Agent ¶
type Agent = TypedAgent[*schema.Message]
func AgentWithDeterministicTransferTo ¶
func AgentWithDeterministicTransferTo(_ context.Context, config *DeterministicTransferConfig) Agent
AgentWithDeterministicTransferTo wraps an agent to transfer to given agents deterministically.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func AgentWithOptions ¶
func AgentWithOptions(ctx context.Context, agent Agent, opts ...AgentOption) Agent
AgentWithOptions wraps an agent with flow-specific options and returns it.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type AgentAction ¶
type AgentAction struct {
Exit bool
Interrupted *InterruptInfo
TransferToAgent *TransferToAgentAction
BreakLoop *BreakLoopAction
CustomizedAction any
// contains filtered or unexported fields
}
AgentAction represents actions that an agent can emit during execution.
Action Scoping in Agent Tools: When an agent is wrapped as an agent tool (via NewAgentTool), actions emitted by the inner agent are scoped to the tool boundary:
- Interrupted: Propagated via CompositeInterrupt to allow proper interrupt/resume across boundaries
- Exit, TransferToAgent, BreakLoop: Ignored outside the agent tool; these actions only affect the inner agent's execution and do not propagate to the parent agent
This scoping ensures that nested agents cannot unexpectedly terminate or transfer control of their parent agent's execution flow.
func NewBreakLoopAction ¶ added in v0.5.8
func NewBreakLoopAction(agentName string) *AgentAction
NewBreakLoopAction creates a new BreakLoopAction, signaling a request to terminate the current loop.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func NewExitAction ¶
func NewExitAction() *AgentAction
NewExitAction creates an action that signals the agent to exit.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func NewTransferToAgentAction ¶
func NewTransferToAgentAction(destAgentName string) *AgentAction
NewTransferToAgentAction creates an action to transfer to the specified agent.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type AgentCallbackInput ¶ added in v0.8.0
type AgentCallbackInput struct {
// Input contains the agent input for a new run. Nil when resuming.
Input *AgentInput
// ResumeInfo contains resume information when resuming from an interrupt. Nil for new runs.
ResumeInfo *ResumeInfo
}
AgentCallbackInput represents the input passed to agent callbacks during OnStart. Use ConvAgentCallbackInput to safely convert from callbacks.CallbackInput.
func ConvAgentCallbackInput ¶ added in v0.8.0
func ConvAgentCallbackInput(input callbacks.CallbackInput) *AgentCallbackInput
ConvAgentCallbackInput converts a generic CallbackInput to AgentCallbackInput. Returns nil if the input is not an AgentCallbackInput.
type AgentCallbackOutput ¶ added in v0.8.0
type AgentCallbackOutput struct {
// Events provides a stream of agent events. Each handler receives its own copy.
Events *AsyncIterator[*AgentEvent]
}
AgentCallbackOutput represents the output passed to agent callbacks during OnEnd. Use ConvAgentCallbackOutput to safely convert from callbacks.CallbackOutput.
Important: The Events iterator should be consumed asynchronously to avoid blocking the agent execution. Each callback handler receives an independent copy of the iterator.
func ConvAgentCallbackOutput ¶ added in v0.8.0
func ConvAgentCallbackOutput(output callbacks.CallbackOutput) *AgentCallbackOutput
ConvAgentCallbackOutput converts a generic CallbackOutput to AgentCallbackOutput. Returns nil if the output is not an AgentCallbackOutput.
type AgentCancelFunc ¶ added in v0.9.0
type AgentCancelFunc func(...AgentCancelOption) (*CancelHandle, bool)
AgentCancelFunc is called to request cancellation of a running agent. It returns after the cancel request is committed; use the returned handle's Wait to block for completion and outcome.
The returned bool reports whether this call contributed to the CancelError for the current execution. "Contributed" means this call's cancel options were included before cancellation was finalized. It is false when cancellation was already finalized (handled or execution completed).
type AgentCancelInfo ¶ added in v0.9.0
type AgentCancelInfo struct {
Mode CancelMode
Escalated bool
Timeout bool
}
AgentCancelInfo contains information about a cancel operation.
type AgentCancelOption ¶ added in v0.9.0
type AgentCancelOption func(*agentCancelConfig)
AgentCancelOption configures cancel behavior.
func WithAgentCancelMode ¶ added in v0.9.0
func WithAgentCancelMode(mode CancelMode) AgentCancelOption
WithAgentCancelMode sets the cancel mode for the agent cancel operation.
func WithAgentCancelTimeout ¶ added in v0.9.0
func WithAgentCancelTimeout(timeout time.Duration) AgentCancelOption
WithAgentCancelTimeout sets a timeout for the cancel operation. This only applies to safe-point modes (CancelAfterChatModel, CancelAfterToolCalls): if the safe-point hasn't fired within this duration, the cancel escalates to CancelImmediate. The escalated cancel still saves a checkpoint, so the execution can be resumed via Runner.Resume or Runner.ResumeWithParams. For CancelImmediate this timeout is ignored — the cancel fires immediately.
func WithRecursive ¶ added in v0.9.0
func WithRecursive() AgentCancelOption
WithRecursive opts into recursive cancel propagation. By default, cancel modes only affect the root agent; descendant agents inside AgentTools are not notified. WithRecursive makes the cancel propagate to all descendants:
- CancelAfterChatModel / CancelAfterToolCalls: descendants check their own safe-points.
- CancelImmediate: descendants receive explicit immediate-cancel signals for clean teardown; the root uses a grace period to collect child interrupts.
With recursive cancellation, each descendant agent also triggers cancellation and cascades its interrupt information upward. The root agent ultimately produces a complete checkpoint that includes descendant checkpoints, enabling resumption from the exact point where each descendant was interrupted.
Once any cancel call includes WithRecursive, the flag stays set for the entire cancel lifecycle (monotonic escalation).
type AgentEvent ¶
type AgentEvent = TypedAgentEvent[*schema.Message]
AgentEvent is the default event type using *schema.Message.
func CompositeInterrupt ¶ added in v0.7.0
func CompositeInterrupt(ctx context.Context, info any, state any, subInterruptSignals ...*InterruptSignal) *AgentEvent
CompositeInterrupt creates an interrupt event that aggregates sub-interrupt signals.
func EventFromMessage ¶
func EventFromMessage(msg Message, msgStream *schema.StreamReader[Message], role schema.RoleType, toolName string) *AgentEvent
EventFromMessage creates an AgentEvent containing the given message and optional stream.
role identifies the origin of this event:
- schema.Assistant: model output (generation or stream).
- schema.Tool: tool execution result; toolName must be non-empty.
For *schema.AgenticMessage events, use EventFromAgenticMessage instead.
func Interrupt ¶ added in v0.7.0
func Interrupt(ctx context.Context, info any) *AgentEvent
Interrupt creates a basic interrupt action. This is used when an agent needs to pause its execution to request external input or intervention, but does not need to save any internal state to be restored upon resumption. The `info` parameter is user-facing data that describes the reason for the interrupt.
func StatefulInterrupt ¶ added in v0.7.0
func StatefulInterrupt(ctx context.Context, info any, state any) *AgentEvent
StatefulInterrupt creates an interrupt action that also saves the agent's internal state. This is used when an agent has internal state that must be restored for it to continue correctly. The `info` parameter is user-facing data describing the interrupt. The `state` parameter is the agent's internal state object, which will be serialized and stored.
type AgentInput ¶
type AgentInput = TypedAgentInput[*schema.Message]
type AgentMiddleware
deprecated
added in
v0.5.14
type AgentMiddleware struct {
// AdditionalInstruction adds supplementary text to the agent's system instruction.
// This instruction is concatenated with the base instruction before each chat model call.
AdditionalInstruction string
// AdditionalTools adds supplementary tools to the agent's available toolset.
// These tools are combined with the tools configured for the agent.
AdditionalTools []tool.BaseTool
// BeforeChatModel is called before each ChatModel invocation, allowing modification of the agent state.
BeforeChatModel func(context.Context, *ChatModelAgentState) error
// AfterChatModel is called after each ChatModel invocation, allowing modification of the agent state.
AfterChatModel func(context.Context, *ChatModelAgentState) error
// WrapToolCall wraps tool calls with custom middleware logic.
// Each middleware contains Invokable and/or Streamable functions for tool calls.
WrapToolCall compose.ToolMiddleware
}
Deprecated: Use ChatModelAgentMiddleware (interface-based Handlers) instead. AgentMiddleware will be removed in a future release.
AgentMiddleware provides hooks to customize agent behavior at various stages of execution.
type AgentOption ¶
type AgentOption func(options *flowAgent)
func WithDisallowTransferToParent ¶
func WithDisallowTransferToParent() AgentOption
WithDisallowTransferToParent prevents a sub-agent from transferring to its parent.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func WithHistoryRewriter ¶
func WithHistoryRewriter(h HistoryRewriter) AgentOption
WithHistoryRewriter sets a rewriter to transform conversation history during agent transfers.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type AgentOutput ¶
type AgentOutput = TypedAgentOutput[*schema.Message]
type AgentRunOption ¶
type AgentRunOption struct {
// contains filtered or unexported fields
}
AgentRunOption is the call option for adk Agent.
func WithAfterToolCallsHook ¶ added in v0.9.0
func WithAfterToolCallsHook(fn func(ctx context.Context) error) AgentRunOption
WithAfterToolCallsHook registers a per-run hook that fires synchronously after all tool calls in a react iteration complete, before the next ChatModel call.
This is suitable for TurnLoop Push+Preempt patterns where the pushed item must be visible to the next turn's GenInput.
func WithAgentToolRunOptions ¶
func WithAgentToolRunOptions(opts map[string][]AgentRunOption) AgentRunOption
WithAgentToolRunOptions specifies per-tool run options for the agent.
func WithCallbacks ¶ added in v0.8.0
func WithCallbacks(handlers ...callbacks.Handler) AgentRunOption
WithCallbacks adds callback handlers to receive agent lifecycle events. Handlers receive OnStart with AgentCallbackInput and OnEnd with AgentCallbackOutput. Multiple handlers can be added; each receives an independent copy of the event stream.
func WithChatModelOptions ¶
func WithChatModelOptions(opts []model.Option) AgentRunOption
WithChatModelOptions sets options for the underlying chat model.
func WithCheckPointID ¶
func WithCheckPointID(id string) AgentRunOption
WithCheckPointID sets the checkpoint ID used for interruption persistence.
func WithHistoryModifier ¶
func WithHistoryModifier(f func(context.Context, []Message) []Message) AgentRunOption
WithHistoryModifier sets a function to modify history during resume. Deprecated: use ResumeWithData and ChatModelAgentResumeData instead.
func WithSessionValues ¶
func WithSessionValues(v map[string]any) AgentRunOption
WithSessionValues sets session-scoped values for the agent run.
func WithSkipTransferMessages ¶
func WithSkipTransferMessages() AgentRunOption
WithSkipTransferMessages disables forwarding transfer messages during execution.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func WithToolOptions ¶
func WithToolOptions(opts []tool.Option) AgentRunOption
WithToolOptions sets options for tools used by the chat model agent.
func WrapImplSpecificOptFn ¶
func WrapImplSpecificOptFn[T any](optFn func(*T)) AgentRunOption
WrapImplSpecificOptFn is the option to wrap the implementation specific option function.
func (AgentRunOption) DesignateAgent ¶
func (o AgentRunOption) DesignateAgent(name ...string) AgentRunOption
type AgentToolOption ¶
type AgentToolOption func(*AgentToolOptions)
func WithAgentInputSchema ¶ added in v0.5.4
func WithAgentInputSchema(schema *schema.ParamsOneOf) AgentToolOption
WithAgentInputSchema sets a custom input schema for the agent tool.
func WithFullChatHistoryAsInput ¶
func WithFullChatHistoryAsInput() AgentToolOption
WithFullChatHistoryAsInput enables using the full chat history as input.
type AgentToolOptions ¶
type AgentToolOptions struct {
// contains filtered or unexported fields
}
type AgenticMessage ¶ added in v0.9.0
type AgenticMessage = *schema.AgenticMessage
type AgenticMessageStream ¶ added in v0.9.0
type AgenticMessageStream = *schema.StreamReader[AgenticMessage]
type AsyncGenerator ¶
type AsyncGenerator[T any] struct { // contains filtered or unexported fields }
func (*AsyncGenerator[T]) Close ¶
func (ag *AsyncGenerator[T]) Close()
func (*AsyncGenerator[T]) Send ¶
func (ag *AsyncGenerator[T]) Send(v T)
type AsyncIterator ¶
type AsyncIterator[T any] struct { // contains filtered or unexported fields }
func (*AsyncIterator[T]) Next ¶
func (ai *AsyncIterator[T]) Next() (T, bool)
type BaseChatModelAgentMiddleware ¶ added in v0.8.0
type BaseChatModelAgentMiddleware = TypedBaseChatModelAgentMiddleware[*schema.Message]
BaseChatModelAgentMiddleware provides default no-op implementations for ChatModelAgentMiddleware. Embed *BaseChatModelAgentMiddleware in custom handlers to only override the methods you need.
Example:
type MyHandler struct {
*adk.BaseChatModelAgentMiddleware
// custom fields
}
func (h *MyHandler) BeforeModelRewriteState(ctx context.Context, state *adk.ChatModelAgentState, mc *adk.ModelContext) (context.Context, *adk.ChatModelAgentState, error) {
// custom logic
return ctx, state, nil
}
type BreakLoopAction ¶ added in v0.5.8
type BreakLoopAction struct {
// From records the name of the agent that initiated the break loop action.
From string
// Done is a state flag that can be used by the framework to mark when the
// action has been handled.
Done bool
// CurrentIterations is populated by the framework to record at which
// iteration the loop was broken.
CurrentIterations int
}
BreakLoopAction is a programmatic-only agent action used to prematurely terminate the execution of a loop workflow agent. When a loop workflow agent receives this action from a sub-agent, it will stop its current iteration and will not proceed to the next one. It will mark the BreakLoopAction as Done, signalling to any 'upper level' loop agent that this action has been processed and should be ignored further up. This action is not intended to be used by LLMs.
type CancelError ¶ added in v0.9.0
type CancelError struct {
Info *AgentCancelInfo
// InterruptContexts provides the interrupt contexts needed for targeted
// resumption via Runner.ResumeWithParams. Each context represents a step
// in the agent hierarchy that was interrupted. This is a slice because
// composite agents (e.g. parallel workflows) may interrupt at multiple
// points simultaneously, matching the shape of AgentAction.Interrupted.InterruptContexts.
// Use each InterruptCtx.ID as a key in ResumeParams.Targets.
InterruptContexts []*InterruptCtx
// contains filtered or unexported fields
}
CancelError is sent via AgentEvent.Err when an agent is canceled. Use errors.As to match and extract *CancelError from event errors.
Interrupt absorption: when a cancel is active (shouldCancel() == true), ANY interrupt — whether from a cancel safe-point node or from business logic (e.g. tool.Interrupt in a tool) — is converted to a CancelError. The cancel "absorbs" the business interrupt. This is intentional:
- In concurrent execution (parallel workflows, concurrent tool calls), cancel-induced and business interrupts can arrive as a single composite signal that cannot be split apart.
- Even in sequential execution, treating business interrupts as CancelError during active cancel gives consistent semantics.
- The business interrupt is NOT lost — the checkpoint preserves the full interrupt hierarchy. On resume (Runner.Resume or Runner.ResumeWithParams), the agent re-executes the interrupting code path and the business interrupt re-fires naturally.
func (*CancelError) Error ¶ added in v0.9.0
func (e *CancelError) Error() string
type CancelHandle ¶ added in v0.9.0
type CancelHandle struct {
// contains filtered or unexported fields
}
CancelHandle represents a cancel operation that can be waited on.
func (*CancelHandle) Wait ¶ added in v0.9.0
func (h *CancelHandle) Wait() error
Wait blocks until the cancel request reaches a terminal outcome.
It reports the result of the cancel operation itself, not the agent's final business error:
- nil: cancellation succeeded, including the case where a business interrupt was absorbed into CancelError while cancellation was active
- ErrCancelTimeout: the requested safe-point cancellation timed out and was escalated to immediate cancellation
- ErrExecutionEnded: the execution ended before cancellation took effect, meaning the stream drained to completion without any interrupt
type CancelMode ¶ added in v0.9.0
type CancelMode int
CancelMode specifies when an agent should be canceled. Modes can be combined with bitwise OR to cancel at multiple safe-points. For example, CancelAfterChatModel | CancelAfterToolCalls cancels the agent after whichever safe-point is reached first.
const ( // CancelImmediate cancels the agent as soon as the signal is received, // without waiting for a ChatModel or ToolCalls safe-point. // By default, only the root agent is interrupted; descendant agents inside // AgentTools are torn down via context cancellation as a side effect. // Use WithRecursive to propagate explicit immediate-cancel signals to // descendants for clean teardown with grace period. CancelImmediate CancelMode = 0 // CancelAfterChatModel cancels after the root agent's next chat model call // completes. By default, only the root agent checks this safe-point; // nested sub-agents inside AgentTools are unaware of the cancel. // Use WithRecursive to propagate the cancel to all descendants — whichever // ChatModel finishes first triggers the cancel. CancelAfterChatModel CancelMode = 1 << iota // CancelAfterToolCalls cancels after the root agent's next set of tool calls // completes. By default, only the root agent checks this safe-point. // Use WithRecursive to propagate to all descendants. CancelAfterToolCalls )
type ChatModelAgent ¶
type ChatModelAgent = TypedChatModelAgent[*schema.Message]
func NewChatModelAgent ¶
func NewChatModelAgent(ctx context.Context, config *ChatModelAgentConfig) (*ChatModelAgent, error)
NewChatModelAgent creates a new ChatModelAgent with the given config.
type ChatModelAgentConfig ¶
type ChatModelAgentConfig = TypedChatModelAgentConfig[*schema.Message]
type ChatModelAgentContext ¶ added in v0.8.0
type ChatModelAgentContext struct {
// Instruction is the current instruction for the Agent execution.
// It includes the instruction configured for the agent, additional instructions appended by framework
// and AgentMiddleware, and modifications applied by previous BeforeAgent handlers.
// The finalized instruction after all BeforeAgent handlers are then passed to GenModelInput,
// to be (optionally) formatted with SessionValues and converted to system message.
Instruction string
// Tools are the raw tools (without any wrapper or tool middleware) currently configured for the Agent execution.
// They includes tools passed in AgentConfig, implicit tools added by framework such as transfer / exit tools,
// and other tools already added by middlewares.
Tools []tool.BaseTool
// ReturnDirectly is the set of tool names currently configured to cause the Agent to return directly.
// This is based on the return directly map configured for the agent, plus any modifications
// by previous BeforeAgent handlers.
ReturnDirectly map[string]bool
// ToolSearchTool is the tool info for the model's native tool search capability.
// When set by a BeforeAgent handler, the framework passes it to the model via model.WithToolSearchTool.
ToolSearchTool *schema.ToolInfo
}
ChatModelAgentContext contains runtime information passed to handlers before each ChatModelAgent run. Handlers can modify Instruction, Tools, and ReturnDirectly to customize agent behavior.
This type is specific to ChatModelAgent. Other agent types may define their own context types.
type ChatModelAgentInterruptInfo ¶
type ChatModelAgentInterruptInfo struct {
Info *compose.InterruptInfo
Data []byte
}
type ChatModelAgentMiddleware ¶ added in v0.8.0
type ChatModelAgentMiddleware = TypedChatModelAgentMiddleware[*schema.Message]
ChatModelAgentMiddleware is the default middleware type using *schema.Message. See TypedChatModelAgentMiddleware for full documentation.
func NewEventSenderModelWrapper ¶ added in v0.8.0
func NewEventSenderModelWrapper() ChatModelAgentMiddleware
NewEventSenderModelWrapper creates a ChatModelAgentMiddleware that sends model output as agent events.
func NewEventSenderToolWrapper ¶ added in v0.9.0
func NewEventSenderToolWrapper() ChatModelAgentMiddleware
NewEventSenderToolWrapper returns a ChatModelAgentMiddleware that sends tool result events. By default, the framework places this before all user middlewares (outermost), so events reflect the fully processed tool output. To control exactly where events are emitted, include this in ChatModelAgentConfig.Handlers at the desired position. When detected in Handlers, the framework skips the default event sender to avoid duplicates.
type ChatModelAgentResumeData ¶ added in v0.7.0
type ChatModelAgentResumeData struct {
// HistoryModifier is a function that can transform the agent's message history before it is sent to the model.
// This allows for adding new information or context upon resumption.
HistoryModifier func(ctx context.Context, history []Message) []Message
}
ChatModelAgentResumeData holds data that can be provided to a ChatModelAgent during a resume operation to modify its behavior. It is provided via the adk.ResumeWithData function.
type ChatModelAgentState ¶ added in v0.5.14
type ChatModelAgentState = TypedChatModelAgentState[*schema.Message]
ChatModelAgentState is the default state type using *schema.Message.
type CheckPointDeleter ¶ added in v0.9.0
type CheckPointDeleter = core.CheckPointDeleter
type CheckPointStore ¶ added in v0.7.22
type CheckPointStore = core.CheckPointStore
type DeterministicTransferConfig ¶
DeterministicTransferConfig is the configuration for AgentWithDeterministicTransferTo.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type EnhancedInvokableToolCallEndpoint ¶ added in v0.8.0
type EnhancedInvokableToolCallEndpoint func(ctx context.Context, toolArgument *schema.ToolArgument, opts ...tool.Option) (*schema.ToolResult, error)
type EnhancedStreamableToolCallEndpoint ¶ added in v0.8.0
type EnhancedStreamableToolCallEndpoint func(ctx context.Context, toolArgument *schema.ToolArgument, opts ...tool.Option) (*schema.StreamReader[*schema.ToolResult], error)
type FailoverContext ¶ added in v0.9.0
type FailoverContext[M MessageType] struct { // FailoverAttempt is the current failover attempt number, starting from 1. FailoverAttempt uint // InputMessages is the original input messages before any transformation. InputMessages []M // LastOutputMessage is the output message from the last failed attempt. // May be nil if no output was produced. For streaming, this may be a partial message // already received before the stream error. LastOutputMessage M // LastErr is the error from the last failed attempt that triggered this failover. // // Note: When ModelRetryConfig is also configured, LastErr will be a *RetryExhaustedError // (if retries were exhausted) rather than the original model error. The original error // can be retrieved via RetryExhaustedError.LastErr. LastErr error }
FailoverContext contains context information during failover process.
type GenInputResult ¶ added in v0.9.0
type GenInputResult[T any, M MessageType] struct { // RunCtx, if non-nil, overrides the context for this turn's execution // (PrepareAgent, agent run, OnAgentEvents). // // Must be derived from the ctx passed to GenInput to preserve the // TurnLoop's cancellation semantics and inherited values. For example: // // runCtx := context.WithValue(ctx, traceKey{}, extractTraceID(items)) // return &GenInputResult[T]{RunCtx: runCtx, ...}, nil // // If nil, the TurnLoop's context is used unchanged. RunCtx context.Context // Input is the agent input to execute Input *TypedAgentInput[M] // RunOpts are the options for this agent run. // Note: do not pass WithCheckPointID here; the TurnLoop automatically // injects the checkpointID into the Runner. RunOpts []AgentRunOption // Consumed are the items selected for this turn. // They are removed from the buffer and passed to PrepareAgent. Consumed []T // Remaining are the items to keep in the buffer for a future turn. // TurnLoop pushes Remaining back into the buffer before running the agent. // // Items from the GenInput input slice that are in neither Consumed nor Remaining // are dropped by the loop. Remaining []T }
GenInputResult contains the result of GenInput processing.
type GenModelInput ¶
type GenModelInput = TypedGenModelInput[*schema.Message]
GenModelInput transforms agent instructions and input into a format suitable for the model.
type GenResumeResult ¶ added in v0.9.0
type GenResumeResult[T any, M MessageType] struct { // RunCtx, if non-nil, overrides the context for this resumed turn's execution // (PrepareAgent, agent resume, OnAgentEvents). RunCtx context.Context // RunOpts are the options for this agent resume run. // Note: do not pass WithCheckPointID here; the TurnLoop automatically // injects the checkpointID into the Runner. RunOpts []AgentRunOption // ResumeParams are optional parameters for resuming an interrupted agent. ResumeParams *ResumeParams // Consumed are the items selected for this resumed turn. // They are removed from the buffer and passed to PrepareAgent. Consumed []T // Remaining are the items to keep in the buffer for a future turn. // TurnLoop pushes Remaining back into the buffer before resuming the agent. // // Items from (interruptedItems, unhandledItems, newItems) that are in neither Consumed // nor Remaining are dropped by the loop. Remaining []T }
GenResumeResult contains the result of GenResume processing.
type HistoryEntry ¶
type HistoryRewriter ¶
type HistoryRewriter func(ctx context.Context, entries []*HistoryEntry) ([]Message, error)
type InterruptCtx ¶ added in v0.7.0
type InterruptCtx = core.InterruptCtx
InterruptCtx provides a structured, user-facing view of a single point of interruption. It contains the ID and Address of the interrupted component, as well as user-defined info. This is a type alias for core.InterruptCtx. See the core package for more details.
type InterruptError ¶ added in v0.9.0
type InterruptError struct {
// InterruptContexts provides the interrupt contexts needed for targeted
// resumption via ResumeParams. Each context represents a step in the agent
// hierarchy that was interrupted. Use each InterruptCtx.ID as a key in
// ResumeParams.Targets.
InterruptContexts []*InterruptCtx
}
InterruptError is the ExitReason when the TurnLoop exits due to a business interrupt (AgentAction.Interrupted). It carries InterruptContexts needed for targeted resumption via ResumeParams, parallel to CancelError.
Unlike CancelError (which indicates forceful cancellation), InterruptError indicates the agent voluntarily paused execution at a business-defined point.
func (*InterruptError) Error ¶ added in v0.9.0
func (e *InterruptError) Error() string
type InterruptInfo ¶
type InterruptInfo struct {
Data any
// InterruptContexts provides a structured, user-facing view of the interrupt chain.
// Each context represents a step in the agent hierarchy that was interrupted.
InterruptContexts []*InterruptCtx
}
InterruptInfo contains all the information about an interruption event. It is created by the framework when an agent returns an interrupt action.
type InterruptSignal ¶ added in v0.7.0
type InterruptSignal = core.InterruptSignal
func FromInterruptContexts ¶ added in v0.7.0
func FromInterruptContexts(contexts []*InterruptCtx) *InterruptSignal
FromInterruptContexts converts user-facing interrupt contexts to an interrupt signal.
type InvokableToolCallEndpoint ¶ added in v0.8.0
type InvokableToolCallEndpoint func(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (string, error)
InvokableToolCallEndpoint is the function signature for invoking a tool synchronously. Middleware authors implement wrappers around this endpoint to add custom behavior.
type Language ¶ added in v0.8.0
Language represents the language setting for the ADK built-in prompts.
const ( // LanguageEnglish represents English language. LanguageEnglish Language = internal.LanguageEnglish // LanguageChinese represents Chinese language. LanguageChinese Language = internal.LanguageChinese )
type LoopAgentConfig ¶
LoopAgentConfig is the configuration for NewLoopAgent.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type MessageStream ¶
type MessageStream = *schema.StreamReader[Message]
type MessageType ¶ added in v0.9.0
type MessageType interface {
*schema.Message | *schema.AgenticMessage
}
MessageType is the sealed type constraint for message types used in ADK. Only *schema.Message and *schema.AgenticMessage satisfy this constraint. External packages cannot add new types to this union; all generic functions in ADK use exhaustive type switches on these two types.
type MessageVariant ¶
type MessageVariant = TypedMessageVariant[*schema.Message]
type ModelContext ¶ added in v0.8.0
type ModelContext = TypedModelContext[*schema.Message]
ModelContext is the default model context type using *schema.Message.
type ModelFailoverConfig ¶ added in v0.9.0
type ModelFailoverConfig[M MessageType] struct { // MaxRetries specifies the maximum number of failover attempts. // // When failover is triggered, GetFailoverModel will be called up to MaxRetries times // (FailoverAttempt starts from 1). If GetFailoverModel returns an error, failover // stops immediately and that error is returned. // // A value of 0 means no failover (GetFailoverModel will not be called). // A value of 1 means GetFailoverModel may be called once. // // Note: if lastSuccessModel is set (from a previous successful call), it will be tried // first before calling GetFailoverModel. MaxRetries uint // ShouldFailover determines whether to fail over to the next model when an error occurs. // It receives the output message (may be nil/zero if no output is available) and the error (non-nil on failure). // For streaming errors, outputMessage can carry a partial message accumulated before the error. // // Note: When ModelRetryConfig is also configured, outputErr will be a *RetryExhaustedError // (if retries were exhausted) rather than the original model error. Use errors.As to extract // the RetryExhaustedError and access RetryExhaustedError.LastErr for the original error. // // Note: When the context itself is cancelled (ctx.Err() != nil), failover will stop immediately // regardless of this function. However, if the model returns context.Canceled or context.DeadlineExceeded // as an error while the context is still active, this function will still be called. // Should not be nil when ModelFailoverConfig is set. // Return true to fail over to the next model, false to stop and return the current result/error. ShouldFailover func(ctx context.Context, outputMessage M, outputErr error) bool // GetFailoverModel is called when a model call fails and ShouldFailover returns true. // It selects the next model to use for the failover attempt and optionally transforms input messages. // It receives the failover context containing attempt number (starting from 1), original input, and last result. // Return values: // - failoverModel: The model to use for this failover attempt. // - failoverModelInputMessages: The transformed input messages for the failover model. If nil, will use original input. // - failoverErr: If non-nil, failover stops and this error is returned. // Should not be nil when ModelFailoverConfig is set via ChatModelAgentConfig. GetFailoverModel func(ctx context.Context, failoverCtx *FailoverContext[M]) ( failoverModel model.BaseModel[M], failoverModelInputMessages []M, failoverErr error) }
ModelFailoverConfig configures failover behavior for ChatModel. When configured, each ChatModel call first tries the last successful model (initially the configured Model), and if that fails, calls GetFailoverModel to select alternate models.
type ModelRetryConfig ¶ added in v0.7.14
type ModelRetryConfig = TypedModelRetryConfig[*schema.Message]
ModelRetryConfig is the default retry config type using *schema.Message.
type OnSubAgents ¶
type OnSubAgents interface {
OnSetSubAgents(ctx context.Context, subAgents []Agent) error
OnSetAsSubAgent(ctx context.Context, parent Agent) error
OnDisallowTransferToParent(ctx context.Context) error
}
OnSubAgents is the interface for agents that support sub-agent registration and transfer.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type ParallelAgentConfig ¶
ParallelAgentConfig is the configuration for NewParallelAgent.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type PushOption ¶ added in v0.9.0
type PushOption[T any, M MessageType] func(*pushConfig[T, M])
PushOption is an option for Push().
func WithPreempt ¶ added in v0.9.0
func WithPreempt[T any, M MessageType](safePoint SafePoint) PushOption[T, M]
WithPreempt signals that the current agent turn should be cancelled at the specified safePoint after pushing the new item. The loop cancels the current turn and starts a new one, where GenInput will see all buffered items including the newly pushed one. Use WithPreemptTimeout to add a timeout that escalates to immediate abort.
Because safe points fire at turn-level boundaries (after the chat model returns or after all tool calls complete), no nested agent is running at the moment of cancellation — nested agents within AgentTools have either not started yet (AfterChatModel) or already finished (AfterToolCalls). Note: WithPreempt does NOT include WithRecursive (no escalation path exists). WithPreemptTimeout DOES include WithRecursive so that on timeout escalation, nested agents are properly torn down.
WithPreempt and WithPreemptTimeout are mutually exclusive; if both are passed to the same Push call, the last one wins.
safePoint must not be zero; passing SafePoint(0) panics.
func WithPreemptDelay ¶ added in v0.9.0
func WithPreemptDelay[T any, M MessageType](delay time.Duration) PushOption[T, M]
WithPreemptDelay sets a delay duration before resolving a preemptive Push. When used with WithPreempt or WithPreemptTimeout, the pushed item is buffered immediately, while the preempt request is resolved after the delay against the turn observed by Push. If that captured turn has already ended, the request is resolved as a no-op and must not cancel a later turn.
func WithPreemptTimeout ¶ added in v0.9.0
func WithPreemptTimeout[T any, M MessageType](safePoint SafePoint, timeout time.Duration) PushOption[T, M]
WithPreemptTimeout is like WithPreempt but adds a timeout. If the agent has not reached the safe point within timeout, the preemption escalates to immediate cancellation. On escalation, nested agents inside AgentTools will also receive the cancel signal and be torn down.
safePoint must not be zero; passing SafePoint(0) panics.
func WithPushStrategy ¶ added in v0.9.0
func WithPushStrategy[T any, M MessageType](fn func(ctx context.Context, tc *TurnContext[T, M]) []PushOption[T, M]) PushOption[T, M]
WithPushStrategy provides dynamic push option resolution based on the current turn state. The callback receives the current turn's context and TurnContext (nil if no turn is active) and returns the actual PushOptions to apply. When WithPushStrategy is used, all other PushOptions passed to the same Push call are ignored.
The returned options must not contain another WithPushStrategy; any nested strategy is silently stripped.
Example: preempt only if the current turn is processing low-priority items:
loop.Push(urgentItem, WithPushStrategy(func(ctx context.Context, tc *TurnContext[MyItem, *schema.Message]) []PushOption[MyItem, *schema.Message] {
if tc == nil {
return nil // between turns, plain push
}
if isLowPriority(tc.Consumed) {
return []PushOption[MyItem, *schema.Message]{WithPreempt[MyItem, *schema.Message](AnySafePoint)}
}
return nil // don't preempt high-priority work
}))
type ResumableAgent ¶
type ResumableAgent = TypedResumableAgent[*schema.Message]
func NewLoopAgent ¶
func NewLoopAgent(ctx context.Context, config *LoopAgentConfig) (ResumableAgent, error)
NewLoopAgent creates an agent that loops over sub-agents with a max iteration limit.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func NewParallelAgent ¶
func NewParallelAgent(ctx context.Context, config *ParallelAgentConfig) (ResumableAgent, error)
NewParallelAgent creates an agent that runs sub-agents in parallel.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func NewSequentialAgent ¶
func NewSequentialAgent(ctx context.Context, config *SequentialAgentConfig) (ResumableAgent, error)
NewSequentialAgent creates an agent that runs sub-agents sequentially.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func SetSubAgents ¶
SetSubAgents sets sub-agents for the given agent and returns the updated agent.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type ResumeInfo ¶
type ResumeInfo struct {
// EnableStreaming indicates whether the original execution was in streaming mode.
EnableStreaming bool
// Deprecated: use InterruptContexts from the embedded InterruptInfo for user-facing details,
// and GetInterruptState for internal state retrieval.
*InterruptInfo
WasInterrupted bool
InterruptState any
IsResumeTarget bool
ResumeData any
}
ResumeInfo holds all the information necessary to resume an interrupted agent execution. It is created by the framework and passed to an agent's Resume method.
type ResumeParams ¶ added in v0.7.0
type ResumeParams struct {
// Targets contains the addresses of components to be resumed as keys,
// with their corresponding resume data as values
Targets map[string]any
}
ResumeParams contains all parameters needed to resume an execution. This struct provides an extensible way to pass resume parameters without requiring breaking changes to method signatures.
type RetryContext ¶ added in v0.9.0
type RetryContext = TypedRetryContext[*schema.Message]
RetryContext is the default retry context type using *schema.Message.
type RetryDecision ¶ added in v0.9.0
type RetryDecision = TypedRetryDecision[*schema.Message]
RetryDecision is the default retry decision type using *schema.Message.
type RetryExhaustedError ¶ added in v0.7.14
RetryExhaustedError is returned when all retry attempts have been exhausted. It wraps the last error that occurred during retry attempts.
func (*RetryExhaustedError) Error ¶ added in v0.7.14
func (e *RetryExhaustedError) Error() string
func (*RetryExhaustedError) Unwrap ¶ added in v0.7.14
func (e *RetryExhaustedError) Unwrap() error
type RunStep ¶
type RunStep struct {
// contains filtered or unexported fields
}
RunStep represents a step in the agent execution path. CheckpointSchema: persisted via serialization.RunCtx (gob).
NOT RECOMMENDED: RunStep is mainly relevant for agent transfer and workflow agents, which have not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type Runner ¶
type Runner = TypedRunner[*schema.Message]
Runner is the default runner type using *schema.Message.
type RunnerConfig ¶
type RunnerConfig = TypedRunnerConfig[*schema.Message]
RunnerConfig is the default runner config type using *schema.Message.
type SafePoint ¶ added in v0.9.0
type SafePoint int
SafePoint describes at which boundary the agent may be cancelled. It is a bitmask: values can be combined with bitwise OR to accept multiple safe points (e.g. AfterToolCalls | AfterChatModel). Internally, SafePoint is translated to CancelMode via toCancelMode().
SafePoint is used only in the preemption API (WithPreempt/WithPreemptTimeout). A key design constraint: preemption always targets a safe point — the user's intent is to cancel at a well-defined boundary, never to abort immediately. Immediate cancellation is only reachable as an automatic timeout escalation (via WithPreemptTimeout), not as a direct user choice. This is why SafePoint has no "immediate" value and why WithPreempt requires a non-zero SafePoint (panics otherwise).
const ( // AfterChatModel allows the agent to finish the current chat-model // call before being cancelled. AfterChatModel SafePoint = 1 << iota // AfterToolCalls allows the agent to finish the current tool-call round // before being cancelled. AfterToolCalls // AnySafePoint is shorthand for AfterChatModel | AfterToolCalls. AnySafePoint = AfterChatModel | AfterToolCalls )
type SequentialAgentConfig ¶
SequentialAgentConfig is the configuration for NewSequentialAgent.
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type StopOption ¶ added in v0.9.0
type StopOption func(*stopConfig)
StopOption is an option for Stop().
func UntilIdleFor ¶ added in v0.9.0
func UntilIdleFor(duration time.Duration) StopOption
UntilIdleFor defers the stop until the TurnLoop has been continuously idle (blocked between turns with no pending items) for at least the given duration. Each time a new item arrives the timer resets from zero.
This is useful when business code monitors agent activity externally and wants to shut down the loop once there has been no work for a while, without racing with concurrent Push calls.
UntilIdleFor does not impact a running agent. It only takes effect when the loop is idle between turns. Cancel options (WithImmediate, WithGraceful, WithGracefulTimeout) in the same Stop call are silently ignored — they are meaningless alongside UntilIdleFor.
To escalate after a prior UntilIdleFor, issue a separate Stop call:
loop.Stop(UntilIdleFor(30 * time.Second)) // wait for idle // ... later, if you need to abort immediately: loop.Stop(WithImmediate()) // overrides the idle wait
Only the first UntilIdleFor duration takes effect; subsequent calls with a different duration are ignored. A Stop() call without UntilIdleFor always shuts down the loop immediately regardless of any pending idle timer.
UntilIdleFor is combinable with non-cancel StopOptions (WithSkipCheckpoint, WithStopCause) in the same call.
duration must be positive; passing a zero or negative value panics.
func WithGraceful ¶ added in v0.9.0
func WithGraceful() StopOption
WithGraceful requests a graceful stop that waits at the nearest safe point (after tool calls or after a chat-model call) and propagates recursively to nested agents. It does not impose a time limit; use WithGracefulTimeout to add a grace period after which the stop escalates to immediate cancellation.
WithGraceful and WithGracefulTimeout are mutually exclusive; if both are passed to the same Stop call, the last one wins.
func WithGracefulTimeout ¶ added in v0.9.0
func WithGracefulTimeout(gracePeriod time.Duration) StopOption
WithGracefulTimeout is like WithGraceful but adds a grace period. If the agent has not reached a safe point within gracePeriod, the stop escalates to immediate cancellation.
gracePeriod must be positive; passing a zero or negative duration panics.
WithGraceful and WithGracefulTimeout are mutually exclusive; if both are passed to the same Stop call, the last one wins.
func WithImmediate ¶ added in v0.9.0
func WithImmediate() StopOption
WithImmediate aborts the running agent turn as soon as possible. The agent is cancelled immediately without waiting for any safe point. Nested agents inside AgentTools will also receive the cancel signal and be torn down.
This is the most aggressive stop mode — typically used when the caller wants to shut down the TurnLoop with no intention of resuming.
func WithSkipCheckpoint ¶ added in v0.9.0
func WithSkipCheckpoint() StopOption
WithSkipCheckpoint tells the TurnLoop not to persist a checkpoint for this Stop call. Use this when the caller does not intend to resume in the future. The flag is sticky: once any Stop() call sets it, subsequent calls cannot undo it.
func WithStopCause ¶ added in v0.9.0
func WithStopCause(cause string) StopOption
WithStopCause attaches a business-supplied reason string to this Stop call. The cause is surfaced in TurnLoopExitState.StopCause and, after the Stopped channel closes, via TurnContext.StopCause(). If multiple Stop() calls provide a cause, the first non-empty value wins.
type StreamCanceledError ¶ added in v0.9.0
type StreamCanceledError struct{}
StreamCanceledError is the concrete error type for ErrStreamCanceled. It is exported so that gob can serialize it during checkpoint save when the error is stored in agentEventWrapper.StreamErr.
func (*StreamCanceledError) Error ¶ added in v0.9.0
func (e *StreamCanceledError) Error() string
type StreamableToolCallEndpoint ¶ added in v0.8.0
type StreamableToolCallEndpoint func(ctx context.Context, argumentsInJSON string, opts ...tool.Option) (*schema.StreamReader[string], error)
StreamableToolCallEndpoint is the function signature for invoking a tool with streaming output. Middleware authors implement wrappers around this endpoint to add custom behavior.
type ToolCallsContext ¶ added in v0.9.0
type ToolCallsContext struct {
// ToolCalls contains the tool call metadata from the model's response.
ToolCalls []ToolContext
}
ToolCallsContext contains metadata about the tool calls that just completed.
type ToolContext ¶ added in v0.8.0
ToolContext provides metadata about the tool being wrapped.
type ToolsConfig ¶
type ToolsConfig struct {
compose.ToolsNodeConfig
// ReturnDirectly specifies tools that cause the agent to return immediately when called.
// The map keys are tool names indicate whether the tool should trigger immediate return.
ReturnDirectly map[string]bool
// EmitInternalEvents indicates whether internal events from agentTool should be emitted
// to the parent agent's AsyncGenerator, allowing real-time streaming of nested agent output
// to the end-user via Runner.
//
// Note that these forwarded events are NOT recorded in the parent agent's runSession.
// They are only emitted to the end-user and have no effect on the parent agent's state
// or checkpoint.
//
// Action Scoping:
// Actions emitted by the inner agent are scoped to the agent tool boundary:
// - Interrupted: Propagated via CompositeInterrupt to allow proper interrupt/resume
// - Exit, TransferToAgent, BreakLoop: Ignored outside the agent tool
EmitInternalEvents bool
}
type TransferToAgentAction ¶
type TransferToAgentAction struct {
DestAgentName string
}
TransferToAgentAction represents a transfer-to-agent action.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
type TurnContext ¶ added in v0.9.0
type TurnContext[T any, M MessageType] struct { // Loop is the TurnLoop instance, allowing Push() or Stop() calls. Loop *TurnLoop[T, M] // Consumed contains items that triggered this agent execution. Consumed []T // Preempted is closed when a preempt signal fires for the current turn // (via Push with WithPreempt/WithPreemptTimeout) and at least one // preemptive Push contributed to the CancelError for the current turn. // "Contributed" means the preempt's cancel options were included in the // CancelError before it was finalized. Remains open if no preempt contributed. // Use in a select to detect preemption while processing events. // // Both Preempted and Stopped may be closed within the same turn if both // signals arrive while the agent is still being cancelled. Whichever // arrives after the cancel is fully handled will not contribute. Preempted <-chan struct{} // Stopped is closed when a Stop() call contributed to the CancelError for the // current turn. // "Contributed" means Stop's cancel options were included in the CancelError // before it was finalized. Remains open if Stop did not contribute. // Use in a select to detect stop while processing events. // // See Preempted for the relationship between the two channels. Stopped <-chan struct{} // StopCause returns the business-supplied reason from WithStopCause. // This value is only meaningful after the Stopped channel is closed. // Before that, it returns an empty string. StopCause func() string }
TurnContext provides per-turn context to the OnAgentEvents callback.
type TurnLoop ¶ added in v0.9.0
type TurnLoop[T any, M MessageType] struct { // contains filtered or unexported fields }
TurnLoop is a push-based event loop for agent execution. Users push items via Push() and the loop processes them through the agent.
Create with NewTurnLoop, then start with Run:
loop := NewTurnLoop(cfg) // pass loop to other components, push initial items, etc. loop.Run(ctx)
Permissive API ¶
All methods are valid on a not-yet-running loop:
- Push: items are buffered and will be processed once Run is called.
- Stop: sets the stopped flag; a subsequent Run will exit immediately.
- Wait: blocks until Run is called AND the loop exits. If Run is never called, Wait blocks forever (this is a programming error, analogous to reading from a channel that nobody writes to).
func NewTurnLoop ¶ added in v0.9.0
func NewTurnLoop[T any, M MessageType](cfg TurnLoopConfig[T, M]) *TurnLoop[T, M]
NewTurnLoop creates a new TurnLoop without starting it. The returned loop accepts Push and Stop calls immediately; pushed items are buffered until Run is called. Call Run to start the processing goroutine.
NewTurnLoop panics if GenInput or PrepareAgent is nil.
func (*TurnLoop[T, M]) Push ¶ added in v0.9.0
func (l *TurnLoop[T, M]) Push(item T, opts ...PushOption[T, M]) (bool, <-chan struct{})
Push adds an item to the loop's buffer for processing. This method is non-blocking and thread-safe. Returns false if the loop has stopped, true otherwise. If a preemptive push succeeds, the second return value is a channel that callers can wait on to confirm the preempt request has been resolved. Specifically:
- If Push observes a planning or active turn that is still the target when the request resolves, the channel closes after TurnLoop attempts to submit cancel for that target turn.
- If Push observes no target turn, the loop has not started, the preempt subsystem is closed, or a delayed target is already gone, the channel closes as a no-op resolution.
If the loop has not been started yet (Run not called), items are buffered and will be processed once Run is called. After Wait() returns, failed pushes can be recovered via TurnLoopExitState.TakeLateItems(). Once TakeLateItems() has been called, any subsequent push that would become a late item will panic instead of being silently dropped.
Use WithPreempt() or WithPreemptTimeout() to atomically push an item and signal preemption of the current agent. This is useful for urgent items that should interrupt the current processing. The returned channel may be waited on if the caller needs to ensure the preempt signal has been observed.
Use WithPreemptDelay() together with WithPreempt()/WithPreemptTimeout() to delay request resolution. Push returns immediately after the item is buffered, and the delayed request remains bound to the turn observed by Push.
func (*TurnLoop[T, M]) Run ¶ added in v0.9.0
Run starts the loop's processing goroutine. It is non-blocking: the loop runs in the background and results are obtained via Wait.
If CheckpointID is configured in TurnLoopConfig and a matching checkpoint exists in Store, the loop automatically resumes from that checkpoint. Otherwise it starts fresh with whatever items were Push()-ed.
Calling Run more than once is a no-op: only the first call starts the loop.
func (*TurnLoop[T, M]) Stop ¶ added in v0.9.0
func (l *TurnLoop[T, M]) Stop(opts ...StopOption)
Stop signals the loop to stop and returns immediately (non-blocking). Without options, the current agent turn runs to completion and the loop exits at the turn boundary without starting a new turn. ExitReason is nil.
Use WithImmediate() to abort the running agent turn immediately. Use WithGraceful() to cancel at the nearest safe point with recursive propagation to nested agents. Use WithGracefulTimeout() for safe-point cancel with an escalation deadline. Use UntilIdleFor() to defer the stop until the loop has been continuously idle for a given duration; the loop shuts down automatically once the idle timer fires.
This method may be called multiple times; subsequent calls update cancel options. A Stop() call without UntilIdleFor shuts down the loop immediately, even if a prior UntilIdleFor is still waiting. Call Wait() to block until the loop has fully exited and get the result.
Stop may be called before Run. In that case, the stopped flag is set and a subsequent Run will exit the loop immediately.
If the running agent does not support the WithCancel AgentRunOption, all cancel-related options (WithImmediate, WithGraceful, WithGracefulTimeout) degrade to "exit the loop on entering the next iteration" — the current agent turn runs to completion before the loop exits.
func (*TurnLoop[T, M]) Wait ¶ added in v0.9.0
func (l *TurnLoop[T, M]) Wait() *TurnLoopExitState[T, M]
Wait blocks until the loop exits and returns the result. This method is safe to call from multiple goroutines. All callers will receive the same result.
Wait blocks until Run is called AND the loop exits. If Run is never called, Wait blocks forever.
type TurnLoopConfig ¶ added in v0.9.0
type TurnLoopConfig[T any, M MessageType] struct { // GenInput receives the TurnLoop instance and all buffered items, and decides what to process. // It returns which items to consume now vs keep for later turns. // The loop parameter allows calling Push() or Stop() directly from within the callback. // Required. GenInput func(ctx context.Context, loop *TurnLoop[T, M], items []T) (*GenInputResult[T, M], error) // GenResume is called at most once during Run(). When CheckpointID is // configured, Run() queries Store for the checkpoint: // - If the checkpoint contains runner state (i.e. an agent was interrupted // or canceled mid-turn), Run() calls GenResume to plan a resume turn. // - Otherwise (no checkpoint, or between-turns checkpoint), GenResume is // never called and the loop proceeds via GenInput. // // It receives: // - interruptedItems: the items being processed when the prior run was interrupted / canceled // - unhandledItems: items buffered but not processed when the prior run exited // - newItems: items that were Push()-ed before Run() was called // // It returns a GenResumeResult describing how to resume the interrupted agent // turn (optional ResumeParams) and how to manipulate the buffer // (Consumed/Remaining) before continuing. GenResume func(ctx context.Context, loop *TurnLoop[T, M], interruptedItems, unhandledItems, newItems []T) (*GenResumeResult[T, M], error) // PrepareAgent returns an Agent configured to handle the consumed items. // This callback should set up the agent with appropriate system prompt, // tools, and middlewares based on what items are being processed. // Called once per turn with the items that GenInput decided to consume. // The loop parameter allows calling Push() or Stop() directly from within the callback. // Required. PrepareAgent func(ctx context.Context, loop *TurnLoop[T, M], consumed []T) (TypedAgent[M], error) // OnAgentEvents is called to handle events emitted by the agent. // The TurnContext provides per-turn info and control: // - tc.Consumed: items that triggered this agent execution // - tc.Loop: allows calling Push() or Stop() directly from within the callback // - tc.Preempted / tc.Stopped: signals while processing events // // Error handling: the returned error is only used when the callback itself // wants to abort the TurnLoop. The callback should NEVER propagate // CancelError — the framework handles it automatically: // - Stop: the framework propagates CancelError as ExitReason, loop exits. // - Preempt: the framework does not propagate CancelError; if the callback // also returns nil, the loop continues with the next turn. // In practice, return a non-nil error only for callback-internal failures // that should terminate the loop. // // Optional. If not provided, events are drained and the first error // (including CancelError from Stop) is returned as ExitReason. OnAgentEvents func(ctx context.Context, tc *TurnContext[T, M], events *AsyncIterator[*TypedAgentEvent[M]]) error // Store is the checkpoint store for persistence and resume. Optional. // When set together with CheckpointID, enables automatic checkpoint-based resume. // The TurnLoop always persists both runner checkpoint bytes and item bookkeeping // (InterruptedItems, UnhandledItems) via gob encoding, so T must be gob-encodable // when Store is used. Store CheckPointStore // CheckpointID, when set together with Store, enables automatic // checkpoint-based resume. On Run(), the TurnLoop queries Store for this ID: // - If a checkpoint exists with runner state (mid-turn interrupt / cancel), // GenResume is called to plan the resume turn. // - If a checkpoint exists without runner state (between-turns), // the stored unhandled items are buffered and the loop proceeds // normally via GenInput. // - If no checkpoint exists, the loop starts fresh. // // On exit, if the TurnLoop saved a new checkpoint, it is saved under this // same CheckpointID. On clean exit (no checkpoint saved), the existing // checkpoint under CheckpointID is deleted to prevent stale resumption. CheckpointID string }
TurnLoopConfig is the configuration for creating a TurnLoop.
type TurnLoopExitState ¶ added in v0.9.0
type TurnLoopExitState[T any, M MessageType] struct { // ExitReason indicates why the loop exited. // nil means clean exit (Stop() was called without cancel options, or the // agent completed normally before Stop took effect). // Non-nil values include context errors, callback errors, *CancelError, etc. // When Stop(WithImmediate()) or Stop(WithGraceful()) cancels a running // agent, ExitReason will be a *CancelError. // This never contains checkpoint errors — see CheckpointErr for those. ExitReason error // UnhandledItems contains items that were buffered but not processed. // These are items for which Push returned true but were never consumed by a turn. // This is always valid regardless of ExitReason. UnhandledItems []T // InterruptedItems contains the items whose turn was interrupted — either by // a cancel (Stop with cancel options → *CancelError) or by a business // interrupt (AgentAction.Interrupted → *InterruptError). // On resume, these are passed to GenResume's interruptedItems parameter. InterruptedItems []T // StopCause is the business-supplied reason passed via WithStopCause. // Empty if Stop was not called or no cause was provided. StopCause string // CheckpointAttempted indicates whether a checkpoint save was attempted when the loop exited. // True when Store is configured, CheckpointID is set, the loop was not idle // at exit time, WithSkipCheckpoint was not used, and the exit was caused by // Stop() (clean or cancel) or a business interrupt (*InterruptError). CheckpointAttempted bool // CheckpointErr is the error from checkpoint save, if any. // nil when CheckpointAttempted is false (no attempt was made) or when the save succeeded. CheckpointErr error // TakeLateItems returns items that were pushed after the loop stopped // (i.e., Push returned false for these items). These items are NOT included // in the checkpoint. // // This function is idempotent: the first call computes and caches the result; // subsequent calls return the same slice. // // After TakeLateItems is called, any subsequent Push() will panic to // prevent items from being silently lost. // // It is safe to call TakeLateItems from any goroutine after Wait() returns. // If TakeLateItems is never called, late items are simply garbage collected. TakeLateItems func() []T }
TurnLoopExitState is returned when TurnLoop exits, containing the exit reason and any items that were not processed.
type TypedAgent ¶ added in v0.9.0
type TypedAgent[M MessageType] interface { Name(ctx context.Context) string Description(ctx context.Context) string // Run runs the agent. // The returned AgentEvent within the AsyncIterator must be safe to modify. // If the returned AgentEvent within the AsyncIterator contains MessageStream, // the MessageStream MUST be exclusive and safe to be received directly. // NOTE: it's recommended to use SetAutomaticClose() on the MessageStream of AgentEvents emitted by AsyncIterator, // so that even the events are not processed, the MessageStream can still be closed. Run(ctx context.Context, input *TypedAgentInput[M], options ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]] }
TypedAgent is the base agent interface parameterized by message type.
For M = *schema.Message, the full ADK feature set is supported (multi-agent orchestration, cancel monitoring, retry, flowAgent). For M = *schema.AgenticMessage, single-agent execution works but cancel monitoring on the model stream and retry are not yet wired.
type TypedAgentCallbackInput ¶ added in v0.9.0
type TypedAgentCallbackInput[M MessageType] struct { // Input contains the agent input for a new run. Nil when resuming. Input *TypedAgentInput[M] // ResumeInfo contains resume information when resuming from an interrupt. Nil for new runs. ResumeInfo *ResumeInfo }
TypedAgentCallbackInput represents the input passed to typed agent callbacks during OnStart. Use ConvTypedCallbackInput to safely convert from callbacks.CallbackInput.
func ConvTypedCallbackInput ¶ added in v0.9.0
func ConvTypedCallbackInput[M MessageType](input callbacks.CallbackInput) *TypedAgentCallbackInput[M]
ConvTypedCallbackInput converts a callbacks.CallbackInput to *TypedAgentCallbackInput[M]. Returns nil if the input is not of the expected type.
type TypedAgentCallbackOutput ¶ added in v0.9.0
type TypedAgentCallbackOutput[M MessageType] struct { // Events provides a stream of agent events. Each handler receives its own copy. Events *AsyncIterator[*TypedAgentEvent[M]] }
TypedAgentCallbackOutput represents the output passed to typed agent callbacks during OnEnd. Use ConvTypedCallbackOutput to safely convert from callbacks.CallbackOutput.
Important: The Events iterator should be consumed asynchronously to avoid blocking the agent execution. Each callback handler receives an independent copy of the iterator.
func ConvTypedCallbackOutput ¶ added in v0.9.0
func ConvTypedCallbackOutput[M MessageType](output callbacks.CallbackOutput) *TypedAgentCallbackOutput[M]
ConvTypedCallbackOutput converts a callbacks.CallbackOutput to *TypedAgentCallbackOutput[M]. Returns nil if the output is not of the expected type.
type TypedAgentEvent ¶ added in v0.9.0
type TypedAgentEvent[M MessageType] struct { AgentName string // RunPath represents the execution path from root agent to the current event source. // This field is managed entirely by the framework and cannot be set by end-users. // // NOT RECOMMENDED: RunPath is mainly relevant for agent transfer and workflow agents, // which have not proven to be more effective empirically. For ChatModelAgent with // AgentTool or DeepAgent, RunPath is trivial. Consider those patterns instead. RunPath []RunStep Output *TypedAgentOutput[M] Action *AgentAction Err error }
TypedAgentEvent represents a single event emitted during agent execution. CheckpointSchema: persisted via serialization.RunCtx (gob).
func EventFromAgenticMessage ¶ added in v0.9.0
func EventFromAgenticMessage(msg AgenticMessage, msgStream AgenticMessageStream, agenticRole schema.AgenticRoleType) *TypedAgentEvent[AgenticMessage]
EventFromAgenticMessage creates a TypedAgentEvent for the AgenticMessage path. Unlike EventFromMessage, it does not require role or toolName parameters because AgenticMessage carries tool results as ContentBlocks within the message itself, and does not support agent transfer.
agenticRole identifies the role of the message (e.g. schema.AgenticRoleTypeAssistant). In streaming mode, the role is available on the event before consuming the stream.
func TypedCompositeInterrupt ¶ added in v0.9.0
func TypedCompositeInterrupt[M MessageType](ctx context.Context, info any, state any, subInterruptSignals ...*InterruptSignal) *TypedAgentEvent[M]
TypedCompositeInterrupt creates a typed interrupt event that aggregates sub-interrupt signals. It is the generic counterpart of CompositeInterrupt; see CompositeInterrupt for full documentation.
func TypedGetMessage ¶ added in v0.9.0
func TypedGetMessage[M MessageType](e *TypedAgentEvent[M]) (M, *TypedAgentEvent[M], error)
TypedGetMessage extracts the message from a TypedAgentEvent, concatenating a stream if present.
func TypedInterrupt ¶ added in v0.9.0
func TypedInterrupt[M MessageType](ctx context.Context, info any) *TypedAgentEvent[M]
TypedInterrupt creates a typed interrupt event that pauses execution to request external input. It is the generic counterpart of Interrupt; see Interrupt for full documentation.
func TypedStatefulInterrupt ¶ added in v0.9.0
func TypedStatefulInterrupt[M MessageType](ctx context.Context, info any, state any) *TypedAgentEvent[M]
TypedStatefulInterrupt creates a typed interrupt event that also saves the agent's internal state. It is the generic counterpart of StatefulInterrupt; see StatefulInterrupt for full documentation.
type TypedAgentInput ¶ added in v0.9.0
type TypedAgentInput[M MessageType] struct { Messages []M EnableStreaming bool }
type TypedAgentOutput ¶ added in v0.9.0
type TypedAgentOutput[M MessageType] struct { MessageOutput *TypedMessageVariant[M] CustomizedOutput any }
type TypedBaseChatModelAgentMiddleware ¶ added in v0.9.0
type TypedBaseChatModelAgentMiddleware[M MessageType] struct{}
func (*TypedBaseChatModelAgentMiddleware[M]) AfterAgent ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) AfterAgent(ctx context.Context, state *TypedChatModelAgentState[M]) (context.Context, error)
func (*TypedBaseChatModelAgentMiddleware[M]) AfterModelRewriteState ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) AfterModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedChatModelAgentState[M], error)
func (*TypedBaseChatModelAgentMiddleware[M]) BeforeAgent ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) BeforeAgent(ctx context.Context, runCtx *ChatModelAgentContext) (context.Context, *ChatModelAgentContext, error)
func (*TypedBaseChatModelAgentMiddleware[M]) BeforeModelRewriteState ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) BeforeModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedChatModelAgentState[M], error)
func (*TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedInvokableToolCall ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedInvokableToolCall(_ context.Context, endpoint EnhancedInvokableToolCallEndpoint, _ *ToolContext) (EnhancedInvokableToolCallEndpoint, error)
func (*TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedStreamableToolCall ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) WrapEnhancedStreamableToolCall(_ context.Context, endpoint EnhancedStreamableToolCallEndpoint, _ *ToolContext) (EnhancedStreamableToolCallEndpoint, error)
func (*TypedBaseChatModelAgentMiddleware[M]) WrapInvokableToolCall ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) WrapInvokableToolCall(_ context.Context, endpoint InvokableToolCallEndpoint, _ *ToolContext) (InvokableToolCallEndpoint, error)
func (*TypedBaseChatModelAgentMiddleware[M]) WrapModel ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) WrapModel(_ context.Context, m model.BaseModel[M], _ *TypedModelContext[M]) (model.BaseModel[M], error)
func (*TypedBaseChatModelAgentMiddleware[M]) WrapStreamableToolCall ¶ added in v0.9.0
func (b *TypedBaseChatModelAgentMiddleware[M]) WrapStreamableToolCall(_ context.Context, endpoint StreamableToolCallEndpoint, _ *ToolContext) (StreamableToolCallEndpoint, error)
type TypedChatModelAgent ¶ added in v0.9.0
type TypedChatModelAgent[M MessageType] struct { // contains filtered or unexported fields }
TypedChatModelAgent is a chat model-backed agent parameterized by message type.
For M = *schema.Message, the full ReAct loop (model → tool calls → model) is used. For M = *schema.AgenticMessage, a single-shot chain is used since agentic models handle tool calling internally. Cancel monitoring and retry on the model stream are not yet supported for agentic models.
func NewTypedChatModelAgent ¶ added in v0.9.0
func NewTypedChatModelAgent[M MessageType](ctx context.Context, config *TypedChatModelAgentConfig[M]) (*TypedChatModelAgent[M], error)
NewTypedChatModelAgent creates a new TypedChatModelAgent with the given config.
func (*TypedChatModelAgent[M]) Description ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) Description(_ context.Context) string
func (*TypedChatModelAgent[M]) GetType ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) GetType() string
func (*TypedChatModelAgent[M]) Name ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) Name(_ context.Context) string
func (*TypedChatModelAgent[M]) OnDisallowTransferToParent ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) OnDisallowTransferToParent(_ context.Context) error
OnDisallowTransferToParent implements OnSubAgents.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func (*TypedChatModelAgent[M]) OnSetAsSubAgent ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) OnSetAsSubAgent(_ context.Context, parent TypedAgent[M]) error
OnSetAsSubAgent implements OnSubAgents.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func (*TypedChatModelAgent[M]) OnSetSubAgents ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) OnSetSubAgents(_ context.Context, subAgents []TypedAgent[M]) error
OnSetSubAgents implements OnSubAgents.
NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
func (*TypedChatModelAgent[M]) Resume ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
func (*TypedChatModelAgent[M]) Run ¶ added in v0.9.0
func (a *TypedChatModelAgent[M]) Run(ctx context.Context, input *TypedAgentInput[M], opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
type TypedChatModelAgentConfig ¶ added in v0.9.0
type TypedChatModelAgentConfig[M MessageType] struct { // Name of the agent. Better be unique across all agents. // Optional. If empty, the agent can still run standalone but cannot be used as // a sub-agent tool via NewAgentTool (which requires a non-empty Name). Name string // Description of the agent's capabilities. // Helps other agents determine whether to transfer tasks to this agent. // Optional. If empty, the agent can still run standalone but cannot be used as // a sub-agent tool via NewAgentTool (which requires a non-empty Description). Description string // Instruction used as the system prompt for this agent. // Optional. If empty, no system prompt will be used. // Supports f-string placeholders for session values in default GenModelInput, for example: // "You are a helpful assistant. The current time is {Time}. The current user is {User}." // These placeholders will be replaced with session values for "Time" and "User". Instruction string // Model is the chat model used by the agent. // If your ChatModelAgent uses any tools, this model must support the model.WithTools // call option, as that's how ChatModelAgent configures the model with tool information. Model model.BaseModel[M] ToolsConfig ToolsConfig // GenModelInput transforms instructions and input messages into the model's input format. // Optional. Defaults to defaultGenModelInput which combines instruction and messages. GenModelInput TypedGenModelInput[M] // Exit defines the tool used to terminate the agent process. // Optional. If nil, no Exit Action will be generated. // You can use the provided 'ExitTool' implementation directly. // // NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven // to be more effective empirically. Consider using ChatModelAgent with AgentTool // or DeepAgent instead for most multi-agent scenarios. Exit tool.BaseTool // OutputKey stores the agent's response in the session. // Optional. When set, stores output via AddSessionValue(ctx, outputKey, msg.Content). // // NOT RECOMMENDED: Agent transfer with full context sharing between agents has not proven // to be more effective empirically. Consider using ChatModelAgent with AgentTool // or DeepAgent instead for most multi-agent scenarios. OutputKey string // MaxIterations defines the upper limit of ChatModel generation cycles. // The agent will terminate with an error if this limit is exceeded. // Optional. Defaults to 20. MaxIterations int // Deprecated: Use Handlers instead. Middlewares will be removed in a future release. // Handlers provides a more flexible interface-based approach for extending agent behavior. Middlewares []AgentMiddleware // Handlers configures interface-based handlers for extending agent behavior. // Unlike Middlewares (struct-based), Handlers allow users to: // - Add custom methods to their handler implementations // - Return modified context from handler methods // - Centralize configuration in struct fields instead of closures // // Handlers are processed after Middlewares, in registration order. // See ChatModelAgentMiddleware documentation for when to use Handlers vs Middlewares. // // Execution Order (relative to AgentMiddleware and ToolsConfig): // // Model call lifecycle (outermost to innermost wrapper chain): // 1. AgentMiddleware.BeforeChatModel (hook, runs before model call) // 2. ChatModelAgentMiddleware.BeforeModelRewriteState (hook, can modify state before model call) // 3. failoverModelWrapper (internal - failover between models, if configured) // 4. retryModelWrapper (internal - retries on failure, if configured) // 5. eventSenderModelWrapper (internal - sends model response events) // 6. ChatModelAgentMiddleware.WrapModel (wrapper, first registered is outermost) // 7. callbackInjectionModelWrapper (internal - injects callbacks if not enabled; when failover is enabled, this is handled per-model inside failoverProxyModel instead) // 8. failoverProxyModel (internal - dispatches to selected failover model, if configured) / Model.Generate/Stream // 9. ChatModelAgentMiddleware.AfterModelRewriteState (hook, can modify state after model call) // 10. AgentMiddleware.AfterChatModel (hook, runs after model call) // // Custom Event Sender Position: // By default, events are sent after all user middlewares (WrapModel) have processed the output, // containing the modified messages. To send events with original (unmodified) output, pass // NewEventSenderModelWrapper as a Handler after the modifying middleware: // // agent, _ := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ // Handlers: []adk.ChatModelAgentMiddleware{ // myCustomHandler, // First registered = outermost wrapper // adk.NewEventSenderModelWrapper(), // Last registered = innermost, events sent with original output // }, // }) // // Handler order: first registered is outermost. So [A, B, C] becomes A(B(C(model))). // EventSenderModelWrapper sends events in post-processing, so placing it innermost // means it receives the original model output before outer handlers modify it. // // When EventSenderModelWrapper is detected in Handlers, the framework skips // the default event sender to avoid duplicate events. // // Tool call lifecycle (outermost to innermost): // 1. eventSenderToolWrapper (internal ToolMiddleware - sends tool result events after all processing) // 2. ToolsConfig.ToolCallMiddlewares (ToolMiddleware) // 3. AgentMiddleware.WrapToolCall (ToolMiddleware) // 4. ChatModelAgentMiddleware.WrapToolCall (wrapper, first registered is outermost) // 5. callbackInjectedToolCall (internal - injects callbacks if tool doesn't handle them) // 6. Tool.InvokableRun/StreamableRun // // Custom Tool Event Sender Position: // By default, tool result events are emitted by an internal event sender placed before // all user middlewares (outermost), so events reflect the fully processed tool output. // To control exactly where in the handler chain tool events are emitted, pass // NewEventSenderToolWrapper() as one of the Handlers. Its position determines which // middlewares' effects are visible in the emitted event: // // agent, _ := adk.NewChatModelAgent(ctx, &adk.ChatModelAgentConfig{ // Handlers: []adk.ChatModelAgentMiddleware{ // loggingHandler, // Outermost: sees event-sender output // adk.NewEventSenderToolWrapper(), // Events reflect output from handlers below // sanitizationHandler, // Innermost: runs first, modifies tool output // }, // }) // // Handler order: first registered is outermost. So [A, B, C] wraps as A(B(C(tool))). // The event sender captures tool output in post-processing, so its position controls // which handlers' modifications are included in the emitted events. // // When NewEventSenderToolWrapper is detected in Handlers, the framework skips // the default event sender to avoid duplicate events. // // Tool List Modification: // // There are two ways to modify the tool list: // // 1. In BeforeAgent: Modify ChatModelAgentContext.Tools ([]tool.BaseTool) directly. This affects // both the tool info list passed to ChatModel AND the actual tools available for // execution. Changes persist for the entire agent run. // // 2. In BeforeModelRewriteState: Modify state.ToolInfos and state.DeferredToolInfos directly. // This affects the tool info list passed to ChatModel for this and all subsequent model // calls (changes are persisted in state). This is the recommended approach for dynamic // tool filtering/selection based on conversation context. // // Modifying tools in WrapModel (e.g. via model.WithTools) is discouraged: changes there // are NOT persisted in state, only affect a single model call, and break prompt cache. Handlers []TypedChatModelAgentMiddleware[M] // ModelRetryConfig configures retry behavior for the ChatModel. // When set, the agent will automatically retry failed ChatModel calls // based on the configured policy. // Optional. If nil, no retry will be performed. ModelRetryConfig *TypedModelRetryConfig[M] // ModelFailoverConfig configures failover behavior for the ChatModel. // When set, the agent will first try the last successful model (initially the configured Model), // and on failure, call GetFailoverModel to select alternate models. // Model field is still required as it serves as the initial model. // Optional. If nil, no failover will be performed. ModelFailoverConfig *ModelFailoverConfig[M] }
TypedChatModelAgentConfig is the generic configuration for ChatModelAgent.
type TypedChatModelAgentMiddleware ¶ added in v0.9.0
type TypedChatModelAgentMiddleware[M MessageType] interface { // BeforeAgent is called before each agent run, allowing modification of // the agent's instruction and tools configuration. BeforeAgent(ctx context.Context, runCtx *ChatModelAgentContext) (context.Context, *ChatModelAgentContext, error) // AfterAgent is called after the agent run reaches a successful terminal state. // Successful terminal states are: final answer (model response with no tool calls), // and return-directly tool result. // // AfterAgent is NOT called when the agent terminates with an error (e.g., // ErrExceedMaxIterations, context cancellation, model errors). // // The state parameter contains the final conversation state, including all messages // from the completed run. // // AfterAgent handlers are called in the same order as BeforeAgent handlers // (first registered = first called). Consistent with all other middleware hooks, // if any handler returns an error, subsequent handlers are NOT called (fail-fast) // and the error is sent to the event stream. AfterAgent(ctx context.Context, state *TypedChatModelAgentState[M]) (context.Context, error) // BeforeModelRewriteState is called before each model invocation. // The returned state is persisted to the agent's internal state and passed to the model. // The returned context is propagated to the model call and subsequent handlers. // // The ChatModelAgentState struct provides access to: // - Messages: the conversation history // - ToolInfos: the tool list that will be sent to the model (modifiable) // - DeferredToolInfos: tools for server-side search (modifiable, nil if unused) // // This is the recommended place to modify messages and tools before a model call. // Changes here are persisted in state and reflected in subsequent iterations. BeforeModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedChatModelAgentState[M], error) // AfterModelRewriteState is called after each model invocation. // The input state includes the model's response as the last message. // The returned state is persisted to the agent's internal state. // // The ChatModelAgentState struct provides access to: // - Messages: the conversation history including the model's response // - ToolInfos: the tool list that was sent to the model // - DeferredToolInfos: tools for server-side search (nil if unused) AfterModelRewriteState(ctx context.Context, state *TypedChatModelAgentState[M], mc *TypedModelContext[M]) (context.Context, *TypedChatModelAgentState[M], error) // WrapInvokableToolCall wraps a tool's synchronous execution with custom behavior. // Return the input endpoint unchanged and nil error if no wrapping is needed. // // This method is only called for tools that implement InvokableTool. // If a tool only implements StreamableTool, this method will not be called for that tool. // // This method is called at request time when the tool is about to be executed. // The tCtx parameter provides metadata about the tool: // - Name: The name of the tool being wrapped // - CallID: The unique identifier for this specific tool call WrapInvokableToolCall(ctx context.Context, endpoint InvokableToolCallEndpoint, tCtx *ToolContext) (InvokableToolCallEndpoint, error) // WrapStreamableToolCall wraps a tool's streaming execution with custom behavior. // Return the input endpoint unchanged and nil error if no wrapping is needed. // // This method is only called for tools that implement StreamableTool. // If a tool only implements InvokableTool, this method will not be called for that tool. // // This method is called at request time when the tool is about to be executed. // The tCtx parameter provides metadata about the tool: // - Name: The name of the tool being wrapped // - CallID: The unique identifier for this specific tool call WrapStreamableToolCall(ctx context.Context, endpoint StreamableToolCallEndpoint, tCtx *ToolContext) (StreamableToolCallEndpoint, error) // WrapEnhancedInvokableToolCall wraps an enhanced tool's synchronous execution with custom behavior. // Return the input endpoint unchanged and nil error if no wrapping is needed. // // This method is only called for tools that implement EnhancedInvokableTool. // If a tool only implements EnhancedStreamableTool, this method will not be called for that tool. // // This method is called at request time when the tool is about to be executed. // The tCtx parameter provides metadata about the tool: // - Name: The name of the tool being wrapped // - CallID: The unique identifier for this specific tool call WrapEnhancedInvokableToolCall(ctx context.Context, endpoint EnhancedInvokableToolCallEndpoint, tCtx *ToolContext) (EnhancedInvokableToolCallEndpoint, error) // WrapEnhancedStreamableToolCall wraps an enhanced tool's streaming execution with custom behavior. // Return the input endpoint unchanged and nil error if no wrapping is needed. // // This method is only called for tools that implement EnhancedStreamableTool. // If a tool only implements EnhancedInvokableTool, this method will not be called for that tool. // // This method is called at request time when the tool is about to be executed. // The tCtx parameter provides metadata about the tool: // - Name: The name of the tool being wrapped // - CallID: The unique identifier for this specific tool call WrapEnhancedStreamableToolCall(ctx context.Context, endpoint EnhancedStreamableToolCallEndpoint, tCtx *ToolContext) (EnhancedStreamableToolCallEndpoint, error) // WrapModel wraps a chat model with custom behavior around the actual model call. // Return the input model unchanged and nil error if no wrapping is needed. // // This method is called at request time when the model is about to be invoked. // Note: The parameter is model.BaseModel[M] (not ToolCallingChatModel) because wrappers // only need to intercept Generate/Stream calls. Tool binding (WithTools) is handled // separately by the framework and does not flow through user wrappers. // // Recommended use cases (behavior around the model call itself): // - Model call retry logic // - Model failover (switching to a backup model) // - Sending events (e.g. streaming progress) // - Processing or transforming the response stream // - Changing call configurations (temperature, top_p, etc.) // // Discouraged use cases (use BeforeModelRewriteState instead): // - Modifying input messages: changes here are NOT persisted in state, only // affect a single model call, and break prompt cache across iterations. // - Modifying the tool list: use state.ToolInfos / state.DeferredToolInfos in // BeforeModelRewriteState, which is the source of truth for tool configuration. // // The mc parameter provides read-only context about the current model call: // - Tools: The tool infos that will be sent to the model (Deprecated: read state.ToolInfos instead) WrapModel(ctx context.Context, m model.BaseModel[M], mc *TypedModelContext[M]) (model.BaseModel[M], error) }
TypedChatModelAgentMiddleware defines the interface for customizing TypedChatModelAgent behavior.
IMPORTANT: This interface is specifically designed for TypedChatModelAgent and agents built on top of it (e.g., DeepAgent).
Why TypedChatModelAgentMiddleware instead of AgentMiddleware?
AgentMiddleware is a struct type, which has inherent limitations:
- Struct types are closed: users cannot add new methods to extend functionality
- The framework only recognizes AgentMiddleware's fixed fields, so even if users embed AgentMiddleware in a custom struct and add methods, the framework cannot call those methods (config.Middlewares is []AgentMiddleware, not a user type)
- Callbacks in AgentMiddleware only return error, cannot return modified context
TypedChatModelAgentMiddleware is an interface type, which is open for extension:
- Users can implement custom handlers with arbitrary internal state and methods
- Hook methods return (context.Context, ..., error) for direct context propagation
- Wrapper methods (WrapToolCall, WrapModel) enable context propagation through the wrapped endpoint chain: wrappers can pass modified context to the next wrapper
- Configuration is centralized in struct fields rather than scattered in closures
TypedChatModelAgentMiddleware vs AgentMiddleware:
- Use AgentMiddleware for simple, static additions (extra instruction/tools)
- Use TypedChatModelAgentMiddleware for dynamic behavior, context modification, or call wrapping
- AgentMiddleware is kept for backward compatibility with existing users
- Both can be used together; see AgentMiddleware documentation for execution order
Use *TypedBaseChatModelAgentMiddleware as an embedded struct to provide default no-op implementations for all methods.
type TypedChatModelAgentState ¶ added in v0.9.0
type TypedChatModelAgentState[M MessageType] struct { // Messages contains all messages in the current conversation session. Messages []M // ToolInfos contains the tool definitions passed to the model via model.WithTools. // BeforeModelRewriteState handlers can read and modify this field to control which tools // the model sees on each call. ToolInfos []*schema.ToolInfo // DeferredToolInfos contains tool definitions for server-side deferred retrieval, // passed to the model via model.WithDeferredTools. These tools are not included in the // immediate tool list but can be discovered by the model through its native search capability. // Nil when not in use. DeferredToolInfos []*schema.ToolInfo }
TypedChatModelAgentState represents the state of a chat model agent during conversation. This is the primary state type for both TypedChatModelAgentMiddleware and AgentMiddleware callbacks.
type TypedGenModelInput ¶ added in v0.9.0
type TypedGenModelInput[M MessageType] func(ctx context.Context, instruction string, input *TypedAgentInput[M]) ([]M, error)
TypedGenModelInput transforms the agent's system instruction and user input into model input messages ([]M). This is the primary customization point for controlling what the model sees. The default implementation prepends a system message (if instruction is non-empty), followed by the user's input messages.
type TypedMessageVariant ¶ added in v0.9.0
type TypedMessageVariant[M MessageType] struct { IsStreaming bool Message M MessageStream *schema.StreamReader[M] // Role indicates the origin of this event within the agent's ReAct loop. // Only meaningful for *schema.Message events: // - schema.Assistant: the event carries model output (generation or stream). // - schema.Tool: the event carries a tool execution result. // Always zero-valued for *schema.AgenticMessage events; use AgenticRole instead. Role schema.RoleType // AgenticRole indicates the role of the agentic message (assistant, user, system). // Only meaningful for *schema.AgenticMessage events. // In streaming mode, this is available before consuming the stream. // Always zero-valued for *schema.Message events; use Role instead. AgenticRole schema.AgenticRoleType // ToolName is the name of the tool that produced this event. // Only meaningful for *schema.Message events: non-empty when Role == schema.Tool. // In streaming mode, this is the only way to identify the source tool before // the stream is consumed. // Always empty for *schema.AgenticMessage events. ToolName string }
TypedMessageVariant represents a message output from an agent event. It carries either a complete message or a streaming reader, along with metadata describing the event's origin.
Role and ToolName are only meaningful for *schema.Message events. For *schema.AgenticMessage events (created via EventFromAgenticMessage), these fields are always zero-valued because AgenticMessage carries tool results as ContentBlocks within the message itself and does not support agent transfer.
For *schema.Message events, Role and ToolName exist independently of the inner Message because in streaming mode (IsStreaming=true, Message=nil), the message has not materialized yet and the consumer needs metadata without consuming the stream.
func (*TypedMessageVariant[M]) GetMessage ¶ added in v0.9.0
func (mv *TypedMessageVariant[M]) GetMessage() (M, error)
func (*TypedMessageVariant[M]) GobDecode ¶ added in v0.9.0
func (mv *TypedMessageVariant[M]) GobDecode(b []byte) error
func (*TypedMessageVariant[M]) GobEncode ¶ added in v0.9.0
func (mv *TypedMessageVariant[M]) GobEncode() ([]byte, error)
type TypedModelContext ¶ added in v0.9.0
type TypedModelContext[M MessageType] struct { // Tools contains the current tool list configured for the agent. // This is populated at request time with the tools that will be sent to the model. // // Deprecated: Use TypedChatModelAgentState.ToolInfos in BeforeModelRewriteState instead. // ModelContext.Tools remains populated for backward compatibility with existing WrapModel handlers, // but new code should read and modify state.ToolInfos which is the source of truth for the model call. Tools []*schema.ToolInfo // ModelRetryConfig contains the retry configuration for the model. // This is populated at request time from the agent's ModelRetryConfig. // Used by EventSenderModelWrapper to wrap stream errors appropriately. ModelRetryConfig *TypedModelRetryConfig[M] // ModelFailoverConfig contains the failover configuration for the model. // This is populated at request time from the agent's ModelFailoverConfig. // Used by EventSenderModelWrapper to wrap stream errors so that failed failover // attempts are skipped (not treated as fatal) by the flow event processor. ModelFailoverConfig *ModelFailoverConfig[M] // contains filtered or unexported fields }
TypedModelContext contains context information passed to WrapModel.
type TypedModelRetryConfig ¶ added in v0.9.0
type TypedModelRetryConfig[M MessageType] struct { // MaxRetries specifies the maximum number of retry attempts. // A value of 0 means no retries will be attempted. // A value of 3 means up to 3 retry attempts (4 total calls including the initial attempt). MaxRetries int // ShouldRetry determines how to handle a model call result. // It receives context information about the current attempt including the output message // and/or error, and returns a decision on whether to retry, what to modify, etc. // Returning nil is treated as &RetryDecision{Retry: false} (accept as-is). // // If nil, defaults to retrying on any non-nil error (backward compatible with IsRetryAble). // // Note: When ShouldRetry is set, IsRetryAble is ignored. // Note: In streaming mode, the entire stream is consumed before ShouldRetry is called. // The event stream is sent to the client in real time regardless; only the retry // decision is deferred until the full response is available. ShouldRetry func(ctx context.Context, retryCtx *TypedRetryContext[M]) *TypedRetryDecision[M] // Deprecated: Use ShouldRetry instead for richer retry control including message // inspection, input modification, and option adjustment. When ShouldRetry is set, // IsRetryAble is ignored. IsRetryAble func(ctx context.Context, err error) bool // BackoffFunc calculates the delay before the next retry attempt. // The attempt parameter starts at 1 for the first retry. // Used as the default when RetryDecision.Backoff is zero. // If nil, a default exponential backoff with jitter is used: // base delay 100ms, exponentially increasing up to 10s max, // with random jitter (0-50% of delay) to prevent thundering herd. BackoffFunc func(ctx context.Context, attempt int) time.Duration }
TypedModelRetryConfig configures retry behavior for the ChatModel node. It defines how the agent should handle transient failures when calling the ChatModel.
type TypedResumableAgent ¶ added in v0.9.0
type TypedResumableAgent[M MessageType] interface { TypedAgent[M] Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]] }
type TypedRetryContext ¶ added in v0.9.0
type TypedRetryContext[M MessageType] struct { // RetryAttempt is the current retry attempt number (1-based). // For the first retry decision (after the initial call), this is 1. RetryAttempt int // InputMessages is the input messages that were sent to the model for the current attempt. InputMessages []M // Options is the model options that were used for the current attempt. Options []model.Option // OutputMessage is the output message from the model, if any. // This is non-nil when the model returned a message successfully. // For streaming, this is the fully concatenated message (the entire stream is consumed // before ShouldRetry is called). // For streaming with mid-stream errors, this is the partial concatenation of chunks // received before the error occurred. // May be nil if the model returned an error without producing a message, or if the // stream was empty (zero chunks before EOF). OutputMessage M // Err is the error from the model call, if any. // May be nil if the model produced a message without error. // Note: both OutputMessage and Err can be nil simultaneously for empty streams. Err error }
TypedRetryContext contains context information passed to TypedModelRetryConfig.ShouldRetry during a retry decision.
State combinations for OutputMessage and Err:
OutputMessage != nil, Err == nil → successful call; inspect message quality OutputMessage == nil, Err != nil → failed call (Generate error or Stream() error) OutputMessage != nil, Err != nil → partial stream (chunks received before mid-stream error) OutputMessage == nil, Err == nil → empty stream (zero chunks before EOF)
type TypedRetryDecision ¶ added in v0.9.0
type TypedRetryDecision[M MessageType] struct { // Retry indicates whether the model call should be retried. // If false, the model output (or error) is accepted as-is, unless RewriteError is set. Retry bool // RewriteError, when non-nil, overrides the return value of the model call with this error. // The agent run will fail with this error. // // This is useful for two scenarios: // - When the model returns a "seemingly correct" message (no error) that actually // contains unrecoverable issues. RewriteError converts the successful output // into a fatal error. // - When the model returns an error, but you want to replace it with a different, // more descriptive error (e.g., adding context or wrapping). // // When Retry is true, RewriteError is ignored. // When Retry is false and RewriteError is non-nil, the model call returns // RewriteError regardless of whether the original call had an error or a message. RewriteError error // ModifiedInputMessages, when non-nil, replaces the input messages for the next retry. // // This enables advanced recovery strategies like context compression or message trimming. // Only used when Retry is true. Ignored when Retry is false. ModifiedInputMessages []M // PersistModifiedInputMessages controls whether ModifiedInputMessages are written // back to the agent's conversation history, affecting subsequent model calls in // the agent loop (not just the next retry attempt). // // When true, the modified messages replace the current conversation history. // When false (default), the modified messages are only used for the next retry attempt // within this retry cycle. // // Only used when Retry is true and ModifiedInputMessages is non-nil. PersistModifiedInputMessages bool // AdditionalOptions, when non-nil, provides additional model options for the next retry. // These options are appended to the existing options, taking precedence via last-wins semantics. // // This enables adjustments like increasing MaxTokens for the retry attempt. // Note: options accumulate across retries within a single retry cycle. If ShouldRetry // returns AdditionalOptions on every attempt, each set is appended to the previous ones. // Only the last value for each option key takes effect, but earlier values remain in the slice. // AdditionalOptions are scoped to the current retry cycle and do not persist to subsequent // agent iterations — each new model call in the agent loop starts with the original options. // Only used when Retry is true. Ignored when Retry is false. AdditionalOptions []model.Option // Backoff specifies the duration to wait before the next retry attempt. // If zero, the default backoff function (from ModelRetryConfig.BackoffFunc or the // built-in exponential backoff) is used. // // This allows the ShouldRetry callback to dynamically control retry timing based on // the specific error or problematic message encountered. // Only used when Retry is true. Ignored when Retry is false. Backoff time.Duration // RejectReason is an optional user-defined value describing why the output was rejected. // When Retry is true and the rejected stream/message is observed downstream via // AgentEvent, this value is attached to the WillRetryError emitted to the event stream. // Consumers can retrieve it via WillRetryError.RejectReason(). // // The ShouldRetry callback has full access to the model output (via retryCtx.OutputMessage) // and error (via retryCtx.Err), so it can distill whatever information it wants into // RejectReason — a string, a struct, the output message itself, or nil. // // Only used when Retry is true. Ignored when Retry is false. RejectReason any }
TypedRetryDecision represents the decision made by TypedModelRetryConfig.ShouldRetry.
type TypedRunner ¶ added in v0.9.0
type TypedRunner[M MessageType] struct { // contains filtered or unexported fields }
TypedRunner is the primary entry point for executing an Agent. It manages the agent's lifecycle, including starting, resuming, and checkpointing.
Execution always goes through the flowAgent pipeline, which handles multi-agent orchestration, callbacks, agent naming, run paths, and cancellation.
func NewTypedRunner ¶ added in v0.9.0
func NewTypedRunner[M MessageType](conf TypedRunnerConfig[M]) *TypedRunner[M]
NewTypedRunner creates a new TypedRunner with the given config.
func (*TypedRunner[M]) Query ¶ added in v0.9.0
func (r *TypedRunner[M]) Query(ctx context.Context, query string, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
Query is a convenience method that starts a new execution with a single user query string.
func (*TypedRunner[M]) Resume ¶ added in v0.9.0
func (r *TypedRunner[M]) Resume(ctx context.Context, checkPointID string, opts ...AgentRunOption) ( *AsyncIterator[*TypedAgentEvent[M]], error)
Resume continues an interrupted execution from a checkpoint, using an "Implicit Resume All" strategy. This method is best for simpler use cases where the act of resuming implies that all previously interrupted points should proceed without specific data.
When using this method, all interrupted agents will receive `isResumeFlow = false` when they call `GetResumeContext`, as no specific agent was targeted. This is suitable for the "Simple Confirmation" pattern where an agent only needs to know `wasInterrupted` is true to continue.
func (*TypedRunner[M]) ResumeWithParams ¶ added in v0.9.0
func (r *TypedRunner[M]) ResumeWithParams(ctx context.Context, checkPointID string, params *ResumeParams, opts ...AgentRunOption) (*AsyncIterator[*TypedAgentEvent[M]], error)
ResumeWithParams continues an interrupted execution from a checkpoint with specific parameters. This is the most common and powerful way to resume, allowing you to target specific interrupt points (identified by their address/ID) and provide them with data.
The params.Targets map should contain the addresses of the components to be resumed as keys. These addresses can point to any interruptible component in the entire execution graph, including ADK agents, compose graph nodes, or tools. The value can be the resume data for that component, or `nil` if no data is needed.
When using this method:
- Components whose addresses are in the params.Targets map will receive `isResumeFlow = true` when they call `GetResumeContext`.
- Interrupted components whose addresses are NOT in the params.Targets map must decide how to proceed: -- "Leaf" components (the actual root causes of the original interrupt) MUST re-interrupt themselves to preserve their state. -- "Composite" agents (like SequentialAgent or ChatModelAgent) should generally proceed with their execution. They act as conduits, allowing the resume signal to flow to their children. They will naturally re-interrupt if one of their interrupted children re-interrupts, as they receive the new `CompositeInterrupt` signal from them.
func (*TypedRunner[M]) Run ¶ added in v0.9.0
func (r *TypedRunner[M]) Run(ctx context.Context, messages []M, opts ...AgentRunOption) *AsyncIterator[*TypedAgentEvent[M]]
type TypedRunnerConfig ¶ added in v0.9.0
type TypedRunnerConfig[M MessageType] struct { Agent TypedAgent[M] EnableStreaming bool CheckPointStore CheckPointStore }
type WillRetryError ¶ added in v0.7.14
type WillRetryError struct {
ErrStr string
RetryAttempt int
// contains filtered or unexported fields
}
WillRetryError is emitted when a retryable error occurs and a retry will be attempted. It allows end-users to observe retry events in real-time via AgentEvent.
Field design rationale:
- ErrStr (exported): Stores the error message string for Gob serialization during checkpointing. This ensures the error message is preserved after checkpoint restore.
- err (unexported): Stores the original error for Unwrap() support at runtime. This field is intentionally unexported because Gob serialization would fail for unregistered concrete error types. Since end-users only need the original error when the AgentEvent first occurs (not after restoring from checkpoint), skipping serialization is acceptable. After checkpoint restore, err will be nil and Unwrap() returns nil.
- rejectReason (unexported): Stores a user-defined value set by the ShouldRetry callback via RetryDecision.RejectReason. This is runtime-only observability data — after checkpoint restore it will be nil. Unexported to avoid Gob serialization of arbitrary types.
func (*WillRetryError) Error ¶ added in v0.7.14
func (e *WillRetryError) Error() string
func (*WillRetryError) RejectReason ¶ added in v0.9.0
func (e *WillRetryError) RejectReason() any
RejectReason returns the user-defined rejection reason set by the ShouldRetry callback via RetryDecision.RejectReason. Returns nil if not set or after checkpoint restore.
func (*WillRetryError) Unwrap ¶ added in v0.7.24
func (e *WillRetryError) Unwrap() error
type WorkflowInterruptInfo ¶
type WorkflowInterruptInfo struct {
OrigInput *AgentInput
SequentialInterruptIndex int
SequentialInterruptInfo *InterruptInfo
LoopIterations int
ParallelInterruptInfo map[int]*InterruptInfo
}
WorkflowInterruptInfo stores interrupt information for workflow agents. CheckpointSchema: persisted via InterruptInfo.Data (gob).
NOT RECOMMENDED: Workflow agents are built on agent transfer with full context sharing, which has not proven to be more effective empirically. Consider using ChatModelAgent with AgentTool or DeepAgent instead for most multi-agent scenarios.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package filesystem provides file system operations.
|
Package filesystem provides file system operations. |
|
Package internal provides adk internal utils.
|
Package internal provides adk internal utils. |
|
middlewares
|
|
|
agentsmd
Package agentsmd provides a middleware that automatically injects Agents.md file contents into model input messages.
|
Package agentsmd provides a middleware that automatically injects Agents.md file contents into model input messages. |
|
dynamictool/toolsearch
Package toolsearch provides tool search middleware.
|
Package toolsearch provides tool search middleware. |
|
filesystem
Package filesystem provides middlewares.
|
Package filesystem provides middlewares. |
|
patchtoolcalls
Package patchtoolcalls provides a middleware that patches dangling tool calls in the message history.
|
Package patchtoolcalls provides a middleware that patches dangling tool calls in the message history. |
|
reduction
Package reduction provides middlewares to trim context and clear tool results.
|
Package reduction provides middlewares to trim context and clear tool results. |
|
reduction/internal
Package internal provides middlewares to trim context and clear tool results.
|
Package internal provides middlewares to trim context and clear tool results. |
|
skill
Package skill provides a Skill middleware, types, and a local filesystem backend.
|
Package skill provides a Skill middleware, types, and a local filesystem backend. |
|
summarization
Package summarization provides a middleware that automatically summarizes conversation history when token count exceeds the configured threshold.
|
Package summarization provides a middleware that automatically summarizes conversation history when token count exceeds the configured threshold. |
|
prebuilt
|
|
|
deep
Package deep provides a prebuilt agent with deep task orchestration.
|
Package deep provides a prebuilt agent with deep task orchestration. |
|
planexecute
Package planexecute implements a plan–execute–replan style agent.
|
Package planexecute implements a plan–execute–replan style agent. |
|
supervisor
Package supervisor implements the supervisor pattern for multi-agent systems, where a central agent coordinates a set of sub-agents.
|
Package supervisor implements the supervisor pattern for multi-agent systems, where a central agent coordinates a set of sub-agents. |