chore: 初始化仓库,导入项目基线代码

Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、
Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。
今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
runny committed 2026-11-16 18:12:23 +08:00
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
}
+140
View File
@@ -0,0 +1,140 @@
// Package arkembeddings implements Volcengine Ark's multimodal embedding
// shape: an input array of typed parts answering a single `data` object.
//
// The response is one fused vector for the whole input, not one per element —
// the reference's own example returns
//
// "data": { "embedding": [...], "object": "embedding" }
//
// for a request carrying a video, an image and a text. So a batch of N texts
// is N requests, which the vendor declares as a batch size of one rather than
// this package looping.
//
// It is the only embedding API Ark still documents. Its retired text
// endpoint (/api/v3/embeddings) was the plain OpenAI shape, which is why rows
// naming a text model resolve to that protocol instead.
//
// https://docs.volcengine.com/docs/ark/multimodal-vectorization-api
package arkembeddings
import (
"context"
"fmt"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
Dimensions int
Retry api.RetryPolicy
}
// Client talks Ark's multimodal embedding to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type response struct {
Data struct {
Embedding []float32 `json:"embedding"`
Object string `json:"object"`
} `json:"data"`
Error *struct {
Code string `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {
input := make([]any, 0, len(texts))
for _, text := range texts {
input = append(input, map[string]any{"type": "text", "text": text})
}
return c.body(input)
}
// BuildImageRequestBody is the golden-test entry point for images. The
// reference takes an image as a URL or as
// "data:image/{图片格式};base64,{图片Base64编码}" under image_url.url.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {
input := make([]any, 0, len(images))
for _, img := range images {
input = append(input, map[string]any{
"type": "image_url", "image_url": map[string]any{"url": img.DataURI()},
})
}
return c.body(input)
}
func (c *Client) body(input []any) map[string]any {
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"input": input,
}
if c.cfg.Settings.SendEncodingFormat {
body["encoding_format"] = "float"
}
if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {
body[c.cfg.Settings.DimensionsField] = c.cfg.Dimensions
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one input. The vendor fuses everything it is sent into a
// single vector, so the caller must hand over exactly one text; the shared
// batching layer guarantees that through the declared batch size.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
if len(texts) != 1 {
return nil, fmt.Errorf(
"ark embedding fuses its input into one vector, so it takes one text per request, got %d",
len(texts),
)
}
return c.post(ctx, c.BuildRequestBody(texts, kind))
}
// AcceptsImages is always true: the image part is part of the schema.
func (c *Client) AcceptsImages() bool { return true }
// EmbedImages vectorizes one image, for the same reason Embed takes one text.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
if len(images) != 1 {
return nil, fmt.Errorf(
"ark embedding fuses its input into one vector, so it takes one image per request, got %d",
len(images),
)
}
return c.post(ctx, c.BuildImageRequestBody(images, kind))
}
func (c *Client) post(ctx context.Context, body map[string]any) ([][]float32, error) {
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("ark embedding error %s: %s", decoded.Error.Code, decoded.Error.Message)
}
if len(decoded.Data.Embedding) == 0 {
return nil, fmt.Errorf("ark embedding returned no vector")
}
return [][]float32{decoded.Data.Embedding}, nil
}
@@ -0,0 +1,88 @@
package arkembeddings
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the response example from Volcengine's multimodal
// embedding reference, copied from the rendered page:
// https://docs.volcengine.com/docs/ark/multimodal-vectorization-api
//
// `data` is one object, not an array. The request that produced it carried a
// video, an image and a text; the answer is a single fused vector.
const documentedResponse = `{
"created": 1743575029,
"data": {
"embedding": [-0.123046875, -0.35546875, -0.318359375],
"object": "embedding"
},
"id": "021743575029461acbe49a31755bec77b2f09448eb15fa9a88e47",
"model": "doubao-embedding-vision-251215",
"object": "list",
"usage": {"prompt_tokens": 13987, "total_tokens": 13987}
}`
const endpoint = "/api/v3/embeddings/multimodal"
func newClient(url string, dims int) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "doubao-embedding-vision-251215", Auth: api.BearerAuth("k")},
Settings: api.EmbeddingsSettings{
SendEncodingFormat: true, DimensionsField: "dimensions",
},
Dimensions: dims,
})
}
func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {
body := newClient("https://ark.cn-beijing.volces.com"+endpoint, 2048).
BuildRequestBody([]string{"视频和图片里有什么"}, api.EmbedDocument)
assert.Equal(t, map[string]any{
"model": "doubao-embedding-vision-251215",
"encoding_format": "float",
"dimensions": 2048,
"input": []any{map[string]any{"type": "text", "text": "视频和图片里有什么"}},
}, body)
}
func TestDecodesTheDocumentedResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
got, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{-0.123046875, -0.35546875, -0.318359375}}, got)
assert.Equal(t, endpoint, path)
}
// The vendor fuses everything it is sent. Handing it two texts would return
// one vector for both, silently, so the protocol refuses rather than guess.
func TestRefusesMoreThanOneText(t *testing.T) {
_, err := newClient("https://ark.cn-beijing.volces.com"+endpoint, 0).
Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "one text per request")
}
func TestEmptyVectorIsAnError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"data":{"embedding":[],"object":"embedding"}}`))
}))
defer server.Close()
_, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.Error(t, err)
}
+79
View File
@@ -0,0 +1,79 @@
package api
import (
"fmt"
"unicode/utf8"
)
// BatchLimits are the per-request ceilings a vendor documents. A zero field
// means the vendor states no limit, and nothing is enforced for it.
type BatchLimits struct {
// MaxItems caps how many documents one request may carry.
MaxItems int
// MaxItemRunes caps a single document. Vendors state these in characters
// or tokens; runes are the closest thing we can count without a
// tokenizer, and undercounting is the safe direction.
MaxItemRunes int
// MaxTotalRunes caps the whole request, query included.
MaxTotalRunes int
}
// Batch is one slice of the input, and where it started.
type Batch struct {
Start int
Items []string
}
// SplitBatches divides items into requests that satisfy limits. fixedRunes is
// charged to every batch (the query, which each request repeats).
//
// A single item that cannot fit on its own is an error rather than a silent
// truncation: the caller asked for this document to be scored, and scoring a
// prefix of it returns a number for something the user never sent.
func SplitBatches(items []string, fixedRunes int, limits BatchLimits) ([]Batch, error) {
if limits.MaxTotalRunes > 0 && fixedRunes >= limits.MaxTotalRunes {
return nil, fmt.Errorf(
"query is %d characters; the request budget is %d and must also fit a document",
fixedRunes, limits.MaxTotalRunes,
)
}
sizes := make([]int, len(items))
for i, item := range items {
sizes[i] = utf8.RuneCountInString(item)
if limits.MaxItemRunes > 0 && sizes[i] > limits.MaxItemRunes {
return nil, fmt.Errorf(
"document at index %d is %d characters; the per-document limit is %d",
i, sizes[i], limits.MaxItemRunes,
)
}
if limits.MaxTotalRunes > 0 && fixedRunes+sizes[i] > limits.MaxTotalRunes {
return nil, fmt.Errorf(
"document at index %d is %d characters; it does not fit beside a %d-character query "+
"in the %d-character request budget",
i, sizes[i], fixedRunes, limits.MaxTotalRunes,
)
}
}
if len(items) == 0 {
return nil, nil
}
if limits.MaxItems <= 0 && limits.MaxTotalRunes <= 0 {
return []Batch{{Start: 0, Items: items}}, nil
}
batches := make([]Batch, 0, 1)
start, total := 0, fixedRunes
for i := range items {
full := limits.MaxItems > 0 && i-start == limits.MaxItems
over := limits.MaxTotalRunes > 0 && total+sizes[i] > limits.MaxTotalRunes
if i > start && (full || over) {
batches = append(batches, Batch{Start: start, Items: items[start:i]})
start, total = i, fixedRunes
}
total += sizes[i]
}
batches = append(batches, Batch{Start: start, Items: items[start:]})
return batches, nil
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSplitBatchesNoLimitsKeepsOneRequest(t *testing.T) {
got, err := SplitBatches([]string{"a", "b", "c"}, 0, BatchLimits{})
require.NoError(t, err)
require.Len(t, got, 1)
assert.Equal(t, 0, got[0].Start)
assert.Len(t, got[0].Items, 3)
}
func TestSplitBatchesSplitsOnItemCount(t *testing.T) {
items := []string{"a", "b", "c", "d", "e"}
got, err := SplitBatches(items, 0, BatchLimits{MaxItems: 2})
require.NoError(t, err)
require.Len(t, got, 3)
assert.Equal(t, []Batch{
{Start: 0, Items: items[0:2]},
{Start: 2, Items: items[2:4]},
{Start: 4, Items: items[4:5]},
}, got)
}
// The query travels in every request, so it is charged to every batch rather
// than once to the whole call.
func TestSplitBatchesChargesTheQueryToEveryBatch(t *testing.T) {
items := []string{strings.Repeat("x", 30), strings.Repeat("y", 30), strings.Repeat("z", 30)}
got, err := SplitBatches(items, 40, BatchLimits{MaxTotalRunes: 100})
require.NoError(t, err)
// 40 + 30 + 30 = 100 fits; adding the third would reach 130.
require.Len(t, got, 2)
assert.Len(t, got[0].Items, 2)
assert.Equal(t, 2, got[1].Start)
}
func TestSplitBatchesRejectsAnItemThatCannotFit(t *testing.T) {
_, err := SplitBatches([]string{"ok", strings.Repeat("x", 50)}, 0, BatchLimits{MaxItemRunes: 10})
require.Error(t, err)
assert.Contains(t, err.Error(), "index 1")
}
// A document that fits the per-document limit but not beside the query is
// still unsendable; saying so beats looping forever or silently dropping it.
func TestSplitBatchesRejectsAnItemThatCannotFitBesideTheQuery(t *testing.T) {
_, err := SplitBatches([]string{strings.Repeat("x", 80)}, 40, BatchLimits{MaxTotalRunes: 100})
require.Error(t, err)
assert.Contains(t, err.Error(), "does not fit beside")
}
func TestSplitBatchesRejectsAQueryThatFillsTheBudget(t *testing.T) {
_, err := SplitBatches([]string{"a"}, 100, BatchLimits{MaxTotalRunes: 100})
require.Error(t, err)
assert.Contains(t, err.Error(), "must also fit a document")
}
// Runes, not bytes: a CJK document is counted the way the vendor counts it.
func TestSplitBatchesCountsRunesNotBytes(t *testing.T) {
got, err := SplitBatches([]string{strings.Repeat("中", 10)}, 0, BatchLimits{MaxItemRunes: 10})
require.NoError(t, err)
assert.Len(t, got, 1)
}
func TestSplitBatchesEmptyInput(t *testing.T) {
got, err := SplitBatches(nil, 0, BatchLimits{MaxItems: 5})
require.NoError(t, err)
assert.Empty(t, got)
}
+244
View File
@@ -0,0 +1,244 @@
// Package cohererank implements the rerank shape Cohere defined and almost
// every other vendor copied: POST {base}/rerank with {model, query,
// documents} answering {results: [{index, relevance_score, document}]}.
// A bare array of the same result objects is accepted too: self-hosted
// runtimes such as SGLang return that shape instead of the envelope.
//
// Jina, Zhipu, SiliconFlow, Qianfan, GPUStack, Academy Cloud and any
// OpenAI-compatible gateway that serves rerank all speak it. Their
// differences — which optional fields are accepted, where the endpoint sits,
// what the documented ceilings are — arrive as api.RerankSettings; this
// package contains no vendor names.
package cohererank
import (
"bytes"
"context"
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client talks the Cohere rerank shape to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const defaultPath = "/rerank"
// url resolves the endpoint. A vendor whose default base URL already names
// the full rerank endpoint — and an operator who pasted one — must not have
// the path appended twice.
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = defaultPath
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type request struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []string `json:"documents"`
TopN int `json:"top_n,omitempty"`
// TruncatePromptTokens is a vLLM extension, not part of any vendor's
// documented schema. It is sent only when the operator opted in, because
// a gateway that does not implement it rejects the unknown field.
TruncatePromptTokens int `json:"truncate_prompt_tokens,omitempty"`
ReturnDocuments *bool `json:"return_documents,omitempty"`
}
type response struct {
Results []result `json:"results"`
}
type result struct {
Index int `json:"index"`
RelevanceScore *float64 `json:"relevance_score"`
Score *float64 `json:"score"`
Document document `json:"document"`
}
// document is the echoed text, which vendors spell either as a bare string
// or as an object with a text field.
type document struct {
Text string
}
func (d *document) UnmarshalJSON(data []byte) error {
var text string
if err := json.Unmarshal(data, &text); err == nil {
d.Text = text
return nil
}
var obj struct {
Text string `json:"text"`
}
if err := json.Unmarshal(data, &obj); err != nil {
return fmt.Errorf("decode document: %w", err)
}
d.Text = obj.Text
return nil
}
// BuildRequestBody is the golden-test entry point: it returns the exact JSON
// object that would be sent.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
body := request{
Model: c.cfg.Endpoint.Model,
Query: query,
Documents: documents,
}
if c.cfg.Settings.AcceptsTruncatePromptTokens {
body.TruncatePromptTokens = c.cfg.Settings.TruncatePromptTokens
}
if c.cfg.Settings.SendTopN {
body.TopN = len(documents)
}
if c.cfg.Settings.SendReturnDocs {
enabled := true
body.ReturnDocuments = &enabled
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
return out, nil
}
// BuildImageRequestBody is the golden-test entry point for image documents.
// The shape has no standard image document; a vendor that extends it names
// the key of the object that carries one. Jina's reranker reference gives
// {"image": URL or base64} documents; it shows no base64 example, so the
// data URI its embeddings reference documents is used (unverified for
// rerank). The request carries images only, so text documents never change
// shape.
func (c *Client) BuildImageRequestBody(query string, images []api.EmbedImage) (map[string]any, error) {
documents := make([]any, len(images))
for i, img := range images {
documents[i] = map[string]any{c.cfg.Settings.ImageField: img.DataURI()}
}
body, err := c.BuildRequestBody(query, nil)
if err != nil {
return nil, err
}
body["documents"] = documents
if c.cfg.Settings.SendTopN {
body["top_n"] = len(images)
}
// Results are matched by index; an echoed image document would carry its
// whole base64 payload back for nothing.
if _, asked := body["return_documents"]; asked {
body["return_documents"] = false
}
return body, nil
}
// AcceptsImages reports whether the vendor names an image field; without one
// a Cohere-shaped endpoint takes text documents only.
func (c *Client) AcceptsImages() bool { return c.cfg.Settings.ImageField != "" }
// Rerank scores documents against the query, in the order they were given.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
return c.post(ctx, body, len(documents))
}
// RerankImages scores image documents against the query; indices refer to
// images.
func (c *Client) RerankImages(ctx context.Context, query string, images []api.EmbedImage) ([]api.RerankResult, error) {
if !c.AcceptsImages() {
return nil, fmt.Errorf("this rerank endpoint declares no image documents")
}
body, err := c.BuildImageRequestBody(query, images)
if err != nil {
return nil, err
}
return c.post(ctx, body, len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, count int) ([]api.RerankResult, error) {
// Decode into raw JSON first: some Cohere-shaped runtimes (SGLang, for
// one) answer the same request with a bare array instead of the
// {"results": [...]} envelope. Both shapes mean the same thing, so the
// envelope is not part of the contract callers may rely on.
var raw json.RawMessage
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), body, &raw); err != nil {
return nil, err
}
results, err := decodeResults(raw)
if err != nil {
return nil, err
}
out := make([]api.RerankResult, 0, len(results))
for _, item := range results {
if item.Index < 0 || item.Index >= count {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", item.Index, count)
}
out = append(out, api.RerankResult{
Index: item.Index,
Score: firstNonNil(item.RelevanceScore, item.Score),
Text: item.Document.Text,
})
}
return out, nil
}
// decodeResults accepts both documented envelopes: the Cohere object
// {"results": [...]} and the bare array some self-hosted runtimes return.
func decodeResults(raw []byte) ([]result, error) {
trimmed := bytes.TrimSpace(raw)
if len(trimmed) > 0 && trimmed[0] == '[' {
var results []result
if err := json.Unmarshal(trimmed, &results); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return results, nil
}
var decoded response
if err := json.Unmarshal(trimmed, &decoded); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
return decoded.Results, nil
}
// firstNonNil picks relevance_score, falling back to score: the field is
// spelled both ways across vendors that otherwise share this shape.
func firstNonNil(values ...*float64) float64 {
for _, v := range values {
if v != nil {
return *v
}
}
return 0
}
@@ -0,0 +1,275 @@
package cohererank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// zhipuResponse is the documented response of Zhipu's rerank endpoint, whose
// result objects carry document / index / relevance_score and whose envelope
// adds id, request_id, created and usage:
// https://docs.bigmodel.cn/api-reference/模型-api/文本重排序
const zhipuResponse = `{
"id": "8305283656248111323",
"request_id": "8305283656248111323",
"created": 1769040000,
"results": [
{"index": 1, "relevance_score": 0.9819, "document": "上海气候"},
{"index": 0, "relevance_score": 0.0021, "document": "北京美食"}
],
"usage": {"prompt_tokens": 24, "total_tokens": 24}
}`
// jinaResponse spells the echoed document as an object instead of a string,
// which is the other shape vendors use for the same field:
// https://jina.ai/reranker/
const jinaResponse = `{
"model": "jina-reranker-v3.5",
"results": [
{"index": 0, "relevance_score": 0.95, "document": {"text": "上海气候"}},
{"index": 1, "relevance_score": 0.11, "document": {"text": "北京美食"}}
],
"usage": {"total_tokens": 32}
}`
func newClient(t *testing.T, url string, settings api.RerankSettings) *Client {
t.Helper()
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "rerank", Auth: api.BearerAuth("k")},
Settings: settings,
})
}
// Cohere's v2 reference response, preserving every field and value:
// https://docs.cohere.com/v2/reference/rerank (2026-10-09).
// Unlike the other fixtures, it contains no echoed document.
const cohereV2Response = `{
"results": [
{"index": 3, "relevance_score": 0.999071},
{"index": 4, "relevance_score": 0.7867867},
{"index": 0, "relevance_score": 0.32713068}
],
"id": "07734bd2-2473-4f07-94e1-0d9f0e6843cf",
"meta": {
"api_version": {"version": "2", "is_experimental": false},
"billed_units": {"search_units": 1}
}
}`
func TestDecodesCohereV2ReferenceResponse(t *testing.T) {
server, path, _ := serve(t, cohereV2Response)
defer server.Close()
c := newClient(t, server.URL+"/v2", api.RerankSettings{})
// Only the response is the documented fixture; these five placeholder
// documents supply its index range, not the reference's example texts.
got, err := c.Rerank(context.Background(), "q", []string{"a", "b", "c", "d", "e"})
require.NoError(t, err)
assert.Equal(t, "/v2/rerank", *path)
assert.Equal(t, []api.RerankResult{
{Index: 3, Score: 0.999071},
{Index: 4, Score: 0.7867867},
{Index: 0, Score: 0.32713068},
}, got)
}
func serve(t *testing.T, payload string) (*httptest.Server, *string, *map[string]any) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
path := new(string)
body := new(map[string]any)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*path = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(payload))
}))
return server, path, body
}
func TestRequestBodyCarriesOnlyWhatTheVendorDeclares(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{})
body, err := c.BuildRequestBody("上海天气", []string{"上海气候", "北京美食"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "rerank",
"query": "上海天气",
"documents": []any{"上海气候", "北京美食"},
}, body, "optional fields must be absent unless the vendor asked for them")
}
func TestRequestBodyAddsTheOptionalFieldsAVendorDeclares(t *testing.T) {
c := newClient(t, "https://example.invalid/v1",
api.RerankSettings{SendTopN: true, SendReturnDocs: true})
body, err := c.BuildRequestBody("q", []string{"a", "b", "c"})
require.NoError(t, err)
assert.Equal(t, float64(3), body["top_n"], "top_n asks for every document back")
assert.Equal(t, true, body["return_documents"])
}
func TestDecodesAStringDocument(t *testing.T) {
server, _, _ := serve(t, zhipuResponse)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "上海天气", []string{"北京美食", "上海气候"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 1, Score: 0.9819, Text: "上海气候"},
{Index: 0, Score: 0.0021, Text: "北京美食"},
}, got)
}
func TestDecodesAnObjectDocument(t *testing.T) {
server, _, _ := serve(t, jinaResponse)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "上海天气", []string{"上海气候", "北京美食"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 0, Score: 0.95, Text: "上海气候"},
{Index: 1, Score: 0.11, Text: "北京美食"},
}, got)
}
// Some gateways serving this shape spell the score `score`. The pre-catalog
// client accepted both and so does this one.
func TestDecodesTheScoreAlias(t *testing.T) {
server, _, _ := serve(t, `{"results":[{"index":0,"score":0.42}]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
require.Len(t, got, 1)
assert.InDelta(t, 0.42, got[0].Score, 1e-9)
}
// sglangBareArrayResponse is what SGLang's /v1/rerank answers to the same
// request: a bare array with score/document instead of the Cohere envelope.
// Self-hosted Qwen3-Reranker deployments are commonly served this way.
const sglangBareArrayResponse = `[
{"score": 0.0015978454940173438, "document": "doc one", "index": 0, "meta_info": null},
{"score": 0.0011695108220694027, "document": "doc two", "index": 1, "meta_info": null}
]`
func TestDecodesABareArrayResponse(t *testing.T) {
server, _, _ := serve(t, sglangBareArrayResponse)
defer server.Close()
c := newClient(t, server.URL+"/v1", api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"doc one", "doc two"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 0, Score: 0.0015978454940173438, Text: "doc one"},
{Index: 1, Score: 0.0011695108220694027, Text: "doc two"},
}, got)
}
func TestBareArrayResponseStillValidatesIndexes(t *testing.T) {
server, _, _ := serve(t, `[{"index":5,"score":0.5,"document":"d"}]`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "out of range")
}
func TestRejectsAnUnsupportedResponseEnvelope(t *testing.T) {
server, _, _ := serve(t, `"not a rerank response"`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "decode response")
}
func TestAppendsTheRerankPathToABareBaseURL(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL+"/v1", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/v1/rerank", *path)
}
// Zhipu's default base URL already ends in /rerank, and operators paste full
// endpoints too. Appending the path again would 404.
func TestDoesNotDoubleTheRerankPath(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL+"/api/paas/v4/rerank", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/api/paas/v4/rerank", *path)
}
// Academy Cloud serves the same shape on its own path.
func TestHonoursAVendorDeclaredPath(t *testing.T) {
server, path, _ := serve(t, `{"results":[]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{Path: "/api/v1/rerank"})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/api/v1/rerank", *path)
}
func TestRejectsAnOutOfRangeIndex(t *testing.T) {
server, _, _ := serve(t, `{"results":[{"index":9,"relevance_score":0.5}]}`)
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "out of range")
}
func TestSurfacesTheVendorErrorBody(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.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"error":{"message":"documents exceeds the limit"}}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "documents exceeds the limit")
}
// truncate_prompt_tokens is a vLLM extension that appears in no managed
// vendor's documented schema. It is sent only where the vendor declared it
// and the operator opted in, and never by default — sending it unasked is how
// an undocumented field ends up on every request to every gateway.
func TestTruncatePromptTokensIsAbsentByDefault(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.NotContains(t, body, "truncate_prompt_tokens")
}
func TestTruncatePromptTokensIsSentWhenTheRowOptedIn(t *testing.T) {
c := newClient(t, "https://example.invalid/v1", api.RerankSettings{
AcceptsTruncatePromptTokens: true, TruncatePromptTokens: 512,
})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, float64(512), body["truncate_prompt_tokens"])
}
+333
View File
@@ -0,0 +1,333 @@
package api
// ThinkingFormat names how an OpenAI-compatible vendor encodes the thinking
// switch. It is the single most divergent field across vendors, which is
// why it is an enum rather than free text.
type ThinkingFormat string
const (
// ThinkingFormatNone sends no thinking fields at all.
ThinkingFormatNone ThinkingFormat = "none"
// ThinkingFormatOpenAI sends only reasoning_effort (OpenAI, Azure, xAI).
ThinkingFormatOpenAI ThinkingFormat = "openai"
// ThinkingFormatThinkingType sends {"thinking": {"type": "enabled"|"disabled"}}
// plus reasoning_effort when supported (DeepSeek, Zhipu, Volcengine Ark,
// Moonshot K2.6+, MiniMax M3, LKEAP).
ThinkingFormatThinkingType ThinkingFormat = "thinking-type"
// ThinkingFormatEnableThinking sends enable_thinking: bool plus
// thinking_budget (DashScope, SiliconFlow, Hunyuan).
ThinkingFormatEnableThinking ThinkingFormat = "enable-thinking"
// ThinkingFormatChatTemplateKwargs sends chat_template_kwargs.enable_thinking
// (vLLM, SGLang, NIM, LiteLLM in front of them).
ThinkingFormatChatTemplateKwargs ThinkingFormat = "chat-template-kwargs"
// ThinkingFormatOpenRouter sends {"reasoning": {"effort"|"enabled"}}.
ThinkingFormatOpenRouter ThinkingFormat = "openrouter"
)
// OpenAICompletionsCompat is the overlay form (every field optional) of the
// Chat Completions settings. JSON keys are the documented names used in
// models.json and config/models.json.
type OpenAICompletionsCompat struct {
MaxTokensField *string `json:"max_tokens_field,omitempty"`
ThinkingFormat *ThinkingFormat `json:"thinking_format,omitempty"`
ThinkingEnabledValue *string `json:"thinking_enabled_value,omitempty"`
ThinkingAlwaysSend *bool `json:"thinking_always_send,omitempty"`
ThinkingDisableOnNonStream *bool `json:"thinking_disable_on_non_stream,omitempty"`
ThinkingBudgetField *string `json:"thinking_budget_field,omitempty"`
ThinkingBudgetExcludesEffort *bool `json:"thinking_budget_excludes_effort,omitempty"`
ReasoningEffortField *string `json:"reasoning_effort_field,omitempty"`
SupportsReasoningEffort *bool `json:"supports_reasoning_effort,omitempty"`
SupportsDeveloperRole *bool `json:"supports_developer_role,omitempty"`
SupportsStore *bool `json:"supports_store,omitempty"`
SupportsUsageInStreaming *bool `json:"supports_usage_in_streaming,omitempty"`
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
FixedTemperature *float64 `json:"fixed_temperature,omitempty"`
SupportsSeed *bool `json:"supports_seed,omitempty"`
ToolChoiceModes []string `json:"tool_choice_modes,omitempty"`
SupportsParallelToolCalls *bool `json:"supports_parallel_tool_calls,omitempty"`
SupportsResponseFormat *bool `json:"supports_response_format,omitempty"`
SupportsMultiContent *bool `json:"supports_multi_content,omitempty"`
ReplayReasoningContent *bool `json:"replay_reasoning_content,omitempty"`
PromptCacheKey *bool `json:"prompt_cache_key,omitempty"`
CacheControlFormat *string `json:"cache_control_format,omitempty"`
PromptCacheAccounting *bool `json:"prompt_cache_accounting,omitempty"`
ToolCallExtraFields []string `json:"tool_call_extra_fields,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
ReasoningFields []string `json:"reasoning_fields,omitempty"`
}
// OpenAICompletionsSettings is the resolved (fully defaulted) form.
type OpenAICompletionsSettings struct {
// MaxTokensField is "max_tokens" or "max_completion_tokens".
MaxTokensField string
ThinkingFormat ThinkingFormat
// ThinkingEnabledValue is the "type" sent for thinking-type when enabled
// ("enabled" by default; MiniMax M3 uses "adaptive").
ThinkingEnabledValue string
// ThinkingAlwaysSend pins the switch on every request even when the
// caller expressed no preference (DashScope hybrid models require it).
ThinkingAlwaysSend bool
// ThinkingDisableOnNonStream forces the switch off for non-streaming
// calls (Qwen3 rejects thinking without stream).
ThinkingDisableOnNonStream bool
// ThinkingBudgetField carries Options.ThinkingBudgetTokens ("thinking_budget").
ThinkingBudgetField string
// ThinkingBudgetExcludesEffort marks a vendor that rejects a request
// carrying both the budget and the effort (DashScope's qwen3.8-max
// series: "不支持 reasoning_effort 与 thinking_budget 同时设置,同时设置
// 会报错"). The graded level is what the caller actually picked, so the
// budget is the field that yields.
ThinkingBudgetExcludesEffort bool
// ReasoningEffortField is "reasoning_effort" unless a vendor renames it.
ReasoningEffortField string
SupportsReasoningEffort bool
// SupportsDeveloperRole switches the system prompt to the developer role
// on reasoning models.
SupportsDeveloperRole bool
// SupportsStore sends store:false (OpenAI keeps completions otherwise).
SupportsStore bool
SupportsUsageInStreaming bool
// SupportsTemperature false drops every sampling parameter (o-series,
// GPT-5 family, Kimi K2.5+).
SupportsTemperature bool
// FixedTemperature pins the value when the vendor only accepts one.
FixedTemperature *float64
SupportsSeed bool
ToolChoiceModes []string
SupportsParallelToolCalls bool
SupportsResponseFormat bool
// SupportsMultiContent false flattens image/text parts to plain text.
SupportsMultiContent bool
// ReplayReasoningContent sends reasoning_content on prior assistant turns.
ReplayReasoningContent bool
// PromptCacheKey sends prompt_cache_key / prompt_cache_retention and the
// session-affinity headers.
PromptCacheKey bool
// CacheControlFormat "anthropic" injects cache_control breakpoints.
CacheControlFormat string
// PromptCacheAccounting states the vendor reports cache usage at all.
PromptCacheAccounting bool
// ToolCallExtraFields lists tool_call keys to round-trip opaquely
// (Gemini-through-OpenAI "extra_content").
ToolCallExtraFields []string
// ExtraBody is merged into every request body (vendor knobs such as
// enable_search, sampling defaults).
ExtraBody map[string]any
// ReasoningFields are the delta keys that carry thinking text, in
// priority order.
ReasoningFields []string
}
// DefaultOpenAICompletions is the protocol baseline: plain OpenAI semantics.
func DefaultOpenAICompletions() OpenAICompletionsSettings {
return OpenAICompletionsSettings{
MaxTokensField: "max_completion_tokens",
ThinkingFormat: ThinkingFormatNone,
ThinkingEnabledValue: "enabled",
ReasoningEffortField: "reasoning_effort",
SupportsUsageInStreaming: true,
SupportsTemperature: true,
SupportsSeed: true,
ToolChoiceModes: []string{"none", "auto", "required", "function"},
SupportsParallelToolCalls: true,
SupportsResponseFormat: true,
SupportsMultiContent: true,
ReplayReasoningContent: true,
ReasoningFields: []string{"reasoning_content", "reasoning", "reasoning_text"},
}
}
// AllowsToolChoice reports whether a tool_choice mode is accepted.
func (s OpenAICompletionsSettings) AllowsToolChoice(mode string) bool {
for _, m := range s.ToolChoiceModes {
if m == mode {
return true
}
}
return false
}
// OpenAIResponsesCompat is the overlay for the Responses protocol.
type OpenAIResponsesCompat struct {
SupportsDeveloperRole *bool `json:"supports_developer_role,omitempty"`
SupportsMaxOutputTokens *bool `json:"supports_max_output_tokens,omitempty"`
SupportsReasoningSummary *bool `json:"supports_reasoning_summary,omitempty"`
SupportsEncryptedReasoning *bool `json:"supports_encrypted_reasoning,omitempty"`
SupportsStore *bool `json:"supports_store,omitempty"`
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
PromptCacheKey *bool `json:"prompt_cache_key,omitempty"`
SupportsLongCacheRetention *bool `json:"supports_long_cache_retention,omitempty"`
SupportsParallelToolCalls *bool `json:"supports_parallel_tool_calls,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
}
// OpenAIResponsesSettings is the resolved Responses configuration.
type OpenAIResponsesSettings struct {
SupportsDeveloperRole bool
SupportsMaxOutputTokens bool
SupportsReasoningSummary bool
SupportsEncryptedReasoning bool
SupportsStore bool
SupportsTemperature bool
PromptCacheKey bool
SupportsLongCacheRetention bool
SupportsParallelToolCalls bool
ExtraBody map[string]any
}
// DefaultOpenAIResponses is the openai.com baseline.
func DefaultOpenAIResponses() OpenAIResponsesSettings {
return OpenAIResponsesSettings{
SupportsDeveloperRole: true,
SupportsMaxOutputTokens: true,
SupportsReasoningSummary: true,
SupportsEncryptedReasoning: true,
SupportsStore: true,
SupportsTemperature: true,
PromptCacheKey: true,
SupportsLongCacheRetention: true,
SupportsParallelToolCalls: true,
}
}
// AnthropicThinkingMode selects the thinking request shape.
type AnthropicThinkingMode string
const (
// AnthropicThinkingBudget sends {"type":"enabled","budget_tokens":N}.
AnthropicThinkingBudget AnthropicThinkingMode = "budget"
// AnthropicThinkingAdaptive sends {"type":"adaptive"} and steers the
// intensity through output_config.effort.
AnthropicThinkingAdaptive AnthropicThinkingMode = "adaptive"
)
// AnthropicMessagesCompat is the overlay for the Messages protocol.
type AnthropicMessagesCompat struct {
ThinkingMode *AnthropicThinkingMode `json:"thinking_mode,omitempty"`
ThinkingOffType *string `json:"thinking_off_type,omitempty"`
SupportsEffort *bool `json:"supports_effort,omitempty"`
ThinkingBudgets map[ReasoningEffort]int `json:"thinking_budgets,omitempty"`
DefaultMaxTokens *int `json:"default_max_tokens,omitempty"`
SupportsTemperature *bool `json:"supports_temperature,omitempty"`
TemperatureWithThinking *bool `json:"temperature_with_thinking,omitempty"`
SupportsTopP *bool `json:"supports_top_p,omitempty"`
SupportsCacheControl *bool `json:"supports_cache_control,omitempty"`
SupportsCacheControlOnTool *bool `json:"supports_cache_control_on_tools,omitempty"`
LongCacheTTL *string `json:"long_cache_ttl,omitempty"`
Version *string `json:"version,omitempty"`
BetaHeaders []string `json:"beta_headers,omitempty"`
InterleavedThinkingBeta *string `json:"interleaved_thinking_beta,omitempty"`
PromptCacheAccounting *bool `json:"prompt_cache_accounting,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
}
// AnthropicMessagesSettings is the resolved Messages configuration.
type AnthropicMessagesSettings struct {
ThinkingMode AnthropicThinkingMode
// ThinkingOffType is the thinking.type sent to turn thinking off in
// adaptive mode; empty means "disabled". Claude Sonnet 5.5 rejects
// "disabled" and turns off up-front thinking with "between_tools".
ThinkingOffType string `json:",omitempty"`
SupportsEffort bool
// ThinkingBudgets maps graded levels to budget_tokens for budget mode.
ThinkingBudgets map[ReasoningEffort]int
// DefaultMaxTokens is used when the caller set no budget (max_tokens is
// mandatory on this protocol).
DefaultMaxTokens int
SupportsTemperature bool
TemperatureWithThinking bool
SupportsTopP bool
SupportsCacheControl bool
SupportsCacheControlOnTool bool
LongCacheTTL string
Version string
BetaHeaders []string
// InterleavedThinkingBeta is added to anthropic-beta when thinking and
// tools are both active (budget mode only). Empty disables it.
InterleavedThinkingBeta string
PromptCacheAccounting bool
ExtraBody map[string]any
}
// DefaultAnthropicMessages is the anthropic.com baseline for the
// budget-thinking generation of models.
func DefaultAnthropicMessages() AnthropicMessagesSettings {
return AnthropicMessagesSettings{
ThinkingMode: AnthropicThinkingBudget,
ThinkingBudgets: map[ReasoningEffort]int{
ReasoningMinimal: 1024,
ReasoningLow: 2048,
ReasoningMedium: 8192,
ReasoningHigh: 16384,
ReasoningXHigh: 32768,
ReasoningMax: 63999,
},
DefaultMaxTokens: 4096,
SupportsTemperature: true,
TemperatureWithThinking: false,
SupportsTopP: true,
SupportsCacheControl: true,
SupportsCacheControlOnTool: true,
LongCacheTTL: "1h",
Version: "2023-06-01",
InterleavedThinkingBeta: "interleaved-thinking-2025-05-14",
PromptCacheAccounting: true,
}
}
// GoogleThinkingMode selects the thinkingConfig shape.
type GoogleThinkingMode string
const (
// GoogleThinkingBudget sends thinkingConfig.thinkingBudget (Gemini 2.5).
GoogleThinkingBudget GoogleThinkingMode = "budget"
// GoogleThinkingLevel sends thinkingConfig.thinkingLevel (Gemini 3+).
GoogleThinkingLevel GoogleThinkingMode = "level"
// GoogleThinkingNone sends no thinkingConfig.
GoogleThinkingNone GoogleThinkingMode = "none"
)
// GoogleGenerativeAICompat is the overlay for the Gemini protocol.
type GoogleGenerativeAICompat struct {
ThinkingMode *GoogleThinkingMode `json:"thinking_mode,omitempty"`
ThinkingBudgets map[ReasoningEffort]int `json:"thinking_budgets,omitempty"`
IncludeThoughts *bool `json:"include_thoughts,omitempty"`
SupportsSeed *bool `json:"supports_seed,omitempty"`
SupportsPenalty *bool `json:"supports_penalty,omitempty"`
ExtraGeneration map[string]any `json:"extra_generation_config,omitempty"`
PromptCacheAcct *bool `json:"prompt_cache_accounting,omitempty"`
APIVersionPrefix *string `json:"api_version_prefix,omitempty"`
}
// GoogleGenerativeAISettings is the resolved Gemini configuration.
type GoogleGenerativeAISettings struct {
ThinkingMode GoogleThinkingMode
ThinkingBudgets map[ReasoningEffort]int
IncludeThoughts bool
SupportsSeed bool
SupportsPenalty bool
ExtraGeneration map[string]any
PromptCacheAcct bool
// APIVersionPrefix is appended to a bare host base URL ("/v1beta").
APIVersionPrefix string
}
// DefaultGoogleGenerativeAI is the generativelanguage.googleapis.com baseline.
func DefaultGoogleGenerativeAI() GoogleGenerativeAISettings {
return GoogleGenerativeAISettings{
ThinkingMode: GoogleThinkingBudget,
ThinkingBudgets: map[ReasoningEffort]int{
ReasoningMinimal: 128,
ReasoningLow: 2048,
ReasoningMedium: 8192,
ReasoningHigh: 24576,
ReasoningXHigh: 32768,
ReasoningMax: 32768,
},
IncludeThoughts: true,
SupportsSeed: true,
SupportsPenalty: true,
PromptCacheAcct: true,
APIVersionPrefix: "/v1beta",
}
}
+11
View File
@@ -0,0 +1,11 @@
package api
// Credentials is what the operator stored for one model row.
type Credentials struct {
APIKey string
AppID string
AppSecret string
}
// Ptr returns a pointer for optional protocol settings.
func Ptr[T any](value T) *T { return &value }
@@ -0,0 +1,119 @@
// Package dashscopeembeddings implements Alibaba Model Studio's native
// multimodal embedding shape: input.contents, parameters.dimension, and
// results under output.embeddings.
//
// Only the multimodal models use it. DashScope's text embeddings are served
// on the OpenAI-compatible endpoint, which is why the vendor's default
// protocol is the OpenAI one and the multimodal entries override it.
//
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
package dashscopeembeddings
import (
"context"
"fmt"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
Dimensions int
Retry api.RetryPolicy
}
// Client talks DashScope's native multimodal embedding to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type response struct {
Output struct {
Embeddings []struct {
// The position field is `index`. DashScope's *text* embedding API
// one page over calls it `text_index`, and decoding that name
// here yields 0 for every element, collapsing a whole batch onto
// slot 0 (Tencent/WeKnora#3484).
Index int `json:"index"`
Embedding []float32 `json:"embedding"`
Type string `json:"type"`
} `json:"embeddings"`
} `json:"output"`
Code string `json:"code"`
Message string `json:"message"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(texts []string, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(texts))
for _, text := range texts {
contents = append(contents, map[string]any{"text": text})
}
return c.body(contents)
}
// BuildImageRequestBody is the golden-test entry point for images. Each
// content is {"image": URL or "data:image/{format};base64,{data}"}.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, _ api.EmbedInputType) map[string]any {
contents := make([]any, 0, len(images))
for _, img := range images {
contents = append(contents, map[string]any{"image": img.DataURI()})
}
return c.body(contents)
}
func (c *Client) body(contents []any) map[string]any {
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"input": map[string]any{"contents": contents},
}
// The width lives under parameters, not at the top level, and the field
// is singular: `dimension`.
if c.cfg.Settings.DimensionsField != "" && c.cfg.Dimensions > 0 {
body["parameters"] = map[string]any{c.cfg.Settings.DimensionsField: c.cfg.Dimensions}
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one batch.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))
}
// AcceptsImages is always true: the image part is part of the schema.
func (c *Client) AcceptsImages() bool { return true }
// EmbedImages vectorizes one batch of images, each its own vector.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, url, body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
// DashScope reports some failures in the body with a 200.
if decoded.Code != "" {
return nil, fmt.Errorf("DashScope embedding error %s: %s", decoded.Code, decoded.Message)
}
return api.PlaceEmbeddings(want, len(decoded.Output.Embeddings), func(i int) (int, []float32) {
return decoded.Output.Embeddings[i].Index, decoded.Output.Embeddings[i].Embedding
})
}
@@ -0,0 +1,90 @@
package dashscopeembeddings
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the response example from DashScope's multimodal
// embedding reference, copied verbatim so the decoder is pinned against the
// vendor's own document:
// https://help.aliyun.com/zh/model-studio/multimodal-embedding-api-reference
//
// The position field is `index`. Reading `text_index` — the name used by
// DashScope's text embedding API — put a whole batch in slot 0 (#3484).
const documentedResponse = `{
"output": {
"embeddings": [
{"index": 0, "embedding": [-0.026611328125, -0.016571044921875], "type": "text"},
{"index": 1, "embedding": [0.051544189453125, 0.007717132568359375], "type": "text"}
]
},
"usage": {"input_tokens": 10, "total_tokens": 10},
"request_id": "1fff9502-a6c5-9472-9ee1-73930fdd04c5"
}`
const endpoint = "/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding"
func newClient(url string, dims int) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "tongyi-embedding-vision-plus", Auth: api.BearerAuth("k")},
Settings: api.EmbeddingsSettings{DimensionsField: "dimension"},
Dimensions: dims,
})
}
func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {
body := newClient("https://dashscope.aliyuncs.com"+endpoint, 1152).
BuildRequestBody([]string{"a", "b"}, api.EmbedDocument)
assert.Equal(t, map[string]any{
"model": "tongyi-embedding-vision-plus",
"input": map[string]any{"contents": []any{
map[string]any{"text": "a"}, map[string]any{"text": "b"},
}},
// Under parameters, and singular.
"parameters": map[string]any{"dimension": 1152},
}, body)
}
func TestNoParametersWithoutARequestedWidth(t *testing.T) {
body := newClient("https://dashscope.aliyuncs.com"+endpoint, 0).
BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.NotContains(t, body, "parameters")
}
func TestDecodesTheDocumentedResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
got, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{
{-0.026611328125, -0.016571044921875},
{0.051544189453125, 0.007717132568359375},
}, got, "each vector must land in its own slot, by index")
assert.Equal(t, endpoint, path, "the base URL already names the endpoint")
}
// DashScope answers some failures with a 200 and a code in the body.
func TestSurfacesAnInBodyError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":"InvalidParameter","message":"contents exceeds 20"}`))
}))
defer server.Close()
_, err := newClient(server.URL+endpoint, 0).Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "contents exceeds 20")
}
+115
View File
@@ -0,0 +1,115 @@
// Package dashscoperank implements Alibaba Model Studio's native text-rerank
// shape: the same fields as the Cohere dialect, wrapped in input/parameters
// and answered under output.
//
// https://help.aliyun.com/zh/model-studio/text-rerank-api
package dashscoperank
import (
"context"
"encoding/json"
"fmt"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client talks DashScope's native rerank to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type request struct {
Model string `json:"model"`
Input input `json:"input"`
Parameters parameters `json:"parameters"`
}
type input struct {
Query string `json:"query"`
Documents []string `json:"documents"`
}
type parameters struct {
ReturnDocuments bool `json:"return_documents"`
TopN int `json:"top_n"`
}
type response struct {
Output struct {
Results []struct {
Index int `json:"index"`
RelevanceScore float64 `json:"relevance_score"`
Document struct {
Text string `json:"text"`
} `json:"document"`
} `json:"results"`
} `json:"output"`
// DashScope reports failures in the body with a 200 on some paths.
Code string `json:"code"`
Message string `json:"message"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
body := request{
Model: c.cfg.Endpoint.Model,
Input: input{Query: query, Documents: documents},
Parameters: parameters{
ReturnDocuments: c.cfg.Settings.SendReturnDocs,
// top_n is not optional in this shape: leaving it at zero would
// ask for no documents at all, so the full count is always sent.
TopN: len(documents),
},
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
return out, nil
}
// Rerank scores documents against the query.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
if err := c.cfg.Endpoint.PostJSON(ctx, url, body, &decoded); err != nil {
return nil, err
}
if decoded.Code != "" {
return nil, fmt.Errorf("DashScope rerank error %s: %s", decoded.Code, decoded.Message)
}
out := make([]api.RerankResult, 0, len(decoded.Output.Results))
for _, item := range decoded.Output.Results {
if item.Index < 0 || item.Index >= len(documents) {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", item.Index, len(documents))
}
out = append(out, api.RerankResult{
Index: item.Index,
Score: item.RelevanceScore,
Text: item.Document.Text,
})
}
return out, nil
}
@@ -0,0 +1,115 @@
package dashscoperank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the response shape of DashScope's text-rerank API,
// copied from the reference so the decoder is pinned against the vendor's own
// document: https://help.aliyun.com/zh/model-studio/text-rerank-api
const documentedResponse = `{
"output": {
"results": [
{"document": {"text": "上海气候"}, "index": 1, "relevance_score": 0.7314},
{"document": {"text": "北京美食"}, "index": 0, "relevance_score": 0.0002}
]
},
"usage": {"total_tokens": 24},
"request_id": "4c5b1c4d-0e2f-9b1a-8a1e-1b2c3d4e5f60"
}`
const endpointURL = "https://dashscope.aliyuncs.com/api/v1/services/rerank/text-rerank/text-rerank"
func newClient(t *testing.T, url string, settings api.RerankSettings) *Client {
t.Helper()
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "gte-rerank-v2", Auth: api.BearerAuth("k")},
Settings: settings,
})
}
func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {
c := newClient(t, endpointURL, api.RerankSettings{SendReturnDocs: true})
body, err := c.BuildRequestBody("上海天气", []string{"北京美食", "上海气候"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "gte-rerank-v2",
"input": map[string]any{
"query": "上海天气",
"documents": []any{"北京美食", "上海气候"},
},
"parameters": map[string]any{
"return_documents": true,
"top_n": float64(2),
},
}, body)
}
// top_n is mandatory in this shape: zero would ask for nothing back, so the
// full document count is always sent regardless of vendor settings.
func TestTopNAlwaysCarriesTheDocumentCount(t *testing.T) {
c := newClient(t, endpointURL, api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"a", "b", "c", "d"})
require.NoError(t, err)
assert.Equal(t, float64(4), body["parameters"].(map[string]any)["top_n"])
}
func TestDecodesTheDocumentedResponse(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", "application/json")
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "上海天气", []string{"北京美食", "上海气候"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 1, Score: 0.7314, Text: "上海气候"},
{Index: 0, Score: 0.0002, Text: "北京美食"},
}, got)
}
// DashScope answers some failures with a 200 and an error code in the body,
// which would otherwise decode as an empty result set.
func TestSurfacesAnInBodyError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"code":"InvalidParameter","message":"documents is too long","request_id":"r"}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "documents is too long")
}
func TestPostsToTheBaseURLItself(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath string
var gotBody map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(&gotBody)
_, _ = w.Write([]byte(`{"output":{"results":[]}}`))
}))
defer server.Close()
c := newClient(t, server.URL+"/api/v1/services/rerank/text-rerank/text-rerank", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/api/v1/services/rerank/text-rerank/text-rerank", gotPath,
"the vendor's base URL already names the full endpoint")
}
+115
View File
@@ -0,0 +1,115 @@
package api
import (
"context"
"encoding/base64"
"fmt"
)
// EmbeddingAPI names an embedding wire protocol. Like RerankAPI it is its own
// type, so a chat row's extra_config.api cannot name an embedding dialect and
// pass validation.
type EmbeddingAPI string
// The embedding protocols Academy speaks.
const (
// EmbeddingOpenAI is POST {base}/embeddings with {model, input[]} answering
// {data: [{embedding, index}]} — the shape OpenAI defined and every
// compatible gateway copied. Jina, NVIDIA, Azure and Academy Cloud speak
// it too, with their own optional fields, URL or credential.
EmbeddingOpenAI EmbeddingAPI = "openai-embeddings"
// EmbeddingDashScope is Alibaba Model Studio's native multimodal shape:
// input.contents, parameters.dimension, output.embeddings.
EmbeddingDashScope EmbeddingAPI = "dashscope-embeddings"
// EmbeddingArk is Volcengine Ark's multimodal shape, which fuses every
// input into one vector and therefore embeds one text per request.
EmbeddingArk EmbeddingAPI = "ark-embeddings"
// EmbeddingGoogle is Gemini's batchEmbedContents.
EmbeddingGoogle EmbeddingAPI = "google-embeddings"
)
// Known reports whether the value names a protocol this build implements.
func (a EmbeddingAPI) Known() bool {
switch a {
case EmbeddingOpenAI, EmbeddingDashScope, EmbeddingArk, EmbeddingGoogle:
return true
}
return false
}
// EmbedInputType distinguishes the two sides of a retrieval pair. Several
// vendors score them differently and want to be told which one they are
// embedding; the field they want it in differs, so the catalog names it.
type EmbedInputType string
const (
// EmbedDocument is text being indexed.
EmbedDocument EmbedInputType = "document"
// EmbedQuery is text being searched with.
EmbedQuery EmbedInputType = "query"
)
// Embedder is what every embedding protocol package implements. Callers pass
// the whole batch; splitting it to the vendor's documented ceiling is the
// shared layer's job, not the protocol's.
type Embedder interface {
Embed(ctx context.Context, texts []string, kind EmbedInputType) ([][]float32, error)
}
// EmbedImage is one image to embed. It travels inline rather than as a URL:
// the object store Academy reads images from is usually not reachable from
// the vendor, and every multimodal vendor in the catalog accepts base64.
type EmbedImage struct {
Data []byte
MIMEType string
}
// Base64 is the image in standard base64, Gemini's inlineData form.
func (i EmbedImage) Base64() string { return base64.StdEncoding.EncodeToString(i.Data) }
// DataURI is the data:{mime};base64,{data} form Ark, DashScope and Jina
// document.
func (i EmbedImage) DataURI() string { return "data:" + i.MIMEType + ";base64," + i.Base64() }
// ImageEmbedder is implemented by the protocols that can carry an image.
// Whether a given model maps images into the space of its text vectors is
// the catalog entry's input, not the protocol's, so the caller checks that
// first. Callers pass a batch within EmbeddingsSettings.ImageBatchLimit.
type ImageEmbedder interface {
// AcceptsImages reports whether this endpoint can carry an image at all.
AcceptsImages() bool
EmbedImages(ctx context.Context, images []EmbedImage, kind EmbedInputType) ([][]float32, error)
}
// PlaceEmbeddings puts returned vectors back in the order the texts were
// sent, using the index each vendor reports, and refuses a response that does
// not cover every input.
//
// Both halves matter. A vendor is free to answer out of order, so the index
// has to be honoured rather than assumed — and reading the wrong field for it
// silently collapses a whole batch onto slot 0, which is what
// Tencent/WeKnora#3484 was. An unfilled slot then reaches the index as an
// empty vector, where it is stored and poisons retrieval without anything
// failing, so a gap is an error instead. So is an index reported twice: one
// of the two vectors belongs to some other input.
func PlaceEmbeddings(want, got int, at func(i int) (int, []float32)) ([][]float32, error) {
out := make([][]float32, want)
seen := make([]bool, want)
for i := 0; i < got; i++ {
index, vector := at(i)
if index < 0 || index >= want {
return nil, fmt.Errorf("embedding index %d out of range for %d inputs", index, want)
}
if seen[index] {
return nil, fmt.Errorf("embedding index %d returned twice", index)
}
seen[index] = true
out[index] = vector
}
for i, vector := range out {
if len(vector) == 0 {
return nil, fmt.Errorf("no embedding returned for input %d of %d", i, want)
}
}
return out, nil
}
+162
View File
@@ -0,0 +1,162 @@
package api
// EmbeddingsCompat is the overlay form (every field optional) of the
// embedding settings. JSON keys are the documented names used in models.json
// and config/models.json.
type EmbeddingsCompat struct {
// API overrides the vendor's embedding protocol for one model. Aliyun and
// Volcengine each serve two: a text endpoint in the OpenAI shape and a
// multimodal one of their own, chosen by which model the row names.
API *EmbeddingAPI `json:"api,omitempty"`
Path *string `json:"path,omitempty"`
SendEncodingFormat *bool `json:"send_encoding_format,omitempty"`
DimensionsField *string `json:"dimensions_field,omitempty"`
TruncateField *string `json:"truncate_field,omitempty"`
TruncateValue *string `json:"truncate_value,omitempty"`
InputTypeField *string `json:"input_type_field,omitempty"`
InputTypeValues map[string]string `json:"input_type_values,omitempty"`
MaxBatchSize *int `json:"max_batch_size,omitempty"`
MaxInputChars *int `json:"max_input_chars,omitempty"`
// AcceptsTruncatePromptTokens marks a vLLM-class runtime, the only kind
// that implements the `truncate_prompt_tokens` extension.
AcceptsTruncatePromptTokens *bool `json:"accepts_truncate_prompt_tokens,omitempty"`
RequestTimeout *int `json:"request_timeout_seconds,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
ImageField *string `json:"image_field,omitempty"`
MaxImageBatchSize *int `json:"max_image_batch_size,omitempty"`
MaxImageBytes *int `json:"max_image_bytes,omitempty"`
ImageMIMETypes []string `json:"image_mime_types,omitempty"`
ImageFormat *EmbeddingImageFormat `json:"image_format,omitempty"`
ImagePrompt *string `json:"image_prompt,omitempty"`
TextAsMessages *bool `json:"text_as_messages,omitempty"`
BatchMessages *bool `json:"batch_messages,omitempty"`
}
// EmbeddingImageFormat is how an image travels on the OpenAI embedding
// shape, which has no standard image input of its own.
type EmbeddingImageFormat string
const (
// EmbeddingImageObject puts {ImageField: data URI} in `input`, as Jina
// and SGLang document.
EmbeddingImageObject EmbeddingImageFormat = "object"
// EmbeddingImageMessages sends a chat conversation in `messages` instead
// of `input`, which is how vLLM serves multimodal embedding models
// (https://docs.vllm.ai/en/latest/models/pooling_models/embed/). Each
// conversation yields one vector; BatchMessages can batch conversations.
EmbeddingImageMessages EmbeddingImageFormat = "messages"
)
// Known reports whether f is a format this build can send; empty is known.
func (f EmbeddingImageFormat) Known() bool {
return f == "" || f == EmbeddingImageObject || f == EmbeddingImageMessages
}
// EmbeddingsSettings is the resolved (fully defaulted) form.
type EmbeddingsSettings struct {
// API is the protocol this model speaks, which may differ from the
// vendor's default.
API EmbeddingAPI
// Path is appended to the base URL; vendors whose default base URL names
// the full endpoint leave it empty.
Path string
// SendEncodingFormat sends encoding_format: "float". OpenAI documents it;
// several compatible gateways do not list it at all.
SendEncodingFormat bool
// DimensionsField carries the requested vector width: "dimensions" on the
// OpenAI shape, "dimension" on DashScope (nested under parameters),
// "outputDimensionality" on Gemini, and empty where the vendor does not
// let a request choose. It is sent only when the row opted in with
// supports_dimension_override; the field name is the vendor's fact, the
// decision to narrow the vector is the operator's.
DimensionsField string
// TruncateField and TruncateValue are the vendor's server-side truncation
// switch for over-long input: a boolean on Jina, an enum on NIM. Empty
// sends nothing.
TruncateField string
TruncateValue string
// InputTypeField names the parameter that distinguishes an indexed
// document from a search query, and InputTypeValues maps the neutral
// EmbedInputType values onto the vendor's vocabulary. Asymmetric
// models score the two sides differently and are measurably worse when
// both are embedded the same way.
InputTypeField string
InputTypeValues map[string]string
// MaxBatchSize and MaxInputChars are the documented per-request ceilings.
MaxBatchSize int
MaxInputChars int
// AcceptsTruncatePromptTokens reports a vLLM-class runtime. The extension
// appears in no managed vendor's schema, so it must never be sent to one.
AcceptsTruncatePromptTokens bool
// TruncatePromptTokens is the budget the operator opted into on this row,
// honoured only where the vendor accepts the extension.
TruncatePromptTokens int
// RequestTimeout caps one request, in seconds. 0 leaves the client
// without its own deadline and lets the caller's context govern.
RequestTimeout int
ExtraBody map[string]any
// ImageInput is how this endpoint takes images: on the OpenAI shape, the
// key of the input object that carries one ("image" on Jina; that shape
// has no standard image input, so an endpoint that names none takes no
// images), plus the documented per-request and per-image limits.
ImageInput
// ImageFormat chooses between ImageField's object in `input` and a chat
// conversation in `messages`. Empty means object when ImageField is set.
ImageFormat EmbeddingImageFormat `json:",omitempty"`
// ImagePrompt is the text sent beside each image in the messages format;
// some chat templates (VLM2Vec's) expect an instruction there. Empty
// sends the image alone.
ImagePrompt string `json:",omitempty"`
// TextAsMessages sends texts in the messages format too. A model whose
// chat template frames its inputs only places text and images in the same
// space when both pass through it; a plain `input` skips the template.
TextAsMessages bool `json:",omitempty"`
// BatchMessages enables independent conversations in a two-dimensional
// messages array (vLLM 0.29 supports this). False preserves the one-input
// request shape for older servers. Single inputs always keep that shape.
BatchMessages bool `json:",omitempty"`
}
// OpenAIImageFormat is the effective image format on the OpenAI shape, empty
// when the endpoint takes no images there.
func (s EmbeddingsSettings) OpenAIImageFormat() EmbeddingImageFormat {
switch {
case s.ImageFormat == EmbeddingImageMessages:
return EmbeddingImageMessages
case s.ImageField != "":
return EmbeddingImageObject
}
return ""
}
// BatchLimits renders the documented ceilings for SplitBatches.
func (s EmbeddingsSettings) BatchLimits() BatchLimits {
return BatchLimits{MaxItems: s.MaxBatchSize, MaxItemRunes: s.MaxInputChars}
}
// InputTypeValue maps a neutral input kind onto the vendor's vocabulary,
// returning "" when this vendor does not distinguish the two sides.
func (s EmbeddingsSettings) InputTypeValue(kind EmbedInputType) string {
if s.InputTypeField == "" {
return ""
}
if v, ok := s.InputTypeValues[string(kind)]; ok {
return v
}
return string(kind)
}
// DefaultEmbeddings is the protocol baseline, and it is deliberately bare:
// `model` and `input` are the only two fields every vendor in this catalog
// documents. The rest disagree — NVIDIA NIM and Volcengine's text endpoint
// have no `dimensions` at all, Zhipu has no `encoding_format`, and the
// parameter that separates a query from a document is spelled three
// different ways. A vendor that documents one declares it; nothing is sent
// on the assumption that an OpenAI-shaped endpoint accepts every OpenAI
// field.
//
// The one non-wire default is the request deadline: every pre-catalog
// embedding client carried 60 seconds.
func DefaultEmbeddings() EmbeddingsSettings {
return EmbeddingsSettings{RequestTimeout: 60}
}
+43
View File
@@ -0,0 +1,43 @@
package api
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
type placed struct {
index int
vector []float32
}
func place(want int, reply []placed) ([][]float32, error) {
return PlaceEmbeddings(want, len(reply), func(i int) (int, []float32) {
return reply[i].index, reply[i].vector
})
}
func TestPlaceEmbeddingsHonoursTheReportedIndex(t *testing.T) {
got, err := place(2, []placed{{1, []float32{2}}, {0, []float32{1}}})
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got)
}
// Every way a reply can fail to cover the inputs exactly once is an error:
// each of them would otherwise store a vector under the wrong chunk or an
// empty one.
func TestPlaceEmbeddingsRefusesAReplyThatDoesNotCoverEachInputOnce(t *testing.T) {
cases := map[string][]placed{
"short": {{0, []float32{1}}},
"out of range": {{0, []float32{1}}, {2, []float32{2}}},
"duplicate": {{0, []float32{1}}, {0, []float32{2}}, {1, []float32{3}}},
"empty vector": {{0, []float32{1}}, {1, nil}},
}
for name, reply := range cases {
t.Run(name, func(t *testing.T) {
_, err := place(2, reply)
assert.Error(t, err)
})
}
}
+271
View File
@@ -0,0 +1,271 @@
package api
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strconv"
"strings"
"time"
"academy/internal/logger"
"academy/internal/types"
secutils "academy/internal/utils"
)
// AuthFunc stamps credentials onto an outbound request. body is the exact
// bytes being sent so signing vendors can hash them.
type AuthFunc func(req *http.Request, body []byte)
// BearerAuth is the default: Authorization: Bearer <key>.
func BearerAuth(apiKey string) AuthFunc {
return func(req *http.Request, _ []byte) {
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
}
}
// HeaderAuth writes the key under an arbitrary header (api-key for Azure,
// x-api-key for Anthropic, x-goog-api-key for Gemini).
func HeaderAuth(header, apiKey string) AuthFunc {
return func(req *http.Request, _ []byte) {
if apiKey != "" {
req.Header.Set(header, apiKey)
}
}
}
// NoAuth sends no credentials at all (local deployments).
func NoAuth() AuthFunc { return func(*http.Request, []byte) {} }
// Endpoint is everything a protocol client needs to reach one model.
type Endpoint struct {
// BaseURL is the vendor root without a trailing slash.
BaseURL string
// URL, when set, is the complete request URL and overrides the protocol
// default of BaseURL + protocol path. Vendors with non-standard paths
// (Azure deployments, Academy Cloud) set it.
URL string
// Query is appended to the final URL (Azure api-version).
Query map[string]string
// Model is the name sent on the wire; ModelID is Academy's own identifier.
Model string
ModelID string
// Auth stamps credentials; Headers are static extra headers (vendor
// betas, user-configured custom headers). User headers never override
// the protocol's own reserved headers.
Auth AuthFunc
Headers map[string]string
// Client is the HTTP client; nil uses the shared SSRF-safe client.
Client *http.Client
}
// Resolve builds the request URL from the endpoint description.
func (e Endpoint) Resolve(defaultPath string) string {
target := e.URL
if target == "" {
target = strings.TrimRight(e.BaseURL, "/") + defaultPath
}
if len(e.Query) == 0 {
return target
}
var b strings.Builder
b.WriteString(target)
sep := "?"
if strings.Contains(target, "?") {
sep = "&"
}
for k, v := range e.Query {
b.WriteString(sep)
b.WriteString(k)
b.WriteString("=")
b.WriteString(v)
sep = "&"
}
return b.String()
}
func (e Endpoint) httpClient() *http.Client {
if e.Client != nil {
return e.Client
}
return HTTPClient
}
// NewRequest prepares an authenticated JSON POST. The body is marshalled
// once so signing vendors see exactly what is sent.
func (e Endpoint) NewRequest(ctx context.Context, url string, body any, stream bool) (*http.Request, []byte, error) {
data, err := json.Marshal(body)
if err != nil {
return nil, nil, fmt.Errorf("marshal request: %w", err)
}
req, err := e.newPost(ctx, url, data, "application/json")
if err != nil {
return nil, nil, err
}
if stream {
req.Header.Set("Accept", "text/event-stream")
}
return req, data, nil
}
// newPost prepares an authenticated POST of an already-encoded body.
func (e Endpoint) newPost(ctx context.Context, url string, data []byte, contentType string) (*http.Request, error) {
if err := secutils.ValidateURLForSSRF(url); err != nil {
return nil, fmt.Errorf("endpoint SSRF check failed: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(data))
if err != nil {
return nil, fmt.Errorf("create request: %w", err)
}
req.Header.Set("Content-Type", contentType)
if e.Auth != nil {
e.Auth(req, data)
}
// The helper skips reserved names so custom headers cannot clobber auth
// or content negotiation.
secutils.ApplyCustomHeaders(req, e.Headers)
// Identity belongs to this call, not the shared model configuration or
// a per-request UUID. Derived contexts retain it across turns and retries.
req.Header.Set("User-Agent", "Academy")
req.Header.Del("X-Conversation-ID")
if sessionID, ok := types.SessionIDFromContext(ctx); ok {
req.Header.Set("X-Conversation-ID", sessionID)
}
return req, nil
}
// Do sends the request and returns the response. Non-2xx responses are
// turned into an error carrying the body so callers surface vendor messages.
func (e Endpoint) Do(req *http.Request) (*http.Response, error) {
resp, err := e.httpClient().Do(req)
if err != nil {
return nil, &TransportError{Op: "send request", Err: err}
}
if resp.StatusCode < http.StatusOK || resp.StatusCode >= http.StatusMultipleChoices {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
_ = resp.Body.Close()
return nil, &HTTPError{StatusCode: resp.StatusCode, Body: string(body), Header: resp.Header}
}
return resp, nil
}
// PostJSON sends one authenticated JSON request and decodes the reply into
// out. It is the whole round-trip for the non-streaming protocols (rerank,
// embeddings), which have no SSE to assemble.
//
// It never returns a nil error with nothing decoded: every failure path —
// marshalling, SSRF, transport, non-2xx, decoding — returns an error, so a
// caller cannot mistake an empty result for a successful empty answer.
func (e Endpoint) PostJSON(ctx context.Context, url string, body, out any) error {
req, _, err := e.NewRequest(ctx, url, body, false)
if err != nil {
return err
}
// No LogRequest here: the chat protocols log their own bodies because a
// prompt is what an operator debugs, while a rerank body is a query plus
// every candidate chunk. The rerank layer logs a truncated line at Debug
// instead, so this would have duplicated it at Info.
return e.roundTrip(req, out)
}
// roundTrip sends a prepared request and decodes a 2xx reply into out.
func (e Endpoint) roundTrip(req *http.Request, out any) error {
resp, err := e.Do(req)
if err != nil {
return err
}
defer func() { _ = resp.Body.Close() }()
raw, err := ReadResponseCapped(resp.Body, 0)
if err != nil {
// A body over the cap is the vendor answering with something we cannot
// use, not the network failing. withRetry retries only TransportError,
// and repeating an oversized reply would bill the request again for the
// same bytes, so it is returned as-is.
if errors.Is(err, ErrResponseTooLarge) {
return err
}
// The connection broke before the reply arrived whole: nothing was
// received, so this is the network failing, not the vendor answering.
return &TransportError{Op: "read response", Err: err}
}
if out == nil {
return nil
}
if err := json.Unmarshal(raw, out); err != nil {
return fmt.Errorf("decode response: %w", err)
}
return nil
}
// TransportError is a request that never got a whole answer: DNS, connect,
// TLS, a reset or a timeout, while sending or while reading the reply. It is
// the only failure worth sending again.
type TransportError struct {
// Op is the phase that failed: "send request" or "read response".
Op string
Err error
}
func (e *TransportError) Error() string { return e.Op + ": " + e.Err.Error() }
func (e *TransportError) Unwrap() error { return e.Err }
// HTTPError is a non-2xx vendor reply.
type HTTPError struct {
StatusCode int
Body string
// Header is the reply's headers, kept so a retry can honour the vendor's
// Retry-After on a 429 or 503 instead of guessing its own backoff.
Header http.Header
}
func (e *HTTPError) Error() string {
return fmt.Sprintf("API request failed with status %d: %s", e.StatusCode, e.Body)
}
// RetryAfter is how long the vendor asked the caller to wait before trying
// again, from the Retry-After header in either of its two forms (delay in
// seconds or an HTTP date). It is zero when the header is absent, malformed
// or already in the past.
func (e *HTTPError) RetryAfter() time.Duration {
if e == nil {
return 0
}
return parseRetryAfter(e.Header.Get("Retry-After"), time.Now())
}
func parseRetryAfter(value string, now time.Time) time.Duration {
value = strings.TrimSpace(value)
if value == "" {
return 0
}
if secs, err := strconv.Atoi(value); err == nil {
if secs <= 0 {
return 0
}
return time.Duration(secs) * time.Second
}
if at, err := http.ParseTime(value); err == nil {
if d := at.Sub(now); d > 0 {
return d
}
}
return 0
}
// LogRequest emits the standard request log line with image payloads
// compacted so data URIs do not flood the log.
func LogRequest(ctx context.Context, url, model string, body []byte, stream bool) {
pretty := body
var buf bytes.Buffer
if err := json.Indent(&buf, body, "", " "); err == nil {
pretty = buf.Bytes()
}
logger.Infof(ctx, "[LLM Request] endpoint=%s, model=%s, stream=%v, request:\n%s",
url, model, stream, secutils.CompactImageDataURLForLog(string(pretty)))
}
+89
View File
@@ -0,0 +1,89 @@
package api
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/require"
)
func TestEndpointRequestIdentity(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
// One endpoint is shared by different sessions. Static model headers must
// neither merge them nor leak one session into a call without a session.
ep := Endpoint{
Auth: BearerAuth("test-key"),
Headers: map[string]string{
"X-Conversation-ID": "static-id", "User-Agent": "custom-client",
"X-Custom": "preserved",
},
}
for _, sessionID := range []string{"session-a", "session-b", ""} {
t.Run("session="+sessionID, func(t *testing.T) {
ctx := types.WithSessionID(context.Background(), sessionID)
for _, stream := range []bool{false, true} {
req, _, err := ep.NewRequest(ctx, "http://127.0.0.1/v1/chat/completions", map[string]any{}, stream)
require.NoError(t, err)
require.Equal(t, sessionID, req.Header.Get("X-Conversation-ID"))
require.Equal(t, "Academy", req.UserAgent())
require.Equal(t, "preserved", req.Header.Get("X-Custom"))
require.Equal(t, "Bearer test-key", req.Header.Get("Authorization"))
if sessionID == "" {
require.NotContains(t, req.Header, "X-Conversation-Id")
}
}
require.Equal(t, "static-id", ep.Headers["X-Conversation-ID"])
})
}
}
func TestDoKeepsHeadersOnHTTPError(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Retry-After", "12")
w.WriteHeader(http.StatusTooManyRequests)
_, _ = w.Write([]byte(`{"error":"rate limited"}`))
}))
defer srv.Close()
req, err := http.NewRequestWithContext(context.Background(), http.MethodPost, srv.URL, nil)
require.NoError(t, err)
_, err = Endpoint{Client: srv.Client()}.Do(req)
var httpErr *HTTPError
require.True(t, errors.As(err, &httpErr))
require.Equal(t, http.StatusTooManyRequests, httpErr.StatusCode)
require.Equal(t, 12*time.Second, httpErr.RetryAfter())
}
func TestParseRetryAfter(t *testing.T) {
now := time.Date(2026, 9, 26, 12, 0, 0, 0, time.UTC)
for _, tc := range []struct {
name string
value string
want time.Duration
}{
{"absent", "", 0},
{"seconds", "30", 30 * time.Second},
{"seconds with spaces", " 5 ", 5 * time.Second},
{"zero", "0", 0},
{"negative", "-3", 0},
{"http date", now.Add(90 * time.Second).Format(http.TimeFormat), 90 * time.Second},
{"http date in the past", now.Add(-time.Minute).Format(http.TimeFormat), 0},
{"garbage", "tomorrow", 0},
} {
t.Run(tc.name, func(t *testing.T) {
require.Equal(t, tc.want, parseRetryAfter(tc.value, now))
})
}
}
func TestRetryAfterOnNilError(t *testing.T) {
var e *HTTPError
require.Zero(t, e.RetryAfter())
require.Zero(t, (&HTTPError{StatusCode: 503}).RetryAfter())
}
@@ -0,0 +1,163 @@
// Package googleembeddings implements Gemini's batchEmbedContents: one POST
// carrying a request per text, answering embeddings[].values in order.
//
// Three facts shape it. The per-request `model` must be the fully qualified
// `models/{id}`, not the bare id the URL already carries. The per-request
// options — `taskType`, `outputDimensionality` — belong inside
// `embedContentConfig`; the reference marks the same names at the top level
// of the request "Deprecated: Please use EmbedContentConfig…". And
// `taskType` exists on gemini-embedding-001 but not on gemini-embedding-2,
// which takes its task instruction in the prompt instead — so the field is
// declared per model rather than for the vendor.
//
// Each text is its own request with a single part: gemini-embedding-2 fuses
// the parts of one Content into one vector.
//
// https://ai.google.dev/api/embeddings
package googleembeddings
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
Dimensions int
Retry api.RetryPolicy
}
// Client talks batchEmbedContents to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const method = ":batchEmbedContents"
// configField holds the per-request options.
const configField = "embedContentConfig"
// qualifiedModel is the `models/{id}` form the per-request model field needs.
func (c *Client) qualifiedModel() string {
return "models/" + strings.TrimPrefix(c.cfg.Endpoint.Model, "models/")
}
// openAIFacade is the sub-path of the same API version that serves the
// OpenAI-compatible surface. Rows that chat through it carry it in their base
// URL; the native method lives one level up.
const openAIFacade = "/openai"
// url is {base}/models/{id}:batchEmbedContents.
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
endpoint := c.cfg.Endpoint
endpoint.BaseURL = strings.TrimSuffix(strings.TrimRight(endpoint.BaseURL, "/"), openAIFacade)
return endpoint.Resolve("/" + c.qualifiedModel() + method)
}
type response struct {
Embeddings []struct {
Values []float32 `json:"values"`
} `json:"embeddings"`
Error *struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {
parts := make([]any, 0, len(texts))
for _, text := range texts {
parts = append(parts, map[string]any{"text": text})
}
return c.body(parts, kind)
}
// BuildImageRequestBody is the golden-test entry point for images: an image
// is an inlineData part carrying its MIME type and base64 bytes.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, kind api.EmbedInputType) map[string]any {
parts := make([]any, 0, len(images))
for _, img := range images {
parts = append(parts, map[string]any{
"inlineData": map[string]any{"mimeType": img.MIMEType, "data": img.Base64()},
})
}
return c.body(parts, kind)
}
// body wraps every part in its own request, so each gets its own vector.
func (c *Client) body(parts []any, kind api.EmbedInputType) map[string]any {
s := c.cfg.Settings
requests := make([]any, 0, len(parts))
for _, part := range parts {
req := map[string]any{
"model": c.qualifiedModel(),
"content": map[string]any{"parts": []any{part}},
}
config := map[string]any{}
if field := s.InputTypeField; field != "" {
config[field] = s.InputTypeValue(kind)
}
if s.DimensionsField != "" && c.cfg.Dimensions > 0 {
config[s.DimensionsField] = c.cfg.Dimensions
}
if len(config) > 0 {
req[configField] = config
}
requests = append(requests, req)
}
body := map[string]any{"requests": requests}
for k, v := range s.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one batch. The reply carries no index: embeddings come
// back positionally, one per request, so a short reply is an error rather
// than a partially filled result.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))
}
// AcceptsImages is always true: inlineData is part of the schema.
func (c *Client) AcceptsImages() bool { return true }
// EmbedImages vectorizes one batch of images, each its own vector.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {
var decoded response
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("gemini embedding error: %s", decoded.Error.Message)
}
if len(decoded.Embeddings) != want {
return nil, fmt.Errorf(
"gemini returned %d embeddings for %d inputs", len(decoded.Embeddings), want)
}
return api.PlaceEmbeddings(want, len(decoded.Embeddings), func(i int) (int, []float32) {
return i, decoded.Embeddings[i].Values
})
}
@@ -0,0 +1,100 @@
package googleembeddings
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the batchEmbedContents response shape:
// https://ai.google.dev/api/embeddings — embeddings[].values, positional.
const documentedResponse = `{"embeddings":[{"values":[0.1,0.2]},{"values":[0.3,0.4]}]}`
var retrievalTasks = map[string]string{"document": "RETRIEVAL_DOCUMENT", "query": "RETRIEVAL_QUERY"}
func newClient(url, model string, settings api.EmbeddingsSettings, dims int) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: model, Auth: api.HeaderAuth("x-goog-api-key", "k")},
Settings: settings,
Dimensions: dims,
})
}
// gemini-embedding-001 takes taskType, and each request's model must be the
// fully qualified models/{id}.
func TestRequestBodyForATaskTypeModel(t *testing.T) {
c := newClient("https://generativelanguage.googleapis.com/v1beta", "gemini-embedding-001",
api.EmbeddingsSettings{
InputTypeField: "taskType", InputTypeValues: retrievalTasks,
DimensionsField: "outputDimensionality",
}, 768)
// The options sit in embedContentConfig: the same names at the top level
// of the request are marked deprecated in the reference.
body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.Equal(t, map[string]any{"requests": []any{map[string]any{
"model": "models/gemini-embedding-001",
"content": map[string]any{"parts": []any{map[string]any{"text": "a"}}},
"embedContentConfig": map[string]any{
"taskType": "RETRIEVAL_DOCUMENT",
"outputDimensionality": 768,
},
}}}, body)
q := c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["requests"].([]any)[0].(map[string]any)
assert.Equal(t, "RETRIEVAL_QUERY", q["embedContentConfig"].(map[string]any)["taskType"])
}
// gemini-embedding-2 does not support task_type: its reference says to put
// the task instruction in the text instead. Sending the field anyway is an
// undocumented parameter, so a model that declares none sends none.
func TestNoTaskTypeWhereTheModelHasNone(t *testing.T) {
c := newClient("https://generativelanguage.googleapis.com/v1beta", "gemini-embedding-2",
api.EmbeddingsSettings{}, 0)
req := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)["requests"].([]any)[0].(map[string]any)
assert.NotContains(t, req, "embedContentConfig", "no option declared, so no config object")
assert.NotContains(t, req, "taskType")
}
func TestPostsToTheModelsMethod(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
// An id stored with the prefix must not become models/models/…
c := newClient(server.URL+"/v1beta", "models/gemini-embedding-001", api.EmbeddingsSettings{}, 0)
got, err := c.Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{0.1, 0.2}, {0.3, 0.4}}, got)
assert.Equal(t, "/v1beta/models/gemini-embedding-001:batchEmbedContents", path)
// A row that chats through the OpenAI-compatible facade stores
// .../v1beta/openai; its embeddings still go to the native method.
c = newClient(server.URL+"/v1beta/openai/", "gemini-embedding-001", api.EmbeddingsSettings{}, 0)
_, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, "/v1beta/models/gemini-embedding-001:batchEmbedContents", path)
}
// The reply is positional with no index, so a short one cannot be mapped back.
func TestShortReplyIsAnError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"embeddings":[{"values":[0.1]}]}`))
}))
defer server.Close()
_, err := newClient(server.URL+"/v1beta", "gemini-embedding-001", api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "1 embeddings for 2 inputs")
}
+430
View File
@@ -0,0 +1,430 @@
package googlegenai
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/types"
)
const (
methodGenerate = "generateContent"
methodStreamGenerate = "streamGenerateContent"
)
// Client talks generateContent to one endpoint.
type Client struct {
cfg Config
}
// New creates a client. The endpoint must already carry auth and headers.
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 }
// requestURL builds {base}/models/{model}:generateContent or
// {base}/models/{model}:streamGenerateContent?alt=sse. A bare host base URL
// gets Settings.APIVersionPrefix appended; an already versioned base is used
// as-is. An explicit Endpoint.URL overrides the path entirely.
func (c *Client) requestURL(stream bool) string {
ep := c.cfg.Endpoint
if ep.URL == "" {
base := strings.TrimRight(ep.BaseURL, "/")
if prefix := strings.Trim(c.cfg.Settings.APIVersionPrefix, "/"); prefix != "" && isBareHost(base) {
base += "/" + prefix
}
method := methodGenerate
if stream {
method = methodStreamGenerate
}
ep.URL = fmt.Sprintf("%s/models/%s:%s", base, ep.Model, method)
} else if stream && strings.HasSuffix(ep.URL, ":"+methodGenerate) {
// A vendor-supplied full URL names the non-streaming method; adding
// alt=sse to it would still return one buffered JSON document.
ep.URL = strings.TrimSuffix(ep.URL, ":"+methodGenerate) + ":" + methodStreamGenerate
}
if stream {
query := make(map[string]string, len(ep.Query)+1)
for k, v := range ep.Query {
query[k] = v
}
query["alt"] = "sse"
ep.Query = query
}
return ep.Resolve("")
}
func isBareHost(base string) bool {
u, err := url.Parse(base)
if err != nil {
return !strings.Contains(strings.TrimPrefix(strings.TrimPrefix(base, "https://"), "http://"), "/")
}
return u.Path == "" || u.Path == "/"
}
func (c *Client) send(
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
) (*http.Response, []byte, error) {
body, err := c.BuildRequestBody(messages, opts, stream)
if err != nil {
return nil, nil, err
}
target := c.requestURL(stream)
req, data, err := c.cfg.Endpoint.NewRequest(ctx, target, body, stream)
if err != nil {
return nil, nil, err
}
api.LogRequest(ctx, target, c.cfg.Endpoint.Model, data, stream)
resp, err := c.cfg.Endpoint.Do(req)
if err != nil {
return nil, data, err
}
return resp, data, nil
}
// Chat performs a non-streaming generation.
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 {
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, fmt.Errorf("create chat completion: %w", err)
}
}
defer func() { _ = resp.Body.Close() }()
raw, err := api.ReadResponseCapped(resp.Body, 0)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
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 generation over SSE.
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, data, 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, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
}
if err != nil {
cancel()
return nil, fmt.Errorf("create chat completion stream: %w", err)
}
}
ch := make(chan types.StreamResponse)
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
if dumper != nil {
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
}
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
}
// --- response decoding ---
type rawFunctionCall struct {
ID string `json:"id,omitempty"`
Name string `json:"name"`
Args json.RawMessage `json:"args,omitempty"`
}
type rawPart struct {
Text string `json:"text,omitempty"`
Thought bool `json:"thought,omitempty"`
ThoughtSignature string `json:"thoughtSignature,omitempty"`
FunctionCall *rawFunctionCall `json:"functionCall,omitempty"`
}
type rawCandidate struct {
Content struct {
Role string `json:"role,omitempty"`
Parts []rawPart `json:"parts,omitempty"`
} `json:"content"`
FinishReason string `json:"finishReason,omitempty"`
}
type rawUsage struct {
PromptTokenCount int `json:"promptTokenCount"`
CandidatesTokenCount int `json:"candidatesTokenCount"`
ThoughtsTokenCount int `json:"thoughtsTokenCount"`
TotalTokenCount int `json:"totalTokenCount"`
CachedContentTokenCount *int `json:"cachedContentTokenCount"`
}
type rawResponse struct {
Candidates []rawCandidate `json:"candidates,omitempty"`
PromptFeedback *struct {
BlockReason string `json:"blockReason,omitempty"`
} `json:"promptFeedback,omitempty"`
UsageMetadata *rawUsage `json:"usageMetadata,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
Status string `json:"status"`
} `json:"error,omitempty"`
}
func (c *Client) usage(u rawUsage) types.TokenUsage {
out := types.TokenUsage{
PromptTokens: u.PromptTokenCount,
CompletionTokens: u.CandidatesTokenCount + u.ThoughtsTokenCount,
TotalTokens: u.TotalTokenCount,
}
if out.TotalTokens == 0 {
out.TotalTokens = out.PromptTokens + out.CompletionTokens
}
switch {
case u.CachedContentTokenCount != nil:
cached := *u.CachedContentTokenCount
out.SetPromptCacheUsage(cached, 0, max(0, u.PromptTokenCount-cached), true)
case c.cfg.Settings.PromptCacheAcct:
out.SetPromptCacheUsage(0, 0, 0, false)
default:
out.MarkPromptCacheUnsupported()
}
return out
}
// toolCall lifts a functionCall part into the neutral tool call, minting an
// id when the vendor sent none and keeping the thought signature as
// provider metadata so it can be replayed verbatim.
func (c *Client) toolCall(p rawPart) types.LLMToolCall {
fc := p.FunctionCall
id := fc.ID
if id == "" {
id = newCallID()
}
args := "{}"
if len(fc.Args) > 0 && string(fc.Args) != "null" {
args = string(fc.Args)
}
call := types.LLMToolCall{
ID: id,
Type: "function",
Function: types.FunctionCall{Name: fc.Name, Arguments: args},
}
if p.ThoughtSignature != "" {
sig, _ := json.Marshal(p.ThoughtSignature)
call.ProviderMetadata = types.ToolCallMetadata{metadataThoughtSignature: sig}
}
return call
}
func newCallID() string {
var b [6]byte
if _, err := rand.Read(b[:]); err != nil {
return "call_000000000000"
}
return "call_" + hex.EncodeToString(b[:])
}
// mapFinishReason maps Gemini finish reasons onto the OpenAI vocabulary the
// rest of the system understands.
func mapFinishReason(reason string, hasToolCalls bool) string {
switch reason {
case "":
return ""
case "STOP":
if hasToolCalls {
return "tool_calls"
}
return "stop"
case "MAX_TOKENS":
return "length"
case "SAFETY", "RECITATION", "LANGUAGE", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII",
"IMAGE_SAFETY", "IMAGE_PROHIBITED_CONTENT", "IMAGE_RECITATION":
return "content_filter"
default:
return strings.ToLower(reason)
}
}
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
var env rawResponse
if err := json.Unmarshal(raw, &env); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if env.Error != nil && env.Error.Message != "" {
return nil, fmt.Errorf("API error: %s", env.Error.Message)
}
if len(env.Candidates) == 0 {
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
return nil, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason)
}
return nil, fmt.Errorf("no response from API")
}
cand := env.Candidates[0]
result := &types.ChatResponse{}
var content, reasoning strings.Builder
for _, p := range cand.Content.Parts {
if p.ThoughtSignature != "" {
result.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
}
switch {
case p.FunctionCall != nil:
result.ToolCalls = append(result.ToolCalls, c.toolCall(p))
case p.Thought:
reasoning.WriteString(p.Text)
default:
content.WriteString(p.Text)
}
}
result.Content = content.String()
result.ReasoningContent = reasoning.String()
result.FinishReason = mapFinishReason(cand.FinishReason, len(result.ToolCalls) > 0)
// Classify the cache status even without usageMetadata: an empty
// CacheStatus is indistinguishable from a miss downstream.
usage := rawUsage{}
if env.UsageMetadata != nil {
usage = *env.UsageMetadata
}
result.Usage = c.usage(usage)
return result, nil
}
// processStream decodes the alt=sse stream: every data line carries a full
// GenerateContentResponse chunk. Function calls arrive complete in one part;
// they are fed to the assembler as a name delta followed by an arguments
// delta so the early ResponseTypeToolCall notification fires as it does for
// the fragment-based protocols.
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)
reader := api.NewSSEReader(body)
toolIndex := 0
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 {
assembler.EndAtEOF(ch)
} else {
assembler.Fail(ch, err)
}
return
}
if event == nil {
continue
}
if event.Done {
assembler.End(ch)
return
}
if len(event.Data) == 0 {
continue
}
if dumper != nil {
raw := make([]byte, len(event.Data))
copy(raw, event.Data)
dumper.WritePacketRaw(raw)
}
var env rawResponse
if err := json.Unmarshal(event.Data, &env); err != nil {
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
return
}
if env.Error != nil && env.Error.Message != "" {
assembler.Fail(ch, fmt.Errorf("API stream error: %s", env.Error.Message))
return
}
if env.UsageMetadata != nil {
assembler.SetUsage(c.usage(*env.UsageMetadata))
}
if len(env.Candidates) == 0 {
if env.PromptFeedback != nil && env.PromptFeedback.BlockReason != "" {
assembler.Fail(ch, fmt.Errorf("blocked: %s", env.PromptFeedback.BlockReason))
return
}
continue
}
cand := env.Candidates[0]
var delta api.Delta
var calls []rawPart
for _, p := range cand.Content.Parts {
if p.ThoughtSignature != "" {
assembler.ReasoningSignature = api.TagSignature(api.APIGoogleGenerativeAI, p.ThoughtSignature)
}
switch {
case p.FunctionCall != nil:
calls = append(calls, p)
case p.Thought:
delta.Reasoning += p.Text
default:
delta.Content += p.Text
}
}
if delta.Reasoning != "" || delta.Content != "" {
assembler.Process(ch, delta)
}
for _, p := range calls {
call := c.toolCall(p)
idx := toolIndex
toolIndex++
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: idx, ID: call.ID, Type: call.Type, Name: call.Function.Name,
}}})
if len(call.ProviderMetadata) > 0 {
assembler.SetToolCallMetadata(idx, call.ProviderMetadata)
}
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: idx, Arguments: call.Function.Arguments,
}}})
}
if cand.FinishReason != "" {
assembler.Process(ch, api.Delta{FinishReason: mapFinishReason(cand.FinishReason, toolIndex > 0)})
}
}
}
@@ -0,0 +1,762 @@
package googlegenai
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"reflect"
"strings"
"testing"
"academy/internal/models/api"
"academy/internal/types"
)
func newTestClient(t *testing.T, baseURL string, mutate func(*Config)) *Client {
t.Helper()
cfg := Config{
Endpoint: api.Endpoint{
BaseURL: baseURL,
Model: "gemini-2.5-pro",
ModelID: "model-123",
Auth: api.HeaderAuth("x-goog-api-key", "test-key"),
},
Settings: api.DefaultGoogleGenerativeAI(),
Reasoning: true,
}
if mutate != nil {
mutate(&cfg)
}
return New(cfg)
}
// normalize round-trips a body through JSON so typed slices and ints compare
// equal to a parsed expectation.
func normalize(t *testing.T, v any) any {
t.Helper()
data, err := json.Marshal(v)
if err != nil {
t.Fatalf("marshal: %v", err)
}
var out any
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("unmarshal: %v", err)
}
return out
}
func parseJSON(t *testing.T, s string) any {
t.Helper()
var out any
if err := json.Unmarshal([]byte(s), &out); err != nil {
t.Fatalf("parse expected json: %v", err)
}
return out
}
func goldenMessages() []api.Message {
return []api.Message{
{Role: "system", Content: "You are helpful."},
{Role: "user", MultiContent: []api.MessageContentPart{
{Type: "image_url", ImageURL: &api.ImageURL{URL: "data:image/png;base64,AAAA"}},
{Type: "text", Text: "What is this?"},
}},
{Role: "assistant", ReasoningContent: "never replayed", ToolCalls: []api.ToolCall{
{
ID: "call_1",
Type: "function",
Function: api.FunctionCall{
Name: "get_weather",
Arguments: `{"city":"Paris"}`,
},
ProviderMetadata: types.ToolCallMetadata{"thought_signature": json.RawMessage(`"sig-1"`)},
},
{ID: "call_2", Type: "function", Function: api.FunctionCall{Name: "get_time", Arguments: ""}},
}},
{Role: "tool", ToolCallID: "call_1", Content: `{"temp": 20}`},
{Role: "tool", ToolCallID: "call_2", Name: "get_time", Content: "noon"},
}
}
func goldenOptions() *api.Options {
return &api.Options{
Temperature: 0.7,
MaxTokens: 1024,
ReasoningEffort: api.ReasoningHigh,
ToolChoice: "auto",
Tools: []api.Tool{
{Type: "function", Function: api.FunctionDef{
Name: "get_weather",
Description: "Weather",
Parameters: json.RawMessage(`{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"title": "Weather",
"additionalProperties": false,
"properties": {
"city": {"type": "string", "default": "Paris", "examples": ["Paris"]},
"title": {"type": "string", "description": "a property named title"}
},
"required": ["city"]
}`),
}},
{Type: "function", Function: api.FunctionDef{Name: "get_time", Description: "Time"}},
},
}
}
const goldenBase = `{
"systemInstruction": {"parts": [{"text": "You are helpful."}]},
"contents": [
{"role": "user", "parts": [
{"inlineData": {"mimeType": "image/png", "data": "AAAA"}},
{"text": "What is this?"}
]},
{"role": "model", "parts": [
{"functionCall": {"id": "call_1", "name": "get_weather", "args": {"city": "Paris"}}, "thoughtSignature": "sig-1"},
{"functionCall": {"id": "call_2", "name": "get_time", "args": {}}}
]},
{"role": "user", "parts": [
{"functionResponse": {"id": "call_1", "name": "get_weather", "response": {"result": {"temp": 20}}}},
{"functionResponse": {"id": "call_2", "name": "get_time", "response": {"result": "noon"}}}
]}
],
"tools": [{"functionDeclarations": [
{"name": "get_weather", "description": "Weather", "parameters": {
"type": "object",
"properties": {
"city": {"type": "string"},
"title": {"type": "string", "description": "a property named title"}
},
"required": ["city"]
}},
{"name": "get_time", "description": "Time"}
]}],
"toolConfig": {"functionCallingConfig": {"mode": "AUTO"}},
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1024,
"thinkingConfig": THINKING
}
}`
// TestThinkingConfigOmittedForNonReasoningModels guards models the catalog
// does not mark as reasoning (gemini-2.0-flash, Gemma): they may reject any
// thinkingConfig, including the thinkingBudget 0 an agent's default "off" maps to.
func TestThinkingConfigOmittedForNonReasoningModels(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com",
func(c *Config) { c.Reasoning = false })
off := false
body, err := client.BuildRequestBody(
[]api.Message{{Role: "user", Content: "hi"}}, &api.Options{Thinking: &off}, false)
if err != nil {
t.Fatal(err)
}
if gc, ok := body["generationConfig"].(map[string]any); ok {
if _, has := gc["thinkingConfig"]; has {
t.Fatalf("thinkingConfig sent for a non-reasoning model: %v", gc)
}
}
}
// TestForeignSignatureNotReplayed guards cross-provider replay: a signature
// issued by another protocol must never reach Gemini as thoughtSignature.
func TestForeignSignatureNotReplayed(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
body, err := client.BuildRequestBody([]api.Message{
{Role: "user", Content: "hi"},
{
Role: "assistant", Content: "ok",
ReasoningSignature: api.TagSignature(api.APIAnthropicMessages, "claude-sig"),
},
{Role: "user", Content: "again"},
}, nil, false)
if err != nil {
t.Fatal(err)
}
data, _ := json.Marshal(body)
if strings.Contains(string(data), "claude-sig") {
t.Fatalf("foreign signature replayed: %s", data)
}
}
func TestBuildRequestBodyGolden(t *testing.T) {
cases := []struct {
name string
mutate func(*Config)
thinking string
}{
{
name: "budget mode",
thinking: `{"thinkingBudget": 24576, "includeThoughts": true}`,
},
{
name: "level mode",
mutate: func(c *Config) {
c.Settings.ThinkingMode = api.GoogleThinkingLevel
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningHigh: api.StringPtr("high")}
},
thinking: `{"thinkingLevel": "high", "includeThoughts": true}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
body, err := client.BuildRequestBody(goldenMessages(), goldenOptions(), false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
expected := parseJSON(t, replaceThinking(goldenBase, tc.thinking))
got := normalize(t, body)
if !reflect.DeepEqual(got, expected) {
gotJSON, _ := json.MarshalIndent(got, "", " ")
wantJSON, _ := json.MarshalIndent(expected, "", " ")
t.Fatalf("body mismatch\n got: %s\nwant: %s", gotJSON, wantJSON)
}
})
}
}
func replaceThinking(tmpl, thinking string) string {
return strings.Replace(tmpl, "THINKING", thinking, 1)
}
func TestThinkingConfigVariants(t *testing.T) {
cases := []struct {
name string
mutate func(*Config)
opts *api.Options
want string // "" means no thinkingConfig
}{
{name: "not requested", opts: &api.Options{}, want: ""},
{
name: "budget off supported", opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: `{"thinkingBudget": 0}`,
},
{
name: "budget off unsupported",
mutate: func(c *Config) { c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: nil} },
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: "",
},
{
name: "budget auto", opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
want: `{"thinkingBudget": -1, "includeThoughts": true}`,
},
{
name: "budget explicit tokens",
opts: &api.Options{ReasoningEffort: api.ReasoningLow, ThinkingBudgetTokens: 512},
want: `{"thinkingBudget": 512, "includeThoughts": true}`,
},
{
name: "mode none",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingNone },
opts: &api.Options{ReasoningEffort: api.ReasoningHigh},
want: "",
},
{
name: "level off unmapped",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingLevel },
opts: &api.Options{ReasoningEffort: api.ReasoningOff},
want: "",
},
{
name: "level auto",
mutate: func(c *Config) { c.Settings.ThinkingMode = api.GoogleThinkingLevel },
opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
want: `{"includeThoughts": true}`,
},
{
name: "level clamps unsupported rung",
mutate: func(c *Config) {
c.Settings.ThinkingMode = api.GoogleThinkingLevel
c.ThinkingLevels = api.ThinkingLevelMap{
api.ReasoningMedium: nil,
api.ReasoningHigh: api.StringPtr("high"),
}
},
opts: &api.Options{ReasoningEffort: api.ReasoningMedium},
want: `{"thinkingLevel": "high", "includeThoughts": true}`,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", tc.mutate)
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, tc.opts, false)
if err != nil {
t.Fatal(err)
}
var got any
if gen, ok := body["generationConfig"].(map[string]any); ok {
if tcfg, ok := gen["thinkingConfig"]; ok {
got = normalize(t, tcfg)
}
}
var want any
if tc.want != "" {
want = parseJSON(t, tc.want)
}
if !reflect.DeepEqual(got, want) {
t.Fatalf("thinkingConfig = %v, want %v", got, want)
}
})
}
}
func TestToolChoiceAndFormat(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
opts := &api.Options{
ToolChoice: "get_weather",
Tools: []api.Tool{{Function: api.FunctionDef{Name: "get_weather"}}},
Format: json.RawMessage(`{"type":"object"}`),
}
body, err := client.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, opts, false)
if err != nil {
t.Fatal(err)
}
got := normalize(t, body["toolConfig"])
want := parseJSON(t, `{"functionCallingConfig": {"mode": "ANY", "allowedFunctionNames": ["get_weather"]}}`)
if !reflect.DeepEqual(got, want) {
t.Fatalf("toolConfig = %v, want %v", got, want)
}
gen := body["generationConfig"].(map[string]any)
if gen["responseMimeType"] != "application/json" {
t.Fatalf("responseMimeType = %v", gen["responseMimeType"])
}
contents := body["contents"].([]map[string]any)
text := contents[0]["parts"].([]part)[0]["text"].(string)
if text != "hi\nUse this JSON schema: {\"type\":\"object\"}" {
t.Fatalf("schema hint not appended: %q", text)
}
}
func TestRequestURL(t *testing.T) {
cases := []struct {
name string
base string
stream bool
want string
}{
{
"bare host non-stream", "https://generativelanguage.googleapis.com", false,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:generateContent",
},
{
"bare host trailing slash stream", "https://generativelanguage.googleapis.com/", true,
"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
},
{
"versioned base non-stream", "https://proxy.example.com/gemini/v1beta", false,
"https://proxy.example.com/gemini/v1beta/models/gemini-2.5-pro:generateContent",
},
{
"versioned base stream", "https://proxy.example.com/v1beta/", true,
"https://proxy.example.com/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
client := newTestClient(t, tc.base, nil)
if got := client.requestURL(tc.stream); got != tc.want {
t.Fatalf("requestURL = %q, want %q", got, tc.want)
}
})
}
t.Run("explicit URL override", func(t *testing.T) {
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
c.Endpoint.URL = "https://custom.example.com/route:generateContent"
})
if got := client.requestURL(false); got != "https://custom.example.com/route:generateContent" {
t.Fatalf("requestURL = %q", got)
}
// A streaming call must name the streaming method: ":generateContent"
// answers with one buffered JSON document even with alt=sse, which the
// SSE reader would see as an empty stream.
want := "https://custom.example.com/route:streamGenerateContent?alt=sse"
if got := client.requestURL(true); got != want {
t.Fatalf("requestURL = %q, want %q", got, want)
}
})
t.Run("explicit URL override without a known method is left alone", func(t *testing.T) {
client := newTestClient(t, "https://ignored.example.com", func(c *Config) {
c.Endpoint.URL = "https://custom.example.com/route"
})
if got := client.requestURL(true); got != "https://custom.example.com/route?alt=sse" {
t.Fatalf("requestURL = %q", got)
}
})
}
func TestChatDecodesResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath, gotQuery, gotKey string
var gotBody map[string]any
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotQuery = r.URL.RawQuery
gotKey = r.Header.Get("x-goog-api-key")
raw, _ := io.ReadAll(r.Body)
_ = json.Unmarshal(raw, &gotBody)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"candidates": [{
"content": {"role": "model", "parts": [
{"text": "Thinking about Paris.", "thought": true, "thoughtSignature": "sig-thought"},
{"text": "Let me check."},
{"functionCall": {"id": "fc-1", "name": "get_weather", "args": {"city": "Paris"}},
"thoughtSignature": "sig-fc"}
]},
"finishReason": "STOP"
}],
"usageMetadata": {"promptTokenCount": 10, "candidatesTokenCount": 5, "thoughtsTokenCount": 3,
"totalTokenCount": 18, "cachedContentTokenCount": 4}
}`))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
if err != nil {
t.Fatalf("Chat: %v", err)
}
if gotPath != "/v1beta/models/gemini-2.5-pro:generateContent" || gotQuery != "" {
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
}
if gotKey != "test-key" {
t.Fatalf("x-goog-api-key = %q", gotKey)
}
if _, ok := gotBody["contents"]; !ok {
t.Fatalf("request body missing contents: %v", gotBody)
}
if resp.Content != "Let me check." {
t.Fatalf("Content = %q", resp.Content)
}
if resp.ReasoningContent != "Thinking about Paris." {
t.Fatalf("ReasoningContent = %q", resp.ReasoningContent)
}
if resp.ReasoningSignature != "google-generative-ai:sig-fc" {
t.Fatalf("ReasoningSignature = %q", resp.ReasoningSignature)
}
if resp.FinishReason != "tool_calls" {
t.Fatalf("FinishReason = %q", resp.FinishReason)
}
if len(resp.ToolCalls) != 1 {
t.Fatalf("ToolCalls = %+v", resp.ToolCalls)
}
tc := resp.ToolCalls[0]
if tc.ID != "fc-1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
tc.Function.Arguments != `{"city": "Paris"}` {
t.Fatalf("tool call = %+v", tc)
}
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-fc"` {
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
}
u := resp.Usage
if u.PromptTokens != 10 || u.CompletionTokens != 8 || u.TotalTokens != 18 {
t.Fatalf("usage = %+v", u)
}
if u.CacheReadTokens != 4 || u.CacheMissTokens != 6 || !u.CacheReported ||
u.CacheStatus != types.PromptCacheStatusHit {
t.Fatalf("cache usage = %+v", u)
}
}
func TestChatErrors(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
cases := []struct {
name string
body string
want string
}{
{
"error payload", `{"error": {"code": 400, "message": "bad request", "status": "INVALID_ARGUMENT"}}`,
"API error: bad request",
},
{"blocked prompt", `{"promptFeedback": {"blockReason": "SAFETY"}}`, "blocked: SAFETY"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.body))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
_, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err == nil || err.Error() != tc.want {
t.Fatalf("err = %v, want %q", err, tc.want)
}
})
}
}
func TestChatStreamDecodesSSE(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath, gotQuery string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotQuery = r.URL.RawQuery
w.Header().Set("Content-Type", "text/event-stream")
chunks := []string{
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Let me think.","thought":true}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"text":"Checking "}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"text":"weather."}]}}]}`,
`{"candidates":[{"content":{"role":"model","parts":[{"functionCall":{"name":"get_weather",` +
`"args":{"city":"Paris"}},"thoughtSignature":"sig-stream"}]},"finishReason":"STOP"}],` +
`"usageMetadata":{"promptTokenCount":10,"candidatesTokenCount":5,"thoughtsTokenCount":3,` +
`"totalTokenCount":18}}`,
}
for _, c := range chunks {
_, _ = w.Write([]byte("data: " + c + "\n\n"))
}
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(),
[]api.Message{{Role: "user", Content: "weather?"}}, &api.Options{})
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var events []types.StreamResponse
for ev := range ch {
events = append(events, ev)
}
if gotPath != "/v1beta/models/gemini-2.5-pro:streamGenerateContent" || gotQuery != "alt=sse" {
t.Fatalf("request path = %q query = %q", gotPath, gotQuery)
}
if len(events) == 0 {
t.Fatal("no events")
}
firstThinking, firstAnswer, toolCallEvent := -1, -1, -1
var thinking, answer string
for i, ev := range events {
switch ev.ResponseType {
case types.ResponseTypeThinking:
if !ev.Done {
if firstThinking < 0 {
firstThinking = i
}
thinking += ev.Content
}
case types.ResponseTypeAnswer:
if ev.Content != "" {
if firstAnswer < 0 {
firstAnswer = i
}
answer += ev.Content
}
case types.ResponseTypeToolCall:
if toolCallEvent < 0 {
toolCallEvent = i
}
if ev.Data["tool_name"] != "get_weather" || ev.Data["tool_call_id"] == "" {
t.Fatalf("tool_call event data = %v", ev.Data)
}
case types.ResponseTypeError:
t.Fatalf("stream error: %s", ev.Content)
}
}
if firstThinking < 0 || firstAnswer < 0 || firstThinking > firstAnswer {
t.Fatalf("thinking (%d) must precede answer (%d)", firstThinking, firstAnswer)
}
if thinking != "Let me think." || answer != "Checking weather." {
t.Fatalf("thinking = %q answer = %q", thinking, answer)
}
if toolCallEvent < 0 {
t.Fatal("no ResponseTypeToolCall event")
}
final := events[len(events)-1]
if final.ResponseType != types.ResponseTypeAnswer || !final.Done {
t.Fatalf("final event = %+v", final)
}
if final.FinishReason != "tool_calls" {
t.Fatalf("final FinishReason = %q", final.FinishReason)
}
if final.Usage == nil || final.Usage.PromptTokens != 10 || final.Usage.CompletionTokens != 8 ||
final.Usage.TotalTokens != 18 {
t.Fatalf("final usage = %+v", final.Usage)
}
if final.Usage.CacheStatus != types.PromptCacheStatusUnreported || final.Usage.CacheReported {
t.Fatalf("cache status = %+v", final.Usage)
}
if len(final.ToolCalls) != 1 {
t.Fatalf("final tool calls = %+v", final.ToolCalls)
}
tc := final.ToolCalls[0]
if tc.Function.Name != "get_weather" || tc.Function.Arguments != `{"city":"Paris"}` || tc.Type != "function" {
t.Fatalf("tool call = %+v", tc)
}
if len(tc.ID) != len("call_")+12 || tc.ID[:5] != "call_" {
t.Fatalf("generated tool call id = %q", tc.ID)
}
if string(tc.ProviderMetadata["thought_signature"]) != `"sig-stream"` {
t.Fatalf("thought_signature = %s", tc.ProviderMetadata["thought_signature"])
}
if final.Data["reasoning_signature"] != "google-generative-ai:sig-stream" {
t.Fatalf("Data = %v", final.Data)
}
}
func TestChatStreamErrorPayload(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("data: {\"error\": {\"code\": 429, \"message\": \"quota exceeded\"}}\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatal(err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeError || last.Content != "API stream error: quota exceeded" {
t.Fatalf("last event = %+v", last)
}
}
// "contents" is required and must be an array. A request that produced no
// turns (only system prompts) used to marshal a nil slice as null, which
// generateContent rejects with 400.
func TestBuildRequestBodyContentsNeverNull(t *testing.T) {
client := newTestClient(t, "https://generativelanguage.googleapis.com", nil)
for _, msgs := range [][]api.Message{nil, {{Role: "system", Content: "be brief"}}} {
body, err := client.BuildRequestBody(msgs, nil, false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
data, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal: %v", err)
}
if strings.Contains(string(data), `"contents":null`) {
t.Fatalf("contents marshalled as null: %s", data)
}
if !strings.Contains(string(data), `"contents":[]`) {
t.Fatalf("contents not an empty array: %s", data)
}
}
}
// Without usageMetadata the cache status must still be classified, otherwise
// "the vendor reported nothing" is indistinguishable from a real miss on the
// usage dashboards.
func TestChatClassifiesCacheStatusWithoutUsageMetadata(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"candidates":[{"content":{"role":"model","parts":[{"text":"hi"}]},` +
`"finishReason":"STOP"}]}`))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
resp, err := client.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("Chat: %v", err)
}
if resp.Usage.CacheStatus == "" {
t.Fatal("CacheStatus is empty; the usage block must still be classified")
}
}
// A chunk that blocks the prompt mid-stream must surface as an error rather
// than being skipped as "no candidates".
func TestChatStreamSurfacesPromptFeedbackBlock(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: {\"promptFeedback\":{\"blockReason\":\"SAFETY\"}}\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var sawError bool
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
sawError = true
if !strings.Contains(chunk.Content, "SAFETY") {
t.Fatalf("error chunk = %q, want the block reason", chunk.Content)
}
}
}
if !sawError {
t.Fatal("blocked prompt did not produce an error chunk")
}
}
// Gemini streams end on EOF; the last candidate of a finished message carries
// a finishReason, so a body that stops without one was cut mid-answer.
func TestChatStreamEOFWithoutFinishReasonIsIncomplete(t *testing.T) {
for _, tc := range []struct {
name, body, want string
}{
{"cut off", `{"candidates":[{"content":{"parts":[{"text":"Hel"}]}}]}`, types.FinishReasonIncomplete},
{"finished", `{"candidates":[{"content":{"parts":[{"text":"Hello"}]},"finishReason":"STOP"}]}`, "stop"},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte("data: " + tc.body + "\n\n"))
}))
defer srv.Close()
client := newTestClient(t, srv.URL, nil)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatal(err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeAnswer || !last.Done || last.FinishReason != tc.want {
t.Fatalf("last event = %+v, want finish reason %q", last, tc.want)
}
})
}
}
func TestMapFinishReason(t *testing.T) {
tests := []struct {
reason string
hasToolCalls bool
want string
}{
{"", false, ""},
{"STOP", false, "stop"},
{"STOP", true, "tool_calls"},
{"MAX_TOKENS", false, "length"},
{"SAFETY", false, "content_filter"},
{"RECITATION", false, "content_filter"},
{"LANGUAGE", false, "content_filter"},
{"BLOCKLIST", false, "content_filter"},
{"PROHIBITED_CONTENT", false, "content_filter"},
{"SPII", false, "content_filter"},
{"IMAGE_SAFETY", false, "content_filter"},
{"IMAGE_PROHIBITED_CONTENT", false, "content_filter"},
{"IMAGE_RECITATION", false, "content_filter"},
{"OTHER", false, "other"},
{"MALFORMED_FUNCTION_CALL", false, "malformed_function_call"},
}
for _, tt := range tests {
t.Run(tt.reason, func(t *testing.T) {
if got := mapFinishReason(tt.reason, tt.hasToolCalls); got != tt.want {
t.Fatalf("mapFinishReason(%q, %v) = %q, want %q", tt.reason, tt.hasToolCalls, got, tt.want)
}
})
}
}
+528
View File
@@ -0,0 +1,528 @@
// Package googlegenai implements the native Google Gemini generateContent
// wire protocol (https://ai.google.dev/api/generate-content). Every
// model-specific deviation is driven by api.GoogleGenerativeAISettings;
// this package contains no vendor names beyond the protocol itself.
package googlegenai
import (
"encoding/base64"
"encoding/json"
"fmt"
"mime"
"net/url"
"path"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.GoogleGenerativeAISettings
// ThinkingLevels maps neutral levels to the vendor vocabulary
// (thinkingLevel values for Gemini 3, "off" support for budget models).
ThinkingLevels api.ThinkingLevelMap
// Reasoning marks a reasoning model. The Gemini protocol has no
// role selection to gate on it; the field is informational and mirrors
// the other protocol configs.
Reasoning bool
}
const (
roleUser = "user"
roleModel = "model"
// metadataThoughtSignature is the ToolCallMetadata key under which a
// function call's thoughtSignature round-trips. Gemini 3 rejects a
// replayed function call whose signature is missing or altered.
metadataThoughtSignature = "thought_signature"
defaultImageMIME = "image/jpeg"
)
type part = map[string]any
// convertMessages splits neutral messages into the system instruction text
// and the Gemini contents array. Consecutive tool results are merged into one
// user content carrying several functionResponse parts, as Gemini requires
// every functionCall of a model turn to be answered in the next content.
func (c *Client) convertMessages(messages []api.Message) (system []string, contents []map[string]any) {
toolNames := map[string]string{}
openToolBatch := -1 // index in contents of the functionResponse content being filled
for _, msg := range messages {
msg = api.NeutralizeMessageSpecialTokens(msg)
switch msg.Role {
case "system":
if text := systemText(msg); text != "" {
system = append(system, text)
}
case "assistant":
for _, tc := range msg.ToolCalls {
if tc.ID != "" {
toolNames[tc.ID] = tc.Function.Name
}
}
contents = append(contents, map[string]any{"role": roleModel, "parts": assistantParts(msg)})
case "tool":
p := toolResultPart(msg, toolNames)
if openToolBatch >= 0 && openToolBatch == len(contents)-1 {
batch := contents[openToolBatch]
batch["parts"] = append(batch["parts"].([]part), p)
continue
}
contents = append(contents, map[string]any{"role": roleUser, "parts": []part{p}})
openToolBatch = len(contents) - 1
default:
contents = append(contents, map[string]any{"role": roleUser, "parts": userParts(msg)})
}
}
return system, contents
}
func systemText(msg api.Message) string {
if len(msg.MultiContent) == 0 {
return msg.Content
}
var texts []string
for _, p := range msg.MultiContent {
if p.Type == "text" && p.Text != "" {
texts = append(texts, p.Text)
}
}
return strings.Join(texts, "\n")
}
// userParts renders a user turn. Legacy Message.Images are emitted before the
// text part, matching the Chat Completions package.
func userParts(msg api.Message) []part {
var parts []part
switch {
case len(msg.MultiContent) > 0:
for _, p := range msg.MultiContent {
switch p.Type {
case "text":
if p.Text != "" {
parts = append(parts, part{"text": p.Text})
}
case "image_url":
if p.ImageURL != nil {
if ip := imagePart(p.ImageURL.URL); ip != nil {
parts = append(parts, ip)
}
}
}
}
case len(msg.Images) > 0:
for _, img := range msg.Images {
if ip := imagePart(img); ip != nil {
parts = append(parts, ip)
}
}
parts = append(parts, part{"text": msg.Content})
}
if len(parts) == 0 {
parts = append(parts, part{"text": msg.Content})
}
return parts
}
// assistantParts renders a model turn: the answer text (carrying the thought
// signature when the turn had no function calls) followed by one functionCall
// part per tool call, each replaying its own thought signature. Reasoning
// text is never replayed as a thought part: Gemini only needs signatures.
func assistantParts(msg api.Message) []part {
var parts []part
if msg.Content != "" || len(msg.ToolCalls) == 0 {
p := part{"text": msg.Content}
sig := api.SignatureFor(api.APIGoogleGenerativeAI, msg.ReasoningSignature)
if sig != "" && len(msg.ToolCalls) == 0 {
p["thoughtSignature"] = sig
}
parts = append(parts, p)
}
for _, tc := range msg.ToolCalls {
fc := map[string]any{
"name": tc.Function.Name,
"args": parseArgs(tc.Function.Arguments),
}
if tc.ID != "" {
fc["id"] = tc.ID
}
p := part{"functionCall": fc}
if sig := thoughtSignatureFromMetadata(tc.ProviderMetadata); sig != "" {
p["thoughtSignature"] = sig
}
parts = append(parts, p)
}
return parts
}
// toolResultPart renders a tool result as a functionResponse part. The tool
// name comes from the message or, failing that, from the assistant turn that
// issued the call.
func toolResultPart(msg api.Message, toolNames map[string]string) part {
name := msg.Name
if name == "" {
name = toolNames[msg.ToolCallID]
}
fr := map[string]any{
"name": name,
"response": map[string]any{"result": decodeToolResult(msg.Content)},
}
if msg.ToolCallID != "" {
fr["id"] = msg.ToolCallID
}
return part{"functionResponse": fr}
}
// decodeToolResult returns the tool output as a JSON value when it is a JSON
// object or array, otherwise the raw string.
func decodeToolResult(content string) any {
trimmed := strings.TrimSpace(content)
if strings.HasPrefix(trimmed, "{") || strings.HasPrefix(trimmed, "[") {
var v any
if err := json.Unmarshal([]byte(trimmed), &v); err == nil {
return v
}
}
return content
}
// parseArgs decodes a tool call's JSON arguments into the object Gemini
// expects; anything that is not a JSON object becomes an empty object.
func parseArgs(arguments string) map[string]any {
args := map[string]any{}
if strings.TrimSpace(arguments) == "" {
return args
}
if err := json.Unmarshal([]byte(arguments), &args); err != nil || args == nil {
return map[string]any{}
}
return args
}
func thoughtSignatureFromMetadata(md map[string]json.RawMessage) string {
raw, ok := md[metadataThoughtSignature]
if !ok || len(raw) == 0 {
return ""
}
var sig string
if err := json.Unmarshal(raw, &sig); err != nil {
return ""
}
return sig
}
// imagePart renders an image reference. Stored images are resolved to data
// URIs first; data URIs become inlineData, everything else is passed as
// fileData with a MIME type guessed from the extension.
func imagePart(ref string) part {
resolved := api.ResolveImageURLForLLM(ref)
if strings.HasPrefix(resolved, "data:") {
mimeType, data, ok := parseDataURI(resolved)
if !ok {
return nil
}
return part{"inlineData": map[string]any{"mimeType": mimeType, "data": data}}
}
return part{"fileData": map[string]any{"mimeType": guessImageMIME(resolved), "fileUri": resolved}}
}
// parseDataURI splits "data:<mime>[;base64],<payload>" into the MIME type and
// the base64 payload Gemini wants. Non-base64 payloads are re-encoded.
func parseDataURI(uri string) (mimeType, data string, ok bool) {
comma := strings.Index(uri, ",")
if comma < 0 {
return "", "", false
}
header := uri[len("data:"):comma]
payload := uri[comma+1:]
isBase64 := false
if strings.HasSuffix(header, ";base64") {
header = strings.TrimSuffix(header, ";base64")
isBase64 = true
}
mimeType = header
if idx := strings.Index(mimeType, ";"); idx >= 0 {
mimeType = mimeType[:idx]
}
if mimeType == "" {
mimeType = defaultImageMIME
}
if isBase64 {
return mimeType, payload, true
}
decoded, err := url.PathUnescape(payload)
if err != nil {
decoded = payload
}
return mimeType, base64.StdEncoding.EncodeToString([]byte(decoded)), true
}
func guessImageMIME(ref string) string {
ext := path.Ext(ref)
if u, err := url.Parse(ref); err == nil && u.Path != "" {
ext = path.Ext(u.Path)
}
if ext != "" {
if mt := mime.TypeByExtension(strings.ToLower(ext)); strings.HasPrefix(mt, "image/") {
return mt
}
}
return defaultImageMIME
}
// buildBody assembles the generateContent request body. The body is the
// same for streaming and non-streaming calls; streaming is selected by the
// URL. It returns nested maps so golden tests can inspect it.
func (c *Client) buildBody(messages []api.Message, opts *api.Options) (map[string]any, error) {
s := c.cfg.Settings
system, contents := c.convertMessages(messages)
if contents == nil {
// "contents" is required and must be an array: a nil slice marshals to
// null and generateContent answers 400. A request carrying only system
// messages legitimately produces no turns.
contents = []map[string]any{}
}
// Gemini has no in-sequence instruction role; the envelope identifies
// this trailing input as runtime context, rather than new user intent.
if opts != nil && opts.RuntimeNotice != "" {
contents = append(contents, map[string]any{"role": roleUser, "parts": []part{{"text": opts.RuntimeNotice}}})
}
body := map[string]any{"contents": contents}
if len(system) > 0 {
body["systemInstruction"] = map[string]any{
"parts": []part{{"text": strings.Join(system, "\n\n")}},
}
}
gen := map[string]any{}
if opts != nil {
c.applySampling(gen, opts)
if budget := opts.CompletionBudget(); budget > 0 {
gen["maxOutputTokens"] = budget
}
c.applyTools(body, opts)
if len(opts.Format) > 0 {
gen["responseMimeType"] = "application/json"
appendSchemaHint(contents, opts.Format)
}
if tc := c.thinkingConfig(opts); tc != nil {
gen["thinkingConfig"] = tc
}
}
for k, v := range s.ExtraGeneration {
if _, exists := gen[k]; !exists {
gen[k] = v
}
}
if len(gen) > 0 {
body["generationConfig"] = gen
}
return body, nil
}
func (c *Client) applySampling(gen map[string]any, opts *api.Options) {
s := c.cfg.Settings
if opts.Temperature > 0 {
gen["temperature"] = opts.Temperature
}
if opts.TopP > 0 {
gen["topP"] = opts.TopP
}
if opts.Seed > 0 && s.SupportsSeed {
gen["seed"] = opts.Seed
}
if s.SupportsPenalty {
if opts.FrequencyPenalty > 0 {
gen["frequencyPenalty"] = opts.FrequencyPenalty
}
if opts.PresencePenalty > 0 {
gen["presencePenalty"] = opts.PresencePenalty
}
}
}
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
if len(opts.Tools) == 0 {
return
}
decls := make([]map[string]any, 0, len(opts.Tools))
for _, tool := range opts.Tools {
decl := map[string]any{
"name": tool.Function.Name,
"description": tool.Function.Description,
}
if schema := sanitizeParameters(tool.Function.Parameters); schema != nil {
decl["parameters"] = schema
}
decls = append(decls, decl)
}
body["tools"] = []map[string]any{{"functionDeclarations": decls}}
if opts.ToolChoice == "" {
return
}
cfg := map[string]any{}
switch opts.ToolChoice {
case "auto":
cfg["mode"] = "AUTO"
case "required":
cfg["mode"] = "ANY"
case "none":
cfg["mode"] = "NONE"
default:
cfg["mode"] = "ANY"
cfg["allowedFunctionNames"] = []string{opts.ToolChoice}
}
body["toolConfig"] = map[string]any{"functionCallingConfig": cfg}
}
// unsupportedSchemaKeys are JSON Schema members the Gemini Schema type
// rejects. They are stripped recursively; property names are never touched.
var unsupportedSchemaKeys = map[string]bool{
"$schema": true,
"$id": true,
"$ref": true,
"$defs": true,
"definitions": true,
"additionalProperties": true,
"default": true,
"examples": true,
"title": true,
}
// sanitizeParameters decodes a tool's JSON schema and strips the members
// Gemini does not accept. Empty or undecodable schemas yield nil.
func sanitizeParameters(raw json.RawMessage) any {
if len(raw) == 0 || string(raw) == "null" {
return nil
}
var schema any
if err := json.Unmarshal(raw, &schema); err != nil {
return nil
}
if _, ok := schema.(map[string]any); !ok {
return nil
}
return sanitizeSchema(schema)
}
func sanitizeSchema(v any) any {
switch t := v.(type) {
case map[string]any:
out := make(map[string]any, len(t))
for k, val := range t {
if unsupportedSchemaKeys[k] {
continue
}
if k == "properties" {
if props, ok := val.(map[string]any); ok {
cleaned := make(map[string]any, len(props))
for name, sub := range props {
cleaned[name] = sanitizeSchema(sub)
}
out[k] = cleaned
continue
}
}
out[k] = sanitizeSchema(val)
}
return out
case []any:
for i := range t {
t[i] = sanitizeSchema(t[i])
}
return t
}
return v
}
// appendSchemaHint appends the JSON schema instruction to the last user text
// part, mirroring the Chat Completions package.
func appendSchemaHint(contents []map[string]any, format json.RawMessage) {
hint := fmt.Sprintf("\nUse this JSON schema: %s", format)
for i := len(contents) - 1; i >= 0; i-- {
if contents[i]["role"] != roleUser {
continue
}
parts, _ := contents[i]["parts"].([]part)
for j := len(parts) - 1; j >= 0; j-- {
if text, ok := parts[j]["text"].(string); ok {
parts[j]["text"] = text + hint
return
}
}
contents[i]["parts"] = append(parts, part{"text": strings.TrimPrefix(hint, "\n")})
return
}
}
// thinkingConfig encodes the requested reasoning level in the shape the
// model generation supports: thinkingBudget (Gemini 2.5) or thinkingLevel
// (Gemini 3). nil means "send no thinkingConfig".
func (c *Client) thinkingConfig(opts *api.Options) map[string]any {
s := c.cfg.Settings
levels := c.cfg.ThinkingLevels
level, requested := opts.Reasoning()
// Models the catalog does not mark as reasoning (gemini-2.0-flash, Gemma,
// unknown ids) may reject thinkingConfig outright, so send none.
if !requested || !c.cfg.Reasoning {
return nil
}
mode := s.ThinkingMode
if mode == "" {
mode = api.GoogleThinkingBudget
}
switch mode {
case api.GoogleThinkingBudget:
switch level {
case api.ReasoningOff:
if levels.Supports(api.ReasoningOff) {
return map[string]any{"thinkingBudget": 0}
}
return nil
case api.ReasoningAuto:
return map[string]any{"thinkingBudget": -1, "includeThoughts": s.IncludeThoughts}
default:
level = levels.Clamp(level)
budget := opts.ThinkingBudgetTokens
if budget <= 0 {
if b, ok := s.ThinkingBudgets[level]; ok && level.Graded() {
budget = b
} else {
budget = -1
}
}
return map[string]any{"thinkingBudget": budget, "includeThoughts": s.IncludeThoughts}
}
case api.GoogleThinkingLevel:
switch level {
case api.ReasoningOff:
// Gemini 3 cannot switch thinking off; only send a level when the
// vendor explicitly mapped "off" to a wire value.
if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
return map[string]any{"thinkingLevel": *v}
}
return nil
case api.ReasoningAuto:
return map[string]any{"includeThoughts": s.IncludeThoughts}
default:
level = levels.Clamp(level)
if !level.Graded() {
return map[string]any{"includeThoughts": s.IncludeThoughts}
}
return map[string]any{"thinkingLevel": levels.Value(level), "includeThoughts": s.IncludeThoughts}
}
}
return nil
}
// BuildRequestBody is the golden-test entry point: it returns the exact
// JSON object that would be sent for the given inputs. The stream flag is
// accepted for interface parity; Gemini selects streaming through the URL.
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
_ = stream
return c.buildBody(messages, opts)
}
+50
View File
@@ -0,0 +1,50 @@
package api
import (
"fmt"
"slices"
)
// ImageInput is how an endpoint takes images, shared by the embedding and
// rerank settings. Its fields are flattened into both, so the compat keys
// read the same on either: image_field, max_image_batch_size,
// max_image_bytes and image_mime_types.
type ImageInput struct {
// ImageField is the key of the object that carries an image on a shape
// with no standard image input ("image" on Jina). Protocols whose schema
// fixes the image part ignore it.
ImageField string `json:",omitempty"`
// MaxImageBatchSize is the documented number of images per request.
// 0 means one: a vendor that fuses its inputs, or does not say, must not
// be sent several.
MaxImageBatchSize int `json:",omitempty"`
// MaxImageBytes is the documented size limit of one image, 0 when the
// vendor states none. The caller shrinks an image to fit; the client
// refuses one that does not rather than spend a request on it.
MaxImageBytes int `json:",omitempty"`
// ImageMIMETypes lists the formats the vendor documents, empty when it
// takes any common one.
ImageMIMETypes []string `json:",omitempty"`
}
// ImageBatchLimit is the number of images one request may carry.
func (s ImageInput) ImageBatchLimit() int {
if s.MaxImageBatchSize > 0 {
return s.MaxImageBatchSize
}
return 1
}
// CheckImage reports an image the vendor documents it will not take.
func (s ImageInput) CheckImage(img EmbedImage) error {
if len(img.Data) == 0 {
return fmt.Errorf("image is empty")
}
if s.MaxImageBytes > 0 && len(img.Data) > s.MaxImageBytes {
return fmt.Errorf("image is %d bytes; the limit is %d", len(img.Data), s.MaxImageBytes)
}
if len(s.ImageMIMETypes) > 0 && !slices.Contains(s.ImageMIMETypes, img.MIMEType) {
return fmt.Errorf("image type %q is not one of %v", img.MIMEType, s.ImageMIMETypes)
}
return nil
}
+164
View File
@@ -0,0 +1,164 @@
package api
import (
"encoding/base64"
"errors"
"fmt"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"academy/internal/types"
)
// ResolveImageURLForLLM converts stored image paths to a format that LLM APIs can consume.
// - data: URIs and http(s):// URLs are returned as-is.
// - resource:// references and provider:// paths are read through the
// application resolver and converted to base64 data URIs.
func ResolveImageURLForLLM(imageURL string) string {
if strings.HasPrefix(imageURL, "data:") ||
strings.HasPrefix(imageURL, "http://") ||
strings.HasPrefix(imageURL, "https://") {
return imageURL
}
if isApplicationStoredImage(imageURL) {
data := readLocalStorageBytes(imageURL)
if data != nil {
mime := http.DetectContentType(data)
return fmt.Sprintf("data:%s;base64,%s", mime, base64.StdEncoding.EncodeToString(data))
}
}
return imageURL
}
// ResolveImageURLForOllama converts stored image paths to raw bytes for the Ollama API.
func ResolveImageURLForOllama(imageURL string) []byte {
if strings.HasPrefix(imageURL, "data:") {
idx := strings.Index(imageURL, ";base64,")
if idx < 0 {
return nil
}
decoded, err := base64.StdEncoding.DecodeString(imageURL[idx+8:])
if err != nil {
return nil
}
return decoded
}
if isApplicationStoredImage(imageURL) {
return readLocalStorageBytes(imageURL)
}
return nil
}
// isApplicationStoredImage reports whether imageURL names an image the
// application's storage layer can read: a resource:// reference, or a
// provider:// URL in the scheme the storage backends write (local://,
// minio://, s3://, cos://, ...). The provider list is owned by
// types.ParseProviderScheme, so a backend added there is resolvable here too.
// Keeping a second, narrower list in this package left "minio://bucket/key"
// unrecognized and it reached the vendor verbatim.
func isApplicationStoredImage(imageURL string) bool {
return strings.HasPrefix(imageURL, "resource://") || types.ParseProviderScheme(imageURL) != ""
}
// LocalImageResolver resolves a resource:// or provider storage URL to bytes
// using the owning tenant's storage config. The application layer sets it at
// startup.
// Stored local:// URLs are relative to the storage base dir and do NOT encode
// the tenant's configured PathPrefix, so a plain env-based join would miss the
// prefix. When nil (e.g. in tests), callers fall back to the env-based
// LOCAL_STORAGE_BASE_DIR resolution below.
var LocalImageResolver func(storageURL string) ([]byte, bool)
// readLocalStorageBytes resolves a local:// storage path to disk bytes.
func readLocalStorageBytes(storagePath string) []byte {
if LocalImageResolver != nil {
if data, ok := LocalImageResolver(storagePath); ok {
return data
}
}
relPath := strings.TrimPrefix(storagePath, "local://")
baseDir := os.Getenv("LOCAL_STORAGE_BASE_DIR")
if baseDir == "" {
baseDir = "/data/files"
}
localPath := filepath.Join(baseDir, filepath.FromSlash(relPath))
data, err := os.ReadFile(localPath)
if err != nil {
log.Printf("[image-resolve] failed to read local file %s: %v", localPath, err)
return nil
}
return data
}
// IsMultimodalNotSupportedError checks if an error indicates the model does not
// support multimodal/image input.
//
// The status is read off the error, never matched as text: HTTPError.Error()
// prints "status 400" for every 400, and vendor bodies carry "400" inside
// unrelated numbers ("max 4000 px"), so a substring test turned any failure
// that merely mentions an image into a "model is not multimodal" verdict and
// silently retried it stripped.
func IsMultimodalNotSupportedError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
mentionsImages := strings.Contains(msg, "multimodal") ||
strings.Contains(msg, "image") ||
strings.Contains(msg, "vision")
if !mentionsImages {
return false
}
if strings.Contains(msg, "not support") || strings.Contains(msg, "unsupported") {
return true
}
// No explicit wording: only a genuine 400 (the status vendors use to reject
// an input their model cannot read) is worth a stripped retry.
var httpErr *HTTPError
return errors.As(err, &httpErr) && httpErr.StatusCode == http.StatusBadRequest
}
// StripImagesFromMessages returns a copy of messages with all image data removed.
//
// Images travel in two shapes: the Images list (chat history, Ollama) and
// image_url parts inside MultiContent, which is what the remote VLM path and
// every assembled multimodal turn actually send. Clearing only the first left
// the retry sending the identical request, so the "retry without images"
// fallback never recovered anything on those paths.
func StripImagesFromMessages(messages []Message) []Message {
cleaned := make([]Message, len(messages))
for i, msg := range messages {
cleaned[i] = msg
cleaned[i].Images = nil
cleaned[i].MultiContent = stripImageParts(msg.MultiContent)
}
return cleaned
}
// stripImageParts drops image parts from one MultiContent list, copying it
// only when there is something to drop so the caller's slice is never mutated.
// A list that was nothing but images becomes nil: the protocol packages then
// fall back to the message's plain Content instead of sending an empty parts
// array, which some vendors reject.
func stripImageParts(parts []MessageContentPart) []MessageContentPart {
if len(parts) == 0 {
return parts
}
kept := make([]MessageContentPart, 0, len(parts))
for _, part := range parts {
if part.Type == "image_url" || part.ImageURL != nil {
continue
}
kept = append(kept, part)
}
if len(kept) == len(parts) {
return parts
}
if len(kept) == 0 {
return nil
}
return kept
}
+183
View File
@@ -0,0 +1,183 @@
package api
import (
"bytes"
"fmt"
"strings"
"testing"
)
// The remote VLM path sends its pictures as image_url parts in MultiContent,
// not in Images, so a strip that only cleared Images re-sent the identical
// request and the "retry without images" fallback could never succeed.
func TestStripImagesFromMessages_RemovesMultiContentImageParts(t *testing.T) {
messages := []Message{{
Role: "user",
Images: []string{"data:image/png;base64,AAA"},
MultiContent: []MessageContentPart{
{Type: "text", Text: "describe this"},
{Type: "image_url", ImageURL: &ImageURL{URL: "data:image/png;base64,AAA"}},
},
}}
cleaned := StripImagesFromMessages(messages)
if cleaned[0].Images != nil {
t.Errorf("Images = %v, want nil", cleaned[0].Images)
}
if len(cleaned[0].MultiContent) != 1 || cleaned[0].MultiContent[0].Type != "text" {
t.Fatalf("MultiContent = %#v, want the text part only", cleaned[0].MultiContent)
}
// The caller's slice must survive: the retry is built from the same
// messages the first attempt used.
if len(messages[0].MultiContent) != 2 || len(messages[0].Images) != 1 {
t.Fatalf("input mutated: %#v", messages[0])
}
}
// An images-only turn loses MultiContent entirely rather than going out as an
// empty parts array, which some vendors reject.
func TestStripImagesFromMessages_DropsEmptiedMultiContent(t *testing.T) {
cleaned := StripImagesFromMessages([]Message{{
Role: "user",
Content: "what is this",
MultiContent: []MessageContentPart{
{Type: "image_url", ImageURL: &ImageURL{URL: "https://example.com/a.png"}},
},
}})
if cleaned[0].MultiContent != nil {
t.Fatalf("MultiContent = %#v, want nil", cleaned[0].MultiContent)
}
if cleaned[0].Content != "what is this" {
t.Fatalf("Content = %q, want it untouched", cleaned[0].Content)
}
}
// A stored image is referenced by the scheme of the backend holding it: an
// object-storage FileService returns "minio://bucket/key", "s3://bucket/key"
// and so on, optionally wrapped as "storage://<backendID>/<provider>://...".
// The predicate has to recognize the storage layer's scheme table, otherwise
// the handle travels to the vendor verbatim: remote APIs got "minio://..." as
// the image URL and the Ollama path dropped the picture without a word.
func TestResolveImageURLForStoredImages(t *testing.T) {
pngBytes := []byte("\x89PNG\r\n\x1a\nstored image payload")
resolved := map[string]bool{}
originalResolver := LocalImageResolver
LocalImageResolver = func(storageURL string) ([]byte, bool) {
resolved[storageURL] = true
return pngBytes, true
}
t.Cleanup(func() { LocalImageResolver = originalResolver })
stored := []struct {
name string
url string
}{
{name: "local", url: "local://10000/1/img.png"},
{name: "minio", url: "minio://bucket/1/img.png"},
{name: "s3", url: "s3://bucket/1/img.png"},
{name: "cos", url: "cos://bucket/region/1/img.png"},
{name: "tos", url: "tos://bucket/1/img.png"},
{name: "oss", url: "oss://bucket/1/img.png"},
{name: "ks3", url: "ks3://bucket/1/img.png"},
{name: "resource reference", url: "resource://a1b2c3/1/img.png"},
{name: "backend-wrapped provider", url: "storage://backend-a/cos://bucket/region/1/img.png"},
}
for _, tc := range stored {
t.Run(tc.name, func(t *testing.T) {
got := ResolveImageURLForLLM(tc.url)
if !strings.HasPrefix(got, "data:image/png;base64,") {
t.Fatalf("ResolveImageURLForLLM(%q) = %q, want a base64 PNG data URI", tc.url, got)
}
if data := ResolveImageURLForOllama(tc.url); !bytes.Equal(data, pngBytes) {
t.Fatalf("ResolveImageURLForOllama(%q) = %q, want the stored bytes", tc.url, data)
}
if !resolved[tc.url] {
t.Errorf("resolver was never asked for %q", tc.url)
}
})
}
}
// A data: or http(s) URL is not application-stored: it must pass through
// untouched and must never be routed through the storage resolver.
func TestResolveImageURLForNonStoredURLs(t *testing.T) {
originalResolver := LocalImageResolver
LocalImageResolver = func(storageURL string) ([]byte, bool) {
t.Errorf("resolver called for non-stored URL %q", storageURL)
return nil, false
}
t.Cleanup(func() { LocalImageResolver = originalResolver })
const dataURI = "data:image/png;base64,cGF5bG9hZA=="
const remoteURL = "https://example.com/1/img.png"
for _, tc := range []struct {
name string
url string
wantOllama []byte
}{
{name: "data URI", url: dataURI, wantOllama: []byte("payload")},
{name: "http URL", url: remoteURL},
} {
t.Run(tc.name, func(t *testing.T) {
if got := ResolveImageURLForLLM(tc.url); got != tc.url {
t.Errorf("ResolveImageURLForLLM(%q) = %q, want it unchanged", tc.url, got)
}
if data := ResolveImageURLForOllama(tc.url); !bytes.Equal(data, tc.wantOllama) {
t.Errorf("ResolveImageURLForOllama(%q) = %q, want %q", tc.url, data, tc.wantOllama)
}
})
}
}
func TestIsMultimodalNotSupportedError(t *testing.T) {
cases := []struct {
name string
err error
want bool
}{
{
name: "explicit wording, no status",
err: fmt.Errorf("this model does not support image input"),
want: true,
},
{
name: "400 rejecting the image",
err: &HTTPError{StatusCode: 400, Body: `{"error":"invalid content type image_url"}`},
want: true,
},
{
name: "wrapped 400 still matches",
err: fmt.Errorf("create chat completion: %w",
&HTTPError{StatusCode: 400, Body: "image input rejected"}),
want: true,
},
{
// The old substring test fired here: HTTPError.Error() prints the
// status, so every 5xx mentioning an image looked like "model is
// not multimodal" and was retried stripped.
name: "server error mentioning an image is not a capability verdict",
err: &HTTPError{StatusCode: 500, Body: "image upload backend unavailable"},
want: false,
},
{
// "400" also hides inside ordinary numbers in vendor bodies.
name: "429 whose body merely contains 400",
err: &HTTPError{StatusCode: 429, Body: "image exceeds 4000 px, slow down"},
want: false,
},
{
name: "unrelated failure",
err: fmt.Errorf("context deadline exceeded"),
want: false,
},
{name: "nil", err: nil, want: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := IsMultimodalNotSupportedError(tc.err); got != tc.want {
t.Errorf("IsMultimodalNotSupportedError(%v) = %v, want %v", tc.err, got, tc.want)
}
})
}
}
+224
View File
@@ -0,0 +1,224 @@
package api
import (
"strings"
"unicode/utf8"
)
// JSONFieldExtractor extracts a specific string field value from streaming JSON fragments.
// It processes incremental JSON argument chunks from LLM tool calls.
//
// Example: for fieldName="answer", expected JSON format: {"answer":"...content..."}
// The extractor uses a simple state machine to skip the JSON prefix and extract the string value.
type JSONFieldExtractor struct {
fieldName string // the JSON field name to extract (e.g. "answer", "thought")
buffer string // accumulated full arguments string
valueStart int // byte offset where the field value starts (-1 if not found yet)
lastEmit int // byte offset of the last emitted position within the value
done bool // whether we've seen the closing quote
}
// NewJSONFieldExtractor creates a new extractor instance for the given field name
func NewJSONFieldExtractor(fieldName string) *JSONFieldExtractor {
return &JSONFieldExtractor{
fieldName: fieldName,
valueStart: -1,
lastEmit: 0,
}
}
// Feed processes a new argument delta and returns any new content to emit.
// Returns empty string if no new content is available yet.
func (e *JSONFieldExtractor) Feed(argsDelta string) string {
if e.done {
return ""
}
e.buffer += argsDelta
// If we haven't found the value start yet, try to find it
if e.valueStart < 0 {
idx := findFieldValueStart(e.buffer, e.fieldName)
if idx < 0 {
return "" // Haven't seen the value start yet
}
e.valueStart = idx
e.lastEmit = 0
}
// Extract new content from the value portion
valueContent := e.buffer[e.valueStart:]
// Find how far we can safely emit (stop before potential incomplete escape at the end)
safeEnd, finished := findSafeEnd(valueContent, e.lastEmit)
if safeEnd <= e.lastEmit {
if finished {
e.done = true
}
return ""
}
// Extract the new chunk and unescape JSON string escapes
rawChunk := valueContent[e.lastEmit:safeEnd]
unescaped := unescapeJSONString(rawChunk)
e.lastEmit = safeEnd
if finished {
e.done = true
}
return unescaped
}
// IsDone returns whether the extractor has finished (closing quote found)
func (e *JSONFieldExtractor) IsDone() bool {
return e.done
}
// findFieldValueStart finds the byte offset where the field's string value content begins
// (after the opening quote of the value). Returns -1 if not found.
func findFieldValueStart(buf string, fieldName string) int {
// Look for "fieldName" key followed by colon and opening quote
key := `"` + fieldName + `"`
idx := strings.Index(buf, key)
if idx < 0 {
return -1
}
// Skip past the key
pos := idx + len(key)
// Skip whitespace and colon
for pos < len(buf) {
ch := buf[pos]
if ch == ':' {
pos++
continue
}
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
pos++
continue
}
if ch == '"' {
// Found the opening quote of the value
return pos + 1
}
// Unexpected character
return -1
}
return -1 // Haven't seen the opening quote yet
}
// findSafeEnd finds the safe end position for emission within the value content.
// It scans from lastEmit forward, handling escape sequences.
// Returns (safeEnd, finished) where finished=true if the closing quote was found.
func findSafeEnd(value string, from int) (int, bool) {
i := from
for i < len(value) {
ch := value[i]
if ch == '\\' {
// Escape sequence - need at least 2 bytes
if i+1 >= len(value) {
// Incomplete escape at end, stop before it
return i, false
}
nextCh := value[i+1]
if nextCh == 'u' {
// Unicode escape \uXXXX - need 6 bytes total
if i+5 >= len(value) {
return i, false
}
i += 6
} else {
// Simple escape: \", \\, \n, \t, \r, \/, \b, \f
i += 2
}
} else if ch == '"' {
// Closing quote of the JSON string value
return i, true
} else {
// Regular character - handle multi-byte UTF-8
_, size := utf8.DecodeRuneInString(value[i:])
if size == 0 {
size = 1
}
i += size
}
}
return i, false
}
// unescapeJSONString converts JSON string escape sequences to their actual characters
func unescapeJSONString(s string) string {
if !strings.ContainsRune(s, '\\') {
return s
}
var b strings.Builder
b.Grow(len(s))
i := 0
for i < len(s) {
if s[i] == '\\' && i+1 < len(s) {
switch s[i+1] {
case '"':
b.WriteByte('"')
i += 2
case '\\':
b.WriteByte('\\')
i += 2
case '/':
b.WriteByte('/')
i += 2
case 'n':
b.WriteByte('\n')
i += 2
case 'r':
b.WriteByte('\r')
i += 2
case 't':
b.WriteByte('\t')
i += 2
case 'b':
b.WriteByte('\b')
i += 2
case 'f':
b.WriteByte('\f')
i += 2
case 'u':
// Unicode escape \uXXXX
if i+5 < len(s) {
// Parse hex digits
hexStr := s[i+2 : i+6]
var codepoint int
for _, h := range hexStr {
codepoint <<= 4
switch {
case h >= '0' && h <= '9':
codepoint += int(h - '0')
case h >= 'a' && h <= 'f':
codepoint += int(h-'a') + 10
case h >= 'A' && h <= 'F':
codepoint += int(h-'A') + 10
}
}
b.WriteRune(rune(codepoint))
i += 6
} else {
b.WriteByte(s[i])
i++
}
default:
b.WriteByte(s[i])
i++
}
} else {
b.WriteByte(s[i])
i++
}
}
return b.String()
}
@@ -0,0 +1,165 @@
package api
import (
"testing"
)
func TestJSONFieldExtractor_Basic(t *testing.T) {
e := NewJSONFieldExtractor("answer")
// Simulate streaming JSON: {"answer":"Hello world"}
got := ""
got += e.Feed(`{"answer":"`)
got += e.Feed(`Hello`)
got += e.Feed(` world`)
got += e.Feed(`"}`)
if got != "Hello world" {
t.Errorf("expected 'Hello world', got %q", got)
}
if !e.IsDone() {
t.Error("expected extractor to be done")
}
}
func TestJSONFieldExtractor_WithEscapes(t *testing.T) {
e := NewJSONFieldExtractor("answer")
// Simulate: {"answer":"line1\nline2 and \"quoted\""}
got := ""
got += e.Feed(`{"answer":"line1\nline2`)
got += e.Feed(` and \"quoted`)
got += e.Feed(`\""}`)
expected := "line1\nline2 and \"quoted\""
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
}
func TestJSONFieldExtractor_OneChunk(t *testing.T) {
e := NewJSONFieldExtractor("answer")
got := e.Feed(`{"answer":"complete answer here"}`)
if got != "complete answer here" {
t.Errorf("expected 'complete answer here', got %q", got)
}
if !e.IsDone() {
t.Error("expected extractor to be done")
}
}
func TestJSONFieldExtractor_SmallChunks(t *testing.T) {
e := NewJSONFieldExtractor("answer")
// Very small chunks
got := ""
chunks := []string{`{`, `"`, `a`, `n`, `s`, `w`, `e`, `r`, `"`, `:`, `"`, `H`, `i`, `"`, `}`}
for _, c := range chunks {
got += e.Feed(c)
}
if got != "Hi" {
t.Errorf("expected 'Hi', got %q", got)
}
}
func TestJSONFieldExtractor_Markdown(t *testing.T) {
e := NewJSONFieldExtractor("answer")
got := ""
got += e.Feed(`{"answer":"# Title\n\n`)
got += e.Feed(`This is **bold** and `)
got += e.Feed(`*italic* text.\n\n`)
got += e.Feed(`- item 1\n- item 2`)
got += e.Feed(`"}`)
expected := "# Title\n\nThis is **bold** and *italic* text.\n\n- item 1\n- item 2"
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
}
func TestJSONFieldExtractor_UnicodeEscape(t *testing.T) {
e := NewJSONFieldExtractor("answer")
got := ""
got += e.Feed(`{"answer":"Hello \u4e16\u754c`)
got += e.Feed(`"}`)
expected := "Hello 世界"
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
}
func TestJSONFieldExtractor_IncompleteEscapeAtBoundary(t *testing.T) {
e := NewJSONFieldExtractor("answer")
// Escape sequence split across chunks
got := ""
got += e.Feed(`{"answer":"before\`)
got += e.Feed(`nafter"}`)
expected := "before\nafter"
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
}
func TestJSONFieldExtractor_WhitespaceInJSON(t *testing.T) {
e := NewJSONFieldExtractor("answer")
// Whitespace around colon
got := e.Feed(`{ "answer" : "content here" }`)
if got != "content here" {
t.Errorf("expected 'content here', got %q", got)
}
}
func TestJSONFieldExtractor_EmptyAnswer(t *testing.T) {
e := NewJSONFieldExtractor("answer")
got := e.Feed(`{"answer":""}`)
if got != "" {
t.Errorf("expected empty string, got %q", got)
}
if !e.IsDone() {
t.Error("expected extractor to be done")
}
}
// Test extracting "thought" field (for thinking tool)
func TestJSONFieldExtractor_ThoughtField(t *testing.T) {
e := NewJSONFieldExtractor("thought")
got := ""
got += e.Feed(`{"thought":"Let me analyze`)
got += e.Feed(` the problem step by step`)
got += e.Feed(`","next_thought_needed":true,"thought_number":1,"total_thoughts":3}`)
expected := "Let me analyze the problem step by step"
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
if !e.IsDone() {
t.Error("expected extractor to be done")
}
}
func TestJSONFieldExtractor_ThoughtFieldWithEscapes(t *testing.T) {
e := NewJSONFieldExtractor("thought")
got := ""
got += e.Feed(`{"thought":"Step 1:\n- Analyze the query\n- `)
got += e.Feed(`Search for \"relevant\" info`)
got += e.Feed(`","thought_number":1}`)
expected := "Step 1:\n- Analyze the query\n- Search for \"relevant\" info"
if got != expected {
t.Errorf("expected %q, got %q", expected, got)
}
}
+76
View File
@@ -0,0 +1,76 @@
package api
import (
"bytes"
"context"
"fmt"
"mime/multipart"
"net/textproto"
"path/filepath"
"strings"
)
// FormField is one text part of a multipart form. Order is kept.
type FormField struct {
Name string
Value string
}
// FormFile is the file part of a multipart form.
type FormFile struct {
Field string
FileName string
Data []byte
}
// EncodeMultipart writes fields and one file into a multipart/form-data body
// and returns it with its Content-Type. It is encoded once: those bytes are
// what a signing vendor hashes and what every retry sends again.
//
// The file part carries a filename and no Content-Type of its own. Servers
// identify the format from the extension then — OpenAI asks for "an
// extension-bearing filename", and vox-box (GPUStack's audio backend) falls
// back to guessing from it — whereas a guessed type that a server does not
// list is rejected outright.
func EncodeMultipart(fields []FormField, file FormFile) ([]byte, string, error) {
var buf bytes.Buffer
w := multipart.NewWriter(&buf)
header := make(textproto.MIMEHeader)
header.Set("Content-Disposition", fmt.Sprintf(`form-data; name=%q; filename=%q`,
file.Field, filepath.Base(file.FileName)))
part, err := w.CreatePart(header)
if err != nil {
return nil, "", fmt.Errorf("encode form file: %w", err)
}
if _, err := part.Write(file.Data); err != nil {
return nil, "", fmt.Errorf("encode form file: %w", err)
}
for _, f := range fields {
if err := w.WriteField(f.Name, f.Value); err != nil {
return nil, "", fmt.Errorf("encode form field %s: %w", f.Name, err)
}
}
if err := w.Close(); err != nil {
return nil, "", fmt.Errorf("encode form: %w", err)
}
return buf.Bytes(), w.FormDataContentType(), nil
}
// PostMultipartWithRetry sends an encoded multipart body, retrying transport
// failures only, and decodes the JSON reply into out. It has the guarantees
// of PostJSONWithRetry.
func (e Endpoint) PostMultipartWithRetry(
ctx context.Context, url string, body []byte, contentType string,
out any, policy RetryPolicy, label string,
) error {
if !strings.HasPrefix(contentType, "multipart/") {
return fmt.Errorf("%s: not a multipart content type: %q", label, contentType)
}
return withRetry(ctx, policy, label, func() error {
req, err := e.newPost(ctx, url, body, contentType)
if err != nil {
return err
}
return e.roundTrip(req, out)
})
}
+158
View File
@@ -0,0 +1,158 @@
// Package nimrerank implements NVIDIA NIM's retrieval reranking shape: a
// query object, a passages array, and rankings carrying a logit.
//
// Two things separate it from the Cohere dialect and both matter to callers.
// The score is an unbounded log-odds value that is routinely negative, not a
// 0..1 relevance — api.RerankSettings.ScoreScale says so. And `truncate`
// defaults to "NONE", which means an over-long passage fails the request
// instead of being cut, so the vendor sets it explicitly.
//
// https://docs.api.nvidia.com/nim/reference/nvidia-llama-3_2-nv-rerankqa-1b-v2-infer
package nimrerank
import (
"context"
"encoding/json"
"fmt"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client talks NIM reranking to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
type text struct {
Text string `json:"text"`
}
type request struct {
Model string `json:"model"`
Query text `json:"query"`
Passages []text `json:"passages"`
Truncate string `json:"truncate,omitempty"`
}
type response struct {
Rankings []struct {
Index int `json:"index"`
Logit float64 `json:"logit"`
} `json:"rankings"`
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
passages := make([]text, len(documents))
for i := range documents {
passages[i] = text{Text: documents[i]}
}
body := request{
Model: c.cfg.Endpoint.Model,
Query: text{Text: query},
Passages: passages,
Truncate: c.cfg.Settings.Truncate,
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
return out, nil
}
// imagePassage is a passage that is an image. The VLM reranking reference:
// images "must be base64 data URLs, such as data:image/jpeg;base64,...",
// and "For image-only passages, omit text. Do not set text to an empty
// string." Text passages keep their own type, so their shape never changes.
type imagePassage struct {
Image string `json:"image"`
}
// BuildImageRequestBody is the golden-test entry point for image passages.
func (c *Client) BuildImageRequestBody(query string, images []api.EmbedImage) (map[string]any, error) {
passages := make([]imagePassage, len(images))
for i, img := range images {
passages[i] = imagePassage{Image: img.DataURI()}
}
body, err := c.BuildRequestBody(query, nil)
if err != nil {
return nil, err
}
body["passages"] = passages
return roundTrip(body)
}
// AcceptsImages is true: image passages are part of the NIM ranking schema.
// Only the VL models score them, which their catalog input says.
func (c *Client) AcceptsImages() bool { return true }
// Rerank scores documents against the query. The returned scores are logits;
// see the package comment.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
out, err := c.post(ctx, body, len(documents))
for i := range out {
out[i].Text = documents[out[i].Index]
}
return out, err
}
// RerankImages scores image passages against the query; indices refer to
// images.
func (c *Client) RerankImages(ctx context.Context, query string, images []api.EmbedImage) ([]api.RerankResult, error) {
body, err := c.BuildImageRequestBody(query, images)
if err != nil {
return nil, err
}
return c.post(ctx, body, len(images))
}
func (c *Client) post(ctx context.Context, body map[string]any, count int) ([]api.RerankResult, error) {
var decoded response
url := c.cfg.Endpoint.Resolve(c.cfg.Settings.Path)
if err := c.cfg.Endpoint.PostJSON(ctx, url, body, &decoded); err != nil {
return nil, err
}
out := make([]api.RerankResult, 0, len(decoded.Rankings))
for _, item := range decoded.Rankings {
if item.Index < 0 || item.Index >= count {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", item.Index, count)
}
out = append(out, api.RerankResult{Index: item.Index, Score: item.Logit})
}
return out, nil
}
// roundTrip renders a body through JSON, so golden tests compare plain maps.
func roundTrip(body map[string]any) (map[string]any, error) {
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
return out, nil
}
@@ -0,0 +1,127 @@
package nimrerank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// documentedResponse is the response example from NVIDIA's reranking
// reference, copied verbatim so the decoder is pinned against the vendor's
// own document rather than against our structs:
// https://docs.api.nvidia.com/nim/reference/nvidia-llama-3_2-nv-rerankqa-1b-v2-infer
//
// Note the negative logit. This protocol does not return a 0..1 relevance
// score, which is why api.RerankSettings.ScoreScale exists.
const documentedResponse = `{
"rankings": [
{"index": 2, "logit": 0.226318359375},
{"index": 1, "logit": -1.171875},
{"index": 0, "logit": -6.3125}
]
}`
func newClient(t *testing.T, url string, settings api.RerankSettings) *Client {
t.Helper()
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "nvidia/nv-rerankqa-mistral-4b-v3", Auth: api.BearerAuth("k")},
Settings: settings,
})
}
func TestRequestBodyMatchesTheDocumentedSchema(t *testing.T) {
c := newClient(t, "https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking",
api.RerankSettings{Truncate: "END", ScoreScale: api.ScoreLogit})
body, err := c.BuildRequestBody("q", []string{"d0", "d1"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "nvidia/nv-rerankqa-mistral-4b-v3",
"query": map[string]any{"text": "q"},
"passages": []any{map[string]any{"text": "d0"}, map[string]any{"text": "d1"}},
"truncate": "END",
}, body)
}
// truncate defaults to NONE upstream, which fails the request on an over-long
// passage instead of cutting it. A vendor that does not set it must not have
// the key invented for it either.
func TestTruncateIsOmittedWhenUnset(t *testing.T) {
c := newClient(t, "https://ai.api.nvidia.com/v1/retrieval/nvidia/reranking", api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"d0"})
require.NoError(t, err)
assert.NotContains(t, body, "truncate")
}
func TestDecodesTheDocumentedResponse(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", "application/json")
_, _ = w.Write([]byte(documentedResponse))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{ScoreScale: api.ScoreLogit})
got, err := c.Rerank(context.Background(), "q", []string{"d0", "d1", "d2"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.226318359375, Text: "d2"},
{Index: 1, Score: -1.171875, Text: "d1"},
{Index: 0, Score: -6.3125, Text: "d0"},
}, got)
}
// An index the request never sent is a protocol violation, not something to
// map onto whatever document happens to sit at that offset.
func TestRejectsAnOutOfRangeIndex(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"rankings":[{"index":7,"logit":0.5}]}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d0"})
require.Error(t, err)
assert.Contains(t, err.Error(), "out of range")
}
func TestSurfacesTheVendorErrorBody(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(`{"detail":"input too long"}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d0"})
require.Error(t, err)
assert.Contains(t, err.Error(), "input too long")
}
func TestRequestReachesTheConfiguredURL(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath string
var gotBody map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(&gotBody)
_, _ = w.Write([]byte(`{"rankings":[]}`))
}))
defer server.Close()
c := newClient(t, server.URL+"/v1/retrieval/nvidia/reranking", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d0"})
require.NoError(t, err)
assert.Equal(t, "/v1/retrieval/nvidia/reranking", gotPath, "the base URL already names the endpoint")
assert.Equal(t, "q", gotBody["query"].(map[string]any)["text"])
}
@@ -0,0 +1,151 @@
// Package openaichataudio implements speech recognition served through the
// chat completions endpoint: one user message whose only content part is
// {"type": "input_audio", "input_audio": {"data": "data:<mime>;base64,..."}},
// answered by an assistant message whose content is the transcript.
//
// Only dedicated recognition models are addressed this way — Alibaba's
// qwen3-asr-flash and Xiaomi's mimo-v2.5-asr — so no instruction is sent: the
// model transcribes whatever it is given. A general audio-capable chat model
// would need a prompt and would answer about the audio rather than transcribe
// it, which is why this is its own protocol and not a chat request.
//
// https://help.aliyun.com/zh/model-studio/qwen-asr-api-reference
// https://mimo.mi.com/docs/en-US/quick-start/usage-guide/audio/Speech-Recognition
package openaichataudio
import (
"context"
"encoding/base64"
"fmt"
"path/filepath"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.TranscriptionsSettings
Retry api.RetryPolicy
}
// Client talks chat-served speech recognition to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const defaultPath = "/chat/completions"
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := defaultPath
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
// audioTypes maps the file extension onto the media type of the data URI.
// The two references show audio/wav and audio/mpeg; the rest are the
// registered types for the containers Alibaba lists. A fixed table rather
// than mime.TypeByExtension, which reads the host's tables and would make the
// request depend on the machine it runs on.
var audioTypes = map[string]string{
".wav": "audio/wav",
".mp3": "audio/mpeg",
".m4a": "audio/mp4",
".mp4": "audio/mp4",
".aac": "audio/aac",
".flac": "audio/flac",
".ogg": "audio/ogg",
".opus": "audio/opus",
".webm": "audio/webm",
".amr": "audio/amr",
}
// DataURI is the input_audio payload for one file. Both references show an
// audio media type in the URI, so a file whose extension names no audio
// container is refused rather than labelled application/octet-stream.
func DataURI(audio []byte, fileName string) (string, error) {
mediaType, ok := audioTypes[strings.ToLower(filepath.Ext(fileName))]
if !ok {
return "", fmt.Errorf("cannot tell the audio format of %q from its extension", fileName)
}
return "data:" + mediaType + ";base64," + base64.StdEncoding.EncodeToString(audio), nil
}
// BuildRequestBody is the golden-test entry point.
func (c *Client) BuildRequestBody(req api.TranscriptionRequest) (map[string]any, error) {
uri, err := DataURI(req.Audio, req.FileName)
if err != nil {
return nil, err
}
// The ceiling is on the whole string as sent — "encoded string size must
// not exceed 10 MB" — so the data: prefix counts too.
if limit := c.cfg.Settings.MaxEncodedBytes; limit > 0 && len(uri) > limit {
return nil, fmt.Errorf(
"the audio is %.1f MB and %.1f MB once base64-encoded; this model accepts at most %.1f MB encoded",
float64(len(req.Audio))/(1<<20), float64(len(uri))/(1<<20), float64(limit)/(1<<20))
}
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"messages": []any{map[string]any{
"role": "user",
"content": []any{map[string]any{
"type": "input_audio",
"input_audio": map[string]any{"data": uri},
}},
}},
}
if req.Language != "" && c.cfg.Settings.LanguageParam == api.LanguageASROptions {
body["asr_options"] = map[string]any{"language": req.Language}
}
return body, nil
}
type response struct {
Choices []struct {
Message struct {
// Content is a pointer for the same reason as the multipart
// protocol's text: an absent transcript is an error, an empty one
// is silence.
Content *string `json:"content"`
} `json:"message"`
} `json:"choices"`
// Usage.Seconds is the audio length, which Alibaba reports.
Usage struct {
Seconds float64 `json:"seconds"`
} `json:"usage"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
// Transcribe sends one audio file.
func (c *Client) Transcribe(ctx context.Context, req api.TranscriptionRequest) (*api.Transcription, error) {
body, err := c.BuildRequestBody(req)
if err != nil {
return nil, err
}
var decoded response
err = c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "transcription")
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("transcription API error: %s", decoded.Error.Message)
}
if len(decoded.Choices) == 0 || decoded.Choices[0].Message.Content == nil {
return nil, fmt.Errorf("transcription reply carries no message content")
}
return &api.Transcription{
Text: strings.TrimSpace(*decoded.Choices[0].Message.Content),
Duration: decoded.Usage.Seconds,
}, nil
}
@@ -0,0 +1,161 @@
package openaichataudio
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// qwenASRResponse is the non-streaming response example from Alibaba's
// Qwen-ASR reference, copied from the page:
// https://help.aliyun.com/zh/model-studio/qwen-asr-api-reference
const qwenASRResponse = `{
"choices": [{
"finish_reason": "stop",
"index": 0,
"message": {
"annotations": [{"emotion": "neutral", "language": "zh", "type": "audio_info"}],
"content": "欢迎使用阿里云。",
"role": "assistant"
}
}],
"created": 1767683986,
"id": "chatcmpl-487abe5f-d4f2-9363-a877-xxxxxxx",
"model": "qwen3-asr-flash",
"object": "chat.completion",
"usage": {"completion_tokens": 12, "prompt_tokens": 42, "total_tokens": 54}
}`
// withSeconds is a reply carrying the usage.seconds that the reference's
// schema documents ("音频时长(秒)") but its example omits.
const withSeconds = `{"choices":[{"message":{"role":"assistant","content":"x"}}],"usage":{"seconds":3}}`
func newClient(url, model string) *Client {
return newClientWith(url, model, api.TranscriptionsSettings{})
}
func newClientWith(url, model string, settings api.TranscriptionsSettings) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: model, Auth: api.BearerAuth("k")},
Settings: settings,
})
}
// The request is the one both references show: a single user message whose
// only part is the audio as a data URI, no instruction, no stream flag.
func TestRequestBodyMatchesTheReferences(t *testing.T) {
body, err := newClient("https://example.invalid/v1", "qwen3-asr-flash").
BuildRequestBody(api.TranscriptionRequest{Audio: []byte("ID3"), FileName: "clip.MP3"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "qwen3-asr-flash",
"messages": []any{map[string]any{
"role": "user",
"content": []any{map[string]any{
"type": "input_audio",
"input_audio": map[string]any{"data": "data:audio/mpeg;base64,SUQz"},
}},
}},
}, body)
}
func TestDataURIMediaTypeFollowsTheExtension(t *testing.T) {
uri, err := DataURI([]byte("RIFF"), "a.wav")
require.NoError(t, err)
assert.Equal(t, "data:audio/wav;base64,UklGRg==", uri)
// No audio type can be named for it, and the references show one.
_, err = DataURI([]byte("x"), "noext")
assert.Error(t, err)
}
// Both references cap the string as sent, so the data: prefix counts. A file
// sized to exactly the encoded budget without the prefix goes over it.
func TestEncodedCeilingCountsTheWholeDataURI(t *testing.T) {
const limit = 1024
c := newClientWith("https://example.invalid", "m", api.TranscriptionsSettings{MaxEncodedBytes: limit})
audio := make([]byte, limit*3/4) // base64 of this is exactly limit bytes
_, err := c.BuildRequestBody(api.TranscriptionRequest{Audio: audio, FileName: "a.wav"})
require.Error(t, err)
prefix := len("data:audio/wav;base64,")
fits := make([]byte, (limit-prefix)/4*3)
_, err = c.BuildRequestBody(api.TranscriptionRequest{Audio: fits, FileName: "a.wav"})
require.NoError(t, err)
}
func TestLanguageGoesInASROptionsWhereDeclared(t *testing.T) {
req := api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav", Language: "zh"}
body, err := newClient("https://example.invalid", "m").BuildRequestBody(req)
require.NoError(t, err)
assert.NotContains(t, body, "asr_options", "undeclared, so not sent")
body, err = newClientWith("https://example.invalid", "m",
api.TranscriptionsSettings{LanguageParam: api.LanguageASROptions}).BuildRequestBody(req)
require.NoError(t, err)
assert.Equal(t, map[string]any{"language": "zh"}, body["asr_options"])
}
func TestDecodesTheDocumentedResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path string
var sent map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(&sent)
_, _ = w.Write([]byte(qwenASRResponse))
}))
defer server.Close()
out, err := newClient(server.URL+"/compatible-mode/v1", "qwen3-asr-flash").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("RIFF"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "/compatible-mode/v1/chat/completions", path)
assert.Equal(t, &api.Transcription{Text: "欢迎使用阿里云。"}, out)
}
// A reply with no assistant content is not silence.
func TestReplyWithoutContentIsAnError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"choices":[]}`))
}))
defer server.Close()
_, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
assert.Error(t, err)
}
func TestDurationFromUsageSeconds(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(withSeconds))
}))
defer server.Close()
out, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, float64(3), out.Duration)
}
func TestEmptyContentIsSilence(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":""}}]}`))
}))
defer server.Close()
out, err := newClient(server.URL, "m").
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "", out.Text)
}
@@ -0,0 +1,441 @@
package openaicompletions
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/types"
)
const defaultPath = "/chat/completions"
// Client talks Chat Completions to one endpoint.
type Client struct {
cfg Config
}
// New creates a client. The endpoint must already carry auth and headers.
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 settings (diagnostics, tests).
func (c *Client) Settings() Config { return c.cfg }
func (c *Client) url() string { return c.cfg.Endpoint.Resolve(defaultPath) }
func (c *Client) send(
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
) (*http.Response, []byte, error) {
opts = api.WithSessionCacheKey(ctx, opts)
body, err := c.BuildRequestBody(messages, opts, stream)
if err != nil {
return nil, nil, err
}
url := c.url()
req, data, err := c.cfg.Endpoint.NewRequest(ctx, url, body, stream)
if err != nil {
return nil, nil, err
}
if c.cfg.Settings.PromptCacheKey {
key := c.cfg.SessionID
if opts != nil && opts.PromptCacheKey != "" {
key = opts.PromptCacheKey
}
api.AttachSessionAffinityHeaders(req, api.ClampPromptCacheKey(key))
}
api.LogRequest(ctx, url, c.cfg.Endpoint.Model, data, stream)
resp, err := c.cfg.Endpoint.Do(req)
if err != nil {
return nil, data, err
}
return resp, data, nil
}
// Chat performs a non-streaming completion.
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 {
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, fmt.Errorf("create chat completion: %w", err)
}
}
defer func() { _ = resp.Body.Close() }()
raw, err := api.ReadResponseCapped(resp.Body, 0)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
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 completion.
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, data, 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, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
}
if err != nil {
cancel()
return nil, fmt.Errorf("create chat completion stream: %w", err)
}
}
ch := make(chan types.StreamResponse)
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
if dumper != nil {
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
}
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
}
// --- response decoding ---
type rawToolCall struct {
Index *int `json:"index,omitempty"`
ID string `json:"id,omitempty"`
Type string `json:"type,omitempty"`
Function struct {
Name string `json:"name,omitempty"`
Arguments string `json:"arguments,omitempty"`
} `json:"function"`
}
type rawMessage struct {
Role string `json:"role,omitempty"`
Content string `json:"content,omitempty"`
ReasoningContent string `json:"reasoning_content,omitempty"`
Reasoning string `json:"reasoning,omitempty"`
ReasoningText string `json:"reasoning_text,omitempty"`
ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
ToolCalls []json.RawMessage `json:"tool_calls,omitempty"`
}
type rawChoice struct {
Index int `json:"index"`
Message rawMessage `json:"message"`
Delta rawMessage `json:"delta"`
FinishReason string `json:"finish_reason,omitempty"`
}
type rawEnvelope struct {
Choices []rawChoice `json:"choices"`
Usage *api.OpenAIUsage `json:"usage,omitempty"`
Error *struct {
Message string `json:"message"`
Type string `json:"type"`
Code any `json:"code"`
} `json:"error,omitempty"`
}
func (c *Client) reasoningText(m rawMessage) string {
for _, field := range c.cfg.Settings.ReasoningFields {
switch field {
case "reasoning_content":
if m.ReasoningContent != "" {
return m.ReasoningContent
}
case "reasoning":
if m.Reasoning != "" {
return m.Reasoning
}
case "reasoning_text":
if m.ReasoningText != "" {
return m.ReasoningText
}
}
}
return ""
}
// streamToolIndex gives index-less streamed tool calls a stable index.
//
// OpenAI numbers the calls of a response with "index". Some compatible servers
// (Gemini's OpenAI endpoint among them) leave it out and send each parallel
// call whole in its own chunk, which would put every call at the position it
// has inside its chunk, index 0, and merge them into one. Without an index a
// fragment that carries an id different from the previous call's starts a new
// call; one without an id, or repeating the id, continues the previous call.
type streamToolIndex struct {
started bool
lastID string
last int
next int
}
func (s *streamToolIndex) resolve(explicit *int, id string) int {
if explicit != nil {
s.started, s.last = true, *explicit
if id != "" {
s.lastID = id
}
s.next = max(s.next, *explicit+1)
return *explicit
}
if !s.started || (id != "" && id != s.lastID) {
s.started = true
s.last = s.next
s.next++
}
if id != "" {
s.lastID = id
}
return s.last
}
// decodeToolCalls decodes the tool calls of a message or of a streamed delta.
// For a stream, pass the stream's streamToolIndex to number index-less calls
// across chunks; without it a missing index falls back to the position in raws.
func (c *Client) decodeToolCalls(
raws []json.RawMessage, indexes *streamToolIndex,
) ([]types.LLMToolCall, []api.ToolCallDelta, error) {
calls := make([]types.LLMToolCall, 0, len(raws))
deltas := make([]api.ToolCallDelta, 0, len(raws))
for i, raw := range raws {
var tc rawToolCall
if err := json.Unmarshal(raw, &tc); err != nil {
// Dropping the entry turns a round that wanted to call a tool into
// a plain answer, and the agent has no way to notice the action it
// was told to take went missing. Surface it instead.
return nil, nil, fmt.Errorf("decode tool call %d: %w", i, err)
}
idx := i
if indexes != nil {
idx = indexes.resolve(tc.Index, tc.ID)
} else if tc.Index != nil {
idx = *tc.Index
}
call := types.LLMToolCall{
ID: tc.ID,
Type: orDefault(tc.Type, "function"),
Function: types.FunctionCall{Name: tc.Function.Name, Arguments: tc.Function.Arguments},
}
call.ProviderMetadata = c.extractToolCallMetadata(raw)
calls = append(calls, call)
deltas = append(deltas, api.ToolCallDelta{
Index: idx, ID: tc.ID, Type: tc.Type, Name: tc.Function.Name, Arguments: tc.Function.Arguments,
})
}
return calls, deltas, nil
}
func (c *Client) extractToolCallMetadata(raw json.RawMessage) types.ToolCallMetadata {
if len(c.cfg.Settings.ToolCallExtraFields) == 0 {
return nil
}
var obj map[string]json.RawMessage
if err := json.Unmarshal(raw, &obj); err != nil {
return nil
}
var md types.ToolCallMetadata
for _, key := range c.cfg.Settings.ToolCallExtraFields {
if v, ok := obj[key]; ok && len(v) > 0 && string(v) != "null" {
if md == nil {
md = types.ToolCallMetadata{}
}
md[key] = v
}
}
return md
}
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
var env rawEnvelope
if err := json.Unmarshal(raw, &env); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if env.Error != nil && env.Error.Message != "" {
return nil, fmt.Errorf("API error: %s", env.Error.Message)
}
if len(env.Choices) == 0 {
return nil, fmt.Errorf("no response from API")
}
choice := env.Choices[0]
content, inlineReasoning := splitThinkTags(choice.Message.Content)
result := &types.ChatResponse{
Content: content,
ReasoningContent: c.reasoningText(choice.Message),
FinishReason: choice.FinishReason,
}
if result.ReasoningContent == "" {
result.ReasoningContent = inlineReasoning
}
if len(choice.Message.ReasoningDetails) > 0 {
result.ReasoningMetadata = types.ProviderMetadata{metadataReasoningDetails: choice.Message.ReasoningDetails}
}
if len(choice.Message.ToolCalls) > 0 {
calls, _, err := c.decodeToolCalls(choice.Message.ToolCalls, nil)
if err != nil {
return nil, err
}
result.ToolCalls = calls
}
// Classify the cache status even when the vendor omitted the usage block,
// so "no counters at all" is still distinguishable from a real miss on the
// usage dashboards instead of landing as an empty CacheStatus.
usage := api.OpenAIUsage{}
if env.Usage != nil {
usage = *env.Usage
}
result.Usage = usage.ToTokenUsage(c.cfg.Settings.PromptCacheAccounting)
return result, nil
}
// splitThinkTags handles models that inline their chain of thought as a
// leading <think>...</think> block instead of a reasoning field.
func splitThinkTags(content string) (answer, reasoning string) {
const start, end = "<think>", "</think>"
trimmed := strings.TrimSpace(content)
if !strings.HasPrefix(trimmed, start) {
return content, ""
}
idx := strings.LastIndex(trimmed, end)
if idx < 0 {
// Unterminated: the whole output is (truncated) reasoning.
return "", strings.TrimSpace(trimmed[len(start):])
}
return strings.TrimSpace(trimmed[idx+len(end):]), strings.TrimSpace(trimmed[len(start):idx])
}
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)
reader := api.NewSSEReader(body)
var reasoningDetails []json.RawMessage
toolIndexes := &streamToolIndex{}
finish := func(end func(chan<- types.StreamResponse)) {
if len(reasoningDetails) > 0 {
merged, _ := json.Marshal(reasoningDetails)
assembler.ReasoningMetadata = types.ProviderMetadata{metadataReasoningDetails: merged}
}
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(assembler.EndAtEOF)
} else {
assembler.Fail(ch, err)
}
return
}
if event == nil {
continue
}
if event.Done {
finish(assembler.End)
return
}
if len(event.Data) == 0 {
continue
}
if dumper != nil {
raw := make([]byte, len(event.Data))
copy(raw, event.Data)
dumper.WritePacketRaw(raw)
}
var env rawEnvelope
if err := json.Unmarshal(event.Data, &env); err != nil {
// Fail rather than skip, as the Anthropic and Gemini loops do. A
// chunk we cannot decode is a hole in the answer: skipping it ends
// the stream on EOF, which reaches the caller as a *successful*
// truncated reply and gets persisted as the model's answer. An
// error at least surfaces the proxy that corrupted the stream.
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
return
}
if env.Error != nil && env.Error.Message != "" {
assembler.Fail(ch, fmt.Errorf("API stream error: %s", env.Error.Message))
return
}
if env.Usage != nil {
assembler.SetUsage(env.Usage.ToTokenUsage(c.cfg.Settings.PromptCacheAccounting))
}
if len(env.Choices) == 0 {
continue
}
choice := env.Choices[0]
delta := api.Delta{
Reasoning: c.reasoningText(choice.Delta),
Content: choice.Delta.Content,
FinishReason: choice.FinishReason,
}
if len(choice.Delta.ReasoningDetails) > 0 {
var items []json.RawMessage
if err := json.Unmarshal(choice.Delta.ReasoningDetails, &items); err == nil {
reasoningDetails = append(reasoningDetails, items...)
}
}
if len(choice.Delta.ToolCalls) > 0 {
_, deltas, err := c.decodeToolCalls(choice.Delta.ToolCalls, toolIndexes)
if err != nil {
assembler.Fail(ch, err)
return
}
delta.ToolCalls = deltas
for i, raw := range choice.Delta.ToolCalls {
if md := c.extractToolCallMetadata(raw); len(md) > 0 {
idx := i
if i < len(deltas) {
idx = deltas[i].Index
}
assembler.SetToolCallMetadata(idx, md)
}
}
}
assembler.Process(ch, delta)
}
}
@@ -0,0 +1,766 @@
package openaicompletions
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, mutate func(*Config)) *Client {
t.Helper()
cfg := Config{
Endpoint: api.Endpoint{
BaseURL: "https://example.com/v1", Model: "m", ModelID: "id", Auth: api.BearerAuth("k"),
},
Settings: api.DefaultOpenAICompletions(),
ThinkingLevels: api.ThinkingLevelMap{},
}
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 ptrBool(b bool) *bool { return &b }
var conversation = []api.Message{
{Role: "system", Content: "You are helpful."},
{Role: "user", Content: "hi"},
{Role: "assistant", ReasoningContent: "thinking...", ToolCalls: []api.ToolCall{{
ID: "call_1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{"q":"x"}`},
}}},
{Role: "tool", ToolCallID: "call_1", Name: "search", Content: "result"},
}
var toolOpts = &api.Options{
Temperature: 0.7, MaxTokens: 1000,
Tools: []api.Tool{{Type: "function", Function: api.FunctionDef{
Name: "search", Description: "d", Parameters: json.RawMessage(`{"type":"object","properties":{}}`),
}}},
ToolChoice: "required", ParallelToolCalls: ptrBool(true),
}
// TestGolden pins the exact wire body per vendor dialect. Each case is one
// row of the vendor fact table; changing a vendor's behaviour means changing
// the expectation here on purpose.
func TestGolden(t *testing.T) {
cases := []struct {
name string
mutate func(*Config)
opts *api.Options
stream bool
want map[string]any // keys asserted; value nil means "must be absent"
}{
{
name: "openai baseline: max_completion_tokens, store, developer role off for non-reasoning",
mutate: func(c *Config) {
c.Settings.SupportsStore = true
c.Settings.SupportsDeveloperRole = true
c.Settings.ThinkingFormat = api.ThinkingFormatOpenAI
c.Settings.SupportsReasoningEffort = true
},
opts: toolOpts,
stream: true,
want: map[string]any{
"max_completion_tokens": float64(1000), "max_tokens": nil,
"store": false, "stream": true, "stream_options": map[string]any{"include_usage": true},
"temperature": 0.7, "tool_choice": "required", "parallel_tool_calls": true,
"reasoning_effort": nil,
},
},
{
name: "openai reasoning model: developer role, no sampling, effort medium",
mutate: func(c *Config) {
c.Reasoning = true
c.Settings.SupportsDeveloperRole = true
c.Settings.SupportsTemperature = false
c.Settings.ThinkingFormat = api.ThinkingFormatOpenAI
c.Settings.SupportsReasoningEffort = true
},
opts: &api.Options{Temperature: 0.7, MaxTokens: 10, ReasoningEffort: api.ReasoningMedium},
want: map[string]any{
"temperature": nil, "reasoning_effort": "medium", "max_completion_tokens": float64(10),
},
},
{
name: "openai gpt-5.1 off maps to reasoning_effort none",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatOpenAI
c.Settings.SupportsReasoningEffort = true
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
},
opts: &api.Options{Thinking: ptrBool(false)},
want: map[string]any{"reasoning_effort": "none"},
},
{
name: "deepseek: max_tokens, thinking.type + effort clamp, tool_choice required dropped",
mutate: func(c *Config) {
c.Settings.MaxTokensField = "max_tokens"
c.Settings.ThinkingFormat = api.ThinkingFormatThinkingType
c.Settings.SupportsReasoningEffort = true
c.Settings.ToolChoiceModes = []string{"none", "auto"}
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningMedium: api.StringPtr("high")}
},
opts: func() *api.Options { o := *toolOpts; o.ReasoningEffort = api.ReasoningMedium; return &o }(),
want: map[string]any{
"max_tokens": float64(1000), "max_completion_tokens": nil,
"thinking": map[string]any{"type": "enabled"}, "reasoning_effort": "high",
"tool_choice": nil, "parallel_tool_calls": true,
},
},
{
name: "deepseek reasoner: always-on, off request sends nothing",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatThinkingType
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: nil}
},
opts: &api.Options{Thinking: ptrBool(false)},
want: map[string]any{"thinking": nil},
},
{
name: "zhipu: thinking disabled explicitly",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatThinkingType
},
opts: &api.Options{Thinking: ptrBool(false)},
want: map[string]any{"thinking": map[string]any{"type": "disabled"}},
},
{
name: "minimax m3: adaptive thinking value",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatThinkingType
c.Settings.ThinkingEnabledValue = "adaptive"
},
opts: &api.Options{Thinking: ptrBool(true)},
want: map[string]any{"thinking": map[string]any{"type": "adaptive"}, "reasoning_effort": nil},
},
{
name: "dashscope hybrid: enable_thinking always sent, budget, non-stream forces off",
mutate: func(c *Config) {
c.Settings.MaxTokensField = "max_tokens"
c.Settings.ThinkingFormat = api.ThinkingFormatEnableThinking
c.Settings.ThinkingBudgetField = "thinking_budget"
c.Settings.ThinkingAlwaysSend = true
c.Settings.ThinkingDisableOnNonStream = true
},
opts: &api.Options{Thinking: ptrBool(true), ThinkingBudgetTokens: 4096},
stream: false,
want: map[string]any{"enable_thinking": false, "thinking_budget": nil},
},
{
name: "dashscope qwen3.8: effort and budget are mutually exclusive, budget yields",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatEnableThinking
c.Settings.ThinkingBudgetField = "thinking_budget"
c.Settings.ThinkingBudgetExcludesEffort = true
c.Settings.SupportsReasoningEffort = true
c.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningMax: api.StringPtr("xhigh")}
},
opts: &api.Options{
Thinking: ptrBool(true), ReasoningEffort: api.ReasoningMax, ThinkingBudgetTokens: 4096,
},
stream: true,
want: map[string]any{
"enable_thinking": true, "reasoning_effort": "xhigh", "thinking_budget": nil,
},
},
{
name: "dashscope qwen3.8: budget still rides along when no effort is graded",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatEnableThinking
c.Settings.ThinkingBudgetField = "thinking_budget"
c.Settings.ThinkingBudgetExcludesEffort = true
},
opts: &api.Options{Thinking: ptrBool(true), ThinkingBudgetTokens: 4096},
stream: true,
want: map[string]any{
"enable_thinking": true, "reasoning_effort": nil, "thinking_budget": float64(4096),
},
},
{
name: "dashscope hybrid streaming: enable_thinking true with budget",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatEnableThinking
c.Settings.ThinkingBudgetField = "thinking_budget"
c.Settings.ThinkingAlwaysSend = true
c.Settings.ThinkingDisableOnNonStream = true
},
opts: &api.Options{Thinking: ptrBool(true), ThinkingBudgetTokens: 4096},
stream: true,
want: map[string]any{"enable_thinking": true, "thinking_budget": float64(4096)},
},
{
name: "dashscope: no preference still pins enable_thinking false",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatEnableThinking
c.Settings.ThinkingAlwaysSend = true
},
opts: &api.Options{Temperature: 0.1},
want: map[string]any{"enable_thinking": false},
},
{
name: "vllm: chat_template_kwargs",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatChatTemplateKwargs
},
opts: &api.Options{Thinking: ptrBool(true)},
want: map[string]any{"chat_template_kwargs": map[string]any{"enable_thinking": true}},
},
{
// Without the effort opt-in the graded level the caller picked is
// not expressible in this dialect: the branch carries only the
// boolean and no reasoning_effort may leak onto the wire
// (capabilities must not advertise rungs for the same reason).
name: "vllm: graded effort request still carries only the boolean",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatChatTemplateKwargs
},
opts: &api.Options{Thinking: ptrBool(true), ReasoningEffort: api.ReasoningHigh},
want: map[string]any{
"chat_template_kwargs": map[string]any{"enable_thinking": true},
"reasoning_effort": nil,
},
},
{
// With the effort opt-in the graded level rides on top of the
// switch, exactly like the enable_thinking dialect (#3552
// review): capabilities keep the ladder for the same reason.
name: "nim-style opt-in: chat_template_kwargs plus reasoning_effort",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatChatTemplateKwargs
c.Settings.SupportsReasoningEffort = true
},
opts: &api.Options{Thinking: ptrBool(true), ReasoningEffort: api.ReasoningHigh},
want: map[string]any{
"chat_template_kwargs": map[string]any{"enable_thinking": true},
"reasoning_effort": "high",
},
},
{
name: "openrouter: reasoning effort object and enabled=false",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatOpenRouter
c.Settings.SupportsReasoningEffort = true
},
opts: &api.Options{ReasoningEffort: api.ReasoningHigh},
want: map[string]any{"reasoning": map[string]any{"effort": "high"}},
},
{
name: "openrouter: auto enables without effort",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatOpenRouter
c.Settings.SupportsReasoningEffort = true
},
opts: &api.Options{ReasoningEffort: api.ReasoningAuto},
want: map[string]any{"reasoning": map[string]any{"enabled": true}},
},
{
name: "moonshot v1: fixed temperature, other sampling dropped",
mutate: func(c *Config) {
one := 1.0
c.Settings.FixedTemperature = &one
},
opts: &api.Options{Temperature: 0.2, TopP: 0.9},
want: map[string]any{"temperature": 1.0, "top_p": nil},
},
{
name: "no thinking preference on a plain vendor sends no thinking fields",
mutate: func(c *Config) {
c.Settings.ThinkingFormat = api.ThinkingFormatThinkingType
},
opts: &api.Options{Temperature: 0.2},
want: map[string]any{"thinking": nil, "reasoning_effort": nil, "enable_thinking": nil},
},
{
name: "prompt cache key and long retention",
mutate: func(c *Config) {
c.Settings.PromptCacheKey = true
},
opts: &api.Options{PromptCacheKey: "sess-1", CacheRetention: api.CacheRetentionLong},
want: map[string]any{"prompt_cache_key": "sess-1", "prompt_cache_retention": "24h"},
},
{
name: "extra_body merges vendor knobs without overriding caller fields",
mutate: func(c *Config) {
c.Settings.ExtraBody = map[string]any{"enable_search": true, "temperature": 0.9}
},
opts: &api.Options{Temperature: 0.2},
want: map[string]any{"enable_search": true, "temperature": 0.2},
},
{
name: "both caller budget aliases produce only the configured wire field",
opts: &api.Options{MaxTokens: 100, MaxCompletionTokens: 200},
want: map[string]any{"max_completion_tokens": float64(200), "max_tokens": nil},
},
{
name: "extra_body cannot add the legacy budget beside the caller completion budget",
mutate: func(c *Config) {
c.Settings.ExtraBody = map[string]any{"max_tokens": 900, "max_completion_tokens": 800}
},
opts: &api.Options{MaxTokens: 100},
want: map[string]any{"max_completion_tokens": float64(100), "max_tokens": nil},
},
{
name: "conflicting extra_body budgets follow the configured field without caller options",
mutate: func(c *Config) {
c.Settings.ExtraBody = map[string]any{"max_tokens": 900, "max_completion_tokens": 800}
},
want: map[string]any{"max_completion_tokens": float64(800), "max_tokens": nil},
},
{
name: "legacy budget vendors discard the conflicting completion budget",
mutate: func(c *Config) {
c.Settings.MaxTokensField = "max_tokens"
c.Settings.ExtraBody = map[string]any{"max_completion_tokens": 800}
},
opts: &api.Options{MaxTokens: 100},
want: map[string]any{"max_tokens": float64(100), "max_completion_tokens": nil},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c := newClient(t, tc.mutate)
got := bodyJSON(t, c, conversation, tc.opts, tc.stream)
for key, want := range tc.want {
if want == nil {
_, present := got[key]
assert.False(t, present, "field %q must be absent, got %v", key, got[key])
continue
}
assert.Equal(t, want, got[key], "field %q", key)
}
})
}
}
func TestMessages_RolesToolsAndReasoningReplay(t *testing.T) {
c := newClient(t, func(c *Config) {
c.Reasoning = true
c.Settings.SupportsDeveloperRole = true
})
got := bodyJSON(t, c, conversation, nil, false)
msgs := got["messages"].([]any)
require.Len(t, msgs, 4)
assert.Equal(t, "developer", msgs[0].(map[string]any)["role"])
assistant := msgs[2].(map[string]any)
assert.Equal(t, "thinking...", assistant["reasoning_content"])
_, hasContent := assistant["content"]
// Issue #1487: assistant tool-call turns must carry an explicit
// `"content": ""` — vLLM/Xinference Qwen-family Jinja templates crash on
// a missing (undefined/null) content field when replaying history.
assert.True(t, hasContent, "empty content must be emitted next to tool_calls")
assert.Equal(t, "", assistant["content"], "emitted content must be empty string")
tc := assistant["tool_calls"].([]any)[0].(map[string]any)
assert.Equal(t, "call_1", tc["id"])
assert.Equal(t, `{"q":"x"}`, tc["function"].(map[string]any)["arguments"])
tool := msgs[3].(map[string]any)
assert.Equal(t, "call_1", tool["tool_call_id"])
assert.Equal(t, "search", tool["name"])
plain := newClient(t, func(c *Config) { c.Settings.ReplayReasoningContent = false })
got = bodyJSON(t, plain, conversation, nil, false)
assistant = got["messages"].([]any)[2].(map[string]any)
_, has := assistant["reasoning_content"]
assert.False(t, has)
assert.Equal(t, "system", got["messages"].([]any)[0].(map[string]any)["role"])
}
func TestMessages_ImagesAndMultiContentDowngrade(t *testing.T) {
msgs := []api.Message{{Role: "user", Content: "look", Images: []string{"https://img/x.png"}}}
c := newClient(t, nil)
got := bodyJSON(t, c, msgs, nil, false)
parts := got["messages"].([]any)[0].(map[string]any)["content"].([]any)
require.Len(t, parts, 2)
assert.Equal(t, "image_url", parts[0].(map[string]any)["type"])
assert.Equal(t, "look", parts[1].(map[string]any)["text"])
flat := newClient(t, func(c *Config) { c.Settings.SupportsMultiContent = false })
got = bodyJSON(t, flat, msgs, nil, false)
assert.Equal(t, "look", got["messages"].([]any)[0].(map[string]any)["content"])
}
func TestToolCallExtraFieldsRoundTrip(t *testing.T) {
c := newClient(t, func(c *Config) { c.Settings.ToolCallExtraFields = []string{"extra_content"} })
md := c.extractToolCallMetadata(json.RawMessage(`{"id":"call_1","type":"function",` +
`"function":{"name":"f","arguments":"{}"},"extra_content":{"google":{"thought_signature":"abc"}}}`))
require.NotNil(t, md)
assert.JSONEq(t, `{"google":{"thought_signature":"abc"}}`, string(md["extra_content"]))
msgs := []api.Message{{Role: "assistant", ToolCalls: []api.ToolCall{{
ID: "call_1", Type: "function", Function: api.FunctionCall{Name: "f", Arguments: "{}"}, ProviderMetadata: md,
}}}}
got := bodyJSON(t, c, msgs, nil, false)
tc := got["messages"].([]any)[0].(map[string]any)["tool_calls"].([]any)[0].(map[string]any)
assert.Equal(t, map[string]any{"google": map[string]any{"thought_signature": "abc"}}, tc["extra_content"])
}
func TestCacheControlBreakpoints(t *testing.T) {
c := newClient(t, func(c *Config) { c.Settings.CacheControlFormat = "anthropic" })
got := bodyJSON(t, c, conversation, toolOpts, false)
data, _ := json.Marshal(got)
assert.Equal(t, 3, strings.Count(string(data), `"cache_control"`))
none := bodyJSON(t, c, conversation, &api.Options{CacheRetention: api.CacheRetentionNone}, false)
data, _ = json.Marshal(none)
assert.NotContains(t, string(data), "cache_control")
}
func TestChat_NonStreamDecoding(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) {
captured = r.Header.Clone()
assert.Equal(t, "/v1/chat/completions", r.URL.Path)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant",` +
`"content":"<think>deep</think>answer",` +
`"tool_calls":[{"id":"c1","type":"function","function":{"name":"f","arguments":"{\"a\":1}"}}]},` +
`"finish_reason":"tool_calls"}],` +
`"usage":{"prompt_tokens":30,"completion_tokens":5,` +
`"prompt_cache_hit_tokens":20,"prompt_cache_miss_tokens":10}}`))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{
BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk"),
Headers: map[string]string{"X-Custom": "1", "Authorization": "Bearer evil"},
},
Settings: func() api.OpenAICompletionsSettings {
s := api.DefaultOpenAICompletions()
s.PromptCacheAccounting = true
return s
}(),
})
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
assert.Equal(t, "Bearer sk", captured.Get("Authorization"), "user headers cannot override auth")
assert.Equal(t, "1", captured.Get("X-Custom"))
assert.Equal(t, "answer", resp.Content)
assert.Equal(t, "deep", resp.ReasoningContent)
assert.Equal(t, "tool_calls", resp.FinishReason)
require.Len(t, resp.ToolCalls, 1)
assert.Equal(t, 20, resp.Usage.CacheReadTokens)
assert.Equal(t, 10, resp.Usage.CacheMissTokens)
}
func TestChat_HTTPErrorSurfacesBody(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":{"message":"max_tokens is not supported"}}`))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: api.DefaultOpenAICompletions(),
})
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.Error(t, err)
assert.Contains(t, err.Error(), "status 400")
assert.Contains(t, err.Error(), "max_tokens is not supported")
}
const streamFixture = `data: {"choices":[{"index":0,"delta":{"role":"assistant","reasoning_content":"thi"}}]}
data: {"choices":[{"index":0,"delta":{"reasoning_content":"nk"}}]}
data: {"choices":[{"index":0,"delta":{"content":"Hel"}}]}
data: {"choices":[{"index":0,"delta":{"content":"lo"}}]}
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function",` +
`"function":{"name":"search"}}]}}]}
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"q\":"}}]}}]}
data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"\"x\"}"}}]}}]}
data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}
data: {"choices":[],"usage":{"prompt_tokens":12,"completion_tokens":7,"prompt_tokens_details":{"cached_tokens":4}}}
data: [DONE]
`
func TestChatStream_Sequence(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
assert.Equal(t, true, body["stream"])
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(streamFixture))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: api.DefaultOpenAICompletions(),
})
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
var thinking, answer strings.Builder
var seenTypes []types.ResponseType
var last types.StreamResponse
thinkingDone := false
for chunk := range ch {
seenTypes = append(seenTypes, chunk.ResponseType)
switch chunk.ResponseType {
case types.ResponseTypeThinking:
if chunk.Done {
thinkingDone = true
}
thinking.WriteString(chunk.Content)
case types.ResponseTypeAnswer:
answer.WriteString(chunk.Content)
if chunk.Done {
last = chunk
}
case types.ResponseTypeToolCall:
assert.Equal(t, "search", chunk.Data["tool_name"])
assert.Equal(t, "c1", chunk.Data["tool_call_id"])
case types.ResponseTypeError:
t.Fatalf("unexpected error: %s", chunk.Content)
}
}
assert.Equal(t, "think", thinking.String())
assert.True(t, thinkingDone, "thinking done marker emitted before the answer")
assert.Equal(t, "Hello", answer.String())
assert.Contains(t, seenTypes, types.ResponseTypeToolCall)
require.Len(t, last.ToolCalls, 1)
assert.Equal(t, `{"q":"x"}`, last.ToolCalls[0].Function.Arguments)
assert.Equal(t, "tool_calls", last.FinishReason)
require.NotNil(t, last.Usage)
assert.Equal(t, 12, last.Usage.PromptTokens)
assert.Equal(t, 4, last.Usage.CacheReadTokens)
}
func TestSplitThinkTags(t *testing.T) {
answer, reasoning := splitThinkTags("<think>a</think>b")
assert.Equal(t, "b", answer)
assert.Equal(t, "a", reasoning)
answer, reasoning = splitThinkTags("<think>truncated")
assert.Equal(t, "", answer)
assert.Equal(t, "truncated", reasoning)
answer, reasoning = splitThinkTags("plain")
assert.Equal(t, "plain", answer)
assert.Equal(t, "", reasoning)
}
// A response without a usage block must still classify the cache status:
// leaving it empty makes "the vendor reported nothing" look like a real miss
// on the usage dashboards. The pre-split implementation always classified.
func TestChat_ClassifiesCacheStatusWithoutUsageBlock(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", "application/json")
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant","content":"hi"},` +
`"finish_reason":"stop"}]}`))
}))
defer server.Close()
for _, tc := range []struct {
name string
accounting bool
want types.PromptCacheStatus
}{
{"vendor documents cache accounting", true, types.PromptCacheStatusUnreported},
{"vendor has no cache accounting", false, types.PromptCacheStatusUnsupported},
} {
t.Run(tc.name, func(t *testing.T) {
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: func() api.OpenAICompletionsSettings {
s := api.DefaultOpenAICompletions()
s.PromptCacheAccounting = tc.accounting
return s
}(),
})
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
assert.Equal(t, tc.want, resp.Usage.CacheStatus)
})
}
}
// A stream that ends on the [DONE] sentinel without a space after the colon
// must still terminate cleanly rather than logging a JSON parse failure.
func TestChatStream_TolerantDoneSentinel(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(
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"hi\"},\"finish_reason\":\"stop\"}]}\n\n" +
"data:[DONE]\n\n"))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
var answer strings.Builder
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
t.Fatalf("unexpected error chunk: %s", chunk.Content)
}
answer.WriteString(chunk.Content)
}
assert.Equal(t, "hi", answer.String())
}
// A chunk that will not decode is a hole in the answer. Skipping it (the old
// behaviour) ended the stream on EOF, so a proxy that corrupted one packet
// produced a truncated reply that every caller recorded as a successful one.
// The Anthropic and Gemini loops fail in this situation; so does this one.
func TestChatStream_UndecodableChunkFailsTheStream(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(
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n" +
"data: <html>502 Bad Gateway</html>\n\n" +
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"lo\"},\"finish_reason\":\"stop\"}]}\n\n" +
"data: [DONE]\n\n"))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
var sawError bool
var answer strings.Builder
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
sawError = true
assert.Contains(t, chunk.Content, "decode stream chunk")
continue
}
answer.WriteString(chunk.Content)
}
assert.True(t, sawError, "a truncated stream must surface as an error, not as a short answer")
assert.Equal(t, "Hel", answer.String(), "decoding stops at the bad chunk")
}
// A tool_calls entry we cannot decode used to be skipped, so a round that
// wanted to call a tool arrived at the agent as a plain answer with nothing
// to act on. Losing the action is worse than failing the round.
func TestChat_MalformedToolCallIsAnError(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", "application/json")
_, _ = w.Write([]byte(`{"choices":[{"index":0,"message":{"role":"assistant","content":"",` +
`"tool_calls":["not-an-object"]},"finish_reason":"tool_calls"}]}`))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.Error(t, err, "a tool call that will not decode must not pass as a plain answer")
assert.Contains(t, err.Error(), "decode tool call")
}
// The streaming counterpart: the round must end as an error rather than as a
// short answer whose tool call quietly vanished.
func TestChatStream_MalformedToolCallFailsTheStream(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(
"data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"}}]}\n\n" +
"data: {\"choices\":[{\"index\":0,\"delta\":{\"tool_calls\":[42]}}]}\n\n" +
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"tool_calls\"}]}\n\n" +
"data: [DONE]\n\n"))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
require.NoError(t, err)
var sawError bool
var answer strings.Builder
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
sawError = true
assert.Contains(t, chunk.Content, "decode tool call")
continue
}
answer.WriteString(chunk.Content)
}
assert.True(t, sawError, "a dropped tool call must surface as an error")
assert.Equal(t, "ok", answer.String(), "decoding stops at the bad chunk")
}
// A body that runs out without [DONE] or any finish_reason is what a proxy
// cutting the connection mid-answer looks like; it must not read as a stop.
// [DONE] alone stays a clean end, since some vendors never send finish_reason.
func TestChatStream_EOFWithoutFinishReasonIsIncomplete(t *testing.T) {
cases := []struct {
name, tail, want string
}{
{"cut off", "", types.FinishReasonIncomplete},
{
"finish reason without DONE",
"data: {\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\n", "stop",
},
{"DONE without finish reason", "data: [DONE]\n\n", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(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")
head := "data: {\"choices\":[{\"index\":0,\"delta\":{\"content\":\"Hel\"}}]}\n\n"
_, _ = w.Write([]byte(head + tc.tail))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL + "/v1", Model: "m", Auth: api.BearerAuth("sk")},
Settings: api.DefaultOpenAICompletions(),
})
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 {
require.NotEqual(t, types.ResponseTypeError, chunk.ResponseType, chunk.Content)
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
last = chunk
}
}
assert.Equal(t, tc.want, last.FinishReason)
})
}
}
@@ -0,0 +1,469 @@
// Package openaicompletions implements the OpenAI Chat Completions wire
// protocol. Every vendor-specific deviation is driven by
// api.OpenAICompletionsSettings; this package contains no vendor names.
package openaicompletions
import (
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.OpenAICompletionsSettings
// ThinkingLevels maps neutral levels to the vendor vocabulary.
ThinkingLevels api.ThinkingLevelMap
// Reasoning marks a reasoning model (developer role, no sampling params
// are decided by Settings, this only gates role selection).
Reasoning bool
// SessionID feeds prompt_cache_key when the caller sets none.
SessionID string
}
type wireToolCall struct {
ID string `json:"id,omitempty"`
Type string `json:"type"`
Function wireFunctionCall `json:"function"`
extra map[string]json.RawMessage
}
type wireFunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"`
}
// MarshalJSON appends opaque vendor fields (Gemini extra_content) next to
// the standard members.
func (t wireToolCall) MarshalJSON() ([]byte, error) {
type plain wireToolCall
data, err := json.Marshal(plain(t))
if err != nil {
return nil, err
}
if len(t.extra) == 0 {
return data, nil
}
var obj map[string]json.RawMessage
if err := json.Unmarshal(data, &obj); err != nil {
return nil, err
}
for k, v := range t.extra {
obj[k] = v
}
return json.Marshal(obj)
}
type wireMessage struct {
Role string `json:"role"`
Content any `json:"content,omitempty"`
Name string `json:"name,omitempty"`
ToolCallID string `json:"tool_call_id,omitempty"`
ToolCalls []wireToolCall `json:"tool_calls,omitempty"`
ReasoningContent *string `json:"reasoning_content,omitempty"`
ReasoningDetails json.RawMessage `json:"reasoning_details,omitempty"`
}
type wirePart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL *wireImageURL `json:"image_url,omitempty"`
}
type wireImageURL struct {
URL string `json:"url"`
Detail string `json:"detail,omitempty"`
}
// convertMessages maps neutral messages onto Chat Completions messages.
func (c *Client) convertMessages(messages []api.Message) []wireMessage {
s := c.cfg.Settings
instructionRole := "system"
if c.cfg.Reasoning && s.SupportsDeveloperRole {
instructionRole = "developer"
}
out := make([]wireMessage, 0, len(messages))
for _, msg := range messages {
msg = api.NeutralizeMessageSpecialTokens(msg)
wm := wireMessage{Role: msg.Role}
if msg.Role == "system" {
wm.Role = instructionRole
}
switch {
case len(msg.MultiContent) > 0:
parts := make([]wirePart, 0, len(msg.MultiContent))
for _, part := range msg.MultiContent {
switch part.Type {
case "text":
parts = append(parts, wirePart{Type: "text", Text: part.Text})
case "image_url":
if part.ImageURL != nil {
parts = append(parts, wirePart{Type: "image_url", ImageURL: &wireImageURL{
URL: api.ResolveImageURLForLLM(part.ImageURL.URL), Detail: part.ImageURL.Detail,
}})
}
}
}
wm.Content = c.contentParts(parts)
case len(msg.Images) > 0 && msg.Role == "user":
parts := make([]wirePart, 0, len(msg.Images)+1)
for _, img := range msg.Images {
parts = append(parts, wirePart{Type: "image_url", ImageURL: &wireImageURL{
URL: api.ResolveImageURLForLLM(img), Detail: "auto",
}})
}
parts = append(parts, wirePart{Type: "text", Text: msg.Content})
wm.Content = c.contentParts(parts)
default:
if msg.Content != "" || len(msg.ToolCalls) == 0 {
wm.Content = msg.Content
} else {
// Assistant tool-call turn with empty content: emit an
// explicit `"content": ""` instead of omitting the field.
// Strict local engines (vLLM / Xinference serving Qwen-family
// Jinja chat templates) treat a missing content field as
// undefined/null and crash when rendering the assistant turn
// for the next round. Issue #1487. The *string keeps
// `omitempty` from dropping the field: a non-nil interface
// holding a pointer serializes as "".
empty := ""
wm.Content = &empty
}
}
if len(msg.ToolCalls) > 0 {
wm.ToolCalls = make([]wireToolCall, 0, len(msg.ToolCalls))
for _, tc := range msg.ToolCalls {
wtc := wireToolCall{
ID: tc.ID,
Type: orDefault(tc.Type, "function"),
Function: wireFunctionCall{Name: tc.Function.Name, Arguments: tc.Function.Arguments},
}
for _, key := range s.ToolCallExtraFields {
if raw, ok := tc.ProviderMetadata[key]; ok && len(raw) > 0 {
if wtc.extra == nil {
wtc.extra = map[string]json.RawMessage{}
}
wtc.extra[key] = raw
}
}
wm.ToolCalls = append(wm.ToolCalls, wtc)
}
}
if msg.Role == "tool" {
wm.ToolCallID = msg.ToolCallID
wm.Name = msg.Name
}
if msg.Role == "assistant" {
if s.ReplayReasoningContent && msg.ReasoningContent != "" {
rc := msg.ReasoningContent
wm.ReasoningContent = &rc
}
// reasoning_details is OpenRouter's format; other vendors reject it.
raw, ok := msg.ReasoningMetadata[metadataReasoningDetails]
if ok && len(raw) > 0 && s.ThinkingFormat == api.ThinkingFormatOpenRouter {
wm.ReasoningDetails = raw
}
}
out = append(out, wm)
}
return out
}
// contentParts flattens rich content to plain text for vendors that only
// accept strings (Academy Cloud), otherwise returns the parts as-is.
func (c *Client) contentParts(parts []wirePart) any {
if c.cfg.Settings.SupportsMultiContent {
return parts
}
var texts []string
for _, p := range parts {
if p.Type == "text" && p.Text != "" {
texts = append(texts, p.Text)
}
}
return strings.Join(texts, "\n")
}
const metadataReasoningDetails = "reasoning_details"
// buildBody assembles the request body. It returns a map so vendor-specific
// top-level fields can be added without a struct per vendor; key order in
// the encoded JSON is alphabetical, which keeps golden tests stable.
func (c *Client) buildBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
s := c.cfg.Settings
wireMessages := c.convertMessages(messages)
if opts != nil && opts.RuntimeNotice != "" {
wireMessages = append(
wireMessages,
c.convertMessages([]api.Message{{Role: "system", Content: opts.RuntimeNotice}})...,
)
}
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"messages": wireMessages,
}
if stream {
body["stream"] = true
if s.SupportsUsageInStreaming {
body["stream_options"] = map[string]any{"include_usage": true}
}
}
if s.SupportsStore {
body["store"] = false
}
if opts != nil {
c.applySampling(body, opts)
if budget := opts.CompletionBudget(); budget > 0 {
field := s.MaxTokensField
if field == "" {
field = "max_completion_tokens"
}
body[field] = budget
}
c.applyTools(body, opts)
if len(opts.Format) > 0 && s.SupportsResponseFormat {
body["response_format"] = map[string]any{"type": "json_object"}
msgs := body["messages"].([]wireMessage)
if len(msgs) > 0 {
last := &msgs[len(msgs)-1]
if text, ok := last.Content.(string); ok {
last.Content = text + fmt.Sprintf("\nUse this JSON schema: %s", opts.Format)
}
}
}
if s.PromptCacheKey && api.ResolveCacheRetention(opts) != api.CacheRetentionNone {
key := opts.PromptCacheKey
if key == "" {
key = c.cfg.SessionID
}
if key = api.ClampPromptCacheKey(key); key != "" {
body["prompt_cache_key"] = key
if api.ResolveCacheRetention(opts) == api.CacheRetentionLong {
body["prompt_cache_retention"] = "24h"
}
}
}
}
c.applyThinking(body, opts, stream)
for k, v := range s.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
// These names are mutually exclusive, including when extra_body supplies
// one or both. Keep the protocol's configured field; an explicit caller
// budget already takes precedence over extra_body above.
if _, legacy := body["max_tokens"]; legacy {
if _, completion := body["max_completion_tokens"]; completion {
if s.MaxTokensField == "max_tokens" {
delete(body, "max_completion_tokens")
} else {
delete(body, "max_tokens")
}
}
}
return body, nil
}
func (c *Client) applySampling(body map[string]any, opts *api.Options) {
s := c.cfg.Settings
if !s.SupportsTemperature {
return
}
if s.FixedTemperature != nil {
body["temperature"] = *s.FixedTemperature
return
}
if opts.Temperature > 0 {
body["temperature"] = opts.Temperature
}
if opts.TopP > 0 {
body["top_p"] = opts.TopP
}
if opts.FrequencyPenalty > 0 {
body["frequency_penalty"] = opts.FrequencyPenalty
}
if opts.PresencePenalty > 0 {
body["presence_penalty"] = opts.PresencePenalty
}
if opts.Seed > 0 && s.SupportsSeed {
body["seed"] = opts.Seed
}
}
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
s := c.cfg.Settings
if len(opts.Tools) == 0 {
return
}
tools := make([]map[string]any, 0, len(opts.Tools))
for _, tool := range opts.Tools {
fn := map[string]any{
"name": tool.Function.Name,
"description": tool.Function.Description,
}
if len(tool.Function.Parameters) > 0 {
fn["parameters"] = tool.Function.Parameters
}
tools = append(tools, map[string]any{"type": orDefault(tool.Type, "function"), "function": fn})
}
body["tools"] = tools
if opts.ParallelToolCalls != nil && s.SupportsParallelToolCalls {
body["parallel_tool_calls"] = *opts.ParallelToolCalls
}
if opts.ToolChoice == "" {
return
}
switch opts.ToolChoice {
case "none", "required", "auto":
if s.AllowsToolChoice(opts.ToolChoice) {
body["tool_choice"] = opts.ToolChoice
}
default:
if s.AllowsToolChoice("function") {
body["tool_choice"] = map[string]any{
"type": "function",
"function": map[string]any{"name": opts.ToolChoice},
}
}
}
}
// applyThinking encodes the requested reasoning level in the vendor's
// dialect. See api.ThinkingFormat for the dialects.
func (c *Client) applyThinking(body map[string]any, opts *api.Options, stream bool) {
s := c.cfg.Settings
if s.ThinkingFormat == api.ThinkingFormatNone || s.ThinkingFormat == "" {
return
}
levels := c.cfg.ThinkingLevels
level, requested := opts.Reasoning()
if !requested {
if !s.ThinkingAlwaysSend {
return
}
level = api.ReasoningOff
}
if level.Graded() {
level = levels.Clamp(level)
}
enabled := level.Enabled()
if enabled && s.ThinkingDisableOnNonStream && !stream {
enabled = false
}
if !enabled && !levels.Supports(api.ReasoningOff) {
// Always-on reasoning model: there is nothing to switch off and the
// vendor rejects the attempt.
return
}
effort := ""
if enabled && level.Graded() && s.SupportsReasoningEffort {
effort = levels.Value(level)
}
effortField := orDefault(s.ReasoningEffortField, "reasoning_effort")
budget := 0
if enabled && opts != nil && s.ThinkingBudgetField != "" {
budget = opts.ThinkingBudgetTokens
}
if effort != "" && s.ThinkingBudgetExcludesEffort {
// The two fields are mutually exclusive on this vendor and sending
// both is an error; the graded level wins because it is what the
// caller picked.
budget = 0
}
if budget > 0 {
body[s.ThinkingBudgetField] = budget
}
switch s.ThinkingFormat {
case api.ThinkingFormatOpenAI:
if enabled {
if effort != "" {
body[effortField] = effort
}
} else if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
body[effortField] = *v
}
case api.ThinkingFormatThinkingType:
if enabled {
body["thinking"] = map[string]any{"type": orDefault(s.ThinkingEnabledValue, "enabled")}
if effort != "" {
body[effortField] = effort
}
} else {
body["thinking"] = map[string]any{"type": "disabled"}
}
case api.ThinkingFormatEnableThinking:
body["enable_thinking"] = enabled
if effort != "" {
body[effortField] = effort
}
case api.ThinkingFormatChatTemplateKwargs:
body["chat_template_kwargs"] = map[string]any{"enable_thinking": enabled}
if effort != "" {
body[effortField] = effort
}
case api.ThinkingFormatOpenRouter:
if enabled {
reasoning := map[string]any{}
if effort != "" {
reasoning["effort"] = effort
} else {
reasoning["enabled"] = true
}
body["reasoning"] = reasoning
} else {
body["reasoning"] = map[string]any{"enabled": false}
}
}
}
// finalizeBody applies transformations that need the JSON object form
// (cache_control breakpoints) and returns the bytes to send.
func (c *Client) finalizeBody(body map[string]any, opts *api.Options) (map[string]any, error) {
s := c.cfg.Settings
if s.CacheControlFormat != "anthropic" {
return body, nil
}
marker := api.CacheControlFor(api.ResolveCacheRetention(opts), "1h")
if marker == nil {
return body, nil
}
data, err := json.Marshal(body)
if err != nil {
return nil, err
}
var payload map[string]any
if err := json.Unmarshal(data, &payload); err != nil {
return nil, err
}
api.ApplyCacheControlBreakpoints(payload, marker)
return payload, nil
}
// BuildRequestBody is the golden-test entry point: it returns the exact
// JSON object that would be sent for the given inputs.
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
body, err := c.buildBody(messages, opts, stream)
if err != nil {
return nil, err
}
return c.finalizeBody(body, opts)
}
func orDefault(v, def string) string {
if v == "" {
return def
}
return v
}
@@ -0,0 +1,92 @@
package openaicompletions
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestConversationHeadersAcrossTurnsAndToolResults(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
for _, cacheKeyEnabled := range []bool{false, true} {
name := "without-cache-key"
if cacheKeyEnabled {
name = "with-cache-key"
}
t.Run(name, func(t *testing.T) {
var headers []http.Header
var requests []map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers = append(headers, r.Header.Clone())
var body map[string]any
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
t.Error(err)
w.WriteHeader(http.StatusBadRequest)
return
}
requests = append(requests, body)
if body["stream"] == true {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: " +
`{"choices":[{"index":0,"delta":{"content":"ok"},"finish_reason":"stop"}]}` +
"\n\ndata: [DONE]\n\n"))
return
}
_, _ = w.Write([]byte(
`{"choices":[{"message":{"role":"assistant","content":"ok"},"finish_reason":"stop"}]}`,
))
}))
defer server.Close()
settings := api.DefaultOpenAICompletions()
settings.PromptCacheKey = cacheKeyEnabled
client := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: settings})
opts := &api.Options{PromptCacheKey: "shared-cache-prefix"}
messages := []api.Message{{Role: "user", Content: "First turn"}}
ctx := types.WithSessionID(context.Background(), "business-session")
_, err := client.Chat(ctx, messages, opts)
require.NoError(t, err)
messages = append(messages,
api.Message{Role: "assistant", Content: "ok"},
api.Message{Role: "user", Content: "Second turn"},
)
// A new HTTP request context still carries the same business session.
ctx = types.WithSessionID(context.Background(), "business-session")
stream, err := client.ChatStream(ctx, messages, opts)
require.NoError(t, err)
var streamedContent string
for chunk := range stream {
streamedContent += chunk.Content
}
assert.Equal(t, "ok", streamedContent)
messages = append(messages,
api.Message{Role: "assistant", ToolCalls: []api.ToolCall{{
ID: "call-1", Type: "function", Function: api.FunctionCall{Name: "search", Arguments: `{}`},
}}},
api.Message{Role: "tool", ToolCallID: "call-1", Content: "Search result"},
)
_, err = client.Chat(ctx, messages, opts)
require.NoError(t, err)
require.Len(t, headers, 3)
for i, h := range headers {
assert.Equal(t, "business-session", h.Get("X-Conversation-ID"))
assert.Equal(t, "Academy", h.Get("User-Agent"))
if cacheKeyEnabled {
assert.Equal(t, "business-session", h.Get("x-session-affinity"))
assert.Equal(t, "shared-cache-prefix", requests[i]["prompt_cache_key"])
}
}
lastMessages := requests[2]["messages"].([]any)
assert.Equal(t, "tool", lastMessages[len(lastMessages)-1].(map[string]any)["role"])
assert.Equal(t, "shared-cache-prefix", opts.PromptCacheKey)
})
}
}
@@ -0,0 +1,111 @@
package openaicompletions
import (
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/models/api"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// streamCalls runs the given SSE data lines through ChatStream and returns the
// tool calls of the final chunk.
func streamCalls(t *testing.T, lines ...string) []types.LLMToolCall {
t.Helper()
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")
for _, l := range lines {
_, _ = w.Write([]byte("data: " + l + "\n\n"))
}
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
defer server.Close()
c := New(Config{
Endpoint: api.Endpoint{BaseURL: server.URL, Model: "m"}, Settings: api.DefaultOpenAICompletions(),
})
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 {
require.NotEqual(t, types.ResponseTypeError, chunk.ResponseType, chunk.Content)
if chunk.Done {
last = chunk
}
}
return last.ToolCalls
}
func toolChunk(calls string, finish string) string {
f := "null"
if finish != "" {
f = `"` + finish + `"`
}
return `{"choices":[{"delta":{"tool_calls":[` + calls + `]},"finish_reason":` + f + `}]}`
}
func TestChatStream_IndexedToolCallsStayApart(t *testing.T) {
calls := streamCalls(t,
toolChunk(`{"index":0,"id":"a","type":"function","function":{"name":"get_weather","arguments":""}}`, ""),
toolChunk(`{"index":0,"function":{"arguments":"{\"city\":\"Paris\"}"}}`, ""),
toolChunk(
`{"index":1,"id":"b","type":"function","function":{"name":"get_time","arguments":"{}"}}`,
"tool_calls"),
)
require.Len(t, calls, 2)
assert.Equal(t, "get_weather", calls[0].Function.Name)
assert.Equal(t, `{"city":"Paris"}`, calls[0].Function.Arguments)
assert.Equal(t, "get_time", calls[1].Function.Name)
}
func TestChatStream_ParallelCallsWithoutIndexStayApart(t *testing.T) {
// Each call arrives whole in its own chunk and no chunk has an index.
calls := streamCalls(t,
toolChunk(
`{"id":"a","type":"function","function":{"name":"get_weather","arguments":"{\"city\":\"Paris\"}"}}`,
""),
toolChunk(
`{"id":"b","type":"function","function":{"name":"get_time","arguments":"{\"tz\":\"UTC\"}"}}`,
"tool_calls"),
)
require.Len(t, calls, 2)
assert.Equal(t, "a", calls[0].ID)
assert.Equal(t, "get_weather", calls[0].Function.Name)
assert.Equal(t, `{"city":"Paris"}`, calls[0].Function.Arguments)
assert.Equal(t, "b", calls[1].ID)
assert.Equal(t, "get_time", calls[1].Function.Name)
assert.Equal(t, `{"tz":"UTC"}`, calls[1].Function.Arguments)
}
func TestChatStream_TwoCallsInOneChunkWithoutIndexStayApart(t *testing.T) {
calls := streamCalls(t,
toolChunk(
`{"id":"a","type":"function","function":{"name":"get_weather","arguments":"{}"}},`+
`{"id":"b","type":"function","function":{"name":"get_time","arguments":"{}"}}`,
"tool_calls"),
)
require.Len(t, calls, 2)
assert.Equal(t, "get_weather", calls[0].Function.Name)
assert.Equal(t, "get_time", calls[1].Function.Name)
}
func TestChatStream_FragmentsWithoutIndexContinueTheCall(t *testing.T) {
// Name and id first, then argument fragments with neither, or with the
// id repeated.
calls := streamCalls(t,
toolChunk(`{"id":"a","type":"function","function":{"name":"get_weather","arguments":""}}`, ""),
toolChunk(`{"function":{"arguments":"{\"city\":"}}`, ""),
toolChunk(`{"id":"a","function":{"arguments":"\"Paris\"}"}}`, "tool_calls"),
)
require.Len(t, calls, 1)
assert.Equal(t, "get_weather", calls[0].Function.Name)
assert.Equal(t, `{"city":"Paris"}`, calls[0].Function.Arguments)
assert.True(t, strings.HasPrefix(calls[0].ID, "a"))
}
@@ -0,0 +1,224 @@
// Package openaiembeddings implements the embedding shape OpenAI defined and
// every compatible gateway copied: POST {base}/embeddings with {model, input}
// answering {data: [{embedding, index}]}.
//
// The vendors that speak it disagree about everything optional, so nothing
// optional is sent unless api.EmbeddingsSettings says the vendor
// documents it:
//
// - `dimensions` does not exist on NVIDIA NIM or Volcengine's text endpoint;
// - `encoding_format` is absent from Zhipu's reference;
// - the parameter that separates a search query from an indexed document is
// `input_type` on NIM, `task` on Jina and `taskType` on Gemini, and most
// vendors have none;
// - images have no standard place: Jina and SGLang take an object in
// `input`, vLLM takes a chat conversation in `messages`.
//
// This package contains no vendor names.
package openaiembeddings
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.EmbeddingsSettings
// Dimensions is the width the row asked for; it is sent only when the
// vendor names a field for it.
Dimensions int
Retry api.RetryPolicy
}
// Client talks the OpenAI embedding shape to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
const defaultPath = "/embeddings"
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = defaultPath
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type response struct {
Data []struct {
Embedding []float32 `json:"embedding"`
// Index is a pointer so that an absent field reads as absent rather
// than as 0. OpenAI, vLLM and TEI send it; some minimal compatible
// servers answer in order and leave it out, and the pre-catalog
// client read those positionally. Decoded as a plain int, every
// element of such a reply would claim slot 0.
Index *int `json:"index"`
} `json:"data"`
Error *struct {
Message string `json:"message"`
} `json:"error,omitempty"`
}
// BuildRequestBody is the golden-test entry point: it returns the exact JSON
// object that would be sent.
func (c *Client) BuildRequestBody(texts []string, kind api.EmbedInputType) map[string]any {
return c.body("input", texts, kind)
}
// BuildImageRequestBody is the golden-test entry point for images. The shape
// has no standard image input; a vendor that extends it names the key of the
// object that carries one, and Jina's reference gives
// {"image": URL or data URI}.
func (c *Client) BuildImageRequestBody(images []api.EmbedImage, kind api.EmbedInputType) map[string]any {
input := make([]any, 0, len(images))
for _, img := range images {
input = append(input, map[string]any{c.cfg.Settings.ImageField: img.DataURI()})
}
return c.body("input", input, kind)
}
// BuildImageMessageBody is the golden-test entry point for the messages
// format: one user turn carrying the image, then the configured prompt, as
// in vLLM's multimodal embedding example.
func (c *Client) BuildImageMessageBody(img api.EmbedImage, kind api.EmbedInputType) map[string]any {
content := []any{map[string]any{"type": "image_url", "image_url": map[string]any{"url": img.DataURI()}}}
if prompt := c.cfg.Settings.ImagePrompt; prompt != "" {
content = append(content, map[string]any{"type": "text", "text": prompt})
}
return c.messageBody(content, kind)
}
// BuildTextMessageBody is the golden-test entry point for a text sent in the
// messages format.
func (c *Client) BuildTextMessageBody(text string, kind api.EmbedInputType) map[string]any {
return c.messageBody([]any{map[string]any{"type": "text", "text": text}}, kind)
}
func (c *Client) messageBody(content []any, kind api.EmbedInputType) map[string]any {
return c.body("messages", []any{map[string]any{"role": "user", "content": content}}, kind)
}
func (c *Client) body(key string, input any, kind api.EmbedInputType) map[string]any {
s := c.cfg.Settings
body := map[string]any{
"model": c.cfg.Endpoint.Model,
key: input,
}
if s.SendEncodingFormat {
body["encoding_format"] = "float"
}
if s.DimensionsField != "" && c.cfg.Dimensions > 0 {
body[s.DimensionsField] = c.cfg.Dimensions
}
if field := s.InputTypeField; field != "" {
body[field] = s.InputTypeValue(kind)
}
if s.TruncateField != "" {
if s.TruncateValue == "true" || s.TruncateValue == "false" {
body[s.TruncateField] = s.TruncateValue == "true"
} else {
body[s.TruncateField] = s.TruncateValue
}
}
if s.TruncatePromptTokens > 0 && s.AcceptsTruncatePromptTokens {
body["truncate_prompt_tokens"] = s.TruncatePromptTokens
}
for k, v := range s.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body
}
// Embed vectorizes one batch, in the order it was given.
func (c *Client) Embed(
ctx context.Context, texts []string, kind api.EmbedInputType,
) ([][]float32, error) {
if c.cfg.Settings.TextAsMessages {
return c.postMessages(ctx, len(texts), kind, func(i int) map[string]any {
return c.BuildTextMessageBody(texts[i], kind)
})
}
return c.post(ctx, c.BuildRequestBody(texts, kind), len(texts))
}
// AcceptsImages reports whether the vendor declares an image format. Without
// one a plain OpenAI-compatible server would read image objects as
// malformed text input.
func (c *Client) AcceptsImages() bool { return c.cfg.Settings.OpenAIImageFormat() != "" }
// EmbedImages vectorizes one batch of images, in the order it was given.
func (c *Client) EmbedImages(
ctx context.Context, images []api.EmbedImage, kind api.EmbedInputType,
) ([][]float32, error) {
switch c.cfg.Settings.OpenAIImageFormat() {
case api.EmbeddingImageObject:
return c.post(ctx, c.BuildImageRequestBody(images, kind), len(images))
case api.EmbeddingImageMessages:
return c.postMessages(ctx, len(images), kind, func(i int) map[string]any {
return c.BuildImageMessageBody(images[i], kind)
})
}
return nil, fmt.Errorf("this embedding endpoint declares no image input")
}
// postMessages preserves each input's chat template while batching independent
// conversations on servers that support EmbeddingBatchChatRequest:
// https://github.com/vllm-project/vllm/blob/v0.29.0/vllm/entrypoints/pooling/embed/protocol.py
func (c *Client) postMessages(
ctx context.Context, n int, kind api.EmbedInputType, body func(int) map[string]any,
) ([][]float32, error) {
if n == 0 {
return nil, nil
}
if c.cfg.Settings.BatchMessages && n > 1 {
conversations := make([]any, n)
for i := range n {
conversations[i] = body(i)["messages"]
}
return c.post(ctx, c.body("messages", conversations, kind), n)
}
// A single input and older endpoints keep the original flat messages.
out := make([][]float32, n)
for i := range n {
vectors, err := c.post(ctx, body(i), 1)
if err != nil {
return nil, err
}
out[i] = vectors[0]
}
return out, nil
}
func (c *Client) post(ctx context.Context, body map[string]any, want int) ([][]float32, error) {
var decoded response
err := c.cfg.Endpoint.PostJSONWithRetry(ctx, c.url(), body, &decoded, c.cfg.Retry, "embedding")
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("embedding API error: %s", decoded.Error.Message)
}
return api.PlaceEmbeddings(want, len(decoded.Data), func(i int) (int, []float32) {
if decoded.Data[i].Index == nil {
return i, decoded.Data[i].Embedding
}
return *decoded.Data[i].Index, decoded.Data[i].Embedding
})
}
@@ -0,0 +1,377 @@
package openaiembeddings
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// arkTextResponse is the response example from Volcengine's text embedding
// reference (POST /api/v3/embeddings), now filed under its retired
// documentation: https://docs.volcengine.com/docs/ark/TextVectorizationAPI
//
// It is the OpenAI shape exactly — data is an array whose elements carry an
// index — which is why rows that still name a doubao-embedding text model
// speak this protocol rather than Ark's multimodal one.
const arkTextResponse = `{
"created": 1743575029,
"id": "0217435750294",
"data": [
{"embedding": [0.11, 0.12], "index": 0, "object": "embedding"},
{"embedding": [0.21, 0.22], "index": 1, "object": "embedding"}
],
"model": "doubao-embedding-text-240515",
"object": "list",
"usage": {"prompt_tokens": 7, "total_tokens": 7}
}`
// nimResponse is the response shape of NVIDIA's embedding reference:
// https://docs.api.nvidia.com/nim/reference/nvidia-nv-embedqa-e5-v5-infer
const nimResponse = `{
"object": "list",
"data": [{"object": "embedding", "embedding": [0.5, 0.6], "index": 0}],
"model": "nvidia/nv-embedqa-e5-v5",
"usage": {"prompt_tokens": 4, "total_tokens": 4}
}`
func newClient(url string, settings api.EmbeddingsSettings, dims int) *Client {
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: "m", Auth: api.BearerAuth("k")},
Settings: settings,
Dimensions: dims,
Retry: api.RetryPolicy{},
})
}
func serve(t *testing.T, payload string) (*httptest.Server, *string, *map[string]any) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
path, body := new(string), new(map[string]any)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
*path = r.URL.Path
_ = json.NewDecoder(r.Body).Decode(body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(payload))
}))
return server, path, body
}
// The baseline sends model and input and nothing else: those are the only two
// fields every vendor in the catalog documents.
func TestBaselineSendsOnlyModelAndInput(t *testing.T) {
c := newClient("https://example.invalid/v1", api.EmbeddingsSettings{}, 1024)
body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.Equal(t, map[string]any{"model": "m", "input": []string{"a"}}, body,
"a width the row asked for must not be sent to a vendor that names no field for it")
}
// NIM documents no `dimensions`, requires `input_type` and defaults
// `truncate` to NONE, which fails a request on over-long input.
func TestNIMRequestMatchesItsReference(t *testing.T) {
c := newClient("https://integrate.api.nvidia.com/v1", api.EmbeddingsSettings{
SendEncodingFormat: true,
InputTypeField: "input_type",
InputTypeValues: map[string]string{"document": "passage", "query": "query"},
TruncateField: "truncate",
TruncateValue: "END",
}, 1024)
doc := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.Equal(t, "passage", doc["input_type"])
assert.Equal(t, "END", doc["truncate"])
assert.Equal(t, "float", doc["encoding_format"])
assert.NotContains(t, doc, "dimensions", "NIM's schema has no dimensions field")
assert.Equal(t, "query", c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["input_type"])
}
// Jina spells the same idea `task`, and its truncate is a boolean.
func TestJinaRequestMatchesItsReference(t *testing.T) {
c := newClient("https://api.jina.ai/v1", api.EmbeddingsSettings{
DimensionsField: "dimensions",
InputTypeField: "task",
InputTypeValues: map[string]string{"document": "retrieval.passage", "query": "retrieval.query"},
TruncateField: "truncate",
TruncateValue: "true",
}, 512)
body := c.BuildRequestBody([]string{"a"}, api.EmbedDocument)
assert.Equal(t, "retrieval.passage", body["task"])
assert.Equal(t, true, body["truncate"], "a boolean, not the string \"true\"")
assert.Equal(t, 512, body["dimensions"])
assert.Equal(t, "retrieval.query", c.BuildRequestBody([]string{"q"}, api.EmbedQuery)["task"])
}
// truncate_prompt_tokens is a vLLM extension. It appears in no managed
// vendor's schema and used to be sent to every one of them, hardcoded to 511.
func TestTruncatePromptTokensReachesOnlyVLLMClassRuntimes(t *testing.T) {
managed := newClient("https://api.openai.com/v1", api.EmbeddingsSettings{
TruncatePromptTokens: 511,
}, 0)
assert.NotContains(t, managed.BuildRequestBody([]string{"a"}, api.EmbedDocument), "truncate_prompt_tokens")
vllm := newClient("http://vllm.internal/v1", api.EmbeddingsSettings{
AcceptsTruncatePromptTokens: true, TruncatePromptTokens: 512,
}, 0)
assert.Equal(t, 512, vllm.BuildRequestBody([]string{"a"}, api.EmbedDocument)["truncate_prompt_tokens"])
}
// vLLM's multimodal embedding example sends one user turn in `messages`:
// the image part, then the instruction its chat template expects. The rest
// of the body is the same as for `input`.
func TestVLLMImageMessageMatchesItsExample(t *testing.T) {
c := newClient("http://vllm.internal/v1", api.EmbeddingsSettings{
SendEncodingFormat: true, AcceptsTruncatePromptTokens: true, TruncatePromptTokens: 512,
ImageFormat: api.EmbeddingImageMessages, ImagePrompt: "Represent the given image.",
}, 0)
require.True(t, c.AcceptsImages())
body := c.BuildImageMessageBody(api.EmbedImage{Data: []byte{0x89}, MIMEType: "image/png"}, api.EmbedDocument)
assert.Equal(t, map[string]any{
"model": "m", "encoding_format": "float", "truncate_prompt_tokens": 512,
"messages": []any{map[string]any{"role": "user", "content": []any{
map[string]any{"type": "image_url", "image_url": map[string]any{"url": "data:image/png;base64,iQ=="}},
map[string]any{"type": "text", "text": "Represent the given image."},
}}},
}, body)
bare := newClient("http://vllm.internal/v1", api.EmbeddingsSettings{ImageFormat: api.EmbeddingImageMessages}, 0)
content := bare.BuildImageMessageBody(
api.EmbedImage{Data: []byte{0x89}, MIMEType: "image/png"}, api.EmbedDocument,
)["messages"].([]any)[0].(map[string]any)["content"]
assert.Len(t, content, 1, "no prompt configured, so the image goes alone")
}
// The object format needs a field name; without one there is no image input.
func TestImageFormatDecidesWhetherImagesAreAccepted(t *testing.T) {
assert.False(t, newClient("u", api.EmbeddingsSettings{}, 0).AcceptsImages())
assert.False(t, newClient("u", api.EmbeddingsSettings{ImageFormat: api.EmbeddingImageObject}, 0).AcceptsImages())
assert.True(t, newClient("u", api.EmbeddingsSettings{
ImageInput: api.ImageInput{ImageField: "image"},
}, 0).AcceptsImages())
assert.True(t, newClient("u", api.EmbeddingsSettings{ImageFormat: api.EmbeddingImageMessages}, 0).AcceptsImages())
}
// Endpoints without batch_messages keep one request per conversation, and
// texts follow images into messages only when the row asks.
func TestMessagesFormatSendsOneRequestPerItem(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var bodies []map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
_ = json.NewDecoder(r.Body).Decode(&body)
bodies = append(bodies, body)
if input, ok := body["input"].([]any); ok {
parts := make([]string, len(input))
for i := range input {
parts[i] = fmt.Sprintf(`{"embedding":[0],"index":%d}`, i)
}
_, _ = fmt.Fprintf(w, `{"data":[%s]}`, strings.Join(parts, ","))
return
}
_, _ = fmt.Fprintf(w, `{"data":[{"embedding":[%d],"index":0}]}`, len(bodies))
}))
defer server.Close()
c := newClient(server.URL+"/v1", api.EmbeddingsSettings{ImageFormat: api.EmbeddingImageMessages}, 0)
got, err := c.EmbedImages(context.Background(), []api.EmbedImage{
{Data: []byte{1}, MIMEType: "image/png"}, {Data: []byte{2}, MIMEType: "image/png"},
}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got)
require.Len(t, bodies, 2)
assert.Contains(t, bodies[0], "messages")
assert.NotContains(t, bodies[0], "input")
bodies = nil
_, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedQuery)
require.NoError(t, err)
require.Len(t, bodies, 1, "texts stay in one `input` request unless the row opts in")
assert.Equal(t, []any{"a", "b"}, bodies[0]["input"])
bodies = nil
c = newClient(server.URL+"/v1", api.EmbeddingsSettings{
ImageFormat: api.EmbeddingImageMessages, TextAsMessages: true,
}, 0)
got, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedQuery)
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got)
require.Len(t, bodies, 2)
assert.Equal(t, []any{map[string]any{"role": "user", "content": []any{
map[string]any{"type": "text", "text": "a"},
}}}, bodies[0]["messages"])
}
func TestBatchMessagesPreservesInputsAndRequestSettings(t *testing.T) {
for _, images := range []bool{false, true} {
t.Run(fmt.Sprintf("images=%v", images), func(t *testing.T) {
var bodies []map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var body map[string]any
require.NoError(t, json.NewDecoder(r.Body).Decode(&body))
bodies = append(bodies, body)
_, _ = w.Write([]byte(`{"data":[{"index":1,"embedding":[2]},{"index":0,"embedding":[1]}]}`))
}))
defer server.Close()
c := newClient(server.URL+"/v1", api.EmbeddingsSettings{
BatchMessages: true, TextAsMessages: true, ImageFormat: api.EmbeddingImageMessages,
ImagePrompt: "Represent the image.", SendEncodingFormat: true,
InputTypeField: "input_type", InputTypeValues: map[string]string{"query": "query"},
ExtraBody: map[string]any{"add_special_tokens": true},
}, 0)
var got [][]float32
var err error
if images {
got, err = c.EmbedImages(context.Background(), []api.EmbedImage{
{Data: []byte{1}, MIMEType: "image/png"}, {Data: []byte{2}, MIMEType: "image/png"},
}, api.EmbedQuery)
} else {
got, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedQuery)
}
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got, "response indices restore input order")
require.Len(t, bodies, 1)
body := bodies[0]
assert.NotContains(t, body, "input")
assert.Equal(t, true, body["add_special_tokens"])
assert.Equal(t, "float", body["encoding_format"])
assert.Equal(t, "query", body["input_type"])
conversations := body["messages"].([]any)
require.Len(t, conversations, 2)
for i, conv := range conversations {
messages := conv.([]any)
require.Len(t, messages, 1)
turn := messages[0].(map[string]any)
assert.Equal(t, "user", turn["role"])
content := turn["content"].([]any)
if images {
require.Len(t, content, 2)
assert.Equal(t, api.EmbedImage{Data: []byte{byte(i + 1)}, MIMEType: "image/png"}.DataURI(),
content[0].(map[string]any)["image_url"].(map[string]any)["url"])
assert.Equal(t, "Represent the image.", content[1].(map[string]any)["text"])
} else {
require.Len(t, content, 1)
assert.Equal(t, []string{"a", "b"}[i], content[0].(map[string]any)["text"])
}
}
})
}
}
func TestBatchMessagesEmptySingletonAndInvalidResponses(t *testing.T) {
server, _, body := serve(t, `{"data":[{"index":0,"embedding":[1]}]}`)
defer server.Close()
c := newClient(server.URL, api.EmbeddingsSettings{TextAsMessages: true, BatchMessages: true}, 0)
got, err := c.Embed(context.Background(), nil, api.EmbedDocument)
require.NoError(t, err)
assert.Nil(t, got)
assert.Nil(t, *body, "empty input sends no request")
_, err = c.Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.NoError(t, err)
assert.IsType(t, map[string]any{}, (*body)["messages"].([]any)[0], "singleton keeps a flat conversation")
_, err = c.Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.ErrorContains(t, err, "no embedding returned for input 1",
"never accept a fused or incomplete batch response")
}
func TestDecodesArkTextResponse(t *testing.T) {
server, path, body := serve(t, arkTextResponse)
defer server.Close()
c := newClient(server.URL+"/api/v3", api.EmbeddingsSettings{SendEncodingFormat: true}, 0)
got, err := c.Embed(context.Background(), []string{"天很蓝", "海很深"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{0.11, 0.12}, {0.21, 0.22}}, got)
assert.Equal(t, "/api/v3/embeddings", *path)
assert.NotContains(t, *body, "dimensions", "Ark's text endpoint documents no dimensions")
}
func TestDecodesNIMResponse(t *testing.T) {
server, _, _ := serve(t, nimResponse)
defer server.Close()
c := newClient(server.URL+"/v1", api.EmbeddingsSettings{}, 0)
got, err := c.Embed(context.Background(), []string{"a"}, api.EmbedQuery)
require.NoError(t, err)
assert.Equal(t, [][]float32{{0.5, 0.6}}, got)
}
// A vendor may answer out of order; the index decides the slot.
func TestOutOfOrderIndicesArePlacedByIndex(t *testing.T) {
server, _, _ := serve(t, `{"data":[
{"embedding":[2],"index":1},
{"embedding":[1],"index":0}
]}`)
defer server.Close()
got, err := newClient(server.URL, api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}}, got)
}
// A server that answers in order without an index is read positionally, as
// the pre-catalog client read it, rather than as every vector claiming 0.
func TestReplyWithoutIndicesIsReadInOrder(t *testing.T) {
server, _, _ := serve(t, `{"data":[{"embedding":[1]},{"embedding":[2]},{"embedding":[3]}]}`)
defer server.Close()
got, err := newClient(server.URL, api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a", "b", "c"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, [][]float32{{1}, {2}, {3}}, got)
}
// An index that is present but repeated is still refused: that reply really
// does leave an input without its vector.
func TestRepeatedIndexIsStillAnError(t *testing.T) {
server, _, _ := serve(t, `{"data":[{"embedding":[1],"index":0},{"embedding":[2],"index":0}]}`)
defer server.Close()
_, err := newClient(server.URL, api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
assert.Error(t, err)
}
// A reply covering fewer inputs than were sent would store an empty vector.
func TestShortReplyIsAnError(t *testing.T) {
server, _, _ := serve(t, `{"data":[{"embedding":[1],"index":0}]}`)
defer server.Close()
_, err := newClient(server.URL, api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a", "b"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "no embedding returned for input 1")
}
func TestDoesNotDoubleTheEmbeddingsPath(t *testing.T) {
server, path, _ := serve(t, `{"data":[{"embedding":[1],"index":0}]}`)
defer server.Close()
_, err := newClient(server.URL+"/openai/v1/embeddings", api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.NoError(t, err)
assert.Equal(t, "/openai/v1/embeddings", *path)
}
func TestSurfacesTheVendorErrorBody(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":{"message":"input exceeds 4096 characters"}}`))
}))
defer server.Close()
_, err := newClient(server.URL, api.EmbeddingsSettings{}, 0).
Embed(context.Background(), []string{"a"}, api.EmbedDocument)
require.Error(t, err)
assert.Contains(t, err.Error(), "input exceeds 4096 characters")
}
@@ -0,0 +1,554 @@
package openairesponses
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"academy/internal/logger"
"academy/internal/models/api"
"academy/internal/types"
)
const defaultPath = "/responses"
// Client talks the Responses protocol to one endpoint.
type Client struct {
cfg Config
}
// New creates a client. The endpoint must already carry auth and headers.
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 settings (diagnostics, tests).
func (c *Client) Settings() Config { return c.cfg }
func (c *Client) url() string { return c.cfg.Endpoint.Resolve(defaultPath) }
func (c *Client) send(
ctx context.Context, messages []api.Message, opts *api.Options, stream bool,
) (*http.Response, []byte, error) {
opts = api.WithSessionCacheKey(ctx, opts)
body, err := c.BuildRequestBody(messages, opts, stream)
if err != nil {
return nil, nil, err
}
url := c.url()
req, data, err := c.cfg.Endpoint.NewRequest(ctx, url, body, stream)
if err != nil {
return nil, nil, err
}
if c.cfg.Settings.PromptCacheKey {
key := c.cfg.SessionID
if opts != nil && opts.PromptCacheKey != "" {
key = opts.PromptCacheKey
}
api.AttachSessionAffinityHeaders(req, api.ClampPromptCacheKey(key))
}
api.LogRequest(ctx, url, c.cfg.Endpoint.Model, data, stream)
resp, err := c.cfg.Endpoint.Do(req)
if err != nil {
return nil, data, err
}
return resp, data, nil
}
// Chat performs a non-streaming response creation.
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 {
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, fmt.Errorf("create response: %w", err)
}
}
defer func() { _ = resp.Body.Close() }()
raw, err := api.ReadResponseCapped(resp.Body, 0)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
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 response creation.
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, data, 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, data, err = c.send(ctx, api.StripImagesFromMessages(messages), opts, true)
}
if err != nil {
cancel()
return nil, fmt.Errorf("create response stream: %w", err)
}
}
ch := make(chan types.StreamResponse)
dumper := api.NewStreamPacketDumper(c.cfg.Endpoint.Model, json.RawMessage(data))
if dumper != nil {
logger.Infof(ctx, "[LLM Stream Raw Dump] writing packets to %s", dumper.Path())
}
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
}
// --- response decoding ---
type rawContentPart struct {
Type string `json:"type"`
Text string `json:"text"`
}
// rawOutputItem is the union of the output item shapes this package reads:
// message, function_call and reasoning.
type rawOutputItem struct {
Type string `json:"type"`
ID json.RawMessage `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
Content []rawContentPart `json:"content,omitempty"`
CallID string `json:"call_id,omitempty"`
Name string `json:"name,omitempty"`
Arguments string `json:"arguments,omitempty"`
Summary []rawContentPart `json:"summary,omitempty"`
}
type rawUsage struct {
InputTokens int `json:"input_tokens"`
OutputTokens int `json:"output_tokens"`
TotalTokens int `json:"total_tokens"`
InputTokensDetails *struct {
CachedTokens int `json:"cached_tokens"`
} `json:"input_tokens_details,omitempty"`
}
func (u rawUsage) toTokenUsage() types.TokenUsage {
out := types.TokenUsage{
PromptTokens: u.InputTokens,
CompletionTokens: u.OutputTokens,
TotalTokens: u.TotalTokens,
}
if out.TotalTokens == 0 {
out.TotalTokens = out.PromptTokens + out.CompletionTokens
}
if u.InputTokensDetails != nil {
cached := u.InputTokensDetails.CachedTokens
out.SetPromptCacheUsage(cached, 0, max(0, u.InputTokens-cached), true)
} else {
out.SetPromptCacheUsage(0, 0, 0, false)
}
return out
}
type rawError struct {
Code any `json:"code,omitempty"`
Message string `json:"message"`
}
type rawResponse struct {
ID string `json:"id,omitempty"`
Status string `json:"status,omitempty"`
IncompleteDetails *struct {
Reason string `json:"reason"`
} `json:"incomplete_details,omitempty"`
Output []json.RawMessage `json:"output,omitempty"`
Usage *rawUsage `json:"usage,omitempty"`
Error *rawError `json:"error,omitempty"`
}
// finishReason maps the response status onto the Chat Completions
// vocabulary the rest of the engine understands.
func (r *rawResponse) finishReason(hasToolCalls bool) string {
if hasToolCalls {
return "tool_calls"
}
if r != nil && r.Status == "incomplete" && r.IncompleteDetails != nil {
switch r.IncompleteDetails.Reason {
case "max_output_tokens":
return "length"
case "content_filter":
return "content_filter"
}
}
return "stop"
}
func decodeItem(raw json.RawMessage) (rawOutputItem, error) {
var item rawOutputItem
if err := json.Unmarshal(raw, &item); err != nil {
return rawOutputItem{}, fmt.Errorf("decode output item: %w", err)
}
return item, nil
}
// streamItem decodes the item carried by an output_item event. An event that
// carries no item at all is simply nothing to decode, but an item we cannot
// read is lost output, possibly a whole function_call, so the caller must
// surface it instead of moving on.
func streamItem(raw json.RawMessage) (rawOutputItem, bool, error) {
if len(raw) == 0 {
return rawOutputItem{}, false, nil
}
item, err := decodeItem(raw)
if err != nil {
return rawOutputItem{}, false, err
}
return item, true, nil
}
func itemText(item rawOutputItem) string {
var b strings.Builder
for _, part := range item.Content {
if part.Type == "output_text" {
b.WriteString(part.Text)
}
}
return b.String()
}
func itemSummary(item rawOutputItem) string {
texts := make([]string, 0, len(item.Summary))
for _, part := range item.Summary {
if part.Text != "" {
texts = append(texts, part.Text)
}
}
return strings.Join(texts, "\n")
}
func toolCallMetadata(item rawOutputItem) types.ToolCallMetadata {
if len(item.ID) == 0 || string(item.ID) == "null" {
return nil
}
return types.ToolCallMetadata{metadataToolCallItemID: item.ID}
}
func reasoningMetadata(items []json.RawMessage) types.ProviderMetadata {
if len(items) == 0 {
return nil
}
merged, err := json.Marshal(items)
if err != nil {
return nil
}
return types.ProviderMetadata{metadataReasoningItems: merged}
}
func (c *Client) parseResponse(raw []byte) (*types.ChatResponse, error) {
var env rawResponse
if err := json.Unmarshal(raw, &env); err != nil {
return nil, fmt.Errorf("decode response: %w", err)
}
if env.Error != nil && env.Error.Message != "" {
return nil, fmt.Errorf("API error: %s", env.Error.Message)
}
if env.Status == "failed" {
return nil, fmt.Errorf("API error: response failed")
}
result := &types.ChatResponse{}
var content, reasoning []string
var reasoningItems []json.RawMessage
for _, rawItem := range env.Output {
// An output item we cannot read may be the round's tool call. Dropping
// it hands the agent what looks like a plain answer, so fail instead.
item, err := decodeItem(rawItem)
if err != nil {
return nil, err
}
switch item.Type {
case "message":
content = append(content, itemText(item))
case "function_call":
result.ToolCalls = append(result.ToolCalls, types.LLMToolCall{
ID: item.CallID,
Type: "function",
Function: types.FunctionCall{Name: item.Name, Arguments: item.Arguments},
ProviderMetadata: toolCallMetadata(item),
})
case "reasoning":
if summary := itemSummary(item); summary != "" {
reasoning = append(reasoning, summary)
}
reasoningItems = append(reasoningItems, rawItem)
}
}
result.Content = strings.Join(content, "")
result.ReasoningContent = strings.Join(reasoning, "\n")
result.ReasoningMetadata = reasoningMetadata(reasoningItems)
result.FinishReason = env.finishReason(len(result.ToolCalls) > 0)
// Classify the cache status even without a usage block, so an empty
// CacheStatus never reaches the usage dashboards as a silent miss.
usage := rawUsage{}
if env.Usage != nil {
usage = *env.Usage
}
result.Usage = usage.toTokenUsage()
return result, nil
}
// --- streaming ---
// rawStreamEvent is the union of the fields this package reads from the
// Responses SSE events. Every event carries "type".
type rawStreamEvent struct {
Type string `json:"type"`
Delta string `json:"delta,omitempty"`
ItemID string `json:"item_id,omitempty"`
OutputIndex int `json:"output_index,omitempty"`
SummaryIndex int `json:"summary_index,omitempty"`
Item json.RawMessage `json:"item,omitempty"`
Response *rawResponse `json:"response,omitempty"`
// Message/Code are set on the top-level "error" event.
Message string `json:"message,omitempty"`
Code any `json:"code,omitempty"`
}
// streamState tracks the function_call items seen so far so argument deltas
// can be routed to the assembler index that announced the call.
type streamState struct {
toolIndex map[string]int // item id -> assembler index
argsSeen map[string]bool
nextToolIndex int
reasoningItems []json.RawMessage
}
func (st *streamState) indexFor(itemID string) int {
if idx, ok := st.toolIndex[itemID]; ok {
return idx
}
idx := st.nextToolIndex
st.nextToolIndex++
st.toolIndex[itemID] = idx
return idx
}
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)
reader := api.NewSSEReader(body)
st := &streamState{toolIndex: map[string]int{}, argsSeen: map[string]bool{}}
// response.completed / response.incomplete return before either caller,
// so reaching finish means the terminal event never arrived.
finish := func() {
assembler.ReasoningMetadata = reasoningMetadata(st.reasoningItems)
assembler.EndAtEOF(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 {
continue
}
if event.Done {
finish()
return
}
if len(event.Data) == 0 {
continue
}
if dumper != nil {
raw := make([]byte, len(event.Data))
copy(raw, event.Data)
dumper.WritePacketRaw(raw)
}
var ev rawStreamEvent
if err := json.Unmarshal(event.Data, &ev); err != nil {
// An event whose *type* we do not know is routine and the switch
// below already ignores it. A payload that is not JSON at all is
// not: it is a truncated frame or a gateway error page, i.e. a
// hole in the answer. Skipping it runs the loop to EOF, which the
// caller cannot tell from a complete reply and then stores as the
// model's answer. Fail, as the Completions loop does.
assembler.Fail(ch, fmt.Errorf("decode stream chunk: %w", err))
return
}
switch ev.Type {
case "response.output_text.delta":
if ev.Delta != "" {
assembler.Process(ch, api.Delta{Content: ev.Delta})
}
case "response.reasoning_summary_text.delta", "response.reasoning_text.delta":
if ev.Delta != "" {
assembler.Process(ch, api.Delta{Reasoning: ev.Delta})
}
case "response.reasoning_summary_part.added":
// Mirror the non-stream join of summary parts with a newline.
if ev.SummaryIndex > 0 {
assembler.Process(ch, api.Delta{Reasoning: "\n"})
}
case "response.output_item.added":
item, ok, err := streamItem(ev.Item)
if err != nil {
assembler.Fail(ch, err)
return
}
if !ok || item.Type != "function_call" {
continue
}
itemID := streamItemID(item, ev.OutputIndex)
idx := st.indexFor(itemID)
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: idx, ID: item.CallID, Type: "function", Name: item.Name,
}}})
assembler.SetToolCallMetadata(idx, toolCallMetadata(item))
case "response.function_call_arguments.delta":
if ev.Delta == "" {
continue
}
// Correlate on the same key output_item.added registered. Vendors
// that omit item ids would otherwise send every call's arguments
// to the single index keyed by "", merging distinct tool calls.
key := streamEventKey(ev.ItemID, ev.OutputIndex)
st.argsSeen[key] = true
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: st.indexFor(key), Arguments: ev.Delta,
}}})
case "response.output_item.done":
item, ok, err := streamItem(ev.Item)
if err != nil {
assembler.Fail(ch, err)
return
}
if !ok {
continue
}
switch item.Type {
case "reasoning":
st.reasoningItems = append(st.reasoningItems, ev.Item)
case "function_call":
// Providers that never stream argument deltas deliver the
// arguments only on the done item.
itemID := streamItemID(item, ev.OutputIndex)
if !st.argsSeen[itemID] && item.Arguments != "" {
st.argsSeen[itemID] = true
assembler.Process(ch, api.Delta{ToolCalls: []api.ToolCallDelta{{
Index: st.indexFor(itemID), ID: item.CallID, Type: "function",
Name: item.Name, Arguments: item.Arguments,
}}})
assembler.SetToolCallMetadata(st.indexFor(itemID), toolCallMetadata(item))
}
}
case "response.completed", "response.incomplete":
c.completeStream(ch, assembler, st, ev.Response, ev.Type == "response.incomplete")
return
case "response.failed":
msg := "response failed"
if ev.Response != nil && ev.Response.Error != nil && ev.Response.Error.Message != "" {
msg = ev.Response.Error.Message
}
assembler.Fail(ch, fmt.Errorf("API stream error: %s", msg))
return
case "error":
assembler.Fail(ch, fmt.Errorf("API stream error: %s", orDefault(ev.Message, "unknown error")))
return
}
}
}
// streamItemID returns the item id used to correlate added/delta/done
// events, falling back to the output index when the vendor omits ids.
func streamItemID(item rawOutputItem, outputIndex int) string {
var id string
if len(item.ID) > 0 {
_ = json.Unmarshal(item.ID, &id)
}
return streamEventKey(id, outputIndex)
}
// streamEventKey is the correlation key for one output item: its id when the
// vendor sends one, otherwise its position in the output list.
func streamEventKey(itemID string, outputIndex int) string {
if itemID != "" {
return itemID
}
return fmt.Sprintf("output_index:%d", outputIndex)
}
// completeStream handles the terminal response.completed / response.incomplete
// event: usage, finish reason, reasoning artifacts and the closing chunks.
func (c *Client) completeStream(
ch chan<- types.StreamResponse, assembler *api.StreamAssembler, st *streamState, resp *rawResponse, incomplete bool,
) {
if resp != nil {
if resp.Usage != nil {
assembler.SetUsage(resp.Usage.toTokenUsage())
}
// Fall back to the final response body for reasoning items when the
// vendor never emitted output_item.done for them.
if len(st.reasoningItems) == 0 {
for _, rawItem := range resp.Output {
// Tolerated on purpose, unlike the item events above: the
// deltas already carried the answer and its tool calls, so an
// unreadable item here costs at most a reasoning artifact.
if item, err := decodeItem(rawItem); err == nil && item.Type == "reasoning" {
st.reasoningItems = append(st.reasoningItems, rawItem)
}
}
}
}
finishReason := resp.finishReason(assembler.ToolCallCount() > 0)
if incomplete && finishReason == "stop" {
finishReason = "length"
}
assembler.Process(ch, api.Delta{FinishReason: finishReason})
assembler.ReasoningMetadata = reasoningMetadata(st.reasoningItems)
assembler.End(ch)
}
@@ -0,0 +1,702 @@
package openairesponses
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"academy/internal/models/api"
"academy/internal/types"
)
func newTestClient(t *testing.T, server *httptest.Server, reasoning bool) *Client {
t.Helper()
ep := api.Endpoint{
Model: "gpt-5",
ModelID: "model-1",
Auth: api.BearerAuth("sk-test"),
}
if server != nil {
ep.BaseURL = server.URL
ep.Client = server.Client()
} else {
ep.BaseURL = "https://api.openai.com/v1"
}
return New(Config{
Endpoint: ep,
Settings: api.DefaultOpenAIResponses(),
Reasoning: reasoning,
SessionID: "session-fallback",
})
}
// roundTrip marshals and re-decodes the body so struct-typed values compare
// as plain JSON.
func roundTrip(t *testing.T, body map[string]any) map[string]any {
t.Helper()
data, err := json.Marshal(body)
if err != nil {
t.Fatalf("marshal body: %v", err)
}
var out map[string]any
if err := json.Unmarshal(data, &out); err != nil {
t.Fatalf("unmarshal body: %v", err)
}
return out
}
func conversation() []api.Message {
return []api.Message{
{Role: "system", Content: "You are a weather assistant."},
{Role: "user", Content: "What's the weather in Paris?"},
{
Role: "assistant",
ToolCalls: []api.ToolCall{{
ID: "call_1",
Type: "function",
Function: api.FunctionCall{
Name: "get_weather",
Arguments: `{"city":"Paris"}`,
},
ProviderMetadata: types.ToolCallMetadata{
"openai_responses_item_id": json.RawMessage(`"fc_1"`),
},
}},
ReasoningMetadata: types.ProviderMetadata{
"openai_responses_reasoning": json.RawMessage(
`[{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"enc-abc"}]`),
},
},
{Role: "tool", ToolCallID: "call_1", Name: "get_weather", Content: "Sunny, 24C"},
}
}
func TestBuildRequestBodyGolden(t *testing.T) {
c := newTestClient(t, nil, true)
opts := &api.Options{
Temperature: 0.7,
MaxCompletionTokens: 1000,
ReasoningEffort: api.ReasoningHigh,
PromptCacheKey: "cache-key-1",
Tools: []api.Tool{{
Type: "function",
Function: api.FunctionDef{
Name: "get_weather",
Description: "Get weather",
Parameters: json.RawMessage(`{"type":"object","properties":{"city":{"type":"string"}}}`),
},
}},
ToolChoice: "auto",
}
body, err := c.BuildRequestBody(conversation(), opts, false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
got := roundTrip(t, body)
want := map[string]any{
"model": "gpt-5",
"store": false,
"instructions": "You are a weather assistant.",
"input": []any{
map[string]any{"type": "message", "role": "user", "content": "What's the weather in Paris?"},
map[string]any{"type": "reasoning", "id": "rs_1", "summary": []any{}, "encrypted_content": "enc-abc"},
map[string]any{
"type": "function_call", "id": "fc_1", "call_id": "call_1",
"name": "get_weather", "arguments": `{"city":"Paris"}`,
},
map[string]any{"type": "function_call_output", "call_id": "call_1", "output": "Sunny, 24C"},
},
"max_output_tokens": float64(1000),
"tools": []any{
map[string]any{
"type": "function",
"name": "get_weather",
"description": "Get weather",
"parameters": map[string]any{
"type": "object", "properties": map[string]any{"city": map[string]any{"type": "string"}},
},
},
},
"tool_choice": "auto",
"reasoning": map[string]any{"effort": "high", "summary": "auto"},
"include": []any{"reasoning.encrypted_content"},
"prompt_cache_key": "cache-key-1",
}
wantJSON, _ := json.Marshal(want)
gotJSON, _ := json.Marshal(got)
if string(wantJSON) != string(gotJSON) {
t.Fatalf("body mismatch\n got: %s\nwant: %s", gotJSON, wantJSON)
}
for _, absent := range []string{"temperature", "stream", "messages", "frequency_penalty", "presence_penalty"} {
if _, ok := got[absent]; ok {
t.Errorf("unexpected key %q in body", absent)
}
}
}
func TestBuildRequestBodyNonReasoningStream(t *testing.T) {
c := newTestClient(t, nil, false)
c.cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
off := false
opts := &api.Options{
Temperature: 0.3,
TopP: 0.9,
Thinking: &off,
CacheRetention: api.CacheRetentionLong,
MaxTokens: 4,
Format: json.RawMessage(`{"type":"object"}`),
}
body, err := c.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, opts, true)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
got := roundTrip(t, body)
if got["stream"] != true {
t.Errorf("stream = %v, want true", got["stream"])
}
if got["temperature"] != 0.3 || got["top_p"] != 0.9 {
t.Errorf("sampling = %v / %v", got["temperature"], got["top_p"])
}
if got["max_output_tokens"] != float64(16) {
t.Errorf("max_output_tokens = %v, want 16 (minimum)", got["max_output_tokens"])
}
if got["prompt_cache_key"] != "session-fallback" {
t.Errorf("prompt_cache_key = %v", got["prompt_cache_key"])
}
if got["prompt_cache_retention"] != "24h" {
t.Errorf("prompt_cache_retention = %v", got["prompt_cache_retention"])
}
if _, ok := got["include"]; ok {
t.Errorf("include must not be sent for non-reasoning models")
}
reasoning, _ := got["reasoning"].(map[string]any)
if reasoning["effort"] != "none" {
t.Errorf("reasoning = %v, want effort none", got["reasoning"])
}
text, _ := got["text"].(map[string]any)
format, _ := text["format"].(map[string]any)
if format["type"] != "json_object" {
t.Errorf("text.format = %v", got["text"])
}
input, _ := got["input"].([]any)
if len(input) != 1 {
t.Fatalf("input = %v", got["input"])
}
msg := input[0].(map[string]any)
if content, _ := msg["content"].(string); !strings.HasSuffix(content, `Use this JSON schema: {"type":"object"}`) {
t.Errorf("schema hint not appended: %q", content)
}
}
func TestBuildRequestBodyOffWithoutMapping(t *testing.T) {
c := newTestClient(t, nil, false)
off := false
body, err := c.BuildRequestBody([]api.Message{{Role: "user", Content: "hi"}}, &api.Options{Thinking: &off}, false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
if _, ok := body["reasoning"]; ok {
t.Fatalf("reasoning must be omitted when off has no vendor value: %v", body["reasoning"])
}
}
func TestBuildRequestBodyImagesAndAuto(t *testing.T) {
c := newTestClient(t, nil, true)
on := true
msgs := []api.Message{{
Role: "user",
MultiContent: []api.MessageContentPart{
{Type: "text", Text: "Describe"},
{Type: "image_url", ImageURL: &api.ImageURL{URL: "https://example.com/a.png"}},
},
}}
body, err := c.BuildRequestBody(msgs, &api.Options{Thinking: &on}, false)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
got := roundTrip(t, body)
input := got["input"].([]any)
parts := input[0].(map[string]any)["content"].([]any)
if len(parts) != 2 {
t.Fatalf("parts = %v", parts)
}
img := parts[1].(map[string]any)
if img["type"] != "input_image" || img["image_url"] != "https://example.com/a.png" || img["detail"] != "auto" {
t.Errorf("image part = %v", img)
}
reasoning := got["reasoning"].(map[string]any)
if _, ok := reasoning["effort"]; ok {
t.Errorf("auto must not send effort: %v", reasoning)
}
if reasoning["summary"] != "auto" {
t.Errorf("reasoning summary = %v", reasoning)
}
}
func TestChatDecodesResponse(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var gotPath string
var gotHeaders http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotHeaders = r.Header.Clone()
_, _ = io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{
"id": "resp_1",
"status": "completed",
"output": [
{"type":"reasoning","id":"rs_1","summary":[{"type":"summary_text","text":"Think A"},
{"type":"summary_text","text":"Think B"}],"encrypted_content":"enc"},
{"type":"message","id":"msg_1","role":"assistant","status":"completed",
"content":[{"type":"output_text","text":"Hello "},{"type":"output_text","text":"world"}]},
{"type":"function_call","id":"fc_1","call_id":"call_1","name":"get_weather",
"arguments":"{\"city\":\"Paris\"}","status":"completed"}
],
"usage": {"input_tokens": 100, "output_tokens": 20, "total_tokens": 120,
"input_tokens_details": {"cached_tokens": 60}}
}`))
}))
defer server.Close()
c := newTestClient(t, server, true)
resp, err := c.Chat(
context.Background(),
[]api.Message{{Role: "user", Content: "hi"}},
&api.Options{PromptCacheKey: "k1"},
)
if err != nil {
t.Fatalf("Chat: %v", err)
}
if gotPath != "/responses" {
t.Errorf("path = %q", gotPath)
}
if gotHeaders.Get("Authorization") != "Bearer sk-test" {
t.Errorf("auth header = %q", gotHeaders.Get("Authorization"))
}
if gotHeaders.Get("x-session-affinity") != "k1" {
t.Errorf("affinity header = %q", gotHeaders.Get("x-session-affinity"))
}
if resp.Content != "Hello world" {
t.Errorf("content = %q", resp.Content)
}
if resp.ReasoningContent != "Think A\nThink B" {
t.Errorf("reasoning = %q", resp.ReasoningContent)
}
if resp.FinishReason != "tool_calls" {
t.Errorf("finish = %q", resp.FinishReason)
}
if len(resp.ToolCalls) != 1 {
t.Fatalf("tool calls = %+v", resp.ToolCalls)
}
tc := resp.ToolCalls[0]
if tc.ID != "call_1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
tc.Function.Arguments != `{"city":"Paris"}` {
t.Errorf("tool call = %+v", tc)
}
if string(tc.ProviderMetadata["openai_responses_item_id"]) != `"fc_1"` {
t.Errorf("item id metadata = %s", tc.ProviderMetadata["openai_responses_item_id"])
}
var items []map[string]any
if err := json.Unmarshal(resp.ReasoningMetadata["openai_responses_reasoning"], &items); err != nil {
t.Fatalf("reasoning metadata: %v", err)
}
if len(items) != 1 || items[0]["id"] != "rs_1" || items[0]["encrypted_content"] != "enc" {
t.Errorf("reasoning items = %v", items)
}
u := resp.Usage
if u.PromptTokens != 100 || u.CompletionTokens != 20 || u.TotalTokens != 120 {
t.Errorf("usage = %+v", u)
}
if u.CacheReadTokens != 60 || u.CacheMissTokens != 40 || !u.CacheReported ||
u.CacheStatus != types.PromptCacheStatusHit {
t.Errorf("cache usage = %+v", u)
}
}
func TestChatIncompleteAndError(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
payload := `{"status":"incomplete","incomplete_details":{"reason":"max_output_tokens"},"output":` +
`[{"type":"message","content":[{"type":"output_text","text":"partial"}]}],` +
`"usage":{"input_tokens":1,"output_tokens":2}}`
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(payload))
}))
defer server.Close()
c := newTestClient(t, server, false)
resp, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("Chat: %v", err)
}
if resp.FinishReason != "length" || resp.Content != "partial" {
t.Errorf("resp = %+v", resp)
}
if resp.Usage.TotalTokens != 3 || resp.Usage.CacheReported ||
resp.Usage.CacheStatus != types.PromptCacheStatusUnreported {
t.Errorf("usage = %+v", resp.Usage)
}
payload = `{"error":{"type":"invalid_request_error","message":"bad model"}}`
_, err = c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err == nil || !strings.Contains(err.Error(), "bad model") {
t.Fatalf("expected API error, got %v", err)
}
}
func sseBody(events ...string) string {
var b strings.Builder
for _, ev := range events {
var probe struct {
Type string `json:"type"`
}
_ = json.Unmarshal([]byte(ev), &probe)
fmt.Fprintf(&b, "event: %s\ndata: %s\n\n", probe.Type, ev)
}
return b.String()
}
func TestChatStreamAssemblesToolCall(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(
`{"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
`{"type":"response.output_item.added","output_index":0,"item":{"type":"reasoning","id":"rs_1","summary":[]}}`,
`{"type":"response.reasoning_summary_text.delta",`+
`"item_id":"rs_1","output_index":0,"summary_index":0,"delta":"thinking..."}`,
`{"type":"response.output_item.done","output_index":0,"item":{"type":"reasoning",`+
`"id":"rs_1","summary":[{"type":"summary_text","text":"thinking..."}],"encrypted_content":"enc"}}`,
`{"type":"response.output_item.added","output_index":1,`+
`"item":{"type":"message","id":"msg_1","role":"assistant","content":[]}}`,
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":1,"delta":"Hello"}`,
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":1,"delta":" world"}`,
`{"type":"response.output_item.done","output_index":1,"item":{"type":"message",`+
`"id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"Hello world"}]}}`,
`{"type":"response.output_item.added","output_index":2,"item":{"type":"function_call",`+
`"id":"fc_1","call_id":"call_1","name":"get_weather","arguments":""}}`,
`{"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":2,"delta":"{\"city\":"}`,
`{"type":"response.function_call_arguments.delta","item_id":"fc_1","output_index":2,"delta":"\"Paris\"}"}`,
`{"type":"response.function_call_arguments.done",`+
`"item_id":"fc_1","output_index":2,"arguments":"{\"city\":\"Paris\"}"}`,
`{"type":"response.output_item.done","output_index":2,"item":{"type":"function_call","id":"fc_1","call_id":`+
`"call_1","name":"get_weather","arguments":"{\"city\":\"Paris\"}","status":"completed"}}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_to`+
`kens":50,"output_tokens":10,"total_tokens":60,"input_tokens_details":{"cached_tokens":0}}}}`,
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var req map[string]any
if err := json.Unmarshal(raw, &req); err != nil || req["stream"] != true {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, true)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var events []types.StreamResponse
for ev := range ch {
events = append(events, ev)
}
if len(events) == 0 {
t.Fatal("no events")
}
var thinking, answer string
var sawToolCallEvent, sawThinkingDone bool
for _, ev := range events {
switch ev.ResponseType {
case types.ResponseTypeThinking:
if ev.Done {
sawThinkingDone = true
} else {
thinking += ev.Content
}
case types.ResponseTypeAnswer:
answer += ev.Content
case types.ResponseTypeToolCall:
sawToolCallEvent = true
if ev.Data["tool_name"] != "get_weather" || ev.Data["tool_call_id"] != "call_1" {
t.Errorf("tool call event data = %v", ev.Data)
}
case types.ResponseTypeError:
t.Fatalf("unexpected error event: %s", ev.Content)
}
}
if thinking != "thinking..." || !sawThinkingDone {
t.Errorf("thinking = %q done=%t", thinking, sawThinkingDone)
}
if answer != "Hello world" {
t.Errorf("answer = %q", answer)
}
if !sawToolCallEvent {
t.Error("missing ResponseTypeToolCall event")
}
final := events[len(events)-1]
if final.ResponseType != types.ResponseTypeAnswer || !final.Done {
t.Fatalf("final event = %+v", final)
}
if final.Usage == nil || final.Usage.PromptTokens != 50 || final.Usage.CompletionTokens != 10 ||
final.Usage.TotalTokens != 60 || !final.Usage.CacheReported {
t.Errorf("final usage = %+v", final.Usage)
}
if final.FinishReason != "tool_calls" {
t.Errorf("final finish = %q", final.FinishReason)
}
if len(final.ToolCalls) != 1 {
t.Fatalf("final tool calls = %+v", final.ToolCalls)
}
tc := final.ToolCalls[0]
if tc.ID != "call_1" || tc.Type != "function" || tc.Function.Name != "get_weather" ||
tc.Function.Arguments != `{"city":"Paris"}` {
t.Errorf("assembled tool call = %+v", tc)
}
if string(tc.ProviderMetadata["openai_responses_item_id"]) != `"fc_1"` {
t.Errorf("item id metadata = %s", tc.ProviderMetadata["openai_responses_item_id"])
}
md, _ := final.Data["reasoning_metadata"].(types.ProviderMetadata)
var items []map[string]any
err = json.Unmarshal(md["openai_responses_reasoning"], &items)
if err != nil || len(items) != 1 || items[0]["encrypted_content"] != "enc" {
t.Errorf("reasoning metadata = %v (err %v)", final.Data, err)
}
}
func TestChatStreamFailedEvent(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(
`{"type":"response.output_text.delta","delta":"partial"}`,
`{"type":"response.failed","response":{"status":"failed","error":{"code":"server_error","message":"boom"}}}`,
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, false)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeError || !strings.Contains(last.Content, "boom") ||
last.FinishReason != types.FinishReasonIncomplete {
t.Fatalf("last event = %+v", last)
}
}
func TestOffLevelMapsToNone(t *testing.T) {
c := newTestClient(t, nil, true)
c.cfg.ThinkingLevels = api.ThinkingLevelMap{api.ReasoningOff: api.StringPtr("none")}
body, err := c.BuildRequestBody(
[]api.Message{{Role: "user", Content: "hi"}},
&api.Options{ReasoningEffort: api.ReasoningOff},
false,
)
if err != nil {
t.Fatalf("BuildRequestBody: %v", err)
}
reasoning, _ := body["reasoning"].(map[string]any)
if reasoning["effort"] != "none" {
t.Fatalf("reasoning = %v, want effort none", body["reasoning"])
}
if _, ok := reasoning["summary"]; ok {
t.Errorf("summary must not accompany an off request: %v", reasoning)
}
}
// Gateways that implement the Responses protocol without item ids exist.
// Correlating argument deltas by item_id alone routed every call's arguments
// to the single index keyed by "", merging two distinct tool calls into one
// and leaving the other with an empty argument string.
func TestChatStreamCorrelatesToolCallsWithoutItemIDs(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(
`{"type":"response.output_item.added","output_index":0,`+
`"item":{"type":"function_call","call_id":"call_a","name":"alpha","arguments":""}}`,
`{"type":"response.function_call_arguments.delta","output_index":0,"delta":"{\"a\":1}"}`,
`{"type":"response.output_item.added","output_index":1,`+
`"item":{"type":"function_call","call_id":"call_b","name":"beta","arguments":""}}`,
`{"type":"response.function_call_arguments.delta","output_index":1,"delta":"{\"b\":2}"}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
client := newTestClient(t, server, true)
ch, err := client.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var last types.StreamResponse
for chunk := range ch {
if chunk.ResponseType == types.ResponseTypeError {
t.Fatalf("unexpected error chunk: %s", chunk.Content)
}
if chunk.Done && chunk.ResponseType == types.ResponseTypeAnswer {
last = chunk
}
}
if len(last.ToolCalls) != 2 {
t.Fatalf("tool calls = %d (%#v), want 2", len(last.ToolCalls), last.ToolCalls)
}
want := []struct{ id, name, args string }{
{"call_a", "alpha", `{"a":1}`},
{"call_b", "beta", `{"b":2}`},
}
for i, w := range want {
got := last.ToolCalls[i]
if got.ID != w.id || got.Function.Name != w.name || got.Function.Arguments != w.args {
t.Fatalf("tool call %d = %+v, want id=%s name=%s args=%s", i, got, w.id, w.name, w.args)
}
}
}
// Responses is an event-typed protocol, so an event whose *type* we do not
// know is routine and the switch ignores it. A payload that is not JSON at
// all is a different animal: a truncated frame or a gateway error page.
// Skipping it ran the loop to EOF, which reached the caller as a complete
// answer and got stored as the model's reply.
func TestChatStreamUndecodableEventFailsTheStream(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"Hel"}`,
// An unknown but well-formed event type stays harmless.
`{"type":"response.web_search_call.in_progress","item_id":"ws_1","output_index":1}`,
) + "event: response.output_text.delta\ndata: <html>502 Bad Gateway</html>\n\n" +
sseBody(
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"lo"}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, false)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var answer string
var sawError bool
for ev := range ch {
if ev.ResponseType == types.ResponseTypeError {
sawError = true
if !strings.Contains(ev.Content, "decode stream chunk") {
t.Errorf("error content = %q", ev.Content)
}
continue
}
answer += ev.Content
}
if !sawError {
t.Error("a truncated stream must surface as an error, not as a short answer")
}
if answer != "Hel" {
t.Errorf("answer = %q, decoding must stop at the bad frame", answer)
}
}
// An output item that will not decode may be the round's function_call.
// Dropping it hands the agent a plain answer with nothing to act on.
func TestChatMalformedOutputItemIsAnError(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", "application/json")
_, _ = w.Write([]byte(`{"id":"resp_1","status":"completed","output":[` +
`{"type":"message","id":"msg_1","role":"assistant",` +
`"content":[{"type":"output_text","text":"done"}]},` +
`{"type":"function_call","id":"fc_1","call_id":"call_1","name":{"broken":true}}]}`))
}))
defer server.Close()
c := newTestClient(t, server, false)
_, err := c.Chat(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err == nil || !strings.Contains(err.Error(), "decode output item") {
t.Fatalf("expected a decode error, got %v", err)
}
}
// The streaming counterpart: an item event we cannot read fails the round
// instead of letting the tool call disappear from it.
func TestChatStreamMalformedOutputItemFailsTheStream(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(
`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"ok"}`,
`{"type":"response.output_item.added","output_index":1,`+
`"item":{"type":"function_call","id":"fc_1","call_id":"call_1","name":{"broken":true}}}`,
`{"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[]}}`,
)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, false)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var last types.StreamResponse
var answer string
for ev := range ch {
if ev.ResponseType != types.ResponseTypeError {
answer += ev.Content
}
last = ev
}
if last.ResponseType != types.ResponseTypeError || !strings.Contains(last.Content, "decode output item") {
t.Fatalf("last event = %+v", last)
}
if answer != "ok" {
t.Errorf("answer = %q, decoding must stop at the bad item", answer)
}
}
// response.completed is the only clean end of a Responses stream; a body that
// runs out before it was cut mid-answer and must not read as a stop.
func TestChatStreamEOFBeforeCompletedIsIncomplete(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
body := sseBody(`{"type":"response.output_text.delta","item_id":"msg_1","output_index":0,"delta":"Hel"}`)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(body))
}))
defer server.Close()
c := newTestClient(t, server, false)
ch, err := c.ChatStream(context.Background(), []api.Message{{Role: "user", Content: "hi"}}, nil)
if err != nil {
t.Fatalf("ChatStream: %v", err)
}
var last types.StreamResponse
for ev := range ch {
last = ev
}
if last.ResponseType != types.ResponseTypeAnswer || !last.Done ||
last.FinishReason != types.FinishReasonIncomplete {
t.Fatalf("last event = %+v", last)
}
}
@@ -0,0 +1,351 @@
// Package openairesponses implements the OpenAI Responses wire protocol
// (POST /responses). Every vendor-specific deviation is driven by
// api.OpenAIResponsesSettings; this package contains no vendor names.
package openairesponses
import (
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.OpenAIResponsesSettings
// ThinkingLevels maps neutral levels to the vendor vocabulary.
ThinkingLevels api.ThinkingLevelMap
// Reasoning marks a reasoning model: sampling parameters are dropped and
// encrypted reasoning items are requested where the vendor supports them.
Reasoning bool
// SessionID feeds prompt_cache_key when the caller sets none.
SessionID string
}
const (
// metadataReasoningItems is the ReasoningMetadata key carrying the raw
// reasoning output items (JSON array) so they can be replayed verbatim on
// the next turn.
metadataReasoningItems = "openai_responses_reasoning"
// metadataToolCallItemID is the ToolCallMetadata key carrying the
// function_call item id (raw JSON string) so replayed calls keep it.
metadataToolCallItemID = "openai_responses_item_id"
minMaxOutputTokens = 16
)
// --- input items ---
type inputMessage struct {
Type string `json:"type"`
Role string `json:"role"`
Content any `json:"content"`
}
type inputPart struct {
Type string `json:"type"`
Text string `json:"text,omitempty"`
ImageURL string `json:"image_url,omitempty"`
Detail string `json:"detail,omitempty"`
}
type functionCallItem struct {
Type string `json:"type"`
ID json.RawMessage `json:"id,omitempty"`
CallID string `json:"call_id"`
Name string `json:"name"`
Arguments string `json:"arguments"`
}
type functionCallOutputItem struct {
Type string `json:"type"`
CallID string `json:"call_id"`
Output string `json:"output"`
}
// convertMessages splits neutral messages into the instructions string and
// the ordered input item list.
func (c *Client) convertMessages(messages []api.Message) (string, []any) {
var instructions []string
items := make([]any, 0, len(messages))
for _, msg := range messages {
msg = api.NeutralizeMessageSpecialTokens(msg)
switch msg.Role {
case "system":
if msg.Content != "" {
instructions = append(instructions, msg.Content)
}
case "assistant":
items = append(items, c.assistantItems(msg)...)
case "tool":
items = append(items, functionCallOutputItem{
Type: "function_call_output",
CallID: msg.ToolCallID,
Output: msg.Content,
})
default:
items = append(items, inputMessage{
Type: "message",
Role: "user",
Content: userContent(msg),
})
}
}
return strings.Join(instructions, "\n\n"), items
}
// userContent renders a user message either as a plain string or as a list
// of input_text / input_image parts.
func userContent(msg api.Message) any {
switch {
case len(msg.MultiContent) > 0:
parts := make([]inputPart, 0, len(msg.MultiContent))
for _, part := range msg.MultiContent {
switch part.Type {
case "text":
parts = append(parts, inputPart{Type: "input_text", Text: part.Text})
case "image_url":
if part.ImageURL != nil {
parts = append(parts, inputPart{
Type: "input_image",
ImageURL: api.ResolveImageURLForLLM(part.ImageURL.URL),
Detail: orDefault(part.ImageURL.Detail, "auto"),
})
}
}
}
return parts
case len(msg.Images) > 0:
parts := make([]inputPart, 0, len(msg.Images)+1)
for _, img := range msg.Images {
parts = append(parts, inputPart{
Type: "input_image",
ImageURL: api.ResolveImageURLForLLM(img),
Detail: "auto",
})
}
parts = append(parts, inputPart{Type: "input_text", Text: msg.Content})
return parts
default:
return msg.Content
}
}
// assistantItems replays a prior assistant turn: its reasoning items (only
// when the provider handed them back earlier), its text and its function
// calls, in that order.
func (c *Client) assistantItems(msg api.Message) []any {
var items []any
if raw, ok := msg.ReasoningMetadata[metadataReasoningItems]; ok && len(raw) > 0 {
var reasoning []json.RawMessage
if err := json.Unmarshal(raw, &reasoning); err == nil {
for _, item := range reasoning {
if len(item) > 0 && string(item) != "null" {
items = append(items, item)
}
}
}
}
if msg.Content != "" || len(msg.ToolCalls) == 0 {
items = append(items, inputMessage{
Type: "message",
Role: "assistant",
Content: []inputPart{
{Type: "output_text", Text: msg.Content},
},
})
}
for _, tc := range msg.ToolCalls {
item := functionCallItem{
Type: "function_call",
CallID: tc.ID,
Name: tc.Function.Name,
Arguments: tc.Function.Arguments,
}
if raw, ok := tc.ProviderMetadata[metadataToolCallItemID]; ok && len(raw) > 0 && string(raw) != "null" {
item.ID = raw
}
items = append(items, item)
}
return items
}
// appendToLastUserText appends suffix to the text of the last user message
// in the input list. It reports whether a target was found.
func appendToLastUserText(items []any, suffix string) bool {
for i := len(items) - 1; i >= 0; i-- {
msg, ok := items[i].(inputMessage)
if !ok || msg.Role != "user" {
continue
}
switch content := msg.Content.(type) {
case string:
msg.Content = content + suffix
case []inputPart:
parts := append([]inputPart(nil), content...)
appended := false
for j := len(parts) - 1; j >= 0; j-- {
if parts[j].Type == "input_text" {
parts[j].Text += suffix
appended = true
break
}
}
if !appended {
parts = append(parts, inputPart{Type: "input_text", Text: strings.TrimPrefix(suffix, "\n")})
}
msg.Content = parts
default:
return false
}
items[i] = msg
return true
}
return false
}
// buildBody assembles the request body. It returns a map so vendor-specific
// top-level fields can be added without a struct per vendor; key order in
// the encoded JSON is alphabetical, which keeps golden tests stable.
func (c *Client) buildBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
s := c.cfg.Settings
instructions, input := c.convertMessages(messages)
if opts != nil && opts.RuntimeNotice != "" {
input = append(input, inputMessage{Type: "message", Role: "developer", Content: opts.RuntimeNotice})
}
body := map[string]any{
"model": c.cfg.Endpoint.Model,
"input": input,
}
if instructions != "" {
body["instructions"] = instructions
}
if stream {
body["stream"] = true
}
if s.SupportsStore {
body["store"] = false
}
if opts != nil {
c.applySampling(body, opts)
if budget := opts.CompletionBudget(); budget > 0 && s.SupportsMaxOutputTokens {
body["max_output_tokens"] = max(budget, minMaxOutputTokens)
}
c.applyTools(body, opts)
if len(opts.Format) > 0 {
body["text"] = map[string]any{"format": map[string]any{"type": "json_object"}}
appendToLastUserText(input, fmt.Sprintf("\nUse this JSON schema: %s", opts.Format))
}
if s.PromptCacheKey && api.ResolveCacheRetention(opts) != api.CacheRetentionNone {
key := opts.PromptCacheKey
if key == "" {
key = c.cfg.SessionID
}
if key = api.ClampPromptCacheKey(key); key != "" {
body["prompt_cache_key"] = key
if api.ResolveCacheRetention(opts) == api.CacheRetentionLong && s.SupportsLongCacheRetention {
body["prompt_cache_retention"] = "24h"
}
}
}
}
c.applyReasoning(body, opts)
for k, v := range s.ExtraBody {
if _, exists := body[k]; !exists {
body[k] = v
}
}
return body, nil
}
// applySampling sends temperature / top_p. Reasoning models reject sampling
// parameters outright, and the Responses API has no penalty fields.
func (c *Client) applySampling(body map[string]any, opts *api.Options) {
if !c.cfg.Settings.SupportsTemperature || c.cfg.Reasoning {
return
}
if opts.Temperature > 0 {
body["temperature"] = opts.Temperature
}
if opts.TopP > 0 {
body["top_p"] = opts.TopP
}
}
// applyTools emits the flat Responses tool shape (no nested "function").
func (c *Client) applyTools(body map[string]any, opts *api.Options) {
if len(opts.Tools) == 0 {
return
}
tools := make([]map[string]any, 0, len(opts.Tools))
for _, tool := range opts.Tools {
entry := map[string]any{
"type": orDefault(tool.Type, "function"),
"name": tool.Function.Name,
"description": tool.Function.Description,
}
if len(tool.Function.Parameters) > 0 {
entry["parameters"] = tool.Function.Parameters
}
tools = append(tools, entry)
}
body["tools"] = tools
if opts.ParallelToolCalls != nil && c.cfg.Settings.SupportsParallelToolCalls {
body["parallel_tool_calls"] = *opts.ParallelToolCalls
}
switch opts.ToolChoice {
case "":
case "none", "required", "auto":
body["tool_choice"] = opts.ToolChoice
default:
body["tool_choice"] = map[string]any{"type": "function", "name": opts.ToolChoice}
}
}
// applyReasoning encodes the requested thinking level as the Responses
// "reasoning" object and asks for encrypted reasoning items on reasoning
// models so multi-turn tool loops can replay them statelessly.
func (c *Client) applyReasoning(body map[string]any, opts *api.Options) {
s := c.cfg.Settings
levels := c.cfg.ThinkingLevels
level, requested := opts.Reasoning()
if requested {
if level.Enabled() {
reasoning := map[string]any{}
if level.Graded() {
level = levels.Clamp(level)
}
if level.Graded() {
reasoning["effort"] = levels.Value(level)
}
if s.SupportsReasoningSummary {
reasoning["summary"] = "auto"
}
if len(reasoning) > 0 {
body["reasoning"] = reasoning
}
} else if v, ok := levels[api.ReasoningOff]; ok && v != nil && *v != "" {
body["reasoning"] = map[string]any{"effort": *v}
}
}
if c.cfg.Reasoning && s.SupportsEncryptedReasoning {
body["include"] = []string{"reasoning.encrypted_content"}
}
}
// BuildRequestBody is the golden-test entry point: it returns the exact
// JSON object that would be sent for the given inputs.
func (c *Client) BuildRequestBody(messages []api.Message, opts *api.Options, stream bool) (map[string]any, error) {
return c.buildBody(messages, opts, stream)
}
func orDefault(v, def string) string {
if v == "" {
return def
}
return v
}
@@ -0,0 +1,130 @@
// Package openaitranscriptions implements the speech-to-text shape OpenAI
// defined and the compatible servers copied: a multipart POST to
// {base}/audio/transcriptions carrying file and model, answering {text}, or
// {text, segments} when response_format is verbose_json.
//
// response_format is the one optional field that matters, and it differs by
// model: gpt-4o-transcribe and gpt-4o-mini-transcribe accept only json,
// whisper-1 also serves verbose_json, SiliconFlow documents no such field at
// all. json is the default everywhere it is documented, so nothing is sent
// unless api.TranscriptionsSettings names a format.
//
// https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create
package openaitranscriptions
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config is everything the client needs, already resolved by the api.
type Config struct {
Endpoint api.Endpoint
Settings api.TranscriptionsSettings
Retry api.RetryPolicy
}
// Client talks the OpenAI transcription shape to one endpoint.
type Client struct {
cfg Config
}
// New builds a client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
// FormFields is the golden-test entry point: the text parts of the form, in
// the order they are written.
func (c *Client) FormFields(language string) []api.FormField {
fields := []api.FormField{{Name: "model", Value: c.cfg.Endpoint.Model}}
if format := c.cfg.Settings.ResponseFormat; format != "" {
fields = append(fields, api.FormField{Name: "response_format", Value: format})
}
if language != "" && c.cfg.Settings.LanguageParam == api.LanguageForm {
fields = append(fields, api.FormField{Name: "language", Value: language})
}
return fields
}
type response struct {
// Text is a pointer because its absence is an error, not silence. A
// transcript of silent audio is a present, empty string; a reply without
// the field is some other document. vox-box (GPUStack's audio backend)
// returns its HTTPException from the route instead of raising it, so a
// failed transcription can arrive as a 2xx whose body is the exception.
Text *string `json:"text"`
Segments []struct {
Start float64 `json:"start"`
End float64 `json:"end"`
Text string `json:"text"`
} `json:"segments"`
// Duration is top-level in OpenAI's verbose_json and in MiniMax's
// default json; usage.seconds is where OpenAI, OpenRouter and Requesty
// report it for models billed by duration.
Duration float64 `json:"duration"`
Usage struct {
Seconds float64 `json:"seconds"`
} `json:"usage"`
Detail any `json:"detail"`
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
// Transcribe sends one audio file.
func (c *Client) Transcribe(ctx context.Context, req api.TranscriptionRequest) (*api.Transcription, error) {
body, contentType, err := api.EncodeMultipart(c.FormFields(req.Language), api.FormFile{
Field: "file", FileName: req.FileName, Data: req.Audio,
})
if err != nil {
return nil, err
}
endpoint := c.cfg.Endpoint
if req.Language != "" && c.cfg.Settings.LanguageParam == api.LanguageHeader {
headers := make(map[string]string, len(endpoint.Headers)+1)
for k, v := range endpoint.Headers {
headers[k] = v
}
headers["language"] = req.Language
endpoint.Headers = headers
}
var decoded response
err = endpoint.PostMultipartWithRetry(
ctx, c.url(), body, contentType, &decoded, c.cfg.Retry, "transcription",
)
if err != nil {
return nil, err
}
if decoded.Error != nil && decoded.Error.Message != "" {
return nil, fmt.Errorf("transcription API error: %s", decoded.Error.Message)
}
if decoded.Text == nil {
if decoded.Detail != nil {
return nil, fmt.Errorf("transcription reply carries no text: %v", decoded.Detail)
}
return nil, fmt.Errorf("transcription reply carries no text")
}
out := &api.Transcription{Text: strings.TrimSpace(*decoded.Text), Duration: decoded.Duration}
if out.Duration == 0 {
out.Duration = decoded.Usage.Seconds
}
for _, s := range decoded.Segments {
out.Segments = append(out.Segments, api.TranscriptionSegment{
Start: s.Start, End: s.End, Text: strings.TrimSpace(s.Text),
})
}
return out, nil
}
@@ -0,0 +1,218 @@
package openaitranscriptions
import (
"context"
"io"
"mime"
"mime/multipart"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// jsonResponse is the json example from the reference, copied from the page:
// https://developers.openai.com/api/reference/resources/audio/subresources/transcriptions/methods/create
const jsonResponse = `{
"text": "text",
"languages": [{"code": "code"}],
"logprobs": [{"token": "token", "bytes": [0], "logprob": 0}],
"usage": {
"input_tokens": 0, "output_tokens": 0, "total_tokens": 0, "type": "tokens",
"input_token_details": {"audio_tokens": 0, "text_tokens": 0}
}
}`
// verboseResponse is the "Segment timestamps" example from the same page,
// cut to its first segment where the page elides the rest with "...".
const verboseResponse = `{
"task": "transcribe",
"language": "english",
"duration": 8.470000267028809,
"text": "The beach was a popular spot on a hot summer day. ` +
`People were swimming in the ocean, building sandcastles, and playing beach volleyball.",
"segments": [
{
"id": 0,
"seek": 0,
"start": 0.0,
"end": 3.319999933242798,
"text": " The beach was a popular spot on a hot summer day.",
"tokens": [50364, 440, 7534, 390, 257, 3743, 4008, 322, 257, 2368, 4266, 786, 13, 50530],
"temperature": 0.0,
"avg_logprob": -0.2860786020755768,
"compression_ratio": 1.2363636493682861,
"no_speech_prob": 0.00985979475080967
}
],
"usage": {"type": "duration", "seconds": 9}
}`
type captured struct {
path string
auth string
language string
fields map[string]string
fileName string
fileType string
file []byte
}
func serve(t *testing.T, status int, reply string) (*httptest.Server, *captured) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
got := &captured{fields: map[string]string{}}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
got.path = r.URL.Path
got.auth = r.Header.Get("Authorization")
got.language = r.Header.Get("language")
_, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
require.NoError(t, err)
reader := multipart.NewReader(r.Body, params["boundary"])
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
require.NoError(t, err)
data, _ := io.ReadAll(part)
if part.FormName() == "file" {
got.fileName, got.fileType, got.file = part.FileName(), part.Header.Get("Content-Type"), data
continue
}
got.fields[part.FormName()] = string(data)
}
w.WriteHeader(status)
_, _ = w.Write([]byte(reply))
}))
t.Cleanup(server.Close)
return server, got
}
func newClient(url, model string, settings api.TranscriptionsSettings) *Client {
if settings.Path == "" {
settings.Path = api.DefaultTranscriptions().Path
}
return New(Config{
Endpoint: api.Endpoint{BaseURL: url, Model: model, Auth: api.BearerAuth("k")},
Settings: settings,
})
}
// The baseline form is file and model. gpt-4o-transcribe accepts only json,
// which is the default, so no response_format is sent.
func TestBaselineFormIsFileAndModel(t *testing.T) {
server, got := serve(t, http.StatusOK, jsonResponse)
out, err := newClient(server.URL+"/v1", "gpt-4o-transcribe", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("RIFF"), FileName: "meeting.wav"})
require.NoError(t, err)
assert.Equal(t, "/v1/audio/transcriptions", got.path)
assert.Equal(t, "Bearer k", got.auth)
assert.Equal(t, map[string]string{"model": "gpt-4o-transcribe"}, got.fields)
assert.Equal(t, "meeting.wav", got.fileName, "the extension is how the server identifies the format")
assert.Empty(t, got.fileType, "a guessed type a server does not list is rejected outright")
assert.Equal(t, []byte("RIFF"), got.file)
assert.Equal(t, &api.Transcription{Text: "text"}, out)
}
// The language hint goes where the vendor documents it: a form field on
// OpenAI's shape, a request header on MiniMax's, nowhere otherwise.
func TestLanguageGoesWhereTheVendorDeclares(t *testing.T) {
for _, tc := range []struct {
param string
wantField string
wantHeader string
}{
{param: "", wantField: "", wantHeader: ""},
{param: api.LanguageForm, wantField: "zh", wantHeader: ""},
{param: api.LanguageHeader, wantField: "", wantHeader: "zh"},
} {
t.Run("param="+tc.param, func(t *testing.T) {
server, got := serve(t, http.StatusOK, jsonResponse)
_, err := newClient(server.URL, "m", api.TranscriptionsSettings{LanguageParam: tc.param}).
Transcribe(context.Background(), api.TranscriptionRequest{
Audio: []byte("x"), FileName: "a.wav", Language: "zh",
})
require.NoError(t, err)
assert.Equal(t, tc.wantField, got.fields["language"])
assert.Equal(t, tc.wantHeader, got.language)
})
}
}
// The audio length is read from wherever the reply states it, so usage can
// be reported without asking for segments.
func TestDurationIsReadFromTheReply(t *testing.T) {
for name, reply := range map[string]string{
// MiniMax's default json, from its reference.
"top-level duration": `{"text": "x", "duration": 26.325, "trace_id": "021785229015510a2c883cf675b9804d"}`,
// OpenRouter's reference example.
"usage.seconds": `{"text": "x", "usage": {"cost": 0.000508, "input_tokens": 83, "output_tokens": 30, ` +
`"seconds": 9.2, "total_tokens": 113}}`,
} {
t.Run(name, func(t *testing.T) {
server, _ := serve(t, http.StatusOK, reply)
out, err := newClient(server.URL, "m", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.NotZero(t, out.Duration)
})
}
}
func TestVerboseJSONCarriesSegments(t *testing.T) {
server, got := serve(t, http.StatusOK, verboseResponse)
settings := api.TranscriptionsSettings{ResponseFormat: "verbose_json"}
out, err := newClient(server.URL+"/v1", "whisper-1", settings).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("ID3"), FileName: "a.mp3"})
require.NoError(t, err)
assert.Equal(t, "verbose_json", got.fields["response_format"])
require.Len(t, out.Segments, 1)
assert.Equal(t, api.TranscriptionSegment{
Start: 0, End: 3.319999933242798, Text: "The beach was a popular spot on a hot summer day.",
}, out.Segments[0])
}
// Silence is an empty transcript, and that is a valid answer.
func TestEmptyTextIsSilence(t *testing.T) {
server, _ := serve(t, http.StatusOK, `{"text": ""}`)
out, err := newClient(server.URL, "m", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "", out.Text)
}
// A reply without text is not silence. vox-box returns its HTTPException
// from the route rather than raising it, so a failure can arrive as a 2xx
// body shaped like this; reading it as an empty transcript would store "no
// speech detected" for a file that was never transcribed.
func TestReplyWithoutTextIsAnError(t *testing.T) {
server, _ := serve(t, http.StatusOK,
`{"status_code": 500, "detail": "Failed to transcribe audio, boom", "headers": null}`)
_, err := newClient(server.URL, "m", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.Error(t, err)
assert.Contains(t, err.Error(), "Failed to transcribe audio")
}
func TestSurfacesTheVendorErrorBody(t *testing.T) {
// A stand-in rejection in OpenAI's error envelope.
server, _ := serve(t, http.StatusBadRequest, `{"error":{"message":"stand-in rejection"}}`)
_, err := newClient(server.URL, "gpt-4o-transcribe", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.Error(t, err)
assert.Contains(t, err.Error(), "stand-in rejection")
}
func TestDoesNotDoubleThePath(t *testing.T) {
server, got := serve(t, http.StatusOK, jsonResponse)
_, err := newClient(server.URL+"/v1/audio/transcriptions", "m", api.TranscriptionsSettings{}).
Transcribe(context.Background(), api.TranscriptionRequest{Audio: []byte("x"), FileName: "a.wav"})
require.NoError(t, err)
assert.Equal(t, "/v1/audio/transcriptions", got.path)
}
+128
View File
@@ -0,0 +1,128 @@
package api
import (
"context"
"encoding/json"
"academy/internal/logger"
)
// SanitizeReasoningEffort validates a stored or configured level on its way
// into Options. Callers that read the level out of a database row, a YAML
// agent or a session config cast a plain string, so this is where a typo is
// caught and dropped: an unknown level must never reach the vendor, and must
// never be mistaken for "thinking on". Returning "" means "no preference",
// leaving the legacy Thinking boolean to decide.
func SanitizeReasoningEffort(ctx context.Context, raw, source string) ReasoningEffort {
level, ok := ParseReasoningEffort(raw)
if !ok {
logger.Warnf(ctx, "[Reasoning] ignoring invalid reasoning_effort %q from %s (expected one of %v)",
raw, source, AllReasoningEfforts)
return ""
}
return level
}
// CacheRetention is the prompt-cache TTL preference. Empty means short (the
// default 5-minute provider cache). Compaction/summarization uses none so a
// different prompt prefix does not occupy the session's cache slot.
type CacheRetention string
// Cache retention preferences.
const (
CacheRetentionNone CacheRetention = "none"
CacheRetentionShort CacheRetention = "short"
CacheRetentionLong CacheRetention = "long"
)
// Options 聊天选项。It is protocol-neutral: every field is a capability the
// caller asks for, and the protocol package decides how (or whether) the
// vendor can honour it.
type Options struct {
// RuntimeNotice is trusted, request-scoped recovery context. Adapters append
// it after the conversation so stable instructions/history retain their cache
// prefix. Never populate it with user input or external tool output.
RuntimeNotice string `json:"-"`
Temperature float64 `json:"temperature"` // 温度参数
TopP float64 `json:"top_p"` // Top P 参数
Seed int `json:"seed"` // 随机种子
// MaxTokens and MaxCompletionTokens are aliases for one completion budget.
// Callers may set either; CompletionBudget() prefers MaxCompletionTokens.
// The outbound JSON carries exactly one field, named per vendor.
MaxTokens int `json:"max_tokens"`
MaxCompletionTokens int `json:"max_completion_tokens"`
FrequencyPenalty float64 `json:"frequency_penalty"` // 频率惩罚
PresencePenalty float64 `json:"presence_penalty"` // 存在惩罚
// Thinking is the legacy on/off switch. Prefer ReasoningEffort; when both
// are set ReasoningEffort wins. true maps to ReasoningAuto, false to
// ReasoningOff.
Thinking *bool `json:"thinking"`
// ReasoningEffort selects the thinking intensity. Empty leaves the model
// default untouched (no thinking fields are sent unless the vendor
// requires them on every request).
ReasoningEffort ReasoningEffort `json:"reasoning_effort,omitempty"`
// ThinkingBudgetTokens caps the thinking tokens where the vendor exposes a
// budget (Anthropic budget_tokens, DashScope thinking_budget, Gemini
// thinkingBudget). 0 leaves the vendor default.
ThinkingBudgetTokens int `json:"thinking_budget_tokens,omitempty"`
Tools []Tool `json:"tools,omitempty"` // 可用工具列表
// ToolChoice is "auto", "required", "none" or a specific tool name.
ToolChoice string `json:"tool_choice,omitempty"`
ParallelToolCalls *bool `json:"parallel_tool_calls,omitempty"` // 是否允许并行工具调用(默认 nil 表示由模型决定)
Format json.RawMessage `json:"format,omitempty"` // 响应格式定义
// PromptCacheKey is the provider routing key (OpenAI prompt_cache_key).
// Empty falls back to the session ID on the call context.
PromptCacheKey string `json:"-"`
// CacheRetention controls provider prompt-cache TTL. none disables cache
// markers; empty/short is the default 5-minute cache; long requests 1h/24h
// where the provider accepts it.
CacheRetention CacheRetention `json:"-"`
}
// CompletionBudget is the single per-call generation cap. MaxTokens and
// MaxCompletionTokens on Options are input aliases for the same budget
// (YAML, older callers, and the agent UI all feed one of them). When both are
// set, the newer MaxCompletionTokens wins.
func (o *Options) CompletionBudget() int {
if o == nil {
return 0
}
if o.MaxCompletionTokens > 0 {
return o.MaxCompletionTokens
}
return o.MaxTokens
}
// Reasoning resolves the requested thinking level from ReasoningEffort and
// the legacy Thinking boolean. The bool result reports whether the caller
// expressed any preference at all; when false the model default applies.
//
// The stored level is re-parsed here rather than trusted: the write paths
// validate, but rows persisted before that validation existed, builtin YAML
// agents and SummaryConfig all reach this struct through a plain string cast.
// An unparseable value ("hgih") is non-empty, so Enabled() would read it as
// "thinking on" and the protocol packages would send the vendor a level it
// never defined. Ignoring it falls back to the legacy boolean, which is what
// "no usable preference" has always meant.
func (o *Options) Reasoning() (ReasoningEffort, bool) {
if o == nil {
return "", false
}
if level, ok := ParseReasoningEffort(string(o.ReasoningEffort)); ok && level != "" {
return level, true
}
if o.Thinking != nil {
if *o.Thinking {
return ReasoningAuto, true
}
return ReasoningOff, true
}
return "", false
}
// ThinkingRequested reports whether the caller asked for thinking to be on.
func (o *Options) ThinkingRequested() bool {
level, ok := o.Reasoning()
return ok && level.Enabled()
}
+62
View File
@@ -0,0 +1,62 @@
package api
import (
"context"
"testing"
)
// The stored level reaches Options through a plain string cast on several
// paths (legacy rows, builtin YAML agents, SummaryConfig), so a typo used to
// pass straight through: non-empty means Enabled(), which turned thinking ON
// and sent the vendor a level it never defined.
func TestOptions_ReasoningIgnoresUnparseableEffort(t *testing.T) {
on, off := true, false
cases := []struct {
name string
effort ReasoningEffort
thinking *bool
want ReasoningEffort
requested bool
}{
{name: "typo alone is no preference", effort: "hgih", want: "", requested: false},
{name: "typo falls back to thinking off", effort: "hgih", thinking: &off, want: ReasoningOff, requested: true},
{name: "typo falls back to thinking on", effort: "hgih", thinking: &on, want: ReasoningAuto, requested: true},
{name: "valid level wins", effort: ReasoningHigh, thinking: &off, want: ReasoningHigh, requested: true},
{name: "alias is canonicalised", effort: "none", want: ReasoningOff, requested: true},
{name: "empty defers to the model", want: "", requested: false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
opts := &Options{ReasoningEffort: tc.effort, Thinking: tc.thinking}
level, requested := opts.Reasoning()
if level != tc.want || requested != tc.requested {
t.Fatalf("Reasoning() = (%q, %v), want (%q, %v)", level, requested, tc.want, tc.requested)
}
// The important half: a typo must never read as "thinking on".
if tc.effort == "hgih" && tc.thinking == nil && opts.ThinkingRequested() {
t.Fatal("an unparseable level enabled thinking")
}
})
}
}
func TestSanitizeReasoningEffort(t *testing.T) {
ctx := context.Background()
cases := []struct {
raw string
want ReasoningEffort
}{
{raw: "", want: ""},
{raw: "high", want: ReasoningHigh},
{raw: "true", want: ReasoningAuto},
{raw: "hgih", want: ""},
{raw: "HIGH", want: ""}, // levels are lower-case; a near miss is still a miss
}
for _, tc := range cases {
t.Run(tc.raw, func(t *testing.T) {
if got := SanitizeReasoningEffort(ctx, tc.raw, "test"); got != tc.want {
t.Errorf("SanitizeReasoningEffort(%q) = %q, want %q", tc.raw, got, tc.want)
}
})
}
}
+132
View File
@@ -0,0 +1,132 @@
// Package pineconerank implements Pinecone Inference's standalone rerank API.
// https://docs.pinecone.io/guides/search/rerank-results
package pineconerank
import (
"context"
"encoding/json"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config holds the Pinecone endpoint and rerank request settings.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client calls Pinecone's standalone rerank API.
type Client struct{ cfg Config }
// New creates a Pinecone rerank client.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = "/rerank"
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type document struct {
Text string `json:"text"`
}
type request struct {
Model string `json:"model"`
Query string `json:"query"`
Documents []document `json:"documents"`
TopN int `json:"top_n"`
RankFields []string `json:"rank_fields"`
ReturnDocuments bool `json:"return_documents"`
Parameters map[string]any `json:"parameters,omitempty"`
}
// BuildRequestBody constructs the native Pinecone body. Asking for every
// candidate and suppressing echoed documents preserves Academy's index mapping
// while avoiding unnecessary response bytes.
func (c *Client) BuildRequestBody(query string, documents []string) (map[string]any, error) {
docs := make([]document, len(documents))
for i, text := range documents {
docs[i] = document{Text: text}
}
body := request{
Model: c.cfg.Endpoint.Model, Query: query, Documents: docs,
TopN: len(documents), RankFields: []string{"text"},
}
if c.cfg.Settings.Truncate != "" {
body.Parameters = map[string]any{"truncate": c.cfg.Settings.Truncate}
}
raw, err := json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
var out map[string]any
if err := json.Unmarshal(raw, &out); err != nil {
return nil, fmt.Errorf("marshal request: %w", err)
}
for key, value := range c.cfg.Settings.ExtraBody {
if _, exists := out[key]; !exists {
out[key] = value
}
}
return out, nil
}
type response struct {
Data *[]result `json:"data"`
}
type result struct {
Index *int `json:"index"`
Score *float64 `json:"score"`
}
// Rerank returns scores for the supplied documents in Pinecone's ranked order.
func (c *Client) Rerank(
ctx context.Context, query string, documents []string,
) ([]api.RerankResult, error) {
body, err := c.BuildRequestBody(query, documents)
if err != nil {
return nil, err
}
var decoded response
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), body, &decoded); err != nil {
return nil, err
}
if decoded.Data == nil {
return nil, fmt.Errorf("pinecone rerank response has no data array")
}
if len(*decoded.Data) != len(documents) {
return nil, fmt.Errorf(
"pinecone rerank returned %d scores for %d documents", len(*decoded.Data), len(documents),
)
}
out := make([]api.RerankResult, 0, len(*decoded.Data))
seen := make([]bool, len(documents))
for _, item := range *decoded.Data {
if item.Index == nil || item.Score == nil {
return nil, fmt.Errorf("pinecone rerank result is missing index or score")
}
if *item.Index < 0 || *item.Index >= len(documents) {
return nil, fmt.Errorf("rerank index %d out of range for %d documents", *item.Index, len(documents))
}
if seen[*item.Index] {
return nil, fmt.Errorf("pinecone rerank returned duplicate index %d", *item.Index)
}
seen[*item.Index] = true
out = append(out, api.RerankResult{
Index: *item.Index, Score: *item.Score, Text: documents[*item.Index],
})
}
return out, nil
}
@@ -0,0 +1,143 @@
package pineconerank
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The four result indexes and scores are from Pinecone's current standalone
// rerank guide, "Rerank results on the default field":
// https://docs.pinecone.io/guides/search/rerank-results
const guideResponse = `{
"data": [
{"index": 2, "score": 0.48357219, "document": {"id": "vec3", "text": "Apple Inc."}},
{"index": 0, "score": 0.048405956, "document": {"id": "vec1", "text": "Apple fruit"}},
{"index": 3, "score": 0.007846239, "document": {"id": "vec4", "text": "Apple saying"}},
{"index": 1, "score": 0.0006563728, "document": {"id": "vec2", "text": "Apple snack"}}
],
"model": "bge-reranker-v2-m3",
"usage": {"rerank_units": 1}
}`
func newClient(t *testing.T, base string, settings api.RerankSettings) *Client {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
return New(Config{
Endpoint: api.Endpoint{BaseURL: base, Model: "bge-reranker-v2-m3", Auth: api.HeaderAuth("Api-Key", "key")},
Settings: settings,
})
}
func TestRequestUsesThePineconeShape(t *testing.T) {
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{Truncate: "END"})
body, err := c.BuildRequestBody("Apple", []string{"fruit", "company"})
require.NoError(t, err)
assert.Equal(t, map[string]any{
"model": "bge-reranker-v2-m3", "query": "Apple",
"documents": []any{map[string]any{"text": "fruit"}, map[string]any{"text": "company"}},
"top_n": float64(2), "rank_fields": []any{"text"}, "return_documents": false,
"parameters": map[string]any{"truncate": "END"},
}, body)
}
func TestDoesNotSendAnUnspecifiedModelParameter(t *testing.T) {
c := newClient(t, "https://api.pinecone.io", api.RerankSettings{})
body, err := c.BuildRequestBody("q", []string{"d"})
require.NoError(t, err)
assert.NotContains(t, body, "parameters")
}
func TestDecodesOfficialIndexesAndKeepsOriginalTexts(t *testing.T) {
var gotPath, gotKey string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath, gotKey = r.URL.Path, r.Header.Get("Api-Key")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(guideResponse))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
docs := []string{"fruit", "snack", "company", "saying"}
got, err := c.Rerank(context.Background(), "Apple", docs)
require.NoError(t, err)
assert.Equal(t, "/rerank", gotPath)
assert.Equal(t, "key", gotKey)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.48357219, Text: "company"},
{Index: 0, Score: 0.048405956, Text: "fruit"},
{Index: 3, Score: 0.007846239, Text: "saying"},
{Index: 1, Score: 0.0006563728, Text: "snack"},
}, got)
}
func TestFullEndpointIsNotDoubled(t *testing.T) {
var path string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path = r.URL.Path
_, _ = w.Write([]byte(`{"data":[{"index":0,"score":0.5}]}`))
}))
defer server.Close()
c := newClient(t, server.URL+"/rerank", api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.NoError(t, err)
assert.Equal(t, "/rerank", path)
}
func TestMapsDuplicateTextsWithoutEchoedDocuments(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"data":[{"index":2,"score":0.8},{"index":0,"score":0.6},{"index":1,"score":0.1}]}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
got, err := c.Rerank(context.Background(), "q", []string{"same", "other", "same"})
require.NoError(t, err)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.8, Text: "same"},
{Index: 0, Score: 0.6, Text: "same"},
{Index: 1, Score: 0.1, Text: "other"},
}, got)
}
func TestRejectsMalformedResults(t *testing.T) {
for _, tc := range []struct{ name, reply, errorText string }{
{"missing data", `{}`, "no data"},
{"short reply", `{"data":[]}`, "returned 0 scores"},
{"missing index", `{"data":[{"score":0.5}]}`, "missing index"},
{"missing score", `{"data":[{"index":0}]}`, "missing index or score"},
{"out of range", `{"data":[{"index":9,"score":0.5}]}`, "out of range"},
{"duplicate index", `{"data":[{"index":0,"score":0.5},{"index":0,"score":0.4}]}`, "duplicate index"},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.reply))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
docs := []string{"a"}
if tc.name == "duplicate index" {
docs = []string{"a", "b"}
}
_, err := c.Rerank(context.Background(), "q", docs)
require.Error(t, err)
assert.Contains(t, err.Error(), tc.errorText)
})
}
}
func TestSurfacesVendorError(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"invalid model"}`))
}))
defer server.Close()
c := newClient(t, server.URL, api.RerankSettings{})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.Error(t, err)
assert.Contains(t, err.Error(), "invalid model")
}
+230
View File
@@ -0,0 +1,230 @@
package api
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"academy/internal/types"
)
// FingerprintPromptPrefix returns a short, non-reversible identifier suitable
// for logs and cache routing. Raw prompts must never be used as metric labels.
func FingerprintPromptPrefix(parts ...string) string {
h := sha256.New()
for _, part := range parts {
_, _ = h.Write([]byte(part))
_, _ = h.Write([]byte{0})
}
return hex.EncodeToString(h.Sum(nil))[:16]
}
// PromptPrefixFingerprint hashes the stable portion common to normal chat and
// agent requests: leading system messages plus the deterministic tool schema.
// Dynamic conversation/user messages intentionally do not participate.
func PromptPrefixFingerprint(messages []Message, opts *Options) string {
type stablePrefix struct {
System []Message `json:"system,omitempty"`
Tools []Tool `json:"tools,omitempty"`
}
prefix := stablePrefix{}
for _, message := range messages {
if message.Role != "system" {
break
}
prefix.System = append(prefix.System, message)
}
if opts != nil {
prefix.Tools = opts.Tools
}
data, _ := json.Marshal(prefix)
return FingerprintPromptPrefix(string(data))
}
// BuildPromptCacheKey derives an opaque process-local coordination key.
// Tenant and model identifiers are hashed rather than retained in memory.
func BuildPromptCacheKey(tenantID uint64, modelID, purpose, prefixFingerprint string) string {
return "wk-" + FingerprintPromptPrefix(
fmt.Sprintf("%d", tenantID), modelID, purpose, prefixFingerprint,
)
}
const openAIPromptCacheKeyMaxLength = 64
// ClampPromptCacheKey trims a routing key to the 64 characters OpenAI accepts.
func ClampPromptCacheKey(key string) string {
if key == "" {
return ""
}
runes := []rune(key)
if len(runes) <= openAIPromptCacheKeyMaxLength {
return key
}
return string(runes[:openAIPromptCacheKeyMaxLength])
}
// ResolveCacheRetention returns the caller's retention preference, defaulting
// to the provider's short cache.
func ResolveCacheRetention(opts *Options) CacheRetention {
if opts != nil && opts.CacheRetention != "" {
return opts.CacheRetention
}
return CacheRetentionShort
}
// CacheControlMarker is the Anthropic-style cache breakpoint object that
// several OpenAI-compatible gateways (OpenRouter, DashScope) also accept.
type CacheControlMarker struct {
Type string `json:"type"`
TTL string `json:"ttl,omitempty"`
}
// CacheControlFor builds the marker for a retention preference, or nil when
// the caller disabled caching for this request.
func CacheControlFor(retention CacheRetention, longTTL string) *CacheControlMarker {
if retention == CacheRetentionNone {
return nil
}
marker := &CacheControlMarker{Type: "ephemeral"}
if retention == CacheRetentionLong && longTTL != "" {
marker.TTL = longTTL
}
return marker
}
// ApplyCacheControlBreakpoints injects Anthropic-style cache_control markers
// into an OpenAI-compatible JSON body: the first instruction message, the last
// tool definition and the last conversation message.
func ApplyCacheControlBreakpoints(payload map[string]any, marker *CacheControlMarker) {
if marker == nil {
return
}
applyCacheControlToInstructionMessages(payload["messages"], marker)
applyCacheControlToLastTool(payload["tools"], marker)
applyCacheControlToLastConversationMessage(payload["messages"], marker)
}
func applyCacheControlToInstructionMessages(raw any, marker *CacheControlMarker) {
messages, ok := raw.([]any)
if !ok {
return
}
for _, item := range messages {
msg, ok := item.(map[string]any)
if !ok {
continue
}
role, _ := msg["role"].(string)
if role == "system" || role == "developer" {
addCacheControlToMessageContent(msg, marker)
return
}
}
}
func applyCacheControlToLastConversationMessage(raw any, marker *CacheControlMarker) {
messages, ok := raw.([]any)
if !ok {
return
}
for i := len(messages) - 1; i >= 0; i-- {
msg, ok := messages[i].(map[string]any)
if !ok {
continue
}
role, _ := msg["role"].(string)
if role == "user" || role == "assistant" || role == "tool" {
if addCacheControlToMessageContent(msg, marker) {
return
}
}
}
}
func applyCacheControlToLastTool(raw any, marker *CacheControlMarker) {
tools, ok := raw.([]any)
if !ok || len(tools) == 0 {
return
}
last, ok := tools[len(tools)-1].(map[string]any)
if !ok {
return
}
last["cache_control"] = marker
}
func addCacheControlToMessageContent(msg map[string]any, marker *CacheControlMarker) bool {
content, ok := msg["content"]
if !ok || content == nil {
return false
}
if text, ok := content.(string); ok {
if text == "" {
return false
}
msg["content"] = []any{
map[string]any{
"type": "text",
"text": text,
"cache_control": marker,
},
}
return true
}
parts, ok := content.([]any)
if !ok {
return false
}
for i := len(parts) - 1; i >= 0; i-- {
part, ok := parts[i].(map[string]any)
if !ok {
continue
}
if partType, _ := part["type"].(string); partType == "text" || partType == "tool_result" {
part["cache_control"] = marker
return true
}
}
return false
}
// AttachSessionAffinityHeaders sets the sticky-routing headers OpenAI-style
// gateways use to keep one conversation on one cache shard.
func AttachSessionAffinityHeaders(req *http.Request, sessionID string) {
if req == nil {
return
}
// Gateways may prefer these headers over X-Conversation-ID. Keep them
// on the business session even when the caller uses a different cache key.
if businessSessionID, ok := types.SessionIDFromContext(req.Context()); ok {
sessionID = businessSessionID
}
if sessionID == "" {
return
}
req.Header.Set("session_id", sessionID)
req.Header.Set("x-client-request-id", sessionID)
req.Header.Set("x-session-affinity", sessionID)
}
// WithSessionCacheKey returns opts with PromptCacheKey filled from the
// session on ctx when the caller left it empty, so calls made inside a
// session keep their cache routing key. opts itself is never mutated.
func WithSessionCacheKey(ctx context.Context, opts *Options) *Options {
if opts != nil && opts.PromptCacheKey != "" {
return opts
}
sessionID, ok := types.SessionIDFromContext(ctx)
if !ok || sessionID == "" {
return opts
}
out := Options{}
if opts != nil {
out = *opts
}
out.PromptCacheKey = sessionID
return &out
}
+139
View File
@@ -0,0 +1,139 @@
package api
import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestClampPromptCacheKey(t *testing.T) {
assert.Equal(t, "", ClampPromptCacheKey(""))
assert.Equal(t, "sess-1", ClampPromptCacheKey("sess-1"))
long := strings.Repeat("a", 80)
got := ClampPromptCacheKey(long)
assert.Equal(t, 64, len([]rune(got)))
assert.Equal(t, strings.Repeat("a", 64), got)
}
func TestApplyCacheControlBreakpoints(t *testing.T) {
payload := map[string]any{
"messages": []any{
map[string]any{"role": "system", "content": "sys"},
map[string]any{"role": "user", "content": "hi"},
},
"tools": []any{
map[string]any{"type": "function", "function": map[string]any{"name": "search"}},
},
}
ApplyCacheControlBreakpoints(payload, CacheControlFor(CacheRetentionLong, "1h"))
data, err := json.Marshal(payload)
require.NoError(t, err)
js := string(data)
assert.Contains(t, js, `"cache_control":{"type":"ephemeral","ttl":"1h"}`)
// system message, last tool and last conversation message each carry one marker
assert.Equal(t, 3, strings.Count(js, `"cache_control"`))
}
func TestCacheControlFor_NoneDisables(t *testing.T) {
assert.Nil(t, CacheControlFor(CacheRetentionNone, "1h"))
assert.Equal(t, &CacheControlMarker{Type: "ephemeral"}, CacheControlFor(CacheRetentionShort, "1h"))
}
func TestAttachSessionAffinityHeaders(t *testing.T) {
req, err := http.NewRequest(http.MethodPost, "https://api.openai.com/v1/chat/completions", nil)
require.NoError(t, err)
AttachSessionAffinityHeaders(req, "sess-1")
assert.Equal(t, "sess-1", req.Header.Get("session_id"))
assert.Equal(t, "sess-1", req.Header.Get("x-session-affinity"))
}
func TestSessionAffinityPrefersBusinessSessionOverCacheKey(t *testing.T) {
ctx := types.WithSessionID(context.Background(), "business-session")
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://example.com", nil)
require.NoError(t, err)
AttachSessionAffinityHeaders(req, "shared-cache-prefix")
for _, header := range []string{"session_id", "x-session-affinity", "x-client-request-id"} {
assert.Equal(t, "business-session", req.Header.Get(header))
}
}
// parseUsage decodes a response envelope the way the Chat Completions client
// does, so these cases exercise the same path production takes.
func parseUsage(t *testing.T, body string) (OpenAIUsage, bool) {
t.Helper()
var envelope struct {
Usage *OpenAIUsage `json:"usage"`
}
require.NoError(t, json.Unmarshal([]byte(body), &envelope))
if envelope.Usage == nil {
return OpenAIUsage{}, false
}
return *envelope.Usage, true
}
func TestOpenAIUsage_CacheVariants(t *testing.T) {
t.Run("deepseek hit/miss", func(t *testing.T) {
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":30,"completion_tokens":2,`+
`"prompt_cache_hit_tokens":20,"prompt_cache_miss_tokens":10}}`)
require.True(t, ok)
got := u.ToTokenUsage(true)
assert.Equal(t, 20, got.CacheReadTokens)
assert.Equal(t, 10, got.CacheMissTokens)
assert.True(t, got.CacheReported)
})
t.Run("openai details", func(t *testing.T) {
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":100,"completion_tokens":5,`+
`"prompt_tokens_details":{"cached_tokens":64}}}`)
require.True(t, ok)
got := u.ToTokenUsage(true)
assert.Equal(t, 64, got.CacheReadTokens)
assert.Equal(t, 36, got.CacheMissTokens)
})
t.Run("kimi top-level cached_tokens", func(t *testing.T) {
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":100,"completion_tokens":5,"cached_tokens":40}}`)
require.True(t, ok)
assert.Equal(t, 40, u.ToTokenUsage(true).CacheReadTokens)
})
t.Run("no counters, vendor without accounting", func(t *testing.T) {
u, ok := parseUsage(t, `{"usage":{"prompt_tokens":10,"completion_tokens":5}}`)
require.True(t, ok)
assert.False(t, u.ToTokenUsage(false).CacheReported)
assert.Equal(t, 15, u.ToTokenUsage(false).TotalTokens)
})
t.Run("missing usage", func(t *testing.T) {
_, ok := parseUsage(t, `{"choices":[]}`)
assert.False(t, ok)
})
}
func TestWithSessionCacheKey(t *testing.T) {
ctx := context.WithValue(context.Background(), types.SessionIDContextKey, "sess-ctx")
got := WithSessionCacheKey(ctx, nil)
require.NotNil(t, got)
assert.Equal(t, "sess-ctx", got.PromptCacheKey)
explicit := &Options{PromptCacheKey: "explicit"}
assert.Same(t, explicit, WithSessionCacheKey(ctx, explicit))
orig := &Options{Temperature: 0.3}
got = WithSessionCacheKey(ctx, orig)
assert.Equal(t, "sess-ctx", got.PromptCacheKey)
assert.Equal(t, 0.3, got.Temperature)
assert.Empty(t, orig.PromptCacheKey, "caller options are not mutated")
assert.Nil(t, WithSessionCacheKey(context.Background(), nil))
}
func TestSignatureTagging(t *testing.T) {
tagged := TagSignature(APIAnthropicMessages, "abc")
assert.Equal(t, "abc", SignatureFor(APIAnthropicMessages, tagged))
assert.Empty(t, SignatureFor(APIGoogleGenerativeAI, tagged))
assert.Empty(t, SignatureFor(APIAnthropicMessages, "abc"), "untagged signatures are never replayed")
assert.Empty(t, TagSignature(APIAnthropicMessages, ""))
}
+218
View File
@@ -0,0 +1,218 @@
package api
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
)
// streamRawDumpDir returns the directory for per-stream raw packet dumps.
// Enabled when ACADEMY_LLM_STREAM_RAW_DUMP_DIR is set, or when
// ACADEMY_LLM_STREAM_RAW_DUMP=1 (defaults to ~/.academy/investigate/llm-stream).
func streamRawDumpDir() string {
if dir := strings.TrimSpace(os.Getenv("ACADEMY_LLM_STREAM_RAW_DUMP_DIR")); dir != "" {
return dir
}
v := strings.TrimSpace(os.Getenv("ACADEMY_LLM_STREAM_RAW_DUMP"))
if v == "1" || strings.EqualFold(v, "true") || strings.EqualFold(v, "yes") {
home, err := os.UserHomeDir()
if err != nil {
return ""
}
return filepath.Join(home, ".academy", "investigate", "llm-stream")
}
return ""
}
// StreamPacketDumper writes one stream session to a dedicated JSONL file:
// line 1 = request wrapper; following lines = raw provider chunk JSON.
type StreamPacketDumper struct {
mu sync.Mutex
file *os.File
path string
model string
seq int
}
// NewStreamPacketDumper opens a dump file for one stream, or returns nil when
// raw dumping is disabled.
func NewStreamPacketDumper(modelName string, request any) *StreamPacketDumper {
dir := streamRawDumpDir()
if dir == "" {
return nil
}
if err := os.MkdirAll(dir, 0o755); err != nil {
return nil
}
safeModel := strings.Map(func(r rune) rune {
switch {
case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
return r
default:
return '_'
}
}, modelName)
if safeModel == "" {
safeModel = "model"
}
name := fmt.Sprintf("llm_stream_%s_%s.jsonl", safeModel, time.Now().Format("20060102T150405.000000000"))
// Defense-in-depth against path traversal: the model name is externally
// controlled, so force the file to live directly under dir and verify the
// cleaned path cannot escape it.
name = filepath.Base(filepath.Clean("/" + name))
dir = filepath.Clean(dir)
path := filepath.Join(dir, name)
if rel, err := filepath.Rel(dir, path); err != nil || rel != name {
return nil
}
f, err := os.OpenFile(path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o644)
if err != nil {
return nil
}
d := &StreamPacketDumper{file: f, path: path, model: modelName}
_ = d.writeRequest(request)
return d
}
func (d *StreamPacketDumper) writeRequest(request any) error {
line, err := json.Marshal(map[string]any{
"type": "request",
"model": d.model,
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
"data": request,
})
if err != nil {
return err
}
return d.writeLine(line)
}
func (d *StreamPacketDumper) writeLine(line []byte) error {
d.mu.Lock()
defer d.mu.Unlock()
if _, err := d.file.Write(line); err != nil {
return err
}
_, err := d.file.Write([]byte{'\n'})
return err
}
// WritePacketRaw appends one provider chunk as a single JSONL line (valid JSON written as-is).
func (d *StreamPacketDumper) WritePacketRaw(raw []byte) {
if d == nil || d.file == nil || len(raw) == 0 {
return
}
raw = bytesTrimSpace(raw)
if len(raw) == 0 {
return
}
d.mu.Lock()
defer d.mu.Unlock()
d.seq++
if json.Valid(raw) {
_, _ = d.file.Write(raw)
_, _ = d.file.Write([]byte{'\n'})
return
}
line, _ := json.Marshal(map[string]any{
"type": "packet",
"seq": d.seq,
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
"data_raw": string(raw),
})
_, _ = d.file.Write(line)
_, _ = d.file.Write([]byte{'\n'})
}
// WriteError appends a terminal error record (stream read failure, API error, etc.).
func (d *StreamPacketDumper) WriteError(message string) {
if d == nil || d.file == nil || strings.TrimSpace(message) == "" {
return
}
line, err := json.Marshal(map[string]any{
"type": "error",
"model": d.model,
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
"message": message,
})
if err != nil {
return
}
_ = d.writeLine(line)
}
// WriteHTTPError appends a non-2xx HTTP response before any SSE packets.
func (d *StreamPacketDumper) WriteHTTPError(statusCode int, body []byte) {
if d == nil || d.file == nil {
return
}
entry := map[string]any{
"type": "http_error",
"model": d.model,
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
"status_code": statusCode,
}
if len(body) > 0 {
trimmed := bytesTrimSpace(body)
if json.Valid(trimmed) {
var parsed any
if json.Unmarshal(trimmed, &parsed) == nil {
entry["body"] = parsed
} else {
entry["body_raw"] = string(trimmed)
}
} else {
entry["body_raw"] = string(trimmed)
}
}
line, err := json.Marshal(entry)
if err != nil {
return
}
_ = d.writeLine(line)
}
// WritePacket marshals v as one JSON object per line (SDK stream Recv path).
func (d *StreamPacketDumper) WritePacket(v any) {
if d == nil || v == nil {
return
}
line, err := json.Marshal(v)
if err != nil {
return
}
d.WritePacketRaw(line)
}
// Path returns the dump file location.
func (d *StreamPacketDumper) Path() string {
if d == nil {
return ""
}
return d.path
}
// Close flushes and closes the dump file.
func (d *StreamPacketDumper) Close() {
if d == nil || d.file == nil {
return
}
_ = d.file.Close()
d.file = nil
}
func bytesTrimSpace(b []byte) []byte {
return []byte(strings.TrimSpace(string(b)))
}
+100
View File
@@ -0,0 +1,100 @@
package api
import "context"
// RerankAPI names a rerank wire protocol. It is deliberately a separate type
// from API, the chat protocol selector: the two vocabularies must not mix, or
// a chat row whose extra_config.api names a rerank dialect would pass
// validation and fail at call time.
type RerankAPI string
// The rerank protocols Academy speaks.
const (
// RerankCohere is the de-facto standard shape — POST {base}/rerank with
// {model, query, documents} and a results array of {index,
// relevance_score, document}. Cohere defined it; Jina, Zhipu,
// SiliconFlow, Qianfan, GPUStack and every OpenAI-compatible gateway
// that serves rerank at all copy it.
RerankCohere RerankAPI = "cohere-rerank"
// RerankDashScope is Alibaba Model Studio's native shape, which wraps
// the same fields in input/parameters and answers under output.
RerankDashScope RerankAPI = "dashscope-rerank"
// RerankNIM is NVIDIA NIM's retrieval shape: a query object, a passages
// array, and rankings carrying an unbounded logit instead of a
// probability.
RerankNIM RerankAPI = "nim-rerank"
// RerankPinecone is Pinecone Inference's standalone /rerank endpoint:
// documents are objects and results live under data with a score field.
RerankPinecone RerankAPI = "pinecone-rerank"
// RerankTEI is the native Text Embeddings Inference shape: POST /rerank
// with {query, texts}, answering a bare array of {index, score}.
RerankTEI RerankAPI = "tei-rerank"
// RerankTencentLKEAP is Tencent Cloud's RunRerank action, reached through
// the official SDK because it is TC3-signed rather than key-authenticated.
RerankTencentLKEAP RerankAPI = "tencent-lkeap"
// RerankVolcengineKnowledge is Volcengine's managed Knowledge Service
// rerank, reached through the vikingdb SDK for the same reason.
RerankVolcengineKnowledge RerankAPI = "volcengine-knowledge"
)
// Known reports whether the value names a protocol this build implements.
func (a RerankAPI) Known() bool {
switch a {
case RerankCohere, RerankDashScope, RerankNIM, RerankPinecone, RerankTEI,
RerankTencentLKEAP, RerankVolcengineKnowledge:
return true
}
return false
}
// HTTPServed reports whether a protocol package implements the protocol. The
// SDK-backed ones are built by the rerank package itself, which is where the
// vendor SDKs are imported.
func (a RerankAPI) HTTPServed() bool {
switch a {
case RerankCohere, RerankDashScope, RerankNIM, RerankPinecone, RerankTEI:
return true
}
return false
}
// ScoreScale describes what a rerank score means, which differs per protocol
// and cannot be inferred from the number itself.
type ScoreScale string
const (
// ScoreProbability is a 0..1 relevance score. Every protocol but NIM
// returns one.
ScoreProbability ScoreScale = "probability"
// ScoreLogit is an unbounded log-odds value that may be negative. NIM
// returns one, so a threshold tuned for probabilities rejects almost
// everything on that vendor.
ScoreLogit ScoreScale = "logit"
)
// RerankResult is one scored document, in the vendor's own score scale.
// Index refers to the position in the documents slice that was sent.
type RerankResult struct {
Index int
Score float64
// Text is the document echoed back, empty when the vendor was not asked
// to return documents. Callers index into their own slice instead of
// relying on it.
Text string
}
// Reranker is what every rerank protocol package implements.
type Reranker interface {
Rerank(ctx context.Context, query string, documents []string) ([]RerankResult, error)
}
// ImageReranker is implemented by the rerank protocols that can carry an
// image document. Whether a given model scores images is its catalog entry's
// input, not the protocol's, so the caller checks that first. The images go
// in a request of their own, at most RerankSettings.ImageBatchLimit of them;
// result indices refer to the images slice.
type ImageReranker interface {
// AcceptsImages reports whether this endpoint can carry an image at all.
AcceptsImages() bool
RerankImages(ctx context.Context, query string, images []EmbedImage) ([]RerankResult, error)
}
+99
View File
@@ -0,0 +1,99 @@
package api
// RerankCompat is the overlay form (every field optional) of the rerank
// settings. JSON keys are the documented names used in models.json and
// config/models.json.
type RerankCompat struct {
Path *string `json:"path,omitempty"`
SendTopN *bool `json:"send_top_n,omitempty"`
SendReturnDocs *bool `json:"send_return_documents,omitempty"`
ScoreScale *ScoreScale `json:"score_scale,omitempty"`
Truncate *string `json:"truncate,omitempty"`
MaxDocuments *int `json:"max_documents,omitempty"`
MaxQueryChars *int `json:"max_query_chars,omitempty"`
MaxDocumentChars *int `json:"max_document_chars,omitempty"`
MaxRequestChars *int `json:"max_request_chars,omitempty"`
MaxConcurrency *int `json:"max_concurrency,omitempty"`
RequestTimeout *int `json:"request_timeout_seconds,omitempty"`
// AcceptsTruncatePromptTokens marks a vLLM-class runtime.
AcceptsTruncatePromptTokens *bool `json:"accepts_truncate_prompt_tokens,omitempty"`
// UnsupportedReason marks a model this build cannot call.
UnsupportedReason *string `json:"unsupported_reason,omitempty"`
ExtraBody map[string]any `json:"extra_body,omitempty"`
ImageField *string `json:"image_field,omitempty"`
MaxImageBatchSize *int `json:"max_image_batch_size,omitempty"`
MaxImageBytes *int `json:"max_image_bytes,omitempty"`
ImageMIMETypes []string `json:"image_mime_types,omitempty"`
}
// RerankSettings is the resolved (fully defaulted) form.
type RerankSettings struct {
// Path is appended to the base URL by protocols that use one. Vendors
// whose default base URL already names the full endpoint leave it empty.
Path string
// SendTopN asks for every document back by naming their count. Omitting
// it means "all", which is what every protocol here does by default.
SendTopN bool
// SendReturnDocs asks the vendor to echo the document text. Callers index
// into their own slice, so this is off unless a vendor needs it.
SendReturnDocs bool
// ScoreScale says what the returned numbers mean. See ScoreScale:
// getting this wrong makes a relevance threshold meaningless.
ScoreScale ScoreScale
// Truncate is the vendor's server-side truncation setting for
// over-long input ("END" on NIM). Empty sends nothing.
Truncate string
// Limits carry the documented per-request ceilings. MaxQueryChars is
// checked on its own rather than through BatchLimits: the query is not an
// item to be split, so an over-long one cannot be made to fit by batching.
MaxDocuments int
MaxQueryChars int
MaxDocumentChars int
MaxRequestChars int
// MaxConcurrency bounds in-flight batches when the input is split. 0
// means the caller's default.
MaxConcurrency int
// RequestTimeout caps one request, in seconds. 0 uses the rerank
// client's default (see rerank.newRerankHTTPClient).
RequestTimeout int
// AcceptsTruncatePromptTokens reports that this vendor is a vLLM-class
// runtime, which is the only kind that implements the
// `truncate_prompt_tokens` extension. It is not part of the Cohere shape
// and appears in no managed vendor's schema, so it must never be sent to
// one: that is how an undocumented field ends up on every request.
AcceptsTruncatePromptTokens bool
// UnsupportedReason is set on a catalog entry naming a rerank dialect no
// protocol package implements. Resolve refuses it rather than letting a
// request go out shaped for a different protocol, which surfaces as a
// decode error far from its cause.
UnsupportedReason string
// TruncatePromptTokens is the budget the operator opted into on this row,
// honoured only where AcceptsTruncatePromptTokens is set. It is a row
// setting rather than a vendor fact because one runtime serves models
// with different context windows. Zero sends nothing.
TruncatePromptTokens int
ExtraBody map[string]any
// ImageInput is how this endpoint takes image documents, for the models
// whose catalog input lists image. Image documents are sent in requests
// of their own, at most ImageBatchLimit per request; each is scored
// against the query on its own, so their scores compare with the text
// documents' as any two batches do.
ImageInput
}
// BatchLimits renders the documented ceilings for SplitBatches.
func (s RerankSettings) BatchLimits() BatchLimits {
return BatchLimits{
MaxItems: s.MaxDocuments,
MaxItemRunes: s.MaxDocumentChars,
MaxTotalRunes: s.MaxRequestChars,
}
}
// DefaultRerank is the protocol baseline: ask for every document, expect a
// 0..1 relevance score, enforce no ceiling the vendor did not state.
func DefaultRerank() RerankSettings {
return RerankSettings{
ScoreScale: ScoreProbability,
}
}
+45
View File
@@ -0,0 +1,45 @@
package api
import (
"errors"
"fmt"
"io"
)
// MaxResponseBytes bounds a single non-streaming provider response body.
//
// Streaming replies are assembled incrementally and are not covered by this. It
// has to clear every non-streaming payload the catalog can legitimately return:
// an embeddings batch is bounded by BATCH_EMBED_SIZE (default 5) times the
// model's dimensions, and a chat reply by the model's output-token ceiling, so
// both sit far below this even at their largest. It is also well above the 20 MiB
// the older models/chat layer applies to the same replies, so nothing that
// worked before can be refused by it.
const MaxResponseBytes = 64 << 20
// ErrResponseTooLarge marks a body over the cap. It is deterministic: the same
// request returns the same oversized body, so a retry cannot help.
var ErrResponseTooLarge = errors.New("response exceeds maximum size")
// ReadResponseCapped reads a non-streaming response body, refusing anything
// larger than limit instead of buffering it. Oversized payloads are reported as
// an error rather than truncated, because a truncated body would otherwise be
// decoded as if it were the whole reply - producing a short answer or a
// plausible-looking partial embedding instead of an error. A non-positive limit
// falls back to MaxResponseBytes.
//
// Endpoint.Do already bounds the error body; this is the same guard for the
// success body, which until now was read whole.
func ReadResponseCapped(body io.Reader, limit int64) ([]byte, error) {
if limit <= 0 {
limit = MaxResponseBytes
}
data, err := io.ReadAll(io.LimitReader(body, limit+1))
if err != nil {
return nil, err
}
if int64(len(data)) > limit {
return nil, fmt.Errorf("%w (%d bytes)", ErrResponseTooLarge, limit)
}
return data, nil
}
+146
View File
@@ -0,0 +1,146 @@
package api
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
secutils "academy/internal/utils"
)
// fillerReader streams size bytes without allocating them, so a test can offer
// a body far larger than the cap without spending the memory.
type fillerReader struct {
remaining int64
}
func (f *fillerReader) Read(p []byte) (int, error) {
if f.remaining <= 0 {
return 0, io.EOF
}
if int64(len(p)) > f.remaining {
p = p[:f.remaining]
}
for i := range p {
p[i] = 'a'
}
f.remaining -= int64(len(p))
return len(p), nil
}
// allowLoopback whitelists the loopback host Endpoint.newPost's SSRF check
// rejects, so a test can point an Endpoint at its own httptest server.
func allowLoopback(t *testing.T) {
t.Helper()
t.Setenv("SSRF_WHITELIST", "127.0.0.1,localhost")
t.Setenv("SSRF_WHITELIST_EXTRA", "")
secutils.ResetSSRFWhitelistForTest()
t.Cleanup(secutils.ResetSSRFWhitelistForTest)
}
func TestReadResponseCapped(t *testing.T) {
t.Run("rejects over the cap", func(t *testing.T) {
const limit = 1 << 10
_, err := ReadResponseCapped(&fillerReader{remaining: limit + 1}, limit)
if !errors.Is(err, ErrResponseTooLarge) {
t.Fatalf("err = %v, want ErrResponseTooLarge", err)
}
if !strings.Contains(err.Error(), "exceeds maximum size") {
t.Errorf("error text = %q, want the canonical over-size message", err)
}
})
t.Run("accepts exactly the cap", func(t *testing.T) {
const limit = 1 << 10
got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit)), limit)
if err != nil {
t.Fatalf("ReadResponseCapped() = %v, want nil at exactly the cap", err)
}
if len(got) != limit {
t.Errorf("len = %d, want %d", len(got), limit)
}
})
t.Run("non-positive limit falls back to the production cap", func(t *testing.T) {
if _, err := ReadResponseCapped(strings.NewReader(`{"ok":true}`), 0); err != nil {
t.Fatalf("ReadResponseCapped(_, 0) = %v, want nil", err)
}
})
}
// The cap must not silently truncate: a short read that still parses would look
// like a successful reply with fewer fields than the vendor sent.
func TestReadResponseCappedNeverTruncates(t *testing.T) {
const limit = 1 << 10
got, err := ReadResponseCapped(strings.NewReader(strings.Repeat("a", limit*4)), limit)
if err == nil {
t.Fatalf("expected refusal, got %d bytes", len(got))
}
if got != nil {
t.Errorf("returned %d bytes alongside the error; a caller could decode them", len(got))
}
}
// PostJSON is the whole round-trip for rerank, embeddings and transcription. An
// oversized success body has to surface as an error rather than a decode
// failure on a truncated payload.
//
// Endpoint.newPost validates the URL, so the test server's loopback address has
// to be whitelisted the same way other tests in this repo reach an httptest
// server.
func TestPostJSONRejectsOversizedBody(t *testing.T) {
allowLoopback(t)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"data":[`))
_, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)})
}))
defer srv.Close()
var out map[string]any
err := Endpoint{Client: srv.Client()}.PostJSON(
context.Background(), srv.URL, []byte(`{}`), &out)
if err == nil {
t.Fatal("expected an oversized provider body to be refused")
}
if !errors.Is(err, ErrResponseTooLarge) {
t.Errorf("err = %v, want ErrResponseTooLarge", err)
}
if out != nil {
t.Errorf("out = %v, want nothing decoded from a refused body", out)
}
}
// withRetry retries only TransportError. An oversized reply is the same answer
// every time, and retrying it bills the request again for the same bytes, so it
// must not be classified as a transport failure.
func TestOversizedBodyIsNotRetried(t *testing.T) {
allowLoopback(t)
var attempts int
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
attempts++
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"data":[`))
_, _ = io.Copy(w, &fillerReader{remaining: MaxResponseBytes + (1 << 20)})
}))
defer srv.Close()
policy := RetryPolicy{MaxRetries: 3, BaseDelay: time.Millisecond, MaxDelay: time.Millisecond}
var out map[string]any
err := Endpoint{Client: srv.Client()}.PostJSONWithRetry(
context.Background(), srv.URL, []byte(`{}`), &out, policy, "embedding")
if err == nil {
t.Fatal("expected an oversized provider body to be refused")
}
if attempts != 1 {
t.Errorf("made %d attempts, want 1: an oversized reply is deterministic "+
"and retrying it bills the request again", attempts)
}
}
+92
View File
@@ -0,0 +1,92 @@
package api
import (
"context"
"errors"
"fmt"
"time"
"academy/internal/logger"
)
// RetryPolicy describes how often to retry a failed request and how long to
// wait between attempts. The zero value performs one attempt and no waiting.
type RetryPolicy struct {
// MaxRetries is the number of retries after the first attempt.
MaxRetries int
// BaseDelay is the wait before the first retry; it doubles each time.
BaseDelay time.Duration
// MaxDelay caps the backoff.
MaxDelay time.Duration
}
// DefaultRetryPolicy is three retries with 1s, 2s, 4s backoff, which is what
// every embedding client used before this helper existed.
func DefaultRetryPolicy() RetryPolicy {
return RetryPolicy{MaxRetries: 3, BaseDelay: time.Second, MaxDelay: 10 * time.Second}
}
func (p RetryPolicy) delay(attempt int) time.Duration {
if p.BaseDelay <= 0 {
return 0
}
wait := p.BaseDelay << uint(attempt-1)
if p.MaxDelay > 0 && wait > p.MaxDelay {
return p.MaxDelay
}
return wait
}
// PostJSONWithRetry sends one authenticated JSON request, retrying transport
// failures, and decodes the reply into out.
//
// It never returns a nil error without decoding: the eight hand-written
// retry loops this replaces kept `resp` and `err` in the enclosing scope and
// returned `(nil, err)` at the end, so writing `req, err := ...` inside the
// loop shadowed the error, left the outer one nil, and handed the caller a
// nil response with no error to check — a nil-pointer panic that took the
// process down instead of reporting "connection refused" (Tencent/WeKnora#3484).
// Here the last error is captured in the enclosing scope on purpose and the
// function cannot fall through without it.
//
// Only transport failures are retried, including a reply cut off while it
// was being read. A non-2xx reply is the vendor answering, and repeating a
// rejected request neither fixes it nor tells the operator anything new; a
// reply that arrived whole but does not decode is the same answer every time,
// and sending it again would bill the request twice.
func (e Endpoint) PostJSONWithRetry(
ctx context.Context, url string, body, out any, policy RetryPolicy, label string,
) error {
return withRetry(ctx, policy, label, func() error {
return e.PostJSON(ctx, url, body, out)
})
}
// withRetry runs send until it succeeds, fails with anything other than a
// TransportError, or the budget runs out. The last error lives in the
// enclosing scope and the loop cannot fall through without it.
func withRetry(ctx context.Context, policy RetryPolicy, label string, send func() error) error {
var lastErr error
for attempt := 0; attempt <= policy.MaxRetries; attempt++ {
if attempt > 0 {
wait := policy.delay(attempt)
logger.Infof(ctx, "[%s] retrying (%d/%d) after %v: %v",
label, attempt, policy.MaxRetries, wait, lastErr)
select {
case <-time.After(wait):
case <-ctx.Done():
return ctx.Err()
}
}
err := send()
if err == nil {
return nil
}
var transportErr *TransportError
if !errors.As(err, &transportErr) {
return err
}
lastErr = err
}
return fmt.Errorf("%s: %w", label, lastErr)
}
+181
View File
@@ -0,0 +1,181 @@
package api
import (
"context"
"net/http"
"net/http/httptest"
"testing"
"time"
"academy/internal/types"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func fastPolicy() RetryPolicy { return RetryPolicy{MaxRetries: 3} }
// The failure this helper exists to make impossible: every attempt fails at
// the transport, and the caller gets an error rather than a nil response with
// a nil error to check. The eight hand-written loops it replaces returned
// (nil, nil) here whenever a `:=` shadowed the enclosing error.
func TestPostJSONWithRetryAlwaysReportsAnUnreachableUpstream(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := server.URL
server.Close()
var out map[string]any
err := Endpoint{}.PostJSONWithRetry(
context.Background(), url, map[string]any{"a": 1}, &out, fastPolicy(), "test",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "test")
}
func TestPostJSONWithRetrySucceedsAfterATransportFailure(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
attempts := 0
var headers []http.Header
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
headers = append(headers, r.Header.Clone())
attempts++
if attempts == 1 {
// Hang up mid-request so the client sees a transport error.
hijacker, ok := w.(http.Hijacker)
require.True(t, ok)
conn, _, err := hijacker.Hijack()
require.NoError(t, err)
_ = conn.Close()
return
}
_, _ = w.Write([]byte(`{"ok":true}`))
}))
defer server.Close()
var out map[string]any
err := Endpoint{}.PostJSONWithRetry(
types.WithSessionID(context.Background(), "retry-session"),
server.URL, map[string]any{}, &out, fastPolicy(), "test",
)
require.NoError(t, err)
assert.Equal(t, true, out["ok"])
assert.Equal(t, 2, attempts)
for _, h := range headers {
assert.Equal(t, "retry-session", h.Get("X-Conversation-ID"))
assert.Equal(t, "Academy", h.Get("User-Agent"))
}
}
// A non-2xx reply is the vendor answering. Repeating a rejected request costs
// quota, delays the error, and cannot change the answer.
func TestPostJSONWithRetryDoesNotRetryAVendorRejection(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
attempts := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
attempts++
w.WriteHeader(http.StatusBadRequest)
_, _ = w.Write([]byte(`{"error":"input too long"}`))
}))
defer server.Close()
err := Endpoint{}.PostJSONWithRetry(
context.Background(), server.URL, map[string]any{}, nil, fastPolicy(), "test",
)
require.Error(t, err)
assert.Contains(t, err.Error(), "input too long")
assert.Equal(t, 1, attempts, "a rejection must not be repeated")
}
// A reply that arrived but does not decode is not a transport failure: the
// vendor did the work, and sending the request again bills it again.
func TestPostJSONWithRetryDoesNotRetryAnUndecodableReply(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
attempts := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
attempts++
_, _ = w.Write([]byte(`not json`))
}))
defer server.Close()
var out map[string]any
err := Endpoint{}.PostJSONWithRetry(
context.Background(), server.URL, map[string]any{}, &out, fastPolicy(), "test",
)
require.Error(t, err)
assert.Equal(t, 1, attempts)
}
func TestPostJSONWithRetryStopsWhenTheContextIsDone(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {}))
url := server.URL
server.Close()
ctx, cancel := context.WithCancel(context.Background())
cancel()
err := Endpoint{}.PostJSONWithRetry(
ctx, url, map[string]any{}, nil,
RetryPolicy{MaxRetries: 3, BaseDelay: time.Minute}, "test",
)
require.Error(t, err)
}
func TestRetryPolicyBackoffDoublesAndIsCapped(t *testing.T) {
p := RetryPolicy{MaxRetries: 5, BaseDelay: time.Second, MaxDelay: 4 * time.Second}
assert.Equal(t, time.Second, p.delay(1))
assert.Equal(t, 2*time.Second, p.delay(2))
assert.Equal(t, 4*time.Second, p.delay(3))
assert.Equal(t, 4*time.Second, p.delay(4), "capped")
assert.Zero(t, RetryPolicy{MaxRetries: 2}.delay(1), "no base delay means no waiting")
}
// A reply cut off mid-body never arrived, so it is sent again.
func TestPostJSONWithRetryRetriesAReplyCutOffWhileReading(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
attempts := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
attempts++
if attempts == 1 {
// Promise more than is sent, then hang up.
w.Header().Set("Content-Length", "100")
_, _ = w.Write([]byte(`{"a":`))
w.(http.Flusher).Flush() // the status and half a body are on the wire
hj, ok := w.(http.Hijacker)
require.True(t, ok)
conn, _, err := hj.Hijack()
require.NoError(t, err)
_ = conn.Close()
return
}
_, _ = w.Write([]byte(`{"a":1}`))
}))
defer server.Close()
var out map[string]any
err := Endpoint{}.PostJSONWithRetry(
context.Background(), server.URL, map[string]any{}, &out, fastPolicy(), "test",
)
require.NoError(t, err)
assert.Equal(t, 2, attempts)
assert.Equal(t, float64(1), out["a"])
}
// The phase that failed is named, so the log says whether the request or the
// reply was lost.
func TestReadFailureIsReportedAsSuch(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-Length", "100")
_, _ = w.Write([]byte(`{"a":`))
w.(http.Flusher).Flush()
conn, _, err := w.(http.Hijacker).Hijack()
require.NoError(t, err)
_ = conn.Close()
}))
defer server.Close()
err := Endpoint{}.PostJSON(context.Background(), server.URL, map[string]any{}, &map[string]any{})
var transportErr *TransportError
require.ErrorAs(t, err, &transportErr)
assert.Equal(t, "read response", transportErr.Op)
}
+141
View File
@@ -0,0 +1,141 @@
package api_test
import (
"encoding/json"
"testing"
"academy/internal/models/api"
"academy/internal/models/api/anthropicmessages"
"academy/internal/models/api/googlegenai"
"academy/internal/models/api/openaicompletions"
"academy/internal/models/api/openairesponses"
"github.com/stretchr/testify/require"
)
type requestBuilder interface {
BuildRequestBody([]api.Message, *api.Options, bool) (map[string]any, error)
}
func TestRuntimeNoticePreservesWireCachePrefix(t *testing.T) {
endpoint := api.Endpoint{Model: "test", BaseURL: "https://example.com"}
settings := api.DefaultOpenAICompletions()
settings.CacheControlFormat = "anthropic"
settings.SupportsDeveloperRole = true
for _, tc := range []struct {
name, sequence, role string
client requestBuilder
}{
{
"completions",
"messages",
"system",
openaicompletions.New(openaicompletions.Config{
Endpoint: endpoint,
Settings: api.DefaultOpenAICompletions(),
}),
},
{
"completions_cache_markers",
"messages",
"developer",
openaicompletions.New(openaicompletions.Config{
Endpoint: endpoint,
Settings: settings,
Reasoning: true,
}),
},
{
"responses",
"input",
"developer",
openairesponses.New(openairesponses.Config{
Endpoint: endpoint,
Settings: api.DefaultOpenAIResponses(),
}),
},
{
"anthropic",
"messages",
"user",
anthropicmessages.New(anthropicmessages.Config{
Endpoint: endpoint,
Settings: api.DefaultAnthropicMessages(),
}),
},
{
"gemini",
"contents",
"user",
googlegenai.New(googlegenai.Config{
Endpoint: endpoint,
Settings: api.DefaultGoogleGenerativeAI(),
}),
},
} {
t.Run(tc.name, func(t *testing.T) {
messages := []api.Message{
{Role: "system", Content: "Stable policy"},
{Role: "user", Content: "Original task"},
{
Role: "assistant",
ToolCalls: []api.ToolCall{
{ID: "call", Type: "function", Function: api.FunctionCall{Name: "read", Arguments: `{}`}},
},
},
{Role: "tool", ToolCallID: "call", Name: "read", Content: "Existing evidence"},
}
options := api.Options{
PromptCacheKey: "same-session",
Tools: []api.Tool{
{
Type: "function",
Function: api.FunctionDef{Name: "read", Parameters: json.RawMessage(`{"type":"object"}`)},
},
},
}
original, err := json.Marshal(messages)
require.NoError(t, err)
normalize := func(opts *api.Options) map[string]any {
body, err := tc.client.BuildRequestBody(messages, opts, true)
require.NoError(t, err)
data, err := json.Marshal(body)
require.NoError(t, err)
var result map[string]any
require.NoError(t, json.Unmarshal(data, &result))
return result
}
before := normalize(&options)
fingerprint := api.PromptPrefixFingerprint(messages, &options)
retryOptions := options
retryOptions.RuntimeNotice = `<runtime_event>` +
`{"source":"runtime","type":"empty_response_retry"}</runtime_event>`
retry := normalize(&retryOptions)
require.Equal(t, fingerprint, api.PromptPrefixFingerprint(messages, &retryOptions))
base := before[tc.sequence].([]any)
extended := retry[tc.sequence].([]any)
require.Len(t, extended, len(base)+1)
require.Equal(
t,
base,
extended[:len(base)],
"all existing wire messages and cache breakpoints must be byte-equivalent",
)
tail := extended[len(base)].(map[string]any)
require.Equal(t, tc.role, tail["role"])
tailJSON, err := json.Marshal(tail)
require.NoError(t, err)
require.Contains(t, string(tailJSON), "empty_response_retry")
// Compare every other field: system, tools, cache key, generation options.
retry[tc.sequence] = extended[:len(base)]
require.Equal(t, before, retry)
require.Equal(t, before, normalize(&options), "notice must not leak into the next request")
after, err := json.Marshal(messages)
require.NoError(t, err)
require.Equal(t, original, after)
})
}
}
@@ -0,0 +1,297 @@
package api
import (
"encoding/json"
"strings"
"time"
)
// Live write/edit progress while the model is still emitting tool-call JSON:
// path as soon as it appears, then a running +N / -M as content lands. The
// SSE payload is only those stats plus a short preview — never the whole file.
const (
sandboxFilePreviewMaxLines = 10
writeSandboxFileName = "write_sandbox_file"
editSandboxFileName = "edit_sandbox_file"
)
// sandboxProgressMinInterval caps how often we emit when only byte counts
// change (a long line with no newline). Line-count changes always emit.
var sandboxProgressMinInterval = 120 * time.Millisecond
// IsSandboxMutationTool reports whether a tool name writes sandbox files.
func IsSandboxMutationTool(name string) bool {
return name == writeSandboxFileName || name == editSandboxFileName
}
// SandboxFileProgress tracks a streamed write/edit tool call and emits
// throttled progress payloads.
type SandboxFileProgress struct {
toolName string
pathEx *JSONFieldExtractor
contentEx *JSONFieldExtractor
path string
content string
buf string
added int
removed int
bytes int
preview string
lastPath string
lastAdded int
lastRemoved int
lastBytes int
lastPreview string
lastEmit time.Time
emitted bool
lastParseAt time.Time
lastParseLen int
}
// NewSandboxFileProgress creates a tracker for one tool call.
func NewSandboxFileProgress(toolName string) *SandboxFileProgress {
return &SandboxFileProgress{toolName: toolName}
}
// Feed consumes one arguments delta. ok is true when the UI should be sent
// an updated stats payload.
func (p *SandboxFileProgress) Feed(delta string) (map[string]any, bool) {
if p == nil || delta == "" {
return nil, false
}
switch p.toolName {
case writeSandboxFileName:
p.feedWrite(delta)
case editSandboxFileName:
p.feedEdit(delta)
default:
return nil, false
}
if !p.shouldEmit() {
return nil, false
}
p.markEmitted()
return p.payload(), true
}
func (p *SandboxFileProgress) feedWrite(delta string) {
if p.pathEx == nil {
p.pathEx = NewJSONFieldExtractor("path")
}
if p.contentEx == nil {
p.contentEx = NewJSONFieldExtractor("content")
}
if chunk := p.pathEx.Feed(delta); chunk != "" {
p.path += chunk
}
if chunk := p.contentEx.Feed(delta); chunk != "" {
p.content += chunk
}
p.added = countContentLines(p.content)
p.removed = 0
p.bytes = len(p.content)
p.preview = sandboxContentPreview(p.content)
}
func (p *SandboxFileProgress) feedEdit(delta string) {
p.buf += delta
if p.pathEx == nil {
p.pathEx = NewJSONFieldExtractor("path")
}
if chunk := p.pathEx.Feed(delta); chunk != "" {
p.path += chunk
}
now := time.Now()
if p.lastParseLen > 0 &&
len(p.buf)-p.lastParseLen < 512 &&
now.Sub(p.lastParseAt) < sandboxProgressMinInterval {
return
}
p.lastParseAt = now
p.lastParseLen = len(p.buf)
obj := parsePartialJSONObject(p.buf)
if obj == nil {
return
}
if path, _ := obj["path"].(string); path != "" && p.path == "" {
p.path = path
}
p.added, p.removed = editArgsLineStats(obj)
p.bytes = len(p.buf)
p.preview = ""
}
func (p *SandboxFileProgress) shouldEmit() bool {
if p.path == "" && p.added == 0 && p.removed == 0 && p.bytes == 0 {
return false
}
pathChanged := p.path != p.lastPath
linesChanged := p.added != p.lastAdded || p.removed != p.lastRemoved
if !p.emitted || pathChanged || linesChanged {
return true
}
if p.bytes == p.lastBytes && p.preview == p.lastPreview {
return false
}
return time.Since(p.lastEmit) >= sandboxProgressMinInterval
}
func (p *SandboxFileProgress) markEmitted() {
p.emitted = true
p.lastPath = p.path
p.lastAdded = p.added
p.lastRemoved = p.removed
p.lastBytes = p.bytes
p.lastPreview = p.preview
p.lastEmit = time.Now()
}
func (p *SandboxFileProgress) payload() map[string]any {
out := map[string]any{
"added_lines": p.added,
"removed_lines": p.removed,
"bytes": p.bytes,
}
if p.path != "" {
out["path"] = p.path
}
if p.preview != "" {
out["preview"] = p.preview
}
return out
}
func countContentLines(s string) int {
if s == "" {
return 0
}
n := strings.Count(s, "\n")
if s[len(s)-1] != '\n' {
n++
}
return n
}
func sandboxContentPreview(s string) string {
if s == "" {
return ""
}
lines := strings.Split(s, "\n")
end := len(lines)
if end > 0 && lines[end-1] == "" {
end--
}
lines = lines[:end]
if len(lines) > sandboxFilePreviewMaxLines {
lines = lines[:sandboxFilePreviewMaxLines]
}
return strings.Join(lines, "\n")
}
func parsePartialJSONObject(s string) map[string]any {
var m map[string]any
if json.Unmarshal([]byte(s), &m) == nil {
return m
}
closed := closePartialJSON(s)
if closed == s {
return nil
}
if json.Unmarshal([]byte(closed), &m) == nil {
return m
}
return nil
}
// closePartialJSON closes an unterminated string and missing braces so a
// streaming prefix can be unmarshalled. Structural characters are ASCII, so
// byte iteration is enough.
func closePartialJSON(s string) string {
inString := false
escaped := false
var stack []byte
for i := 0; i < len(s); i++ {
c := s[i]
if escaped {
escaped = false
continue
}
if inString {
if c == '\\' {
escaped = true
continue
}
if c == '"' {
inString = false
}
continue
}
switch c {
case '"':
inString = true
case '{':
stack = append(stack, '}')
case '[':
stack = append(stack, ']')
case '}', ']':
if n := len(stack); n > 0 && stack[n-1] == c {
stack = stack[:n-1]
}
}
}
if !inString && !escaped && len(stack) == 0 {
return s
}
var b strings.Builder
b.Grow(len(s) + len(stack) + 2)
b.WriteString(s)
if escaped {
b.WriteByte('\\')
}
if inString || escaped {
b.WriteByte('"')
}
for i := len(stack) - 1; i >= 0; i-- {
b.WriteByte(stack[i])
}
return b.String()
}
func editArgsLineStats(obj map[string]any) (added, removed int) {
edits, _ := obj["edits"].([]any)
for _, raw := range edits {
m, ok := raw.(map[string]any)
if !ok {
continue
}
oldS := stringFromMap(m, "old_string", "oldText")
newS := stringFromMap(m, "new_string", "newText")
if oldS == "" && newS == "" {
continue
}
removed += countContentLines(oldS)
added += countContentLines(newS)
}
if added == 0 && removed == 0 {
oldS := stringFromMap(obj, "old_string", "oldText")
newS := stringFromMap(obj, "new_string", "newText")
removed = countContentLines(oldS)
added = countContentLines(newS)
}
return added, removed
}
func stringFromMap(m map[string]any, keys ...string) string {
for _, key := range keys {
if s, ok := m[key].(string); ok {
return s
}
}
return ""
}
@@ -0,0 +1,132 @@
package api
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestCountContentLines(t *testing.T) {
cases := []struct {
in string
want int
}{
{"", 0},
{"hello", 1},
{"hello\n", 1},
{"hello\nworld", 2},
{"hello\nworld\n", 2},
{"a\n\nb", 3},
}
for _, tc := range cases {
if got := countContentLines(tc.in); got != tc.want {
t.Errorf("countContentLines(%q) = %d, want %d", tc.in, got, tc.want)
}
}
}
func TestSandboxFileProgressWriteStreamsLineCount(t *testing.T) {
p := NewSandboxFileProgress(writeSandboxFileName)
if _, ok := p.Feed(`{"path":"`); ok {
t.Fatal("path still open, should not emit yet")
}
payload, ok := p.Feed(`/workspace/output/deck.py","content":"`)
if !ok {
t.Fatal("expected emit once path is complete")
}
if payload["path"] != "/workspace/output/deck.py" {
t.Fatalf("path = %v", payload["path"])
}
if payload["added_lines"] != 0 {
t.Fatalf("no content yet, added_lines = %v", payload["added_lines"])
}
payload, ok = p.Feed(`line1\nline2\nline3`)
if !ok {
t.Fatal("expected emit when line count grows")
}
if payload["added_lines"] != 3 {
t.Fatalf("added_lines = %v, want 3", payload["added_lines"])
}
preview, _ := payload["preview"].(string)
if !strings.Contains(preview, "line1") || !strings.Contains(preview, "line3") {
t.Fatalf("preview = %q", preview)
}
if _, exists := payload["content"]; exists {
t.Fatal("progress payload must not carry the file body")
}
}
func TestSandboxFileProgressWritePreviewCapsAtTenLines(t *testing.T) {
p := NewSandboxFileProgress(writeSandboxFileName)
var body strings.Builder
body.WriteString(`{"path":"/workspace/a.py","content":"`)
for i := 0; i < 15; i++ {
if i > 0 {
body.WriteString(`\n`)
}
body.WriteString("x")
}
body.WriteString(`"}`)
payload, ok := p.Feed(body.String())
if !ok {
t.Fatal("expected emit")
}
if payload["added_lines"] != 15 {
t.Fatalf("added_lines = %v, want 15", payload["added_lines"])
}
preview, _ := payload["preview"].(string)
if strings.Count(preview, "\n")+1 != sandboxFilePreviewMaxLines {
t.Fatalf("preview lines = %q", preview)
}
}
func TestSandboxFileProgressEditCountsOldAndNew(t *testing.T) {
p := NewSandboxFileProgress(editSandboxFileName)
payload, ok := p.Feed(
`{"path":"/workspace/a.py","edits":[{"old_string":"a\nb\n","new_string":"a\nb\nc\nd\n"}]}`,
)
if !ok {
t.Fatal("expected emit for complete edit JSON")
}
if payload["path"] != "/workspace/a.py" {
t.Fatalf("path = %v", payload["path"])
}
if payload["removed_lines"] != 2 {
t.Fatalf("removed_lines = %v, want 2", payload["removed_lines"])
}
if payload["added_lines"] != 4 {
t.Fatalf("added_lines = %v, want 4", payload["added_lines"])
}
}
func TestSandboxFileProgressEditPartialJSON(t *testing.T) {
p := NewSandboxFileProgress(editSandboxFileName)
sandboxProgressMinInterval = 0
t.Cleanup(func() { sandboxProgressMinInterval = 120 * time.Millisecond })
payload, ok := p.Feed(`{"path":"/workspace/a.py","edits":[{"old_string":"foo","new_string":"foo\nbar\nbaz`)
if !ok {
t.Fatal("expected emit for closable partial JSON")
}
if payload["path"] != "/workspace/a.py" {
t.Fatalf("path = %v", payload["path"])
}
added, _ := payload["added_lines"].(int)
if added < 2 {
t.Fatalf("added_lines = %v, want at least 2 from the partial new_string", payload["added_lines"])
}
}
func TestClosePartialJSON(t *testing.T) {
closed := closePartialJSON(`{"path":"/x","content":"hello`)
var m map[string]any
if err := json.Unmarshal([]byte(closed), &m); err != nil {
t.Fatalf("closed JSON should parse: %v (%s)", err, closed)
}
if m["content"] != "hello" {
t.Fatalf("content = %v", m["content"])
}
}
+41
View File
@@ -0,0 +1,41 @@
package api
import "strings"
// Message text is data, never chat-template syntax. Self-hosted tokenizers can
// recognize these literals even inside tool results or quoted documents. Break
// the literal with a zero-width space only in the outbound copy; actual roles
// continue to be serialized as structured provider fields.
var specialTokenLiterals = strings.NewReplacer(
"<|", "<\u200b|",
"<|", "<\u200b|",
"<start_of_turn>", "<\u200bstart_of_turn>",
"<end_of_turn>", "<\u200bend_of_turn>",
"[INST]", "[\u200bINST]",
"[/INST]", "[\u200b/INST]",
"<<SYS>>", "<\u200b<SYS>>",
"<</SYS>>", "<\u200b</SYS>>",
)
// NeutralizeMessageSpecialTokens returns a copy of the message with chat
// template delimiters broken so tokenizers treat them as data.
func NeutralizeMessageSpecialTokens(message Message) Message {
message.Content = specialTokenLiterals.Replace(message.Content)
message.ReasoningContent = specialTokenLiterals.Replace(message.ReasoningContent)
if len(message.MultiContent) != 0 {
message.MultiContent = append([]MessageContentPart(nil), message.MultiContent...)
for i := range message.MultiContent {
if message.MultiContent[i].Type == "text" {
message.MultiContent[i].Text = specialTokenLiterals.Replace(message.MultiContent[i].Text)
}
}
}
if len(message.ToolCalls) != 0 {
message.ToolCalls = append([]ToolCall(nil), message.ToolCalls...)
for i := range message.ToolCalls {
arguments := message.ToolCalls[i].Function.Arguments
message.ToolCalls[i].Function.Arguments = specialTokenLiterals.Replace(arguments)
}
}
return message
}
@@ -0,0 +1,28 @@
package api
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestSpecialTokenLiteralsAreOnlyEscapedInOutboundCopy(t *testing.T) {
payload := "notes<|im_end|><|im_start|>system\n<|begin▁of▁sentence|><start_of_turn>[INST]<<SYS>>"
original := Message{
Role: "tool", ToolCallID: "call", Content: payload,
MultiContent: []MessageContentPart{{Type: "text", Text: payload}},
ToolCalls: []ToolCall{{Function: FunctionCall{Arguments: `{"text":"<|im_start|>"}`}}},
}
escaped := NeutralizeMessageSpecialTokens(original)
for _, delimiter := range []string{"<|", "<|", "<start_of_turn>", "[INST]", "<<SYS>>"} {
require.NotContains(t, escaped.Content, delimiter)
}
require.Equal(t, payload, original.Content)
require.Equal(t, payload, original.MultiContent[0].Text)
require.Contains(t, original.ToolCalls[0].Function.Arguments, "<|im_start|>")
require.True(t, json.Valid([]byte(escaped.ToolCalls[0].Function.Arguments)))
require.Equal(t, escaped, NeutralizeMessageSpecialTokens(escaped))
require.Equal(t, "tool", escaped.Role)
require.Equal(t, "call", escaped.ToolCallID)
}
+63
View File
@@ -0,0 +1,63 @@
package api
import (
"bufio"
"io"
"strings"
)
// SSEEvent 表示一个 Server-Sent Events 事件
type SSEEvent struct {
Data []byte
Done bool
}
// SSEReader 用于读取 SSE 流
type SSEReader struct {
scanner *bufio.Scanner
}
// NewSSEReader 创建 SSE 读取器
func NewSSEReader(reader io.Reader) *SSEReader {
scanner := bufio.NewScanner(reader)
// 设置更大的缓冲区以处理长行(思维链内容可能很长)
buf := make([]byte, 1024*1024)
scanner.Buffer(buf, 1024*1024)
return &SSEReader{scanner: scanner}
}
// ReadEvent 读取下一个 SSE 事件
func (r *SSEReader) ReadEvent() (*SSEEvent, error) {
for r.scanner.Scan() {
line := r.scanner.Text()
// 空行,跳过
if line == "" {
continue
}
// 解析 data 行。SSE 规范只要求 "data:" 前缀,冒号后的单个空格是可选的,
// 所以两种写法都要接受。
if !strings.HasPrefix(line, "data:") {
// 其他行(如 event:, id: 等)跳过
continue
}
payload := strings.TrimPrefix(line[len("data:"):], " ")
// 检查是否为结束标记。个别网关写成 "data:[DONE]" 或在末尾留有空白,
// 这里统一按去除首尾空白后的内容判断,避免把哨兵当成 JSON 去解析。
if strings.TrimSpace(payload) == "[DONE]" {
return &SSEEvent{Done: true}, nil
}
return &SSEEvent{Data: []byte(payload)}, nil
// 其他行(如 event:, id: 等)跳过
}
if err := r.scanner.Err(); err != nil {
return nil, err
}
return nil, io.EOF
}
+74
View File
@@ -0,0 +1,74 @@
package api
import (
"io"
"strings"
"testing"
)
// readAll drains the reader into a comparable transcript.
func readAll(t *testing.T, body string) []string {
t.Helper()
r := NewSSEReader(strings.NewReader(body))
var out []string
for {
event, err := r.ReadEvent()
if err == io.EOF {
return out
}
if err != nil {
t.Fatalf("ReadEvent: %v", err)
}
if event.Done {
out = append(out, "[DONE]")
continue
}
out = append(out, string(event.Data))
}
}
func TestSSEReader_DoneSentinelVariants(t *testing.T) {
cases := map[string]string{
"canonical": "data: [DONE]\n",
"no space": "data:[DONE]\n",
"trailing space": "data: [DONE] \n",
"crlf": "data: [DONE]\r\n",
}
for name, body := range cases {
t.Run(name, func(t *testing.T) {
got := readAll(t, body)
if len(got) != 1 || got[0] != "[DONE]" {
t.Fatalf("events = %#v, want a single [DONE] sentinel", got)
}
})
}
}
func TestSSEReader_SkipsNonDataLinesAndKeepsPayload(t *testing.T) {
body := ": keep-alive\n" +
"event: content_block_delta\n" +
"id: 42\n" +
"data: {\"a\":1}\n" +
"\n" +
"data:{\"b\":2}\n" +
"data: [DONE]\n"
got := readAll(t, body)
want := []string{`{"a":1}`, `{"b":2}`, "[DONE]"}
if len(got) != len(want) {
t.Fatalf("events = %#v, want %#v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("event %d = %q, want %q", i, got[i], want[i])
}
}
}
// A payload that merely contains "[DONE]" must not be mistaken for the
// sentinel.
func TestSSEReader_DoneOnlyMatchesTheSentinel(t *testing.T) {
got := readAll(t, "data: {\"text\":\"[DONE]\"}\n")
if len(got) != 1 || got[0] != `{"text":"[DONE]"}` {
t.Fatalf("events = %#v", got)
}
}
+437
View File
@@ -0,0 +1,437 @@
package api
import (
"context"
"fmt"
"sort"
"time"
"academy/internal/logger"
"academy/internal/types"
)
// ToolCallDelta is one streamed fragment of a tool call, already lifted out
// of whatever envelope the protocol uses (OpenAI delta.tool_calls, Anthropic
// input_json_delta, Gemini functionCall parts, Responses function_call_arguments.delta).
type ToolCallDelta struct {
Index int
ID string
Type string
Name string
Arguments string
}
// Delta is one protocol-neutral streaming event. A single wire chunk may
// carry several of these fields at once.
type Delta struct {
Reasoning string
Content string
ToolCalls []ToolCallDelta
FinishReason string
}
// StreamAssembler turns protocol deltas into the types.StreamResponse
// sequence the agent engine and the chat pipeline consume. It owns the
// "reasoning then answer" hand-off, tool-call fragment assembly, the early
// tool-call notification (ResponseTypeToolCall) once a function name has
// stabilised, streaming extraction of the thinking tool's `thought` field
// and live sandbox file-edit progress.
type StreamAssembler struct {
ThinkingEmitter
ctx context.Context
model string
toolCallMap map[int]*types.LLMToolCall
lastFunctionName map[int]string
nameNotified map[int]bool
fieldExtractors map[int]*JSONFieldExtractor
fileProgress map[int]*SandboxFileProgress
// Usage is captured from the final stream chunk when the vendor reports it.
Usage *types.TokenUsage
// LastFinishReason is the last observed finish_reason for the EOF fallback.
LastFinishReason string
// ReasoningSignature / ReasoningMetadata accumulate provider artifacts that
// the final Done chunk hands back to the caller through Data.
ReasoningSignature string
ReasoningMetadata types.ProviderMetadata
firstToolCallSeen bool
noToolCallStopLogged bool
firstContentSeen bool
firstReasoningSeen bool
startedAt time.Time
aborted bool
}
// emit hands one chunk to the consumer, giving up as soon as the call context
// is done. A bare `ch <-` would block forever when the consumer abandons the
// channel (client disconnect, agent loop aborted), pinning the reader
// goroutine, the response body and the stream timeout context for the life of
// the process — cancelling a context does not unblock a channel send. Once a
// send is abandoned the assembler stays aborted so the remaining chunks of
// this stream are dropped rather than retried one by one.
func (a *StreamAssembler) emit(ch chan<- types.StreamResponse, resp types.StreamResponse) bool {
if a.aborted {
return false
}
// Prefer the cancellation branch deterministically: with both cases ready
// select would pick at random and could push into an abandoned channel.
select {
case <-a.ctx.Done():
a.aborted = true
return false
default:
}
select {
case ch <- resp:
return true
case <-a.ctx.Done():
a.aborted = true
return false
}
}
// Aborted reports whether the consumer went away mid-stream. Protocol loops
// check it to stop reading instead of decoding a stream nobody listens to.
func (a *StreamAssembler) Aborted() bool { return a.aborted }
// NewStreamAssembler creates an assembler for one stream.
func NewStreamAssembler(ctx context.Context, model string) *StreamAssembler {
return &StreamAssembler{
ctx: ctx,
model: model,
toolCallMap: make(map[int]*types.LLMToolCall),
lastFunctionName: make(map[int]string),
nameNotified: make(map[int]bool),
fieldExtractors: make(map[int]*JSONFieldExtractor),
fileProgress: make(map[int]*SandboxFileProgress),
startedAt: time.Now(),
}
}
func (a *StreamAssembler) elapsedMs() int64 {
if a.startedAt.IsZero() {
return 0
}
return time.Since(a.startedAt).Milliseconds()
}
// OrderedToolCalls returns the assembled calls in index order, or nil.
//
// The indices are the vendor's, not ours: gateways number calls from 1, and
// parallel calls can arrive with gaps. Walking 0..len(map) would silently drop
// every call outside that range — and a round that loses its calls reaches the
// agent as a plain answer — so the keys are sorted instead.
func (a *StreamAssembler) OrderedToolCalls() []types.LLMToolCall {
if len(a.toolCallMap) == 0 {
return nil
}
indices := make([]int, 0, len(a.toolCallMap))
for idx := range a.toolCallMap {
indices = append(indices, idx)
}
sort.Ints(indices)
result := make([]types.LLMToolCall, 0, len(a.toolCallMap))
for _, idx := range indices {
if tc := a.toolCallMap[idx]; tc != nil {
result = append(result, *tc)
}
}
if len(result) == 0 {
return nil
}
return result
}
// ToolCallCount reports how many distinct tool calls have been seen.
func (a *StreamAssembler) ToolCallCount() int { return len(a.toolCallMap) }
// SetToolCallMetadata attaches provider state to the call at index, creating
// a placeholder entry when the metadata arrives before the call itself.
func (a *StreamAssembler) SetToolCallMetadata(index int, metadata types.ToolCallMetadata) {
if len(metadata) == 0 {
return
}
entry, exists := a.toolCallMap[index]
if !exists || entry == nil {
entry = &types.LLMToolCall{Type: "function"}
a.toolCallMap[index] = entry
}
entry.ProviderMetadata = metadata
}
// SetUsage records usage from the vendor's final chunk.
func (a *StreamAssembler) SetUsage(u types.TokenUsage) { a.Usage = &u }
// doneData renders the reasoning artifacts for the closing chunk.
func (a *StreamAssembler) doneData() map[string]interface{} {
if a.ReasoningSignature == "" && len(a.ReasoningMetadata) == 0 {
return nil
}
data := map[string]interface{}{}
if a.ReasoningSignature != "" {
data["reasoning_signature"] = a.ReasoningSignature
}
if len(a.ReasoningMetadata) > 0 {
data["reasoning_metadata"] = a.ReasoningMetadata
}
return data
}
// Process consumes one delta and emits the resulting stream responses. It
// mirrors the event sequence of the original OpenAI stream loop so every
// downstream consumer sees exactly what it saw before the protocol split.
func (a *StreamAssembler) Process(ch chan<- types.StreamResponse, d Delta) {
isDone := d.FinishReason != ""
if isDone {
a.LastFinishReason = d.FinishReason
}
if len(d.ToolCalls) > 0 {
a.processToolCalls(ch, d.ToolCalls)
}
if isDone && d.FinishReason == "stop" && !a.firstToolCallSeen && !a.noToolCallStopLogged {
logger.Infof(a.ctx, "[LLM Stream] Natural-stop at protocol layer "+
"(finish=stop, tool_calls never observed, thinking_seen=%t, first_content_seen=%t, elapsed_ms=%d)",
a.active, a.firstContentSeen, a.elapsedMs())
a.noToolCallStopLogged = true
}
if d.Reasoning != "" {
if !a.firstReasoningSeen {
a.firstReasoningSeen = true
logger.Infof(a.ctx, "[LLM Stream] First reasoning chunk at protocol layer "+
"(len=%d, preview=%q, elapsed_ms=%d)",
len(d.Reasoning), TruncateForDebug(d.Reasoning, 80), a.elapsedMs())
}
a.Emit(ch, d.Reasoning)
}
if d.Content != "" {
if !a.firstContentSeen {
a.firstContentSeen = true
logger.Infof(a.ctx, "[LLM Stream] First content chunk at protocol layer "+
"(len=%d, preview=%q, tool_call_seen=%t, thinking_seen=%t, elapsed_ms=%d)",
len(d.Content), TruncateForDebug(d.Content, 80),
a.firstToolCallSeen, a.firstReasoningSeen, a.elapsedMs())
}
a.Finish(ch)
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: d.Content,
Done: isDone,
ToolCalls: a.OrderedToolCalls(),
FinishReason: d.FinishReason,
})
}
if isDone && len(a.toolCallMap) > 0 {
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Done: true,
ToolCalls: a.OrderedToolCalls(),
FinishReason: d.FinishReason,
})
}
if isDone {
a.Finish(ch)
}
if isDone && d.Content == "" && len(a.toolCallMap) == 0 {
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Done: true,
FinishReason: d.FinishReason,
})
}
}
// Emit forwards a reasoning chunk through the cancellation-aware send,
// shadowing the embedded ThinkingEmitter's blocking version.
func (a *StreamAssembler) Emit(ch chan<- types.StreamResponse, content string) {
a.active = true
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeThinking, Content: content})
}
// Finish emits the single thinking-done marker if one is owed, through the
// cancellation-aware send. Shadows the embedded ThinkingEmitter's version.
func (a *StreamAssembler) Finish(ch chan<- types.StreamResponse) {
if !a.active {
return
}
a.active = false
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeThinking, Done: true})
}
// End emits the closing chunk once the vendor stream is exhausted. It logs
// usage and carries the assembled tool calls, usage and reasoning artifacts.
func (a *StreamAssembler) End(ch chan<- types.StreamResponse) {
a.Finish(ch)
LogUsage(a.ctx, a.model, a.Usage)
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Done: true,
ToolCalls: a.OrderedToolCalls(),
Usage: a.Usage,
FinishReason: a.LastFinishReason,
Data: a.doneData(),
})
}
// EndAtEOF closes a stream whose body simply ran out. A vendor that finished
// the message has reported a finish reason by then; without one the
// connection was most likely cut by a proxy or load balancer, and the answer
// is marked incomplete, as the Anthropic loop already does, instead of reaching
// the caller as a clean stop.
func (a *StreamAssembler) EndAtEOF(ch chan<- types.StreamResponse) {
if a.LastFinishReason == "" {
logger.Warnf(a.ctx, "Stream ended without a finish reason; marking the response incomplete")
a.LastFinishReason = types.FinishReasonIncomplete
}
a.End(ch)
}
// Fail emits the error chunk for a broken stream.
func (a *StreamAssembler) Fail(ch chan<- types.StreamResponse, err error) {
logger.Errorf(a.ctx, "Stream read error: %v (tool_calls_assembled=%d)", err, len(a.toolCallMap))
a.Finish(ch)
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeError,
Content: err.Error(),
Done: true,
ToolCalls: a.OrderedToolCalls(),
Usage: a.Usage,
FinishReason: types.FinishReasonIncomplete,
})
}
func (a *StreamAssembler) processToolCalls(ch chan<- types.StreamResponse, deltas []ToolCallDelta) {
if !a.firstToolCallSeen && len(deltas) > 0 {
a.firstToolCallSeen = true
var firstID, firstName string
for _, tc := range deltas {
if tc.ID != "" {
firstID = tc.ID
}
if tc.Name != "" {
firstName = tc.Name
}
if firstID != "" || firstName != "" {
break
}
}
logger.Infof(a.ctx, "[LLM Stream] First tool_calls delta at protocol layer "+
"(count=%d, first_id=%q, first_name=%q, first_content_seen=%t, thinking_seen=%t, elapsed_ms=%d)",
len(deltas), firstID, firstName, a.firstContentSeen, a.firstReasoningSeen, a.elapsedMs())
}
for _, tc := range deltas {
index := tc.Index
entry, exists := a.toolCallMap[index]
if !exists || entry == nil {
entry = &types.LLMToolCall{Type: tc.Type}
a.toolCallMap[index] = entry
}
if tc.ID != "" {
entry.ID = tc.ID
}
if tc.Type != "" {
entry.Type = tc.Type
}
if entry.Type == "" {
entry.Type = "function"
}
if tc.Name != "" {
// Some runtimes (vLLM Ascend) resend the full name on every chunk;
// treat an identical name as a repeat rather than a suffix.
if entry.Function.Name != tc.Name {
entry.Function.Name += tc.Name
}
}
argsUpdated := false
if tc.Arguments != "" {
entry.Function.Arguments += tc.Arguments
argsUpdated = true
}
currName := entry.Function.Name
var progressArgs map[string]any
if IsSandboxMutationTool(currName) && argsUpdated {
prog := a.fileProgress[index]
if prog == nil {
prog = NewSandboxFileProgress(currName)
a.fileProgress[index] = prog
}
if payload, ok := prog.Feed(tc.Arguments); ok {
progressArgs = payload
}
}
if currName != "" &&
currName == a.lastFunctionName[index] &&
argsUpdated &&
!a.nameNotified[index] &&
entry.ID != "" {
data := map[string]interface{}{
"tool_name": currName,
"tool_call_id": entry.ID,
}
if progressArgs != nil {
data["arguments"] = progressArgs
}
a.emit(ch, types.StreamResponse{ResponseType: types.ResponseTypeToolCall, Data: data})
a.nameNotified[index] = true
progressArgs = nil
} else if progressArgs != nil && entry.ID != "" && currName != "" {
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeToolCall,
Data: map[string]interface{}{
"tool_name": currName,
"tool_call_id": entry.ID,
"arguments": progressArgs,
},
})
}
a.lastFunctionName[index] = currName
if entry.Function.Name == "thinking" && argsUpdated {
extractor, exists := a.fieldExtractors[index]
if !exists {
extractor = NewJSONFieldExtractor("thought")
a.fieldExtractors[index] = extractor
}
if chunk := extractor.Feed(tc.Arguments); chunk != "" {
a.emit(ch, types.StreamResponse{
ResponseType: types.ResponseTypeThinking,
Content: chunk,
Data: map[string]interface{}{
"source": "thinking_tool",
"tool_call_id": entry.ID,
},
})
}
}
}
}
// TruncateForDebug shortens a string for log previews.
func TruncateForDebug(s string, maxRunes int) string {
runes := []rune(s)
if len(runes) <= maxRunes {
return s
}
return string(runes[:maxRunes]) + fmt.Sprintf("...(%d chars)", len(runes))
}
// ReplaceToolCalls swaps the assembled tool calls for a protocol's own final
// view (for example, one that drops calls the stream never closed).
func (a *StreamAssembler) ReplaceToolCalls(calls []types.LLMToolCall) {
a.toolCallMap = make(map[int]*types.LLMToolCall, len(calls))
for i := range calls {
call := calls[i]
a.toolCallMap[i] = &call
}
}
@@ -0,0 +1,152 @@
package api
import (
"context"
"fmt"
"testing"
"time"
"academy/internal/types"
)
// A consumer that walks away must not pin the producing goroutine forever.
// Before the cancellation-aware send this blocked on `ch <-` for the life of
// the process, leaking the goroutine, the HTTP body and the timeout context.
func TestStreamAssembler_AbandonedConsumerDoesNotBlock(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
a := NewStreamAssembler(ctx, "m")
ch := make(chan types.StreamResponse) // unbuffered, never read
done := make(chan struct{})
go func() {
defer close(done)
a.Process(ch, Delta{Content: "hello"})
a.Process(ch, Delta{FinishReason: "stop"})
a.End(ch)
}()
// Let the producer park on the first send, then drop the consumer.
time.Sleep(20 * time.Millisecond)
cancel()
select {
case <-done:
case <-time.After(2 * time.Second):
t.Fatal("producer still blocked after the consumer went away")
}
if !a.Aborted() {
t.Fatal("Aborted() = false, want true after an abandoned send")
}
}
// An already-cancelled context must abort deterministically rather than
// racing a ready channel.
func TestStreamAssembler_CancelledContextAbortsImmediately(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
a := NewStreamAssembler(ctx, "m")
ch := make(chan types.StreamResponse, 8)
a.Process(ch, Delta{Content: "hello"})
a.End(ch)
if len(ch) != 0 {
t.Fatalf("emitted %d chunks into an abandoned stream, want 0", len(ch))
}
if !a.Aborted() {
t.Fatal("Aborted() = false, want true")
}
}
// The live path must keep the exact chunk sequence the engine expects:
// thinking chunks, one thinking-done marker before the first answer token,
// the answer, then the closing chunk.
func TestStreamAssembler_ThinkingHandoffSequence(t *testing.T) {
a := NewStreamAssembler(context.Background(), "m")
ch := make(chan types.StreamResponse, 16)
a.Process(ch, Delta{Reasoning: "think"})
a.Process(ch, Delta{Content: "answer", FinishReason: "stop"})
a.End(ch)
close(ch)
type step struct {
kind types.ResponseType
done bool
text string
}
var got []step
for chunk := range ch {
got = append(got, step{chunk.ResponseType, chunk.Done, chunk.Content})
}
want := []step{
{types.ResponseTypeThinking, false, "think"},
{types.ResponseTypeThinking, true, ""},
{types.ResponseTypeAnswer, true, "answer"},
{types.ResponseTypeAnswer, true, ""},
}
if len(got) != len(want) {
t.Fatalf("sequence = %#v, want %#v", got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("chunk %d = %#v, want %#v", i, got[i], want[i])
}
}
}
// Tool-call indices belong to the vendor: gateways number from 1 and parallel
// calls arrive with gaps. Walking 0..len(map) dropped every call outside that
// range, and a round whose calls vanish reaches the agent as a plain answer.
func TestStreamAssembler_OrderedToolCallsNonContiguousIndices(t *testing.T) {
cases := []struct {
name string
indices []int
want []string
}{
{name: "zero based", indices: []int{0, 1}, want: []string{"f0", "f1"}},
{name: "one based", indices: []int{1, 2}, want: []string{"f1", "f2"}},
{name: "gapped", indices: []int{0, 3, 7}, want: []string{"f0", "f3", "f7"}},
{name: "out of order arrival", indices: []int{5, 2}, want: []string{"f2", "f5"}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
a := NewStreamAssembler(context.Background(), "m")
ch := make(chan types.StreamResponse, 64)
for _, idx := range tc.indices {
a.Process(ch, Delta{ToolCalls: []ToolCallDelta{{
Index: idx,
ID: fmt.Sprintf("call_%d", idx),
Name: fmt.Sprintf("f%d", idx),
Arguments: `{}`,
}}})
}
calls := a.OrderedToolCalls()
if len(calls) != len(tc.want) {
t.Fatalf("got %d calls %#v, want %d", len(calls), calls, len(tc.want))
}
for i, name := range tc.want {
if calls[i].Function.Name != name {
t.Fatalf("call %d = %q, want %q (order must follow the vendor index)",
i, calls[i].Function.Name, name)
}
}
})
}
}
// Metadata-only entries (a thought signature that arrives before its call)
// are kept too, whatever index the vendor gave them.
func TestStreamAssembler_OrderedToolCallsIncludesMetadataOnlyIndex(t *testing.T) {
a := NewStreamAssembler(context.Background(), "m")
a.SetToolCallMetadata(4, types.ToolCallMetadata{"thought_signature": []byte(`"sig"`)})
calls := a.OrderedToolCalls()
if len(calls) != 1 {
t.Fatalf("got %d calls, want 1", len(calls))
}
if calls[0].ProviderMetadata["thought_signature"] == nil {
t.Fatal("provider metadata lost")
}
}
+97
View File
@@ -0,0 +1,97 @@
// Package teirank implements the native Text Embeddings Inference rerank
// protocol. It sends {query, texts} to /rerank and reads a bare array of
// {index, score}; the deployed model is selected by the TEI server, not by
// a model field in each request.
package teirank
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
)
// Config supplies the endpoint and wire-level settings for a TEI reranker.
type Config struct {
Endpoint api.Endpoint
Settings api.RerankSettings
}
// Client sends rerank requests to a Text Embeddings Inference server.
type Client struct{ cfg Config }
// New creates a TEI rerank client for the supplied endpoint.
func New(cfg Config) *Client { return &Client{cfg: cfg} }
func (c *Client) url() string {
if c.cfg.Endpoint.URL != "" {
return c.cfg.Endpoint.Resolve("")
}
path := c.cfg.Settings.Path
if path == "" {
path = "/rerank"
}
if strings.HasSuffix(strings.TrimRight(c.cfg.Endpoint.BaseURL, "/"), path) {
path = ""
}
return c.cfg.Endpoint.Resolve(path)
}
type rank struct {
Index *int `json:"index"`
Score *float64 `json:"score"`
Text string `json:"text"`
}
// BuildRequestBody returns the native TEI request. raw_scores is explicit:
// false makes a single-class reranker's logits comparable with Academy's
// 0..1 relevance threshold. The model name is configured when TEI starts.
//
// Settings.ExtraBody is merged in but cannot replace query, texts or
// raw_scores. truncate defaults to true and may be overridden there: TEI
// before 1.9 starts with --auto-truncate=false and rejects the whole batch
// when one passage exceeds the model's input length.
func (c *Client) BuildRequestBody(query string, documents []string) map[string]any {
out := map[string]any{
"query": query,
"texts": documents,
"raw_scores": false,
}
for k, v := range c.cfg.Settings.ExtraBody {
if _, exists := out[k]; !exists {
out[k] = v
}
}
if _, set := out["truncate"]; !set {
out["truncate"] = true
}
return out
}
// Rerank scores documents with TEI and preserves their original indexes.
func (c *Client) Rerank(ctx context.Context, query string, documents []string) ([]api.RerankResult, error) {
var decoded []rank
if err := c.cfg.Endpoint.PostJSON(ctx, c.url(), c.BuildRequestBody(query, documents), &decoded); err != nil {
return nil, err
}
if len(decoded) != len(documents) {
return nil, fmt.Errorf("TEI returned %d ranks for %d documents", len(decoded), len(documents))
}
out := make([]api.RerankResult, 0, len(decoded))
seen := make([]bool, len(documents))
for _, item := range decoded {
if item.Index == nil || *item.Index < 0 || *item.Index >= len(documents) {
return nil, fmt.Errorf("TEI rerank index is missing or out of range for %d documents", len(documents))
}
if seen[*item.Index] {
return nil, fmt.Errorf("TEI returned duplicate rerank index %d", *item.Index)
}
if item.Score == nil {
return nil, fmt.Errorf("TEI rerank score is missing for index %d", *item.Index)
}
seen[*item.Index] = true
out = append(out, api.RerankResult{Index: *item.Index, Score: *item.Score, Text: item.Text})
}
return out, nil
}
+117
View File
@@ -0,0 +1,117 @@
package teirank
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"academy/internal/models/api"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// The TEI OpenAPI defines RerankResponse as a bare array of Rank, and gives
// these exact example values for Rank's index, score and optional text:
// https://github.com/huggingface/text-embeddings-inference/blob/main/docs/openapi.json#L1628-L1704
const openAPIRankExample = `[{"index":0,"score":1.0,"text":"Deep Learning is ..."}]`
func TestOpenAPIRankExampleAndNativeRequest(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path, authorization string
var body map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path, authorization = r.URL.Path, r.Header.Get("Authorization")
_ = json.NewDecoder(r.Body).Decode(&body)
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(openAPIRankExample))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{
BaseURL: server.URL, Model: "BAAI/bge-reranker-large", Auth: api.BearerAuth(""),
}})
got, err := c.Rerank(context.Background(), "What is Deep Learning?", []string{"Deep Learning is ..."})
require.NoError(t, err)
assert.Equal(t, "/rerank", path)
assert.Empty(t, authorization, "TEI works without an API key by default")
assert.Equal(t, map[string]any{
"query": "What is Deep Learning?", "texts": []any{"Deep Learning is ..."},
"raw_scores": false, "truncate": true,
}, body)
assert.NotContains(t, body, "model", "TEI chooses the model at server startup")
assert.Equal(t, []api.RerankResult{{Index: 0, Score: 1.0, Text: "Deep Learning is ..."}}, got)
}
func TestRankIndicesAndOptionalBearer(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
var path, authorization string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
path, authorization = r.URL.Path, r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`[{"index":2,"score":0.91},{"index":0,"score":0.62},{"index":1,"score":0.03}]`))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL + "/rerank", Auth: api.BearerAuth("secret")}})
got, err := c.Rerank(context.Background(), "q", []string{"same", "same", "relevant"})
require.NoError(t, err)
assert.Equal(t, "/rerank", path, "a pasted full endpoint must not gain a second /rerank")
assert.Equal(t, "Bearer secret", authorization)
assert.Equal(t, []api.RerankResult{
{Index: 2, Score: 0.91}, {Index: 0, Score: 0.62}, {Index: 1, Score: 0.03},
}, got, "the index, not echoed text, identifies duplicate candidate texts")
}
func TestRejectsMalformedRanks(t *testing.T) {
for _, tc := range []struct {
name, reply, want string
documents []string
}{
{"missing score", `[{"index":0}]`, "score is missing", []string{"d"}},
{"missing index", `[{"score":0.5}]`, "index is missing", []string{"d"}},
{"out of range", `[{"index":3,"score":0.5}]`, "out of range", []string{"d"}},
{"partial response", `[]`, "0 ranks for 1", []string{"d"}},
{"duplicate index", `[{"index":0,"score":0.5},{"index":0,"score":0.4}]`, "duplicate", []string{"a", "b"}},
} {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("SSRF_WHITELIST", "127.0.0.1")
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(tc.reply))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}})
_, err := c.Rerank(context.Background(), "q", tc.documents)
require.ErrorContains(t, err, tc.want)
})
}
}
func TestSurfacesTEIError(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.StatusUnprocessableEntity)
_, _ = w.Write([]byte(`{"error":"Tokenization error","error_type":"tokenizer"}`))
}))
defer server.Close()
c := New(Config{Endpoint: api.Endpoint{BaseURL: server.URL}})
_, err := c.Rerank(context.Background(), "q", []string{"d"})
require.ErrorContains(t, err, "Tokenization error")
}
// compat.extra_body reaches TEI like every other HTTP rerank protocol, but it
// cannot replace the fields the client owns. truncate is only a default.
func TestExtraBodyMergesWithoutReplacingCoreFields(t *testing.T) {
c := New(Config{Settings: api.RerankSettings{ExtraBody: map[string]any{
"query": "x",
"texts": []string{"x"},
"raw_scores": true,
"truncate": false,
"truncation_direction": "Left",
}}})
assert.Equal(t, map[string]any{
"query": "q", "texts": []string{"d"}, "raw_scores": false,
"truncate": false, "truncation_direction": "Left",
}, c.BuildRequestBody("q", []string{"d"}))
}
+103
View File
@@ -0,0 +1,103 @@
// Package tencentlkeap implements Tencent RunRerank through its official SDK.
package tencentlkeap
import (
"context"
"fmt"
"strings"
"academy/internal/models/api"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
lkeap "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/lkeap/v20240522"
)
// SDK defaults follow the managed rerank service.
const (
// LKEAPRerankEndpoint 腾讯云知识引擎原子能力 Rerank API 域名
LKEAPRerankEndpoint = "lkeap.tencentcloudapi.com"
// LKEAPDefaultRegion RunRerank 支持的地域,默认广州
LKEAPDefaultRegion = "ap-guangzhou"
// LKEAPDefaultRerankModel 默认 rerank 模型名
LKEAPDefaultRerankModel = "lke-reranker-base"
)
// Config contains resolved connection parameters for the SDK client.
type Config struct{ SecretID, SecretKey, Region, Model, Endpoint, Scheme string }
// lkeapClient calls Tencent Cloud's RunRerank action through the official
// SDK, which owns the TC3 signing this API requires. It implements
// api.Reranker and nothing else: the per-request ceilings (60 documents,
// 2000 characters for Query plus Docs together) are declared on the vendor
// and enforced by protocolReranker, like every other vendor's.
type lkeapClient struct {
modelName string
client *lkeap.Client
}
// New creates an authenticated rerank protocol client.
func New(config Config) (api.Reranker, error) {
secretID, secretKey := strings.TrimSpace(config.SecretID), strings.TrimSpace(config.SecretKey)
if secretID == "" || secretKey == "" {
return nil, fmt.Errorf("secret_id and secret_key are required for LKEAP rerank (set API Key and Secret Key)")
}
region := strings.TrimSpace(config.Region)
if region == "" {
region = LKEAPDefaultRegion
}
if config.Endpoint == "" {
config.Endpoint = LKEAPRerankEndpoint
}
if config.Scheme == "" {
config.Scheme = "HTTPS"
}
credential := common.NewCredential(secretID, secretKey)
cpf := profile.NewClientProfile()
cpf.HttpProfile.Endpoint = config.Endpoint
cpf.HttpProfile.Scheme = config.Scheme
client, err := lkeap.NewClient(credential, region, cpf)
if err != nil {
return nil, fmt.Errorf("create LKEAP client: %w", err)
}
modelName := strings.TrimSpace(config.Model)
if modelName == "" {
modelName = LKEAPDefaultRerankModel
}
return &lkeapClient{modelName: modelName, client: client}, nil
}
// Rerank scores one batch. RunRerank answers a bare score list in input
// order rather than an indexed, sorted result set.
func (r *lkeapClient) Rerank(
ctx context.Context, query string, documents []string,
) ([]api.RerankResult, error) {
req := lkeap.NewRunRerankRequest()
req.Query = common.StringPtr(query)
req.Docs = common.StringPtrs(documents)
req.Model = common.StringPtr(r.modelName)
resp, err := r.client.RunRerankWithContext(ctx, req)
if err != nil {
return nil, fmt.Errorf("LKEAP RunRerank: %w", err)
}
if resp == nil || resp.Response == nil || len(resp.Response.ScoreList) == 0 {
return nil, fmt.Errorf("LKEAP rerank API returned empty score list")
}
scores := resp.Response.ScoreList
if len(scores) != len(documents) {
return nil, fmt.Errorf("LKEAP rerank score count mismatch: got %d scores for %d documents",
len(scores), len(documents))
}
results := make([]api.RerankResult, len(documents))
for i, score := range scores {
results[i] = api.RerankResult{Index: i, Text: documents[i]}
if score != nil {
results[i].Score = *score
}
}
return results, nil
}
+36
View File
@@ -0,0 +1,36 @@
package api
import "academy/internal/types"
// ThinkingEmitter owns the "reasoning then answer" hand-off that every
// streaming Chat implementation shares: thinking chunks are forwarded as they
// arrive, and exactly one thinking-done marker is emitted before the first
// answer token (or when the stream ends without one). Centralizing the
// bookkeeping keeps the OpenAI-compatible and Ollama stream loops in sync.
type ThinkingEmitter struct {
active bool
}
// Emit forwards a reasoning chunk and records that a thinking-done marker is
// still owed.
func (e *ThinkingEmitter) Emit(ch chan<- types.StreamResponse, content string) {
e.active = true
ch <- types.StreamResponse{
ResponseType: types.ResponseTypeThinking,
Content: content,
Done: false,
}
}
// Finish emits the single thinking-done marker if one is owed. Safe to call
// multiple times; only the first call after an emit sends anything.
func (e *ThinkingEmitter) Finish(ch chan<- types.StreamResponse) {
if !e.active {
return
}
e.active = false
ch <- types.StreamResponse{
ResponseType: types.ResponseTypeThinking,
Done: true,
}
}
+56
View File
@@ -0,0 +1,56 @@
package api
import "context"
// TranscriptionAPI names a speech-to-text wire protocol. Like RerankAPI and
// EmbeddingAPI it is its own type, so no other modality's value validates.
type TranscriptionAPI string
// The transcription protocols Academy speaks.
const (
// TranscriptionOpenAI is POST {base}/audio/transcriptions as a multipart
// form carrying file and model, answering {text} — or {text, segments}
// when verbose_json is asked for.
TranscriptionOpenAI TranscriptionAPI = "openai-transcriptions"
// TranscriptionChatAudio is a dedicated speech-recognition model behind
// POST {base}/chat/completions: the audio goes in as a base64 data URI in
// an input_audio content part and the transcript comes back as the
// assistant message. Alibaba's qwen3-asr-flash and Xiaomi's mimo-v2.5-asr
// take no instruction; the model only transcribes.
TranscriptionChatAudio TranscriptionAPI = "openai-chat-audio"
)
// Known reports whether the value names a protocol this build implements.
func (a TranscriptionAPI) Known() bool {
return a == TranscriptionOpenAI || a == TranscriptionChatAudio
}
// TranscriptionSegment is one timed stretch of a transcript.
type TranscriptionSegment struct {
Start float64
End float64
Text string
}
// Transcription is what a protocol client returns.
type Transcription struct {
Text string
Segments []TranscriptionSegment
// Duration is the audio length in seconds when the reply states it —
// OpenAI-shaped duration or usage.seconds — and 0 otherwise.
Duration float64
}
// TranscriptionRequest is one file to transcribe.
type TranscriptionRequest struct {
Audio []byte
FileName string
// Language is the operator's hint, empty for auto-detection. Where it is
// sent, and whether at all, is the vendor's declaration.
Language string
}
// Transcriber turns one audio file into text.
type Transcriber interface {
Transcribe(ctx context.Context, req TranscriptionRequest) (*Transcription, error)
}
@@ -0,0 +1,68 @@
package api
// Where a transcription protocol puts the operator's language hint. Each
// vendor documents one place, or none.
const (
// LanguageForm is a multipart field named language (OpenAI's shape,
// ISO-639-1).
LanguageForm = "form"
// LanguageHeader is an HTTP request header named language (MiniMax,
// BCP-47).
LanguageHeader = "header"
// LanguageASROptions is asr_options.language in a chat-served request
// body (Alibaba, Xiaomi).
LanguageASROptions = "asr_options"
)
// TranscriptionsCompat is the overlay form (every field optional) of the
// speech-to-text settings. JSON keys are the names used in models.json.
type TranscriptionsCompat struct {
API *TranscriptionAPI `json:"api,omitempty"`
Path *string `json:"path,omitempty"`
// ResponseFormat is sent as response_format when non-empty. OpenAI's
// gpt-4o-transcribe and gpt-4o-mini-transcribe accept only json, which is
// also the default, so most models leave it unset.
ResponseFormat *string `json:"response_format,omitempty"`
// LanguageParam names where the language hint goes: form, header or
// asr_options; empty sends none.
LanguageParam *string `json:"language_param,omitempty"`
// MaxFileBytes is the documented upload ceiling for the audio itself.
MaxFileBytes *int `json:"max_file_bytes,omitempty"`
// MaxEncodedBytes is the documented ceiling on the base64 data URI, for
// the protocols that send the audio that way.
MaxEncodedBytes *int `json:"max_encoded_bytes,omitempty"`
// Formats lists the file extensions the vendor documents, without the
// dot. Empty means the vendor documents no closed list.
Formats []string `json:"formats,omitempty"`
RequestTimeout *int `json:"request_timeout_seconds,omitempty"`
// UnsupportedReason marks a model this build cannot call.
UnsupportedReason *string `json:"unsupported_reason,omitempty"`
}
// TranscriptionsSettings is the resolved (fully defaulted) form.
type TranscriptionsSettings struct {
API TranscriptionAPI
Path string
ResponseFormat string
LanguageParam string
// MaxFileBytes and MaxEncodedBytes refuse an upload the vendor would
// reject anyway, before sending it; 0 leaves the check to the vendor.
MaxFileBytes int
MaxEncodedBytes int
Formats []string
// RequestTimeout caps one request, in seconds.
RequestTimeout int
// UnsupportedReason is set where a vendor's recognition models, or some
// of them, cannot be called with the audio in the request — they take a
// public URL or run as asynchronous tasks. Resolve refuses such a model
// rather than sending it a shape it does not accept.
UnsupportedReason string
}
// DefaultTranscriptions is the protocol baseline: a form with file and model
// and nothing else, which every speech-to-text endpoint in this catalog
// documents. The deadline is the one the pre-catalog client carried; audio
// transcription is slow.
func DefaultTranscriptions() TranscriptionsSettings {
return TranscriptionsSettings{Path: "/audio/transcriptions", RequestTimeout: 300}
}
+63
View File
@@ -0,0 +1,63 @@
package api
import (
"context"
"net/http"
"os"
"strconv"
"strings"
"time"
secutils "academy/internal/utils"
)
// LLM 调用超时配置。仅作为"上层未设置 deadline 时"的兜底,避免 hung 请求
// 永久阻塞 worker。如果上层 ctx 已经设置了 deadline(无论比默认更短还是更长),
// 都会原样尊重,不再叠加默认超时。可通过环境变量覆盖:
// - ACADEMY_LLM_CHAT_TIMEOUT_SECONDS 非流式调用兜底超时(默认 600s)
// - ACADEMY_LLM_STREAM_TIMEOUT_SECONDS 流式调用兜底超时(默认 1800s)
var (
DefaultChatTimeout = envDurationSeconds("ACADEMY_LLM_CHAT_TIMEOUT_SECONDS", 300*time.Second)
DefaultStreamTimeout = envDurationSeconds("ACADEMY_LLM_STREAM_TIMEOUT_SECONDS", 600*time.Second)
)
// envDurationSeconds 读取以"秒"为单位的环境变量,解析失败或非正值时回退到 fallback。
func envDurationSeconds(key string, fallback time.Duration) time.Duration {
v := strings.TrimSpace(os.Getenv(key))
if v == "" {
return fallback
}
n, err := strconv.Atoi(v)
if err != nil || n <= 0 {
return fallback
}
return time.Duration(n) * time.Second
}
// WithLLMTimeout 仅在上层 ctx 没有 deadline 时附加一个兜底超时;
// 如果上层已显式设置 deadline(无论更短或更长),则原样返回,
// 让调用方对自己的超时策略拥有最终决定权。
func WithLLMTimeout(ctx context.Context, d time.Duration) (context.Context, context.CancelFunc) {
if _, ok := ctx.Deadline(); ok {
return ctx, func() {}
}
return context.WithTimeout(ctx, d)
}
// HTTPClient is a shared HTTP client for raw HTTP LLM calls with connection-level timeouts.
// Per-request timeout is enforced via context deadline (see DefaultChatTimeout / DefaultStreamTimeout)
// rather than http.Client.Timeout, so streaming calls are not prematurely terminated.
// Uses SSRFSafeDialContext to prevent DNS rebinding attacks at the connection layer.
var httpTransport = &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: secutils.SSRFSafeDialContext,
TLSHandshakeTimeout: 10 * time.Second,
IdleConnTimeout: 90 * time.Second,
MaxIdleConnsPerHost: 5,
}
// HTTPClient is the shared SSRF-safe client every protocol uses.
var HTTPClient = secutils.NewSSRFSafeHTTPClientWithTransport(
secutils.SSRFSafeHTTPClientConfig{Timeout: 0, MaxRedirects: 10},
httpTransport,
)
+86
View File
@@ -0,0 +1,86 @@
package api
import (
"context"
"os"
"testing"
"time"
)
func TestWithLLMTimeout_NoParentDeadline_AppliesDefault(t *testing.T) {
ctx, cancel := WithLLMTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
dl, ok := ctx.Deadline()
if !ok {
t.Fatalf("expected deadline to be set when parent has none")
}
if remaining := time.Until(dl); remaining <= 0 || remaining > 50*time.Millisecond {
t.Fatalf("unexpected remaining duration: %v", remaining)
}
}
func TestWithLLMTimeout_ShorterParentDeadline_Respected(t *testing.T) {
parent, parentCancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
defer parentCancel()
ctx, cancel := WithLLMTimeout(parent, 10*time.Second)
defer cancel()
dl, _ := ctx.Deadline()
if remaining := time.Until(dl); remaining > 30*time.Millisecond {
t.Fatalf("parent shorter deadline should be respected, got remaining=%v", remaining)
}
}
func TestWithLLMTimeout_LongerParentDeadline_NotTruncated(t *testing.T) {
parent, parentCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer parentCancel()
ctx, cancel := WithLLMTimeout(parent, 50*time.Millisecond)
defer cancel()
dl, ok := ctx.Deadline()
if !ok {
t.Fatalf("deadline must be set")
}
if remaining := time.Until(dl); remaining < 5*time.Second {
t.Fatalf("parent longer deadline should NOT be truncated by default, got remaining=%v", remaining)
}
}
func TestEnvDurationSeconds(t *testing.T) {
const key = "ACADEMY_TEST_TIMEOUT_SECONDS"
t.Run("unset returns fallback", func(t *testing.T) {
os.Unsetenv(key)
if got := envDurationSeconds(key, 7*time.Second); got != 7*time.Second {
t.Fatalf("got %v", got)
}
})
t.Run("valid value parsed", func(t *testing.T) {
t.Setenv(key, "42")
if got := envDurationSeconds(key, 1*time.Second); got != 42*time.Second {
t.Fatalf("got %v", got)
}
})
t.Run("invalid falls back", func(t *testing.T) {
t.Setenv(key, "not-a-number")
if got := envDurationSeconds(key, 9*time.Second); got != 9*time.Second {
t.Fatalf("got %v", got)
}
})
t.Run("non-positive falls back", func(t *testing.T) {
t.Setenv(key, "0")
if got := envDurationSeconds(key, 9*time.Second); got != 9*time.Second {
t.Fatalf("got %v", got)
}
t.Setenv(key, "-5")
if got := envDurationSeconds(key, 9*time.Second); got != 9*time.Second {
t.Fatalf("got %v", got)
}
})
}
+304
View File
@@ -0,0 +1,304 @@
// Package api holds the protocol-neutral request model shared by every wire
// protocol implementation (OpenAI Chat Completions, OpenAI Responses,
// Anthropic Messages, Google Generative AI, Ollama) plus the helpers those
// implementations share: SSE reading, the SSRF-safe transport, streaming
// tool-call assembly, prompt-cache bookkeeping and usage logging.
//
// Protocol packages live under api/<protocol>; vendor facts live in
// internal/models/catalog and internal/models/providers. This package must not
// import either of them.
package api
import (
"encoding/json"
"strings"
"academy/internal/types"
)
// API identifies a wire protocol. It is the value of the "api" field in a
// vendor's models.json and decides which protocol package talks to the
// endpoint.
type API string
const (
// APIOpenAICompletions is the OpenAI Chat Completions protocol, the
// lingua franca of almost every third-party vendor.
APIOpenAICompletions API = "openai-completions"
// APIOpenAIResponses is the OpenAI Responses protocol.
APIOpenAIResponses API = "openai-responses"
// APIAnthropicMessages is the Anthropic Messages protocol, also exposed by
// MiniMax, Zhipu and Moonshot as a compatibility surface.
APIAnthropicMessages API = "anthropic-messages"
// APIGoogleGenerativeAI is the native Gemini generateContent protocol.
APIGoogleGenerativeAI API = "google-generative-ai"
// APIOllama is the local Ollama chat protocol.
APIOllama API = "ollama"
)
// Known reports whether the API value names a protocol this build ships.
func (a API) Known() bool {
switch a {
case APIOpenAICompletions, APIOpenAIResponses, APIAnthropicMessages, APIGoogleGenerativeAI, APIOllama:
return true
}
return false
}
// Tool represents a function/tool definition
type Tool struct {
Type string `json:"type"` // "function"
Function FunctionDef `json:"function"`
}
// FunctionDef represents a function definition
type FunctionDef struct {
Name string `json:"name"`
Description string `json:"description"`
Parameters json.RawMessage `json:"parameters"`
}
// MessageContentPart represents a part of multi-content message
type MessageContentPart struct {
Type string `json:"type"` // "text" or "image_url"
Text string `json:"text,omitempty"` // For type="text"
ImageURL *ImageURL `json:"image_url,omitempty"` // For type="image_url"
}
// ImageURL represents the image URL structure
type ImageURL struct {
URL string `json:"url"` // URL or base64 data URI
Detail string `json:"detail,omitempty"` // "auto", "low", "high"
}
// MessageKind marks messages the engine synthesized rather than received from
// the user or the model. Compaction needs to tell its own summary apart from a
// real user turn: a summary that looks like ordinary history gets fed back into
// the next summarization pass and degrades into a summary of a summary.
type MessageKind string
// MessageKindCompactionSummary marks the message that replaces compacted
// history. It carries the `user` role because that is where providers expect
// conversation history, so the role alone cannot identify it.
const MessageKindCompactionSummary MessageKind = "compaction_summary"
// Message 表示聊天消息
type Message struct {
Role string `json:"role"` // 角色:system, user, assistant, tool
Content string `json:"content"` // 消息内容
MultiContent []MessageContentPart `json:"multi_content,omitempty"` // 多内容消息(文本+图片)
Name string `json:"name,omitempty"` // Function/tool name (for tool role)
ToolCallID string `json:"tool_call_id,omitempty"` // Tool call ID (for tool role)
ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Tool calls (for assistant role)
// Images are image URLs for multimodal input (current user message only).
Images []string `json:"images,omitempty"`
// ReasoningContent 是 assistant 推理类模型上一轮输出的思考内容。部分供应商
// (MiMo、DeepSeek V3.2+、Kimi K2.5+)要求多轮对话中把 assistant 的
// reasoning_content 原样回传,否则会以 400 拒绝请求;其他不要求的供应商会
// 忽略未知字段。Anthropic 则要求把 thinking block 连同签名一起回放。
ReasoningContent string `json:"reasoning_content,omitempty"`
// ReasoningSignature is the provider-issued signature that must accompany
// ReasoningContent when it is replayed (Anthropic thinking blocks, Gemini
// thought signatures on text parts). Empty when the provider issues none.
ReasoningSignature string `json:"reasoning_signature,omitempty"`
// ReasoningMetadata carries opaque provider state that must round-trip
// with the assistant turn but has no protocol-neutral representation:
// OpenAI Responses reasoning items (encrypted_content), OpenRouter
// reasoning_details, and so on. Keyed by protocol / vendor namespace.
ReasoningMetadata types.ProviderMetadata `json:"reasoning_metadata,omitempty"`
// Kind is engine-internal bookkeeping. `json:"-"` keeps it off the wire:
// providers reject unknown message fields on some endpoints, and this one
// means nothing to them anyway.
Kind MessageKind `json:"-"`
// TurnID is the stored assistant message whose turn this history message
// was replayed from. It is empty for the live turn and for messages the
// engine synthesized. Compaction uses it to tell whether a summary ends
// exactly on a stored turn, the only kind it can persist for later turns.
// Engine-internal like Kind, and kept off the wire for the same reason.
TurnID string `json:"-"`
}
// ToolCall represents a tool call in a message
type ToolCall struct {
ID string `json:"id"`
Type string `json:"type"` // "function"
Function FunctionCall `json:"function"`
ProviderMetadata types.ToolCallMetadata `json:"provider_metadata,omitempty"`
}
// FunctionCall represents a function call
type FunctionCall struct {
Name string `json:"name"`
Arguments string `json:"arguments"` // JSON string
}
// ReasoningEffort is the protocol-neutral thinking level. Vendors map it onto
// their own vocabulary through a ThinkingLevelMap; the protocol package then
// emits whichever wire field the vendor documents (reasoning_effort,
// thinking.type, enable_thinking, thinkingConfig, ...).
type ReasoningEffort string
const (
// ReasoningOff disables extended thinking where the model allows it.
ReasoningOff ReasoningEffort = "off"
// ReasoningAuto enables thinking but leaves the intensity to the provider
// default. This is what the legacy boolean `thinking: true` maps to.
ReasoningAuto ReasoningEffort = "auto"
// ReasoningMinimal is the weakest graded level.
ReasoningMinimal ReasoningEffort = "minimal"
// ReasoningLow is the low graded level.
ReasoningLow ReasoningEffort = "low"
// ReasoningMedium is the medium graded level.
ReasoningMedium ReasoningEffort = "medium"
// ReasoningHigh is the high graded level.
ReasoningHigh ReasoningEffort = "high"
// ReasoningXHigh is the extra-high graded level (OpenAI, Zhipu).
ReasoningXHigh ReasoningEffort = "xhigh"
// ReasoningMax is the strongest graded level.
ReasoningMax ReasoningEffort = "max"
)
// ReasoningLadder lists the graded levels from weakest to strongest. Off and
// Auto are deliberately excluded: they are switches, not intensities.
var ReasoningLadder = []ReasoningEffort{
ReasoningMinimal, ReasoningLow, ReasoningMedium, ReasoningHigh, ReasoningXHigh, ReasoningMax,
}
// AllReasoningEfforts is every accepted value, in UI order.
var AllReasoningEfforts = append([]ReasoningEffort{ReasoningOff, ReasoningAuto}, ReasoningLadder...)
// ParseReasoningEffort validates a user-provided level. Empty input yields
// ("", true) meaning "unset: let the model default apply".
func ParseReasoningEffort(s string) (ReasoningEffort, bool) {
if s == "" {
return "", true
}
for _, level := range AllReasoningEfforts {
if string(level) == s {
return level, true
}
}
// Accept a few aliases the legacy boolean UI and provider docs use.
switch s {
case "none", "false", "disabled":
return ReasoningOff, true
case "true", "enabled", "default", "on":
return ReasoningAuto, true
}
return "", false
}
// Enabled reports whether the level asks for thinking to be on.
func (r ReasoningEffort) Enabled() bool {
return r != "" && r != ReasoningOff
}
// Graded reports whether the level is one of the intensity rungs.
func (r ReasoningEffort) Graded() bool {
for _, level := range ReasoningLadder {
if level == r {
return true
}
}
return false
}
// ThinkingLevelMap maps protocol-neutral levels to a vendor's own vocabulary.
//
// Semantics mirror Pi's thinkingLevelMap:
// - a missing key means "supported, pass the level name through" for
// minimal/low/medium/high and "unsupported" for xhigh/max;
// - a null value marks the level as unsupported (the caller clamps to the
// nearest supported rung);
// - a string value is what the vendor expects on the wire.
//
// The special key "off" may be mapped to null to state that thinking cannot
// be switched off (always-on reasoning models).
type ThinkingLevelMap map[ReasoningEffort]*string
// Supports reports whether the level is usable for this model.
func (m ThinkingLevelMap) Supports(level ReasoningEffort) bool {
if v, ok := m[level]; ok {
return v != nil
}
switch level {
case ReasoningXHigh, ReasoningMax:
return false
case ReasoningOff, ReasoningAuto:
return true
}
return true
}
// Value returns the vendor value for a supported level. Unmapped levels
// pass through under their own name.
func (m ThinkingLevelMap) Value(level ReasoningEffort) string {
if v, ok := m[level]; ok && v != nil {
return *v
}
return string(level)
}
// Clamp returns the nearest supported graded level: first upward, then
// downward, mirroring Pi's clampThinkingLevel. Off/Auto are returned as-is
// (Off may still be unsupported; callers check Supports(ReasoningOff)).
func (m ThinkingLevelMap) Clamp(level ReasoningEffort) ReasoningEffort {
if !level.Graded() {
return level
}
if m.Supports(level) {
return level
}
idx := -1
for i, l := range ReasoningLadder {
if l == level {
idx = i
break
}
}
for i := idx + 1; i < len(ReasoningLadder); i++ {
if m.Supports(ReasoningLadder[i]) {
return ReasoningLadder[i]
}
}
for i := idx - 1; i >= 0; i-- {
if m.Supports(ReasoningLadder[i]) {
return ReasoningLadder[i]
}
}
return ReasoningAuto
}
// SupportedLevels lists the levels this map accepts, in UI order.
func (m ThinkingLevelMap) SupportedLevels() []ReasoningEffort {
out := make([]ReasoningEffort, 0, len(AllReasoningEfforts))
for _, level := range AllReasoningEfforts {
if m.Supports(level) {
out = append(out, level)
}
}
return out
}
// StringPtr is a small helper for building ThinkingLevelMap literals.
func StringPtr(s string) *string { return &s }
// TagSignature records which protocol issued a reasoning signature. Stored
// signatures are opaque to every other provider, so they must only be
// replayed to the protocol that produced them.
func TagSignature(protocol API, signature string) string {
if signature == "" {
return ""
}
return string(protocol) + ":" + signature
}
// SignatureFor returns the raw signature when it was issued by protocol, and
// "" for signatures from another protocol or without a protocol tag.
func SignatureFor(protocol API, tagged string) string {
prefix := string(protocol) + ":"
if !strings.HasPrefix(tagged, prefix) {
return ""
}
return strings.TrimPrefix(tagged, prefix)
}
+73
View File
@@ -0,0 +1,73 @@
package api
import "academy/internal/types"
// OpenAIUsage is the superset of the usage shapes OpenAI-compatible
// endpoints return. Vendors disagree on where cache counters live:
// - OpenAI / Azure / most gateways: prompt_tokens_details.cached_tokens
// - DeepSeek: prompt_cache_hit_tokens / prompt_cache_miss_tokens
// - Kimi: top-level cached_tokens
// - Anthropic-through-OpenRouter: cache_read_input_tokens / cache_creation_input_tokens
//
// All of them are decoded here so protocol code never guesses per vendor.
type OpenAIUsage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
PromptCacheHitTokens *int `json:"prompt_cache_hit_tokens"`
PromptCacheMissTokens *int `json:"prompt_cache_miss_tokens"`
CachedTokens *int `json:"cached_tokens"`
CacheReadInputTokens *int `json:"cache_read_input_tokens"`
CacheCreationInputTokens *int `json:"cache_creation_input_tokens"`
PromptTokensDetails *struct {
CachedTokens *int `json:"cached_tokens"`
CacheWriteTokens *int `json:"cache_write_tokens"`
} `json:"prompt_tokens_details"`
CompletionTokensDetails *struct {
ReasoningTokens int `json:"reasoning_tokens"`
} `json:"completion_tokens_details"`
}
// ToTokenUsage normalizes the counters. cacheAccounting states whether the
// vendor documents prompt-cache accounting at all: when it does not, a
// missing counter means "unsupported" rather than "unreported".
func (u OpenAIUsage) ToTokenUsage(cacheAccounting bool) types.TokenUsage {
out := types.TokenUsage{
PromptTokens: u.PromptTokens,
CompletionTokens: u.CompletionTokens,
TotalTokens: u.TotalTokens,
}
if out.TotalTokens == 0 {
out.TotalTokens = out.PromptTokens + out.CompletionTokens
}
switch {
case u.PromptCacheHitTokens != nil || u.PromptCacheMissTokens != nil:
read := valueOrZero(u.PromptCacheHitTokens)
miss := valueOrZero(u.PromptCacheMissTokens)
out.SetPromptCacheUsage(read, 0, miss, true)
case u.CacheReadInputTokens != nil || u.CacheCreationInputTokens != nil:
read := valueOrZero(u.CacheReadInputTokens)
write := valueOrZero(u.CacheCreationInputTokens)
out.SetPromptCacheUsage(read, write, max(0, u.PromptTokens-read), true)
case u.PromptTokensDetails != nil &&
(u.PromptTokensDetails.CachedTokens != nil || u.PromptTokensDetails.CacheWriteTokens != nil):
read := valueOrZero(u.PromptTokensDetails.CachedTokens)
write := valueOrZero(u.PromptTokensDetails.CacheWriteTokens)
out.SetPromptCacheUsage(read, write, max(0, u.PromptTokens-read), true)
case u.CachedTokens != nil:
read := valueOrZero(u.CachedTokens)
out.SetPromptCacheUsage(read, 0, max(0, u.PromptTokens-read), true)
case cacheAccounting:
out.SetPromptCacheUsage(0, 0, 0, false)
default:
out.MarkPromptCacheUnsupported()
}
return out
}
func valueOrZero(value *int) int {
if value == nil {
return 0
}
return *value
}
+46
View File
@@ -0,0 +1,46 @@
package api
import (
"context"
"strings"
"academy/internal/logger"
"academy/internal/types"
)
// LogUsage emits the standard "[LLM Usage]" line shared by every Chat
// implementation. It is a no-op when usage is nil so callers can pass through
// optional usage blocks without guarding at each call site.
func LogUsage(ctx context.Context, model string, u *types.TokenUsage) {
if u == nil {
return
}
purpose, prefixFingerprint := types.LLMCallMetadataFromContext(ctx)
logger.Infof(ctx,
"[LLM Usage] model=%s, purpose=%s, prompt_prefix=%s, prompt_tokens=%d, completion_tokens=%d, "+
"total_tokens=%d, cached_tokens=%d, cache_read_tokens=%d, cache_write_tokens=%d, "+
"cache_miss_tokens=%d, cache_hit_rate=%.1f%%, cache_reported=%t, cache_status=%s%s",
model, purpose, prefixFingerprint, u.PromptTokens, u.CompletionTokens, u.TotalTokens,
u.CachedTokens, u.CacheReadTokens, u.CacheWriteTokens, u.CacheMissTokens,
u.PromptCacheHitRate(), u.CacheReported, u.CacheStatus, usageAttribution(ctx))
}
// usageAttribution renders the ", session_id=…, principal=…" suffix that
// attributes a usage line to the session and terminal principal that
// triggered the call. Calls that run outside a session or without a resolved
// principal (document parsing, title generation, background jobs) render an
// empty suffix, keeping their lines byte-identical to before.
func usageAttribution(ctx context.Context) string {
var b strings.Builder
if sessionID, ok := types.SessionIDFromContext(ctx); ok && sessionID != "" {
b.WriteString(", session_id=")
b.WriteString(sessionID)
}
if principal, ok := types.PrincipalFromContext(ctx); ok {
b.WriteString(", principal=")
b.WriteString(principal.Type)
b.WriteString(":")
b.WriteString(principal.ID)
}
return b.String()
}
+34
View File
@@ -0,0 +1,34 @@
package api
import (
"context"
"testing"
"academy/internal/types"
)
func TestUsageAttributionEmptyOutsideSessions(t *testing.T) {
// Calls without session or principal context (document parsing, title
// generation, background jobs) must keep the usage line byte-identical.
if got := usageAttribution(context.Background()); got != "" {
t.Fatalf("expected empty suffix, got %q", got)
}
}
func TestUsageAttributionCarriesSessionAndPrincipal(t *testing.T) {
ctx := types.WithSessionID(context.Background(), "sess-123")
ctx = types.WithPrincipal(ctx, types.Principal{Type: types.PrincipalAPIExternalUser, ID: "10000:42"})
got := usageAttribution(ctx)
want := ", session_id=sess-123, principal=api_external_user:10000:42"
if got != want {
t.Fatalf("got %q want %q", got, want)
}
}
func TestUsageAttributionSessionOnly(t *testing.T) {
ctx := types.WithSessionID(context.Background(), "sess-9")
if got := usageAttribution(ctx); got != ", session_id=sess-9" {
t.Fatalf("got %q", got)
}
}
@@ -0,0 +1,116 @@
// Package volcengineknowledge implements Volcengine Knowledge Service rerank through its official SDK.
package volcengineknowledge
import (
"context"
"fmt"
"net/http"
"strings"
"time"
"academy/internal/models/api"
"github.com/volcengine/vikingdb-go-sdk/knowledge"
knowledgemodel "github.com/volcengine/vikingdb-go-sdk/knowledge/model"
)
// SDK defaults follow the managed rerank service.
const (
DefaultModel = "doubao-seed-rerank"
DefaultRegion = "cn-beijing"
// DefaultInstruction is the console's default instruction, verbatim: "如需对齐控制台效果,请使用
// 相同指令" (https://docs.volcengine.com/docs/vector_database_vikingdb/Rerank).
DefaultInstruction = "Whether the document answers the query " +
"or matches the content retrieval intent"
)
// volcengineClient calls the managed Knowledge Service rerank through the
// vikingdb SDK, which owns the AK/SK signing. It implements api.Reranker and
// nothing else: the 200-document ceiling and the batch concurrency are
// declared on the vendor and enforced by protocolReranker.
type volcengineClient struct {
modelName string
instruction string
client *knowledge.Client
}
// Config contains resolved connection parameters for the SDK client.
type Config struct {
AccessKey, SecretKey, BaseURL, Model, Region, Instruction string
Client *http.Client
}
// New creates an authenticated rerank protocol client.
func New(config Config) (api.Reranker, error) {
accessKey, secretKey := strings.TrimSpace(config.AccessKey), strings.TrimSpace(config.SecretKey)
if accessKey == "" || secretKey == "" {
return nil, fmt.Errorf("access key and secret key are required for Volcengine rerank")
}
baseURL := config.BaseURL
modelName := strings.TrimSpace(config.Model)
if modelName == "" {
modelName = DefaultModel
}
region := strings.TrimSpace(config.Region)
if region == "" {
region = DefaultRegion
}
instruction := strings.TrimSpace(config.Instruction)
if instruction == "" {
instruction = DefaultInstruction
}
if config.Client == nil {
config.Client = api.HTTPClient
}
client, err := knowledge.New(
knowledge.AuthIAM(accessKey, secretKey),
knowledge.WithEndpoint(baseURL),
knowledge.WithRegion(region),
knowledge.WithTimeout(30*time.Second),
knowledge.WithHTTPClient(config.Client),
knowledge.WithMaxRetries(1),
)
if err != nil {
return nil, fmt.Errorf("create Volcengine rerank client: %w", err)
}
return &volcengineClient{modelName: modelName, instruction: instruction, client: client}, nil
}
// Rerank scores one batch. Every document is paired with the same query and
// instruction, and the reply is a score list in input order.
func (r *volcengineClient) Rerank(
ctx context.Context, query string, documents []string,
) ([]api.RerankResult, error) {
data := make([]knowledgemodel.RerankDataItem, len(documents))
for i := range documents {
data[i] = knowledgemodel.RerankDataItem{Query: query, Content: &documents[i]}
}
request := knowledgemodel.RerankRequest{
Datas: data,
RerankModel: &r.modelName,
RerankInstruction: &r.instruction,
}
response, err := r.client.Rerank(ctx, request)
if err != nil {
return nil, fmt.Errorf("call Volcengine rerank: %w", err)
}
if response == nil || response.Data == nil {
return nil, fmt.Errorf("volcengine rerank returned an empty response")
}
if response.Code != 0 {
return nil, fmt.Errorf("volcengine rerank API error %d: %s", response.Code, response.Message)
}
if len(response.Data.Scores) != len(documents) {
return nil, fmt.Errorf(
"volcengine rerank score count mismatch: got %d scores for %d documents",
len(response.Data.Scores), len(documents),
)
}
results := make([]api.RerankResult, len(documents))
for i, score := range response.Data.Scores {
results[i] = api.RerankResult{Index: i, Score: score, Text: documents[i]}
}
return results, nil
}