Execute 并行执行所有子 Agent
(ctx context.Context, message string)
| 67 | |
| 68 | // Execute 并行执行所有子 Agent |
| 69 | func (a *ParallelAgent) Execute(ctx context.Context, message string) *stream.Reader[*session.Event] { |
| 70 | reader, writer := stream.Pipe[*session.Event](len(a.subAgents) * 10) |
| 71 | |
| 72 | go func() { |
| 73 | defer writer.Close() |
| 74 | |
| 75 | var ( |
| 76 | eg, egCtx = errgroup.WithContext(ctx) |
| 77 | resultsCh = make(chan result, len(a.subAgents)*10) // 缓冲通道 |
| 78 | doneCh = make(chan struct{}) |
| 79 | ) |
| 80 | |
| 81 | // 启动所有子 Agent |
| 82 | for i, subAgent := range a.subAgents { |
| 83 | sa := subAgent |
| 84 | branch := fmt.Sprintf("%s.%s", a.name, sa.Name()) |
| 85 | index := i |
| 86 | |
| 87 | eg.Go(func() error { |
| 88 | return a.runSubAgent(egCtx, sa, branch, index, message, resultsCh, doneCh) |
| 89 | }) |
| 90 | } |
| 91 | |
| 92 | // 等待所有子 Agent 完成 |
| 93 | go func() { |
| 94 | _ = eg.Wait() // 错误已通过 resultsCh 传递 |
| 95 | close(resultsCh) |
| 96 | }() |
| 97 | |
| 98 | // 流式返回结果 |
| 99 | defer close(doneCh) |
| 100 | |
| 101 | for res := range resultsCh { |
| 102 | if writer.Send(res.event, res.err) { |
| 103 | return // 客户端取消 |
| 104 | } |
| 105 | } |
| 106 | }() |
| 107 | |
| 108 | return reader |
| 109 | } |
| 110 | |
| 111 | // runSubAgent 运行单个子 Agent |
| 112 | func (a *ParallelAgent) runSubAgent( |
no test coverage detected