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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AgentFrame 编排层 (Orchestrator)
|
| 3 |
+
===============================
|
| 4 |
+
DeepSeek 决策 ↔ OpenClaw 执行的桥接层
|
| 5 |
+
|
| 6 |
+
核心循环:
|
| 7 |
+
1. DeepSeek 分析用户意图 → 决定下一步
|
| 8 |
+
2. 调用 OpenClaw 工具 (exec/browser/computer-use)
|
| 9 |
+
3. 工具结果 → 分层量化存入 KV 缓存
|
| 10 |
+
4. 循环直到任务完成
|
| 11 |
+
|
| 12 |
+
架构:
|
| 13 |
+
Orchestrator
|
| 14 |
+
├── Brain: DeepSeek 客户端 (本地 L40S / API 兜底)
|
| 15 |
+
├── Hands: OpenClaw 工具桥 (exec/browser)
|
| 16 |
+
├── Memory: 前缀感知缓存池 (复用 agentframe_core.py)
|
| 17 |
+
└── Loop: Agent 循环控制
|
| 18 |
+
|
| 19 |
+
依赖:
|
| 20 |
+
- agentframe_core.py (前缀缓存池 + KV 量化)
|
| 21 |
+
- OpenClaw gateway (exec/browser 工具)
|
| 22 |
+
- DeepSeek 模型 (本地或 API)
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import time
|
| 27 |
+
import subprocess
|
| 28 |
+
from typing import Dict, List, Optional, Any, Callable
|
| 29 |
+
|
| 30 |
+
# ============================================================
|
| 31 |
+
# 1. Brain: DeepSeek 客户端抽象 (本地/API 可切换)
|
| 32 |
+
# ============================================================
|
| 33 |
+
|
| 34 |
+
class DeepSeekBrain:
|
| 35 |
+
"""
|
| 36 |
+
DeepSeek 决策大脑
|
| 37 |
+
mode: 'local' (L40S 本地) | 'api' (DeepSeek 官方)
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
def __init__(self, mode: str = "api", model: str = "deepseek-chat",
|
| 41 |
+
api_key: str = "", base_url: str = "https://api.deepseek.com"):
|
| 42 |
+
self.mode = mode
|
| 43 |
+
self.model = model
|
| 44 |
+
self.api_key = api_key
|
| 45 |
+
self.base_url = base_url
|
| 46 |
+
self.system_prompt = ""
|
| 47 |
+
self.conversation: List[Dict] = []
|
| 48 |
+
|
| 49 |
+
def set_system_prompt(self, prompt: str):
|
| 50 |
+
"""设置 Agent 系统提示 (含工具定义)"""
|
| 51 |
+
self.system_prompt = prompt
|
| 52 |
+
self.conversation = [{"role": "system", "content": prompt}]
|
| 53 |
+
|
| 54 |
+
def think(self, user_input: str, tools: List[Dict]) -> Dict:
|
| 55 |
+
"""
|
| 56 |
+
DeepSeek 决策: 返回 JSON {action, tool, args} 或 {action: "reply", content}
|
| 57 |
+
"""
|
| 58 |
+
if self.mode == "api":
|
| 59 |
+
return self._think_api(user_input, tools)
|
| 60 |
+
else:
|
| 61 |
+
return self._think_local(user_input, tools)
|
| 62 |
+
|
| 63 |
+
def _think_api(self, user_input: str, tools: List[Dict]) -> Dict:
|
| 64 |
+
"""API 模式 (OpenAI 兼容)"""
|
| 65 |
+
import urllib.request
|
| 66 |
+
|
| 67 |
+
self.conversation.append({"role": "user", "content": user_input})
|
| 68 |
+
payload = {
|
| 69 |
+
"model": self.model,
|
| 70 |
+
"messages": self.conversation,
|
| 71 |
+
"tools": tools,
|
| 72 |
+
"tool_choice": "auto",
|
| 73 |
+
"stream": False,
|
| 74 |
+
}
|
| 75 |
+
req = urllib.request.Request(
|
| 76 |
+
f"{self.base_url}/chat/completions",
|
| 77 |
+
data=json.dumps(payload).encode(),
|
| 78 |
+
headers={
|
| 79 |
+
"Content-Type": "application/json",
|
| 80 |
+
"Authorization": f"Bearer {self.api_key}",
|
| 81 |
+
},
|
| 82 |
+
)
|
| 83 |
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
| 84 |
+
data = json.loads(resp.read().decode())
|
| 85 |
+
|
| 86 |
+
msg = data["choices"][0]["message"]
|
| 87 |
+
self.conversation.append(msg)
|
| 88 |
+
|
| 89 |
+
# 解析工具调用
|
| 90 |
+
if msg.get("tool_calls"):
|
| 91 |
+
tc = msg["tool_calls"][0]
|
| 92 |
+
return {
|
| 93 |
+
"action": "tool",
|
| 94 |
+
"tool": tc["function"]["name"],
|
| 95 |
+
"args": json.loads(tc["function"]["arguments"] or "{}"),
|
| 96 |
+
}
|
| 97 |
+
return {"action": "reply", "content": msg.get("content", "")}
|
| 98 |
+
|
| 99 |
+
def _think_local(self, user_input: str, tools: List[Dict]) -> Dict:
|
| 100 |
+
"""本地模式 (L40S + V2-Lite, 待实现真实推理)"""
|
| 101 |
+
# TODO: 接入 agentframe 的本地推理 (KV 优化)
|
| 102 |
+
# 目前返回占位, 等 GPU 开机实现
|
| 103 |
+
return {"action": "reply", "content": "[本地模式待实现 - 需 GPU]"}
|
| 104 |
+
|
| 105 |
+
def remember_tool_result(self, result: str):
|
| 106 |
+
"""把工具结果追加到对话 (供下轮决策)"""
|
| 107 |
+
self.conversation.append({"role": "tool", "content": result})
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
# ============================================================
|
| 111 |
+
# 2. Hands: OpenClaw 工具桥
|
| 112 |
+
# ============================================================
|
| 113 |
+
|
| 114 |
+
class OpenClawHands:
|
| 115 |
+
"""
|
| 116 |
+
OpenClaw 工具执行桥 (调用 gateway 的 exec/browser)
|
| 117 |
+
通过 subprocess 调用 openclaw CLI, 或直接调用系统命令
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
def __init__(self, workspace: str = "/root/.openclaw/workspace"):
|
| 121 |
+
self.workspace = workspace
|
| 122 |
+
|
| 123 |
+
def exec(self, command: str, timeout: int = 30) -> Dict:
|
| 124 |
+
"""执行 shell 命令 (OpenClaw exec 能力)"""
|
| 125 |
+
try:
|
| 126 |
+
result = subprocess.run(
|
| 127 |
+
command,
|
| 128 |
+
shell=True,
|
| 129 |
+
capture_output=True,
|
| 130 |
+
text=True,
|
| 131 |
+
timeout=timeout,
|
| 132 |
+
cwd=self.workspace,
|
| 133 |
+
)
|
| 134 |
+
return {
|
| 135 |
+
"success": result.returncode == 0,
|
| 136 |
+
"stdout": result.stdout[:2000],
|
| 137 |
+
"stderr": result.stderr[:500],
|
| 138 |
+
"exit_code": result.returncode,
|
| 139 |
+
}
|
| 140 |
+
except subprocess.TimeoutExpired:
|
| 141 |
+
return {"success": False, "stdout": "", "stderr": "timeout", "exit_code": -1}
|
| 142 |
+
|
| 143 |
+
def read_file(self, path: str) -> str:
|
| 144 |
+
"""读文件"""
|
| 145 |
+
return self.exec(f"cat {path}")["stdout"]
|
| 146 |
+
|
| 147 |
+
def write_file(self, path: str, content: str) -> bool:
|
| 148 |
+
"""写文件"""
|
| 149 |
+
import base64
|
| 150 |
+
b64 = base64.b64encode(content.encode()).decode()
|
| 151 |
+
result = self.exec(f"echo '{b64}' | base64 -d > {path}")
|
| 152 |
+
return result["success"]
|
| 153 |
+
|
| 154 |
+
def browser_open(self, url: str) -> Dict:
|
| 155 |
+
"""浏览器打开网页"""
|
| 156 |
+
result = self.exec(f"openclaw browser --browser-profile openclaw open {url}")
|
| 157 |
+
return {"success": result["success"], "note": "browser opened"}
|
| 158 |
+
|
| 159 |
+
def browser_snapshot(self) -> str:
|
| 160 |
+
"""浏览器快照"""
|
| 161 |
+
result = self.exec("openclaw browser --browser-profile openclaw snapshot")
|
| 162 |
+
return result["stdout"]
|
| 163 |
+
|
| 164 |
+
def list_tools(self) -> List[str]:
|
| 165 |
+
"""可用工具清单"""
|
| 166 |
+
return ["exec", "read_file", "write_file", "browser_open", "browser_snapshot"]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ============================================================
|
| 170 |
+
# 3. Memory: KV 记忆集成 (前缀缓存池)
|
| 171 |
+
# ============================================================
|
| 172 |
+
|
| 173 |
+
class AgentMemory:
|
| 174 |
+
"""Agent 记忆: 复用 agentframe_core 的前缀池 + 分层量化"""
|
| 175 |
+
|
| 176 |
+
def __init__(self, system_prompt: str, prompt_tokens: int = 3000):
|
| 177 |
+
from agentframe_core import PrefixPool, SessionManager, AbsorbedMLAEncoder
|
| 178 |
+
self.pool = PrefixPool()
|
| 179 |
+
self.sessions = SessionManager(self.pool)
|
| 180 |
+
self.encoder = AbsorbedMLAEncoder()
|
| 181 |
+
self.system_prompt = system_prompt
|
| 182 |
+
# 创建主会话
|
| 183 |
+
self.session = self.sessions.create_session(
|
| 184 |
+
"agent-main", system_prompt, prompt_tokens
|
| 185 |
+
)
|
| 186 |
+
self.history: List[Dict] = []
|
| 187 |
+
|
| 188 |
+
def record(self, role: str, content: str, layer_idx: int = 0):
|
| 189 |
+
"""记录对话/工具结果到记忆 (分层量化)"""
|
| 190 |
+
import numpy as np
|
| 191 |
+
# 模拟 KV 写入: 思考用 INT8, 工具结果用 INT4
|
| 192 |
+
fake_kv = np.random.randn(1, 8, self.encoder.kv_rank)
|
| 193 |
+
if role == "thought":
|
| 194 |
+
kv = self.encoder.encode_thought(fake_kv)
|
| 195 |
+
else:
|
| 196 |
+
kv = self.encoder.encode_tool_result(fake_kv)
|
| 197 |
+
self.sessions.append_tool_result(self.session, layer_idx, kv)
|
| 198 |
+
self.history.append({"role": role, "content": content[:500]})
|
| 199 |
+
|
| 200 |
+
def memory_report(self) -> Dict:
|
| 201 |
+
return self.sessions.session_memory(self.session)
|
| 202 |
+
|
| 203 |
+
def close(self):
|
| 204 |
+
self.sessions.close_session("agent-main")
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# ============================================================
|
| 208 |
+
# 4. Loop: Agent 主循环
|
| 209 |
+
# ============================================================
|
| 210 |
+
|
| 211 |
+
class AgentLoop:
|
| 212 |
+
"""Agent 执行循环: 思考 → 行动 → 观察 → 循环"""
|
| 213 |
+
|
| 214 |
+
def __init__(self, brain: DeepSeekBrain, hands: OpenClawHands, memory: AgentMemory):
|
| 215 |
+
self.brain = brain
|
| 216 |
+
self.hands = hands
|
| 217 |
+
self.memory = memory
|
| 218 |
+
self.max_steps = 10
|
| 219 |
+
|
| 220 |
+
def _tool_schemas(self) -> List[Dict]:
|
| 221 |
+
"""给 DeepSeek 的工具定义 (OpenClaw 能力)"""
|
| 222 |
+
return [
|
| 223 |
+
{
|
| 224 |
+
"type": "function",
|
| 225 |
+
"function": {
|
| 226 |
+
"name": "exec",
|
| 227 |
+
"description": "执行 shell 命令",
|
| 228 |
+
"parameters": {
|
| 229 |
+
"type": "object",
|
| 230 |
+
"properties": {
|
| 231 |
+
"command": {"type": "string", "description": "要执行的命令"}
|
| 232 |
+
},
|
| 233 |
+
"required": ["command"],
|
| 234 |
+
},
|
| 235 |
+
},
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"type": "function",
|
| 239 |
+
"function": {
|
| 240 |
+
"name": "browser_open",
|
| 241 |
+
"description": "打开网页",
|
| 242 |
+
"parameters": {
|
| 243 |
+
"type": "object",
|
| 244 |
+
"properties": {
|
| 245 |
+
"url": {"type": "string", "description": "网页地址"}
|
| 246 |
+
},
|
| 247 |
+
"required": ["url"],
|
| 248 |
+
},
|
| 249 |
+
},
|
| 250 |
+
},
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
def run(self, task: str) -> str:
|
| 254 |
+
"""执行一个任务"""
|
| 255 |
+
self.brain.set_system_prompt(self.memory.system_prompt)
|
| 256 |
+
self.memory.record("user", task)
|
| 257 |
+
|
| 258 |
+
for step in range(self.max_steps):
|
| 259 |
+
print(f"\n[Step {step+1}] 🧠 DeepSeek 思考中...")
|
| 260 |
+
self.memory.record("thought", f"step {step+1}")
|
| 261 |
+
|
| 262 |
+
decision = self.brain.think(task, self._tool_schemas())
|
| 263 |
+
|
| 264 |
+
if decision["action"] == "reply":
|
| 265 |
+
print(f" 💬 Agent: {decision['content']}")
|
| 266 |
+
return decision["content"]
|
| 267 |
+
|
| 268 |
+
if decision["action"] == "tool":
|
| 269 |
+
tool = decision["tool"]
|
| 270 |
+
args = decision["args"]
|
| 271 |
+
print(f" 🛠 调用 {tool}({args})")
|
| 272 |
+
|
| 273 |
+
# 执行工具
|
| 274 |
+
if tool == "exec":
|
| 275 |
+
result = self.hands.exec(args.get("command", ""))
|
| 276 |
+
elif tool == "browser_open":
|
| 277 |
+
result = self.hands.browser_open(args.get("url", ""))
|
| 278 |
+
else:
|
| 279 |
+
result = {"success": False, "stdout": f"未知工具 {tool}"}
|
| 280 |
+
|
| 281 |
+
# 记录结果 (工具结果 → INT4 压缩)
|
| 282 |
+
result_str = json.dumps(result, ensure_ascii=False)[:500]
|
| 283 |
+
self.memory.record("tool_result", result_str)
|
| 284 |
+
self.brain.remember_tool_result(result_str)
|
| 285 |
+
task = result_str # 下一轮基于结果继续
|
| 286 |
+
|
| 287 |
+
return "[达到最大步数,任务未完成]"
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
# ============================================================
|
| 291 |
+
# 5. 演示
|
| 292 |
+
# ============================================================
|
| 293 |
+
|
| 294 |
+
if __name__ == "__main__":
|
| 295 |
+
print("=" * 60)
|
| 296 |
+
print("AgentFrame 编排层 演示 (无 GPU 版)")
|
| 297 |
+
print("=" * 60)
|
| 298 |
+
|
| 299 |
+
# 1. 组装
|
| 300 |
+
sys_prompt = """你是智能助手,可以操控电脑完成任务。
|
| 301 |
+
你有以下工具:
|
| 302 |
+
- exec: 执行 shell 命令
|
| 303 |
+
- browser_open: 打开网页
|
| 304 |
+
请根据用户需求,一步步完成任务。每次只调用一个工具,观察结果后再决定下一步。"""
|
| 305 |
+
|
| 306 |
+
brain = DeepSeekBrain(mode="api", model="deepseek-chat", api_key="") # 无 key 时演示流程
|
| 307 |
+
hands = OpenClawHands()
|
| 308 |
+
memory = AgentMemory(sys_prompt, prompt_tokens=3000)
|
| 309 |
+
|
| 310 |
+
# 2. 测试手的能力 (无需 GPU)
|
| 311 |
+
print("\n🖐 测试 OpenClaw 手:")
|
| 312 |
+
r = hands.exec("echo 'AgentFrame 就绪!' && ls /root/.openclaw/workspace/*.py | head -3")
|
| 313 |
+
print(f" exec: {'✅' if r['success'] else '❌'}")
|
| 314 |
+
print(f" → {r['stdout'][:100]}")
|
| 315 |
+
|
| 316 |
+
# 3. 测试记忆 (前缀池)
|
| 317 |
+
print("\n🧠 测试记忆 (前缀缓存池):")
|
| 318 |
+
memory.record("thought", "分析任务")
|
| 319 |
+
memory.record("tool_result", "ls 输出: agentframe_core.py, agentframe_orchestrator.py")
|
| 320 |
+
rep = memory.memory_report()
|
| 321 |
+
print(f" 前缀引用数: {rep['prefix_refs']}")
|
| 322 |
+
print(f" 增量内存: {rep['incremental_bytes']/1024:.0f}KB")
|
| 323 |
+
|
| 324 |
+
# 4. Agent 循环 (无 API key 时走 reply 占位)
|
| 325 |
+
print("\n🤖 Agent 循环:")
|
| 326 |
+
loop = AgentLoop(brain, hands, memory)
|
| 327 |
+
# 用本地模式跑流程 (不真正调 API)
|
| 328 |
+
brain.mode = "local"
|
| 329 |
+
result = loop.run("查看当前目录有什么文件")
|
| 330 |
+
print(f" 结果: {result}")
|
| 331 |
+
|
| 332 |
+
print("\n✅ AgentFrame 编排层骨架验证完成")
|
| 333 |
+
print(" (真实 DeepSeek 推理需 GPU 开机后接入)")
|