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,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
}