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 GenTransferMessages(_ context.Context, destAgentName string) (Message, Message)
- func GetImplSpecificOptions[T any](base *T, opts ...AgentRunOption) *T
- func GetMessage(e *AgentEvent) (Message, *AgentEvent, 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 SendToolGenAction(ctx context.Context, toolName string, action *AgentAction) error
- type Address
- type AddressSegment
- type AddressSegmentType
- type Agent
- type AgentAction
- type AgentEvent
- func CompositeInterrupt(ctx context.Context, info any, state any, ...) *AgentEvent
- func EventFromMessage(msg Message, msgStream MessageStream, role schema.RoleType, toolName string) *AgentEvent
- func Interrupt(ctx context.Context, info any) *AgentEvent
- func StatefulInterrupt(ctx context.Context, info any, state any) *AgentEvent
- type AgentInput
- type AgentMiddleware
- type AgentOption
- type AgentOutput
- type AgentRunOption
- func WithAgentToolRunOptions(opts map[string][]AgentRunOption) 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 AsyncGenerator
- type AsyncIterator
- type BreakLoopAction
- type ChatModelAgent
- func (a *ChatModelAgent) Description(_ context.Context) string
- func (a *ChatModelAgent) Name(_ context.Context) string
- func (a *ChatModelAgent) OnDisallowTransferToParent(_ context.Context) error
- func (a *ChatModelAgent) OnSetAsSubAgent(_ context.Context, parent Agent) error
- func (a *ChatModelAgent) OnSetSubAgents(_ context.Context, subAgents []Agent) error
- func (a *ChatModelAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
- func (a *ChatModelAgent) Run(ctx context.Context, input *AgentInput, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
- type ChatModelAgentConfig
- type ChatModelAgentInterruptInfo
- type ChatModelAgentResumeData
- type ChatModelAgentState
- type DeterministicTransferConfig
- type ExitTool
- type GenModelInput
- type HistoryEntry
- type HistoryRewriter
- type InterruptCtx
- type InterruptInfo
- type InterruptSignal
- type LoopAgentConfig
- type Message
- type MessageStream
- type MessageVariant
- type ModelRetryConfig
- type OnSubAgents
- type ParallelAgentConfig
- 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 RetryExhaustedError
- type RunStep
- type Runner
- func (r *Runner) Query(ctx context.Context, query string, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
- func (r *Runner) Resume(ctx context.Context, checkPointID string, opts ...AgentRunOption) (*AsyncIterator[*AgentEvent], error)
- func (r *Runner) ResumeWithParams(ctx context.Context, checkPointID string, params *ResumeParams, ...) (*AsyncIterator[*AgentEvent], error)
- func (r *Runner) Run(ctx context.Context, messages []Message, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
- type RunnerConfig
- type SequentialAgentConfig
- type State
- type ToolsConfig
- type TransferToAgentAction
- type WillRetryError
- type WorkflowInterruptInfo
Constants ¶
const ( TransferToAgentToolName = "transfer_to_agent" TransferToAgentToolDesc = "Transfer the question to another agent." )
const (
TransferToAgentInstruction = `` /* 268-byte string literal not displayed */
)
Variables ¶
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 GenTransferMessages ¶
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 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.
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 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.
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 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
}
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 AgentEvent ¶
type AgentEvent struct {
AgentName string
// RunPath semantics:
// - The eino framework prepends parent context exactly once: parentRunPath + event.RunPath.
// - Custom agents should NOT include parent segments; any provided RunPath is treated as relative child provenance.
// - Exact RunPath match against the framework's runCtx.RunPath governs recording to runSession.
// STRONG RECOMMENDATION: Custom agents should NOT set RunPath themselves unless they fully understand
// the merge and recording rules. Setting parent or absolute paths can lead to duplicated segments
// after merge and unexpected non-recording. Prefer leaving RunPath empty and let the framework set
// context, or append only relative child segments when implementing advanced orchestration.
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 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.
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 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 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(_ 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) 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 (a *ChatModelAgent) Resume(ctx context.Context, info *ResumeInfo, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
func (*ChatModelAgent) Run ¶
func (a *ChatModelAgent) Run(ctx context.Context, input *AgentInput, opts ...AgentRunOption) *AsyncIterator[*AgentEvent]
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 model.ToolCallingChatModel
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.
Middlewares []AgentMiddleware
// 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 ChatModelAgentInterruptInfo ¶
type ChatModelAgentInterruptInfo struct {
Info *compose.InterruptInfo
Data []byte
}
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.
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 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 LoopAgentConfig ¶
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 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 ParallelAgentConfig ¶
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 ¶
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
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).
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 compose.CheckPointStore
}
type SequentialAgentConfig ¶
type State ¶
type State struct {
Messages []Message
HasReturnDirectly bool
ReturnDirectlyToolCallID string
ToolGenActions map[string]*AgentAction
AgentName string
RemainingIterations int
}
State holds agent runtime state including messages, tool actions, and remaining iterations.
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 generator via a tool option injection at run-time.
EmitInternalEvents bool
}
type TransferToAgentAction ¶
type TransferToAgentAction struct {
DestAgentName string
}
type WillRetryError ¶ added in v0.7.14
func (*WillRetryError) Error ¶ added in v0.7.14
func (e *WillRetryError) Error() string
type WorkflowInterruptInfo ¶
type WorkflowInterruptInfo struct {
OrigInput *AgentInput
SequentialInterruptIndex int
SequentialInterruptInfo *InterruptInfo
LoopIterations int
ParallelInterruptInfo map[int]*InterruptInfo
}
WorkflowInterruptInfo CheckpointSchema: persisted via InterruptInfo.Data (gob).
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
middlewares
|
|
|
filesystem
Package filesystem provides middlewares and types for file system operations.
|
Package filesystem provides middlewares and types for file system operations. |
|
reduction
Package reduction provides middlewares to trim context and clear tool results.
|
Package reduction provides middlewares to trim context and clear tool results. |
|
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. |