context

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 6 Imported by: 0

Documentation

Overview

Package context 提供代理上下文构建、压缩与注入能力。

Index

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

func (m *AgentContextManager) CanAddMessage(messages []types.Message, newMsg types.Message) bool

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"`
}

配置定义上下文工程配置 。

func DefaultConfig

func DefaultConfig() Config

默认Config返回200k上下文模型的合理默认值.

type Engineer

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

工程师是代理商的统一上下文管理部分. 它处理压缩,打压,以及适应性聚焦策略.

func New

func New(config Config, logger *zap.Logger) *Engineer

新创建了新的上下文工程师.

func (*Engineer) CanAddMessage

func (e *Engineer) CanAddMessage(msgs []types.Message, newMsg types.Message) bool

CanAddMessage 检查是否可以添加新信件 。

func (*Engineer) EstimateTokens

func (e *Engineer) EstimateTokens(msgs []types.Message) int

估计Tokens返回消息的符号数 。

func (*Engineer) GetStats

func (e *Engineer) GetStats() Stats

GetStats 返回压缩统计.

func (*Engineer) GetStatus

func (e *Engineer) GetStatus(msgs []types.Message) Status

GetState 返回当前上下文状态 。

func (*Engineer) Manage

func (e *Engineer) Manage(ctx context.Context, msgs []types.Message, query string) ([]types.Message, error)

根据当前上下文使用管理处理信件 。

func (*Engineer) MustFit

func (e *Engineer) MustFit(ctx context.Context, msgs []types.Message, query string) ([]types.Message, error)

必须 适合可确保消息符合上下文窗口。

type Level

type Level int

关卡代表压缩紧急关卡.

const (
	LevelNone Level = iota
	LevelNormal
	LevelAggressive
	LevelEmergency
)

func (Level) String

func (l Level) String() string

String returns the string representation of Level.

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 Strategy

type Strategy string

战略确定了背景管理战略。

const (
	StrategyAdaptive   Strategy = "adaptive"
	StrategySummary    Strategy = "summary"
	StrategyPruning    Strategy = "pruning"
	StrategySliding    Strategy = "sliding"
	StrategyAggressive Strategy = "aggressive"
)

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 TokenCounter

type TokenCounter interface {
	CountTokens(text string) int
}

TokenCounter counts tokens in text. Compatible with rag.Tokenizer.

Note: llm/tools.TokenCounter has a different signature (returns error). These cannot be unified because this interface is error-free by design (context window management should not fail on token counting).

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 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.

func (*WindowManager) GetStatus

func (w *WindowManager) GetStatus(messages []types.Message) any

GetStatus returns the current window state.

func (*WindowManager) PrepareMessages

func (w *WindowManager) PrepareMessages(ctx context.Context, messages []types.Message, _ string) ([]types.Message, error)

PrepareMessages trims messages according to the configured strategy.

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"
)

Jump to

Keyboard shortcuts

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