chore: 项目基线(基于 WeKnora 定制版,整理文件忽略规则)

This commit is contained in:
runny committed 2026-11-13 17:54:56 +08:00
commit 9097ee699d
5769 files changed
+1446466

No files matched your search

@@ -0,0 +1,441 @@
package openaicompletions
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/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 WeKnora'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"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/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"
"github.com/Tencent/WeKnora/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 (WeKnora 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"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/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, "WeKnora", 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"
"github.com/Tencent/WeKnora/internal/models/api"
"github.com/Tencent/WeKnora/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"))
}