Debian Codegraph @

internal/providers/providerconfig/providerconfig.go

raw
1 package providerconfig
2
3 import (
4 "fmt"
5 "regexp"
6 "strconv"
7 "strings"
8 )
9
10 type Provider string
11
12 const (
13 ProviderAnthropic Provider = "anthropic"
14 ProviderOpenAI Provider = "openai"
15 )
16
17 type ProviderAPI string
18
19 const (
20 ProviderAPIAuto ProviderAPI = "auto"
21 ProviderAPIOpenAIChatCompletions ProviderAPI = "openai-chat-completions"
22 ProviderAPIOpenAIResponses ProviderAPI = "openai-responses"
23 )
24
25 func ParseProvider(raw string) (Provider, error) {
26 provider := Provider(strings.ToLower(strings.TrimSpace(raw)))
27 if provider == ProviderAnthropic || provider == ProviderOpenAI {
28 return provider, nil
29 }
30 return "", fmt.Errorf(`invalid provider %q (allowed: anthropic, openai)`, raw)
31 }
32
33 func ParseProviderAPI(raw string) (ProviderAPI, error) {
34 api := ProviderAPI(strings.ToLower(strings.TrimSpace(raw)))
35 if api == ProviderAPIAuto || api == ProviderAPIOpenAIChatCompletions ||
36 api == ProviderAPIOpenAIResponses {
37 return api, nil
38 }
39 return "", fmt.Errorf(
40 `invalid provider-api %q (allowed: auto, openai-chat-completions, openai-responses)`,
41 raw,
42 )
43 }
44
45 const (
46 DefaultAnthropicMaxTokens = 4096
47 MaxAnthropicNonStreamingTokens = 21333
48 MinAnthropicThinkingBudgetTokens = 1024
49 )
50
51 type OptionalInt struct {
52 Value int
53 Set bool
54 }
55
56 // ProviderRequestOptions holds provider-agnostic request configuration.
57 type ProviderRequestOptions struct {
58 Effort ProviderEffortOptions
59 Output ProviderOutputOptions
60 AnthropicManual AnthropicManualThinkingOptions
61 }
62
63 // ProviderEffortOptions describes the user-requested effort level.
64 type ProviderEffortOptions struct {
65 // Level is "auto", "low", "medium", "high", "xhigh", or "max".
66 // "auto" means omit provider-specific effort fields.
67 Level string
68 // Set distinguishes omitted effort from explicit --effort auto.
69 Set bool
70 }
71
72 // ProviderOutputOptions describes the user-requested output token cap.
73 type ProviderOutputOptions struct {
74 MaxOutputTokens OptionalInt
75 }
76
77 // AnthropicManualThinkingOptions is an advanced legacy escape hatch for
78 // manual thinking budget (not the normal UX).
79 type AnthropicManualThinkingOptions struct {
80 ThinkingBudgetTokens OptionalInt
81 }
82
83 var datedSnapshotSuffix = regexp.MustCompile(`-\d{4}-\d{2}-\d{2}$`)
84
85 var openAIResponsesAllowlist = map[string]struct{}{
86 "gpt-5": {},
87 "gpt-5-mini": {},
88 "gpt-5-nano": {},
89 "gpt-5-pro": {},
90 "gpt-5.1": {},
91 "gpt-5.2": {},
92 "gpt-5.4": {},
93 "gpt-5.4-mini": {},
94 "gpt-5.4-nano": {},
95 "gpt-5-codex": {},
96 "gpt-5.1-codex": {},
97 "gpt-5.1-codex-mini": {},
98 "gpt-5.1-codex-max": {},
99 "gpt-5.2-codex": {},
100 "gpt-5.3-codex": {},
101 "gpt-4.1": {},
102 "gpt-4.1-mini": {},
103 "gpt-4.1-nano": {},
104 "o3-pro": {},
105 }
106
107 var unsupportedStructuredOpenAIModels = map[string]struct{}{
108 "gpt-5.2-pro": {},
109 "gpt-5.4-pro": {},
110 }
111
112 func ResolveProviderAPI(
113 provider Provider,
114 providerAPI ProviderAPI,
115 model string,
116 ) (ProviderAPI, error) {
117 if provider == ProviderOpenAI {
118 normalizedModel := strings.ToLower(strings.TrimSpace(model))
119 if listedModel(unsupportedStructuredOpenAIModels, normalizedModel) {
120 return "", fmt.Errorf(
121 "model %q is unsupported for clnkr agent turns: structured outputs are required and this model does not support that contract",
122 model,
123 )
124 }
125
126 return resolveOpenAIProviderAPI(normalizedModel, providerAPI), nil
127 }
128 return providerAPI, nil
129 }
130
131 func SupportsBashToolCalls(provider Provider, providerAPI ProviderAPI) bool {
132 if provider == ProviderAnthropic {
133 return true
134 }
135 return provider == ProviderOpenAI && providerAPI == ProviderAPIOpenAIResponses
136 }
137
138 func ValidateRequestOptions(
139 provider Provider,
140 providerAPI ProviderAPI,
141 model string,
142 useBashToolCalls bool,
143 opts ProviderRequestOptions,
144 ) (ProviderRequestOptions, error) {
145 if useBashToolCalls && !SupportsBashToolCalls(provider, providerAPI) {
146 if provider == ProviderOpenAI {
147 return ProviderRequestOptions{}, fmt.Errorf(
148 "bash tool calls require provider-api %q for provider openai",
149 ProviderAPIOpenAIResponses,
150 )
151 }
152 return ProviderRequestOptions{}, fmt.Errorf(
153 "bash tool calls are not supported for provider %q",
154 provider,
155 )
156 }
157 opts.Effort.Level = strings.ToLower(strings.TrimSpace(opts.Effort.Level))
158 if opts.Effort.Set {
159 if err := validateEffort(provider, providerAPI, model, opts.Effort.Level); err != nil {
160 return ProviderRequestOptions{}, err
161 }
162 }
163 if opts.Output.MaxOutputTokens.Set {
164 if opts.Output.MaxOutputTokens.Value < 1 {
165 return ProviderRequestOptions{}, fmt.Errorf("max-output-tokens must be at least 1")
166 }
167 if provider == ProviderOpenAI && providerAPI != ProviderAPIOpenAIResponses {
168 return ProviderRequestOptions{}, fmt.Errorf(
169 "max-output-tokens is not supported for provider-api %q",
170 providerAPI,
171 )
172 }
173 if provider == ProviderAnthropic &&
174 opts.Output.MaxOutputTokens.Value > MaxAnthropicNonStreamingTokens {
175 return ProviderRequestOptions{}, fmt.Errorf(
176 "max-output-tokens for anthropic must be at most %d while streaming is unsupported",
177 MaxAnthropicNonStreamingTokens,
178 )
179 }
180 }
181 if opts.AnthropicManual.ThinkingBudgetTokens.Set {
182 if err := validateThinkingBudgetTokens(provider, model, opts); err != nil {
183 return ProviderRequestOptions{}, err
184 }
185 }
186 return opts, nil
187 }
188
189 func validateEffort(provider Provider, providerAPI ProviderAPI, model, effort string) error {
190 if !allowedEffort(effort) {
191 return fmt.Errorf(
192 `invalid effort %q (allowed: auto, low, medium, high, xhigh, max)`,
193 effort,
194 )
195 }
196 if effort == "auto" {
197 return nil
198 }
199 // Non-auto effort
200 if provider == ProviderAnthropic {
201 switch effort {
202 case "low", "medium", "high":
203 return nil
204 default:
205 return fmt.Errorf(
206 `effort %q is not supported for provider anthropic (allowed: low, medium, high)`,
207 effort,
208 )
209 }
210 }
211 if provider == ProviderOpenAI {
212 if providerAPI == ProviderAPIOpenAIChatCompletions {
213 return fmt.Errorf(`effort is not supported for provider-api %q`, providerAPI)
214 }
215 normalizedModel := strings.ToLower(strings.TrimSpace(model))
216 baseModel := stripDatedSnapshotSuffix(normalizedModel)
217 switch effort {
218 case "max":
219 return fmt.Errorf(`effort %q is not supported for OpenAI Responses`, effort)
220 case "xhigh":
221 if !isCodexMaxOrNewerModel(normalizedModel) {
222 return fmt.Errorf(
223 `effort %q is not supported for model %q; xhigh requires codex-max-or-newer`,
224 effort,
225 model,
226 )
227 }
228 case "low", "medium", "high":
229 switch {
230 case baseModel == "gpt-5-pro" && effort != "high":
231 return fmt.Errorf(
232 `effort %q is not supported for model %q; gpt-5-pro only supports high`,
233 effort,
234 model,
235 )
236 case !isReasoningCapableOpenAIModel(normalizedModel):
237 return fmt.Errorf("effort requires an OpenAI reasoning-capable model")
238 }
239 }
240 }
241 return nil
242 }
243
244 func allowedEffort(effort string) bool {
245 switch effort {
246 case "auto", "low", "medium", "high", "xhigh", "max":
247 return true
248 default:
249 return false
250 }
251 }
252
253 func validateThinkingBudgetTokens(
254 provider Provider,
255 model string,
256 opts ProviderRequestOptions,
257 ) error {
258 if provider != ProviderAnthropic {
259 return fmt.Errorf("thinking-budget-tokens requires provider anthropic")
260 }
261 if !isAnthropicExtendedThinkingModel(strings.ToLower(strings.TrimSpace(model))) {
262 return fmt.Errorf(
263 "thinking-budget-tokens requires an Anthropic extended-thinking-capable model",
264 )
265 }
266 if isAnthropicOpus47Plus(model) {
267 return fmt.Errorf(
268 "thinking-budget-tokens is not supported for model %q (Opus 4.7+ does not support manual thinking budget)",
269 model,
270 )
271 }
272 if opts.Effort.Set && opts.Effort.Level != "auto" {
273 return fmt.Errorf(
274 "thinking-budget-tokens requires either no --effort flag or --effort auto; non-auto effort is incompatible with manual thinking budget",
275 )
276 }
277 if opts.AnthropicManual.ThinkingBudgetTokens.Value < MinAnthropicThinkingBudgetTokens {
278 return fmt.Errorf(
279 "thinking-budget-tokens must be at least %d",
280 MinAnthropicThinkingBudgetTokens,
281 )
282 }
283 maxTokens := DefaultAnthropicMaxTokens
284 if opts.Output.MaxOutputTokens.Set {
285 maxTokens = opts.Output.MaxOutputTokens.Value
286 }
287 if opts.AnthropicManual.ThinkingBudgetTokens.Value >= maxTokens {
288 return fmt.Errorf(
289 "thinking-budget-tokens must be less than effective anthropic max_tokens (%d)",
290 maxTokens,
291 )
292 }
293 return nil
294 }
295
296 func resolveOpenAIProviderAPI(model string, providerAPI ProviderAPI) ProviderAPI {
297 if providerAPI == ProviderAPIOpenAIChatCompletions ||
298 providerAPI == ProviderAPIOpenAIResponses {
299 return providerAPI
300 }
301 if isKnownNonOpenAIModel(model) {
302 return ProviderAPIOpenAIChatCompletions
303 }
304 if listedModel(openAIResponsesAllowlist, model) || isOpenAILookingModel(model) {
305 return ProviderAPIOpenAIResponses
306 }
307 return ProviderAPIOpenAIChatCompletions
308 }
309
310 func isKnownNonOpenAIModel(model string) bool {
311 return strings.HasPrefix(model, "chatgpt-") ||
312 strings.HasPrefix(model, "olmo-") ||
313 strings.HasPrefix(model, "openhermes-") ||
314 strings.HasPrefix(model, "orca-")
315 }
316
317 func isOpenAILookingModel(model string) bool {
318 return strings.HasPrefix(model, "gpt-") ||
319 model == "codex" ||
320 strings.HasPrefix(model, "codex-") ||
321 strings.HasSuffix(model, "-codex") ||
322 strings.Contains(model, "-codex-") ||
323 len(model) > 1 && model[0] == 'o' && model[1] >= '0' && model[1] <= '9'
324 }
325
326 func isReasoningCapableOpenAIModel(model string) bool {
327 model = stripDatedSnapshotSuffix(model)
328 return strings.HasPrefix(model, "gpt-5") ||
329 model == "codex" ||
330 strings.HasPrefix(model, "codex-") ||
331 strings.HasSuffix(model, "-codex") ||
332 strings.Contains(model, "-codex-") ||
333 len(model) > 1 && model[0] == 'o' && model[1] >= '0' && model[1] <= '9'
334 }
335
336 func isCodexMaxOrNewerModel(model string) bool {
337 model = stripDatedSnapshotSuffix(model)
338 return strings.Contains(model, "codex-max") ||
339 strings.HasPrefix(model, "gpt-5.2-codex") ||
340 strings.HasPrefix(model, "gpt-5.3-codex") ||
341 strings.HasPrefix(model, "gpt-5.4-codex") ||
342 strings.HasPrefix(model, "codex-max")
343 }
344
345 func isAnthropicExtendedThinkingModel(model string) bool {
346 model = stripDatedSnapshotSuffix(model)
347 return strings.Contains(model, "claude-3-7-sonnet") ||
348 strings.Contains(model, "claude-sonnet-4") ||
349 strings.Contains(model, "claude-opus-4")
350 }
351
352 func isAnthropicOpus47Plus(model string) bool {
353 model = stripDatedSnapshotSuffix(strings.ToLower(strings.TrimSpace(model)))
354 idx := strings.Index(model, "opus-4-")
355 if idx < 0 {
356 return false
357 }
358 after := model[idx+len("opus-4-"):]
359 end := strings.IndexByte(after, '-')
360 if end > 0 {
361 after = after[:end]
362 }
363 if len(after) > 2 {
364 return false
365 }
366 if v, err := strconv.Atoi(after); err == nil {
367 return v >= 7
368 }
369 return false
370 }
371
372 // Keep this matcher intentionally conservative: exact names plus dated snapshots only.
373 func listedModel(models map[string]struct{}, model string) bool {
374 _, ok := models[model]
375 if !ok && datedSnapshotSuffix.MatchString(model) {
376 _, ok = models[model[:len(model)-11]]
377 }
378 return ok
379 }
380
381 func stripDatedSnapshotSuffix(model string) string {
382 if datedSnapshotSuffix.MatchString(model) {
383 return model[:len(model)-11]
384 }
385 return model
386 }