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HuggingFace Spaces Demo
|
| 5 |
+
展示 PES (Plan-Execute-Summary) 进化式 Agent 工作流程
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import gradio as gr
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
import random
|
| 12 |
+
from typing import List, Dict, Any
|
| 13 |
+
|
| 14 |
+
# ============================================================================
|
| 15 |
+
# PES 工作流程模拟
|
| 16 |
+
# ============================================================================
|
| 17 |
+
|
| 18 |
+
def simulate_planner(task: str) -> Dict[str, Any]:
|
| 19 |
+
"""模拟 Planner 阶段的思考过程"""
|
| 20 |
+
time.sleep(0.5)
|
| 21 |
+
|
| 22 |
+
strategies = [
|
| 23 |
+
"我将把任务分解为多个子目标,逐步实现每个目标。",
|
| 24 |
+
"首先分析任务需求,然后设计实现方案,最后进行代码编写。",
|
| 25 |
+
"采用迭代式方法,从简单版本开始,逐步添加复杂功能。",
|
| 26 |
+
"我将使用分治策略,将大问题分解为小问题解决。",
|
| 27 |
+
]
|
| 28 |
+
|
| 29 |
+
return {
|
| 30 |
+
"role": "Planner",
|
| 31 |
+
"thought": random.choice(strategies),
|
| 32 |
+
"plan": f"""
|
| 33 |
+
## 任务分析
|
| 34 |
+
- 用户需求: {task}
|
| 35 |
+
|
| 36 |
+
## 执行计划
|
| 37 |
+
1. 理解任务要求
|
| 38 |
+
2. 设计解决方案
|
| 39 |
+
3. 编写代码实现
|
| 40 |
+
4. 测试验证功能
|
| 41 |
+
""".strip(),
|
| 42 |
+
"timestamp": time.strftime("%H:%M:%S")
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def simulate_executor(task: str, plan: str) -> Dict[str, Any]:
|
| 47 |
+
"""模拟 Executor 阶段的执行过程"""
|
| 48 |
+
time.sleep(0.8)
|
| 49 |
+
|
| 50 |
+
code_samples = {
|
| 51 |
+
"todo": '''```python
|
| 52 |
+
# Todo List App
|
| 53 |
+
class TodoList:
|
| 54 |
+
def __init__(self):
|
| 55 |
+
self.tasks = []
|
| 56 |
+
|
| 57 |
+
def add_task(self, title):
|
| 58 |
+
self.tasks.append({"title": title, "done": False})
|
| 59 |
+
|
| 60 |
+
def complete_task(self, index):
|
| 61 |
+
self.tasks[index]["done"] = True
|
| 62 |
+
```''',
|
| 63 |
+
"file": '''```python
|
| 64 |
+
# File Processor
|
| 65 |
+
import os
|
| 66 |
+
import shutil
|
| 67 |
+
|
| 68 |
+
def process_files(input_dir, output_dir):
|
| 69 |
+
for filename in os.listdir(input_dir):
|
| 70 |
+
src = os.path.join(input_dir, filename)
|
| 71 |
+
dst = os.path.join(output_dir, filename)
|
| 72 |
+
shutil.copy2(src, dst)
|
| 73 |
+
```''',
|
| 74 |
+
"default": '''```python
|
| 75 |
+
# Solution Implementation
|
| 76 |
+
def solve_task(task):
|
| 77 |
+
# 分析任务
|
| 78 |
+
analysis = analyze(task)
|
| 79 |
+
|
| 80 |
+
# 设计方案
|
| 81 |
+
solution = design(analysis)
|
| 82 |
+
|
| 83 |
+
# 实现代码
|
| 84 |
+
code = implement(solution)
|
| 85 |
+
|
| 86 |
+
# 返回结果
|
| 87 |
+
return execute(code)
|
| 88 |
+
```'''
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
code = code_samples.get("default")
|
| 92 |
+
for key, c in code_samples.items():
|
| 93 |
+
if key in task.lower():
|
| 94 |
+
code = c
|
| 95 |
+
break
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
"role": "Executor",
|
| 99 |
+
"action": "编写并执行代码",
|
| 100 |
+
"code": code,
|
| 101 |
+
"result": "代码执行成功,所有测试通过 ✓",
|
| 102 |
+
"timestamp": time.strftime("%H:%M:%S")
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def simulate_summary(iteration: int, score: float) -> Dict[str, Any]:
|
| 107 |
+
"""模拟 Summary 阶段的反思过程"""
|
| 108 |
+
time.sleep(0.3)
|
| 109 |
+
|
| 110 |
+
reflections = [
|
| 111 |
+
"本次迭代成功实现了核心功能,但还有优化空间。",
|
| 112 |
+
"代码结构良好,可以进一步简化逻辑。",
|
| 113 |
+
"测试覆盖完整,建议增加边界情况处理。",
|
| 114 |
+
"性能表现良好,可以考虑添加缓存机制。",
|
| 115 |
+
]
|
| 116 |
+
|
| 117 |
+
improvements = [
|
| 118 |
+
"建议优化代码结构,提高可读性",
|
| 119 |
+
"可以添加更多的错误处理",
|
| 120 |
+
"考虑性能优化和资源管理",
|
| 121 |
+
"建议增加单元测试覆盖",
|
| 122 |
+
]
|
| 123 |
+
|
| 124 |
+
new_score = min(1.0, score + random.uniform(0.05, 0.15))
|
| 125 |
+
|
| 126 |
+
return {
|
| 127 |
+
"role": "Summary",
|
| 128 |
+
"reflection": random.choice(reflections),
|
| 129 |
+
"improvement": random.choice(improvements),
|
| 130 |
+
"score": new_score,
|
| 131 |
+
"timestamp": time.strftime("%H:%M:%S")
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def run_pes_iteration(task: str, iteration: int, current_score: float) -> List[Dict[str, Any]]:
|
| 136 |
+
"""运行一次完整的 PES 迭代"""
|
| 137 |
+
results = []
|
| 138 |
+
|
| 139 |
+
# Phase 1: Plan
|
| 140 |
+
planner_result = simulate_planner(task)
|
| 141 |
+
results.append({
|
| 142 |
+
"phase": "📋 Plan (计划)",
|
| 143 |
+
"content": planner_result["thought"],
|
| 144 |
+
"detail": planner_result["plan"],
|
| 145 |
+
"timestamp": planner_result["timestamp"]
|
| 146 |
+
})
|
| 147 |
+
|
| 148 |
+
# Phase 2: Execute
|
| 149 |
+
executor_result = simulate_executor(task, planner_result["plan"])
|
| 150 |
+
results.append({
|
| 151 |
+
"phase": "⚡ Execute (执行)",
|
| 152 |
+
"content": executor_result["action"],
|
| 153 |
+
"detail": f"{executor_result['code']}\n\n**执行结果**: {executor_result['result']}",
|
| 154 |
+
"timestamp": executor_result["timestamp"]
|
| 155 |
+
})
|
| 156 |
+
|
| 157 |
+
# Phase 3: Summary
|
| 158 |
+
summary_result = simulate_summary(iteration, current_score)
|
| 159 |
+
results.append({
|
| 160 |
+
"phase": "📊 Summary (总结)",
|
| 161 |
+
"content": summary_result["reflection"],
|
| 162 |
+
"detail": f"**改进建议**: {summary_result['improvement']}\n\n**当前分数**: {summary_result['score']:.2f}",
|
| 163 |
+
"timestamp": summary_result["timestamp"]
|
| 164 |
+
})
|
| 165 |
+
|
| 166 |
+
return results, summary_result["score"]
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
# ============================================================================
|
| 170 |
+
# Gradio UI
|
| 171 |
+
# ============================================================================
|
| 172 |
+
|
| 173 |
+
def create_demo():
|
| 174 |
+
"""创建 Gradio 界面"""
|
| 175 |
+
|
| 176 |
+
with gr.Blocks(title="LoongFlow PES Demo", theme=gr.themes.Soft()) as demo:
|
| 177 |
+
gr.Markdown("""
|
| 178 |
+
# 🐉 LoongFlow PES Agent Demo
|
| 179 |
+
|
| 180 |
+
**LoongFlow** 是一个进化式 Agent 开发框架,采用 **PES (Plan-Execute-Summary)** 思考范式。
|
| 181 |
+
|
| 182 |
+
这个 Demo 展示了一个 Agent 如何通过计划-执行-总结的循环来解决问题,并逐步改进解决方案。
|
| 183 |
+
|
| 184 |
+
---
|
| 185 |
+
|
| 186 |
+
### PES 工作流程
|
| 187 |
+
|
| 188 |
+
```
|
| 189 |
+
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
|
| 190 |
+
│ Plan │────▶│ Execute │────▶│ Summary │
|
| 191 |
+
│ (计划) │ │ (执行) │ │ (总结) │
|
| 192 |
+
└─────────────┘ └─────────────┘ └─────────────┘
|
| 193 |
+
│ │
|
| 194 |
+
│ 迭代改进 ◀───────────────────┘
|
| 195 |
+
│
|
| 196 |
+
┌─────────────┐
|
| 197 |
+
│ 目标达成 │
|
| 198 |
+
└─────────────┘
|
| 199 |
+
```
|
| 200 |
+
""")
|
| 201 |
+
|
| 202 |
+
with gr.Row():
|
| 203 |
+
with gr.Column(scale=2):
|
| 204 |
+
task_input = gr.Textbox(
|
| 205 |
+
label="输入任务描述",
|
| 206 |
+
placeholder="例如: 帮我写一个待办事项应用 / 创建一个文件处理工具",
|
| 207 |
+
lines=3
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
with gr.Row():
|
| 211 |
+
max_iterations = gr.Slider(
|
| 212 |
+
minimum=1, maximum=10, value=5, step=1,
|
| 213 |
+
label="最大迭代次数"
|
| 214 |
+
)
|
| 215 |
+
target_score = gr.Slider(
|
| 216 |
+
minimum=0.5, maximum=1.0, value=0.85, step=0.05,
|
| 217 |
+
label="目标分数"
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
run_btn = gr.Button("🚀 开始执行任务", variant="primary")
|
| 221 |
+
|
| 222 |
+
with gr.Column(scale=1):
|
| 223 |
+
status_output = gr.JSON(
|
| 224 |
+
label="执行状态",
|
| 225 |
+
visible=False
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
with gr.Row():
|
| 229 |
+
score_chart = gr.LinePlot(
|
| 230 |
+
label="分数演进",
|
| 231 |
+
x="iteration",
|
| 232 |
+
y="score",
|
| 233 |
+
height=300
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
with gr.Accordion("📝 迭代详情", open=True):
|
| 237 |
+
iteration_output = gr.JSON(
|
| 238 |
+
label="迭代历史",
|
| 239 |
+
elem_id="iteration-output"
|
| 240 |
+
)
|
| 241 |
+
|
| 242 |
+
# 状态变量
|
| 243 |
+
iterations_data = []
|
| 244 |
+
|
| 245 |
+
def run_task(task: str, max_iter: int, target: float):
|
| 246 |
+
if not task.strip():
|
| 247 |
+
yield {"error": "请输入任务描述"}, [], gr.update()
|
| 248 |
+
return
|
| 249 |
+
|
| 250 |
+
iterations_data.clear()
|
| 251 |
+
yield {"status": "开始执行任务...", "task": task}, [], gr.update()
|
| 252 |
+
|
| 253 |
+
current_score = 0.0
|
| 254 |
+
all_results = []
|
| 255 |
+
|
| 256 |
+
for i in range(1, max_iter + 1):
|
| 257 |
+
yield {
|
| 258 |
+
"status": f"正在执行第 {i} 次迭代...",
|
| 259 |
+
"iteration": i,
|
| 260 |
+
"score": current_score
|
| 261 |
+
}, [], gr.update(visible=True)
|
| 262 |
+
|
| 263 |
+
results, current_score = run_pes_iteration(task, i, current_score)
|
| 264 |
+
all_results.extend(results)
|
| 265 |
+
|
| 266 |
+
# 更新图表数据
|
| 267 |
+
iterations_data.append({"iteration": i, "score": current_score})
|
| 268 |
+
|
| 269 |
+
yield {
|
| 270 |
+
"status": f"第 {i} 次迭代完成",
|
| 271 |
+
"iteration": i,
|
| 272 |
+
"score": current_score
|
| 273 |
+
}, all_results, gr.update(
|
| 274 |
+
value=iterations_data,
|
| 275 |
+
visible=True
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# 检查是否达到目标
|
| 279 |
+
if current_score >= target:
|
| 280 |
+
break
|
| 281 |
+
|
| 282 |
+
time.sleep(0.5)
|
| 283 |
+
|
| 284 |
+
final_status = {
|
| 285 |
+
"status": "任务完成" if current_score >= target else "达到最大迭代",
|
| 286 |
+
"final_score": current_score,
|
| 287 |
+
"iterations": len(iterations_data)
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
yield final_status, all_results, gr.update(
|
| 291 |
+
value=iterations_data,
|
| 292 |
+
visible=True
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
run_btn.click(
|
| 296 |
+
fn=run_task,
|
| 297 |
+
inputs=[task_input, max_iterations, target_score],
|
| 298 |
+
outputs=[status_output, iteration_output, score_chart]
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
gr.Markdown("""
|
| 302 |
+
---
|
| 303 |
+
|
| 304 |
+
### 关于 LoongFlow
|
| 305 |
+
|
| 306 |
+
LoongFlow 是一个面向复杂任务的进化式 Agent 框架,特别适用于:
|
| 307 |
+
|
| 308 |
+
- 📐 **数学推理**: 开放式数学问题求解
|
| 309 |
+
- 🤖 **机器学习**: AutoML 和算法优化
|
| 310 |
+
- 💻 **代码生成**: 复杂编程任务
|
| 311 |
+
- 🔬 **科学研究**: 实验设计和分析
|
| 312 |
+
|
| 313 |
+
了解更多: [GitHub](https://github.com/your-repo/loongflow)
|
| 314 |
+
""")
|
| 315 |
+
|
| 316 |
+
return demo
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
if __name__ == "__main__":
|
| 320 |
+
demo = create_demo()
|
| 321 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|