Documentation
¶
Overview ¶
Package memory provides vector-backed chat history memory for agents.
Index ¶
- type Config
- type HistoryProvider
- func (p *HistoryProvider) Close() error
- func (p *HistoryProvider) Invoked(ctx context.Context, invoked agent.InvokedContext) error
- func (p *HistoryProvider) Invoking(ctx context.Context, invoking agent.InvokingContext) ([]*message.Message, []agent.Option, error)
- func (p *HistoryProvider) StateKeys() []string
- type Scope
- type SearchBehavior
- type State
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// SearchTime defaults to [BeforeInvoke].
SearchTime SearchBehavior
// FunctionToolName names the on-demand search tool. Nil defaults to "Search".
FunctionToolName *string
// FunctionToolDescription describes the on-demand search tool. Nil uses a
// default description about searching related previous chat history.
FunctionToolDescription *string
// ContextPrompt prefixes retrieved messages. Nil uses a default memory prompt.
// An explicit empty string suppresses the prompt text.
ContextPrompt *string
// MaxResults limits the number of search results. Nil defaults to 3.
// An explicit value must be positive.
MaxResults *int
// StateKey identifies provider state in the session. Nil defaults to
// "ChatHistoryMemoryProvider". Explicit empty or whitespace-only keys are
// invalid. Use distinct keys for providers that need independent scopes.
StateKey *string
// SearchInputMessageFilter filters automatic search input.
// Nil defaults to [messagefilter.ExternalOnly].
SearchInputMessageFilter messagefilter.Filter
// StorageInputRequestMessageFilter filters request messages before storage.
// Nil defaults to [messagefilter.ExternalOnly].
StorageInputRequestMessageFilter messagefilter.Filter
// StorageInputResponseMessageFilter filters response messages before storage.
// Nil passes all response messages through.
StorageInputResponseMessageFilter messagefilter.Filter
// Logger receives provider diagnostics. When nil, logging is disabled.
Logger *slog.Logger
// LogSensitiveData includes user IDs, queries, and retrieved text in logs.
// The default is false. When true, Redactor is ignored.
LogSensitiveData bool
// Redactor transforms sensitive log data. When nil and LogSensitiveData is
// false, nonempty sensitive values are replaced with "<redacted>".
Redactor func(string) string
}
Config configures the provider created by NewHistoryProvider.
type HistoryProvider ¶
type HistoryProvider struct {
// contains filtered or unexported fields
}
HistoryProvider stores chat messages in a vector collection and retrieves related messages as context. Create it with NewHistoryProvider. Do not copy it after use.
func NewHistoryProvider ¶
func NewHistoryProvider(store *vectordata.Store, collectionName string, vectorDimensions int, stateInitializer func(*agent.Session) *State, config Config) (*HistoryProvider, error)
NewHistoryProvider creates a chat history memory provider.
The store must support dynamic map records, UUID keys, and embedding generation from strings. The provider obtains a collection handle at construction and creates the collection lazily on the first search or successful run. Failed creation is retried. The store is borrowed.
stateInitializer supplies storage and search scopes when a session has no readable state. It must return a non-nil state. Without a session, it is called with nil for each lifecycle hook and no state is retained. On-demand tools capture the current invocation's search scope, not a later run's scope.
Attach the provider using agent.Config.ContextProviders. Automatic searches join nonblank request texts with newlines and append nonblank results as one source-attributed user message. On-demand searches use only the tool's userQuestion argument. Use automatic tool invocation middleware when the underlying provider does not execute tools.
Successful runs store filtered request messages followed by response messages, including messages without text. Storage and automatic-search failures are logged when Logger is configured and otherwise ignored, except cancellation errors while the caller's context is canceled. On-demand search, message-filter, and session-state errors are returned.
Stored messages may contain sensitive data. Configure storage access controls and appropriate scopes; an empty scope searches across all stored conversations. Retrieved content and model-generated queries are untrusted.
It panics if store or stateInitializer is nil, collectionName or StateKey is blank, or vectorDimensions or an explicit MaxResults is not positive. Collection configuration errors are returned.
func (*HistoryProvider) Close ¶
func (p *HistoryProvider) Close() error
Close is an optimization that releases the collection early if it implements io.Closer. A successful call cancels the runtime.AddCleanup fallback, which attempts to close the collection after the provider becomes unreachable. Runtime cleanup is asynchronous and is not guaranteed to run before program exit.
Close never closes the borrowed store. Repeated calls follow the collection's Close behavior. Do not overlap Close with runs or tool calls.
func (*HistoryProvider) Invoked ¶
func (p *HistoryProvider) Invoked(ctx context.Context, invoked agent.InvokedContext) error
Invoked stores eligible request and response messages after successful runs.
func (*HistoryProvider) Invoking ¶
func (p *HistoryProvider) Invoking(ctx context.Context, invoking agent.InvokingContext) ([]*message.Message, []agent.Option, error)
Invoking adds retrieved memories or a search tool scoped to this invocation.
func (*HistoryProvider) StateKeys ¶
func (p *HistoryProvider) StateKeys() []string
StateKeys returns the session key used by this provider. The returned slice belongs to the caller.
type Scope ¶
type Scope struct {
ApplicationID *string `json:"applicationId,omitempty"`
AgentID *string `json:"agentId,omitempty"`
UserID *string `json:"userId,omitempty"`
SessionID *string `json:"sessionId,omitempty"`
}
Scope selects which application, agent, user, and session a memory belongs to. A nil ID leaves that dimension unrestricted when searching. An explicit empty string matches only an empty ID.
type SearchBehavior ¶
type SearchBehavior int
SearchBehavior controls when chat history is searched.
const ( // BeforeInvoke searches before each agent run and adds results as a user message. BeforeInvoke SearchBehavior = iota // OnDemandFunctionCalling exposes a search tool for the model to call when needed. OnDemandFunctionCalling )
type State ¶
type State struct {
StorageScope Scope `json:"storageScope"`
// SearchScope defaults to StorageScope when nil.
SearchScope *Scope `json:"searchScope,omitempty"`
}
State holds a provider's per-session scopes. The provider stores a *State under the key returned by HistoryProvider.StateKeys. Synchronize edits with runs and tool calls, and use agent.Session.Set to persist changes to restored state.