Documentation
¶
Overview ¶
包 context 为智能体提供上下文窗口管理、压缩与自适应调控能力。
概述 ¶
context 解决的核心问题是:LLM 的上下文窗口有限,而智能体的 对话历史会持续增长。本包通过多级压缩策略与窗口管理机制, 确保消息始终适配模型的 token 预算,同时尽可能保留关键信息。
核心模型 ¶
- Engineer:统一上下文管理引擎,根据 token 使用率自动选择 压缩级别(None / Normal / Aggressive / Emergency), 提供 Manage / MustFit / GetStatus 等核心方法
- WindowManager:上下文窗口管理器,实现三种裁剪策略, 满足 agent.ContextManager 接口约定
- AgentContextManager:面向 Agent 的集成组件,封装 Engineer 并提供 PrepareMessages / ShouldCompress / GetRecommendation 等便捷方法
主要能力 ¶
- 多级压缩:基于 SoftLimit(70%) / WarnLimit(85%) / HardLimit(95%) 三道阈值,自动触发 Normal → Aggressive → Emergency 压缩
- 窗口策略:WindowManager 支持 SlidingWindow(保留最近 N 条)、 TokenBudget(按 token 预算从新到旧裁剪)、Summarize(LLM 摘要压缩旧消息)三种策略
- 紧急兜底:MustFit 最多重试 5 轮压缩,最终通过 hardTruncate 强制裁剪,保证消息永远不会超出上下文窗口
- 模型适配:DefaultAgentContextConfig 为 GPT-4 / Claude-3 / Gemini 等主流模型提供预设参数
- 统计追踪:Stats 记录压缩次数、紧急压缩次数、平均压缩比、 节省 token 数等运行指标
扩展方式 ¶
- 实现 Summarizer 接口接入自定义 LLM 摘要能力
- 通过 SetSummaryProvider 为 AgentContextManager 注入摘要函数
- 调整 Config 中的阈值与策略参数适配不同场景
与其他包协同 ¶
context 是 Agent 执行链路的核心前置环节。每次调用 LLM 前, Agent 通过 PrepareMessages 或 MustFit 确保消息适配上下文窗口, 与 agent/conversation 的多轮对话和 agent/tools 的工具调用 产生的长输出协同工作。
Index ¶
- type AgentContextConfig
- type AgentContextManager
- func (m *AgentContextManager) CanAddMessage(messages []types.Message, newMsg types.Message) bool
- func (m *AgentContextManager) EstimateTokens(messages []types.Message) int
- func (m *AgentContextManager) GetRecommendation(messages []types.Message) string
- func (m *AgentContextManager) GetStats() Stats
- func (m *AgentContextManager) GetStatus(messages []types.Message) Status
- func (m *AgentContextManager) PrepareMessages(ctx context.Context, messages []types.Message, currentQuery string) ([]types.Message, error)
- func (m *AgentContextManager) SetSummaryProvider(fn func(context.Context, []types.Message) (string, error))
- func (m *AgentContextManager) ShouldCompress(messages []types.Message) bool
- type Config
- type Engineer
- func (e *Engineer) CanAddMessage(msgs []types.Message, newMsg types.Message) bool
- func (e *Engineer) EstimateTokens(msgs []types.Message) int
- func (e *Engineer) GetStats() Stats
- func (e *Engineer) GetStatus(msgs []types.Message) Status
- func (e *Engineer) Manage(ctx context.Context, msgs []types.Message, query string) ([]types.Message, error)
- func (e *Engineer) MustFit(ctx context.Context, msgs []types.Message, query string) ([]types.Message, error)
- type Level
- type Stats
- type Status
- type Strategy
- type Summarizer
- type WindowConfig
- type WindowManager
- type WindowStatus
- type WindowStrategy
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AgentContextConfig ¶
type AgentContextConfig struct {
// Max ContextTokens是模型的上下文窗口大小.
MaxContextTokens int `json:"max_context_tokens"`
// 储备输出为模型输出保留符.
ReserveForOutput int `json:"reserve_for_output"`
// 策略决定了压缩行为.
Strategy Strategy `json:"strategy"`
// 启用度量衡允许压缩度量衡收集 。
EnableMetrics bool `json:"enable_metrics"`
}
Agent ContextConfig 配置代理上下文管理器.
func DefaultAgentContextConfig ¶
func DefaultAgentContextConfig(modelFamily string) AgentContextConfig
默认 Agent ContextConfig 返回常见模型的默认值。
type AgentContextManager ¶
type AgentContextManager struct {
// contains filtered or unexported fields
}
Agent ContextManager是代理的标准上下文管理组件. 它将工程师包裹在具有特定代理功能的容器上.
func NewAgentContextManager ¶
func NewAgentContextManager(cfg AgentContextConfig, logger *zap.Logger) *AgentContextManager
NewAgent ContextManager为代理创建上下文管理器.
func (*AgentContextManager) CanAddMessage ¶
CanAddMessage 检查是否可以不溢出添加消息 。
func (*AgentContextManager) EstimateTokens ¶
func (m *AgentContextManager) EstimateTokens(messages []types.Message) int
估计Tokens返回消息的符号数 。
func (*AgentContextManager) GetRecommendation ¶
func (m *AgentContextManager) GetRecommendation(messages []types.Message) string
Get Agreement return a human可读的推荐。
func (*AgentContextManager) GetStats ¶
func (m *AgentContextManager) GetStats() Stats
GetStats 返回压缩统计.
func (*AgentContextManager) GetStatus ¶
func (m *AgentContextManager) GetStatus(messages []types.Message) Status
GetState 返回当前上下文状态 。
func (*AgentContextManager) PrepareMessages ¶
func (m *AgentContextManager) PrepareMessages( ctx context.Context, messages []types.Message, currentQuery string, ) ([]types.Message, error)
ReadyMessages在发送到 LLM 之前优化消息.
func (*AgentContextManager) SetSummaryProvider ¶
func (m *AgentContextManager) SetSummaryProvider(fn func(context.Context, []types.Message) (string, error))
SetSummary Provider 设置基于 LLM 的汇总函数.
func (*AgentContextManager) ShouldCompress ¶
func (m *AgentContextManager) ShouldCompress(messages []types.Message) bool
如果建议压缩, 则应该压缩检查 。
type Config ¶
type Config struct {
MaxContextTokens int `json:"max_context_tokens"`
ReserveForOutput int `json:"reserve_for_output"`
SoftLimit float64 `json:"soft_limit"`
WarnLimit float64 `json:"warn_limit"`
HardLimit float64 `json:"hard_limit"`
TargetUsage float64 `json:"target_usage"`
Strategy Strategy `json:"strategy"`
}
配置定义上下文工程配置 。
type Engineer ¶
type Engineer struct {
// contains filtered or unexported fields
}
工程师是代理商的统一上下文管理部分. 它处理压缩,打压,以及适应性聚焦策略.
func (*Engineer) CanAddMessage ¶
CanAddMessage 检查是否可以添加新信件 。
func (*Engineer) EstimateTokens ¶
估计Tokens返回消息的符号数 。
type Stats ¶
type Stats struct {
TotalCompressions int64 `json:"total_compressions"`
EmergencyCount int64 `json:"emergency_count"`
AvgCompressionRatio float64 `json:"avg_compression_ratio"`
TokensSaved int64 `json:"tokens_saved"`
}
Stats跟踪上下文工程统计.
type Status ¶
type Status struct {
CurrentTokens int `json:"current_tokens"`
MaxTokens int `json:"max_tokens"`
UsageRatio float64 `json:"usage_ratio"`
Level Level `json:"level"`
Recommendation string `json:"recommendation"`
}
状况代表当前背景状况。
type Summarizer ¶
type Summarizer interface {
Summarize(ctx context.Context, messages []types.Message) (string, error)
}
Summarizer compresses messages into a summary string via LLM. Optional — when nil, the Summarize strategy falls back to TokenBudget.
type WindowConfig ¶
type WindowConfig struct {
Strategy WindowStrategy `json:"strategy"`
MaxTokens int `json:"max_tokens"` // Token budget ceiling
MaxMessages int `json:"max_messages"` // Maximum message count
ReserveTokens int `json:"reserve_tokens"` // Tokens reserved for new reply
SummaryModel string `json:"summary_model"` // Model for summarization (optional)
KeepSystemMsg bool `json:"keep_system_msg"` // Always preserve system messages
KeepLastN int `json:"keep_last_n"` // Always preserve last N messages
}
WindowConfig configures the window manager.
type WindowManager ¶
type WindowManager struct {
// contains filtered or unexported fields
}
WindowManager implements automatic context window management. It satisfies the agent.ContextManager interface.
func NewWindowManager ¶
func NewWindowManager(config WindowConfig, tokenCounter types.TokenCounter, summarizer Summarizer) *WindowManager
NewWindowManager creates a WindowManager. tokenCounter may be nil (defaults to len/4 estimation). summarizer may be nil (Summarize strategy falls back to TokenBudget).
func (*WindowManager) EstimateTokens ¶
func (w *WindowManager) EstimateTokens(messages []types.Message) int
EstimateTokens returns the total token count across all messages.
type WindowStatus ¶
type WindowStatus struct {
TotalTokens int `json:"total_tokens"`
MessageCount int `json:"message_count"`
MaxTokens int `json:"max_tokens"`
Trimmed bool `json:"trimmed"`
}
WindowStatus reports the current state of the context window.
type WindowStrategy ¶
type WindowStrategy string
WindowStrategy defines the context window management strategy.
const ( // StrategySlidingWindow keeps the most recent N messages. StrategySlidingWindow WindowStrategy = "sliding_window" // StrategyTokenBudget trims messages by token budget. StrategyTokenBudget WindowStrategy = "token_budget" // StrategySummarize compresses old messages via LLM summarization. StrategySummarize WindowStrategy = "summarize" )