adk

package
v0.8.0-alpha.13 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 27, 2026 License: Apache-2.0 Imports: 31 Imported by: 63

Documentation

Overview

Package adk provides core agent development kit utilities and types.

Index

Constants

View Source
const (
	TransferToAgentToolName        = "transfer_to_agent"
	TransferToAgentToolDesc        = "Transfer the question to another agent."
	TransferToAgentToolDescChinese = "将问题移交给其他 Agent。"
)
View Source
const (
	TransferToAgentInstruction = `` /* 268-byte string literal not displayed */

	TransferToAgentInstructionChinese = `` /* 303-byte string literal not displayed */

)
View Source
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.

Variables

View Source
var ErrExceedMaxIterations = errors.New("exceeds max iterations")

ErrExceedMaxIterations indicates the agent reached the maximum iterations limit.

View Source
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")
)
View Source
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

func AddSessionValue(ctx context.Context, key string, value any)

AddSessionValue sets a single session key-value pair for the current run.

func AddSessionValues

func AddSessionValues(ctx context.Context, kvs map[string]any)

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

func ClearRunCtx(ctx context.Context) context.Context

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

func DeleteRunLocalValue(ctx context.Context, key string) error

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 GenTransferMessages

func GenTransferMessages(_ context.Context, destAgentName string) (Message, Message)

GenTransferMessages generates assistant and tool messages to instruct a transfer-to-agent tool call targeting the destination agent.

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 GetRunLocalValue

func GetRunLocalValue(ctx context.Context, key string) (any, bool, error)

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

func GetSessionValue(ctx context.Context, key string) (any, bool)

GetSessionValue retrieves a session value by key and reports whether it exists.

func GetSessionValues

func GetSessionValues(ctx context.Context) map[string]any

GetSessionValues returns all session key-value pairs for the current run.

func NewAgentTool

func NewAgentTool(_ context.Context, agent Agent, options ...AgentToolOption) tool.BaseTool

NewAgentTool creates a tool that wraps an agent for invocation.

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 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

func SetLanguage(lang Language) error

SetLanguage sets the language for the ADK built-in prompts. The default language is English if not explicitly set.

func SetRunLocalValue

func SetRunLocalValue(ctx context.Context, key string, value any) error

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.

Types

type Address added in v0.7.0

type Address = core.Address

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 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 *AgentInput, options ...AgentRunOption) *AsyncIterator[*AgentEvent]
}

func AgentWithDeterministicTransferTo

func AgentWithDeterministicTransferTo(_ context.Context, config *DeterministicTransferConfig) Agent

AgentWithDeterministicTransferTo wraps an agent to transfer to given agents deterministically.

func AgentWithOptions

func AgentWithOptions(ctx context.Context, agent Agent, opts ...AgentOption) Agent

AgentWithOptions wraps an agent with flow-specific options and returns it.

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.

func NewExitAction

func NewExitAction() *AgentAction

NewExitAction creates an action that signals the agent to exit.

func NewTransferToAgentAction

func NewTransferToAgentAction(destAgentName string) *AgentAction

NewTransferToAgentAction creates an action to transfer to the specified agent.

type AgentCallbackInput

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

func ConvAgentCallbackInput(input callbacks.CallbackInput) *AgentCallbackInput

ConvAgentCallbackInput converts a generic CallbackInput to AgentCallbackInput. Returns nil if the input is not an AgentCallbackInput.

type AgentCallbackOutput

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

func ConvAgentCallbackOutput(output callbacks.CallbackOutput) *AgentCallbackOutput

ConvAgentCallbackOutput converts a generic CallbackOutput to AgentCallbackOutput. Returns nil if the output is not an AgentCallbackOutput.

type AgentEvent

type AgentEvent struct {
	AgentName string

	// RunPath represents the execution path from root agent to the current event source.
	// This field is managed entirely by the eino framework and cannot be set by end-users
	// because RunStep's fields are unexported. The framework sets RunPath exactly once:
	// - flowAgent sets it when the event has no RunPath (len == 0)
	// - agentTool prepends parent RunPath when forwarding events from nested agents
	RunPath []RunStep

	Output *AgentOutput

	Action *AgentAction

	Err error
}

AgentEvent CheckpointSchema: persisted via serialization.RunCtx (gob).

func CompositeInterrupt added in v0.7.0

func CompositeInterrupt(ctx context.Context, info any, state any,
	subInterruptSignals ...*InterruptSignal) *AgentEvent

CompositeInterrupt creates an interrupt action for a workflow agent. It combines the interrupts from one or more of its sub-agents into a single, cohesive interrupt. This is used by workflow agents (like Sequential, Parallel, or Loop) to propagate interrupts from their children. The `info` parameter is user-facing data describing the workflow's own reason for interrupting. The `state` parameter is the workflow agent's own state (e.g., the index of the sub-agent that was interrupted). The `subInterruptSignals` is a variadic list of the InterruptSignal objects from the interrupted sub-agents.

func EventFromMessage

func EventFromMessage(msg Message, msgStream MessageStream,
	role schema.RoleType, toolName string) *AgentEvent

EventFromMessage wraps a message or stream into an AgentEvent with role metadata.

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 struct {
	Messages        []Message
	EnableStreaming bool
}

type AgentMiddleware 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
}

AgentMiddleware provides hooks to customize agent behavior at various stages of execution.

Limitations of AgentMiddleware (struct-based):

  • Struct types are closed: users cannot add new methods
  • Callbacks only return error, cannot return modified context
  • Configuration is scattered across closures when using factory functions

For new code requiring extensibility, consider using ChatModelAgentMiddleware (interface-based) instead. AgentMiddleware is kept for backward compatibility and remains suitable for simple, static additions like extra instruction or tools.

See ChatModelAgentMiddleware documentation for detailed comparison.

type AgentOption

type AgentOption func(options *flowAgent)

func WithDisallowTransferToParent

func WithDisallowTransferToParent() AgentOption

WithDisallowTransferToParent prevents a sub-agent from transferring to its parent.

func WithHistoryRewriter

func WithHistoryRewriter(h HistoryRewriter) AgentOption

WithHistoryRewriter sets a rewriter to transform conversation history.

type AgentOutput

type AgentOutput struct {
	MessageOutput *MessageVariant

	CustomizedOutput any
}

type AgentRunOption

type AgentRunOption struct {
	// contains filtered or unexported fields
}

AgentRunOption is the call option for adk Agent.

func WithAgentToolRunOptions

func WithAgentToolRunOptions(opts map[string][]AgentRunOption) AgentRunOption

WithAgentToolRunOptions specifies per-tool run options for the agent.

func WithCallbacks

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.

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 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

type BaseChatModelAgentMiddleware struct{}

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
}

func (*BaseChatModelAgentMiddleware) AfterModelRewriteState

func (*BaseChatModelAgentMiddleware) BeforeAgent

func (*BaseChatModelAgentMiddleware) BeforeModelRewriteState

func (*BaseChatModelAgentMiddleware) WrapEnhancedInvokableToolCall

func (*BaseChatModelAgentMiddleware) WrapEnhancedStreamableToolCall

func (*BaseChatModelAgentMiddleware) WrapInvokableToolCall

func (*BaseChatModelAgentMiddleware) WrapModel

func (*BaseChatModelAgentMiddleware) WrapStreamableToolCall

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 ChatModelAgent

type ChatModelAgent struct {
	// contains filtered or unexported fields
}

func NewChatModelAgent

func NewChatModelAgent(ctx context.Context, config *ChatModelAgentConfig) (*ChatModelAgent, error)

NewChatModelAgent constructs a chat model-backed agent with the provided config.

func (*ChatModelAgent) Description

func (a *ChatModelAgent) Description(_ context.Context) string

func (*ChatModelAgent) GetType

func (a *ChatModelAgent) GetType() string

func (*ChatModelAgent) Name

func (a *ChatModelAgent) Name(_ context.Context) string

func (*ChatModelAgent) OnDisallowTransferToParent

func (a *ChatModelAgent) OnDisallowTransferToParent(_ context.Context) error

func (*ChatModelAgent) OnSetAsSubAgent

func (a *ChatModelAgent) OnSetAsSubAgent(_ context.Context, parent Agent) error

func (*ChatModelAgent) OnSetSubAgents

func (a *ChatModelAgent) OnSetSubAgents(_ context.Context, subAgents []Agent) error

func (*ChatModelAgent) Resume

func (*ChatModelAgent) Run

type ChatModelAgentConfig

type ChatModelAgentConfig struct {
	// Name of the agent. Better be unique across all agents.
	Name string
	// Description of the agent's capabilities.
	// Helps other agents determine whether to transfer tasks to this agent.
	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.BaseChatModel

	ToolsConfig ToolsConfig

	// GenModelInput transforms instructions and input messages into the model's input format.
	// Optional. Defaults to defaultGenModelInput which combines instruction and messages.
	GenModelInput GenModelInput

	// 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.
	Exit tool.BaseTool

	// OutputKey stores the agent's response in the session.
	// Optional. When set, stores output via AddSessionValue(ctx, outputKey, msg.Content).
	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

	// Middlewares configures agent middleware for extending functionality.
	// Use for simple, static additions like extra instruction or tools.
	// Kept for backward compatibility; for new code, consider using Handlers instead.
	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. retryModelWrapper (internal - retries on failure, if configured)
	//  4. eventSenderModelWrapper (internal - sends model response events)
	//  5. ChatModelAgentMiddleware.WrapModel (wrapper, first registered is outermost)
	//  6. callbackInjectionModelWrapper (internal - injects callbacks if not enabled)
	//  7. Model.Generate/Stream
	//  8. ChatModelAgentMiddleware.AfterModelRewriteState (hook, can modify state after model call)
	//  9. 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. eventSenderToolHandler (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
	//
	// 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 WrapModel: Create a model wrapper that modifies the tool info list per model
	//     request using model.WithTools(toolInfos). This ONLY affects the tool info list
	//     passed to ChatModel, NOT the actual tools available for execution. Use this for
	//     dynamic tool filtering/selection based on conversation context. The modification
	//     is scoped to this model request only.
	Handlers []ChatModelAgentMiddleware

	// 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 *ModelRetryConfig
}

type ChatModelAgentContext

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
}

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

type ChatModelAgentMiddleware 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)

	// 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
	//
	// The ModelContext struct provides read-only access to:
	//   - Tools: the current tool list that will be sent to the model
	BeforeModelRewriteState(ctx context.Context, state *ChatModelAgentState, mc *ModelContext) (context.Context, *ChatModelAgentState, 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
	//
	// The ModelContext struct provides read-only access to:
	//   - Tools: the current tool list that was sent to the model
	AfterModelRewriteState(ctx context.Context, state *ChatModelAgentState, mc *ModelContext) (context.Context, *ChatModelAgentState, 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.
	// 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 BaseChatModel (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.
	//
	// The mc parameter contains the current tool configuration:
	//   - Tools: The tool infos that will be sent to the model
	WrapModel(ctx context.Context, m model.BaseChatModel, mc *ModelContext) (model.BaseChatModel, error)
}

ChatModelAgentMiddleware defines the interface for customizing ChatModelAgent behavior.

IMPORTANT: This interface is specifically designed for ChatModelAgent and agents built on top of it (e.g., DeepAgent).

Why ChatModelAgentMiddleware 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

ChatModelAgentMiddleware 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

ChatModelAgentMiddleware vs AgentMiddleware:

  • Use AgentMiddleware for simple, static additions (extra instruction/tools)
  • Use ChatModelAgentMiddleware 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 *BaseChatModelAgentMiddleware as an embedded struct to provide default no-op implementations for all methods.

func NewEventSenderModelWrapper

func NewEventSenderModelWrapper() ChatModelAgentMiddleware

NewEventSenderModelWrapper returns a ChatModelAgentMiddleware that sends model response events. By default, the framework applies this wrapper after all user middlewares, so events contain modified messages. To send events with original (unmodified) output, pass this as a Handler after the modifying middleware (placing it innermost in the wrapper chain). 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 struct {
	// Messages contains all messages in the current conversation session.
	Messages []Message
}

ChatModelAgentState represents the state of a chat model agent during conversation. This is the primary state type for both ChatModelAgentMiddleware and AgentMiddleware callbacks.

type CheckPointStore added in v0.7.22

type CheckPointStore = core.CheckPointStore

type DeterministicTransferConfig

type DeterministicTransferConfig struct {
	Agent        Agent
	ToAgentNames []string
}

type EnhancedInvokableToolCallEndpoint

type EnhancedInvokableToolCallEndpoint func(ctx context.Context, toolArgument *schema.ToolArgument, opts ...tool.Option) (*schema.ToolResult, error)

type EnhancedStreamableToolCallEndpoint

type EnhancedStreamableToolCallEndpoint func(ctx context.Context, toolArgument *schema.ToolArgument, opts ...tool.Option) (*schema.StreamReader[*schema.ToolResult], error)

type ExitTool

type ExitTool struct{}

func (ExitTool) Info

func (et ExitTool) Info(_ context.Context) (*schema.ToolInfo, error)

func (ExitTool) InvokableRun

func (et ExitTool) InvokableRun(ctx context.Context, argumentsInJSON string, _ ...tool.Option) (string, error)

type GenModelInput

type GenModelInput func(ctx context.Context, instruction string, input *AgentInput) ([]Message, error)

GenModelInput transforms agent instructions and input into a format suitable for the model.

type HistoryEntry

type HistoryEntry struct {
	IsUserInput bool
	AgentName   string
	Message     Message
}

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 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

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

type Language = internal.Language

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

type LoopAgentConfig struct {
	Name        string
	Description string
	SubAgents   []Agent

	MaxIterations int
}

type Message

type Message = *schema.Message

type MessageStream

type MessageStream = *schema.StreamReader[Message]

type MessageVariant

type MessageVariant struct {
	IsStreaming bool

	Message       Message
	MessageStream MessageStream
	// message role: Assistant or Tool
	Role schema.RoleType
	// only used when Role is Tool
	ToolName string
}

func (*MessageVariant) GetMessage

func (mv *MessageVariant) GetMessage() (Message, error)

func (*MessageVariant) GobDecode

func (mv *MessageVariant) GobDecode(b []byte) error

func (*MessageVariant) GobEncode

func (mv *MessageVariant) GobEncode() ([]byte, error)

type ModelContext

type ModelContext 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.
	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 *ModelRetryConfig
}

ModelContext contains context information passed to WrapModel.

type ModelRetryConfig added in v0.7.14

type ModelRetryConfig 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

	// IsRetryAble is a function that determines whether an error should trigger a retry.
	// If nil, all errors are considered retry-able.
	// Return true if the error is transient and the operation should be retried.
	// Return false if the error is permanent and should be propagated immediately.
	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.
	// 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
}

ModelRetryConfig configures retry behavior for the ChatModel node. It defines how the agent should handle transient failures when calling the ChatModel.

type OnSubAgents

type OnSubAgents interface {
	OnSetSubAgents(ctx context.Context, subAgents []Agent) error
	OnSetAsSubAgent(ctx context.Context, parent Agent) error

	OnDisallowTransferToParent(ctx context.Context) error
}

type ParallelAgentConfig

type ParallelAgentConfig struct {
	Name        string
	Description string
	SubAgents   []Agent
}

type ResumableAgent

type ResumableAgent interface {
	Agent

	Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
}

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.

func NewParallelAgent

func NewParallelAgent(ctx context.Context, config *ParallelAgentConfig) (ResumableAgent, error)

NewParallelAgent creates an agent that runs sub-agents in parallel.

func NewSequentialAgent

func NewSequentialAgent(ctx context.Context, config *SequentialAgentConfig) (ResumableAgent, error)

NewSequentialAgent creates an agent that runs sub-agents sequentially.

func SetSubAgents

func SetSubAgents(ctx context.Context, agent Agent, subAgents []Agent) (ResumableAgent, error)

SetSubAgents sets sub-agents for the given agent and returns the updated agent.

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 RetryExhaustedError added in v0.7.14

type RetryExhaustedError struct {
	LastErr      error
	TotalRetries int
}

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 CheckpointSchema: persisted via serialization.RunCtx (gob).

func (*RunStep) Equals

func (r *RunStep) Equals(r1 RunStep) bool

func (*RunStep) GobDecode

func (r *RunStep) GobDecode(b []byte) error

func (*RunStep) GobEncode

func (r *RunStep) GobEncode() ([]byte, error)

func (*RunStep) String

func (r *RunStep) String() string

type Runner

type Runner struct {
	// contains filtered or unexported fields
}

Runner is the primary entry point for executing an Agent. It manages the agent's lifecycle, including starting, resuming, and checkpointing.

func NewRunner

func NewRunner(_ context.Context, conf RunnerConfig) *Runner

NewRunner creates a Runner that executes an Agent with optional streaming and checkpoint persistence.

func (*Runner) Query

func (r *Runner) Query(ctx context.Context,
	query string, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]

Query is a convenience method that starts a new execution with a single user query string.

func (*Runner) Resume

func (r *Runner) Resume(ctx context.Context, checkPointID string, opts ...AgentRunOption) (
	*AsyncIterator[*AgentEvent], 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 (*Runner) ResumeWithParams added in v0.7.0

func (r *Runner) ResumeWithParams(ctx context.Context, checkPointID string, params *ResumeParams, opts ...AgentRunOption) (*AsyncIterator[*AgentEvent], 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 (*Runner) Run

func (r *Runner) Run(ctx context.Context, messages []Message,
	opts ...AgentRunOption) *AsyncIterator[*AgentEvent]

Run starts a new execution of the agent with a given set of messages. It returns an iterator that yields agent events as they occur. If the Runner was configured with a CheckPointStore, it will automatically save the agent's state upon interruption.

type RunnerConfig

type RunnerConfig struct {
	Agent           Agent
	EnableStreaming bool

	CheckPointStore CheckPointStore
}

type SequentialAgentConfig

type SequentialAgentConfig struct {
	Name        string
	Description string
	SubAgents   []Agent
}

type State deprecated

type State struct {
	Messages []Message

	// Internal fields below - do not access directly.
	// Kept exported for backward compatibility with existing checkpoints.
	ReturnDirectlyToolCallID string
	ToolGenActions           map[string]*AgentAction
	AgentName                string
	RemainingIterations      int
	// contains filtered or unexported fields
}

State holds agent runtime state including messages and user-extensible storage.

Deprecated: This type will be unexported in v1.0.0. Use ChatModelAgentState in HandlerMiddleware and AgentMiddleware callbacks instead. Direct use of compose.ProcessState[*State] is discouraged and will stop working in v1.0.0; use the handler APIs instead.

func (*State) GobDecode

func (s *State) GobDecode(b []byte) error

func (*State) GobEncode

func (s *State) GobEncode() ([]byte, error)

type StreamableToolCallEndpoint

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 ToolContext

type ToolContext struct {
	Name   string
	CallID string
}

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.
	// If multiple listed tools are called simultaneously, only the first one triggers the return.
	// 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
}

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.

func (*WillRetryError) Error added in v0.7.14

func (e *WillRetryError) Error() string

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 CheckpointSchema: persisted via InterruptInfo.Data (gob).

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
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 the skill middleware, types, and a local filesystem backend.
Package skill provides the 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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL