Debian Codegraph @

internal/providers/openairesponses/toolcalls.go

raw
1 package openairesponses
2
3 import (
4 "encoding/json"
5 "fmt"
6 "strings"
7
8 "github.com/clnkr-ai/clnkr"
9 "github.com/clnkr-ai/clnkr/internal/providers/openaiwire"
10 )
11
12 type toolCallResponseParts struct {
13 calls []outputItem
14 text string
15 replay []clnkr.ProviderReplayItem
16 rawBody string
17 usage clnkr.Usage
18 protocolOK bool
19 }
20
21 func parseToolCallResponse(respBody []byte) (clnkr.Response, error) {
22 apiResp, err := unmarshalResponse(respBody)
23 if err != nil {
24 return clnkr.Response{}, err
25 }
26 if err := failedResponseError(apiResp); err != nil {
27 return clnkr.Response{}, err
28 }
29
30 parts, err := collectToolCallResponseParts(apiResp, string(respBody))
31 if err != nil {
32 return clnkr.Response{}, err
33 }
34 if len(parts.calls) > 0 {
35 return responseFromFunctionCalls(parts), nil
36 }
37 return responseFromToolCallText(parts)
38 }
39
40 func collectToolCallResponseParts(apiResp response, rawBody string) (toolCallResponseParts, error) {
41 parts := toolCallResponseParts{
42 rawBody: rawBody,
43 usage: clnkr.Usage{
44 InputTokens: apiResp.Usage.InputTokens,
45 OutputTokens: apiResp.Usage.OutputTokens,
46 },
47 replay: make([]clnkr.ProviderReplayItem, 0),
48 }
49 var text strings.Builder
50
51 for i, item := range apiResp.Output {
52 switch item.Type {
53 case "function_call":
54 parts.calls = append(parts.calls, item)
55 case "message":
56 if item.Role != "assistant" {
57 continue
58 }
59 for _, content := range item.Content {
60 switch content.Type {
61 case "output_text":
62 text.WriteString(content.Text)
63 case "refusal":
64 if strings.TrimSpace(content.Refusal) != "" {
65 return toolCallResponseParts{}, fmt.Errorf(
66 "tool-call refusal: %s",
67 content.Refusal,
68 )
69 }
70 }
71 }
72 default:
73 if i < len(apiResp.RawOutput) {
74 parts.replay = append(parts.replay, clnkr.ProviderReplayItem{
75 Provider: replayProvider,
76 ProviderAPI: replayProviderAPI,
77 Type: item.Type,
78 JSON: append(json.RawMessage(nil), apiResp.RawOutput[i]...),
79 })
80 }
81 }
82 }
83
84 parts.text = text.String()
85 if len(parts.calls) > 0 && strings.TrimSpace(parts.text) != "" {
86 parts.protocolOK = false
87 return parts, nil
88 }
89 parts.protocolOK = true
90 return parts, nil
91 }
92
93 func responseFromFunctionCalls(parts toolCallResponseParts) clnkr.Response {
94 if !parts.protocolOK {
95 return clnkr.Response{
96 Raw: parts.rawBody,
97 Usage: parts.usage,
98 ProtocolErr: fmt.Errorf(
99 "%w: mixed bash tool call and structured text",
100 clnkr.ErrInvalidJSON,
101 ),
102 }
103 }
104
105 actions := make([]clnkr.BashAction, 0, len(parts.calls))
106 toolCalls := make([]clnkr.BashToolCall, 0, len(parts.calls))
107 for _, item := range parts.calls {
108 action, call, err := turnFromFunctionCall(item)
109 if err != nil {
110 return clnkr.Response{Raw: parts.rawBody, Usage: parts.usage, ProtocolErr: err}
111 }
112 actions = append(actions, action)
113 toolCalls = append(toolCalls, call)
114 }
115 return clnkr.Response{
116 Turn: &clnkr.ActTurn{Bash: clnkr.BashBatch{Commands: actions}},
117 Raw: parts.rawBody,
118 Usage: parts.usage,
119 BashToolCalls: toolCalls,
120 ProviderReplay: parts.replay,
121 }
122 }
123
124 func responseFromToolCallText(parts toolCallResponseParts) (clnkr.Response, error) {
125 if strings.TrimSpace(parts.text) == "" {
126 return clnkr.Response{}, fmt.Errorf(
127 "tool-call response: no usable output_text or bash tool call",
128 )
129 }
130 turn, err := openaiwire.ParseProviderTurn(parts.text)
131 if err != nil {
132 return clnkr.Response{Raw: parts.text, Usage: parts.usage, ProtocolErr: err}, nil
133 }
134 if _, ok := turn.(*clnkr.ActTurn); ok {
135 return clnkr.Response{
136 Raw: parts.text,
137 Usage: parts.usage,
138 ProtocolErr: fmt.Errorf(
139 "%w: tool-call mode does not accept text act turns",
140 clnkr.ErrInvalidJSON,
141 ),
142 }, nil
143 }
144 if _, err := clnkr.CanonicalTurnJSON(turn); err != nil {
145 return clnkr.Response{}, fmt.Errorf("canonicalize tool-call payload: %w", err)
146 }
147 return clnkr.Response{Turn: turn, Raw: parts.text, Usage: parts.usage}, nil
148 }
149
150 func turnFromFunctionCall(item outputItem) (clnkr.BashAction, clnkr.BashToolCall, error) {
151 if strings.TrimSpace(item.CallID) == "" {
152 return clnkr.BashAction{}, clnkr.BashToolCall{}, fmt.Errorf(
153 "%w: bash tool call missing call_id",
154 clnkr.ErrInvalidJSON,
155 )
156 }
157 if item.Name != "bash" {
158 return clnkr.BashAction{}, clnkr.BashToolCall{}, fmt.Errorf(
159 "%w: unsupported tool %q",
160 clnkr.ErrInvalidJSON,
161 item.Name,
162 )
163 }
164 var args struct {
165 Command string `json:"command"`
166 Workdir *string `json:"workdir"`
167 }
168 var fields map[string]json.RawMessage
169 if err := json.Unmarshal([]byte(item.Arguments), &fields); err != nil {
170 return clnkr.BashAction{}, clnkr.BashToolCall{}, fmt.Errorf(
171 "%w: malformed bash tool arguments: %v",
172 clnkr.ErrInvalidJSON,
173 err,
174 )
175 }
176 if _, ok := fields["workdir"]; !ok {
177 return clnkr.BashAction{}, clnkr.BashToolCall{}, fmt.Errorf(
178 "%w: bash tool arguments missing workdir",
179 clnkr.ErrInvalidJSON,
180 )
181 }
182 dec := json.NewDecoder(strings.NewReader(item.Arguments))
183 dec.DisallowUnknownFields()
184 if err := dec.Decode(&args); err != nil {
185 return clnkr.BashAction{}, clnkr.BashToolCall{}, fmt.Errorf(
186 "%w: malformed bash tool arguments: %v",
187 clnkr.ErrInvalidJSON,
188 err,
189 )
190 }
191 if strings.TrimSpace(args.Command) == "" {
192 return clnkr.BashAction{}, clnkr.BashToolCall{}, clnkr.ErrMissingCommand
193 }
194 call := clnkr.BashToolCall{ID: item.CallID, Command: args.Command}
195 action := clnkr.BashAction{ID: item.CallID, Command: args.Command}
196 if args.Workdir != nil {
197 call.Workdir = *args.Workdir
198 action.Workdir = *args.Workdir
199 }
200 return action, call, nil
201 }