forked from trpc-group/trpc-agent-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
427 lines (381 loc) · 9.57 KB
/
Copy pathmain.go
File metadata and controls
427 lines (381 loc) · 9.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//
// Tencent is pleased to support the open source community by making
// trpc-agent-go available.
//
// Copyright (C) 2025 Tencent. All rights reserved.
//
// trpc-agent-go is licensed under the Apache License Version 2.0.
//
// Package main runs an OpenClaw runtime and consumes it via A2A.
package main
import (
"context"
"errors"
"flag"
"fmt"
"log"
"net"
"net/http"
"os"
"strings"
"time"
"trpc.group/trpc-go/trpc-agent-go/agent"
"trpc.group/trpc-go/trpc-agent-go/agent/a2aagent"
"trpc.group/trpc-go/trpc-agent-go/event"
"trpc.group/trpc-go/trpc-agent-go/model"
"trpc.group/trpc-go/trpc-agent-go/openclaw/app"
"trpc.group/trpc-go/trpc-agent-go/runner"
"trpc.group/trpc-go/trpc-agent-go/session/inmemory"
)
const (
defaultQuestion = "What's the weather in Shanghai today?"
defaultFollowUp = "What about tomorrow?"
defaultSkillsRoot = "./skills"
defaultA2ABase = "/a2a"
defaultA2AName = "openclaw-sandbox"
defaultA2ADesc = "Sandbox agent for bundled skills."
defaultInstruction = "For live weather or forecast questions, " +
"call skill_load for the weather skill before skill_run. " +
"Use the loaded weather skill instead of guessing current " +
"conditions."
weatherSkillName = "weather"
skillsLoadSession = "session"
openAIMode = "openai"
exampleRunnerName = "openclaw-a2a-example"
exampleAppName = "openclaw-a2a-example"
exampleUserID = "example-user"
exampleSessionID = "example-session"
startupTimeout = 15 * time.Second
requestTimeout = 150 * time.Second
shutdownWait = 5 * time.Second
pollInterval = 100 * time.Millisecond
)
var (
addrFlag = flag.String(
"addr",
"",
"HTTP listen address for OpenClaw (default random loopback port)",
)
skillsRootFlag = flag.String(
"skills-root",
defaultSkillsRoot,
"Path to the OpenClaw skills root",
)
stateDirFlag = flag.String(
"state-dir",
"",
"State dir for the embedded OpenClaw runtime",
)
modelFlag = flag.String(
"model",
"",
"Optional OpenAI model override",
)
baseURLFlag = flag.String(
"openai-base-url",
"",
"Optional OpenAI base URL override",
)
questionFlag = flag.String(
"question",
defaultQuestion,
"First user question sent through A2A",
)
followUpFlag = flag.String(
"follow-up",
defaultFollowUp,
"Optional follow-up question using the same session",
)
streamingFlag = flag.Bool(
"streaming",
true,
"Enable streaming on the OpenClaw A2A surface",
)
advertiseToolsFlag = flag.Bool(
"advertise-tools",
false,
"Advertise individual tools in the agent card",
)
)
func main() {
log.SetFlags(0)
flag.Parse()
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
listener, addr, err := listenLoopback(*addrFlag)
if err != nil {
return err
}
a2aURL := "http://" + addr + defaultA2ABase
stateDir, cleanupStateDir, err := resolveStateDir(*stateDirFlag)
if err != nil {
_ = listener.Close()
return err
}
if cleanupStateDir != nil {
defer cleanupStateDir()
}
configPath, cleanupConfig, err := writeConfigStub()
if err != nil {
_ = listener.Close()
return err
}
defer cleanupConfig()
rt, err := newRuntime(configPath, a2aURL, addr, stateDir)
if err != nil {
_ = listener.Close()
return err
}
defer func() {
_ = rt.Close()
}()
httpSrv := newHTTPServer(rt)
serveErr := make(chan error, 1)
go func() {
serveErr <- httpSrv.Serve(listener)
}()
defer shutdownServer(httpSrv)
if err := waitForReady(
context.Background(),
addr,
rt.A2A.AgentCardPath,
); err != nil {
return err
}
a2aAgent, err := a2aagent.New(
a2aagent.WithAgentCardURL(a2aURL),
)
if err != nil {
return fmt.Errorf("create a2a agent failed: %w", err)
}
card := a2aAgent.GetAgentCard()
if card == nil {
return errors.New("resolved a2a agent card is nil")
}
fmt.Printf("A2A URL: %s\n", a2aURL)
fmt.Printf("Agent: %s\n", card.Name)
fmt.Printf("Published skills: %d\n\n", len(card.Skills))
sessionSvc := inmemory.NewSessionService()
procRunner := runner.NewRunner(
exampleRunnerName,
a2aAgent,
runner.WithSessionService(sessionSvc),
)
defer procRunner.Close()
promptList := prompts()
for idx, prompt := range promptList {
answer, err := ask(procRunner, prompt)
if err != nil {
return err
}
fmt.Printf("Q%d: %s\n", idx+1, prompt)
fmt.Printf("A%d: %s\n\n", idx+1, answer)
}
if err := receiveServeErr(serveErr); err != nil {
return err
}
return nil
}
func newRuntime(
configPath string,
a2aURL string,
addr string,
stateDir string,
) (*app.Runtime, error) {
args := []string{
"-config", configPath,
"-mode", openAIMode,
"-http-addr", addr,
"-admin-enabled=false",
"-skills-root", *skillsRootFlag,
"-skills-allow-bundled", weatherSkillName,
"-skills-load-mode", skillsLoadSession,
"-agent-instruction", defaultInstruction,
"-state-dir", stateDir,
"-a2a",
"-a2a-host", a2aURL,
fmt.Sprintf("-a2a-streaming=%t", *streamingFlag),
fmt.Sprintf(
"-a2a-advertise-tools=%t",
*advertiseToolsFlag,
),
"-a2a-name", defaultA2AName,
"-a2a-description", defaultA2ADesc,
}
if trimmedModel := strings.TrimSpace(*modelFlag); trimmedModel != "" {
args = append(args, "-model", trimmedModel)
}
if trimmedBaseURL := strings.TrimSpace(*baseURLFlag); trimmedBaseURL != "" {
args = append(args, "-openai-base-url", trimmedBaseURL)
}
rt, err := app.NewRuntime(context.Background(), args)
if err != nil {
return nil, fmt.Errorf("create openclaw runtime failed: %w", err)
}
return rt, nil
}
func newHTTPServer(rt *app.Runtime) *http.Server {
mux := http.NewServeMux()
mux.Handle("/", rt.Gateway.Handler)
mux.Handle(rt.A2A.BasePath, rt.A2A.Handler)
mux.Handle(rt.A2A.BasePath+"/", rt.A2A.Handler)
return &http.Server{
Handler: mux,
ReadHeaderTimeout: shutdownWait,
}
}
func listenLoopback(rawAddr string) (net.Listener, string, error) {
addr := strings.TrimSpace(rawAddr)
if addr == "" {
addr = "127.0.0.1:0"
}
listener, err := net.Listen("tcp", addr)
if err != nil {
return nil, "", fmt.Errorf("listen on %s failed: %w", addr, err)
}
return listener, listener.Addr().String(), nil
}
func resolveStateDir(raw string) (string, func(), error) {
if trimmed := strings.TrimSpace(raw); trimmed != "" {
return trimmed, nil, nil
}
stateDir, err := os.MkdirTemp("", "openclaw-a2a-example-*")
if err != nil {
return "", nil, fmt.Errorf("create temp state dir failed: %w", err)
}
return stateDir, func() {
_ = os.RemoveAll(stateDir)
}, nil
}
func writeConfigStub() (string, func(), error) {
configFile, err := os.CreateTemp(
"",
"openclaw-a2a-example-*.yaml",
)
if err != nil {
return "", nil, fmt.Errorf("create temp config failed: %w", err)
}
content := []byte("app_name: \"" + exampleAppName + "\"\n")
if _, err := configFile.Write(content); err != nil {
_ = configFile.Close()
_ = os.Remove(configFile.Name())
return "", nil, fmt.Errorf("write temp config failed: %w", err)
}
if err := configFile.Close(); err != nil {
_ = os.Remove(configFile.Name())
return "", nil, fmt.Errorf("close temp config failed: %w", err)
}
return configFile.Name(), func() {
_ = os.Remove(configFile.Name())
}, nil
}
func waitForReady(
ctx context.Context,
addr string,
cardPath string,
) error {
deadline := time.Now().Add(startupTimeout)
url := "http://" + addr + cardPath
client := &http.Client{
Timeout: pollInterval,
}
for time.Now().Before(deadline) {
req, err := http.NewRequestWithContext(
ctx,
http.MethodGet,
url,
nil,
)
if err != nil {
return fmt.Errorf("build readiness request failed: %w", err)
}
resp, err := client.Do(req)
if err == nil {
_ = resp.Body.Close()
if resp.StatusCode == http.StatusOK {
return nil
}
} else if errors.Is(err, context.Canceled) ||
errors.Is(err, context.DeadlineExceeded) {
return err
}
time.Sleep(pollInterval)
}
return fmt.Errorf("a2a card was not ready at %s", url)
}
func prompts() []string {
items := []string{
strings.TrimSpace(*questionFlag),
}
if followUp := strings.TrimSpace(*followUpFlag); followUp != "" {
items = append(items, followUp)
}
return items
}
func ask(procRunner runner.Runner, prompt string) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), requestTimeout)
defer cancel()
eventCh, err := procRunner.Run(
ctx,
exampleUserID,
exampleSessionID,
model.NewUserMessage(prompt),
agent.WithStream(*streamingFlag),
)
if err != nil {
return "", fmt.Errorf("run a2a request failed: %w", err)
}
answer, err := collectAnswer(eventCh)
if err != nil {
return "", err
}
if answer == "" {
return "", errors.New("assistant returned an empty answer")
}
return answer, nil
}
func collectAnswer(eventCh <-chan *event.Event) (string, error) {
var (
finalText strings.Builder
streamed strings.Builder
)
for evt := range eventCh {
if evt.Error != nil {
return "", errors.New(evt.Error.Message)
}
if evt.Response == nil {
continue
}
for _, choice := range evt.Response.Choices {
if choice.Delta.Content != "" {
streamed.WriteString(choice.Delta.Content)
}
if choice.Message.Content != "" {
finalText.Reset()
finalText.WriteString(choice.Message.Content)
}
}
}
if text := strings.TrimSpace(finalText.String()); text != "" {
return text, nil
}
return strings.TrimSpace(streamed.String()), nil
}
func shutdownServer(httpSrv *http.Server) {
ctx, cancel := context.WithTimeout(context.Background(), shutdownWait)
defer cancel()
_ = httpSrv.Shutdown(ctx)
}
func receiveServeErr(serveErr <-chan error) error {
select {
case err := <-serveErr:
if err != nil && !errors.Is(err, http.ErrServerClosed) {
return fmt.Errorf("http server failed: %w", err)
}
default:
}
return nil
}