| 1 |
package anthropic |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"context" |
| 6 |
"encoding/json" |
| 7 |
"fmt" |
| 8 |
"io" |
| 9 |
"net/http" |
| 10 |
"net/url" |
| 11 |
"strings" |
| 12 |
"time" |
| 13 |
|
| 14 |
"github.com/clnkr-ai/clnkr" |
| 15 |
) |
| 16 |
|
| 17 |
// ThinkingMode describes how Anthropic thinking is configured. |
| 18 |
type ThinkingMode string |
| 19 |
|
| 20 |
const ( |
| 21 |
ThinkingModeOmitted ThinkingMode = "" |
| 22 |
ThinkingModeEnabled ThinkingMode = "enabled" |
| 23 |
ThinkingModeAdaptive ThinkingMode = "adaptive" |
| 24 |
ThinkingModeManual ThinkingMode = "manual" |
| 25 |
) |
| 26 |
|
| 27 |
// Model talks to the Anthropic Messages API. |
| 28 |
type Model struct { |
| 29 |
baseURL string |
| 30 |
apiKey string |
| 31 |
model string |
| 32 |
systemPrompt string |
| 33 |
maxTokens int |
| 34 |
thinkingBudgetTokens int |
| 35 |
thinkingMode ThinkingMode |
| 36 |
effort string |
| 37 |
useBashToolCalls bool |
| 38 |
unattended bool |
| 39 |
client *http.Client |
| 40 |
} |
| 41 |
|
| 42 |
const DefaultMaxTokens = 4096 |
| 43 |
|
| 44 |
type Options struct { |
| 45 |
MaxTokens int |
| 46 |
ThinkingBudgetTokens int |
| 47 |
ThinkingMode ThinkingMode |
| 48 |
Effort string |
| 49 |
UseBashToolCalls bool |
| 50 |
Unattended bool |
| 51 |
} |
| 52 |
|
| 53 |
// NewModel sets up an Anthropic adapter. |
| 54 |
func NewModel(baseURL, apiKey, model, systemPrompt string) *Model { |
| 55 |
return NewModelWithOptions(baseURL, apiKey, model, systemPrompt, Options{}) |
| 56 |
} |
| 57 |
|
| 58 |
// NewModelWithOptions sets up an Anthropic adapter with request options. |
| 59 |
func NewModelWithOptions(baseURL, apiKey, model, systemPrompt string, opts Options) *Model { |
| 60 |
maxTokens := DefaultMaxTokens |
| 61 |
if opts.MaxTokens > 0 { |
| 62 |
maxTokens = opts.MaxTokens |
| 63 |
} |
| 64 |
return &Model{ |
| 65 |
baseURL: baseURL, |
| 66 |
apiKey: apiKey, |
| 67 |
model: model, |
| 68 |
systemPrompt: systemPrompt, |
| 69 |
maxTokens: maxTokens, |
| 70 |
thinkingBudgetTokens: opts.ThinkingBudgetTokens, |
| 71 |
thinkingMode: opts.ThinkingMode, |
| 72 |
effort: opts.Effort, |
| 73 |
useBashToolCalls: opts.UseBashToolCalls, |
| 74 |
unattended: opts.Unattended, |
| 75 |
client: &http.Client{Timeout: 240 * time.Second}, |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
type request struct { |
| 80 |
Model string `json:"model"` |
| 81 |
MaxTokens int `json:"max_tokens"` |
| 82 |
System string `json:"system,omitempty"` |
| 83 |
Messages []anthropicMessage `json:"messages"` |
| 84 |
OutputConfig *outputConfig `json:"output_config,omitempty"` |
| 85 |
Thinking *thinkingOptions `json:"thinking,omitempty"` |
| 86 |
Tools []anthropicTool `json:"tools,omitempty"` |
| 87 |
} |
| 88 |
|
| 89 |
type textRequest struct { |
| 90 |
Model string `json:"model"` |
| 91 |
MaxTokens int `json:"max_tokens"` |
| 92 |
System string `json:"system,omitempty"` |
| 93 |
Messages []anthropicMessage `json:"messages"` |
| 94 |
OutputConfig *outputConfig `json:"output_config,omitempty"` |
| 95 |
Thinking *thinkingOptions `json:"thinking,omitempty"` |
| 96 |
} |
| 97 |
|
| 98 |
type anthropicMessage struct { |
| 99 |
Role string `json:"role"` |
| 100 |
Content any `json:"content"` |
| 101 |
} |
| 102 |
|
| 103 |
type outputConfig struct { |
| 104 |
Effort string `json:"effort,omitempty"` |
| 105 |
Format *outputFormat `json:"format,omitempty"` |
| 106 |
} |
| 107 |
|
| 108 |
type outputFormat struct { |
| 109 |
Type string `json:"type"` |
| 110 |
Schema map[string]any `json:"schema,omitempty"` |
| 111 |
} |
| 112 |
|
| 113 |
type thinkingOptions struct { |
| 114 |
Type string `json:"type"` |
| 115 |
BudgetTokens int `json:"budget_tokens,omitempty"` |
| 116 |
} |
| 117 |
|
| 118 |
type anthropicTool struct { |
| 119 |
Name string `json:"name"` |
| 120 |
Description string `json:"description,omitempty"` |
| 121 |
InputSchema map[string]any `json:"input_schema"` |
| 122 |
} |
| 123 |
|
| 124 |
type response struct { |
| 125 |
Content []contentBlock `json:"content"` |
| 126 |
StopReason string `json:"stop_reason"` |
| 127 |
Usage struct { |
| 128 |
InputTokens int `json:"input_tokens"` |
| 129 |
OutputTokens int `json:"output_tokens"` |
| 130 |
} `json:"usage"` |
| 131 |
} |
| 132 |
|
| 133 |
type contentBlock struct { |
| 134 |
Type string `json:"type"` |
| 135 |
ID string `json:"id,omitempty"` |
| 136 |
Name string `json:"name,omitempty"` |
| 137 |
Input json.RawMessage `json:"input,omitempty"` |
| 138 |
Text string `json:"text,omitempty"` |
| 139 |
} |
| 140 |
|
| 141 |
const maxResponseBytes = 1 << 20 // 1MB |
| 142 |
|
| 143 |
// extractErrorMessage pulls the message from an API error response body. |
| 144 |
// Handles both {"error":{"message":"..."}} and [{...}] array-wrapped forms. |
| 145 |
// Falls back to the raw body if parsing fails. |
| 146 |
func extractErrorMessage(body []byte) string { |
| 147 |
type errorBody struct { |
| 148 |
Error struct { |
| 149 |
Message string `json:"message"` |
| 150 |
} `json:"error"` |
| 151 |
} |
| 152 |
|
| 153 |
var single errorBody |
| 154 |
if err := json.Unmarshal(body, &single); err == nil && single.Error.Message != "" { |
| 155 |
return single.Error.Message |
| 156 |
} |
| 157 |
|
| 158 |
var arr []errorBody |
| 159 |
if err := json.Unmarshal(body, &arr); err == nil && len(arr) > 0 && arr[0].Error.Message != "" { |
| 160 |
return arr[0].Error.Message |
| 161 |
} |
| 162 |
|
| 163 |
return string(body) |
| 164 |
} |
| 165 |
|
| 166 |
func apiError(statusCode int, message string) error { |
| 167 |
err := fmt.Errorf("api error (status %d): %s", statusCode, message) |
| 168 |
if isContextLengthError(statusCode, message) { |
| 169 |
return fmt.Errorf("%w: %w", clnkr.ErrContextLengthExceeded, err) |
| 170 |
} |
| 171 |
return err |
| 172 |
} |
| 173 |
|
| 174 |
func contextWindowStopReasonError(stopReason string) error { |
| 175 |
if stopReason != "model_context_window_exceeded" { |
| 176 |
return nil |
| 177 |
} |
| 178 |
err := fmt.Errorf("api response stop_reason: %s", stopReason) |
| 179 |
return fmt.Errorf("%w: %w", clnkr.ErrContextLengthExceeded, err) |
| 180 |
} |
| 181 |
|
| 182 |
func isContextLengthError(statusCode int, message string) bool { |
| 183 |
if statusCode != http.StatusBadRequest { |
| 184 |
return false |
| 185 |
} |
| 186 |
normalized := strings.ToLower(message) |
| 187 |
if strings.Contains(normalized, "rate limit") || |
| 188 |
strings.Contains(normalized, "too many requests") || |
| 189 |
strings.Contains(normalized, "throttling") { |
| 190 |
return false |
| 191 |
} |
| 192 |
return strings.Contains(normalized, "context window") || |
| 193 |
strings.Contains(normalized, "prompt is too long") || |
| 194 |
strings.Contains(normalized, "context limit") || |
| 195 |
strings.Contains(normalized, "context length") || |
| 196 |
strings.Contains(normalized, "too many tokens") |
| 197 |
} |
| 198 |
|
| 199 |
func (m *Model) Query(ctx context.Context, messages []clnkr.Message) (clnkr.Response, error) { |
| 200 |
var tools []anthropicTool |
| 201 |
schema := requestSchema() |
| 202 |
if m.unattended { |
| 203 |
schema = unattendedRequestSchema() |
| 204 |
} |
| 205 |
mappedMessages := mapTextMessages(messages) |
| 206 |
if m.useBashToolCalls { |
| 207 |
tools = []anthropicTool{bashToolSchema()} |
| 208 |
schema = finalTurnSchema() |
| 209 |
if m.unattended { |
| 210 |
schema = doneOnlySchema() |
| 211 |
} |
| 212 |
mappedMessages = mapToolCallMessages(messages) |
| 213 |
} |
| 214 |
|
| 215 |
outputCfg := &outputConfig{Format: &outputFormat{Type: "json_schema", Schema: schema}} |
| 216 |
if m.effort != "" { |
| 217 |
outputCfg.Effort = m.effort |
| 218 |
} |
| 219 |
|
| 220 |
body, err := json.Marshal(request{ |
| 221 |
Model: m.model, |
| 222 |
MaxTokens: m.maxTokens, |
| 223 |
System: m.systemPrompt, |
| 224 |
Messages: mappedMessages, |
| 225 |
OutputConfig: outputCfg, |
| 226 |
Thinking: m.thinkingOptions(), |
| 227 |
Tools: tools, |
| 228 |
}) |
| 229 |
if err != nil { |
| 230 |
return clnkr.Response{}, fmt.Errorf("marshal request: %w", err) |
| 231 |
} |
| 232 |
|
| 233 |
respBody, err := m.doRequest(ctx, body) |
| 234 |
if err != nil { |
| 235 |
return clnkr.Response{}, err |
| 236 |
} |
| 237 |
|
| 238 |
var apiResp response |
| 239 |
if err := json.Unmarshal(respBody, &apiResp); err != nil { |
| 240 |
return clnkr.Response{}, fmt.Errorf("unmarshal response: %w", err) |
| 241 |
} |
| 242 |
|
| 243 |
if err := contextWindowStopReasonError(apiResp.StopReason); err != nil { |
| 244 |
return clnkr.Response{}, err |
| 245 |
} |
| 246 |
|
| 247 |
if m.useBashToolCalls { |
| 248 |
return parseToolCallResponse(apiResp, respBody) |
| 249 |
} |
| 250 |
|
| 251 |
text, textBlocks := extractTextBlocks(apiResp.Content) |
| 252 |
if textBlocks != 1 { |
| 253 |
return clnkr.Response{}, fmt.Errorf( |
| 254 |
"structured output response: expected exactly one text block, got %d", |
| 255 |
textBlocks, |
| 256 |
) |
| 257 |
} |
| 258 |
if strings.TrimSpace(text) == "" { |
| 259 |
return clnkr.Response{}, fmt.Errorf("structured output response: empty text payload") |
| 260 |
} |
| 261 |
turn, err := parseProviderTurn(text) |
| 262 |
if err != nil { |
| 263 |
return clnkr.Response{ |
| 264 |
Raw: text, |
| 265 |
Usage: clnkr.Usage{ |
| 266 |
InputTokens: apiResp.Usage.InputTokens, |
| 267 |
OutputTokens: apiResp.Usage.OutputTokens, |
| 268 |
}, |
| 269 |
ProtocolErr: err, |
| 270 |
}, nil |
| 271 |
} |
| 272 |
if _, err := clnkr.CanonicalTurnJSON(turn); err != nil { |
| 273 |
return clnkr.Response{}, fmt.Errorf( |
| 274 |
"structured output response: canonicalize turn payload: %w", |
| 275 |
err, |
| 276 |
) |
| 277 |
} |
| 278 |
return clnkr.Response{ |
| 279 |
Turn: turn, |
| 280 |
Raw: text, |
| 281 |
Usage: clnkr.Usage{ |
| 282 |
InputTokens: apiResp.Usage.InputTokens, |
| 283 |
OutputTokens: apiResp.Usage.OutputTokens, |
| 284 |
}, |
| 285 |
}, nil |
| 286 |
} |
| 287 |
|
| 288 |
func (m *Model) QueryFinal(ctx context.Context, messages []clnkr.Message) (clnkr.Response, error) { |
| 289 |
outputCfg := &outputConfig{Format: &outputFormat{Type: "json_schema", Schema: doneOnlySchema()}} |
| 290 |
if m.effort != "" { |
| 291 |
outputCfg.Effort = m.effort |
| 292 |
} |
| 293 |
body, err := json.Marshal(request{ |
| 294 |
Model: m.model, |
| 295 |
MaxTokens: m.maxTokens, |
| 296 |
System: m.systemPrompt, |
| 297 |
Messages: mapRawMessages(messages), |
| 298 |
OutputConfig: outputCfg, |
| 299 |
Thinking: m.thinkingOptions(), |
| 300 |
}) |
| 301 |
if err != nil { |
| 302 |
return clnkr.Response{}, fmt.Errorf("marshal request: %w", err) |
| 303 |
} |
| 304 |
|
| 305 |
respBody, err := m.doRequest(ctx, body) |
| 306 |
if err != nil { |
| 307 |
return clnkr.Response{}, err |
| 308 |
} |
| 309 |
|
| 310 |
var apiResp response |
| 311 |
if err := json.Unmarshal(respBody, &apiResp); err != nil { |
| 312 |
return clnkr.Response{}, fmt.Errorf("unmarshal response: %w", err) |
| 313 |
} |
| 314 |
if err := contextWindowStopReasonError(apiResp.StopReason); err != nil { |
| 315 |
return clnkr.Response{}, err |
| 316 |
} |
| 317 |
return parseStructuredResponse(apiResp, "structured output response") |
| 318 |
} |
| 319 |
|
| 320 |
func parseStructuredResponse(apiResp response, context string) (clnkr.Response, error) { |
| 321 |
text, textBlocks := extractTextBlocks(apiResp.Content) |
| 322 |
if textBlocks != 1 { |
| 323 |
return clnkr.Response{}, fmt.Errorf( |
| 324 |
"%s: expected exactly one text block, got %d", |
| 325 |
context, |
| 326 |
textBlocks, |
| 327 |
) |
| 328 |
} |
| 329 |
if strings.TrimSpace(text) == "" { |
| 330 |
return clnkr.Response{}, fmt.Errorf("%s: empty text payload", context) |
| 331 |
} |
| 332 |
turn, err := parseProviderTurn(text) |
| 333 |
if err != nil { |
| 334 |
return clnkr.Response{ |
| 335 |
Raw: text, |
| 336 |
Usage: clnkr.Usage{ |
| 337 |
InputTokens: apiResp.Usage.InputTokens, |
| 338 |
OutputTokens: apiResp.Usage.OutputTokens, |
| 339 |
}, |
| 340 |
ProtocolErr: err, |
| 341 |
}, nil |
| 342 |
} |
| 343 |
if _, err := clnkr.CanonicalTurnJSON(turn); err != nil { |
| 344 |
return clnkr.Response{}, fmt.Errorf("%s: canonicalize turn payload: %w", context, err) |
| 345 |
} |
| 346 |
return clnkr.Response{ |
| 347 |
Turn: turn, |
| 348 |
Raw: text, |
| 349 |
Usage: clnkr.Usage{ |
| 350 |
InputTokens: apiResp.Usage.InputTokens, |
| 351 |
OutputTokens: apiResp.Usage.OutputTokens, |
| 352 |
}, |
| 353 |
}, nil |
| 354 |
} |
| 355 |
|
| 356 |
func parseToolCallResponse(apiResp response, raw []byte) (clnkr.Response, error) { |
| 357 |
usage := clnkr.Usage{ |
| 358 |
InputTokens: apiResp.Usage.InputTokens, |
| 359 |
OutputTokens: apiResp.Usage.OutputTokens, |
| 360 |
} |
| 361 |
var toolUses []contentBlock |
| 362 |
var text strings.Builder |
| 363 |
for _, block := range apiResp.Content { |
| 364 |
switch block.Type { |
| 365 |
case "tool_use": |
| 366 |
toolUses = append(toolUses, block) |
| 367 |
case "text": |
| 368 |
text.WriteString(block.Text) |
| 369 |
} |
| 370 |
} |
| 371 |
outputText := text.String() |
| 372 |
if len(toolUses) > 0 { |
| 373 |
actions := make([]clnkr.BashAction, 0, len(toolUses)) |
| 374 |
calls := make([]clnkr.BashToolCall, 0, len(toolUses)) |
| 375 |
for _, toolUse := range toolUses { |
| 376 |
turn, call, err := turnFromToolUse(toolUse) |
| 377 |
if err != nil { |
| 378 |
return clnkr.Response{Raw: string(raw), Usage: usage, ProtocolErr: err}, nil |
| 379 |
} |
| 380 |
act, ok := turn.(*clnkr.ActTurn) |
| 381 |
if !ok || len(act.Bash.Commands) != 1 { |
| 382 |
return clnkr.Response{}, fmt.Errorf( |
| 383 |
"tool-call response: expected one command from tool use", |
| 384 |
) |
| 385 |
} |
| 386 |
actions = append(actions, act.Bash.Commands[0]) |
| 387 |
calls = append(calls, call) |
| 388 |
} |
| 389 |
return clnkr.Response{ |
| 390 |
Turn: &clnkr.ActTurn{ |
| 391 |
Bash: clnkr.BashBatch{Commands: actions}, |
| 392 |
Reasoning: strings.TrimSpace(outputText), |
| 393 |
}, |
| 394 |
Raw: string(raw), |
| 395 |
Usage: usage, |
| 396 |
BashToolCalls: calls, |
| 397 |
}, nil |
| 398 |
} |
| 399 |
if strings.TrimSpace(outputText) == "" { |
| 400 |
return clnkr.Response{}, fmt.Errorf("tool-call response: missing text block or tool_use") |
| 401 |
} |
| 402 |
turn, err := parseProviderTurn(outputText) |
| 403 |
if err != nil { |
| 404 |
return clnkr.Response{Raw: outputText, Usage: usage, ProtocolErr: err}, nil |
| 405 |
} |
| 406 |
if _, ok := turn.(*clnkr.ActTurn); ok { |
| 407 |
return clnkr.Response{ |
| 408 |
Raw: outputText, |
| 409 |
Usage: usage, |
| 410 |
ProtocolErr: fmt.Errorf( |
| 411 |
"%w: tool-call mode does not accept text act turns", |
| 412 |
clnkr.ErrInvalidJSON, |
| 413 |
), |
| 414 |
}, nil |
| 415 |
} |
| 416 |
if _, err := clnkr.CanonicalTurnJSON(turn); err != nil { |
| 417 |
return clnkr.Response{}, fmt.Errorf( |
| 418 |
"tool-call response: canonicalize turn payload: %w", |
| 419 |
err, |
| 420 |
) |
| 421 |
} |
| 422 |
return clnkr.Response{Turn: turn, Raw: outputText, Usage: usage}, nil |
| 423 |
} |
| 424 |
|
| 425 |
func turnFromToolUse(block contentBlock) (clnkr.Turn, clnkr.BashToolCall, error) { |
| 426 |
if strings.TrimSpace(block.ID) == "" { |
| 427 |
return nil, clnkr.BashToolCall{}, fmt.Errorf( |
| 428 |
"%w: bash tool use missing id", |
| 429 |
clnkr.ErrInvalidJSON, |
| 430 |
) |
| 431 |
} |
| 432 |
if block.Name != "bash" { |
| 433 |
return nil, clnkr.BashToolCall{}, fmt.Errorf( |
| 434 |
"%w: unsupported tool %q", |
| 435 |
clnkr.ErrInvalidJSON, |
| 436 |
block.Name, |
| 437 |
) |
| 438 |
} |
| 439 |
var input struct { |
| 440 |
Command string `json:"command"` |
| 441 |
Workdir *string `json:"workdir"` |
| 442 |
} |
| 443 |
dec := json.NewDecoder(bytes.NewReader(block.Input)) |
| 444 |
dec.DisallowUnknownFields() |
| 445 |
if err := dec.Decode(&input); err != nil { |
| 446 |
return nil, clnkr.BashToolCall{}, fmt.Errorf( |
| 447 |
"%w: malformed bash tool input: %v", |
| 448 |
clnkr.ErrInvalidJSON, |
| 449 |
err, |
| 450 |
) |
| 451 |
} |
| 452 |
if strings.TrimSpace(input.Command) == "" { |
| 453 |
return nil, clnkr.BashToolCall{}, clnkr.ErrMissingCommand |
| 454 |
} |
| 455 |
call := clnkr.BashToolCall{ID: block.ID, Command: input.Command} |
| 456 |
action := clnkr.BashAction{ID: block.ID, Command: input.Command} |
| 457 |
if input.Workdir != nil { |
| 458 |
call.Workdir = *input.Workdir |
| 459 |
action.Workdir = *input.Workdir |
| 460 |
} |
| 461 |
return &clnkr.ActTurn{Bash: clnkr.BashBatch{Commands: []clnkr.BashAction{action}}}, call, nil |
| 462 |
} |
| 463 |
|
| 464 |
func (m *Model) QueryText(ctx context.Context, messages []clnkr.Message) (string, error) { |
| 465 |
var outputCfg *outputConfig |
| 466 |
if m.effort != "" { |
| 467 |
outputCfg = &outputConfig{Effort: m.effort} |
| 468 |
} |
| 469 |
body, err := json.Marshal(textRequest{ |
| 470 |
Model: m.model, |
| 471 |
MaxTokens: m.maxTokens, |
| 472 |
System: m.systemPrompt, |
| 473 |
Messages: mapRawMessages(messages), |
| 474 |
OutputConfig: outputCfg, |
| 475 |
Thinking: m.thinkingOptions(), |
| 476 |
}) |
| 477 |
if err != nil { |
| 478 |
return "", fmt.Errorf("marshal request: %w", err) |
| 479 |
} |
| 480 |
|
| 481 |
respBody, err := m.doRequest(ctx, body) |
| 482 |
if err != nil { |
| 483 |
return "", err |
| 484 |
} |
| 485 |
|
| 486 |
var apiResp response |
| 487 |
if err := json.Unmarshal(respBody, &apiResp); err != nil { |
| 488 |
return "", fmt.Errorf("unmarshal response: %w", err) |
| 489 |
} |
| 490 |
if err := contextWindowStopReasonError(apiResp.StopReason); err != nil { |
| 491 |
return "", err |
| 492 |
} |
| 493 |
text, textBlocks := extractTextBlocks(apiResp.Content) |
| 494 |
if textBlocks == 0 { |
| 495 |
return "", fmt.Errorf("free-form response: missing text block") |
| 496 |
} |
| 497 |
if strings.TrimSpace(text) == "" { |
| 498 |
return "", fmt.Errorf("free-form response: empty text payload") |
| 499 |
} |
| 500 |
return text, nil |
| 501 |
} |
| 502 |
|
| 503 |
func mapTextMessages(messages []clnkr.Message) []anthropicMessage { |
| 504 |
normalized := normalizeMessagesForProvider(messages) |
| 505 |
return mapRawMessages(normalized) |
| 506 |
} |
| 507 |
|
| 508 |
func mapRawMessages(messages []clnkr.Message) []anthropicMessage { |
| 509 |
mapped := make([]anthropicMessage, 0, len(messages)) |
| 510 |
for _, msg := range messages { |
| 511 |
mapped = append(mapped, anthropicMessage{Role: msg.Role, Content: msg.Content}) |
| 512 |
} |
| 513 |
return mapped |
| 514 |
} |
| 515 |
|
| 516 |
func mapToolCallMessages(messages []clnkr.Message) []anthropicMessage { |
| 517 |
normalized := normalizeMessagesForProvider(messages) |
| 518 |
mapped := make([]anthropicMessage, 0, len(normalized)) |
| 519 |
knownCalls := make(map[string]struct{}) |
| 520 |
for i := 0; i < len(normalized); i++ { |
| 521 |
msg := normalized[i] |
| 522 |
if msg.Role == "assistant" && len(msg.BashToolCalls) > 0 { |
| 523 |
blocks := make([]map[string]any, 0, len(msg.BashToolCalls)) |
| 524 |
for _, call := range msg.BashToolCalls { |
| 525 |
knownCalls[call.ID] = struct{}{} |
| 526 |
blocks = append(blocks, toolUseBlock(call)) |
| 527 |
} |
| 528 |
mapped = append(mapped, anthropicMessage{Role: "assistant", Content: blocks}) |
| 529 |
continue |
| 530 |
} |
| 531 |
if msg.BashToolResult != nil { |
| 532 |
if _, ok := knownCalls[msg.BashToolResult.ID]; ok { |
| 533 |
blocks := make([]map[string]any, 0, 1) |
| 534 |
for ; i < len(normalized); i++ { |
| 535 |
next := normalized[i] |
| 536 |
if next.BashToolResult == nil { |
| 537 |
break |
| 538 |
} |
| 539 |
if _, ok := knownCalls[next.BashToolResult.ID]; !ok { |
| 540 |
break |
| 541 |
} |
| 542 |
blocks = append(blocks, toolResultBlock(*next.BashToolResult)) |
| 543 |
} |
| 544 |
mapped = append(mapped, anthropicMessage{ |
| 545 |
Role: "user", |
| 546 |
Content: blocks, |
| 547 |
}) |
| 548 |
i-- |
| 549 |
continue |
| 550 |
} |
| 551 |
} |
| 552 |
mapped = append(mapped, anthropicMessage{Role: msg.Role, Content: msg.Content}) |
| 553 |
} |
| 554 |
return mapped |
| 555 |
} |
| 556 |
|
| 557 |
func toolResultBlock(result clnkr.BashToolResult) map[string]any { |
| 558 |
block := map[string]any{ |
| 559 |
"type": "tool_result", |
| 560 |
"tool_use_id": result.ID, |
| 561 |
"content": result.Content, |
| 562 |
} |
| 563 |
if result.IsError { |
| 564 |
block["is_error"] = true |
| 565 |
} |
| 566 |
return block |
| 567 |
} |
| 568 |
|
| 569 |
func toolUseBlock(call clnkr.BashToolCall) map[string]any { |
| 570 |
input := map[string]any{"command": call.Command, "workdir": nil} |
| 571 |
if call.Workdir != "" { |
| 572 |
input["workdir"] = call.Workdir |
| 573 |
} |
| 574 |
return map[string]any{ |
| 575 |
"type": "tool_use", |
| 576 |
"id": call.ID, |
| 577 |
"name": "bash", |
| 578 |
"input": input, |
| 579 |
} |
| 580 |
} |
| 581 |
|
| 582 |
func bashToolSchema() anthropicTool { |
| 583 |
return anthropicTool{ |
| 584 |
Name: "bash", |
| 585 |
Description: "Run one bash command in the current clnkr shell session.", |
| 586 |
InputSchema: map[string]any{ |
| 587 |
"type": "object", |
| 588 |
"additionalProperties": false, |
| 589 |
"properties": map[string]any{ |
| 590 |
"command": map[string]any{"type": "string"}, |
| 591 |
"workdir": map[string]any{ |
| 592 |
"anyOf": []any{ |
| 593 |
map[string]any{"type": "string"}, |
| 594 |
map[string]any{"type": "null"}, |
| 595 |
}, |
| 596 |
}, |
| 597 |
}, |
| 598 |
"required": []string{"command", "workdir"}, |
| 599 |
}, |
| 600 |
} |
| 601 |
} |
| 602 |
|
| 603 |
func (m *Model) thinkingOptions() *thinkingOptions { |
| 604 |
if m.thinkingMode == ThinkingModeOmitted && m.thinkingBudgetTokens == 0 { |
| 605 |
return nil |
| 606 |
} |
| 607 |
// Auto-derive mode from legacy ThinkingBudgetTokens field. |
| 608 |
if m.thinkingMode == ThinkingModeOmitted && m.thinkingBudgetTokens > 0 { |
| 609 |
m.thinkingMode = ThinkingModeManual |
| 610 |
} |
| 611 |
anthropicType := m.thinkingMode |
| 612 |
if m.thinkingMode == ThinkingModeManual { |
| 613 |
anthropicType = ThinkingModeEnabled |
| 614 |
} |
| 615 |
to := &thinkingOptions{Type: string(anthropicType)} |
| 616 |
if m.thinkingMode == ThinkingModeManual && m.thinkingBudgetTokens > 0 { |
| 617 |
to.BudgetTokens = m.thinkingBudgetTokens |
| 618 |
} |
| 619 |
return to |
| 620 |
} |
| 621 |
|
| 622 |
func (m *Model) doRequest(ctx context.Context, body []byte) ([]byte, error) { |
| 623 |
req, err := http.NewRequestWithContext( |
| 624 |
ctx, |
| 625 |
"POST", |
| 626 |
endpointURL(m.baseURL, "/v1/messages"), |
| 627 |
bytes.NewReader(body), |
| 628 |
) |
| 629 |
if err != nil { |
| 630 |
return nil, fmt.Errorf("create request: %w", err) |
| 631 |
} |
| 632 |
req.Header.Set("Content-Type", "application/json") |
| 633 |
req.Header.Set("x-api-key", m.apiKey) |
| 634 |
req.Header.Set("anthropic-version", "2023-06-01") |
| 635 |
|
| 636 |
resp, err := m.client.Do(req) |
| 637 |
if err != nil { |
| 638 |
return nil, fmt.Errorf("send request: %w", err) |
| 639 |
} |
| 640 |
defer resp.Body.Close() //nolint:errcheck // best-effort cleanup |
| 641 |
|
| 642 |
respBody, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes)) |
| 643 |
if err != nil { |
| 644 |
return nil, fmt.Errorf("read response: %w", err) |
| 645 |
} |
| 646 |
if resp.StatusCode != http.StatusOK { |
| 647 |
return nil, apiError(resp.StatusCode, extractErrorMessage(respBody)) |
| 648 |
} |
| 649 |
return respBody, nil |
| 650 |
} |
| 651 |
|
| 652 |
func endpointURL(baseURL, endpoint string) string { |
| 653 |
parsed, err := url.Parse(baseURL) |
| 654 |
if err != nil || parsed.Scheme == "" || parsed.Host == "" || parsed.Opaque != "" { |
| 655 |
return joinURLBoundary(baseURL, endpoint) |
| 656 |
} |
| 657 |
|
| 658 |
escapedPath := strings.TrimRight( |
| 659 |
parsed.EscapedPath(), |
| 660 |
"/", |
| 661 |
) + "/" + strings.TrimLeft( |
| 662 |
endpoint, |
| 663 |
"/", |
| 664 |
) |
| 665 |
decodedPath, err := url.PathUnescape(escapedPath) |
| 666 |
if err != nil { |
| 667 |
return joinURLBoundary(baseURL, endpoint) |
| 668 |
} |
| 669 |
parsed.Path = decodedPath |
| 670 |
parsed.RawPath = "" |
| 671 |
if escapedPath != (&url.URL{Path: decodedPath}).EscapedPath() { |
| 672 |
parsed.RawPath = escapedPath |
| 673 |
} |
| 674 |
return parsed.String() |
| 675 |
} |
| 676 |
|
| 677 |
func joinURLBoundary(baseURL, endpoint string) string { |
| 678 |
return strings.TrimRight(baseURL, "/") + "/" + strings.TrimLeft(endpoint, "/") |
| 679 |
} |
| 680 |
|
| 681 |
func extractTextBlocks(blocks []contentBlock) (string, int) { |
| 682 |
var text string |
| 683 |
textBlocks := 0 |
| 684 |
for _, block := range blocks { |
| 685 |
if block.Type == "text" { |
| 686 |
textBlocks++ |
| 687 |
text += block.Text |
| 688 |
} |
| 689 |
} |
| 690 |
return text, textBlocks |
| 691 |
} |