loopExample 循环优化示例
(ctx context.Context)
| 113 | |
| 114 | // loopExample 循环优化示例 |
| 115 | func loopExample(ctx context.Context) { |
| 116 | // 创建优化流程的子 Agent |
| 117 | agents := []workflow.Agent{ |
| 118 | NewMockAgent("Critic", "评估当前方案"), |
| 119 | NewMockAgent("Improver", "提出改进建议"), |
| 120 | } |
| 121 | |
| 122 | // 创建 LoopAgent(最多 3 次迭代) |
| 123 | loop, err := workflow.NewLoopAgent(workflow.LoopConfig{ |
| 124 | Name: "OptimizationLoop", |
| 125 | SubAgents: agents, |
| 126 | MaxIterations: 3, |
| 127 | StopCondition: func(event *session.Event) bool { |
| 128 | // 如果评分达到 90 分,提前停止 |
| 129 | if score, ok := event.Metadata["quality_score"].(int); ok { |
| 130 | return score >= 90 |
| 131 | } |
| 132 | return false |
| 133 | }, |
| 134 | }) |
| 135 | if err != nil { |
| 136 | log.Fatal(err) |
| 137 | } |
| 138 | |
| 139 | // 执行 |
| 140 | fmt.Println("开始循环优化:") |
| 141 | iteration := 0 |
| 142 | reader := loop.Execute(ctx, "优化代码质量") |
| 143 | for { |
| 144 | event, err := reader.Recv() |
| 145 | if err != nil { |
| 146 | if errors.Is(err, io.EOF) { |
| 147 | break |
| 148 | } |
| 149 | log.Printf("错误: %v", err) |
| 150 | break |
| 151 | } |
| 152 | |
| 153 | // 追踪迭代次数 |
| 154 | if iterNum, ok := event.Metadata["loop_iteration"].(uint); ok { |
| 155 | if uint(iteration) != iterNum { |
| 156 | iteration = int(iterNum) |
| 157 | fmt.Printf("\n--- 迭代 %d ---\n", iteration) |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | printEvent(event) |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | // nestedExample 嵌套工作流示例 |
| 166 | func nestedExample(ctx context.Context) { |
no test coverage detected