MCPcopy Create free account
hub / github.com/astercloud/aster / loopExample

Function loopExample

examples/workflow-agents/main.go:115–163  ·  view source on GitHub ↗

loopExample 循环优化示例

(ctx context.Context)

Source from the content-addressed store, hash-verified

113
114// loopExample 循环优化示例
115func 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 嵌套工作流示例
166func nestedExample(ctx context.Context) {

Callers 1

mainFunction · 0.85

Calls 6

ExecuteMethod · 0.95
NewLoopAgentFunction · 0.92
NewMockAgentFunction · 0.85
printEventFunction · 0.85
RecvMethod · 0.80
PrintfMethod · 0.80

Tested by

no test coverage detected