()
| 14 | ) |
| 15 | |
| 16 | func main() { |
| 17 | fmt.Println("=== SubAgent 异步执行示例 ===") |
| 18 | fmt.Println() |
| 19 | |
| 20 | // 1. 创建 Backend |
| 21 | backend := backends.NewStateBackend() |
| 22 | fmt.Println("✓ 创建 StateBackend") |
| 23 | |
| 24 | // 2. 定义子代理规格 |
| 25 | specs := []middleware.SubAgentSpec{ |
| 26 | { |
| 27 | Name: "researcher", |
| 28 | Description: "深度研究和分析专家", |
| 29 | Prompt: "你是一个专注于深度研究的 AI。仔细分析问题,提供详细的研究报告。", |
| 30 | }, |
| 31 | { |
| 32 | Name: "data-analyst", |
| 33 | Description: "数据分析专家", |
| 34 | Prompt: "你是一个数据分析专家。处理和分析大量数据,生成洞察报告。", |
| 35 | }, |
| 36 | } |
| 37 | fmt.Printf("✓ 定义了 %d 个子代理规格\n", len(specs)) |
| 38 | |
| 39 | // 3. 创建子代理工厂(模拟长时间运行的任务) |
| 40 | factory := func(ctx context.Context, spec middleware.SubAgentSpec) (middleware.SubAgent, error) { |
| 41 | execFn := func(ctx context.Context, description string, parentContext map[string]any) (string, error) { |
| 42 | // 模拟长时间运行的任务 |
| 43 | fmt.Printf("[%s] 开始执行任务: %s\n", spec.Name, description) |
| 44 | time.Sleep(5 * time.Second) // 模拟5秒的处理时间 |
| 45 | |
| 46 | result := fmt.Sprintf(`[%s] 任务完成报告 |
| 47 | 任务描述: %s |
| 48 | 执行时间: 5秒 |
| 49 | 系统提示: %s |
| 50 | 上下文: %v |
| 51 | |
| 52 | 分析结果: |
| 53 | 1. 任务已成功完成 |
| 54 | 2. 处理了大量数据 |
| 55 | 3. 生成了详细报告`, spec.Name, description, spec.Prompt, parentContext) |
| 56 | |
| 57 | fmt.Printf("[%s] 任务完成\n", spec.Name) |
| 58 | return result, nil |
| 59 | } |
| 60 | return middleware.NewSimpleSubAgent(spec.Name, spec.Prompt, execFn), nil |
| 61 | } |
| 62 | fmt.Println("✓ 创建子代理工厂") |
| 63 | |
| 64 | // 4. 创建 SubAgentMiddleware(启用异步执行) |
| 65 | subagentMiddleware, err := middleware.NewSubAgentMiddleware(&middleware.SubAgentMiddlewareConfig{ |
| 66 | Specs: specs, |
| 67 | Factory: factory, |
| 68 | EnableParallel: true, |
| 69 | EnableAsync: true, // 启用异步执行 |
| 70 | EnableProcessIsolation: false, // 使用 goroutine 模式(演示用) |
| 71 | DefaultTimeout: 30 * time.Second, |
| 72 | }) |
| 73 | if err != nil { |
nothing calls this directly
no test coverage detected