session

package
v0.35.0 Latest Latest
Warning

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

Go to latest
Published: Dec 29, 2025 License: MIT Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// KeyPrefixApp 应用级状态前缀
	// 跨所有用户和会话共享
	KeyPrefixApp string = "app:"

	// KeyPrefixUser 用户级状态前缀
	// 同一用户的所有会话共享
	KeyPrefixUser string = "user:"

	// KeyPrefixTemp 临时状态前缀
	// 仅当前调用有效,调用结束后丢弃
	KeyPrefixTemp string = "temp:"

	// KeyPrefixSession 会话级状态前缀
	// 当前会话有效
	KeyPrefixSession string = "session:"
)

State 作用域前缀常量

Variables

View Source
var (
	ErrStateKeyNotExist = errors.New("state key does not exist")
	ErrSessionNotFound  = errors.New("session not found")
	ErrInvalidStateKey  = errors.New("invalid state key")
)

错误定义

Functions

func IsAppKey

func IsAppKey(key string) bool

IsAppKey 判断是否为应用级 key

func IsSessionKey

func IsSessionKey(key string) bool

IsSessionKey 判断是否为会话级 key

func IsTempKey

func IsTempKey(key string) bool

IsTempKey 判断是否为临时 key

func IsUserKey

func IsUserKey(key string) bool

IsUserKey 判断是否为用户级 key

Types

type CreateRequest

type CreateRequest struct {
	AppName  string
	UserID   string
	AgentID  string
	Metadata map[string]any
}

CreateRequest 创建会话请求

type Event

type Event struct {
	// 基础字段
	ID           string
	Timestamp    time.Time
	InvocationID string

	// Agent 相关
	AgentID string
	Branch  string // 多 Agent 分支隔离: "agent1.agent2.agent3"
	Author  string // 事件作者 (user/agent/system)

	// 内容
	Content types.Message

	// 推理/思考内容 (Kimi thinking, DeepSeek reasoner 等)
	Reasoning string

	// 动作
	Actions EventActions

	// 长时运行工具 ID 列表
	LongRunningToolIDs []string

	// 元数据
	Metadata map[string]any
}

Event 表示会话中的一个交互事件 扩展自 types.Event,增加更多元数据

func NewEvent

func NewEvent(invocationID string) *Event

NewEvent 创建新事件

func (*Event) IsFinalResponse

func (e *Event) IsFinalResponse() bool

IsFinalResponse 判断是否为最终响应

type EventActions

type EventActions struct {
	// StateDelta 状态增量更新
	StateDelta map[string]any

	// ArtifactDelta Artifact 版本变化 (filename -> version)
	ArtifactDelta map[string]int64

	// SkipSummarization 是否跳过总结
	SkipSummarization bool

	// TransferToAgent 转移到指定 Agent
	TransferToAgent string

	// Escalate 升级到上级 Agent
	Escalate bool

	// CustomActions 自定义动作
	CustomActions map[string]any
}

EventActions 表示事件附带的动作

type EventFilter

type EventFilter struct {
	AgentID   string
	Branch    string
	Author    string
	StartTime *time.Time
	EndTime   *time.Time
	Limit     int
	Offset    int
}

EventFilter 事件过滤器

type EventOptions

type EventOptions struct {
	InvocationID string
	Branch       string
	Limit        int
	Offset       int
}

EventOptions 事件查询选项(用于数据库实现)

type Events

type Events interface {
	// All 返回所有事件的迭代器,保持顺序
	All() iter.Seq[*Event]

	// Len 返回事件总数
	Len() int

	// At 返回指定索引的事件
	At(i int) *Event

	// Filter 根据条件过滤事件
	Filter(predicate func(*Event) bool) []Event

	// Last 返回最后一个事件
	Last() *Event
}

Events 定义事件列表接口

type GetRequest

type GetRequest struct {
	AppName   string
	UserID    string
	SessionID string
}

GetRequest 获取会话请求

type InMemoryService

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

InMemoryService 内存实现的 Session 服务 适用于开发和测试环境

func NewInMemoryService

func NewInMemoryService() *InMemoryService

NewInMemoryService 创建内存 Session 服务

func (*InMemoryService) AppendEvent

func (s *InMemoryService) AppendEvent(ctx context.Context, sessionID string, event *Event) error

AppendEvent 添加事件

func (*InMemoryService) Create

func (s *InMemoryService) Create(ctx context.Context, req *CreateRequest) (Session, error)

Create 创建新会话

func (*InMemoryService) Delete

func (s *InMemoryService) Delete(ctx context.Context, sessionID string) error

Delete 删除会话

func (*InMemoryService) Get

func (s *InMemoryService) Get(ctx context.Context, req *GetRequest) (Session, error)

Get 获取会话

func (*InMemoryService) GetEvents

func (s *InMemoryService) GetEvents(ctx context.Context, sessionID string, filter *EventFilter) ([]Event, error)

GetEvents 获取事件列表

func (*InMemoryService) List

func (s *InMemoryService) List(ctx context.Context, req *ListRequest) ([]*Session, error)

List 列出会话

func (*InMemoryService) Update

func (s *InMemoryService) Update(ctx context.Context, req *UpdateRequest) error

Update 更新会话

func (*InMemoryService) UpdateState

func (s *InMemoryService) UpdateState(ctx context.Context, sessionID string, delta map[string]any) error

UpdateState 更新状态

type ListOptions

type ListOptions struct {
	AppName string
	Limit   int
	Offset  int
}

ListOptions 列表选项(用于数据库实现)

type ListRequest

type ListRequest struct {
	AppName string
	UserID  string
	Limit   int
	Offset  int
}

ListRequest 列出会话请求

type ReadonlyState

type ReadonlyState interface {
	Get(key string) (any, error)
	All() iter.Seq2[string, any]
	Has(key string) bool
}

ReadonlyState 只读状态接口

type SearchOptions added in v0.13.0

type SearchOptions struct {
	Query         string    // 搜索关键词
	AgentID       string    // 限定 Agent ID
	StartTime     time.Time // 开始时间
	EndTime       time.Time // 结束时间
	Limit         int       // 返回结果数量限制
	Offset        int       // 偏移量
	MatchMode     string    // 匹配模式: "exact", "contains", "fuzzy"
	OnlyUser      bool      // 只搜索用户消息
	OnlyAssistant bool      // 只搜索助手消息
}

SearchOptions 搜索选项

type SearchResult added in v0.13.0

type SearchResult struct {
	AgentID      string        `json:"agent_id"`
	MessageIndex int           `json:"message_index"`
	Message      types.Message `json:"message"`
	Snippet      string        `json:"snippet"`
	Relevance    float64       `json:"relevance"`
	Timestamp    time.Time     `json:"timestamp"`
}

SearchResult 搜索结果

type Searcher added in v0.13.0

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

Searcher Session 搜索器

func NewSearcher added in v0.13.0

func NewSearcher(config SearcherConfig) *Searcher

NewSearcher 创建 Session 搜索器

func (*Searcher) FindSimilarMessages added in v0.13.0

func (s *Searcher) FindSimilarMessages(ctx context.Context, agentID string, referenceMessage types.Message, limit int) ([]SearchResult, error)

FindSimilarMessages 查找相似消息

func (*Searcher) SearchAcrossSessions added in v0.13.0

func (s *Searcher) SearchAcrossSessions(ctx context.Context, agentIDs []string, query string, limit int) ([]SearchResult, error)

SearchAcrossSessions 跨 Session 搜索

func (*Searcher) SearchHistory added in v0.13.0

func (s *Searcher) SearchHistory(ctx context.Context, opts SearchOptions) ([]SearchResult, error)

SearchHistory 搜索历史消息

type SearcherConfig added in v0.13.0

type SearcherConfig struct {
	Store store.Store
}

SearcherConfig Session 搜索器配置

type Service

type Service interface {
	// Create 创建新会话
	Create(ctx context.Context, req *CreateRequest) (Session, error)

	// Get 获取会话
	Get(ctx context.Context, req *GetRequest) (Session, error)

	// Update 更新会话
	Update(ctx context.Context, req *UpdateRequest) error

	// Delete 删除会话
	Delete(ctx context.Context, sessionID string) error

	// List 列出会话
	List(ctx context.Context, req *ListRequest) ([]*Session, error)

	// AppendEvent 添加事件
	AppendEvent(ctx context.Context, sessionID string, event *Event) error

	// GetEvents 获取事件列表
	GetEvents(ctx context.Context, sessionID string, filter *EventFilter) ([]Event, error)

	// UpdateState 更新状态
	UpdateState(ctx context.Context, sessionID string, delta map[string]any) error
}

Service 定义 Session 服务接口

type Session

type Session interface {
	// ID 返回会话的唯一标识符
	ID() string

	// AppName 返回应用名称
	AppName() string

	// UserID 返回用户 ID
	UserID() string

	// AgentID 返回关联的 Agent ID
	AgentID() string

	// State 返回会话状态管理器
	State() State

	// Events 返回事件列表
	Events() Events

	// LastUpdateTime 返回最后更新时间
	LastUpdateTime() time.Time

	// Metadata 返回会话元数据
	Metadata() map[string]any
}

Session 表示用户与 Agent 之间的一系列交互 参考 Google ADK-Go 的 Session 设计

type SessionData

type SessionData struct {
	ID             string
	AppName        string
	UserID         string
	AgentID        string
	CreatedAt      time.Time
	LastUpdateTime time.Time
	Metadata       map[string]any
}

SessionData Session 接口的具体实现(用于数据库服务)

type SessionSummary added in v0.13.0

type SessionSummary struct {
	Text          string    `json:"text"`
	MessageCount  int       `json:"message_count"`
	GeneratedAt   time.Time `json:"generated_at"`
	TokensUsed    int       `json:"tokens_used"`
	KeyTopics     []string  `json:"key_topics"`
	Participants  []string  `json:"participants"`
	IsIncremental bool      `json:"is_incremental"`
}

SessionSummary Session 摘要

type State

type State interface {
	// Get 获取指定 key 的值
	// 如果 key 不存在,返回 ErrStateKeyNotExist
	Get(key string) (any, error)

	// Set 设置 key-value,覆盖已存在的值
	Set(key string, value any) error

	// Delete 删除指定 key
	Delete(key string) error

	// All 返回所有 key-value 的迭代器
	All() iter.Seq2[string, any]

	// Has 检查 key 是否存在
	Has(key string) bool
}

State 定义分层的状态管理接口 支持三种作用域: App/User/Temp

type Summarizer added in v0.13.0

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

Summarizer Session 摘要器

func NewSummarizer added in v0.13.0

func NewSummarizer(config SummarizerConfig) *Summarizer

NewSummarizer 创建 Session 摘要器

func (*Summarizer) SummarizeIncremental added in v0.13.0

func (s *Summarizer) SummarizeIncremental(ctx context.Context, previousSummary string, newMessages []types.Message) (*SessionSummary, error)

SummarizeIncremental 增量摘要(基于之前的摘要)

func (*Summarizer) SummarizeSession added in v0.13.0

func (s *Summarizer) SummarizeSession(ctx context.Context, messages []types.Message) (*SessionSummary, error)

SummarizeSession 生成 Session 摘要

type SummarizerConfig added in v0.13.0

type SummarizerConfig struct {
	Provider               provider.Provider
	MaxMessagesPerCall     int     // 每次摘要的最大消息数
	MinMessagesToSummarize int     // 触发摘要的最小消息数
	Temperature            float64 // 摘要生成温度
	SystemPrompt           string  // 自定义系统提示词
}

SummarizerConfig Session 摘要器配置

type UpdateRequest

type UpdateRequest struct {
	SessionID string
	Metadata  map[string]any
}

UpdateRequest 更新会话请求

Directories

Path Synopsis
Package sqlite provides a SQLite-based implementation of the session.Service interface.
Package sqlite provides a SQLite-based implementation of the session.Service interface.

Jump to

Keyboard shortcuts

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