adk

package
v0.7.5 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2025 License: Apache-2.0 Imports: 25 Imported by: 26

Documentation

Index

Constants

View Source
const (
	TransferToAgentToolName = "transfer_to_agent"
	TransferToAgentToolDesc = "Transfer the question to another agent."
)
View Source
const (
	TransferToAgentInstruction = `` /* 268-byte string literal not displayed */

)

Variables

View Source
var ErrExceedMaxIterations = errors.New("exceeds max iterations")
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)

func AddSessionValues

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

func AppendAddressSegment added in v0.7.0

func AppendAddressSegment(ctx context.Context, segType AddressSegmentType, segID string) context.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 GenTransferMessages

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

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)

func GetSessionValue

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

func GetSessionValues

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

func NewAgentTool

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

func NewAsyncIteratorPair

func NewAsyncIteratorPair[T any]() (*AsyncIterator[T], *AsyncGenerator[T])

func SendToolGenAction

func SendToolGenAction(ctx context.Context, toolName string, action *AgentAction) error

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

func AgentWithOptions

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

func NewLoopAgent

func NewLoopAgent(ctx context.Context, config *LoopAgentConfig) (Agent, error)

func NewParallelAgent

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

func NewSequentialAgent

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

func SetSubAgents

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

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

func NewTransferToAgentAction

func NewTransferToAgentAction(destAgentName string) *AgentAction

type AgentEvent

type AgentEvent struct {
	AgentName string

	RunPath []RunStep

	Output *AgentOutput

	Action *AgentAction

	Err error
}

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

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.

type AgentOption

type AgentOption func(options *flowAgent)

func WithDisallowTransferToParent

func WithDisallowTransferToParent() AgentOption

func WithHistoryRewriter

func WithHistoryRewriter(h HistoryRewriter) AgentOption

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

func WithChatModelOptions

func WithChatModelOptions(opts []model.Option) AgentRunOption

func WithCheckPointID

func WithCheckPointID(id string) AgentRunOption

func WithHistoryModifier deprecated

func WithHistoryModifier(f func(context.Context, []Message) []Message) AgentRunOption

Deprecated: use ResumeWithData and ChatModelAgentResumeData instead.

func WithSessionValues

func WithSessionValues(v map[string]any) AgentRunOption

func WithSkipTransferMessages

func WithSkipTransferMessages() AgentRunOption

func WithToolOptions

func WithToolOptions(opts []tool.Option) AgentRunOption

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

func WithFullChatHistoryAsInput

func WithFullChatHistoryAsInput() AgentToolOption

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)

func (*ChatModelAgent) Description

func (a *ChatModelAgent) Description(_ context.Context) 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 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
}

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 DeterministicTransferConfig

type DeterministicTransferConfig struct {
	Agent        Agent
	ToAgentNames []string
}

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

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

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 RunStep

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

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

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 SequentialAgentConfig struct {
	Name        string
	Description string
	SubAgents   []Agent
}

type State

type State struct {
	Messages []Message

	HasReturnDirectly        bool
	ReturnDirectlyToolCallID string

	ToolGenActions map[string]*AgentAction

	AgentName string

	RemainingIterations int
}

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
}

type TransferToAgentAction

type TransferToAgentAction struct {
	DestAgentName string
}

type WorkflowInterruptInfo

type WorkflowInterruptInfo struct {
	OrigInput *AgentInput

	SequentialInterruptIndex int
	SequentialInterruptInfo  *InterruptInfo

	LoopIterations int

	ParallelInterruptInfo map[int]*InterruptInfo
}

Directories

Path Synopsis
prebuilt

Jump to

Keyboard shortcuts

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