shenlun-forge 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- shenlun_forge-0.2.0/LICENSE +21 -0
- shenlun_forge-0.2.0/PKG-INFO +445 -0
- shenlun_forge-0.2.0/README.md +414 -0
- shenlun_forge-0.2.0/context_forge/__init__.py +71 -0
- shenlun_forge-0.2.0/context_forge/adapters/__init__.py +1 -0
- shenlun_forge-0.2.0/context_forge/adapters/langchain_adapter.py +159 -0
- shenlun_forge-0.2.0/context_forge/analyzer.py +279 -0
- shenlun_forge-0.2.0/context_forge/base.py +74 -0
- shenlun_forge-0.2.0/context_forge/cli.py +212 -0
- shenlun_forge-0.2.0/context_forge/compressor.py +235 -0
- shenlun_forge-0.2.0/context_forge/formatter.py +196 -0
- shenlun_forge-0.2.0/context_forge/llm.py +105 -0
- shenlun_forge-0.2.0/context_forge/processor.py +280 -0
- shenlun_forge-0.2.0/context_forge/registry.py +41 -0
- shenlun_forge-0.2.0/context_forge/retriever.py +201 -0
- shenlun_forge-0.2.0/context_forge/strategies/__init__.py +1 -0
- shenlun_forge-0.2.0/context_forge/strategies/hybrid.py +307 -0
- shenlun_forge-0.2.0/context_forge/strategies/simple.py +176 -0
- shenlun_forge-0.2.0/context_forge/types.py +91 -0
- shenlun_forge-0.2.0/pyproject.toml +42 -0
- shenlun_forge-0.2.0/setup.cfg +4 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/PKG-INFO +445 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/SOURCES.txt +25 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/dependency_links.txt +1 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/entry_points.txt +2 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/requires.txt +17 -0
- shenlun_forge-0.2.0/shenlun_forge.egg-info/top_level.txt +1 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Liu Rongchen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,445 @@
|
|
|
1
|
+
Metadata-Version: 2.1
|
|
2
|
+
Name: shenlun-forge
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Task-driven context compression for LLM agents with analytical compression strategy
|
|
5
|
+
Author-email: Liu Rongchen <rederdan@coze.email>
|
|
6
|
+
License: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/liurongchen1/context-forge
|
|
8
|
+
Project-URL: Repository, https://github.com/liurongchen1/context-forge
|
|
9
|
+
Keywords: llm,context,compression,agent,acs
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Intended Audience :: Developers
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
15
|
+
Requires-Python: >=3.9
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Requires-Dist: pydantic>=2.0
|
|
19
|
+
Requires-Dist: tiktoken>=0.5.0
|
|
20
|
+
Provides-Extra: openai
|
|
21
|
+
Requires-Dist: openai>=1.0; extra == "openai"
|
|
22
|
+
Provides-Extra: langchain
|
|
23
|
+
Requires-Dist: langchain-core>=0.1; extra == "langchain"
|
|
24
|
+
Provides-Extra: full
|
|
25
|
+
Requires-Dist: openai>=1.0; extra == "full"
|
|
26
|
+
Requires-Dist: langchain-core>=0.1; extra == "full"
|
|
27
|
+
Requires-Dist: anthropic>=0.20; extra == "full"
|
|
28
|
+
Provides-Extra: dev
|
|
29
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
30
|
+
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
|
|
31
|
+
|
|
32
|
+
# ContextForge
|
|
33
|
+
|
|
34
|
+
**面向 LLM Agent 的任务驱动型上下文压缩库**
|
|
35
|
+
**Task-Driven Context Compression for LLM Agents**
|
|
36
|
+
|
|
37
|
+
*一个轻量级 Python 库,在将对话上下文发送给 LLM 之前进行智能压缩,灵感来源于结构化分析方法论。*
|
|
38
|
+
*A lightweight Python library that intelligently compresses conversation context before sending it to LLMs, inspired by structured analytical methodology.*
|
|
39
|
+
|
|
40
|
+
[](https://www.python.org/downloads/)
|
|
41
|
+
[](https://opensource.org/licenses/MIT)
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## 为什么选择 ContextForge? / Why ContextForge?
|
|
46
|
+
|
|
47
|
+
LLM Agent 面临**上下文溢出**问题——随着对话增长,完整历史会超出 token 限制或变得过于昂贵。现有方案(截断、简单摘要、滑动窗口)会丢失关键信息,或在无关内容上浪费 token。
|
|
48
|
+
LLM agents suffer from **context overflow** — as conversations grow, the full history exceeds token limits or becomes too expensive. Existing solutions (truncation, simple summarization, sliding windows) lose critical information or waste tokens on irrelevant content.
|
|
49
|
+
|
|
50
|
+
**ContextForge 采用不同的方法**:它像专家分析师处理信息一样对待上下文压缩——首先理解*需要什么*,然后只提取相关事实,将重复内容合并并加上描述性标签,最后在严格的 token 预算内格式化输出。
|
|
51
|
+
**ContextForge takes a different approach**: it treats context compression like an expert analyst processing information — first understanding *what's needed*, then extracting only relevant facts, merging duplicates with descriptive labels, and formatting everything within a strict token budget.
|
|
52
|
+
|
|
53
|
+
## 核心创新:ACS 四阶段流水线 / The Innovation: ACS Four-Stage Pipeline
|
|
54
|
+
|
|
55
|
+
ContextForge 将**结构化分析方法论**映射到 LLM 上下文管理,形成四阶段分析压缩策略(Analytical Compression Strategy, ACS):
|
|
56
|
+
ContextForge maps a proven structured analytical methodology to LLM context management, forming a four-stage Analytical Compression Strategy (ACS):
|
|
57
|
+
|
|
58
|
+
| 阶段 / Stage | ContextForge 模块 / Module | 功能 / What It Does |
|
|
59
|
+
|-----------|-------------------|--------------|
|
|
60
|
+
| **分析** (Analyze) | `ACSAnalyzer` | 理解当前任务,确定哪些信息重要 / Understands the current task and determines what information matters |
|
|
61
|
+
| **检索** (Retrieve) | `ACSRetriever` | 从完整上下文中查找并评分相关信息 / Finds and scores relevant information from the full context |
|
|
62
|
+
| **处理** (Process) | `ACSProcessor` | 合并重复项,提取摘要标签,规范化表达 / Merges duplicates, extracts summary labels, normalizes expressions |
|
|
63
|
+
| **格式化** (Format) | `ACSFormatter` | 在 token 预算内输出结构化压缩文本 / Outputs structured, compressed text within token budget |
|
|
64
|
+
|
|
65
|
+
### 差异化对比 / What Makes This Different?
|
|
66
|
+
|
|
67
|
+
| 特性 / Feature | ContextForge | 简单摘要 / Simple Summary | 滑动窗口 / Sliding Window | RAG |
|
|
68
|
+
|---------|:-----------:|:--------------:|:--------------:|:---:|
|
|
69
|
+
| 任务感知压缩 / Task-aware compression | ✅ | ❌ | ❌ | ❌ |
|
|
70
|
+
| 层级合并 / Hierarchical merging | ✅ | ❌ | ❌ | 部分 / Partial |
|
|
71
|
+
| 摘要标签 / Summary labels | ✅ | ❌ | ❌ | ❌ |
|
|
72
|
+
| 硬性 token 预算 / Hard token budget | ✅ | ❌ | ✅ | ❌ |
|
|
73
|
+
| 表达规范化 / Expression normalization | ✅ | ❌ | ❌ | ❌ |
|
|
74
|
+
| 无需额外索引 / No extra retrieval index | ✅ | ✅ | ✅ | ❌ |
|
|
75
|
+
|
|
76
|
+
## 安装 / Installation
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
# 基础安装(包含 tiktoken 用于精确 token 计数)
|
|
80
|
+
# Basic installation (includes tiktoken for accurate token counting)
|
|
81
|
+
pip install context-forge
|
|
82
|
+
|
|
83
|
+
# 含 OpenAI 兼容 API 支持(推荐用于 LLM 驱动策略)
|
|
84
|
+
# With OpenAI-compatible API support (recommended for LLM-powered strategies)
|
|
85
|
+
pip install context-forge[openai]
|
|
86
|
+
|
|
87
|
+
# 含 LangChain 适配器
|
|
88
|
+
# With LangChain adapter
|
|
89
|
+
pip install context-forge[langchain]
|
|
90
|
+
|
|
91
|
+
# 完整安装(所有可选依赖)
|
|
92
|
+
# Full installation (all optional dependencies)
|
|
93
|
+
pip install context-forge[full]
|
|
94
|
+
|
|
95
|
+
# 开发安装
|
|
96
|
+
# Development installation
|
|
97
|
+
pip install context-forge[dev]
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## 快速开始 / Quick Start
|
|
101
|
+
|
|
102
|
+
### Python API
|
|
103
|
+
|
|
104
|
+
```python
|
|
105
|
+
import asyncio
|
|
106
|
+
from context_forge import ContextForge
|
|
107
|
+
|
|
108
|
+
async def main():
|
|
109
|
+
# 初始化 LLM 提供者 / Initialize with your LLM provider
|
|
110
|
+
forge = ContextForge(
|
|
111
|
+
model="deepseek-chat",
|
|
112
|
+
api_key="your-api-key",
|
|
113
|
+
base_url="https://api.deepseek.com/v1",
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
# 对话历史 / Conversation history
|
|
117
|
+
messages = [
|
|
118
|
+
{"role": "user", "content": "I'm building a restaurant app with FastAPI."},
|
|
119
|
+
{"role": "assistant", "content": "Great! Let's use FastAPI with SQLAlchemy..."},
|
|
120
|
+
# ... 更多消息 / more messages ...
|
|
121
|
+
]
|
|
122
|
+
|
|
123
|
+
# 为当前查询压缩上下文 / Compress context for the current query
|
|
124
|
+
result = await forge.compress(
|
|
125
|
+
messages=messages,
|
|
126
|
+
current_query="What database did we decide on?",
|
|
127
|
+
max_tokens=4000,
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
print(result.compressed_text)
|
|
131
|
+
print(f"压缩率 / Compression ratio: {result.compression_ratio:.1%}")
|
|
132
|
+
print(f"节省 token / Token savings: {result.original_tokens - result.compressed_tokens} tokens")
|
|
133
|
+
|
|
134
|
+
asyncio.run(main())
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
### 选择策略 / Choosing a Strategy
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from context_forge import ContextForge
|
|
141
|
+
|
|
142
|
+
# ACS 全量分析流水线(需要 LLM,最佳质量)
|
|
143
|
+
# Full ACS pipeline (requires LLM, best quality)
|
|
144
|
+
forge = ContextForge.create(strategy="acs", model="deepseek-chat", api_key="...")
|
|
145
|
+
|
|
146
|
+
# 简单策略(无需 LLM,基于规则,最快速)
|
|
147
|
+
# Simple strategy (no LLM needed, rule-based, fastest)
|
|
148
|
+
forge = ContextForge.create(strategy="simple")
|
|
149
|
+
|
|
150
|
+
# HCS 混合策略(ACS + 逐字代码块,最适合编码任务)
|
|
151
|
+
# HCS hybrid strategy (ACS + verbatim code blocks, best for coding tasks)
|
|
152
|
+
forge = ContextForge.create(strategy="hcs", model="deepseek-chat", api_key="...")
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
### CLI 用法 / CLI Usage
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
# 压缩 JSON 消息文件 / Compress a JSON messages file
|
|
159
|
+
context-forge compress --messages messages.json \
|
|
160
|
+
--query "What did we decide about the database?" \
|
|
161
|
+
--strategy acs \
|
|
162
|
+
--max-tokens 4000 \
|
|
163
|
+
--api-key "sk-..." \
|
|
164
|
+
--base-url "https://api.deepseek.com/v1"
|
|
165
|
+
|
|
166
|
+
# 从 stdin 读取消息 / Read messages from stdin
|
|
167
|
+
echo '[{"role":"user","content":"Hello"}]' | \
|
|
168
|
+
context-forge compress --stdin --strategy simple --query "Summary"
|
|
169
|
+
|
|
170
|
+
# 使用环境变量配置凭据 / Use environment variables for credentials
|
|
171
|
+
export CONTEXT_FORGE_API_KEY="sk-..."
|
|
172
|
+
export CONTEXT_FORGE_BASE_URL="https://api.deepseek.com/v1"
|
|
173
|
+
export CONTEXT_FORGE_MODEL="deepseek-chat"
|
|
174
|
+
context-forge compress --messages chat.json --query "Recap" --verbose
|
|
175
|
+
|
|
176
|
+
# 保存输出到文件 / Save output to file
|
|
177
|
+
context-forge compress -m messages.json -q "Summary" -o result.json
|
|
178
|
+
|
|
179
|
+
# 列出可用策略 / List available strategies
|
|
180
|
+
context-forge strategies
|
|
181
|
+
|
|
182
|
+
# 显示版本 / Show version
|
|
183
|
+
context-forge version
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
**CLI 输出格式 / CLI output format:**
|
|
187
|
+
```json
|
|
188
|
+
{
|
|
189
|
+
"compressed_text": "...",
|
|
190
|
+
"original_tokens": 12500,
|
|
191
|
+
"compressed_tokens": 3200,
|
|
192
|
+
"compression_ratio": 0.256,
|
|
193
|
+
"stats": {
|
|
194
|
+
"strategy": "acs",
|
|
195
|
+
"total_duration_ms": 2340,
|
|
196
|
+
"original_messages": 30,
|
|
197
|
+
"relevant_blocks": 18,
|
|
198
|
+
"compressed_groups": 8
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### LangChain 集成 / With LangChain
|
|
204
|
+
|
|
205
|
+
```python
|
|
206
|
+
from context_forge.adapters.langchain_adapter import LangChainContextForge
|
|
207
|
+
|
|
208
|
+
forge = LangChainContextForge(
|
|
209
|
+
model="deepseek-chat",
|
|
210
|
+
api_key="your-key",
|
|
211
|
+
max_tokens=4000,
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
# 作为可调用组件集成到流水线中 / Use as a callable in your pipeline
|
|
215
|
+
result = forge.invoke({
|
|
216
|
+
"messages": chat_history,
|
|
217
|
+
"query": current_question,
|
|
218
|
+
})
|
|
219
|
+
|
|
220
|
+
# 或作为回调处理器自动压缩 / Or as a callback handler for automatic compression
|
|
221
|
+
handler = forge.as_callback_handler()
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## 架构 / Architecture
|
|
225
|
+
|
|
226
|
+
```
|
|
227
|
+
context_forge/
|
|
228
|
+
├── __init__.py # 公共 API 导出 / Public API exports
|
|
229
|
+
├── types.py # 数据模型 / Data models (ContextBlock, TaskProfile, InfoType, etc.)
|
|
230
|
+
├── base.py # 抽象基类 / Abstract base classes
|
|
231
|
+
├── llm.py # LLM 提供者 / LLM provider (OpenAI-compatible)
|
|
232
|
+
├── analyzer.py # 阶段 1: 任务分析 / Step 1: Task analysis (ACSAnalyzer)
|
|
233
|
+
├── retriever.py # 阶段 2: 信息提取 / Step 2: Information extraction (ACSRetriever)
|
|
234
|
+
├── processor.py # 阶段 3: 合并与规范化 / Step 3: Merge & normalize (ACSProcessor)
|
|
235
|
+
├── formatter.py # 阶段 4: Token 预算格式化 / Step 4: Token-budget formatting (ACSFormatter)
|
|
236
|
+
├── compressor.py # 主编排器 / Main orchestrator (ContextForge class)
|
|
237
|
+
├── registry.py # 策略注册表 / Strategy registry for extensibility
|
|
238
|
+
├── cli.py # 命令行接口 / Command-line interface
|
|
239
|
+
├── strategies/
|
|
240
|
+
│ ├── __init__.py
|
|
241
|
+
│ ├── simple.py # 规则回退(无需 LLM)/ Rule-based fallback (no LLM)
|
|
242
|
+
│ └── hybrid.py # ACS + 逐字代码增强 / ACS + verbatim code augmentation (HCSCompressor)
|
|
243
|
+
└── adapters/
|
|
244
|
+
├── __init__.py
|
|
245
|
+
└── langchain_adapter.py # LangChain 集成 / LangChain integration
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
## 工作原理 / How It Works
|
|
249
|
+
|
|
250
|
+
### 阶段 1:分析 — 任务解析 / Step 1: Analyze — Task Analysis
|
|
251
|
+
|
|
252
|
+
ACSAnalyzer 检查当前查询和对话,确定以下信息:
|
|
253
|
+
The ACSAnalyzer examines the current query and conversation to determine:
|
|
254
|
+
|
|
255
|
+
- **任务类型 / Task type**:QA、代码生成、分析、创意写作等 / QA, code generation, analysis, creative, etc.
|
|
256
|
+
- **关键要素 / Key elements**:需要哪些具体信息 / What specific information is needed
|
|
257
|
+
- **优先级权重 / Priority weights**:每类信息的重要程度 / How important each type of information is
|
|
258
|
+
- **输出格式 / Output format**:顺序、结构化或要点列表 / Sequential, structured, or bullet points
|
|
259
|
+
|
|
260
|
+
当 LLM 不可用时,快速规则分类器使用关键词匹配作为回退。
|
|
261
|
+
When LLM is unavailable, a fast rule-based classifier uses keyword matching as fallback.
|
|
262
|
+
|
|
263
|
+
### 阶段 2:检索 — 信息提取 / Step 2: Retrieve — Information Extraction
|
|
264
|
+
|
|
265
|
+
ACSRetriever 基于 6 个维度对每条消息块评分:
|
|
266
|
+
The ACSRetriever scores every message block based on 6 dimensions:
|
|
267
|
+
|
|
268
|
+
1. **关键词相关性 / Keyword relevance**:与当前查询的匹配度 / Match to current query
|
|
269
|
+
2. **信息类型 / Information type**:事实、动作、问题、数据等 / Facts, actions, problems, data, etc.
|
|
270
|
+
3. **时效性 / Recency**:较新消息通常更相关 / Newer messages generally more relevant
|
|
271
|
+
4. **角色重要性 / Role importance**:工具结果 > 用户指令 > 助手解释 / Tool results > user instructions > assistant explanations
|
|
272
|
+
5. **信号词 / Signal words**:"but"、"therefore"、"important" 等
|
|
273
|
+
6. **内容密度 / Content density**:代码、表格、结构化数据得分更高 / Code, tables, structured data score higher
|
|
274
|
+
|
|
275
|
+
### 阶段 3:处理 — 核心创新 / Step 3: Process — Core Innovation
|
|
276
|
+
|
|
277
|
+
ACSProcessor 执行三个关键操作:
|
|
278
|
+
The ACSProcessor performs three key operations:
|
|
279
|
+
|
|
280
|
+
1. **合并同类项 / Merge duplicates**:语义相似的块被分组 / Semantically similar blocks are grouped
|
|
281
|
+
2. **提炼摘要标签 / Extract labels**:每组获得一个简洁的 2-6 字符标签 / Each group gets a concise 2-6 character label
|
|
282
|
+
3. **规范化表达 / Normalize**:非正式语言转为技术表达 / Informal language is converted to technical expressions
|
|
283
|
+
|
|
284
|
+
### 阶段 4:格式化 — 输出 / Step 4: Format — Formatted Output
|
|
285
|
+
|
|
286
|
+
ACSFormatter 完成以下工作:
|
|
287
|
+
The ACSFormatter:
|
|
288
|
+
|
|
289
|
+
- 按相关性和信息类型排列块优先级 / Prioritizes blocks by relevance and information type
|
|
290
|
+
- 在 token 预算内贪心填充最高优先级内容 / Greedily fills the token budget with highest-priority content
|
|
291
|
+
- 按任务配置格式化输出(顺序、结构化或要点)/ Formats output according to the task profile
|
|
292
|
+
- 预算紧张时优雅截断 / Truncates gracefully when budget is tight
|
|
293
|
+
|
|
294
|
+
## 基准测试结果 / Benchmark Results
|
|
295
|
+
|
|
296
|
+
### 单场景对比(5 种策略)/ Single-Scenario Comparison (5 Strategies)
|
|
297
|
+
|
|
298
|
+
| 策略 / Strategy | 事实保留 / Facts Retained | 压缩率 / Compression Ratio | 说明 / Notes |
|
|
299
|
+
|----------|:---:|:---:|-------|
|
|
300
|
+
| **Full ACS** | 100% | 58% | 最佳事实保留,强压缩 / Best fact retention with strong compression |
|
|
301
|
+
| HCS | 100% | 65% | 混合内容良好平衡 / Good balance for mixed content |
|
|
302
|
+
| Direct LLM | 80% | 45% | 简单摘要,丢失细节 / Simple summarization, loses details |
|
|
303
|
+
| Sliding Window | 70% | 75% | 完全丢失早期上下文 / Loses early context entirely |
|
|
304
|
+
| Simple (no LLM) | 60% | 50% | 快速但质量较低 / Fast but low quality |
|
|
305
|
+
|
|
306
|
+
### 6 场景批量实验 / 6-Scenario Batch Experiment
|
|
307
|
+
|
|
308
|
+
| 场景 / Scenario | Full ACS | HCS | Simple | Sliding Window |
|
|
309
|
+
|----------|:---:|:---:|:---:|:---:|
|
|
310
|
+
| 安全分析 / Security Analysis | **10/10** | 2/10 | 0/10 | 0/10 |
|
|
311
|
+
| 被拒方案 / Rejected Alternatives | **8/8** | 7/8 | 2/8 | 2/8 |
|
|
312
|
+
| 代码细节 / Code Detail | 1/10 | 1/10 | 1/10 | 1/10 |
|
|
313
|
+
| 事实回忆 / Fact Recall | **16/16** | 15/16 | 12/16 | 12/16 |
|
|
314
|
+
| 架构设计 / Architecture | **13/15** | 13/15 | 11/15 | 11/15 |
|
|
315
|
+
| 任务/时间线 / Tasks/Timeline | 7/10 | 2/10 | **10/10** | **10/10** |
|
|
316
|
+
|
|
317
|
+
### 消融研究(5 个变体 × 6 场景)/ Ablation Study (5 Variants × 6 Scenarios)
|
|
318
|
+
|
|
319
|
+
| 变体 / Variant | 说明 / Description | 平均得分 / Avg Score |
|
|
320
|
+
|---------|-------------|:---------:|
|
|
321
|
+
| **Full ACS** | 完整四阶段流水线 / Complete 4-step pipeline | **最高 / Highest overall** |
|
|
322
|
+
| HCS | ACS + 逐字代码 / ACS + verbatim code | 代码密集任务最佳 / Best for code-heavy tasks |
|
|
323
|
+
| Direct-Only | 仅 LLM 摘要 / LLM summarization only | 中等表现 / Moderate performance |
|
|
324
|
+
| Analyze-Only | 分析+检索(跳过合并/格式化)/ Analyze + Extract (skip merge/format) | 事实回忆良好 / Good for factual recall |
|
|
325
|
+
| Simple | 纯规则驱动 / Pure rule-based | 最快速,质量最低 / Fastest, lowest quality |
|
|
326
|
+
|
|
327
|
+
### 关键发现 / Key Findings
|
|
328
|
+
|
|
329
|
+
- **Full ACS** 在推理和事实回忆任务中占优(6 个场景中 4 个最佳)/ dominates in reasoning and fact recall tasks (4/6 scenarios best)
|
|
330
|
+
- **HCS** 在需要精确保留代码块时表现出色 / excels when code blocks need exact preservation
|
|
331
|
+
- **Simple** 在时间线/顺序任务中出人意料地有效(无 LLM 成本!)/ surprisingly effective for timeline/sequential tasks (no LLM cost!)
|
|
332
|
+
- 代码细节保留是所有策略的共同挑战 / Code detail retention is a universal challenge across all strategies
|
|
333
|
+
|
|
334
|
+
## 配置 / Configuration
|
|
335
|
+
|
|
336
|
+
### LLM 提供者 / LLM Provider
|
|
337
|
+
|
|
338
|
+
```python
|
|
339
|
+
from context_forge import OpenAIProvider
|
|
340
|
+
|
|
341
|
+
# 兼容任何 OpenAI 兼容 API / Works with any OpenAI-compatible API
|
|
342
|
+
provider = OpenAIProvider(
|
|
343
|
+
model="deepseek-chat", # 或 / or "gpt-4o", "claude-3-haiku", etc.
|
|
344
|
+
api_key="sk-...",
|
|
345
|
+
base_url="https://api.deepseek.com/v1",
|
|
346
|
+
temperature=0.1, # 低温度保证分析一致性 / Low temperature for consistent analysis
|
|
347
|
+
max_tokens=4096,
|
|
348
|
+
)
|
|
349
|
+
```
|
|
350
|
+
|
|
351
|
+
### 自定义组件 / Custom Components
|
|
352
|
+
|
|
353
|
+
```python
|
|
354
|
+
from context_forge import ContextForge
|
|
355
|
+
from context_forge.analyzer import ACSAnalyzer
|
|
356
|
+
from context_forge.retriever import ACSRetriever
|
|
357
|
+
|
|
358
|
+
forge = ContextForge(
|
|
359
|
+
analyzer=ACSAnalyzer(llm=provider, use_fast_path=True),
|
|
360
|
+
retriever=ACSRetriever(llm=provider, min_score_threshold=0.2),
|
|
361
|
+
# 使用默认处理器和格式化器 / Use default processor and formatter
|
|
362
|
+
)
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
### 任务类型 / Task Types
|
|
366
|
+
|
|
367
|
+
```python
|
|
368
|
+
from context_forge import TaskType
|
|
369
|
+
|
|
370
|
+
# 强制指定任务类型(跳过自动检测)
|
|
371
|
+
# Force a specific task type (skip auto-detection)
|
|
372
|
+
result = await forge.compress(
|
|
373
|
+
messages=messages,
|
|
374
|
+
current_query="Fix this bug",
|
|
375
|
+
task_type="code_gen", # 强制代码聚焦压缩 / Forces code-focused compression
|
|
376
|
+
max_tokens=4000,
|
|
377
|
+
)
|
|
378
|
+
```
|
|
379
|
+
|
|
380
|
+
### 添加自定义策略 / Adding Custom Strategies
|
|
381
|
+
|
|
382
|
+
扩展策略注册表以添加自定义压缩策略:
|
|
383
|
+
Extend the strategy registry to add your own compression strategies:
|
|
384
|
+
|
|
385
|
+
```python
|
|
386
|
+
# 在代码中或通过猴子补丁 / In your code or via monkey-patching
|
|
387
|
+
from context_forge.registry import get_strategy_class
|
|
388
|
+
|
|
389
|
+
# 注册表是懒加载的,可以在导入时添加条目
|
|
390
|
+
# The registry is lazy-loaded, so you can add entries at import time
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
## 依赖要求 / Requirements
|
|
394
|
+
|
|
395
|
+
- Python 3.9+
|
|
396
|
+
- `pydantic>=2.0` — 数据验证和模型 / Data validation and models
|
|
397
|
+
- `tiktoken>=0.5.0` — 精确 token 计数 / Accurate token counting
|
|
398
|
+
- 可选 / Optional: `openai>=1.0` — OpenAI 兼容 LLM 提供者 / OpenAI-compatible LLM provider
|
|
399
|
+
- 可选 / Optional: `langchain-core>=0.1` — LangChain 适配器集成 / LangChain adapter integration
|
|
400
|
+
|
|
401
|
+
## 研究背景 / Research Background
|
|
402
|
+
|
|
403
|
+
本方法受结构化分析方法论启发,该方法论要求:
|
|
404
|
+
This approach is inspired by structured analytical methodology, where analysts must:
|
|
405
|
+
|
|
406
|
+
1. 理解问题要求 / Understand the question requirements
|
|
407
|
+
2. 从冗长材料中提取相关事实 / Extract relevant facts from lengthy materials
|
|
408
|
+
3. 合并重复项并添加摘要标签 / Merge duplicates and add summary labels
|
|
409
|
+
4. 在严格的字数限制内呈现 / Present within strict word limits
|
|
410
|
+
|
|
411
|
+
我们对 21 个代表性上下文压缩系统(2023-2026)的学术调研发现,**现有系统均不同时具备**以下四个特征:
|
|
412
|
+
Our academic survey of 21 representative context compression systems (2023-2026) found that **no existing system** combines all four of these features:
|
|
413
|
+
|
|
414
|
+
- 任务驱动压缩策略 / Task-driven compression strategy
|
|
415
|
+
- 语义去重的层级合并 / Hierarchical merging with semantic deduplication
|
|
416
|
+
- 显式摘要标签提取 / Explicit summary label extraction
|
|
417
|
+
- 硬性 token 预算执行 / Hard token budget enforcement
|
|
418
|
+
|
|
419
|
+
最接近的工作包括 GraphRAG(层级但基于图)、SUPO(任务驱动但仅 RL)和 HTSIR(层级但基于文档结构)。
|
|
420
|
+
The closest works are GraphRAG (hierarchical but graph-based), SUPO (task-driven but RL-only), and HTSIR (hierarchical but document-structure-based).
|
|
421
|
+
|
|
422
|
+
## 许可证 / License
|
|
423
|
+
|
|
424
|
+
MIT 许可证 — 详见 LICENSE 文件 / MIT License — see LICENSE file for details.
|
|
425
|
+
|
|
426
|
+
## 引用 / Citation
|
|
427
|
+
|
|
428
|
+
```bibtex
|
|
429
|
+
@software{contextforge2026,
|
|
430
|
+
title={ContextForge: Task-Driven Context Compression for LLM Agents},
|
|
431
|
+
author={Liu, Rongchen},
|
|
432
|
+
year={2026},
|
|
433
|
+
url={https://github.com/rederdan/context-forge}
|
|
434
|
+
}
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
## 贡献 / Contributing
|
|
438
|
+
|
|
439
|
+
欢迎贡献!我们特别需要以下方面的帮助:
|
|
440
|
+
Contributions welcome! Areas we'd love help with:
|
|
441
|
+
|
|
442
|
+
- 更多框架适配器 / More framework adapters (AutoGen, CrewAI, LlamaIndex)
|
|
443
|
+
- 额外压缩策略 / Additional compression strategies
|
|
444
|
+
- 上下文压缩评估基准数据集 / Benchmark datasets for context compression evaluation
|
|
445
|
+
- 多语言表达规范化映射 / Multilingual expression normalization maps
|