NewSummarizationMiddleware 创建中间件
(config *SummarizationMiddlewareConfig)
| 80 | |
| 81 | // NewSummarizationMiddleware 创建中间件 |
| 82 | func NewSummarizationMiddleware(config *SummarizationMiddlewareConfig) (*SummarizationMiddleware, error) { |
| 83 | if config == nil { |
| 84 | return nil, errors.New("config cannot be nil") |
| 85 | } |
| 86 | |
| 87 | if config.MaxTokensBeforeSummary <= 0 { |
| 88 | config.MaxTokensBeforeSummary = 170000 |
| 89 | } |
| 90 | |
| 91 | if config.MessagesToKeep <= 0 { |
| 92 | config.MessagesToKeep = 6 |
| 93 | } |
| 94 | |
| 95 | if config.SummaryPrefix == "" { |
| 96 | config.SummaryPrefix = "## Previous conversation summary:" |
| 97 | } |
| 98 | |
| 99 | if config.TokenCounter == nil { |
| 100 | config.TokenCounter = defaultTokenCounter |
| 101 | } |
| 102 | |
| 103 | if config.Summarizer == nil { |
| 104 | config.Summarizer = defaultSummarizer |
| 105 | } |
| 106 | |
| 107 | // 初始化压缩策略 |
| 108 | compactionStrategy := config.CompactionStrategy |
| 109 | if compactionStrategy == nil { |
| 110 | compactionStrategy = DefaultCompactionStrategy() |
| 111 | } |
| 112 | |
| 113 | m := &SummarizationMiddleware{ |
| 114 | BaseMiddleware: NewBaseMiddleware("summarization", 40), |
| 115 | maxTokensBeforeSummary: config.MaxTokensBeforeSummary, |
| 116 | messagesToKeep: config.MessagesToKeep, |
| 117 | summaryPrefix: config.SummaryPrefix, |
| 118 | tokenCounter: config.TokenCounter, |
| 119 | summarizer: config.Summarizer, |
| 120 | summarizationCount: 0, |
| 121 | compactionStrategy: compactionStrategy, |
| 122 | useMetadataVisibility: config.UseMetadataVisibility, |
| 123 | enableProgressiveCompact: config.EnableProgressiveCompact, |
| 124 | } |
| 125 | |
| 126 | sumLog.Info(context.Background(), "initialized", map[string]any{ |
| 127 | "max_tokens": config.MaxTokensBeforeSummary, |
| 128 | "keep_messages": config.MessagesToKeep, |
| 129 | "progressive_compact": config.EnableProgressiveCompact, |
| 130 | "metadata_visibility": config.UseMetadataVisibility, |
| 131 | }) |
| 132 | return m, nil |
| 133 | } |
| 134 | |
| 135 | // WrapModelCall 包装模型调用,在调用前检查是否需要总结 |
| 136 | func (m *SummarizationMiddleware) WrapModelCall(ctx context.Context, req *ModelRequest, handler ModelCallHandler) (*ModelResponse, error) { |