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

Function runOnce

examples/openrouter/main.go:90–127  ·  view source on GitHub ↗

runOnce 非交互模式:执行单次对话并退出

(ctx context.Context, ag *agent.Agent, prompt string)

Source from the content-addressed store, hash-verified

88
89// runOnce 非交互模式:执行单次对话并退出
90func runOnce(ctx context.Context, ag *agent.Agent, prompt string) error {
91 // 订阅事件以捕获文本输出
92 var textOutput strings.Builder
93 eventCh := ag.Subscribe([]types.AgentChannel{types.ChannelProgress}, nil)
94
95 done := make(chan struct{})
96 go func() {
97 for envelope := range eventCh {
98 switch e := envelope.Event.(type) {
99 case *types.ProgressTextChunkEvent:
100 textOutput.WriteString(e.Delta)
101 }
102 }
103 close(done)
104 }()
105
106 result, err := ag.Chat(ctx, prompt)
107 ag.Unsubscribe(eventCh)
108 <-done
109
110 if err != nil {
111 return fmt.Errorf("对话失败: %w", err)
112 }
113
114 // 优先使用事件流收集的文本,其次使用 result.Text
115 output := textOutput.String()
116 if output == "" {
117 output = result.Text
118 }
119
120 if output != "" {
121 fmt.Println(output)
122 } else {
123 fmt.Println("[完成]")
124 }
125
126 return nil
127}
128
129// runInteractive 交互模式:REPL 循环
130func runInteractive(ctx context.Context, ag *agent.Agent) error {

Callers 1

runFunction · 0.85

Calls 4

SubscribeMethod · 0.65
UnsubscribeMethod · 0.65
ChatMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected