Documentation
¶
Overview ¶
Package types provides core interfaces and contracts for the Agent Development Kit (ADK).
The types package defines the fundamental interfaces, structures, and contracts that all components of the ADK system follow. It serves as the central definition of how agents, models, tools, sessions, and other components interact with each other.
Core Interfaces ¶
The package defines several key interfaces that form the foundation of the ADK:
- Agent: Defines execution, hierarchy navigation, and lifecycle methods
- Model: Unified LLM abstraction for content generation and streaming
- Tool/Toolset: Extensible tool system with function declarations
- Session/SessionService: Conversation and state management abstractions
- Flow: Pipeline architecture for LLM interaction processing
- ArtifactService: Storage and retrieval of agent-generated content
- CredentialService: Secure authentication credential management
Agent Interface ¶
The Agent interface defines the contract for all agent types:
type Agent interface {
Name() string
Description() string
ParentAgent() Agent
SubAgents() []Agent
BeforeAgentCallbacks() []AgentCallback
AfterAgentCallbacks() []AgentCallback
Execute(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
Run(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
RunLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
// ... additional methods
}
All agent implementations (LLMAgent, SequentialAgent, ParallelAgent, LoopAgent) implement this interface, enabling polymorphic usage and hierarchical composition.
Model Interface ¶
The Model interface provides unified LLM abstraction:
type Model interface {
Name() string
SupportedModels() []string
Connect(ctx context.Context, request *LLMRequest) (ModelConnection, error)
GenerateContent(ctx context.Context, request *LLMRequest) (*LLMResponse, error)
StreamGenerateContent(ctx context.Context, request *LLMRequest) iter.Seq2[*LLMResponse, error]
}
This abstraction supports multiple providers (Google Gemini, Anthropic Claude) with consistent interfaces for both synchronous and streaming generation.
Tool System ¶
The tool system is built around flexible interfaces:
type Tool interface {
Name() string
Description() string
IsLongRunning() bool
GetDeclaration() *genai.FunctionDeclaration
Run(ctx context.Context, args map[string]any, toolCtx *ToolContext) (any, error)
ProcessLLMRequest(ctx context.Context, toolCtx *ToolContext, request *LLMRequest) error
}
type Toolset interface {
Name() string
Description() string
Tools() []Tool
}
Tools can be individual functions or grouped into toolsets for organized functionality.
Event System ¶
Events represent all interactions in the system:
type Event struct {
*LLMResponse
InvocationID string
Author string
Actions *EventActions
LongRunningToolIDs py.Set[string]
Branch string
ID string
Timestamp time.Time
}
type EventActions struct {
StateDelta map[string]any
AgentTransfer *AgentTransfer
FunctionCalls []*genai.FunctionCall
FunctionResponses []*genai.FunctionResponse
}
Events carry rich metadata and enable comprehensive conversation tracking.
Session Management ¶
Sessions provide stateful conversation tracking:
type Session interface {
ID() string
AppName() string
UserID() string
State() map[string]any
Events() []*Event
LastUpdateTime() time.Time
AddEvent(events ...*Event)
// ... additional methods
}
type SessionService interface {
CreateSession(ctx context.Context, appName, userID, sessionID string, state map[string]any) (Session, error)
GetSession(ctx context.Context, appName, userID, sessionID string, config *GetSessionConfig) (Session, error)
ListSessions(ctx context.Context, appName, userID string) ([]Session, error)
DeleteSession(ctx context.Context, appName, userID, sessionID string) error
AppendEvent(ctx context.Context, ses Session, event *Event) (*Event, error)
ListEvents(ctx context.Context, appName, userID, sessionID string, maxEvents int, since *time.Time) ([]Event, error)
}
State Management ¶
The ADK supports three-tier state management:
// App-level state (shared across all users) StateDelta["app:config"] = "production" // User-level state (shared across user's sessions) StateDelta["user:preferences"] = userPrefs // Session-level state (specific to conversation) StateDelta["temp:context"] = "current_topic"
State changes are applied through EventActions with automatic propagation.
Context System ¶
Rich context flows through all operations:
type InvocationContext struct {
// Session and state management
Session() Session
SessionService() SessionService
State() map[string]any
// Agent hierarchy
Agent() Agent
ParentAgent() Agent
RootAgent() Agent
// Services and configuration
ArtifactService() ArtifactService
CredentialService() CredentialService
MemoryService() MemoryService
CodeExecutor() CodeExecutor
// Execution tracking
AppName() string
UserID() string
SessionID() string
InvocationID() string
Branch() string
}
Flow System ¶
Flows provide pipeline architecture for processing:
type Flow interface {
Run(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
RunLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
}
Flows can be composed into pipelines with processors for request/response handling.
Code Execution ¶
Secure code execution is abstracted through interfaces:
type CodeExecutor interface {
OptimizeDataFile() bool
IsLongRunning() bool
IsStateful() bool
ErrorRetryAttempts() int
CodeBlockDelimiters() []DelimiterPair
ExecutionResultDelimiters() DelimiterPair
ExecuteCode(ctx context.Context, ictx *InvocationContext, input *CodeExecutionInput) (*CodeExecutionResult, error)
Close() error
}
Authentication System ¶
Authentication is handled through flexible interfaces:
type CredentialService interface {
LoadCredential(ctx context.Context, authConfig *AuthConfig, toolCtx *ToolContext) (*AuthCredential, error)
SaveCredential(ctx context.Context, authConfig *AuthConfig, toolCtx *ToolContext) error
}
type AuthConfig struct {
Type AuthType
CredentialKey string
ClientID string
ClientSecret string
Scopes []string
ExchangedAuthCredential *AuthCredential
// ... additional fields
}
Memory System ¶
Long-term memory is provided through:
type MemoryService interface {
AddMemories(ctx context.Context, appName, userID string, memories []*MemoryEntry) error
SearchMemories(ctx context.Context, appName, userID, query string) (*SearchMemoryResponse, error)
}
Artifact Management ¶
Artifacts provide persistent storage:
type ArtifactService interface {
SaveArtifact(ctx context.Context, appName, userID, sessionID, filename string, artifact *genai.Part) (int, error)
LoadArtifact(ctx context.Context, appName, userID, sessionID, filename string, version int) (*genai.Part, error)
ListArtifactKey(ctx context.Context, appName, userID, sessionID string) ([]string, error)
DeleteArtifact(ctx context.Context, appName, userID, sessionID, filename string) error
ListVersions(ctx context.Context, appName, userID, sessionID, filename string) ([]int, error)
Close() error
}
Planning System ¶
Strategic planning is defined through:
type Planner interface {
BuildPlanningInstruction(ctx context.Context, rctx *ReadOnlyContext, request *LLMRequest) string
ProcessPlanningResponse(ctx context.Context, cctx *CallbackContext, responseParts []*genai.Part) []*genai.Part
}
Best Practices ¶
When implementing these interfaces:
- Follow interface contracts exactly
- Handle context cancellation appropriately
- Provide meaningful error messages
- Ensure thread safety where required
- Clean up resources in Close() methods
- Use appropriate state prefixes (app:, user:, temp:)
- Validate inputs early and thoroughly
The types package provides the foundation for building sophisticated AI agents with strong typing, clear contracts, and flexible composition patterns.
Index ¶
- Constants
- func DecodeContent(content map[string]any) (*genai.Content, error)
- func Deref[T any](ptr *T, def T) T
- func EncodeContent(content *genai.Content) (map[string]any, error)
- func NewEventID() string
- func NewInvocationContextID() string
- func NewLLMCallsLimitExceededError(msg string, a ...any) error
- func ToPtr[T any](v T) *T
- type APIKeyIn
- type APIKeySecurityScheme
- type ActiveStreamingTool
- func (a *ActiveStreamingTool[T]) ClearStream()
- func (a *ActiveStreamingTool[T]) GetStream() *LiveRequestQueue
- func (a *ActiveStreamingTool[T]) IsActive() bool
- func (a *ActiveStreamingTool[T]) SetStream(stream *LiveRequestQueue)
- func (a *ActiveStreamingTool[T]) WithStream(stream *LiveRequestQueue) *ActiveStreamingTool[T]
- func (a *ActiveStreamingTool[T]) WithTask(task *pyasyncio.Task[T]) *ActiveStreamingTool[T]
- type AfterModelCallback
- type AfterToolCallback
- type Agent
- type AgentCallback
- type ArtifactService
- type AuthConfig
- type AuthCredential
- type AuthCredentialTypes
- type AuthHandler
- func (h *AuthHandler) ExchangeAuthToken(ctx context.Context) (*AuthCredential, error)
- func (h *AuthHandler) GenerateAuthRequest() (*AuthConfig, error)
- func (h *AuthHandler) GenerateAuthURI() (*AuthCredential, error)
- func (h *AuthHandler) GetAuthResponse(state *State) *AuthCredential
- func (h *AuthHandler) GetCredentialKey() string
- func (h *AuthHandler) ParseAndStoreAuthSesponse(ctx context.Context, state *State) error
- type AuthScheme
- type AuthToolArguments
- type AuthenticatedTool
- type BaseAgent
- func (a *BaseAgent) AfterAgentCallbacks() []AgentCallback
- func (a *BaseAgent) AsLLMAgent() (LLMAgent, bool)
- func (a *BaseAgent) BeforeAgentCallbacks() []AgentCallback
- func (a *BaseAgent) Description() string
- func (a *BaseAgent) Execute(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
- func (a *BaseAgent) ExecuteLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
- func (a *BaseAgent) FindAgent(name string) Agent
- func (a *BaseAgent) FindSubAgent(name string) Agent
- func (a *BaseAgent) Name() string
- func (a *BaseAgent) ParentAgent() Agent
- func (a *BaseAgent) RootAgent() Agent
- func (a *BaseAgent) Run(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
- func (a *BaseAgent) RunLive(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
- func (a *BaseAgent) SubAgents() []Agent
- type BeforeModelCallback
- type BeforeToolCallback
- type CallbackContext
- func (cc *CallbackContext) EventActions() *EventActions
- func (cc *CallbackContext) LoadArtifact(ctx context.Context, filename string, version int) (*genai.Part, error)
- func (cc *CallbackContext) SaveArtifact(ctx context.Context, filename string, artifact *genai.Part) (int, error)
- func (cc *CallbackContext) State() *State
- func (cc *CallbackContext) WithEventActions(eventActions *EventActions) *CallbackContext
- type CodeExecutionFile
- func (f *CodeExecutionFile) IsBinary() bool
- func (f *CodeExecutionFile) IsText() bool
- func (f *CodeExecutionFile) MarshalJSON() ([]byte, error)
- func (f *CodeExecutionFile) String() string
- func (f *CodeExecutionFile) UnmarshalJSON(data []byte) error
- func (f *CodeExecutionFile) WriteToFile(path string) error
- type CodeExecutionInput
- type CodeExecutionResult
- type CodeExecutor
- type Config
- type CredentialExchangError
- type CredentialExchanger
- type CredentialExchangerRegistry
- type CredentialManager
- func (cm *CredentialManager) AuthConfig() *AuthConfig
- func (cm *CredentialManager) GetAuthCredential(ctx context.Context, toolCtx *ToolContext) (*AuthCredential, error)
- func (cm *CredentialManager) RegisterCredentialExchanger(ctx context.Context, credentialType AuthCredentialTypes, ...)
- func (cm *CredentialManager) RequestCredential(ctx context.Context, toolCtx *ToolContext)
- type CredentialRefresher
- type CredentialRefresherError
- type CredentialRefresherRegistry
- type CredentialService
- type DelimiterPair
- type Event
- func (e *Event) GetFunctionCalls() []*genai.FunctionCall
- func (e *Event) GetFunctionResponses() []*genai.FunctionResponse
- func (e *Event) HasTrailingCodeExecutionResult() bool
- func (e *Event) IsFinalResponse() bool
- func (e *Event) WithActions(actions *EventActions) *Event
- func (e *Event) WithAuthor(author string) *Event
- func (e *Event) WithBranch(branch string) *Event
- func (e *Event) WithContent(content *genai.Content) *Event
- func (e *Event) WithInvocationID(id string) *Event
- func (e *Event) WithLLMResponse(response *LLMResponse) *Event
- func (e *Event) WithLongRunningToolIDs(ids ...string) *Event
- type EventActions
- func (ea *EventActions) WithArtifactDelta(artifactDelta map[string]int) *EventActions
- func (ea *EventActions) WithEscalate(escalate bool) *EventActions
- func (ea *EventActions) WithRequestedAuthConfigs(requestedAuthConfigs map[string]*AuthConfig) *EventActions
- func (ea *EventActions) WithSkipSummarization(skipSummarization bool) *EventActions
- func (ea *EventActions) WithStateDelta(stateDelta map[string]any) *EventActions
- func (ea *EventActions) WithTransferToAgent(transferToAgent string) *EventActions
- type ExecutionConfig
- type ExecutionOption
- func WithCodeBlockDelimiters(delimiters ...DelimiterPair) ExecutionOption
- func WithDefaultTimeout(timeout time.Duration) ExecutionOption
- func WithExecutionResultDelimiters(delimiters DelimiterPair) ExecutionOption
- func WithMaxRetries(retries int) ExecutionOption
- func WithOptimizeDataFiles(optimize bool) ExecutionOption
- func WithRetryDelay(delay time.Duration) ExecutionOption
- type Flow
- type GetSessionConfig
- type HTTPAuth
- type HTTPBaseSecurityScheme
- type HTTPCredentials
- type IncludeContents
- type InstructionProvider
- type InvocationContext
- type InvocationContextOption
- func WithActiveStreamingTools[T any](activeStreamingTools map[string]*ActiveStreamingTool[any]) InvocationContextOption
- func WithArtifactService(svc ArtifactService) InvocationContextOption
- func WithBranch(branch string) InvocationContextOption
- func WithLiveRequestQueue(liveRequestQueue *LiveRequestQueue) InvocationContextOption
- func WithMemoryService(svc MemoryService) InvocationContextOption
- func WithTranscriptionCache(entries ...*TranscriptionEntry) InvocationContextOption
- func WithUserContent(content *genai.Content) InvocationContextOption
- type InvocationCostManager
- type LLMAgent
- type LLMCallsLimitExceededError
- type LLMRequest
- func (r *LLMRequest) AppendInstructions(instructions ...string)
- func (r *LLMRequest) AppendTools(tools ...Tool) *LLMRequest
- func (r *LLMRequest) SetOutputSchema(schema *genai.Schema) *LLMRequest
- func (r *LLMRequest) ToGenaiContents() []*genai.Content
- func (r *LLMRequest) ToJSON() (string, error)
- func (r *LLMRequest) WithModelName(name string) LLMRequestOption
- type LLMRequestOption
- type LLMRequestProcessor
- type LLMResponse
- func (r *LLMResponse) GetText() string
- func (r *LLMResponse) IsError() bool
- func (r *LLMResponse) WithCustomMetadata(metadata map[string]any) *LLMResponse
- func (r *LLMResponse) WithInterrupted(interrupted bool) *LLMResponse
- func (r *LLMResponse) WithPartial(partial bool) *LLMResponse
- func (r *LLMResponse) WithTurnComplete(complete bool) *LLMResponse
- type LLMResponseProcessor
- type ListEventsResponse
- type ListSessionsResponse
- type LiveRequest
- type LiveRequestQueue
- type MemoryEntry
- type MemoryService
- type Model
- type ModelConnection
- type NotImplementedError
- type OAuth2Auth
- type OAuth2CredentialRefresher
- type OAuth2SecurityScheme
- type OAuth2Session
- type OAuthFlow
- type OAuthFlows
- type OAuthGrantType
- type OpenIDConnectWithConfig
- type OpenIdConnectSecurityScheme
- type Option
- type Planner
- type ReadOnlyContext
- type RunConfig
- type SearchMemoryResponse
- type SecurityScheme
- type ServiceAccount
- type ServiceAccountCredential
- type Session
- type SessionService
- type State
- func (s *State) ApplyDelta()
- func (s *State) ClearDelta()
- func (s *State) Get(key string) (any, bool)
- func (s *State) GetApp(key string) (any, bool)
- func (s *State) GetDelta() map[string]any
- func (s *State) GetTemp(key string) (any, bool)
- func (s *State) GetUser(key string) (any, bool)
- func (s *State) GetWithDefault(key string, defaultVal any) any
- func (s *State) Has(key string) bool
- func (s *State) HasDelta() bool
- func (s *State) Set(key string, val any)
- func (s *State) SetApp(key string, val any)
- func (s *State) SetTemp(key string, val any)
- func (s *State) SetUser(key string, val any)
- func (s *State) ToMap() map[string]any
- func (s *State) Update(update map[string]any)
- type StreamingMode
- type Tool
- type ToolCall
- type ToolContext
- func (tc *ToolContext) Actions() *EventActions
- func (tc *ToolContext) FunctionCallID() string
- func (tc *ToolContext) GetAuthResponse(authConfig *AuthConfig) *AuthCredential
- func (tc *ToolContext) InvocationContext() *InvocationContext
- func (tc *ToolContext) ListArtifacts(ctx context.Context) ([]string, error)
- func (tc *ToolContext) RequestCredential(ts *AuthConfig) error
- func (tc *ToolContext) SearchMemory(ctx context.Context, query string) (*SearchMemoryResponse, error)
- func (tc *ToolContext) WithEventActions(eventActions *EventActions) *ToolContext
- func (tc *ToolContext) WithFunctionCallID(funcCallID string) *ToolContext
- type Toolset
- type TranscriptionEntry
Constants ¶
const ( // AppPrefix is the prefix for application state keys AppPrefix = "app:" // UserPrefix is the prefix for user state keys UserPrefix = "user:" // TempPrefix is the prefix for temporary state keys TempPrefix = "temp:" )
Constants for different state key prefixes
const DefaultMaxLLMCalls = 500
DefaultMaxLLMCalls is the default limit on the total number of llm calls.
Variables ¶
This section is empty.
Functions ¶
func DecodeContent ¶
DecodeContent decodes a Content object from a JSON dictionary.
func Deref ¶
func Deref[T any](ptr *T, def T) T
Deref dereferences ptr and returns the value it points to if no nil, or else returns def.
func EncodeContent ¶
EncodeContent encodes a Content object to a JSON dictionary.
func NewEventID ¶
func NewEventID() string
func NewInvocationContextID ¶
func NewInvocationContextID() string
NewInvocationContextID generates a new invocation context ID.
func NewLLMCallsLimitExceededError ¶
NewLLMCallsLimitExceededError returns the new LLMCallsLimitExceededError error.
Types ¶
type APIKeySecurityScheme ¶
type APIKeySecurityScheme struct {
Type AuthCredentialTypes `json:"type"`
In APIKeyIn `json:"in,omitzero"`
Name string `json:"name,omitzero"`
}
APIKeySecurityScheme represents an API key security scheme.
func (*APIKeySecurityScheme) AuthType ¶
func (a *APIKeySecurityScheme) AuthType() AuthCredentialTypes
AuthType returns a string representation of the APIKeySecurityScheme type.
type ActiveStreamingTool ¶
type ActiveStreamingTool[T any] struct { // The active task of this streaming tool. Task *pyasyncio.Task[T] // Stream is the active LiveRequestQueue for this tool. Stream *LiveRequestQueue // contains filtered or unexported fields }
ActiveStreamingTool manages streaming tool related resources during invocation.
func NewActiveStreamingTool ¶
func NewActiveStreamingTool[T any]() *ActiveStreamingTool[T]
NewActiveStreamingTool creates a new ActiveStreamingTool instance.
func (*ActiveStreamingTool[T]) ClearStream ¶
func (a *ActiveStreamingTool[T]) ClearStream()
ClearStream clears the current stream.
func (*ActiveStreamingTool[T]) GetStream ¶
func (a *ActiveStreamingTool[T]) GetStream() *LiveRequestQueue
GetStream returns the current stream.
func (*ActiveStreamingTool[T]) IsActive ¶
func (a *ActiveStreamingTool[T]) IsActive() bool
IsActive returns true if there is an active task or stream.
func (*ActiveStreamingTool[T]) SetStream ¶
func (a *ActiveStreamingTool[T]) SetStream(stream *LiveRequestQueue)
SetStream sets the active stream for this tool.
func (*ActiveStreamingTool[T]) WithStream ¶
func (a *ActiveStreamingTool[T]) WithStream(stream *LiveRequestQueue) *ActiveStreamingTool[T]
func (*ActiveStreamingTool[T]) WithTask ¶
func (a *ActiveStreamingTool[T]) WithTask(task *pyasyncio.Task[T]) *ActiveStreamingTool[T]
type AfterModelCallback ¶
type AfterModelCallback func(cctx *CallbackContext, response *LLMResponse) (*LLMResponse, error)
AfterModelCallback is called after receiving a response from the model.
type AfterToolCallback ¶
type AfterToolCallback func(tool Tool, args map[string]any, toolCtx *ToolContext, toolResponse map[string]any) (map[string]any, error)
AfterToolCallback is called after executing a tool.
type Agent ¶
type Agent interface {
// Name returns the agent's name.
//
// Agent name must be a Python identifier and unique within the agent tree.
// Agent name cannot be "user", since it's reserved for end-user's input.
Name() string
// Description returns the description about the agent's capability.
//
// The model uses this to determine whether to delegate control to the agent.
// One-line description is enough and preferred.
Description() string
// ParentAgent is the parent agent of this agent.
//
// Note that an agent can ONLY be added as sub-agent once.
//
// If you want to add one agent twice as sub-agent, consider to create two agent
// instances with identical config, but with different name and add them to the
// agent tree.
ParentAgent() Agent
// SubAgents returns the sub-agents of this agent.
SubAgents() []Agent
// BeforeAgentCallbacks returns the list of [AgentCallback] to be invoked before the agent run.
//
// When a list of callbacks is provided, the callbacks will be called in the
// order they are listed until a callback does not return None.
BeforeAgentCallbacks() []AgentCallback
// AfterAgentCallbacks returns the list of [AgentCallback] to be invoked after the agent run.
//
// When a list of callbacks is provided, the callbacks will be called in the
// order they are listed until a callback does not return None.
AfterAgentCallbacks() []AgentCallback
// Execute is the core logic to run this agent via text-based conversation.
//
// Execute is equivalent to [agents._run_async_impl] in adk-python.
Execute(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
// ExecuteLive is the core logic to run this agent via video/audio-based conversation.
//
// ExecuteLive is equivalent to [agents._run_live_impl] in adk-python.
ExecuteLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
// Run is the entry method to run an agent via text-based conversation.
//
// Run is equivalent to [agents.run_async] in adk-python.
Run(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
// RunLive is the entry method to run an agent via video/audio-based conversation.
//
// RunLive is equivalent to [agents.run_live] in adk-python.
RunLive(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
// Gets the root agent of this agent.
RootAgent() Agent
// FindAgent finds the agent with the given name in this agent and its descendants.
FindAgent(name string) Agent
// FindSubAgent finds the agent with the given name in this agent's descendants.
FindSubAgent(name string) Agent
// AsLLMAgent reports whether this agent is an [LLMAgent].
AsLLMAgent() (LLMAgent, bool)
}
Agent represents an all agents in Agent Development Kit.
type AgentCallback ¶
type AgentCallback func(cctx *CallbackContext) (*genai.Content, error)
AgentCallback represents a callback function that can be invoked before or after an agent runs.
type ArtifactService ¶
type ArtifactService interface {
// SaveArtifact saves an artifact to the artifact service storage.
//
// The artifact is a file identified by the app name, user ID, session ID, and
// filename. After saving the artifact, a revision ID is returned to identify
// the artifact version.
SaveArtifact(ctx context.Context, appName, userID, sessionID, filename string, artifact *genai.Part) (int, error)
// LoadArtifact gets an artifact from the artifact service storage.
//
// The artifact is a file identified by the app name, user ID, session ID, and filename.
LoadArtifact(ctx context.Context, appName, userID, sessionID, filename string, version int) (*genai.Part, error)
// ListArtifactKey lists all the artifact filenames within a session.
ListArtifactKey(ctx context.Context, appName, userID, sessionID string) ([]string, error)
// DeleteArtifact deletes an artifact.
DeleteArtifact(ctx context.Context, appName, userID, sessionID, filename string) error
// ListVersions lists all versions of an artifact.
ListVersions(ctx context.Context, appName, userID, sessionID, filename string) ([]int, error)
// Close closes the artifact service connection.
Close() error
}
ArtifactService represents an abstract base class for artifact services.
type AuthConfig ¶
type AuthConfig struct {
// The auth scheme used to collect credentials
AuthScheme AuthScheme
// The raw auth credential used to collect credentials. The raw auth
// credentials are used in some auth scheme that needs to exchange auth
// credentials. e.g. OAuth2 and OIDC. For other auth scheme, it could be None.
RawAuthCredential *AuthCredential
// The exchanged auth credential used to collect credentials. adk and client
// will work together to fill it. For those auth scheme that doesn't need to
// exchange auth credentials, e.g. API key, service account etc. It's filled by
// client directly. For those auth scheme that need to exchange auth credentials,
// e.g. OAuth2 and OIDC, it's first filled by adk. If the raw credentials
// passed by tool only has client id and client credential, adk will help to
// generate the corresponding authorization uri and state and store the processed
// credential in this field. If the raw credentials passed by tool already has
// authorization uri, state, etc. then it's copied to this field. Client will use
// this field to guide the user through the OAuth2 flow and fill auth response in
// this field.
ExchangedAuthCredential *AuthCredential
// contains filtered or unexported fields
}
AuthConfig response an auth config sent by tool asking client to collect auth credentials and adk and client will help to fill in the response.
func ConvertToAuthConfig ¶
func ConvertToAuthConfig(data map[string]any, config *AuthConfig) (*AuthConfig, error)
TODO(zchee): implements correctly
func (*AuthConfig) CredentialKey ¶
func (ac *AuthConfig) CredentialKey() string
CredentialKey builds a hash key based on auth_scheme and raw_auth_credential used to save / load this credential to / from a credentials service.
type AuthCredential ¶
type AuthCredential struct {
AuthType AuthCredentialTypes `json:"auth_type,omitzero"`
// Resource reference for the credential.
// This will be supported in the future.
ResourceRef string `json:"resource_ref,omitzero"`
APIKey string `json:"api_key,omitzero"`
HTTP *HTTPAuth `json:"http,omitzero"`
ServiceAccount *ServiceAccount `json:"service_account,omitzero"`
OAuth2 *OAuth2Auth `json:"oauth2,omitzero"`
}
AuthCredential represents a data class representing an authentication credential.
To exchange for the actual credential, please use CredentialExchanger.exchange_credential().
func UpdateCredentialWithTokens ¶
func UpdateCredentialWithTokens(authCredential *AuthCredential, token *oauth2.Token) *AuthCredential
UpdateCredentialWithTokens update the credential with new tokens.
type AuthCredentialTypes ¶
type AuthCredentialTypes string
AuthCredentialTypes represents the type of authentication credential.
const ( // # API Key credential: // # https://swagger.io/docs/specification/v3_0/authentication/api-keys/ APIKeyCredentialTypes AuthCredentialTypes = "apiKey" // Credentials for HTTP Auth schemes: // https://www.iana.org/assignments/http-authschemes/http-authschemes.xhtml HTTPCredentialTypes AuthCredentialTypes = "http" // OAuth2 credentials: // https://swagger.io/docs/specification/v3_0/authentication/oauth2/ OAuth2CredentialTypes AuthCredentialTypes = "oauth2" // OpenID Connect credentials: // https://swagger.io/docs/specification/v3_0/authentication/openid-connect-discovery/ OpenIDConnectCredentialTypes AuthCredentialTypes = "openIdConnect" // Service Account credentials: // https://cloud.google.com/iam/docs/service-account-creds ServiceAccountCredentialTypes AuthCredentialTypes = "serviceAccount" )
func GetAuthSchemeType ¶
func GetAuthSchemeType(scheme AuthScheme) AuthCredentialTypes
GetAuthSchemeType returns the scheme type from an AuthScheme type.
type AuthHandler ¶
type AuthHandler struct {
// contains filtered or unexported fields
}
func NewAuthHandler ¶
func NewAuthHandler(authConfig *AuthConfig) *AuthHandler
NewAuthHandler creates a new AuthHandler with the given authConfig.
func (*AuthHandler) ExchangeAuthToken ¶
func (h *AuthHandler) ExchangeAuthToken(ctx context.Context) (*AuthCredential, error)
ExchangeAuthToken Generates an auth token from the authorization response.
func (*AuthHandler) GenerateAuthRequest ¶
func (h *AuthHandler) GenerateAuthRequest() (*AuthConfig, error)
func (*AuthHandler) GenerateAuthURI ¶
func (h *AuthHandler) GenerateAuthURI() (*AuthCredential, error)
GenerateAuthURI generates an response containing the auth uri for user to sign in.
func (*AuthHandler) GetAuthResponse ¶
func (h *AuthHandler) GetAuthResponse(state *State) *AuthCredential
func (*AuthHandler) GetCredentialKey ¶
func (h *AuthHandler) GetCredentialKey() string
GetCredentialKey generates an unique key for the given auth scheme and credential.
func (*AuthHandler) ParseAndStoreAuthSesponse ¶
func (h *AuthHandler) ParseAndStoreAuthSesponse(ctx context.Context, state *State) error
type AuthScheme ¶
type AuthScheme interface {
AuthType() AuthCredentialTypes
}
AuthScheme represents either a SecurityScheme or OpenIDConnectWithConfig.
type AuthToolArguments ¶
type AuthToolArguments struct {
// FunctionCallID is the ID of the function call requesting authentication.
FunctionCallID string `json:"function_call_id"`
// AuthConfig is the authentication configuration requested.
AuthConfig *AuthConfig `json:"auth_config"`
}
AuthToolArguments response an arguments for the special long running function tool that is used to request end user credentials.
type AuthenticatedTool ¶
type AuthenticatedTool interface {
Tool
// Execute executes the tool logic with the provided arguments, tool context, and authentication credential.
Execute(ctx context.Context, args map[string]any, toolCtx *ToolContext, credential *AuthCredential) (any, error)
}
AuthenticatedTool represents a base tool class that handles authentication before the actual tool logic gets called. Functions can accept a special `credential` argument which is the credential ready for use.(Experimental)
type BaseAgent ¶
type BaseAgent struct {
*Config
}
BaseAgent represents the base agent.
func NewBaseAgent ¶
NewBaseAgent creates a new agent configuration with the given name.
TODO(zchee): implements validate logic same as belows in adk-python.
agents.BaseAgent.__validate_name agents.BaseAgent.__set_parent_agent_for_sub_agents
func (*BaseAgent) AfterAgentCallbacks ¶
func (a *BaseAgent) AfterAgentCallbacks() []AgentCallback
AfterAgentCallbacks implements Agent.
func (*BaseAgent) AsLLMAgent ¶
AsLLMAgent implements types.Agent.
func (*BaseAgent) BeforeAgentCallbacks ¶
func (a *BaseAgent) BeforeAgentCallbacks() []AgentCallback
BeforeAgentCallbacks implements Agent.
func (*BaseAgent) Description ¶
Description implements Agent.
func (*BaseAgent) ExecuteLive ¶
func (a *BaseAgent) ExecuteLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
ExecuteLive implements Agent.
func (*BaseAgent) FindSubAgent ¶
FindSubAgent finds the agent with the given name in this agent's descendants.
func (*BaseAgent) ParentAgent ¶
ParentAgent implements types.Agent.
func (*BaseAgent) Run ¶
func (a *BaseAgent) Run(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
Run implements Agent.
func (*BaseAgent) RunLive ¶
func (a *BaseAgent) RunLive(ctx context.Context, parentContext *InvocationContext) iter.Seq2[*Event, error]
RunLive implements Agent.
func (*BaseAgent) SubAgents ¶
SubAgents implements types.Agent.
type BeforeModelCallback ¶
type BeforeModelCallback func(cctx *CallbackContext, request *LLMRequest) (*LLMResponse, error)
BeforeModelCallback is called before sending a request to the model.
type BeforeToolCallback ¶
type BeforeToolCallback func(tool Tool, args map[string]any, toolCtx *ToolContext) (map[string]any, error)
BeforeToolCallback is called before executing a tool.
type CallbackContext ¶
type CallbackContext struct {
*ReadOnlyContext
// contains filtered or unexported fields
}
CallbackContext provides the context of various callbacks within an agent run.
func NewCallbackContext ¶
func NewCallbackContext(iccx *InvocationContext) *CallbackContext
NewCallbackContext creates a new *CallbackContext with the given args.
func (*CallbackContext) EventActions ¶
func (cc *CallbackContext) EventActions() *EventActions
EventActions returns the event actions of the current session.
func (*CallbackContext) LoadArtifact ¶
func (cc *CallbackContext) LoadArtifact(ctx context.Context, filename string, version int) (*genai.Part, error)
LoadArtifact loads an artifact attached to the current session.
func (*CallbackContext) SaveArtifact ¶
func (cc *CallbackContext) SaveArtifact(ctx context.Context, filename string, artifact *genai.Part) (int, error)
SaveArtifact saves an artifact and records it as delta for the current session.
func (*CallbackContext) State ¶
func (cc *CallbackContext) State() *State
State returns the delta-aware state of the current session.
For any state change, you can mutate this object directly, e.g. `ctx.state['foo'] = 'bar'`
func (*CallbackContext) WithEventActions ¶
func (cc *CallbackContext) WithEventActions(eventActions *EventActions) *CallbackContext
type CodeExecutionFile ¶
type CodeExecutionFile struct {
// Name is the filename, including any relative path.
Name string `json:"name"`
// Content is the raw file content as bytes.
Content []byte `json:"-"`
// MIMEType specifies the MIME type of the file content.
// If empty, it will be inferred from the file extension or content.
MIMEType string `json:"mime_type,omitempty"`
// Size is the size of the content in bytes.
Size int64 `json:"size"`
}
CodeExecutionFile represents a file with content for code execution. Content is stored as raw bytes internally but marshaled as base64 for JSON compatibility.
func NewExecutionFile ¶
func NewExecutionFile(name string, content []byte, mimeType string) *CodeExecutionFile
NewExecutionFile creates a new ExecutionFile with the given name and content.
func NewExecutionFileFromPath ¶
func NewExecutionFileFromPath(path string) (*CodeExecutionFile, error)
NewExecutionFileFromPath creates a new ExecutionFile by reading from a file path.
func (*CodeExecutionFile) IsBinary ¶
func (f *CodeExecutionFile) IsBinary() bool
IsBinary returns true if the file appears to contain binary content.
func (*CodeExecutionFile) IsText ¶
func (f *CodeExecutionFile) IsText() bool
IsText returns true if the file appears to contain text content.
func (*CodeExecutionFile) MarshalJSON ¶
func (f *CodeExecutionFile) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler to encode content as base64.
func (*CodeExecutionFile) String ¶
func (f *CodeExecutionFile) String() string
String returns a string representation of the file.
func (*CodeExecutionFile) UnmarshalJSON ¶
func (f *CodeExecutionFile) UnmarshalJSON(data []byte) error
UnmarshalJSON implements json.Unmarshaler to decode content from base64.
func (*CodeExecutionFile) WriteToFile ¶
func (f *CodeExecutionFile) WriteToFile(path string) error
WriteToFile writes the ExecutionFile content to the specified path.
type CodeExecutionInput ¶
type CodeExecutionInput struct {
// Code is the code to execute.
Code string `json:"code"`
// Language specifies the programming language (e.g., "python", "go", "javascript").
// If empty, the executor may attempt to auto-detect or use a default.
Language string `json:"language,omitempty"`
// InputFiles are files that should be available to the code during execution.
InputFiles []*CodeExecutionFile `json:"input_files,omitempty"`
// ExecutionID is an optional identifier for stateful execution sessions.
// When provided, stateful executors will maintain session state across calls.
ExecutionID string `json:"execution_id,omitempty"`
// WorkingDirectory specifies the directory where code should be executed.
// If empty, a temporary directory will be used.
WorkingDirectory string `json:"working_directory,omitempty"`
// Environment contains environment variables to set during execution.
Environment map[string]string `json:"environment,omitempty"`
// Timeout specifies the maximum execution time.
// If zero, the executor's default timeout will be used.
Timeout time.Duration `json:"timeout,omitempty"`
}
CodeExecutionInput represents a structure that contains the input of code execution.
type CodeExecutionResult ¶
type CodeExecutionResult struct {
// Code is the code to execute.
Code string `json:"code"`
// Stdout contains the standard output from the executed code.
Stdout string `json:"stdout"`
// Stderr contains the standard error output from the executed code.
Stderr string `json:"stderr"`
// OutputFiles contains files generated during code execution.
OutputFiles []*CodeExecutionFile `json:"output_files,omitempty"`
// ExitCode is the exit code returned by the executed code.
// A value of 0 typically indicates success.
ExitCode int `json:"exit_code"`
Timestamp time.Time `json:"timestamp"`
// ExecutionTime is the duration the code took to execute.
ExecutionTime time.Duration `json:"execution_time"`
// ExecutionID is the session identifier used for this execution.
ExecutionID string `json:"execution_id,omitempty"`
// Error contains any execution error that occurred.
// This is separate from stderr and represents infrastructure errors.
Error error `json:"error,omitempty"`
}
CodeExecutionResult represents the result of code execution.
type CodeExecutor ¶
type CodeExecutor interface {
// OptimizeDataFile reports whether the extract and process data files from the model request
// and attach them to the code executor.
// Supported data file MimeTypes are [text/csv].
//
// Default to false.
OptimizeDataFile() bool
// IsLongRunning reports whether the code executor supports long-running operations.
IsLongRunning() bool
// IsStateful reports whether the code executor is stateful.
//
// Stateful executors can reuse variables and imports across multiple Execute calls.
IsStateful() bool
// ErrorRetryAttempts returns the number of attempts to retry on consecutive code execution errors.
//
// Default to 2.
ErrorRetryAttempts() int
// CodeBlockDelimiters returns the list of the enclosing delimiters to identify the code blocks.
//
// For example, the delimiter ('“`python\n', '\n“`') can be
// used to identify code blocks with the following format:
//
// “`python
// print("hello")
// “`
CodeBlockDelimiters() []DelimiterPair
// ExecutionResultDelimiters returns the delimiters to format the code execution result.
ExecutionResultDelimiters() DelimiterPair
// Execute runs the provided code and returns the execution result.
// The context can be used for cancellation and timeout control.
ExecuteCode(ctx context.Context, ictx *InvocationContext, input *CodeExecutionInput) (*CodeExecutionResult, error)
// Close cleans up any resources used by the executor.
Close() error
}
CodeExecutor defines the interface for executing code in various environments. It supports both stateful and stateless execution modes with configurable retry logic and file handling.
type Config ¶
type Config struct {
// The agent's Name.
//
// Agent Name must be a Go identifier and unique within the agent tree.
// Agent Name cannot be "user", since it's reserved for end-user's input.
Name string
// Description about the agent's capability.
//
// The model uses this to determine whether to delegate control to the agent.
// One-line Description is enough and preferred.
Description string
// contains filtered or unexported fields
}
Config represents the configuration for an types.Agent.
type CredentialExchangError ¶
type CredentialExchangError string
CredentialExchangError is the credential exchange errors.
func (CredentialExchangError) Error ¶
func (e CredentialExchangError) Error() string
Error returns a string representation of the CredentialExchangError.
type CredentialExchanger ¶
type CredentialExchanger interface {
// Exchange exchange credential if needed.
Exchange(ctx context.Context, authCredential *AuthCredential, authScheme AuthScheme) (*AuthCredential, error)
}
CredentialExchanger represents an interface for credential exchangers.
Credential exchangers are responsible for exchanging credentials from one format or scheme to another.
type CredentialExchangerRegistry ¶
type CredentialExchangerRegistry struct {
// contains filtered or unexported fields
}
CredentialExchangerRegistry registry for credential exchanger instances.
Experimental ¶
This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
func NewCredentialExchangerRegistry ¶
func NewCredentialExchangerRegistry() *CredentialExchangerRegistry
NewCredentialExchangerRegistry returns the new CredentialExchangerRegistry.
func (*CredentialExchangerRegistry) GetExchanger ¶
func (e *CredentialExchangerRegistry) GetExchanger(credentialType AuthCredentialTypes) (CredentialExchanger, bool)
GetExchanger get the exchanger for a credential type.
func (*CredentialExchangerRegistry) Register ¶
func (e *CredentialExchangerRegistry) Register(credentialType AuthCredentialTypes, exchanger CredentialExchanger)
Register registry for credential exchanger instances.
type CredentialManager ¶
type CredentialManager struct {
// contains filtered or unexported fields
}
CredentialManager manages authentication credentials through a structured workflow.
The CredentialManager orchestrates the complete lifecycle of authentication credentials, from initial loading to final preparation for use. It provides a centralized interface for handling various credential types and authentication schemes while maintaining proper credential hygiene (refresh, exchange, caching).
This class is only for use by Agent Development Kit.
Experimental ¶
This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
func NewCredentialManager ¶
func NewCredentialManager(authConfig *AuthConfig) *CredentialManager
NewCredentialManager creates a new CredentialManager with the given AuthConfig.
func (*CredentialManager) AuthConfig ¶
func (cm *CredentialManager) AuthConfig() *AuthConfig
AuthConfig returns the AuthConfig used by the CredentialManager.
func (*CredentialManager) GetAuthCredential ¶
func (cm *CredentialManager) GetAuthCredential(ctx context.Context, toolCtx *ToolContext) (*AuthCredential, error)
GetAuthCredential load and prepare authentication credential through a structured workflow.
func (*CredentialManager) RegisterCredentialExchanger ¶
func (cm *CredentialManager) RegisterCredentialExchanger(ctx context.Context, credentialType AuthCredentialTypes, exchanger CredentialExchanger)
RegisterCredentialExchanger register a credential exchanger for a credential type.
func (*CredentialManager) RequestCredential ¶
func (cm *CredentialManager) RequestCredential(ctx context.Context, toolCtx *ToolContext)
RequestCredential requests a credential for the given ToolContext.
type CredentialRefresher ¶
type CredentialRefresher interface {
// IsRefreshNeeded checks if a credential needs to be refreshed.
IsRefreshNeeded(ctx context.Context, authCredential *AuthCredential, authScheme AuthScheme) bool
// Refresh refreshes a credential if needed.
Refresh(ctx context.Context, authCredential *AuthCredential, authScheme AuthScheme) (*AuthCredential, error)
}
CredentialRefresher represents an interface for credential refreshers.
Credential refreshers are responsible for checking if a credential is expired or needs to be refreshed, and for refreshing it if necessary.
type CredentialRefresherError ¶
type CredentialRefresherError string
CredentialRefresherError is the credential refresh errors.
func (CredentialRefresherError) Error ¶
func (e CredentialRefresherError) Error() string
Error returns a string representation of the CredentialRefresherError.
type CredentialRefresherRegistry ¶
type CredentialRefresherRegistry struct {
// contains filtered or unexported fields
}
CredentialRefresherRegistry registry for credential refresher instances.
Experimental ¶
This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
func NewCredentialRefresherRegistry ¶
func NewCredentialRefresherRegistry() *CredentialRefresherRegistry
NewCredentialRefresherRegistry returns the new CredentialRefresherRegistry.
func (*CredentialRefresherRegistry) GetRefresher ¶
func (r *CredentialRefresherRegistry) GetRefresher(credentialType AuthCredentialTypes) (CredentialRefresher, bool)
GetRefresher get the refresher instance for a credential type.
func (*CredentialRefresherRegistry) Register ¶
func (r *CredentialRefresherRegistry) Register(credentialType AuthCredentialTypes, refresher CredentialRefresher)
Register register a refresher instance for a credential type.
type CredentialService ¶
type CredentialService interface {
// LoadCredential loads the credential by auth config and current tool context from the
// backend credential store.
LoadCredential(ctx context.Context, authConfig *AuthConfig, toolCtx *ToolContext) (*AuthCredential, error)
// SaveCredential saves the exchanged_auth_credential in auth config to the backend credential
// store.
SaveCredential(ctx context.Context, authConfig *AuthConfig, toolCtx *ToolContext) error
}
CredentialService represents an abstract class for Service that loads / saves tool credentials from / to the backend credential store.
Experimental ¶
This feature is experimental and may change or be removed in future versions without notice. It may introduce breaking changes at any time.
type DelimiterPair ¶
DelimiterPair represents a pair of start and end delimiters for text parsing.
type Event ¶
type Event struct {
*LLMResponse
// InvocationID is The invocation ID of the event.
// TODO(adk-python): revert to be required after spark migration
InvocationID string
// Author is the 'user' or the name of the agent, indicating who appended the event to the session.
Author string
// Actions is the Actions taken by the agent
Actions *EventActions
// LongRunningToolIDs set of ids of the long running function calls.
//
// Agent client will know from this field about which function call is long running.
// Only valid for function call event.
LongRunningToolIDs py.Set[string]
// Branch is The Branch of the event.
//
// The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
// agent_2, and agent_2 is the parent of agent_3.
//
// Branch is used when multiple sub-agent shouldn't see their peer agents'
// conversation history.
Branch string
// ID is the unique identifier of the event.
//
// ReadOnly. It will be assigned by the session layer.
ID string
// Timestamp is The Timestamp of the event.
//
// ReadOnly. It will be assigned by the session layer.
Timestamp time.Time
}
Event represents an event in a conversation between agents and users.
It is used to store the content of the conversation, as well as the actions taken by the agents like function calls, etc.
func (*Event) GetFunctionCalls ¶
func (e *Event) GetFunctionCalls() []*genai.FunctionCall
GetFunctionCalls returns the function calls in the event.
func (*Event) GetFunctionResponses ¶
func (e *Event) GetFunctionResponses() []*genai.FunctionResponse
GetFunctionResponses returns the function responses in the event.
func (*Event) HasTrailingCodeExecutionResult ¶
HasTrailingCodeExecutionResult returns whether the event has a trailing code execution result.
func (*Event) IsFinalResponse ¶
IsFinalResponse returns whether the event is the final response of the agent.
func (*Event) WithActions ¶
func (e *Event) WithActions(actions *EventActions) *Event
WithActions sets the actions of the event.
func (*Event) WithAuthor ¶
WithAuthor sets the author of the event.
func (*Event) WithBranch ¶
WithBranch sets the branch of the event.
func (*Event) WithContent ¶
WithContent sets the content of the event's LLMResponse.
func (*Event) WithInvocationID ¶
WithInvocationID sets the invocation ID of the event.
func (*Event) WithLLMResponse ¶
func (e *Event) WithLLMResponse(response *LLMResponse) *Event
WithLLMResponse sets the LLMResponse for the event.
func (*Event) WithLongRunningToolIDs ¶
WithLongRunningToolIDs sets the long running tool IDs of the event.
type EventActions ¶
type EventActions struct {
// SkipSummarization if true, it won't call model to summarize function response.
//
// Only used for functionResponse event.
SkipSummarization bool
// StateDelta indicates that the event is updating the state with the given delta.
StateDelta map[string]any
// ArtifactDelta indicates that the event is updating an artifact. key is the filename, value is the version.
ArtifactDelta map[string]int
// TransferToAgent if set, the event transfers to the specified agent.
TransferToAgent string
// Escalate is the agent is escalating to a higher level agent.
Escalate bool
// RequestedAuthConfigs authentication configurations requested by tool responses.
//
// This field will only be set by a tool response event indicating tool request
// auth credential.
//
// Keys:
// The function call id. Since one function response event could contain
// multiple function responses that correspond to multiple function calls. Each
// function call could request different auth configs. This id is used to
// identify the function call.
//
// Values:
// The requested auth config.
RequestedAuthConfigs map[string]*AuthConfig
}
EventActions represents the actions attached to an event.
func NewEventActions ¶
func NewEventActions() *EventActions
NewEventActions creates a new EventActions instance with default values.
func (*EventActions) WithArtifactDelta ¶
func (ea *EventActions) WithArtifactDelta(artifactDelta map[string]int) *EventActions
WithArtifactDelta configures the artifactDelta to the EventActions.
func (*EventActions) WithEscalate ¶
func (ea *EventActions) WithEscalate(escalate bool) *EventActions
WithEscalate configures the escalate to the EventActions.
func (*EventActions) WithRequestedAuthConfigs ¶
func (ea *EventActions) WithRequestedAuthConfigs(requestedAuthConfigs map[string]*AuthConfig) *EventActions
WithRequestedAuthConfigs configures the requestedAuthConfigs to the EventActions.
func (*EventActions) WithSkipSummarization ¶
func (ea *EventActions) WithSkipSummarization(skipSummarization bool) *EventActions
WithSkipSummarization configures the skipSummarization to the EventActions.
func (*EventActions) WithStateDelta ¶
func (ea *EventActions) WithStateDelta(stateDelta map[string]any) *EventActions
WithStateDelta configures the stateDelta to the EventActions.
func (*EventActions) WithTransferToAgent ¶
func (ea *EventActions) WithTransferToAgent(transferToAgent string) *EventActions
WithTransferToAgent configures the transferToAgent to the EventActions.
type ExecutionConfig ¶
type ExecutionConfig struct {
// OptimizeDataFiles enables optimization for large data files (e.g., CSV processing).
OptimizeDataFiles bool
// LongRunning indicates whether the code executor supports long-running operations.
LongRunning bool
// Stateful whether the code executor is stateful.
Stateful bool
// MaxRetries specifies the maximum number of retry attempts for failed executions.
MaxRetries int
// RetryDelay specifies the delay between retry attempts.
RetryDelay time.Duration
// DefaultTimeout specifies the default execution timeout.
DefaultTimeout time.Duration
// CodeBlockDelimiters defines the patterns used to extract code blocks from text.
CodeBlockDelimiters []DelimiterPair
// ExecutionResultDelimiters defines the patterns used to format execution results.
ExecutionResultDelimiters DelimiterPair
}
ExecutionConfig holds configuration options for code executors.
func DefaultConfig ¶
func DefaultConfig() *ExecutionConfig
DefaultConfig returns a default ExecutionConfig with sensible defaults.
type ExecutionOption ¶
type ExecutionOption func(*ExecutionConfig)
ExecutionOption is a functional option for configuring code executors.
func WithCodeBlockDelimiters ¶
func WithCodeBlockDelimiters(delimiters ...DelimiterPair) ExecutionOption
WithCodeBlockDelimiters sets custom code block delimiters.
func WithDefaultTimeout ¶
func WithDefaultTimeout(timeout time.Duration) ExecutionOption
WithDefaultTimeout sets the default execution timeout.
func WithExecutionResultDelimiters ¶
func WithExecutionResultDelimiters(delimiters DelimiterPair) ExecutionOption
WithExecutionResultDelimiters sets custom execution result delimiters.
func WithMaxRetries ¶
func WithMaxRetries(retries int) ExecutionOption
WithMaxRetries sets the maximum number of retry attempts.
func WithOptimizeDataFiles ¶
func WithOptimizeDataFiles(optimize bool) ExecutionOption
WithOptimizeDataFiles enables or disables data file optimization.
func WithRetryDelay ¶
func WithRetryDelay(delay time.Duration) ExecutionOption
WithRetryDelay sets the delay between retry attempts.
type Flow ¶
type Flow interface {
// Run runs the flow with the given invocation context and returns a sequence of events.
Run(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
// RunLive runs the flow with the given invocation context in a live mode and returns a sequence of events.
RunLive(ctx context.Context, ictx *InvocationContext) iter.Seq2[*Event, error]
}
Flow represents the basic interface that all flows must implement.
type GetSessionConfig ¶
GetSessionConfig is the configuration of getting a session.
type HTTPAuth ¶
type HTTPAuth struct {
Scheme string `json:"scheme"`
Credentials HTTPCredentials `json:"Credentials"`
}
HTTPAuth represents a credentials and metadata for HTTP authentication.
The name of the HTTP Authorization scheme to be used in the Authorization header as defined in RFC7235. The values used SHOULD be registered in the IANA Authentication Scheme registry. Examples: 'basic', 'bearer'
type HTTPBaseSecurityScheme ¶
type HTTPBaseSecurityScheme struct {
Type AuthCredentialTypes `json:"type"`
Scheme string `json:"scheme,omitzero"`
}
HTTPBaseSecurityScheme represents a base HTTP security scheme.
func (*HTTPBaseSecurityScheme) AuthType ¶
func (a *HTTPBaseSecurityScheme) AuthType() AuthCredentialTypes
AuthType returns a string representation of the HTTPBaseSecurityScheme type.
type HTTPCredentials ¶
type IncludeContents ¶
type IncludeContents string
IncludeContents whether to include contents in the model request.
const ( IncludeContentsDefault IncludeContents = "default" IncludeContentsNone IncludeContents = "none" )
type InstructionProvider ¶
type InstructionProvider func(rctx *ReadOnlyContext) string
InstructionProvider is a function that provides instructions based on context.
type InvocationContext ¶
type InvocationContext struct {
ArtifactService ArtifactService
SessionService SessionService
MemoryService MemoryService
CredentialService CredentialService
// InvocationID is the id of this invocation context. Readonly.
InvocationID string
// The branch of the invocation context.
//
// The format is like agent_1.agent_2.agent_3, where agent_1 is the parent of
// agent_2, and agent_2 is the parent of agent_3.
//
// Branch is used when multiple sub-agents shouldn't see their peer agents'
// conversation history.
Branch string
// The current agent of this invocation context. Readonly.
Agent Agent
// The user content that started this invocation. Readonly.
UserContent *genai.Content
// The current session of this invocation context. Readonly.
Session Session
// Whether to end this invocation.
//
// Set to True in callbacks or tools to terminate this invocation.
EndInvocation bool
// The queue to receive live requests.
LiveRequestQueue *LiveRequestQueue
// The running streaming tools of this invocation.
ActiveStreamingTools map[string]*ActiveStreamingTool[any]
// Caches necessary, data audio or contents, that are needed by transcription.
TranscriptionCache []*TranscriptionEntry
// Configurations for live agents under this invocation.
RunConfig *RunConfig
// contains filtered or unexported fields
}
InvocationContext an invocation context represents the data of a single invocation of an agent.
An invocation:
- Starts with a user message and ends with a final response.
- Can contain one or multiple agent calls.
- Is handled by runner.run_async().
An invocation runs an agent until it does not request to transfer to another agent.
An agent call:
- Is handled by agent.run().
- Ends when agent.run() ends.
An LLM agent call is an agent with a BaseLLMFlow.
An LLM agent call can contain one or multiple steps.
An LLM agent runs steps in a loop until:
- A final response is generated.
- The agent transfers to another agent.
- The end_invocation is set to true by any callbacks or tools.
A step:
- Calls the LLM only once and yields its response.
- Calls the tools and yields their responses if requested.
The summarization of the function response is considered another step, since it is another llm call. A step ends when it's done calling llm and tools, or if the end_invocation is set to true at any time.
┌─────────────────────── invocation ──────────────────────────┐ ┌──────────── llm_agent_call_1 ────────────┐ ┌─ agent_call_2 ─┐ ┌──── step_1 ────────┐ ┌───── step_2 ──────┐ [call_llm] [call_tool] [call_llm] [transfer]
func NewInvocationContext ¶
func NewInvocationContext(agent Agent, session Session, sessionSvc SessionService, opts ...InvocationContextOption) *InvocationContext
NewInvocationContext creates a new InvocationContext.
func (*InvocationContext) AppName ¶
func (ictx *InvocationContext) AppName() string
func (*InvocationContext) IncrementLLMCallCount ¶
func (ictx *InvocationContext) IncrementLLMCallCount() error
IncrementLLMCallCount tracks number of llm calls made.
func (*InvocationContext) UserID ¶
func (ictx *InvocationContext) UserID() string
type InvocationContextOption ¶
type InvocationContextOption func(*InvocationContext)
InvocationContextOption is a function that modifies the InvocationContext.
func WithActiveStreamingTools ¶
func WithActiveStreamingTools[T any](activeStreamingTools map[string]*ActiveStreamingTool[any]) InvocationContextOption
func WithArtifactService ¶
func WithArtifactService(svc ArtifactService) InvocationContextOption
func WithBranch ¶
func WithBranch(branch string) InvocationContextOption
func WithLiveRequestQueue ¶
func WithLiveRequestQueue(liveRequestQueue *LiveRequestQueue) InvocationContextOption
func WithMemoryService ¶
func WithMemoryService(svc MemoryService) InvocationContextOption
func WithTranscriptionCache ¶
func WithTranscriptionCache(entries ...*TranscriptionEntry) InvocationContextOption
func WithUserContent ¶
func WithUserContent(content *genai.Content) InvocationContextOption
type InvocationCostManager ¶
type InvocationCostManager struct {
// contains filtered or unexported fields
}
InvocationCostManager represents a container to keep track of the cost of invocation.
While we don't expected the metrics captured here to be a direct representatative of monetary cost incurred in executing the current invocation, but they, in someways have an indirect affect.
func (*InvocationCostManager) IncrementAndEnforceLLMCallsLimit ¶
func (mgr *InvocationCostManager) IncrementAndEnforceLLMCallsLimit(runConfig *RunConfig) error
IncrementAndEnforceLLMCallsLimit increments llmCalls and enforces the limit.
type LLMAgent ¶
type LLMAgent interface {
Agent
// CanonicalModel returns the resolved model field as [model.Model].
//
// This method is only for use by Agent Development Kit.
CanonicalModel(ctx context.Context) (Model, error)
// CanonicalInstructions returns the resolved self.instruction field to construct instruction for this agent.
//
// This method is only for use by Agent Development Kit.
CanonicalInstructions(rctx *ReadOnlyContext) string
// CanonicalGlobalInstruction returns the resolved self.instruction field to construct global instruction.
//
// This method is only for use by Agent Development Kit.
CanonicalGlobalInstruction(rctx *ReadOnlyContext) (string, bool)
// CanonicalTool returns the resolved tools field as a list of [Tool] based on the context.
//
// This method is only for use by Agent Development Kit.
CanonicalTool(rctx *ReadOnlyContext) []Tool
// GenerateContentConfig returns the [*genai.GenerateContentConfig] for [LLMAgent] agent.
GenerateContentConfig() *genai.GenerateContentConfig
// DisallowTransferToParent reports whether teh disallows LLM-controlled transferring to the parent agent.
DisallowTransferToParent() bool
// DisallowTransferToPeers reports whether teh disallows LLM-controlled transferring to the peer agents.
DisallowTransferToPeers() bool
// IncludeContents returns the mode of include contents in the model request.
IncludeContents() IncludeContents
// InputSchema returns the structured input.
InputSchema() *genai.Schema
// OutputSchema returns the structured output.
OutputSchema() *genai.Schema
// OutputKey returns the key in session state to store the output of the agent.
OutputKey() string
// Planner returns the instructs the agent to make a plan and execute it step by step.
Planner() Planner
// CodeExecutor returns the code executor for the agent.
CodeExecutor() CodeExecutor
// BeforeModelCallbacks returns the resolved self.before_model_callback field as a list of _SingleBeforeModelCallback.
//
// This method is only for use by Agent Development Kit.
BeforeModelCallbacks() []BeforeModelCallback
// AfterModelCallbacks returns the resolved self.before_tool_callback field as a list of BeforeToolCallback.
//
// This method is only for use by Agent Development Kit.
AfterModelCallbacks() []AfterModelCallback
// BeforeToolCallbacks returns the resolved self.before_tool_callback field as a list of BeforeToolCallback.
//
// This method is only for use by Agent Development Kit.
BeforeToolCallback() []BeforeToolCallback
// AfterToolCallbacks returns the resolved self.after_tool_callback field as a list of AfterToolCallback.
//
// This method is only for use by Agent Development Kit.
AfterToolCallbacks() []AfterToolCallback
}
LLMAgent is an interface for agents that are specifically designed to work with LLMs (Large Language Models).
type LLMCallsLimitExceededError ¶
type LLMCallsLimitExceededError string
LLMCallsLimitExceededError represents error thrown when the number of LLM calls exceed the limit.
func (LLMCallsLimitExceededError) Error ¶
func (e LLMCallsLimitExceededError) Error() string
Error returns a string representation of the LLMCallsLimitExceededError.
type LLMRequest ¶
type LLMRequest struct {
// The model name.
Model string `json:"model,omitempty"`
// The contents to send to the model.
Contents []*genai.Content `json:"contents"`
// Additional config for the generate content request.
//
// tools in generate_content_config should not be set.
Config *genai.GenerateContentConfig `json:"config,omitempty"`
LiveConnectConfig *genai.LiveConnectConfig `json:"live_connect_config,omitempty"`
// The tools map.
ToolMap map[string]Tool `json:"tool_map,omitempty"`
}
LLMRequest represents a LLM request class that allows passing in tools, output schema and system.
func NewLLMRequest ¶
func NewLLMRequest(contents []*genai.Content, opts ...LLMRequestOption) *LLMRequest
NewLLMRequest creates a new LLMRequest.
func (*LLMRequest) AppendInstructions ¶
func (r *LLMRequest) AppendInstructions(instructions ...string)
AppendInstructions appends instructions to the system instruction.
func (*LLMRequest) AppendTools ¶
func (r *LLMRequest) AppendTools(tools ...Tool) *LLMRequest
AppendTools adds tools to the request.
func (*LLMRequest) SetOutputSchema ¶
func (r *LLMRequest) SetOutputSchema(schema *genai.Schema) *LLMRequest
SetOutputSchema configures the expected response format.
func (*LLMRequest) ToGenaiContents ¶
func (r *LLMRequest) ToGenaiContents() []*genai.Content
ToGenaiContents converts the LLMRequest contents to genai.Content slice.
func (*LLMRequest) ToJSON ¶
func (r *LLMRequest) ToJSON() (string, error)
ToJSON converts the request to a JSON string.
func (*LLMRequest) WithModelName ¶
func (r *LLMRequest) WithModelName(name string) LLMRequestOption
WithModelName sets the model name.
type LLMRequestOption ¶
type LLMRequestOption func(*LLMRequest)
func WithGenerationConfig ¶
func WithGenerationConfig(config *genai.GenerateContentConfig) LLMRequestOption
WithGenerationConfig sets the *genai.GenerateContentConfig for the LLMRequestOption.
func WithLiveConnectConfig ¶
func WithLiveConnectConfig(config *genai.LiveConnectConfig) LLMRequestOption
WithLiveConnectConfig sets the *genai.LiveConnectConfig for the LLMRequestOption.
func WithSafetySettings ¶
func WithSafetySettings(settings ...*genai.SafetySetting) LLMRequestOption
WithSafetySettings sets the *genai.SafetySetting for the LLMRequestOption.
type LLMRequestProcessor ¶
type LLMRequestProcessor interface {
// Run runs the processor.
Run(ctx context.Context, ictx *InvocationContext, request *LLMRequest) iter.Seq2[*Event, error]
}
LLMRequestProcessor represents a base class for LLM request processor.
type LLMResponse ¶
type LLMResponse struct {
// Content is the content of the response.
Content *genai.Content
// GroundingMetadata is the grounding metadata of the response.
GroundingMetadata *genai.GroundingMetadata
// Partial indicates whether the text content is part of an unfinished text stream.
// Only used for streaming mode and when the content is plain text.
Partial bool
// TurnComplete indicates whether the response from the model is complete.
// Only used for streaming mode.
TurnComplete bool
// ErrorCode is the error code if the response is an error. Code varies by model.
ErrorCode string
// ErrorMessage is the error message if the response is an error.
ErrorMessage string
// Interrupted indicates that LLM was interrupted when generating the content.
// Usually it's due to user interruption during a bidirectional streaming.
Interrupted bool
// CustomMetadata is the custom metadata of the LLMResponse.
// An optional key-value pair to label an LLMResponse.
// The entire map must be JSON serializable.
CustomMetadata map[string]any
FinishReason genai.FinishReason
UsageMetadata *genai.GenerateContentResponseUsageMetadata
}
LLMResponse represents a LLM response class that provides the first candidate response from the model if available. Otherwise, returns error code and message.
func CreateFromGenerateContentResponse ¶
func CreateFromGenerateContentResponse(generateContentResponse *genai.GenerateContentResponse) *LLMResponse
CreateFromGenerateContentResponse creates an LLMResponse from a GenerateContentResponse. This is kept for backward compatibility.
Parameters:
- generateContentResponse: The GenerateContentResponse to create the LLMResponse from.
Returns:
- The LLMResponse.
func CreateLLMResponse ¶
func CreateLLMResponse(resp *genai.GenerateContentResponse) *LLMResponse
CreateLLMResponse creates an LLMResponse from a *genai.GenerateContentResponse.
func (*LLMResponse) GetText ¶
func (r *LLMResponse) GetText() string
GetText returns the text content of the response if available. Returns empty string if no content is available.
func (*LLMResponse) IsError ¶
func (r *LLMResponse) IsError() bool
IsError returns true if the response contains an error.
func (*LLMResponse) WithCustomMetadata ¶
func (r *LLMResponse) WithCustomMetadata(metadata map[string]any) *LLMResponse
WithCustomMetadata sets the custom metadata and returns the response.
func (*LLMResponse) WithInterrupted ¶
func (r *LLMResponse) WithInterrupted(interrupted bool) *LLMResponse
WithInterrupted sets the interrupted flag and returns the response.
func (*LLMResponse) WithPartial ¶
func (r *LLMResponse) WithPartial(partial bool) *LLMResponse
WithPartial sets the partial flag and returns the response.
func (*LLMResponse) WithTurnComplete ¶
func (r *LLMResponse) WithTurnComplete(complete bool) *LLMResponse
WithTurnComplete sets the turn complete flag and returns the response.
type LLMResponseProcessor ¶
type LLMResponseProcessor interface {
// Run processes the LLM response.
Run(ctx context.Context, ictx *InvocationContext, response *LLMResponse) iter.Seq2[*Event, error]
}
LLMResponseProcessor represents a base class for LLM response processor.
type ListEventsResponse ¶
ListEventsResponse is the response of listing events in a session.
type ListSessionsResponse ¶
type ListSessionsResponse struct {
Sessions []Session
}
ListSessionsResponse is the response of listing sessions.
The events and states are not set within each Session object.
type LiveRequest ¶
type LiveRequest struct {
// Send the content to the model in turn-by-turn mode if any.
Content *genai.Content `json:"content,omitempty"`
// Send the blob to the model in realtime mode if any.
Blob *genai.Blob `json:"blob,omitempty"`
// Close the queue.
Close bool `json:"close"`
}
LiveRequest represents a request send to live agents.
type LiveRequestQueue ¶
type LiveRequestQueue struct {
// contains filtered or unexported fields
}
LiveRequestQueue is used to send LiveRequest in a bidirectional streaming way.
func NewLiveRequestQueue ¶
func NewLiveRequestQueue() *LiveRequestQueue
NewLiveRequestQueue creates a new LiveRequestQueue with a buffered channel.
func (*LiveRequestQueue) Close ¶
func (q *LiveRequestQueue) Close()
Close signals that the queue should be closed by sending a LiveRequest with Close set to true.
func (*LiveRequestQueue) Get ¶
func (q *LiveRequestQueue) Get(ctx context.Context) (*LiveRequest, error)
Get gets a LiveRequest from the queue.
It accepts a context for cancellation, which is a Go idiomatic pattern different from the Python async/await approach.
func (*LiveRequestQueue) Send ¶
func (q *LiveRequestQueue) Send(req *LiveRequest)
Send sends a LiveRequest to the queue.
func (*LiveRequestQueue) SendContent ¶
func (q *LiveRequestQueue) SendContent(content *genai.Content)
SendContent sends content to the queue.
func (*LiveRequestQueue) SendRealtime ¶
func (q *LiveRequestQueue) SendRealtime(blob *genai.Blob)
SendRealtime sends a blob to the queue in realtime mode.
type MemoryEntry ¶
type MemoryEntry struct {
// The main content of the memory.
Content *genai.Content
// The author of the memory.
Author string
// The timestamp when the original content of this memory happened.
//
// This string will be forwarded to LLM. Preferred format is ISO 8601 format.
Timestamp time.Time
}
MemoryEntry represents an one memory entry.
type MemoryService ¶
type MemoryService interface {
// AddSessionToMemory adds the contents of a session to memory.
AddSessionToMemory(ctx context.Context, session Session) error
// SearchMemory searches for sessions that match the query.
SearchMemory(ctx context.Context, appName, userID, query string) (*SearchMemoryResponse, error)
// Close closes the underlying memory client and releases resources.
Close() error
}
MemoryService defines the interface for memory services.
A session may be added multiple times during its lifetime.
type Model ¶
type Model interface {
// Name returns the name of the LLM model.
//
// e.g. gemini-1.5-flash or gemini-1.5-flash-001.
Name() string
// SupportedModels returns a list of supported models for the [LLMRegistry].
SupportedModels() []string
// Connect creates a live connection to the LLM.
Connect(ctx context.Context, request *LLMRequest) (ModelConnection, error)
// GenerateContent Generates one content from the given contents and tools.
GenerateContent(ctx context.Context, request *LLMRequest) (*LLMResponse, error)
// StreamGenerateContent generates one content from the given contents and tools with streaming call.
StreamGenerateContent(ctx context.Context, request *LLMRequest) iter.Seq2[*LLMResponse, error]
}
Model represents a generative AI model.
type ModelConnection ¶
type ModelConnection interface {
// SendHistory sends the conversation history to the model.
// The model will respond if the last content is from user, otherwise it will
// wait for new user input before responding.
SendHistory(ctx context.Context, history []*genai.Content) error
// SendContent sends a user content to the model.
// The model will respond immediately upon receiving the content.
SendContent(ctx context.Context, content *genai.Content) error
// SendRealtime sends a chunk of audio or a frame of video to the model in realtime.
// The model may not respond immediately upon receiving the blob.
SendRealtime(ctx context.Context, blob []byte, mimeType string) error
// Receive returns a channel that yields model responses.
// It should be called after SendHistory, SendContent, or SendRealtime.
Receive(ctx context.Context) iter.Seq2[*LLMResponse, error]
// Close terminates the connection to the model.
// The connection object should not be used after this call.
Close() error
}
ModelConnection defines the interface for a live model connection.
type NotImplementedError ¶
type NotImplementedError string
NotImplementedError is the error type for unimplemented behaiviour.
func (NotImplementedError) Error ¶
func (e NotImplementedError) Error() string
Error returns a string representation of the NotImplementedError.
type OAuth2Auth ¶
type OAuth2Auth struct {
ClientID string `json:"client_id,omitzero"`
ClientSecret string `json:"client_secret,omitzero"`
// tool or adk can generate the auth_uri with the state info thus client
// can verify the state
AuthURI string `json:"auth_uri,omitzero"`
State string `json:"state,omitzero"`
// tool or adk can decide the redirect_uri if they don't want client to decide
RedirectURI string `json:"redirect_uri,omitzero"`
AuthResponseURI string `json:"auth_response_uri,omitzero"`
AuthCode string `json:"auth_code,omitzero"`
AccessToken string `json:"access_token,omitzero"`
RefreshToken string `json:"refresh_token,omitzero"`
ExpiresAt time.Time `json:"expires_at,omitzero"`
ExpiresIn int64 `json:"expires_in,omitzero"`
}
OAuth2Auth represents credential value and its metadata for a OAuth2 credential.
type OAuth2CredentialRefresher ¶
type OAuth2CredentialRefresher struct{}
OAuth2CredentialRefresher Refreshes OAuth2 credentials including Google OAuth2 JSON credentials.
func (*OAuth2CredentialRefresher) IsRefreshNeeded ¶
func (r *OAuth2CredentialRefresher) IsRefreshNeeded(ctx context.Context, authCredential *AuthCredential, authScheme AuthScheme) bool
IsRefreshNeeded implements types.CredentialRefresher.
func (*OAuth2CredentialRefresher) Refresh ¶
func (r *OAuth2CredentialRefresher) Refresh(ctx context.Context, authCredential *AuthCredential, authScheme AuthScheme) (*AuthCredential, error)
Refresh implements types.CredentialRefresher.
type OAuth2SecurityScheme ¶
type OAuth2SecurityScheme struct {
Type AuthCredentialTypes `json:"type"`
Flows *OAuthFlows `json:"flows"`
}
OAuth2SecurityScheme represents an OAuth2 security scheme with various flows.
func (*OAuth2SecurityScheme) AuthType ¶
func (a *OAuth2SecurityScheme) AuthType() AuthCredentialTypes
AuthType returns a string representation of the OAuth2SecurityScheme type.
type OAuth2Session ¶
OAuth2Session represents a new OAuth 2 client requests session.
func CreateOAuth2Session ¶
func CreateOAuth2Session(ctx context.Context, authScheme AuthScheme, authCredential *AuthCredential) *OAuth2Session
CreateOAuth2Session create an OAuth2 session for token operations.
type OAuthFlow ¶
type OAuthFlow struct {
AuthorizationURL string `json:"authorizationUrl,omitzero"`
TokenURL string `json:"tokenUrl,omitzero"`
RefreshURL string `json:"refreshUrl,omitzero"`
Scopes map[string]string `json:"scopes,omitzero"`
}
OAuthFlow represents an OAuth2 flow configuration.
type OAuthFlows ¶
type OAuthFlows struct {
Implicit *OAuthFlow `json:"implicit,omitzero"`
Password *OAuthFlow `json:"password,omitzero"`
ClientCredentials *OAuthFlow `json:"clientCredentials,omitzero"`
AuthorizationCode *OAuthFlow `json:"authorizationCode,omitzero"`
}
OAuthFlows represents an OAuth2 flow configurations.
type OAuthGrantType ¶
type OAuthGrantType string
OAuthGrantType represents the OAuth2 flow or grant type.
const ( // ClientCredentialsGrant represents the client credentials grant type. // See RFC 6749 Section 4.4. ClientCredentialsGrant OAuthGrantType = "client_credentials" // AuthorizationCodeGrant represents the authorization code grant type. // See RFC 6749 Section 4.1. AuthorizationCodeGrant OAuthGrantType = "authorization_code" // ImplicitGrant represents the implicit grant type. // See RFC 6749 Section 4.2. ImplicitGrant OAuthGrantType = "implicit" // PasswordGrant represents the password grant type. // See RFC 6749 Section 4.3. PasswordGrant OAuthGrantType = "password" )
func FromOAuthFlows ¶
func FromOAuthFlows(flows *OAuthFlows) OAuthGrantType
FromOAuthFlows determines the grant type from OAuthFlows.
type OpenIDConnectWithConfig ¶
type OpenIDConnectWithConfig struct {
Type AuthCredentialTypes `json:"type"`
AuthorizationEndpoint string `json:"authorization_endpoint"`
TokenEndpoint string `json:"token_endpoint"`
UserinfoEndpoint string `json:"userinfo_endpoint,omitzero"`
RevocationEndpoint string `json:"revocation_endpoint,omitzero"`
TokenEndpointAuthMethodsSupported string `json:"token_endpoint_auth_methods_supported,omitzero"`
GrantTypesSupported []string `json:"grant_types_supported,omitzero"`
Scopes []string `json:"scopes,omitzero"`
}
OpenIDConnectWithConfig represents an OpenID Connect configuration with additional endpoints and methods.
func (*OpenIDConnectWithConfig) AuthType ¶
func (a *OpenIDConnectWithConfig) AuthType() AuthCredentialTypes
AuthType returns a string representation of the OpenIDConnectWithConfig type.
type OpenIdConnectSecurityScheme ¶
type OpenIdConnectSecurityScheme struct {
Type AuthCredentialTypes `json:"type"`
OpenIDConnectURL string `json:"openIdConnectUrl"`
}
OpenIdConnectSecurityScheme represents an OpenID Connect security scheme.
func (*OpenIdConnectSecurityScheme) AuthType ¶
func (a *OpenIdConnectSecurityScheme) AuthType() AuthCredentialTypes
AuthType returns a string representation of the OpenIdConnectSecurityScheme type.
type Option ¶
type Option interface {
// contains filtered or unexported methods
}
Option configures a Config.
func WithAfterAgentCallbacks ¶
func WithAfterAgentCallbacks(callbacks ...AgentCallback) Option
func WithBeforeAgentCallbacks ¶
func WithBeforeAgentCallbacks(callbacks ...AgentCallback) Option
func WithLogger ¶
WithLogger sets the logger for the Config.
func WithParentAgent ¶
WithParentAgent sets the parentAgent for the Config.
func WithSubAgents ¶
WithSubAgents adds sub-agents for the Config.
type Planner ¶
type Planner interface {
// BuildPlanningInstruction builds the system instruction to be appended to the LLM request for planning.
BuildPlanningInstruction(ctx context.Context, rctx *ReadOnlyContext, request *LLMRequest) string
// ProcessPlanningResponse Processes the LLM response for planning.
ProcessPlanningResponse(ctx context.Context, cctx *CallbackContext, responseParts []*genai.Part) []*genai.Part
}
Planner represents an abstract base class for all planners.
The planner allows the agent to generate plans for the queries to guide its action.
type ReadOnlyContext ¶
type ReadOnlyContext struct {
InvocationContext *InvocationContext
}
ReadOnlyContext provides read-only access to agent context.
func NewReadOnlyContext ¶
func NewReadOnlyContext(ictx *InvocationContext) *ReadOnlyContext
NewReadOnlyContext creates a new read-only context.
func (*ReadOnlyContext) AgentName ¶
func (rc *ReadOnlyContext) AgentName() string
AgentName returns the name of the agent that is currently running.
func (*ReadOnlyContext) InvocationContextID ¶
func (rc *ReadOnlyContext) InvocationContextID() string
InvocationContextID returns the current invocation id.
func (*ReadOnlyContext) State ¶
func (rc *ReadOnlyContext) State() map[string]any
State returns the state of the current session. READONLY field.
func (*ReadOnlyContext) UserContent ¶
func (rc *ReadOnlyContext) UserContent() *genai.Content
UserContent returns the user content that started this invocation. READONLY field.
type RunConfig ¶
type RunConfig struct {
// Speech configuration for the live agent.
SpeechConfig *genai.SpeechConfig
// The output modalities. If not set, it's default to AUDIO.
ResponseModalities []genai.Modality
// Whether or not to save the input blobs as artifacts.
SaveInputBlobsAsArtifacts bool
// Whether to support CFC (Compositional Function Calling). Only applicable for
// StreamingMode.SSE. If it's true. the LIVE API will be invoked. Since only LIVE
// API supports CFC
SupportCFC bool
// Streaming mode.
StreamingMode StreamingMode
// Output transcription for live agents with audio response.
OutputAudioTranscription *genai.AudioTranscriptionConfig
// Input transcription for live agents with audio input from user.
InputAudioTranscription *genai.AudioTranscriptionConfig
// A limit on the total number of llm calls for a given run.
MaxLLMCalls int
}
RunConfig represents a configs for runtime behavior of agents.
type SearchMemoryResponse ¶
type SearchMemoryResponse struct {
// Results are the memory items matching the search.
Memories []*MemoryEntry `json:"memories"`
}
SearchMemoryResponse represents the response from a memory search.
type SecurityScheme ¶
type SecurityScheme interface {
AuthScheme
// contains filtered or unexported methods
}
SecurityScheme represents a security scheme that implements the AuthScheme interface.
type ServiceAccount ¶
type ServiceAccount struct {
ServiceAccountCredential ServiceAccountCredential `json:"service_account_credential,omitzero"`
Scopes []string `json:"scopes"`
UseDefaultCredential bool `json:"use_default_credential,omitzero"`
}
ServiceAccount represents Google Service Account configuration.
type ServiceAccountCredential ¶
type ServiceAccountCredential struct {
ProjectID string `json:"project_id"`
PrivateKeyID string `json:"private_key_id"`
PrivateKey string `json:"private_key"`
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
AuthURI string `json:"auth_uri"`
TokenURI string `json:"token_uri"`
AuthProviderX509CertURL string `json:"auth_provider_x509_cert_url"`
ClientX509CertURL string `json:"client_x509_cert_url"`
UniverseDomain string `json:"universe_domain"`
}
ServiceAccountCredential represents Google Service Account configuration.
type Session ¶
type Session interface {
// ID returns the session ID.
ID() string
// AppName returns the application name.
AppName() string
// UserID returns the user ID.
UserID() string
// State is the state of the session.
State() map[string]any
// Events returns the events in the session.
Events() []*Event
// LastUpdateTime is the last update time of the session.
LastUpdateTime() time.Time
// AddEvent adds an event to this session.
AddEvent(events ...*Event)
// GetRecentEvents returns the most recent n events.
SetLastUpdateTime(time.Time)
}
Session represents a user session with events that can be stored in memory.
type SessionService ¶
type SessionService interface {
// CreateSession creates a new session with the given parameters.
CreateSession(ctx context.Context, appName, userID, sessionID string, state map[string]any) (Session, error)
// GetSession retrieves a specific session.
// If maxEvents is > 0, only return the last maxEvents events.
// If since is not nil, only return events after the given time.
GetSession(ctx context.Context, appName, userID, sessionID string, config *GetSessionConfig) (Session, error)
// ListSessions lists all sessions for a user/app.
ListSessions(ctx context.Context, appName, userID string) ([]Session, error)
// DeleteSession removes a specific session.
DeleteSession(ctx context.Context, appName, userID, sessionID string) error
// // AppendEvent adds an event to a session and updates session state.
AppendEvent(ctx context.Context, sess Session, event *Event) (*Event, error)
// ListEvents retrieves events within a session.
ListEvents(ctx context.Context, appName, userID, sessionID string, maxEvents int, since *time.Time) ([]Event, error)
}
SessionService is an interface for managing sessions and their events.
type State ¶
type State struct {
// contains filtered or unexported fields
}
State maintains the current value of a state dictionary and any pending deltas that haven't been committed yet.
func (*State) ApplyDelta ¶
func (s *State) ApplyDelta()
ApplyDelta applies all pending changes to the base state and clears the delta.
func (*State) ClearDelta ¶
func (s *State) ClearDelta()
ClearDelta clears any pending changes, usually called after committing changes to the persistent storage.
func (*State) Get ¶
Get returns the value for the given key, prioritizing delta values over the base values.
func (*State) GetWithDefault ¶
GetWithDefault returns the value for the given key, or the default value if the key doesn't exist.
func (*State) Set ¶
Set sets the value for the given key, updating both value and delta. TODO: Consider updating only delta, with value updated at commit time.
type StreamingMode ¶
type StreamingMode int
StreamingMode is the streaming mode.
const ( StreamingModeNone StreamingMode = iota StreamingModeSSE StreamingModeBidi )
func (StreamingMode) String ¶
func (mode StreamingMode) String() string
String returns a string representation of the StreamingMode.
type Tool ¶
type Tool interface {
// Name returns the name of the tool.
Name() string
// Description returns the description of the tool.
Description() string
// IsLongRunning whether the tool is a long running operation, which typically returns a
// resource id first and finishes the operation later.
IsLongRunning() bool
// GetDeclaration gets the OpenAPI specification of this tool in the form of a [*genai.FunctionDeclaration].
GetDeclaration() *genai.FunctionDeclaration
// Run runs the tool with the given arguments and context.
Run(ctx context.Context, args map[string]any, toolCtx *ToolContext) (any, error)
// ProcessLLMRequest processes the outgoing LLM request for this tool.
ProcessLLMRequest(ctx context.Context, toolCtx *ToolContext, request *LLMRequest) error
}
Tool defines the interface that all tools must implement.
type ToolCall ¶
type ToolCall struct {
// Name is the name of the tool.
Name string
// Input is the input provided to the tool.
Input map[string]any
// Output is the result from the tool execution.
Output map[string]any
// Error is set if the tool call failed.
Error error
}
ToolCall represents a call to a tool during agent execution.
type ToolContext ¶
type ToolContext struct {
*CallbackContext
// contains filtered or unexported fields
}
ToolContext represents a context of the tool.
This type provides the context for a tool invocation, including access to the invocation context, function call ID, event actions, and authentication response. It also provides methods for requesting credentials, retrieving authentication responses, listing artifacts, and searching memory.
func NewToolContext ¶
func NewToolContext(ictx *InvocationContext) *ToolContext
NewToolContext creates a new ToolContext with the given invocation context.
func (*ToolContext) Actions ¶
func (tc *ToolContext) Actions() *EventActions
Actions returns the event actions for the tool context.
func (*ToolContext) FunctionCallID ¶
func (tc *ToolContext) FunctionCallID() string
FunctionCallID returns the function call ID for the tool context.
func (*ToolContext) GetAuthResponse ¶
func (tc *ToolContext) GetAuthResponse(authConfig *AuthConfig) *AuthCredential
GetAuthResponse returns the authentication credential for the given authConfig.
func (*ToolContext) InvocationContext ¶
func (tc *ToolContext) InvocationContext() *InvocationContext
InvocationContext returns the invocation context for the tool context.
func (*ToolContext) ListArtifacts ¶
func (tc *ToolContext) ListArtifacts(ctx context.Context) ([]string, error)
ListArtifacts lists the filenames of the artifacts attached to the current session.
func (*ToolContext) RequestCredential ¶
func (tc *ToolContext) RequestCredential(ts *AuthConfig) error
func (*ToolContext) SearchMemory ¶
func (tc *ToolContext) SearchMemory(ctx context.Context, query string) (*SearchMemoryResponse, error)
SearchMemory searches the memory of the current user.
func (*ToolContext) WithEventActions ¶
func (tc *ToolContext) WithEventActions(eventActions *EventActions) *ToolContext
WithEventActions sets the *EventActions for the *ToolContext.
func (*ToolContext) WithFunctionCallID ¶
func (tc *ToolContext) WithFunctionCallID(funcCallID string) *ToolContext
WithFunctionCallID sets the function call ID for the *ToolContext.
type Toolset ¶
type Toolset interface {
// GetTools returns the all tools in the toolset based on the provided context.
GetTools(rctx *ReadOnlyContext) []Tool
// Close performs cleanup and releases resources held by the toolset.
//
// NOTE: This method is invoked, for example, at the end of an agent server's
// lifecycle or when the toolset is no longer needed. Implementations
// should ensure that any open connections, files, or other managed
// resources are properly released to prevent leaks.
Close()
}
Toolset represents a base for toolset.
A toolset is a collection of tools that can be used by an agent.
type TranscriptionEntry ¶
type TranscriptionEntry struct {
// The role that created this data, typically "user" or "model".
Role string
// The data that can be used for transcription.
Data any
}
TranscriptionEntry represents a store the data that can be used for transcription.
func NewTranscriptionEntry ¶
NewTranscriptionEntry creates a new TranscriptionEntry.
Source Files
¶
- agent.go
- agent_active_streaming_tool.go
- agent_base.go
- agent_callback_context.go
- agent_config.go
- agent_invocation_context.go
- agent_live_request_queue.go
- agent_readonly_context.go
- agent_run_config.go
- agent_transcription_entry.go
- artifact_service.go
- auth_credential.go
- auth_credential_manager.go
- auth_credential_refresher.go
- auth_credential_service.go
- auth_exchanger.go
- auth_exchanger_credential_exchanger_registry.go
- auth_handler.go
- auth_oauth2_credential_util.go
- auth_refresher_credential_refresher_registry.go
- auth_refresher_oauth2_credential_refresher.go
- auth_schemas.go
- auth_tool.go
- codeexecutor.go
- doc.go
- errors.go
- event.go
- event_actions.go
- flow.go
- flow_llm_processor.go
- memory.go
- model.go
- model_llm_request.go
- model_llm_response.go
- planner.go
- ptr.go
- session.go
- session_service.go
- session_state.go
- tool.go
- tool_authenticated.go
- tool_call.go
- tool_context.go
- tool_toolset.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package aiconv provides comprehensive bidirectional type conversion between unified genai types and provider-specific AI platform types.
|
Package aiconv provides comprehensive bidirectional type conversion between unified genai types and provider-specific AI platform types. |