adk

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 33 Imported by: 0

Documentation

Index

Constants

View Source
const DefaultTokenBudget = 32000

DefaultTokenBudget is the token budget used when no explicit budget is provided.

Variables

This section is empty.

Functions

func AdaptTool

func AdaptTool(t *agent.Tool) (tool.Tool, error)

AdaptTool converts an internal agent.Tool to an ADK tool.Tool.

func AdaptToolForAgent added in v0.4.0

func AdaptToolForAgent(t *agent.Tool, agentName string) (tool.Tool, error)

AdaptToolForAgent converts an internal agent.Tool to an ADK tool.Tool and injects the given agentName into the context for every handler invocation. This allows downstream hooks and middleware to identify which agent owns the tool call.

func AdaptToolForAgentWithTimeout added in v0.4.0

func AdaptToolForAgentWithTimeout(t *agent.Tool, agentName string, timeout time.Duration) (tool.Tool, error)

AdaptToolForAgentWithTimeout combines agent name injection with a per-call timeout.

func AdaptToolWithTimeout

func AdaptToolWithTimeout(t *agent.Tool, timeout time.Duration) (tool.Tool, error)

AdaptToolWithTimeout converts an internal agent.Tool to an ADK tool.Tool with an enforced per-call timeout. If timeout <= 0, behaves like AdaptTool.

func AgentNameFromContext added in v0.4.0

func AgentNameFromContext(ctx context.Context) string

AgentNameFromContext extracts the agent name stored in ctx. Returns an empty string when no agent name is present.

func ModelTokenBudget

func ModelTokenBudget(modelName string) int

ModelTokenBudget returns an appropriate history token budget for the given model. It uses approximately 50-60% of each model family's context window, leaving room for system prompts, tool definitions, and generated output. Returns DefaultTokenBudget for unknown models.

func WithAgentName added in v0.4.0

func WithAgentName(ctx context.Context, name string) context.Context

WithAgentName returns a context carrying the given agent name. This delegates to ctxkeys.WithAgentName so that any package importing ctxkeys can read the value without depending on the adk package.

func WithChildSession added in v0.4.0

func WithChildSession(ctx context.Context, info ChildSessionInfo) context.Context

WithChildSession stores child session info in context.

Types

type Agent

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

Agent wraps the ADK runner for integration with Lango.

func NewAgent

func NewAgent(ctx context.Context, tools []tool.Tool, mod model.LLM, systemPrompt string, store internal.Store, opts ...AgentOption) (*Agent, error)

NewAgent creates a new Agent instance.

func NewAgentFromADK

func NewAgentFromADK(adkAgent adk_agent.Agent, store internal.Store, opts ...AgentOption) (*Agent, error)

NewAgentFromADK creates a Lango Agent wrapping a pre-built ADK agent. Used for multi-agent orchestration where the agent tree is built externally.

func (*Agent) ADKAgent

func (a *Agent) ADKAgent() adk_agent.Agent

ADKAgent returns the underlying ADK agent, or nil if not available.

func (*Agent) Run

func (a *Agent) Run(ctx context.Context, sessionID string, input string) iter.Seq2[*session.Event, error]

Run executes the agent for a given session and returns an event iterator. It enforces a maximum turn limit to prevent unbounded tool-calling loops.

func (*Agent) RunAndCollect

func (a *Agent) RunAndCollect(ctx context.Context, sessionID, input string, opts ...RunOption) (string, error)

RunAndCollect executes the agent and returns the full text response. If the agent encounters a "failed to find agent" error (hallucinated agent name), it sends a correction message and retries once.

func (*Agent) RunStreaming

func (a *Agent) RunStreaming(ctx context.Context, sessionID, input string, onChunk ChunkCallback, opts ...RunOption) (string, error)

RunStreaming executes the agent and streams partial text chunks via the callback. It returns the full accumulated response text for backward compatibility.

func (*Agent) WithErrorFixProvider

func (a *Agent) WithErrorFixProvider(p ErrorFixProvider) *Agent

WithErrorFixProvider sets an optional provider for learning-based error correction. When set, the agent will attempt to apply known fixes on errors before giving up.

func (*Agent) WithMaxTurns

func (a *Agent) WithMaxTurns(n int) *Agent

WithMaxTurns sets the maximum number of tool-calling turns per run. Zero or negative values use the default (25).

type AgentError added in v0.5.0

type AgentError struct {
	Code    ErrorCode
	Message string        // internal message
	Cause   error         // underlying error
	Partial string        // accumulated text before failure
	Elapsed time.Duration // time spent before failure
}

AgentError is a structured error type that preserves partial results accumulated before the failure, along with classification metadata.

func (*AgentError) Error added in v0.5.0

func (e *AgentError) Error() string

func (*AgentError) Unwrap added in v0.5.0

func (e *AgentError) Unwrap() error

func (*AgentError) UserMessage added in v0.5.0

func (e *AgentError) UserMessage() string

UserMessage returns a user-facing formatted message with error code and hint.

type AgentOption

type AgentOption func(*agentOptions)

AgentOption configures optional Agent behavior at construction time.

func WithAgentErrorFixProvider

func WithAgentErrorFixProvider(p ErrorFixProvider) AgentOption

WithAgentErrorFixProvider sets a learning-based error correction provider.

func WithAgentMaxTurns

func WithAgentMaxTurns(n int) AgentOption

WithAgentMaxTurns sets the maximum number of tool-calling turns per run.

func WithAgentTokenBudget

func WithAgentTokenBudget(budget int) AgentOption

WithAgentTokenBudget sets the session history token budget. Use ModelTokenBudget(modelName) to derive an appropriate value.

type ChildSessionInfo added in v0.4.0

type ChildSessionInfo struct {
	ChildKey  string
	ParentKey string
	AgentName string
}

ChildSessionInfo holds child session metadata in context.

func ChildSessionFromContext added in v0.4.0

func ChildSessionFromContext(ctx context.Context) (ChildSessionInfo, bool)

ChildSessionFromContext retrieves child session info from context.

type ChildSessionServiceAdapter added in v0.4.0

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

ChildSessionServiceAdapter wraps a ChildSessionStore to provide fork/merge/discard operations integrated with ADK's session management.

func NewChildSessionServiceAdapter added in v0.4.0

func NewChildSessionServiceAdapter(childStore session.ChildSessionStore, summarizer Summarizer) *ChildSessionServiceAdapter

NewChildSessionServiceAdapter creates a new adapter.

func (*ChildSessionServiceAdapter) Discard added in v0.4.0

func (a *ChildSessionServiceAdapter) Discard(childKey string) error

Discard removes a child session without merging.

func (*ChildSessionServiceAdapter) Fork added in v0.4.0

func (a *ChildSessionServiceAdapter) Fork(parentKey, agentName string, cfg session.ChildSessionConfig) (*session.ChildSession, error)

Fork creates a child session for a sub-agent.

func (*ChildSessionServiceAdapter) MergeWithSummary added in v0.4.0

func (a *ChildSessionServiceAdapter) MergeWithSummary(childKey string) error

MergeWithSummary merges a child session using the configured summarizer.

type ChunkCallback

type ChunkCallback func(chunk string)

ChunkCallback is called for each streaming text chunk during agent execution.

type ContextAwareModelAdapter

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

ContextAwareModelAdapter wraps a ModelAdapter with context retrieval. Before each LLM call, it retrieves relevant knowledge and injects it into the system instruction.

func NewContextAwareModelAdapter

func NewContextAwareModelAdapter(
	inner *ModelAdapter,
	retriever *knowledge.ContextRetriever,
	builder *prompt.Builder,
	logger *zap.SugaredLogger,
) *ContextAwareModelAdapter

NewContextAwareModelAdapter creates a context-aware model adapter. The builder is used to produce the base system prompt; dynamic context (knowledge, memory, RAG) is still appended at call time.

func (*ContextAwareModelAdapter) GenerateContent

func (m *ContextAwareModelAdapter) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error]

GenerateContent retrieves context and injects an augmented system prompt before delegating to the inner adapter.

func (*ContextAwareModelAdapter) Name

func (m *ContextAwareModelAdapter) Name() string

Name delegates to the inner adapter.

func (*ContextAwareModelAdapter) WithGraphRAG

WithGraphRAG adds graph-enhanced RAG support. When set, graph expansion is performed on vector search results to discover structurally connected context.

func (*ContextAwareModelAdapter) WithMemory

WithMemory adds observational memory support to the adapter. The session key is resolved at call time from the request context via session.SessionKeyFromContext.

func (*ContextAwareModelAdapter) WithMemoryLimits

func (m *ContextAwareModelAdapter) WithMemoryLimits(maxReflections, maxObservations int) *ContextAwareModelAdapter

WithMemoryLimits sets the maximum number of reflections and observations to include in the LLM context. Zero means unlimited (existing behavior).

func (*ContextAwareModelAdapter) WithMemoryTokenBudget

func (m *ContextAwareModelAdapter) WithMemoryTokenBudget(budget int) *ContextAwareModelAdapter

WithMemoryTokenBudget sets the maximum token budget for the memory section injected into the system prompt. Reflections are prioritized first (higher information density), then observations fill the remaining budget. Zero means use default (4000 tokens).

func (*ContextAwareModelAdapter) WithRAG

WithRAG adds RAG (retrieval-augmented generation) support.

func (*ContextAwareModelAdapter) WithRuntimeAdapter

WithRuntimeAdapter adds runtime context support to the adapter.

type ErrorCode added in v0.5.0

type ErrorCode string

ErrorCode identifies the category of an agent error.

const (
	ErrTimeout     ErrorCode = "E001"
	ErrModelError  ErrorCode = "E002"
	ErrToolError   ErrorCode = "E003"
	ErrTurnLimit   ErrorCode = "E004"
	ErrInternal    ErrorCode = "E005"
	ErrIdleTimeout ErrorCode = "E006"
)

type ErrorFixProvider

type ErrorFixProvider interface {
	GetFixForError(ctx context.Context, toolName string, err error) (string, bool)
}

ErrorFixProvider returns a known fix for a tool error if one exists. Implemented by learning.Engine.

type EventsAdapter

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

EventsAdapter adapts internal history to adk events. Uses token-budget truncation: includes messages from most recent until the budget is exhausted. Truncated history and converted events are lazily cached for O(1) repeated access.

func (*EventsAdapter) All

func (e *EventsAdapter) All() iter.Seq[*session.Event]

func (*EventsAdapter) At

func (e *EventsAdapter) At(i int) *session.Event

At returns the i-th event. The full event list is built once on first call and cached, making subsequent At calls O(1) instead of O(n).

func (*EventsAdapter) Len

func (e *EventsAdapter) Len() int

type MemoryProvider

type MemoryProvider interface {
	ListObservations(ctx context.Context, sessionKey string) ([]memory.Observation, error)
	ListReflections(ctx context.Context, sessionKey string) ([]memory.Reflection, error)
	ListRecentReflections(ctx context.Context, sessionKey string, limit int) ([]memory.Reflection, error)
	ListRecentObservations(ctx context.Context, sessionKey string, limit int) ([]memory.Observation, error)
}

MemoryProvider retrieves observations and reflections for a session.

type ModelAdapter

type ModelAdapter struct {
	OnTokenUsage TokenUsageCallback
	// contains filtered or unexported fields
}

func NewModelAdapter

func NewModelAdapter(p provider.Provider, model string) *ModelAdapter

func (*ModelAdapter) GenerateContent

func (m *ModelAdapter) GenerateContent(ctx context.Context, req *model.LLMRequest, stream bool) iter.Seq2[*model.LLMResponse, error]

func (*ModelAdapter) Name

func (m *ModelAdapter) Name() string

type PIIRedactingModelAdapter

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

PIIRedactingModelAdapter wraps an LLM and redacts PII from user messages before forwarding them to the underlying model. It also scans tool results and model responses for known secret values.

func NewPIIRedactingModelAdapter

func NewPIIRedactingModelAdapter(
	inner model.LLM,
	redactor *agent.PIIRedactor,
	scanner *agent.SecretScanner,
) *PIIRedactingModelAdapter

NewPIIRedactingModelAdapter creates a PII-redacting model adapter. If scanner is nil, output scanning is disabled.

func (*PIIRedactingModelAdapter) GenerateContent

func (m *PIIRedactingModelAdapter) GenerateContent(
	ctx context.Context,
	req *model.LLMRequest,
	stream bool,
) iter.Seq2[*model.LLMResponse, error]

GenerateContent redacts PII from user messages, scans tool results for secrets, and wraps the response iterator to scan model output.

func (*PIIRedactingModelAdapter) Name

func (m *PIIRedactingModelAdapter) Name() string

Name delegates to the inner adapter.

type RunOption added in v0.5.0

type RunOption func(*runOptions)

RunOption configures optional behavior for a single agent run.

func WithOnActivity added in v0.5.0

func WithOnActivity(fn func()) RunOption

WithOnActivity sets a callback that is invoked whenever the agent produces activity (text chunks, function calls). Useful for extending deadlines.

type RuntimeContextAdapter

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

RuntimeContextAdapter provides runtime session/system state.

func NewRuntimeContextAdapter

func NewRuntimeContextAdapter(toolCount int, encryption, knowledgeEnabled, memoryEnabled bool) *RuntimeContextAdapter

NewRuntimeContextAdapter creates a RuntimeContextAdapter with static system info.

func (*RuntimeContextAdapter) GetRuntimeContext

func (a *RuntimeContextAdapter) GetRuntimeContext() knowledge.RuntimeContext

GetRuntimeContext returns a snapshot of the current runtime context.

func (*RuntimeContextAdapter) SetSession

func (a *RuntimeContextAdapter) SetSession(sessionKey string)

SetSession updates the session key and derives the channel type.

type SessionAdapter

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

SessionAdapter adapts internal.Session to adk.Session

func NewSessionAdapter

func NewSessionAdapter(s *internal.Session, store internal.Store, rootAgentName string) *SessionAdapter

func (*SessionAdapter) AppName

func (s *SessionAdapter) AppName() string

func (*SessionAdapter) Events

func (s *SessionAdapter) Events() session.Events

func (*SessionAdapter) EventsWithTokenBudget

func (s *SessionAdapter) EventsWithTokenBudget(budget int) session.Events

EventsWithTokenBudget returns an EventsAdapter that uses token-budget truncation.

func (*SessionAdapter) ID

func (s *SessionAdapter) ID() string

func (*SessionAdapter) LastUpdateTime

func (s *SessionAdapter) LastUpdateTime() time.Time

func (*SessionAdapter) State

func (s *SessionAdapter) State() session.State

func (*SessionAdapter) UserID

func (s *SessionAdapter) UserID() string

type SessionServiceAdapter

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

func NewSessionServiceAdapter

func NewSessionServiceAdapter(store internal.Store, rootAgentName string) *SessionServiceAdapter

func (*SessionServiceAdapter) AppendEvent

func (s *SessionServiceAdapter) AppendEvent(ctx context.Context, sess session.Session, evt *session.Event) error

func (*SessionServiceAdapter) Create

func (*SessionServiceAdapter) Delete

func (*SessionServiceAdapter) Get

func (*SessionServiceAdapter) List

func (*SessionServiceAdapter) WithTokenBudget

func (s *SessionServiceAdapter) WithTokenBudget(budget int) *SessionServiceAdapter

WithTokenBudget sets the token budget for history truncation. Use ModelTokenBudget(modelName) to derive an appropriate budget from the model name.

type StateAdapter

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

StateAdapter adapts internal.Session.Metadata to adk.State

func (*StateAdapter) All

func (s *StateAdapter) All() iter.Seq2[string, any]

func (*StateAdapter) Get

func (s *StateAdapter) Get(key string) (any, error)

func (*StateAdapter) Set

func (s *StateAdapter) Set(key string, val any) error

type StructuredSummarizer added in v0.4.0

type StructuredSummarizer struct{}

StructuredSummarizer extracts the last assistant response as the summary. This is the default zero-cost summarizer that avoids LLM calls.

func (*StructuredSummarizer) Summarize added in v0.4.0

func (s *StructuredSummarizer) Summarize(messages []session.Message) (string, error)

Summarize returns the last assistant message content as the summary. If no assistant message is found, returns an empty string.

type Summarizer added in v0.4.0

type Summarizer interface {
	Summarize(messages []session.Message) (string, error)
}

Summarizer produces a summary string from a child session's messages.

type TokenUsageCallback added in v0.5.0

type TokenUsageCallback func(providerID, model string, input, output, total, cache int64)

TokenUsageCallback is called when a provider returns token usage data.

type ToolRegistryAdapter

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

ToolRegistryAdapter adapts []*agent.Tool to knowledge.ToolRegistryProvider.

func NewToolRegistryAdapter

func NewToolRegistryAdapter(tools []*agent.Tool) *ToolRegistryAdapter

NewToolRegistryAdapter creates a ToolRegistryAdapter from agent tools. The input slice is copied to prevent caller mutation.

func (*ToolRegistryAdapter) ListTools

func (a *ToolRegistryAdapter) ListTools() []knowledge.ToolDescriptor

ListTools returns all available tools.

func (*ToolRegistryAdapter) SearchTools

func (a *ToolRegistryAdapter) SearchTools(query string, limit int) []knowledge.ToolDescriptor

SearchTools returns tools whose name or description contains the query (case-insensitive).

Jump to

Keyboard shortcuts

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