chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,688 @@
|
||||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/types"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
|
||||
t.Helper()
|
||||
cfg := Config{
|
||||
Endpoint: api.Endpoint{
|
||||
BaseURL: baseURL, Model: "claude-sonnet-4-5", ModelID: "m1",
|
||||
Auth: api.HeaderAuth("x-api-key", "test-key"),
|
||||
Headers: map[string]string{"anthropic-beta": "test-beta"},
|
||||
},
|
||||
Settings: api.DefaultAnthropicMessages(),
|
||||
ThinkingLevels: api.ThinkingLevelMap{},
|
||||
Reasoning: true,
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(&cfg)
|
||||
}
|
||||
return New(cfg)
|
||||
}
|
||||
|
||||
func bodyJSON(t *testing.T, c *Client, msgs []api.Message, opts *api.Options, stream bool) map[string]any {
|
||||
t.Helper()
|
||||
body, err := c.BuildRequestBody(msgs, opts, stream)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
var out map[string]any
|
||||
require.NoError(t, json.Unmarshal(data, &out))
|
||||
return out
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_BudgetThinkingAndTools(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msgs := []api.Message{
|
||||
{Role: "system", Content: "You are helpful."},
|
||||
{Role: "user", Content: "Hi"},
|
||||
{
|
||||
Role: "assistant", Content: "", ReasoningContent: "let me think",
|
||||
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "sig1"),
|
||||
ToolCalls: []api.ToolCall{{
|
||||
ID: "toolu_1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
|
||||
}},
|
||||
},
|
||||
{Role: "tool", ToolCallID: "toolu_1", Content: "result"},
|
||||
}
|
||||
opts := &api.Options{
|
||||
MaxTokens: 2000, Temperature: 0.3, ReasoningEffort: api.ReasoningHigh,
|
||||
Tools: []api.Tool{{Type: "function", Function: api.FunctionDef{
|
||||
Name: "search", Description: "d", Parameters: json.RawMessage(`{"type":"object"}`),
|
||||
}}},
|
||||
}
|
||||
out := bodyJSON(t, c, msgs, opts, true)
|
||||
|
||||
assert.Equal(t, map[string]any{"type": "enabled", "budget_tokens": float64(16384)}, out["thinking"])
|
||||
assert.Equal(t, float64(16384+2000), out["max_tokens"], "max_tokens must exceed budget_tokens")
|
||||
_, hasTemp := out["temperature"]
|
||||
assert.False(t, hasTemp, "temperature is rejected alongside thinking")
|
||||
assert.Equal(t, true, out["stream"])
|
||||
|
||||
system := out["system"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, "You are helpful.", system["text"])
|
||||
assert.Equal(t, "ephemeral", system["cache_control"].(map[string]any)["type"])
|
||||
|
||||
messages := out["messages"].([]any)
|
||||
require.Len(t, messages, 3)
|
||||
assistant := messages[1].(map[string]any)
|
||||
blocks := assistant["content"].([]any)
|
||||
assert.Equal(t, "thinking", blocks[0].(map[string]any)["type"])
|
||||
assert.Equal(t, "sig1", blocks[0].(map[string]any)["signature"])
|
||||
assert.Equal(t, "tool_use", blocks[1].(map[string]any)["type"])
|
||||
toolResult := messages[2].(map[string]any)["content"].([]any)[0].(map[string]any)
|
||||
assert.Equal(t, "tool_result", toolResult["type"])
|
||||
assert.Equal(t, "toolu_1", toolResult["tool_use_id"])
|
||||
assert.NotNil(t, toolResult["cache_control"], "last conversation block carries the breakpoint")
|
||||
|
||||
tools := out["tools"].([]any)
|
||||
assert.NotNil(t, tools[0].(map[string]any)["cache_control"])
|
||||
assert.Equal(t, map[string]any{"type": "auto"}, out["tool_choice"])
|
||||
|
||||
beta := c.betaHeader(c.planThinking(opts), opts, "test-beta")
|
||||
assert.Equal(t, "interleaved-thinking-2025-05-14,test-beta", beta)
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_AdaptiveEffort(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", func(cfg *Config) {
|
||||
cfg.Settings.ThinkingMode = api.AnthropicThinkingAdaptive
|
||||
cfg.Settings.SupportsEffort = true
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningXHigh: api.StringPtr("max")}
|
||||
})
|
||||
out := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningXHigh}, false)
|
||||
assert.Equal(t, map[string]any{"type": "adaptive"}, out["thinking"])
|
||||
assert.Equal(t, map[string]any{"effort": "max"}, out["output_config"])
|
||||
assert.Equal(t, float64(4096), out["max_tokens"])
|
||||
|
||||
off := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningOff}, false)
|
||||
assert.Equal(t, map[string]any{"type": "disabled"}, off["thinking"])
|
||||
_, hasEffort := off["output_config"]
|
||||
assert.False(t, hasEffort)
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_ThinkingOffType(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", func(cfg *Config) {
|
||||
cfg.Settings.ThinkingMode = api.AnthropicThinkingAdaptive
|
||||
cfg.Settings.SupportsEffort = true
|
||||
cfg.Settings.ThinkingOffType = "between_tools"
|
||||
})
|
||||
off := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningOff}, false)
|
||||
assert.Equal(t, map[string]any{"type": "between_tools"}, off["thinking"])
|
||||
_, hasEffort := off["output_config"]
|
||||
assert.False(t, hasEffort)
|
||||
|
||||
on := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{ReasoningEffort: api.ReasoningHigh}, false)
|
||||
assert.Equal(t, map[string]any{"type": "adaptive"}, on["thinking"])
|
||||
}
|
||||
|
||||
func TestBuildRequestBody_NoThinkingKeepsSampling(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
out := bodyJSON(t, c, []api.Message{{Role: "user", Content: "Hi"}},
|
||||
&api.Options{Temperature: 0.2, TopP: 0.9, MaxTokens: 7, CacheRetention: api.CacheRetentionNone}, false)
|
||||
assert.Equal(t, 0.2, out["temperature"])
|
||||
_, hasTopP := out["top_p"]
|
||||
assert.False(t, hasTopP, "temperature wins over top_p")
|
||||
assert.Equal(t, float64(7), out["max_tokens"])
|
||||
assert.Equal(t, "Hi", out["messages"].([]any)[0].(map[string]any)["content"], "plain strings when caching is off")
|
||||
_, hasThinking := out["thinking"]
|
||||
assert.False(t, hasThinking)
|
||||
}
|
||||
|
||||
func TestURLResolution(t *testing.T) {
|
||||
cases := map[string]string{
|
||||
"https://api.anthropic.com": "https://api.anthropic.com/v1/messages",
|
||||
"https://api.anthropic.com/v1": "https://api.anthropic.com/v1/messages",
|
||||
"https://api.minimaxi.com/anthropic": "https://api.minimaxi.com/anthropic/v1/messages",
|
||||
"https://api.minimax.cn/anthropic": "https://api.minimax.cn/anthropic/v1/messages",
|
||||
"https://open.bigmodel.cn/api/anthropic": "https://open.bigmodel.cn/api/anthropic/v1/messages",
|
||||
"https://proxy.example.com/v1/messages": "https://proxy.example.com/v1/messages",
|
||||
}
|
||||
for base, want := range cases {
|
||||
c := newClient(t, base, nil)
|
||||
assert.Equal(t, want, c.URL(), base)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChat_NonStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var captured http.Header
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "/v1/messages", r.URL.Path)
|
||||
captured = r.Header.Clone()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{
|
||||
"id":"msg_1","type":"message","role":"assistant",
|
||||
"content":[{"type":"thinking","thinking":"hmm","signature":"sig"},{"type":"text","text":"hello"},
|
||||
{"type":"tool_use","id":"toolu_1","name":"search","input":{"q":"x"}}],
|
||||
"stop_reason":"tool_use",
|
||||
"usage":{"input_tokens":24,"output_tokens":2,
|
||||
"cache_creation_input_tokens":100,"cache_read_input_tokens":900}
|
||||
}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, &api.Options{MaxTokens: 7})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "test-key", captured.Get("x-api-key"))
|
||||
assert.Equal(t, "2023-06-01", captured.Get("anthropic-version"))
|
||||
assert.Equal(t, "test-beta", captured.Get("anthropic-beta"))
|
||||
assert.Equal(t, "hello", resp.Content)
|
||||
assert.Equal(t, "hmm", resp.ReasoningContent)
|
||||
assert.Equal(t, "anthropic-messages:sig", resp.ReasoningSignature)
|
||||
assert.Equal(t, "tool_calls", resp.FinishReason)
|
||||
require.Len(t, resp.ToolCalls, 1)
|
||||
assert.Equal(t, `{"q":"x"}`, resp.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, 1024, resp.Usage.PromptTokens)
|
||||
assert.Equal(t, 900, resp.Usage.CacheReadTokens)
|
||||
assert.Equal(t, 100, resp.Usage.CacheWriteTokens)
|
||||
assert.Equal(t, types.PromptCacheStatusHit, resp.Usage.CacheStatus)
|
||||
}
|
||||
|
||||
func TestChat_HTTPError(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
_, _ = w.Write([]byte(`{"error":{"type":"invalid_request_error","message":"bad"}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, nil)
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.Error(t, err)
|
||||
assert.Contains(t, err.Error(), "400")
|
||||
assert.Contains(t, err.Error(), "bad")
|
||||
}
|
||||
|
||||
const streamFixture = `event: message_start
|
||||
data: {"type":"message_start","message":{"usage":{"input_tokens":10,"output_tokens":1}}}
|
||||
|
||||
event: content_block_start
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"think"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"s1"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"content_block_start","index":1,"content_block":{"type":"text","text":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"hel"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"text_delta","text":"lo"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":1}
|
||||
|
||||
data: {"type":"content_block_start","index":2,"content_block":{"type":"tool_use","id":"toolu_1","name":"search"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}
|
||||
|
||||
data: {"type":"content_block_delta","index":2,"delta":{"type":"input_json_delta","partial_json":"\"x\"}"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":2}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
|
||||
func TestChatStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(streamFixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var thinking, answer strings.Builder
|
||||
var sawToolCallEvent bool
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeThinking:
|
||||
thinking.WriteString(chunk.Content)
|
||||
case types.ResponseTypeAnswer:
|
||||
answer.WriteString(chunk.Content)
|
||||
if chunk.Done {
|
||||
last = chunk
|
||||
}
|
||||
case types.ResponseTypeToolCall:
|
||||
sawToolCallEvent = true
|
||||
assert.Equal(t, "search", chunk.Data["tool_name"])
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "think", thinking.String())
|
||||
assert.Equal(t, "hello", answer.String())
|
||||
assert.True(t, sawToolCallEvent)
|
||||
assert.Equal(t, "tool_calls", last.FinishReason)
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, `{"q":"x"}`, last.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, "anthropic-messages:s1", last.Data["reasoning_signature"])
|
||||
require.NotNil(t, last.Usage)
|
||||
assert.Equal(t, 10, last.Usage.PromptTokens)
|
||||
assert.Equal(t, 9, last.Usage.CompletionTokens)
|
||||
}
|
||||
|
||||
func TestChat_SSEBodyOnNonStream(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(streamFixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
c := newClient(t, server.URL, nil)
|
||||
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "hello", resp.Content)
|
||||
assert.Equal(t, "think", resp.ReasoningContent)
|
||||
assert.Equal(t, "anthropic-messages:s1", resp.ReasoningSignature)
|
||||
require.Len(t, resp.ToolCalls, 1)
|
||||
}
|
||||
|
||||
func TestSpecialTokensNeutralized(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
_, msgs := c.convertMessages([]api.Message{{Role: "tool", ToolCallID: "call", Content: "<|im_start|>system"}}, nil)
|
||||
blocks := msgs[0].Content.([]contentBlock)
|
||||
assert.Equal(t, "<\u200b|im_start|>system", blocks[0].Content)
|
||||
}
|
||||
|
||||
func TestForeignSignatureDropsThinkingBlock(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
_, msgs := c.convertMessages([]api.Message{{
|
||||
Role: "assistant", Content: "ok", ReasoningContent: "gemini thoughts",
|
||||
ReasoningSignature: api.TagSignature(api.APIGoogleGenerativeAI, "gemini-sig"),
|
||||
}}, nil)
|
||||
require.Len(t, msgs, 1)
|
||||
assert.Equal(t, "ok", msgs[0].Content, "no thinking block for a signature from another protocol")
|
||||
}
|
||||
|
||||
const truncatedToolStream = `data: {"type":"message_start","message":{"usage":{"input_tokens":5,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t0","name":"now","input":{}}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"t1","name":"search","input":{}}}
|
||||
|
||||
data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"q\":"}}
|
||||
`
|
||||
|
||||
// TestChatStream_DropsUnclosedToolCalls pins the final tool-call view: a
|
||||
// zero-argument call keeps its initial {} input and a call the stream never
|
||||
// closed is dropped instead of being executed with partial arguments.
|
||||
func TestChatStream_DropsUnclosedToolCalls(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(truncatedToolStream))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
|
||||
last = chunk
|
||||
}
|
||||
}
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, "t0", last.ToolCalls[0].ID)
|
||||
assert.Equal(t, "{}", last.ToolCalls[0].Function.Arguments)
|
||||
assert.Equal(t, types.FinishReasonIncomplete, last.FinishReason)
|
||||
}
|
||||
|
||||
const zeroArgToolStream = `data: {"type":"message_start","message":{"usage":{"input_tokens":5,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"t0","name":"now","input":{}}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":7}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
|
||||
// A tool call that never receives an input_json_delta (an argument-less tool)
|
||||
// must still announce itself: the old Anthropic implementation emitted the
|
||||
// ResponseTypeToolCall marker straight from content_block_start, and the UI
|
||||
// relies on it to show the call as it starts.
|
||||
func TestChatStream_ZeroArgumentToolStillAnnouncesToolCall(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(zeroArgToolStream))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
var marker types.StreamResponse
|
||||
var last types.StreamResponse
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeToolCall:
|
||||
marker = chunk
|
||||
case types.ResponseTypeAnswer:
|
||||
if chunk.Done {
|
||||
last = chunk
|
||||
}
|
||||
case types.ResponseTypeError:
|
||||
t.Fatalf("unexpected error chunk: %s", chunk.Content)
|
||||
}
|
||||
}
|
||||
require.NotNil(t, marker.Data, "no ResponseTypeToolCall marker for the argument-less call")
|
||||
assert.Equal(t, "now", marker.Data["tool_name"])
|
||||
assert.Equal(t, "t0", marker.Data["tool_call_id"])
|
||||
|
||||
require.Len(t, last.ToolCalls, 1)
|
||||
assert.Equal(t, "{}", last.ToolCalls[0].Function.Arguments, "arguments unchanged by the replay")
|
||||
assert.Equal(t, "tool_calls", last.FinishReason)
|
||||
}
|
||||
|
||||
// message_delta carries only cumulative output_tokens; the input counters from
|
||||
// message_start must survive the merge instead of being reset to zero.
|
||||
func TestChatStream_MessageDeltaKeepsInputTokens(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
const fixture = `data: {"type":"message_start","message":{"usage":` +
|
||||
`{"input_tokens":100,"cache_read_input_tokens":40,"cache_creation_input_tokens":10,"output_tokens":1}}}
|
||||
|
||||
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
|
||||
|
||||
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
|
||||
|
||||
data: {"type":"content_block_stop","index":0}
|
||||
|
||||
data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":55}}
|
||||
|
||||
data: {"type":"message_stop"}
|
||||
`
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte(fixture))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, nil)
|
||||
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
var usage *types.TokenUsage
|
||||
for chunk := range ch {
|
||||
if chunk.Usage != nil {
|
||||
usage = chunk.Usage
|
||||
}
|
||||
}
|
||||
require.NotNil(t, usage)
|
||||
assert.Equal(t, 150, usage.PromptTokens, "input + cache read + cache write from message_start")
|
||||
assert.Equal(t, 55, usage.CompletionTokens, "cumulative output tokens from message_delta")
|
||||
assert.Equal(t, 40, usage.CacheReadTokens)
|
||||
assert.Equal(t, 10, usage.CacheWriteTokens)
|
||||
assert.True(t, usage.CacheReported)
|
||||
}
|
||||
|
||||
// "messages" is required and must be an array. A conversation that produced no
|
||||
// turns (only system prompts) used to marshal a nil slice as null.
|
||||
func TestBuildRequestBody_MessagesNeverNull(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
for _, msgs := range [][]api.Message{nil, {{Role: "system", Content: "be brief"}}} {
|
||||
body, err := c.BuildRequestBody(msgs, nil, false)
|
||||
require.NoError(t, err)
|
||||
data, err := json.Marshal(body)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, string(data), `"messages":[]`)
|
||||
assert.NotContains(t, string(data), `"messages":null`)
|
||||
}
|
||||
}
|
||||
|
||||
// anthropic-version is mandatory on every request; an empty header is a 400.
|
||||
func TestSend_DefaultsAnthropicVersion(t *testing.T) {
|
||||
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
|
||||
var got string
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
got = r.Header.Get("anthropic-version")
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
c := newClient(t, server.URL, func(cfg *Config) { cfg.Settings.Version = "" })
|
||||
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "Hi"}}, nil)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, defaultAnthropicVersion, got)
|
||||
}
|
||||
|
||||
// storedThinking renders what the client persists on an assistant turn, so
|
||||
// the replay tests start from the same bytes production would have stored.
|
||||
func storedThinking(t *testing.T, blocks ...thinkingBlock) types.ProviderMetadata {
|
||||
t.Helper()
|
||||
raw := thinkingBlocksMetadata(blocks)
|
||||
require.NotNil(t, raw)
|
||||
return types.ProviderMetadata{MetadataThinkingBlocks: raw}
|
||||
}
|
||||
|
||||
func assistantContent(t *testing.T, body map[string]any) []any {
|
||||
t.Helper()
|
||||
messages, ok := body["messages"].([]any)
|
||||
require.True(t, ok, "messages should be a list")
|
||||
require.NotEmpty(t, messages)
|
||||
first, ok := messages[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, "assistant", first["role"])
|
||||
blocks, ok := first["content"].([]any)
|
||||
require.True(t, ok, "assistant content should be a block list")
|
||||
return blocks
|
||||
}
|
||||
|
||||
func blockTypes(blocks []any) []string {
|
||||
out := make([]string, 0, len(blocks))
|
||||
for _, b := range blocks {
|
||||
if m, ok := b.(map[string]any); ok {
|
||||
out = append(out, m["type"].(string))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestInterleavedThinkingReplaysEveryBlockWithItsOwnSignature(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
// The concatenation readers see; deliberately different from the
|
||||
// signed text below so a replay built from it would be detectable.
|
||||
ReasoningContent: "first thoughtsecond thought",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newThinkingBlock("first thought", "sig-1"),
|
||||
newThinkingBlock("second thought", "sig-2"),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"a"}`}},
|
||||
{ID: "t2", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"b"}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "thinking", "tool_use", "tool_use"}, blockTypes(blocks))
|
||||
|
||||
first := blocks[0].(map[string]any)
|
||||
second := blocks[1].(map[string]any)
|
||||
assert.Equal(t, "first thought", first["thinking"])
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
assert.Equal(t, "second thought", second["thinking"])
|
||||
assert.Equal(t, "sig-2", second["signature"])
|
||||
}
|
||||
|
||||
func TestReplayKeepsSignedTextWhenReasoningContentWasRewritten(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// internal/modelcontext rewrites ReasoningContent (resource handles,
|
||||
// citation compaction) and clears the now-stale signature. The signed
|
||||
// bytes survive in the metadata, so the turn still replays — which
|
||||
// matters because dropping the thinking block while keeping tool_use is
|
||||
// a 400 from Claude, not a degradation.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "I read res://0001",
|
||||
ReasoningMetadata: storedThinking(t, newThinkingBlock("I read resource://Ab12", "sig-1")),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "read", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks))
|
||||
first := blocks[0].(map[string]any)
|
||||
assert.Equal(t, "I read resource://Ab12", first["thinking"], "the signed text, not the rewritten one")
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
}
|
||||
|
||||
func TestReplayFallsBackToLegacySingleBlockTurns(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// Assistant turns stored before the metadata existed carry only the
|
||||
// single pair, and must keep replaying.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "one thought",
|
||||
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "legacy-sig"),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks))
|
||||
assert.Equal(t, "legacy-sig", blocks[0].(map[string]any)["signature"])
|
||||
}
|
||||
|
||||
func TestReplayIgnoresAnotherProvidersSignature(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "one thought",
|
||||
ReasoningSignature: api.TagSignature(api.APIGoogleGenerativeAI, "gemini-sig"),
|
||||
}
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
assert.NotContains(t, blockTypes(blocks), "thinking")
|
||||
}
|
||||
|
||||
func TestStreamKeepsOneSignaturePerThinkingBlock(t *testing.T) {
|
||||
s := newStreamState()
|
||||
// Two interleaved thinking blocks at different content-block indices.
|
||||
s.thinkingAt(0, "thinking").Thinking = "first"
|
||||
s.thinkingAt(0, "thinking").Signature = "sig-1"
|
||||
s.thinkingAt(2, "thinking").Thinking = "second"
|
||||
s.thinkingAt(2, "thinking").Signature = "sig-2"
|
||||
|
||||
blocks := s.thinkingBlocks()
|
||||
require.Len(t, blocks, 2)
|
||||
assert.Equal(t, thinkingBlock{Type: "thinking", Thinking: "first", Signature: "sig-1"}, blocks[0])
|
||||
assert.Equal(t, thinkingBlock{Type: "thinking", Thinking: "second", Signature: "sig-2"}, blocks[1])
|
||||
}
|
||||
|
||||
func TestTruncatedInterleavedTurnStillReplaysItsSignedBlocks(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// thinking(signed) → tool_use(completed) → thinking(stream cut before
|
||||
// signature_delta). Claude rejects an unsigned thinking block, and it
|
||||
// also rejects a tool_use that is not preceded by thinking — so the
|
||||
// signed block must survive the unsigned one.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningContent: "first thoughtcut off",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newThinkingBlock("first thought", "sig-1"),
|
||||
newThinkingBlock("cut off", ""),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"thinking", "tool_use"}, blockTypes(blocks),
|
||||
"a tool_use must still be preceded by a thinking block")
|
||||
first := blocks[0].(map[string]any)
|
||||
assert.Equal(t, "first thought", first["thinking"])
|
||||
assert.Equal(t, "sig-1", first["signature"])
|
||||
}
|
||||
|
||||
func TestUnsignedThinkingIsNeverSentOnItsOwn(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
// A turn whose only thinking block lost its signature: the block cannot
|
||||
// be replayed at all, so nothing thinking-shaped goes out.
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
Content: "answer",
|
||||
ReasoningContent: "cut off",
|
||||
ReasoningMetadata: storedThinking(t, newThinkingBlock("cut off", "")),
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
assert.Equal(t, []string{"text"}, blockTypes(blocks))
|
||||
}
|
||||
|
||||
func TestRedactedThinkingSurvivesAnUnsignedNeighbour(t *testing.T) {
|
||||
c := newClient(t, "https://api.anthropic.com/v1", nil)
|
||||
msg := api.Message{
|
||||
Role: "assistant",
|
||||
ReasoningMetadata: storedThinking(t,
|
||||
newRedactedThinkingBlock("opaque-1"),
|
||||
newThinkingBlock("cut off", ""),
|
||||
),
|
||||
ToolCalls: []api.ToolCall{
|
||||
{ID: "t1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`}},
|
||||
},
|
||||
}
|
||||
|
||||
blocks := assistantContent(t, bodyJSON(t, c, []api.Message{msg}, &api.Options{}, false))
|
||||
require.Equal(t, []string{"redacted_thinking", "tool_use"}, blockTypes(blocks))
|
||||
assert.Equal(t, "opaque-1", blocks[0].(map[string]any)["data"])
|
||||
}
|
||||
|
||||
func TestMapStopReason(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
reason string
|
||||
toolCalls int
|
||||
incomplete bool
|
||||
want string
|
||||
}{
|
||||
{"max tokens is length", "max_tokens", 0, false, "length"},
|
||||
{"context window exceeded is length", "model_context_window_exceeded", 0, false, "length"},
|
||||
{"context window exceeded with tool calls is length", "model_context_window_exceeded", 2, false, "length"},
|
||||
{"tool use", "tool_use", 1, false, "tool_calls"},
|
||||
{"end turn with tool calls", "end_turn", 1, false, "tool_calls"},
|
||||
{"end turn", "end_turn", 0, false, "end_turn"},
|
||||
{"refusal", "refusal", 0, false, "content_filter"},
|
||||
{"incomplete stream", "max_tokens", 0, true, types.FinishReasonIncomplete},
|
||||
{"empty reason", "", 0, false, types.FinishReasonIncomplete},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, mapStopReason(tt.reason, tt.toolCalls, tt.incomplete))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,606 @@
|
||||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"academy/internal/logger"
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// defaultAnthropicVersion is the anthropic-version value used when the
|
||||
// catalog supplies none.
|
||||
const defaultAnthropicVersion = "2023-06-01"
|
||||
|
||||
// Client talks the Messages protocol to one endpoint.
|
||||
type Client struct {
|
||||
cfg Config
|
||||
}
|
||||
|
||||
// New creates a client.
|
||||
func New(cfg Config) *Client {
|
||||
if cfg.ThinkingLevels == nil {
|
||||
cfg.ThinkingLevels = api.ThinkingLevelMap{}
|
||||
}
|
||||
return &Client{cfg: cfg}
|
||||
}
|
||||
|
||||
// GetModelName returns the wire model name.
|
||||
func (c *Client) GetModelName() string { return c.cfg.Endpoint.Model }
|
||||
|
||||
// GetModelID returns Academy's model identifier.
|
||||
func (c *Client) GetModelID() string { return c.cfg.Endpoint.ModelID }
|
||||
|
||||
// Settings exposes the resolved configuration.
|
||||
func (c *Client) Settings() Config { return c.cfg }
|
||||
|
||||
// URL resolves the messages endpoint. Operators paste base URLs in three
|
||||
// shapes: a host ("https://api.anthropic.com"), a versioned root
|
||||
// (".../v1", ".../anthropic/v1") or the full messages URL.
|
||||
func (c *Client) URL() string {
|
||||
if c.cfg.Endpoint.URL != "" {
|
||||
return c.cfg.Endpoint.Resolve("")
|
||||
}
|
||||
base := strings.TrimRight(c.cfg.Endpoint.BaseURL, "/")
|
||||
u, err := url.Parse(base)
|
||||
path := ""
|
||||
if err == nil {
|
||||
path = strings.TrimRight(u.Path, "/")
|
||||
}
|
||||
switch {
|
||||
case strings.HasSuffix(path, "/messages"):
|
||||
return base
|
||||
case strings.HasSuffix(path, "/v1") || strings.HasSuffix(path, "/v1beta"):
|
||||
return base + "/messages"
|
||||
default:
|
||||
return base + "/v1/messages"
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) send(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
|
||||
) (*httpResponse, error) {
|
||||
body, err := c.BuildRequestBody(messages, opts, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
target := c.URL()
|
||||
req, data, err := c.cfg.Endpoint.NewRequest(ctx, target, body, stream)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// anthropic-version is mandatory; an empty value is rejected with 400, so
|
||||
// fall back to the baseline version when the catalog left it unset.
|
||||
version := c.cfg.Settings.Version
|
||||
if version == "" {
|
||||
version = defaultAnthropicVersion
|
||||
}
|
||||
req.Header.Set("anthropic-version", version)
|
||||
if beta := c.betaHeader(c.planThinking(opts), opts, req.Header.Get("anthropic-beta")); beta != "" {
|
||||
req.Header.Set("anthropic-beta", beta)
|
||||
}
|
||||
api.LogRequest(ctx, target, c.cfg.Endpoint.Model, data, stream)
|
||||
resp, err := c.cfg.Endpoint.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &httpResponse{body: resp.Body, contentType: resp.Header.Get("Content-Type"), data: data}, nil
|
||||
}
|
||||
|
||||
type httpResponse struct {
|
||||
body io.ReadCloser
|
||||
contentType string
|
||||
data []byte
|
||||
}
|
||||
|
||||
// Chat performs a non-streaming call.
|
||||
func (c *Client) Chat(ctx context.Context, messages []api.Message, opts *api.Options) (*types.ChatResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultChatTimeout)
|
||||
defer cancel()
|
||||
resp, err := c.send(ctx, messages, opts, false)
|
||||
if err != nil {
|
||||
// Claude's own models all accept images, but this protocol is also
|
||||
// the compatibility surface of vendors whose text-only models do
|
||||
// not, and the other three clients already degrade this way.
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Request] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, false)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
defer func() { _ = resp.body.Close() }()
|
||||
raw, err := api.ReadResponseCapped(resp.body, 0)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read response: %w", err)
|
||||
}
|
||||
var result *types.ChatResponse
|
||||
if strings.Contains(strings.ToLower(resp.contentType), "text/event-stream") {
|
||||
// Some proxies answer non-stream calls with SSE; consume it fully.
|
||||
result, err = c.collectStream(ctx, strings.NewReader(string(raw)))
|
||||
} else {
|
||||
result, err = c.parseResponse(raw)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
api.LogUsage(ctx, c.cfg.Endpoint.Model, &result.Usage)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// ChatStream performs a streaming call.
|
||||
func (c *Client) ChatStream(
|
||||
ctx context.Context, messages []api.Message, opts *api.Options,
|
||||
) (<-chan types.StreamResponse, error) {
|
||||
ctx, cancel := api.WithLLMTimeout(ctx, api.DefaultStreamTimeout)
|
||||
resp, err := c.send(ctx, messages, opts, true)
|
||||
if err != nil {
|
||||
if api.IsMultimodalNotSupportedError(err) {
|
||||
logger.Warnf(ctx, "[LLM Stream] Model %s does not support multimodal, retrying without images",
|
||||
c.cfg.Endpoint.Model)
|
||||
resp, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
|
||||
}
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
ch := make(chan types.StreamResponse)
|
||||
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(resp.data))
|
||||
go func() {
|
||||
defer cancel()
|
||||
defer close(ch)
|
||||
defer func() { _ = resp.body.Close() }()
|
||||
if dumper != nil {
|
||||
defer dumper.Close()
|
||||
}
|
||||
c.processStream(ctx, resp.body, ch, dumper)
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
|
||||
// --- decoding ---
|
||||
|
||||
type usageBlock struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
|
||||
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
|
||||
}
|
||||
|
||||
type responseBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
Data string `json:"data"`
|
||||
}
|
||||
|
||||
type response struct {
|
||||
Type string `json:"type"`
|
||||
Content []responseBlock `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage usageBlock `json:"usage"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type streamEvent struct {
|
||||
Type string `json:"type"`
|
||||
Index int `json:"index"`
|
||||
ContentBlock *responseBlock `json:"content_block,omitempty"`
|
||||
Message *struct {
|
||||
Usage usageBlock `json:"usage"`
|
||||
} `json:"message,omitempty"`
|
||||
Delta *struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
PartialJSON string `json:"partial_json"`
|
||||
} `json:"delta,omitempty"`
|
||||
Usage *usageBlock `json:"usage,omitempty"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) usageFrom(u usageBlock) types.TokenUsage {
|
||||
read := valueOrZero(u.CacheReadInputTokens)
|
||||
write := valueOrZero(u.CacheCreationInputTokens)
|
||||
prompt := u.InputTokens + read + write
|
||||
out := types.TokenUsage{
|
||||
PromptTokens: prompt, CompletionTokens: u.OutputTokens, TotalTokens: prompt + u.OutputTokens,
|
||||
}
|
||||
reported := u.CacheReadInputTokens != nil || u.CacheCreationInputTokens != nil
|
||||
if !reported && !c.cfg.Settings.PromptCacheAccounting {
|
||||
out.MarkPromptCacheUnsupported()
|
||||
return out
|
||||
}
|
||||
out.SetPromptCacheUsage(read, write, max(0, prompt-read), reported)
|
||||
return out
|
||||
}
|
||||
|
||||
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
|
||||
var resp response
|
||||
if err := json.Unmarshal(raw, &resp); err != nil {
|
||||
return nil, fmt.Errorf("decode response: %w", err)
|
||||
}
|
||||
if resp.Error != nil && resp.Error.Message != "" {
|
||||
return nil, fmt.Errorf("API error: %s", resp.Error.Message)
|
||||
}
|
||||
result := &types.ChatResponse{Usage: c.usageFrom(resp.Usage)}
|
||||
var text, thinking []string
|
||||
// Interleaved thinking puts several signed thinking blocks in one reply,
|
||||
// each signed over its own text, so they are kept separately for replay.
|
||||
// ReasoningContent / ReasoningSignature stay filled for readers and for
|
||||
// older stored turns, but they are no longer what goes back on the wire.
|
||||
var stored []thinkingBlock
|
||||
for _, block := range resp.Content {
|
||||
switch block.Type {
|
||||
case "text":
|
||||
if block.Text != "" {
|
||||
text = append(text, block.Text)
|
||||
}
|
||||
case "thinking":
|
||||
thinking = append(thinking, block.Thinking)
|
||||
stored = append(stored, newThinkingBlock(block.Thinking, block.Signature))
|
||||
if block.Signature != "" {
|
||||
result.ReasoningSignature = api.TagSignature(api.APIAnthropicMessages, block.Signature)
|
||||
}
|
||||
case "redacted_thinking":
|
||||
stored = append(stored, newRedactedThinkingBlock(block.Data))
|
||||
case "tool_use":
|
||||
input := string(block.Input)
|
||||
if input == "" {
|
||||
input = "{}"
|
||||
}
|
||||
result.ToolCalls = append(result.ToolCalls, types.LLMToolCall{
|
||||
ID: block.ID, Type: "function",
|
||||
Function: types.FunctionCall{Name: block.Name, Arguments: input},
|
||||
})
|
||||
}
|
||||
}
|
||||
result.Content = strings.Join(text, "")
|
||||
result.ReasoningContent = strings.Join(thinking, "")
|
||||
if blocks := thinkingBlocksMetadata(stored); blocks != nil {
|
||||
result.ReasoningMetadata = types.ProviderMetadata{MetadataThinkingBlocks: blocks}
|
||||
}
|
||||
result.FinishReason = mapStopReason(resp.StopReason, len(result.ToolCalls), false)
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// toolInput accumulates one streamed tool_use block.
|
||||
type toolInput struct {
|
||||
call types.LLMToolCall
|
||||
initial string
|
||||
json strings.Builder
|
||||
closed bool
|
||||
}
|
||||
|
||||
// streamState tracks per-index content blocks of one streamed message.
|
||||
type streamState struct {
|
||||
tools map[int]*toolInput
|
||||
toolOrder []int
|
||||
blockType map[int]string
|
||||
signature string
|
||||
// thinking accumulates each thinking / redacted_thinking block by its
|
||||
// content-block index, and thinkingOrder keeps the order they started in.
|
||||
// Interleaved thinking sends several, each with its own signature_delta;
|
||||
// accumulating into one string would splice two signatures together and
|
||||
// produce one that verifies against nothing.
|
||||
thinking map[int]*thinkingBlock
|
||||
thinkingOrder []int
|
||||
stop string
|
||||
usage *types.TokenUsage
|
||||
}
|
||||
|
||||
func newStreamState() *streamState {
|
||||
return &streamState{
|
||||
tools: map[int]*toolInput{},
|
||||
blockType: map[int]string{},
|
||||
thinking: map[int]*thinkingBlock{},
|
||||
}
|
||||
}
|
||||
|
||||
// thinkingAt returns the block being streamed at this content-block index,
|
||||
// creating it on first use. A vendor that sends deltas without a
|
||||
// content_block_start still gets a block rather than losing the text.
|
||||
func (s *streamState) thinkingAt(index int, blockType string) *thinkingBlock {
|
||||
if b, ok := s.thinking[index]; ok {
|
||||
return b
|
||||
}
|
||||
b := &thinkingBlock{Type: blockType}
|
||||
s.thinking[index] = b
|
||||
s.thinkingOrder = append(s.thinkingOrder, index)
|
||||
return b
|
||||
}
|
||||
|
||||
// thinkingBlocks returns the finished blocks in the order Claude sent them.
|
||||
func (s *streamState) thinkingBlocks() []thinkingBlock {
|
||||
blocks := make([]thinkingBlock, 0, len(s.thinkingOrder))
|
||||
for _, index := range s.thinkingOrder {
|
||||
if b := s.thinking[index]; b != nil {
|
||||
blocks = append(blocks, *b)
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func (s *streamState) calls() []types.LLMToolCall {
|
||||
indexes := make([]int, 0, len(s.tools))
|
||||
for index := range s.tools {
|
||||
indexes = append(indexes, index)
|
||||
}
|
||||
sort.Ints(indexes)
|
||||
var calls []types.LLMToolCall
|
||||
for _, index := range indexes {
|
||||
t := s.tools[index]
|
||||
if !t.closed {
|
||||
// A cut-off stream often starts the next tool_use with {}. Executing
|
||||
// that empty object is worse than omitting it.
|
||||
continue
|
||||
}
|
||||
call := t.call
|
||||
call.Function.Arguments = t.initial
|
||||
if t.json.Len() > 0 {
|
||||
call.Function.Arguments = t.json.String()
|
||||
}
|
||||
calls = append(calls, call)
|
||||
}
|
||||
return calls
|
||||
}
|
||||
|
||||
func (s *streamState) incomplete() bool {
|
||||
for _, t := range s.tools {
|
||||
if !t.closed {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *streamState) toolIndex(blockIndex int) int {
|
||||
for i, idx := range s.toolOrder {
|
||||
if idx == blockIndex {
|
||||
return i
|
||||
}
|
||||
}
|
||||
s.toolOrder = append(s.toolOrder, blockIndex)
|
||||
return len(s.toolOrder) - 1
|
||||
}
|
||||
|
||||
// consume folds one event into the state and returns the protocol-neutral
|
||||
// delta to hand to the assembler (may be empty).
|
||||
func (c *Client) consume(s *streamState, ev streamEvent) api.Delta {
|
||||
var d api.Delta
|
||||
switch ev.Type {
|
||||
case "message_start":
|
||||
if ev.Message != nil {
|
||||
u := c.usageFrom(ev.Message.Usage)
|
||||
s.usage = &u
|
||||
}
|
||||
case "content_block_start":
|
||||
if ev.ContentBlock == nil {
|
||||
break
|
||||
}
|
||||
s.blockType[ev.Index] = ev.ContentBlock.Type
|
||||
switch ev.ContentBlock.Type {
|
||||
case "tool_use":
|
||||
initial := string(ev.ContentBlock.Input)
|
||||
if initial == "" || initial == "null" {
|
||||
initial = "{}"
|
||||
}
|
||||
s.tools[ev.Index] = &toolInput{
|
||||
initial: initial,
|
||||
call: types.LLMToolCall{
|
||||
ID: ev.ContentBlock.ID, Type: "function",
|
||||
Function: types.FunctionCall{Name: ev.ContentBlock.Name},
|
||||
},
|
||||
}
|
||||
d.ToolCalls = []api.ToolCallDelta{{
|
||||
Index: s.toolIndex(ev.Index), ID: ev.ContentBlock.ID, Type: "function", Name: ev.ContentBlock.Name,
|
||||
}}
|
||||
case "redacted_thinking":
|
||||
s.thinkingAt(ev.Index, "redacted_thinking").Data = ev.ContentBlock.Data
|
||||
case "thinking":
|
||||
block := s.thinkingAt(ev.Index, "thinking")
|
||||
if ev.ContentBlock.Thinking != "" {
|
||||
block.Thinking += ev.ContentBlock.Thinking
|
||||
d.Reasoning = ev.ContentBlock.Thinking
|
||||
}
|
||||
case "text":
|
||||
if ev.ContentBlock.Text != "" {
|
||||
d.Content = ev.ContentBlock.Text
|
||||
}
|
||||
}
|
||||
case "content_block_delta":
|
||||
if ev.Delta == nil {
|
||||
break
|
||||
}
|
||||
switch ev.Delta.Type {
|
||||
case "text_delta":
|
||||
d.Content = ev.Delta.Text
|
||||
case "thinking_delta":
|
||||
d.Reasoning = ev.Delta.Thinking
|
||||
s.thinkingAt(ev.Index, "thinking").Thinking += ev.Delta.Thinking
|
||||
case "signature_delta":
|
||||
// The signature belongs to the block at this index; the top-level
|
||||
// field keeps carrying the last one for readers that still use it.
|
||||
block := s.thinkingAt(ev.Index, "thinking")
|
||||
block.Signature += ev.Delta.Signature
|
||||
s.signature = block.Signature
|
||||
case "input_json_delta":
|
||||
if t := s.tools[ev.Index]; t != nil {
|
||||
t.json.WriteString(ev.Delta.PartialJSON)
|
||||
d.ToolCalls = []api.ToolCallDelta{{Index: s.toolIndex(ev.Index), Arguments: ev.Delta.PartialJSON}}
|
||||
}
|
||||
}
|
||||
case "content_block_stop":
|
||||
if t := s.tools[ev.Index]; t != nil {
|
||||
t.closed = true
|
||||
if t.json.Len() == 0 {
|
||||
// No input_json_delta carried any payload — an argument-less
|
||||
// tool, or a vendor that puts the whole input on
|
||||
// content_block_start. The assembler only emits its early
|
||||
// ResponseTypeToolCall marker once a chunk updates the
|
||||
// arguments of an already-named call, so replay the initial
|
||||
// input here. Without it the UI never learns the call started.
|
||||
// The final arguments are unchanged: calls() uses t.initial too.
|
||||
d.ToolCalls = []api.ToolCallDelta{{Index: s.toolIndex(ev.Index), Arguments: t.initial}}
|
||||
}
|
||||
}
|
||||
case "message_delta":
|
||||
if ev.Delta != nil && ev.Delta.StopReason != "" {
|
||||
s.stop = ev.Delta.StopReason
|
||||
}
|
||||
if ev.Usage != nil {
|
||||
u := c.usageFrom(*ev.Usage)
|
||||
if s.usage != nil {
|
||||
// message_delta carries cumulative output tokens; input
|
||||
// counters arrived on message_start.
|
||||
u.PromptTokens = max(u.PromptTokens, s.usage.PromptTokens)
|
||||
u.SetPromptCacheUsage(
|
||||
max(u.CacheReadTokens, s.usage.CacheReadTokens),
|
||||
max(u.CacheWriteTokens, s.usage.CacheWriteTokens),
|
||||
max(0, u.PromptTokens-max(u.CacheReadTokens, s.usage.CacheReadTokens)),
|
||||
u.CacheReported || s.usage.CacheReported,
|
||||
)
|
||||
u.TotalTokens = u.PromptTokens + u.CompletionTokens
|
||||
}
|
||||
s.usage = &u
|
||||
}
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
func (c *Client) processStream(
|
||||
ctx context.Context, body io.Reader, ch chan<- types.StreamResponse, dumper *api.StreamPacketDumper,
|
||||
) {
|
||||
assembler := api.NewStreamAssembler(ctx, c.cfg.Endpoint.Model)
|
||||
state := newStreamState()
|
||||
reader := api.NewSSEReader(body)
|
||||
finish := func() {
|
||||
calls := state.calls()
|
||||
assembler.ReplaceToolCalls(calls)
|
||||
assembler.ReasoningSignature = api.TagSignature(api.APIAnthropicMessages, state.signature)
|
||||
if blocks := thinkingBlocksMetadata(state.thinkingBlocks()); blocks != nil {
|
||||
assembler.ReasoningMetadata = types.ProviderMetadata{MetadataThinkingBlocks: blocks}
|
||||
}
|
||||
if state.usage != nil {
|
||||
assembler.SetUsage(*state.usage)
|
||||
}
|
||||
assembler.Process(ch, api.Delta{FinishReason: mapStopReason(state.stop, len(calls), state.incomplete())})
|
||||
assembler.End(ch)
|
||||
}
|
||||
for {
|
||||
// The consumer went away (client disconnect, aborted agent turn): stop
|
||||
// decoding a stream nobody will read instead of spinning to EOF.
|
||||
if assembler.Aborted() {
|
||||
return
|
||||
}
|
||||
event, err := reader.ReadEvent()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
finish()
|
||||
} else {
|
||||
assembler.Fail(ch, err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if event == nil || event.Done {
|
||||
if event != nil && event.Done {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if len(event.Data) == 0 {
|
||||
continue
|
||||
}
|
||||
if dumper != nil {
|
||||
raw := make([]byte, len(event.Data))
|
||||
copy(raw, event.Data)
|
||||
dumper.WritePacketRaw(raw)
|
||||
}
|
||||
var ev streamEvent
|
||||
if err := json.Unmarshal(event.Data, &ev); err != nil {
|
||||
assembler.Fail(ch, fmt.Errorf("decode SSE response: %w", err))
|
||||
return
|
||||
}
|
||||
if ev.Error != nil && ev.Error.Message != "" {
|
||||
assembler.Fail(ch, fmt.Errorf("API stream error: %s", ev.Error.Message))
|
||||
return
|
||||
}
|
||||
delta := c.consume(state, ev)
|
||||
if delta.Content != "" || delta.Reasoning != "" || len(delta.ToolCalls) > 0 {
|
||||
assembler.Process(ch, delta)
|
||||
}
|
||||
if ev.Type == "message_stop" {
|
||||
finish()
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// collectStream folds an SSE body into one ChatResponse (used when a proxy
|
||||
// answers a non-stream request with SSE).
|
||||
func (c *Client) collectStream(ctx context.Context, body io.Reader) (*types.ChatResponse, error) {
|
||||
ch := make(chan types.StreamResponse, 64)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
c.processStream(ctx, body, ch, nil)
|
||||
}()
|
||||
result := &types.ChatResponse{}
|
||||
var content, reasoning strings.Builder
|
||||
for chunk := range ch {
|
||||
switch chunk.ResponseType {
|
||||
case types.ResponseTypeError:
|
||||
return nil, fmt.Errorf("%s", chunk.Content)
|
||||
case types.ResponseTypeThinking:
|
||||
reasoning.WriteString(chunk.Content)
|
||||
case types.ResponseTypeAnswer:
|
||||
content.WriteString(chunk.Content)
|
||||
if len(chunk.ToolCalls) > 0 {
|
||||
result.ToolCalls = chunk.ToolCalls
|
||||
}
|
||||
if chunk.Usage != nil {
|
||||
result.Usage = *chunk.Usage
|
||||
}
|
||||
if chunk.FinishReason != "" {
|
||||
result.FinishReason = chunk.FinishReason
|
||||
}
|
||||
if sig, ok := chunk.Data["reasoning_signature"].(string); ok {
|
||||
result.ReasoningSignature = sig
|
||||
}
|
||||
if md, ok := chunk.Data["reasoning_metadata"].(types.ProviderMetadata); ok {
|
||||
result.ReasoningMetadata = md
|
||||
}
|
||||
}
|
||||
}
|
||||
result.Content = content.String()
|
||||
result.ReasoningContent = reasoning.String()
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func valueOrZero(v *int) int {
|
||||
if v == nil {
|
||||
return 0
|
||||
}
|
||||
return *v
|
||||
}
|
||||
@@ -0,0 +1,538 @@
|
||||
// Package anthropicmessages implements the Anthropic Messages wire protocol
|
||||
// (https://docs.anthropic.com/en/api/messages). MiniMax, Zhipu, Moonshot and
|
||||
// Volcengine expose the same protocol on an ".../anthropic" base URL, so the
|
||||
// package contains no vendor names: every deviation is a
|
||||
// api.AnthropicMessagesSettings field.
|
||||
package anthropicmessages
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"academy/internal/models/api"
|
||||
"academy/internal/types"
|
||||
)
|
||||
|
||||
// Config is everything the client needs, already resolved by the api.
|
||||
type Config struct {
|
||||
Endpoint api.Endpoint
|
||||
Settings api.AnthropicMessagesSettings
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
Reasoning bool
|
||||
}
|
||||
|
||||
// Metadata keys used on messages and tool calls.
|
||||
const (
|
||||
// MetadataRedactedThinking stores redacted_thinking blocks (JSON array
|
||||
// of {"data": ...}) that must be replayed verbatim. Superseded by
|
||||
// MetadataThinkingBlocks; still read so assistant turns stored by an
|
||||
// earlier build keep replaying.
|
||||
MetadataRedactedThinking = "anthropic_redacted_thinking"
|
||||
// MetadataThinkingBlocks stores the turn's thinking and
|
||||
// redacted_thinking blocks exactly as Claude emitted them, in order.
|
||||
//
|
||||
// Two properties make this the only correct source for replay. First,
|
||||
// Claude signs the exact text of each block, so one assistant turn with
|
||||
// interleaved thinking carries several (text, signature) pairs that a
|
||||
// single ReasoningContent / ReasoningSignature pair cannot represent —
|
||||
// concatenating them produces a signature that matches nothing. Second,
|
||||
// ReasoningContent is rewritten downstream (resource-handle encoding,
|
||||
// citation compaction, special-token neutralisation) for the benefit of
|
||||
// readers and of the next prompt, which invalidates the signature over
|
||||
// it. This metadata is opaque to all of that and travels unchanged.
|
||||
MetadataThinkingBlocks = "anthropic_thinking_blocks"
|
||||
)
|
||||
|
||||
// thinkingBlock is one stored thinking or redacted_thinking block. It is the
|
||||
// wire shape, so replay is a copy rather than a reconstruction.
|
||||
type thinkingBlock struct {
|
||||
Type string `json:"type"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
}
|
||||
|
||||
// thinkingBlocksMetadata renders the blocks for storage on the assistant
|
||||
// message. It returns nil when there is nothing to replay.
|
||||
func thinkingBlocksMetadata(blocks []thinkingBlock) json.RawMessage {
|
||||
if len(blocks) == 0 {
|
||||
return nil
|
||||
}
|
||||
data, err := json.Marshal(blocks)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
// newThinkingBlock records a signed thinking block.
|
||||
func newThinkingBlock(thinking, signature string) thinkingBlock {
|
||||
return thinkingBlock{Type: "thinking", Thinking: thinking, Signature: signature}
|
||||
}
|
||||
|
||||
// newRedactedThinkingBlock records an opaque redacted_thinking block.
|
||||
func newRedactedThinkingBlock(data string) thinkingBlock {
|
||||
return thinkingBlock{Type: "redacted_thinking", Data: data}
|
||||
}
|
||||
|
||||
type cacheControl struct {
|
||||
Type string `json:"type"`
|
||||
TTL string `json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
type contentBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text,omitempty"`
|
||||
CacheControl *cacheControl `json:"cache_control,omitempty"`
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input json.RawMessage `json:"input,omitempty"`
|
||||
ToolUseID string `json:"tool_use_id,omitempty"`
|
||||
Content any `json:"content,omitempty"`
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
Source *imageSource `json:"source,omitempty"`
|
||||
}
|
||||
|
||||
type imageSource struct {
|
||||
Type string `json:"type"` // "base64" | "url"
|
||||
MediaType string `json:"media_type,omitempty"`
|
||||
Data string `json:"data,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
}
|
||||
|
||||
type message struct {
|
||||
Role string `json:"role"`
|
||||
Content any `json:"content"`
|
||||
}
|
||||
|
||||
type tool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema json.RawMessage `json:"input_schema"`
|
||||
CacheControl *cacheControl `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type toolChoice struct {
|
||||
Type string `json:"type"`
|
||||
Name string `json:"name,omitempty"`
|
||||
DisableParallelToolUse *bool `json:"disable_parallel_tool_use,omitempty"`
|
||||
}
|
||||
|
||||
// thinkingPlan is the resolved thinking request for one call.
|
||||
type thinkingPlan struct {
|
||||
enabled bool
|
||||
body map[string]any // the "thinking" object, nil when omitted
|
||||
effort string // output_config.effort, "" when omitted
|
||||
budget int // budget_tokens in budget mode
|
||||
}
|
||||
|
||||
func (c *Client) planThinking(opts *api.Options) thinkingPlan {
|
||||
s := c.cfg.Settings
|
||||
levels := c.cfg.ThinkingLevels
|
||||
level, requested := opts.Reasoning()
|
||||
if !requested {
|
||||
return thinkingPlan{}
|
||||
}
|
||||
if level.Graded() {
|
||||
level = levels.Clamp(level)
|
||||
}
|
||||
if !level.Enabled() {
|
||||
if levels.Supports(api.ReasoningOff) && s.ThinkingMode == api.AnthropicThinkingAdaptive {
|
||||
offType := s.ThinkingOffType
|
||||
if offType == "" {
|
||||
offType = "disabled"
|
||||
}
|
||||
return thinkingPlan{body: map[string]any{"type": offType}}
|
||||
}
|
||||
// Budget mode: omitting the thinking object disables it.
|
||||
return thinkingPlan{}
|
||||
}
|
||||
plan := thinkingPlan{enabled: true}
|
||||
switch s.ThinkingMode {
|
||||
case api.AnthropicThinkingAdaptive:
|
||||
plan.body = map[string]any{"type": "adaptive"}
|
||||
if level.Graded() && s.SupportsEffort {
|
||||
plan.effort = levels.Value(level)
|
||||
}
|
||||
default:
|
||||
budget := 0
|
||||
if opts != nil && opts.ThinkingBudgetTokens > 0 {
|
||||
budget = opts.ThinkingBudgetTokens
|
||||
} else {
|
||||
key := level
|
||||
if !key.Graded() {
|
||||
key = api.ReasoningMedium
|
||||
}
|
||||
budget = s.ThinkingBudgets[key]
|
||||
}
|
||||
if budget < 1024 {
|
||||
budget = 1024
|
||||
}
|
||||
plan.budget = budget
|
||||
plan.body = map[string]any{"type": "enabled", "budget_tokens": budget}
|
||||
}
|
||||
return plan
|
||||
}
|
||||
|
||||
// BuildRequestBody is the golden-test entry point.
|
||||
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
|
||||
s := c.cfg.Settings
|
||||
body := map[string]any{"model": c.cfg.Endpoint.Model}
|
||||
if stream {
|
||||
body["stream"] = true
|
||||
}
|
||||
plan := c.planThinking(opts)
|
||||
|
||||
maxTokens := opts.CompletionBudget()
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = s.DefaultMaxTokens
|
||||
if maxTokens <= 0 {
|
||||
maxTokens = 4096
|
||||
}
|
||||
}
|
||||
if plan.budget > 0 && maxTokens <= plan.budget {
|
||||
// max_tokens must exceed budget_tokens; keep the caller's answer
|
||||
// budget on top of the thinking budget.
|
||||
maxTokens = plan.budget + max(maxTokens, 1024)
|
||||
}
|
||||
body["max_tokens"] = maxTokens
|
||||
|
||||
if opts != nil {
|
||||
if s.SupportsTemperature && opts.Temperature > 0 && (!plan.enabled || s.TemperatureWithThinking) {
|
||||
body["temperature"] = opts.Temperature
|
||||
} else if s.SupportsTopP && opts.TopP > 0 && !plan.enabled {
|
||||
// temperature and top_p are mutually exclusive on current models;
|
||||
// temperature wins when both are set.
|
||||
body["top_p"] = opts.TopP
|
||||
}
|
||||
}
|
||||
|
||||
retention := api.ResolveCacheRetention(opts)
|
||||
var marker *cacheControl
|
||||
if s.SupportsCacheControl {
|
||||
if m := api.CacheControlFor(retention, s.LongCacheTTL); m != nil {
|
||||
marker = &cacheControl{Type: m.Type, TTL: m.TTL}
|
||||
}
|
||||
}
|
||||
|
||||
if opts != nil && len(opts.Tools) > 0 {
|
||||
tools := make([]tool, 0, len(opts.Tools))
|
||||
for _, t := range opts.Tools {
|
||||
schema := t.Function.Parameters
|
||||
if len(schema) == 0 {
|
||||
schema = json.RawMessage(`{"type":"object","properties":{}}`)
|
||||
}
|
||||
tools = append(tools, tool{Name: t.Function.Name, Description: t.Function.Description, InputSchema: schema})
|
||||
}
|
||||
if marker != nil && s.SupportsCacheControlOnTool {
|
||||
tools[len(tools)-1].CacheControl = marker
|
||||
}
|
||||
body["tools"] = tools
|
||||
choice := &toolChoice{Type: "auto"}
|
||||
switch opts.ToolChoice {
|
||||
case "", "auto":
|
||||
case "required":
|
||||
choice.Type = "any"
|
||||
case "none":
|
||||
choice.Type = "none"
|
||||
default:
|
||||
choice.Type, choice.Name = "tool", opts.ToolChoice
|
||||
}
|
||||
if opts.ParallelToolCalls != nil && choice.Type != "none" {
|
||||
disable := !*opts.ParallelToolCalls
|
||||
choice.DisableParallelToolUse = &disable
|
||||
}
|
||||
body["tool_choice"] = choice
|
||||
}
|
||||
|
||||
systemParts, converted := c.convertMessages(messages, opts)
|
||||
systemText := strings.Join(systemParts, "\n\n")
|
||||
if marker == nil {
|
||||
if systemText != "" {
|
||||
body["system"] = systemText
|
||||
}
|
||||
} else {
|
||||
if systemText != "" {
|
||||
body["system"] = []contentBlock{{Type: "text", Text: systemText, CacheControl: marker}}
|
||||
}
|
||||
if len(converted) > 0 {
|
||||
last := &converted[len(converted)-1]
|
||||
switch content := last.Content.(type) {
|
||||
case string:
|
||||
if content != "" {
|
||||
last.Content = []contentBlock{{Type: "text", Text: content, CacheControl: marker}}
|
||||
}
|
||||
case []contentBlock:
|
||||
if len(content) > 0 {
|
||||
content[len(content)-1].CacheControl = marker
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if converted == nil {
|
||||
// "messages" is required and must be an array: a nil slice would
|
||||
// marshal to null and the API answers 400. A request whose only
|
||||
// entries were system messages legitimately produces no turns.
|
||||
converted = []message{}
|
||||
}
|
||||
// Anthropic has no in-sequence instruction role. Keep the marked runtime
|
||||
// notice in a trailing input turn, after the existing cache breakpoint;
|
||||
// never move transient recovery text into the stable system prefix.
|
||||
if opts != nil && opts.RuntimeNotice != "" {
|
||||
converted = append(converted, message{Role: "user", Content: opts.RuntimeNotice})
|
||||
}
|
||||
body["messages"] = converted
|
||||
|
||||
if plan.body != nil {
|
||||
body["thinking"] = plan.body
|
||||
}
|
||||
if plan.effort != "" {
|
||||
body["output_config"] = map[string]any{"effort": plan.effort}
|
||||
}
|
||||
for k, v := range s.ExtraBody {
|
||||
if _, exists := body[k]; !exists {
|
||||
body[k] = v
|
||||
}
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// betaHeader composes the anthropic-beta header for this request.
|
||||
func (c *Client) betaHeader(plan thinkingPlan, opts *api.Options, userValue string) string {
|
||||
s := c.cfg.Settings
|
||||
seen := map[string]bool{}
|
||||
var betas []string
|
||||
add := func(v string) {
|
||||
for _, part := range strings.Split(v, ",") {
|
||||
part = strings.TrimSpace(part)
|
||||
if part != "" && !seen[part] {
|
||||
seen[part] = true
|
||||
betas = append(betas, part)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, b := range s.BetaHeaders {
|
||||
add(b)
|
||||
}
|
||||
if plan.enabled && s.ThinkingMode != api.AnthropicThinkingAdaptive && s.InterleavedThinkingBeta != "" &&
|
||||
opts != nil && len(opts.Tools) > 0 {
|
||||
add(s.InterleavedThinkingBeta)
|
||||
}
|
||||
add(userValue)
|
||||
return strings.Join(betas, ",")
|
||||
}
|
||||
|
||||
// convertMessages maps neutral messages onto Anthropic messages. System
|
||||
// messages are lifted out; tool calls become tool_use blocks; consecutive
|
||||
// tool results merge into one user message; thinking blocks are replayed
|
||||
// only when they carry a signature (the API rejects unsigned ones).
|
||||
func (c *Client) convertMessages(messages []api.Message, _ *api.Options) ([]string, []message) {
|
||||
var system []string
|
||||
var result []message
|
||||
for _, msg := range messages {
|
||||
msg = api.NeutralizeMessageSpecialTokens(msg)
|
||||
content := strings.TrimSpace(msg.Content)
|
||||
switch msg.Role {
|
||||
case "system":
|
||||
if content == "" {
|
||||
content = textFromMultiContent(msg.MultiContent)
|
||||
}
|
||||
if content != "" {
|
||||
system = append(system, content)
|
||||
}
|
||||
case "assistant":
|
||||
blocks := c.assistantBlocks(msg, content)
|
||||
if len(blocks) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(blocks) == 1 && blocks[0].Type == "text" && len(msg.ToolCalls) == 0 {
|
||||
result = append(result, message{Role: "assistant", Content: blocks[0].Text})
|
||||
continue
|
||||
}
|
||||
result = append(result, message{Role: "assistant", Content: blocks})
|
||||
case "tool":
|
||||
block := contentBlock{Type: "tool_result", ToolUseID: msg.ToolCallID, Content: msg.Content}
|
||||
if len(result) > 0 && result[len(result)-1].Role == "user" {
|
||||
if blocks, ok := result[len(result)-1].Content.([]contentBlock); ok && len(blocks) > 0 &&
|
||||
blocks[0].Type == "tool_result" {
|
||||
result[len(result)-1].Content = append(blocks, block)
|
||||
continue
|
||||
}
|
||||
}
|
||||
result = append(result, message{Role: "user", Content: []contentBlock{block}})
|
||||
default:
|
||||
blocks := userBlocks(msg, content)
|
||||
if len(blocks) == 0 {
|
||||
continue
|
||||
}
|
||||
if len(blocks) == 1 && blocks[0].Type == "text" {
|
||||
result = append(result, message{Role: "user", Content: blocks[0].Text})
|
||||
continue
|
||||
}
|
||||
result = append(result, message{Role: "user", Content: blocks})
|
||||
}
|
||||
}
|
||||
return system, result
|
||||
}
|
||||
|
||||
func (c *Client) assistantBlocks(msg api.Message, content string) []contentBlock {
|
||||
blocks := replayThinkingBlocks(msg)
|
||||
if content == "" {
|
||||
content = textFromMultiContent(msg.MultiContent)
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
for _, call := range msg.ToolCalls {
|
||||
input := json.RawMessage(call.Function.Arguments)
|
||||
if len(input) == 0 || !json.Valid(input) {
|
||||
input = json.RawMessage(`{}`)
|
||||
}
|
||||
blocks = append(blocks, contentBlock{Type: "tool_use", ID: call.ID, Name: call.Function.Name, Input: input})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// replayThinkingBlocks rebuilds the leading thinking / redacted_thinking
|
||||
// blocks of a stored assistant turn.
|
||||
//
|
||||
// Claude requires them back verbatim whenever that turn also carries tool_use
|
||||
// and extended thinking was on: dropping them answers 400 ("Expected
|
||||
// `thinking` or `redacted_thinking`, but found `tool_use`"), and altering the
|
||||
// signed text answers 400 as well. Preference order is therefore the verbatim
|
||||
// metadata first, then the legacy single-block fields for turns stored before
|
||||
// that metadata existed.
|
||||
func replayThinkingBlocks(msg api.Message) []contentBlock {
|
||||
if raw, ok := msg.ReasoningMetadata[MetadataThinkingBlocks]; ok && len(raw) > 0 {
|
||||
var stored []thinkingBlock
|
||||
if err := json.Unmarshal(raw, &stored); err == nil {
|
||||
blocks := make([]contentBlock, 0, len(stored))
|
||||
for _, b := range stored {
|
||||
switch b.Type {
|
||||
case "thinking":
|
||||
// An unsigned block cannot go back: Claude rejects a
|
||||
// thinking block without a signature. It means the stream
|
||||
// ended inside that block (truncation), so it is the last
|
||||
// one and produced no tool_use of its own. Skip just it —
|
||||
// discarding the whole turn's blocks instead would strip
|
||||
// the signed ones that a completed tool_use in the same
|
||||
// turn still needs, which is the 400 this replay exists
|
||||
// to prevent.
|
||||
if b.Signature == "" {
|
||||
continue
|
||||
}
|
||||
blocks = append(blocks, contentBlock{
|
||||
Type: "thinking", Thinking: b.Thinking, Signature: b.Signature,
|
||||
})
|
||||
case "redacted_thinking":
|
||||
blocks = append(blocks, contentBlock{Type: "redacted_thinking", Data: b.Data})
|
||||
}
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
}
|
||||
|
||||
var blocks []contentBlock
|
||||
if raw, ok := msg.ReasoningMetadata[MetadataRedactedThinking]; ok && len(raw) > 0 {
|
||||
var redacted []string
|
||||
if err := json.Unmarshal(raw, &redacted); err == nil {
|
||||
for _, data := range redacted {
|
||||
blocks = append(blocks, contentBlock{Type: "redacted_thinking", Data: data})
|
||||
}
|
||||
}
|
||||
}
|
||||
sig := api.SignatureFor(api.APIAnthropicMessages, msg.ReasoningSignature)
|
||||
if msg.ReasoningContent != "" && sig != "" {
|
||||
blocks = append(blocks, contentBlock{
|
||||
Type: "thinking", Thinking: msg.ReasoningContent, Signature: sig,
|
||||
})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
func userBlocks(msg api.Message, content string) []contentBlock {
|
||||
var blocks []contentBlock
|
||||
addImage := func(ref string) {
|
||||
if src := imageSourceFor(ref); src != nil {
|
||||
blocks = append(blocks, contentBlock{Type: "image", Source: src})
|
||||
}
|
||||
}
|
||||
if len(msg.MultiContent) > 0 {
|
||||
for _, part := range msg.MultiContent {
|
||||
switch part.Type {
|
||||
case "text":
|
||||
if t := strings.TrimSpace(part.Text); t != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: t})
|
||||
}
|
||||
case "image_url":
|
||||
if part.ImageURL != nil {
|
||||
addImage(part.ImageURL.URL)
|
||||
}
|
||||
}
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
for _, img := range msg.Images {
|
||||
addImage(img)
|
||||
}
|
||||
if content != "" {
|
||||
blocks = append(blocks, contentBlock{Type: "text", Text: content})
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
// imageSourceFor converts a data URI or URL into an image source block.
|
||||
func imageSourceFor(ref string) *imageSource {
|
||||
ref = api.ResolveImageURLForLLM(ref)
|
||||
if strings.HasPrefix(ref, "data:") {
|
||||
semi := strings.Index(ref, ";base64,")
|
||||
if semi < 0 {
|
||||
return nil
|
||||
}
|
||||
mediaType := strings.TrimPrefix(ref[:semi], "data:")
|
||||
data := ref[semi+len(";base64,"):]
|
||||
if _, err := base64.StdEncoding.DecodeString(data); err != nil {
|
||||
return nil
|
||||
}
|
||||
return &imageSource{Type: "base64", MediaType: mediaType, Data: data}
|
||||
}
|
||||
if u, err := url.Parse(ref); err == nil && (u.Scheme == "http" || u.Scheme == "https") {
|
||||
return &imageSource{Type: "url", URL: ref}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func textFromMultiContent(parts []api.MessageContentPart) string {
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
textParts := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if part.Type == "text" && strings.TrimSpace(part.Text) != "" {
|
||||
textParts = append(textParts, strings.TrimSpace(part.Text))
|
||||
}
|
||||
}
|
||||
return strings.Join(textParts, "\n")
|
||||
}
|
||||
|
||||
// mapStopReason converts Anthropic stop reasons to the shared vocabulary.
|
||||
func mapStopReason(reason string, toolCalls int, incomplete bool) string {
|
||||
switch {
|
||||
case incomplete, reason == "":
|
||||
return types.FinishReasonIncomplete
|
||||
case reason == "max_tokens", reason == "model_context_window_exceeded":
|
||||
return "length"
|
||||
case reason == "tool_use" || (toolCalls > 0 && reason == "end_turn"):
|
||||
return "tool_calls"
|
||||
case reason == "refusal":
|
||||
return "content_filter"
|
||||
}
|
||||
return reason
|
||||
}
|
||||
Reference in new issue
Block a user