xonecas.io
6312
Ga

go-opencode-ai-zen-sdk / commit bb394f9

fix: lot's of fixes and a working example reference

xonecas2026-02-19 bb394f97ba42bfd520097e61e1c520ab4417f2d6 parent a9649b5

6 files changed

examples/agent_loop/main.go+244−0
@@ -0,0 +1,244 @@
1+package main
2+
3+import (
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+
14+func 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+
53+func 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+ for step := 0; step < maxSteps; step++ {
61+ req := zen.NormalizedRequest{
62+ Model: model,
63+ System: "You are a precise assistant. Always use the add tool for arithmetic, including doubling by adding a number to itself.",
64+ Messages: messages,
65+ Reasoning: &zen.NormalizedReasoning{Effort: "low"},
66+ Tools: []zen.NormalizedTool{
67+ {
68+ Name: "add",
69+ Description: "Adds two numbers",
70+ Parameters: json.RawMessage(`{"type":"object","properties":{"a":{"type":"number"},"b":{"type":"number"}},"required":["a","b"]}`),
71+ },
72+ },
73+ ToolChoice: &zen.NormalizedToolChoice{Type: zen.ToolChoiceAuto},
74+ }
75+
76+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
77+ deltas, errs, err := streamDeltas(ctx, client, req, debugSSE)
78+ if err != nil {
79+ cancel()
80+ return err
81+ }
82+
83+ var text strings.Builder
84+ accumulator := zen.NewToolCallAccumulator()
85+
86+ for d := range deltas {
87+ switch d.Type {
88+ case zen.DeltaText:
89+ text.WriteString(d.Content)
90+ case zen.DeltaReasoning:
91+ fmt.Printf("[reasoning] %s", d.Content)
92+ case zen.DeltaToolCallBegin, zen.DeltaToolCallArgumentsDelta, zen.DeltaToolCallDone:
93+ accumulator.Apply(d)
94+ }
95+ }
96+ if err := <-errs; err != nil {
97+ cancel()
98+ return err
99+ }
100+ cancel()
101+
102+ calls := accumulator.CompleteCalls()
103+ if len(calls) == 0 {
104+ messages = append(messages, zen.NormalizedMessage{
105+ Role: "assistant",
106+ Content: text.String(),
107+ })
108+ fmt.Printf("\n[assistant] %s\n", text.String())
109+ return nil
110+ }
111+
112+ assistant := zen.NormalizedMessage{Role: "assistant"}
113+ for i := range calls {
114+ if calls[i].Name == "" && toolName != "" {
115+ calls[i].Name = toolName
116+ }
117+ assistant.ToolCalls = append(assistant.ToolCalls, zen.NormalizedToolCall{
118+ ID: calls[i].ID,
119+ Name: calls[i].Name,
120+ Arguments: calls[i].Arguments,
121+ })
122+ }
123+ messages = append(messages, assistant)
124+
125+ for _, call := range calls {
126+ tool := tools[call.Name]
127+ result := ""
128+ if tool == nil {
129+ result = "unknown tool: " + call.Name
130+ } else {
131+ out, err := tool(context.Background(), call.Arguments)
132+ if err != nil {
133+ result = "error: " + err.Error()
134+ } else {
135+ result = out
136+ }
137+ }
138+ fmt.Printf("\n[tool:%s] %s\n", call.Name, result)
139+ messages = append(messages, zen.NormalizedMessage{
140+ Role: "tool",
141+ ToolCallID: call.ID,
142+ FunctionName: call.Name,
143+ Content: result,
144+ })
145+ }
146+ }
147+ return fmt.Errorf("max steps reached without final response")
148+}
149+
150+func streamDeltas(ctx context.Context, client *zen.Client, req zen.NormalizedRequest, debug bool) (<-chan zen.NormalizedDelta, <-chan error, error) {
151+ if !debug {
152+ return client.Stream(ctx, req)
153+ }
154+
155+ evCh, errCh, err := client.StreamEvents(ctx, req)
156+ if err != nil {
157+ return nil, nil, err
158+ }
159+
160+ out := make(chan zen.NormalizedDelta)
161+ outErr := make(chan error, 1)
162+
163+ go func() {
164+ defer close(out)
165+ defer close(outErr)
166+ for ev := range evCh {
167+ if ev.Event != "" {
168+ fmt.Printf("[sse:%s] %s\n", ev.Event, ev.Raw)
169+ } else {
170+ fmt.Printf("[sse] %s\n", ev.Raw)
171+ }
172+ for _, delta := range zen.ParseNormalizedEvent(ev) {
173+ out <- delta
174+ }
175+ }
176+ if err := <-errCh; err != nil {
177+ outErr <- err
178+ }
179+ }()
180+
181+ return out, outErr, nil
182+}
183+
184+func resolveModels(args []string) []string {
185+ if len(args) > 0 {
186+ models := make([]string, 0, len(args))
187+ for _, arg := range args {
188+ if normalized := normalizeModelAlias(arg); normalized != "" {
189+ models = append(models, normalized)
190+ }
191+ }
192+ if len(models) > 0 {
193+ return models
194+ }
195+ }
196+ if raw := strings.TrimSpace(os.Getenv("MODELS")); raw != "" {
197+ parts := strings.Split(raw, ",")
198+ models := make([]string, 0, len(parts))
199+ for _, part := range parts {
200+ if v := strings.TrimSpace(part); v != "" {
201+ if normalized := normalizeModelAlias(v); normalized != "" {
202+ models = append(models, normalized)
203+ }
204+ }
205+ }
206+ if len(models) > 0 {
207+ return models
208+ }
209+ }
210+ return []string{"gpt-5.1"}
211+}
212+
213+func singleToolName(tools map[string]func(context.Context, json.RawMessage) (string, error)) string {
214+ if len(tools) != 1 {
215+ return ""
216+ }
217+ for name := range tools {
218+ return name
219+ }
220+ return ""
221+}
222+
223+func normalizeModelAlias(value string) string {
224+ model := strings.ToLower(strings.TrimSpace(value))
225+ if model == "" {
226+ return ""
227+ }
228+ if strings.HasPrefix(model, "opencode/") {
229+ model = strings.TrimPrefix(model, "opencode/")
230+ }
231+ model = strings.ReplaceAll(model, " ", "-")
232+ model = strings.ReplaceAll(model, "_", "-")
233+
234+ switch model {
235+ case "haiku", "claude-haiku", "claude-haiku-3-5", "claude-3-5-haiku", "claude-haiku-4-5":
236+ return "claude-3-5-haiku"
237+ case "gemini-3-pro", "gemini-3-pro-preview", "gemini-3.0-pro", "gemini-3-pro-preview-raw":
238+ return "gemini-3-pro"
239+ case "minimax2.5", "minimax-2.5", "minimax-m2.5":
240+ return "minimax-m2.5"
241+ }
242+
243+ return model
244+}
normalized.go+70−12
@@ -1,8 +1,10 @@
11 package zen
22
33 import (
4+ "encoding/base64"
45 "encoding/json"
56 "errors"
7+ "sort"
68 "strings"
79 )
810
@@ -32,9 +34,52 @@ type NormalizedReasoning struct {
3234 }
3335
3436 type NormalizedToolCall struct {
35- ID string
36- Name string
37- Arguments json.RawMessage
37+ ID string
38+ Name string
39+ Arguments json.RawMessage
40+ ThoughtSignature string
41+}
42+
43+const geminiSignatureSeparator = "|ts="
44+
45+func encodeGeminiToolCallID(callID, signature string) string {
46+ if signature == "" {
47+ return callID
48+ }
49+ if strings.Contains(callID, geminiSignatureSeparator) {
50+ return callID
51+ }
52+ encoded := base64.RawURLEncoding.EncodeToString([]byte(signature))
53+ return callID + geminiSignatureSeparator + encoded
54+}
55+
56+func decodeGeminiThoughtSignature(callID string) (string, string) {
57+ idx := strings.Index(callID, geminiSignatureSeparator)
58+ if idx == -1 {
59+ return callID, ""
60+ }
61+ base := callID[:idx]
62+ encoded := callID[idx+len(geminiSignatureSeparator):]
63+ if encoded == "" {
64+ return base, ""
65+ }
66+ decoded, err := base64.RawURLEncoding.DecodeString(encoded)
67+ if err != nil {
68+ return base, ""
69+ }
70+ return base, string(decoded)
71+}
72+
73+func sortedNormalizedTools(tools []NormalizedTool) []NormalizedTool {
74+ if len(tools) <= 1 {
75+ return tools
76+ }
77+ sorted := make([]NormalizedTool, len(tools))
78+ copy(sorted, tools)
79+ sort.Slice(sorted, func(i, j int) bool {
80+ return sorted[i].Name < sorted[j].Name
81+ })
82+ return sorted
3883 }
3984
4085 type NormalizedMessage struct {
@@ -137,8 +182,9 @@ func (r NormalizedRequest) ToResponsesRequest() (*ResponsesRequest, error) {
137182 }
138183
139184 if len(r.Tools) > 0 {
140- req.Tools = make([]ResponsesTool, 0, len(r.Tools))
141- for _, t := range r.Tools {
185+ tools := sortedNormalizedTools(r.Tools)
186+ req.Tools = make([]ResponsesTool, 0, len(tools))
187+ for _, t := range tools {
142188 req.Tools = append(req.Tools, ResponsesTool{
143189 Type: "function",
144190 Name: t.Name,
@@ -192,12 +238,17 @@ func (r NormalizedRequest) ToChatCompletionsRequest() (*ChatCompletionsRequest,
192238 }
193239
194240 if r.Reasoning != nil && r.Reasoning.Effort != "" {
195- req.Reasoning = &ChatReasoning{Effort: r.Reasoning.Effort}
241+ if req.Extra == nil {
242+ req.Extra = map[string]any{}
243+ }
244+ // OpenAI-compatible reasoning uses reasoning_effort, not reasoning.
245+ req.Extra["reasoning_effort"] = r.Reasoning.Effort
196246 }
197247
198248 if len(r.Tools) > 0 {
199- req.Tools = make([]ChatTool, 0, len(r.Tools))
200- for _, t := range r.Tools {
249+ tools := sortedNormalizedTools(r.Tools)
250+ req.Tools = make([]ChatTool, 0, len(tools))
251+ for _, t := range tools {
201252 req.Tools = append(req.Tools, ChatTool{
202253 Type: "function",
203254 Function: ChatToolFunction(t),
@@ -263,8 +314,9 @@ func (r NormalizedRequest) ToMessagesRequest() (*MessagesRequest, error) {
263314 }
264315
265316 if len(r.Tools) > 0 {
266- req.Tools = make([]AnthropicTool, 0, len(r.Tools))
267- for _, t := range r.Tools {
317+ tools := sortedNormalizedTools(r.Tools)
318+ req.Tools = make([]AnthropicTool, 0, len(tools))
319+ for _, t := range tools {
268320 req.Tools = append(req.Tools, AnthropicTool{
269321 Name: t.Name,
270322 Description: t.Description,
@@ -334,11 +386,16 @@ func (r NormalizedRequest) ToGeminiRequest() (*GeminiRequest, error) {
334386 if role == "model" && len(m.ToolCalls) > 0 {
335387 parts := make([]GeminiPart, 0, len(m.ToolCalls))
336388 for _, tc := range m.ToolCalls {
389+ signature := tc.ThoughtSignature
390+ if signature == "" {
391+ _, signature = decodeGeminiThoughtSignature(tc.ID)
392+ }
337393 parts = append(parts, GeminiPart{
338394 FunctionCall: &GeminiFunctionCall{
339395 Name: tc.Name,
340396 Args: tc.Arguments,
341397 },
398+ ThoughtSignature: signature,
342399 })
343400 }
344401 contents = append(contents, GeminiContent{Role: role, Parts: parts})
@@ -393,8 +450,9 @@ func (r NormalizedRequest) ToGeminiRequest() (*GeminiRequest, error) {
393450 }
394451
395452 if len(r.Tools) > 0 {
396- tool := GeminiTool{FunctionDeclarations: make([]GeminiFunctionDeclaration, 0, len(r.Tools))}
397- for _, t := range r.Tools {
453+ tools := sortedNormalizedTools(r.Tools)
454+ tool := GeminiTool{FunctionDeclarations: make([]GeminiFunctionDeclaration, 0, len(tools))}
455+ for _, t := range tools {
398456 tool.FunctionDeclarations = append(tool.FunctionDeclarations, GeminiFunctionDeclaration(t))
399457 }
400458 req.Tools = []GeminiTool{tool}
parse.go+103−21
@@ -2,6 +2,7 @@ package zen
22
33 import (
44 "encoding/json"
5+ "fmt"
56 "strings"
67 )
78
@@ -33,11 +34,12 @@ type NormalizedDelta struct {
3334 Content string
3435
3536 // Tool call fields.
36- ToolCallIndex int // index within this response (0-based)
37- ToolCallID string // set on DeltaToolCallBegin / DeltaToolCallDone
38- ToolCallName string // set on DeltaToolCallBegin / DeltaToolCallDone
39- ArgumentsDelta string // set on DeltaToolCallArgumentsDelta
40- ArgumentsFull string // set on DeltaToolCallDone (fully accumulated)
37+ ToolCallIndex int // index within this response (0-based)
38+ ToolCallID string // set on DeltaToolCallBegin / DeltaToolCallDone
39+ ToolCallName string // set on DeltaToolCallBegin / DeltaToolCallDone
40+ ToolCallSignature string // set on DeltaToolCallBegin / DeltaToolCallDone when provided by provider
41+ ArgumentsDelta string // set on DeltaToolCallArgumentsDelta
42+ ArgumentsFull string // set on DeltaToolCallDone (fully accumulated)
4143 }
4244
4345 // ParseNormalizedEvent parses a single UnifiedEvent into zero or more NormalizedDelta values.
@@ -75,7 +77,11 @@ type chatCompletionChunk struct {
7577 Role string `json:"role"`
7678 Content string `json:"content"`
7779 ReasoningContent string `json:"reasoning_content"`
78- ToolCalls []struct {
80+ Reasoning string `json:"reasoning"`
81+ ReasoningDetails []struct {
82+ Text string `json:"text"`
83+ } `json:"reasoning_details"`
84+ ToolCalls []struct {
7985 Index int `json:"index"`
8086 ID string `json:"id"`
8187 Type string `json:"type"`
@@ -104,6 +110,14 @@ func parseChatCompletionsDelta(ev UnifiedEvent) []NormalizedDelta {
104110 if delta.ReasoningContent != "" {
105111 out = append(out, NormalizedDelta{Type: DeltaReasoning, Content: delta.ReasoningContent})
106112 }
113+ if delta.Reasoning != "" {
114+ out = append(out, NormalizedDelta{Type: DeltaReasoning, Content: delta.Reasoning})
115+ }
116+ for _, detail := range delta.ReasoningDetails {
117+ if detail.Text != "" {
118+ out = append(out, NormalizedDelta{Type: DeltaReasoning, Content: detail.Text})
119+ }
120+ }
107121 if delta.Content != "" {
108122 out = append(out, NormalizedDelta{Type: DeltaText, Content: delta.Content})
109123 }
@@ -142,13 +156,15 @@ type responsesEvent struct {
142156 Delta string `json:"delta"`
143157 // For tool call events.
144158 Item struct {
145- Type string `json:"type"`
146- ID string `json:"id"`
147- Name string `json:"name"`
159+ Type string `json:"type"`
160+ ID string `json:"id"`
161+ CallID string `json:"call_id"`
162+ Name string `json:"name"`
148163 } `json:"item"`
149164 OutputIndex int `json:"output_index"`
150165 Name string `json:"name"`
151166 CallID string `json:"call_id"`
167+ ItemID string `json:"item_id"`
152168 Arguments string `json:"arguments"`
153169 }
154170
@@ -167,7 +183,7 @@ func parseResponsesDelta(ev UnifiedEvent) []NormalizedDelta {
167183 if e.Delta != "" {
168184 return []NormalizedDelta{{Type: DeltaReasoning, Content: e.Delta}}
169185 }
170- case "response.function_call_arguments_delta":
186+ case "response.function_call_arguments_delta", "response.function_call_arguments.delta":
171187 if e.Delta != "" {
172188 return []NormalizedDelta{{
173189 Type: DeltaToolCallArgumentsDelta,
@@ -175,21 +191,42 @@ func parseResponsesDelta(ev UnifiedEvent) []NormalizedDelta {
175191 ArgumentsDelta: e.Delta,
176192 }}
177193 }
178- case "response.function_call_arguments_done":
194+ case "response.function_call_arguments_done", "response.function_call_arguments.done":
195+ callID := e.CallID
196+ if callID == "" {
197+ callID = e.ItemID
198+ }
179199 return []NormalizedDelta{{
180200 Type: DeltaToolCallDone,
181201 ToolCallIndex: e.OutputIndex,
182- ToolCallID: e.CallID,
202+ ToolCallID: callID,
183203 ToolCallName: e.Name,
184204 ArgumentsFull: e.Arguments,
185205 }}
186206 case "response.output_item.added":
187207 if e.Item.Type == "function_call" {
208+ callID := e.Item.CallID
209+ name := e.Item.Name
210+ if callID == "" || name == "" {
211+ fallbackCallID, fallbackName := extractResponsesFunctionCallItem(ev.Data)
212+ if callID == "" {
213+ callID = fallbackCallID
214+ }
215+ if name == "" {
216+ name = fallbackName
217+ }
218+ }
219+ if callID == "" {
220+ callID = e.Item.ID
221+ }
222+ if name == "" {
223+ name = e.Name
224+ }
188225 return []NormalizedDelta{{
189226 Type: DeltaToolCallBegin,
190227 ToolCallIndex: e.OutputIndex,
191- ToolCallID: e.Item.ID,
192- ToolCallName: e.Item.Name,
228+ ToolCallID: callID,
229+ ToolCallName: name,
193230 }}
194231 }
195232 case "response.completed", "response.done":
@@ -199,6 +236,36 @@ func parseResponsesDelta(ev UnifiedEvent) []NormalizedDelta {
199236 return nil
200237 }
201238
239+func extractResponsesFunctionCallItem(raw json.RawMessage) (string, string) {
240+ var root map[string]any
241+ if err := json.Unmarshal(raw, &root); err != nil {
242+ return "", ""
243+ }
244+ item, ok := root["item"].(map[string]any)
245+ if !ok {
246+ return "", ""
247+ }
248+ if t, ok := item["type"].(string); ok && t != "function_call" {
249+ return "", ""
250+ }
251+
252+ var callID string
253+ if v, ok := item["call_id"].(string); ok {
254+ callID = v
255+ } else if v, ok := item["id"].(string); ok {
256+ callID = v
257+ }
258+
259+ var name string
260+ if v, ok := item["name"].(string); ok {
261+ name = v
262+ } else if v, ok := item["tool_name"].(string); ok {
263+ name = v
264+ }
265+
266+ return callID, name
267+}
268+
202269 // ---------------------------------------------------------------------------
203270 // messages (Anthropic)
204271 // ---------------------------------------------------------------------------
@@ -285,9 +352,10 @@ type geminiChunk struct {
285352 Candidates []struct {
286353 Content struct {
287354 Parts []struct {
288- Text string `json:"text"`
289- Thought bool `json:"thought"`
290- FunctionCall *geminiFC `json:"functionCall,omitempty"`
355+ Text string `json:"text"`
356+ Thought bool `json:"thought"`
357+ FunctionCall *geminiFC `json:"functionCall,omitempty"`
358+ ThoughtSignature string `json:"thoughtSignature"`
291359 } `json:"parts"`
292360 } `json:"content"`
293361 FinishReason string `json:"finishReason"`
@@ -313,16 +381,30 @@ func parseGeminiDelta(ev UnifiedEvent) []NormalizedDelta {
313381
314382 for i, part := range cand.Content.Parts {
315383 if part.FunctionCall != nil {
384+ callID := fmt.Sprintf("gemini-%d", i)
385+ callID = encodeGeminiToolCallID(callID, part.ThoughtSignature)
316386 out = append(out, NormalizedDelta{
317- Type: DeltaToolCallBegin,
318- ToolCallIndex: i,
319- ToolCallName: part.FunctionCall.Name,
387+ Type: DeltaToolCallBegin,
388+ ToolCallIndex: i,
389+ ToolCallID: callID,
390+ ToolCallName: part.FunctionCall.Name,
391+ ToolCallSignature: part.ThoughtSignature,
320392 })
321393 if len(part.FunctionCall.Args) > 0 {
394+ args := string(part.FunctionCall.Args)
322395 out = append(out, NormalizedDelta{
323396 Type: DeltaToolCallArgumentsDelta,
324397 ToolCallIndex: i,
325- ArgumentsDelta: string(part.FunctionCall.Args),
398+ ToolCallID: callID,
399+ ArgumentsDelta: args,
400+ })
401+ out = append(out, NormalizedDelta{
402+ Type: DeltaToolCallDone,
403+ ToolCallIndex: i,
404+ ToolCallID: callID,
405+ ToolCallName: part.FunctionCall.Name,
406+ ToolCallSignature: part.ThoughtSignature,
407+ ArgumentsFull: args,
326408 })
327409 }
328410 continue
parse_test.go+6−3
@@ -274,9 +274,9 @@ func TestParseGeminiThoughtThenText(t *testing.T) {
274274 func TestParseGeminiFunctionCall(t *testing.T) {
275275 ev := makeEvent(EndpointModels, `{"candidates":[{"content":{"parts":[{"functionCall":{"name":"get_weather","args":{"city":"Paris"}}}]}}]}`)
276276 deltas := ParseNormalizedEvent(ev)
277- // Expect DeltaToolCallBegin + DeltaToolCallArgumentsDelta
278- if len(deltas) != 2 {
279- t.Fatalf("expected 2 deltas, got %d: %+v", len(deltas), deltas)
277+ // Expect DeltaToolCallBegin + DeltaToolCallArgumentsDelta + DeltaToolCallDone
278+ if len(deltas) != 3 {
279+ t.Fatalf("expected 3 deltas, got %d: %+v", len(deltas), deltas)
280280 }
281281 if deltas[0].Type != DeltaToolCallBegin || deltas[0].ToolCallName != "get_weather" {
282282 t.Fatalf("expected tool_call_begin with name get_weather, got %+v", deltas[0])
@@ -284,6 +284,9 @@ func TestParseGeminiFunctionCall(t *testing.T) {
284284 if deltas[1].Type != DeltaToolCallArgumentsDelta {
285285 t.Fatalf("expected tool_call_arguments_delta, got %+v", deltas[1])
286286 }
287+ if deltas[2].Type != DeltaToolCallDone {
288+ t.Fatalf("expected tool_call_done, got %+v", deltas[2])
289+ }
287290 }
288291
289292 func TestParseGeminiDone(t *testing.T) {
tool_calls.go+109−0
@@ -0,0 +1,109 @@
1+package zen
2+
3+import (
4+ "encoding/json"
5+ "fmt"
6+ "strings"
7+)
8+
9+// StreamToolCall is a fully assembled tool call extracted from a stream.
10+type StreamToolCall struct {
11+ ID string
12+ Name string
13+ Arguments json.RawMessage
14+}
15+
16+// ToolCallAccumulator stitches streaming tool call deltas into complete calls.
17+// Call Apply for every NormalizedDelta, then call CompleteCalls at the end.
18+type ToolCallAccumulator struct {
19+ calls map[int]*toolCallState
20+ order []int
21+}
22+
23+type toolCallState struct {
24+ index int
25+ id string
26+ name string
27+ args strings.Builder
28+ full string
29+}
30+
31+// NewToolCallAccumulator creates a new accumulator for streaming tool calls.
32+func NewToolCallAccumulator() *ToolCallAccumulator {
33+ return &ToolCallAccumulator{calls: map[int]*toolCallState{}}
34+}
35+
36+// Apply ingests a single delta. It returns true if the delta affected tool state.
37+func (a *ToolCallAccumulator) Apply(delta NormalizedDelta) bool {
38+ switch delta.Type {
39+ case DeltaToolCallBegin, DeltaToolCallArgumentsDelta, DeltaToolCallDone:
40+ // continue
41+ default:
42+ return false
43+ }
44+
45+ call := a.ensure(delta.ToolCallIndex)
46+ switch delta.Type {
47+ case DeltaToolCallBegin:
48+ if call.id == "" {
49+ call.id = delta.ToolCallID
50+ }
51+ if call.name == "" {
52+ call.name = delta.ToolCallName
53+ }
54+ case DeltaToolCallArgumentsDelta:
55+ call.args.WriteString(delta.ArgumentsDelta)
56+ case DeltaToolCallDone:
57+ if call.id == "" {
58+ call.id = delta.ToolCallID
59+ }
60+ if call.name == "" {
61+ call.name = delta.ToolCallName
62+ }
63+ if delta.ArgumentsFull != "" {
64+ call.full = delta.ArgumentsFull
65+ }
66+ }
67+
68+ return true
69+}
70+
71+// CompleteCalls returns fully assembled tool calls in their original order.
72+// Any missing IDs are filled with stable synthetic IDs.
73+func (a *ToolCallAccumulator) CompleteCalls() []StreamToolCall {
74+ if len(a.order) == 0 {
75+ return nil
76+ }
77+ out := make([]StreamToolCall, 0, len(a.order))
78+ for _, idx := range a.order {
79+ call := a.calls[idx]
80+ if call == nil {
81+ continue
82+ }
83+ id := call.id
84+ if id == "" {
85+ id = fmt.Sprintf("tool-%d", call.index)
86+ }
87+ full := call.full
88+ if full == "" {
89+ full = call.args.String()
90+ }
91+ out = append(out, StreamToolCall{
92+ ID: id,
93+ Name: call.name,
94+ Arguments: json.RawMessage(full),
95+ })
96+ }
97+ return out
98+}
99+
100+func (a *ToolCallAccumulator) ensure(index int) *toolCallState {
101+ call := a.calls[index]
102+ if call != nil {
103+ return call
104+ }
105+ call = &toolCallState{index: index}
106+ a.calls[index] = call
107+ a.order = append(a.order, index)
108+ return call
109+}
types_gemini.go+1−0
@@ -49,6 +49,7 @@ type GeminiPart struct {
4949 Text string `json:"text,omitempty"`
5050 FunctionCall *GeminiFunctionCall `json:"functionCall,omitempty"`
5151 FunctionResponse *GeminiFunctionResponse `json:"functionResponse,omitempty"`
52+ ThoughtSignature string `json:"thoughtSignature,omitempty"`
5253 }
5354
5455 type GeminiTool struct {