6312
Ga
go-opencode-ai-zen-sdk / files
go-opencode-ai-zen-sdk / examples / agent_loop / main.go
6.3 KB
1package main 2 3import ( 4 "context" 5 "encoding/json" 6 "fmt" 7 "os" 8 "strings" 9 "time" 10 11 zen "github.com/sacenox/go-opencode-ai-zen-sdk" 12) 13 14func main() { 15 apiKey := os.Getenv("OPENCODE_API_KEY") 16 if apiKey == "" { 17 fmt.Fprintln(os.Stderr, "OPENCODE_API_KEY is required") 18 os.Exit(1) 19 } 20 debugSSE := os.Getenv("DEBUG_SSE") == "1" 21 22 client, err := zen.NewClient(zen.Config{APIKey: apiKey}) 23 if err != nil { 24 panic(err) 25 } 26 27 tools := map[string]func(context.Context, json.RawMessage) (string, error){ 28 "add": func(_ context.Context, args json.RawMessage) (string, error) { 29 var input struct { 30 A float64 `json:"a"` 31 B float64 `json:"b"` 32 } 33 if err := json.Unmarshal(args, &input); err != nil { 34 return "", err 35 } 36 return fmt.Sprintf("%.0f", input.A+input.B), nil 37 }, 38 } 39 toolName := singleToolName(tools) 40 41 models := resolveModels(os.Args[1:]) 42 for _, model := range models { 43 fmt.Printf("=== Model: %s ===\n", model) 44 if err := runAgentLoop(client, model, debugSSE, tools, toolName); err != nil { 45 fmt.Fprintf(os.Stderr, "model %s failed: %v\n", model, err) 46 if apiErr, ok := err.(*zen.APIError); ok && len(apiErr.Body) > 0 { 47 fmt.Fprintf(os.Stderr, "api error body: %s\n", string(apiErr.Body)) 48 } 49 } 50 } 51} 52 53func runAgentLoop(client *zen.Client, model string, debugSSE bool, tools map[string]func(context.Context, json.RawMessage) (string, error), toolName string) error { 54 messages := []zen.NormalizedMessage{{ 55 Role: "user", 56 Content: "What is 3 + 4, then double it?", 57 }} 58 59 maxSteps := 6 60 var totalIn, totalOut int 61 for step := 0; step < maxSteps; step++ { 62 req := zen.NormalizedRequest{ 63 Model: model, 64 System: "You are a precise assistant. Always use the add tool for arithmetic, including doubling by adding a number to itself.", 65 Messages: messages, 66 Reasoning: &zen.NormalizedReasoning{Effort: "low"}, 67 Tools: []zen.NormalizedTool{ 68 { 69 Name: "add", 70 Description: "Adds two numbers", 71 Parameters: json.RawMessage(`{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}`), 72 }, 73 }, 74 ToolChoice: &zen.NormalizedToolChoice{Type: zen.ToolChoiceAuto}, 75 } 76 77 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) 78 deltas, errs, err := streamDeltas(ctx, client, req, debugSSE) 79 if err != nil { 80 cancel() 81 return err 82 } 83 84 var text strings.Builder 85 accumulator := zen.NewToolCallAccumulator() 86 var stepIn, stepOut int 87 88 for d := range deltas { 89 switch d.Type { 90 case zen.DeltaText: 91 text.WriteString(d.Content) 92 case zen.DeltaReasoning: 93 fmt.Printf("[reasoning] %s", d.Content) 94 case zen.DeltaToolCallBegin, zen.DeltaToolCallArgumentsDelta, zen.DeltaToolCallDone: 95 accumulator.Apply(d) 96 case zen.DeltaUsage: 97 if d.InputTokens > stepIn { 98 stepIn = d.InputTokens 99 } 100 stepOut += d.OutputTokens 101 } 102 } 103 if err := <-errs; err != nil { 104 cancel() 105 return err 106 } 107 cancel() 108 109 totalIn += stepIn 110 totalOut += stepOut 111 fmt.Printf("[usage:step%d] in=%d out=%d\n", step+1, stepIn, stepOut) 112 113 calls := accumulator.CompleteCalls() 114 if len(calls) == 0 { 115 messages = append(messages, zen.NormalizedMessage{ 116 Role: "assistant", 117 Content: text.String(), 118 }) 119 fmt.Printf("\n[assistant] %s\n", text.String()) 120 fmt.Printf("[usage:total] in=%d out=%d\n", totalIn, totalOut) 121 return nil 122 } 123 124 assistant := zen.NormalizedMessage{Role: "assistant"} 125 for i := range calls { 126 if calls[i].Name == "" && toolName != "" { 127 calls[i].Name = toolName 128 } 129 assistant.ToolCalls = append(assistant.ToolCalls, zen.NormalizedToolCall{ 130 ID: calls[i].ID, 131 Name: calls[i].Name, 132 Arguments: calls[i].Arguments, 133 ThoughtSignature: calls[i].ThoughtSignature, 134 }) 135 } 136 messages = append(messages, assistant) 137 138 for _, call := range calls { 139 tool := tools[call.Name] 140 result := "" 141 if tool == nil { 142 result = "unknown tool: " + call.Name 143 } else { 144 out, err := tool(context.Background(), call.Arguments) 145 if err != nil { 146 result = "error: " + err.Error() 147 } else { 148 result = out 149 } 150 } 151 fmt.Printf("\n[tool:%s] %s\n", call.Name, result) 152 messages = append(messages, zen.NormalizedMessage{ 153 Role: "tool", 154 ToolCallID: call.ID, 155 FunctionName: call.Name, 156 Content: result, 157 }) 158 } 159 } 160 fmt.Printf("[usage:total] in=%d out=%d\n", totalIn, totalOut) 161 return fmt.Errorf("max steps reached without final response") 162} 163 164func streamDeltas(ctx context.Context, client *zen.Client, req zen.NormalizedRequest, debug bool) (<-chan zen.NormalizedDelta, <-chan error, error) { 165 if !debug { 166 return client.Stream(ctx, req) 167 } 168 169 evCh, errCh, err := client.StreamEvents(ctx, req) 170 if err != nil { 171 return nil, nil, err 172 } 173 174 out := make(chan zen.NormalizedDelta) 175 outErr := make(chan error, 1) 176 177 go func() { 178 defer close(out) 179 defer close(outErr) 180 for ev := range evCh { 181 if ev.Event != "" { 182 fmt.Printf("[sse:%s] %s\n", ev.Event, ev.Raw) 183 } else { 184 fmt.Printf("[sse] %s\n", ev.Raw) 185 } 186 for _, delta := range zen.ParseNormalizedEvent(ev) { 187 out <- delta 188 } 189 } 190 if err := <-errCh; err != nil { 191 outErr <- err 192 } 193 }() 194 195 return out, outErr, nil 196} 197 198func resolveModels(args []string) []string { 199 if len(args) > 0 { 200 models := make([]string, 0, len(args)) 201 for _, arg := range args { 202 if normalized := normalizeModelAlias(arg); normalized != "" { 203 models = append(models, normalized) 204 } 205 } 206 if len(models) > 0 { 207 return models 208 } 209 } 210 if raw := strings.TrimSpace(os.Getenv("MODELS")); raw != "" { 211 parts := strings.Split(raw, ",") 212 models := make([]string, 0, len(parts)) 213 for _, part := range parts { 214 if v := strings.TrimSpace(part); v != "" { 215 if normalized := normalizeModelAlias(v); normalized != "" { 216 models = append(models, normalized) 217 } 218 } 219 } 220 if len(models) > 0 { 221 return models 222 } 223 } 224 return []string{"gpt-5.1"} 225} 226 227func singleToolName(tools map[string]func(context.Context, json.RawMessage) (string, error)) string { 228 if len(tools) != 1 { 229 return "" 230 } 231 for name := range tools { 232 return name 233 } 234 return "" 235} 236 237func normalizeModelAlias(value string) string { 238 model := strings.ToLower(strings.TrimSpace(value)) 239 if model == "" { 240 return "" 241 } 242 if strings.HasPrefix(model, "opencode/") { 243 model = strings.TrimPrefix(model, "opencode/") 244 } 245 model = strings.ReplaceAll(model, " ", "-") 246 model = strings.ReplaceAll(model, "_", "-") 247 248 return model 249}