Initial commit: Go agentic harness extracted from Felix

This commit is contained in:
sausheong committed 2026-05-07 11:31:42 +08:00
commit 1f2c471ff9
89 files changed
+19388

No files matched your search

+545
View File
@@ -0,0 +1,545 @@
package anthropic
import (
"context"
"encoding/base64"
"encoding/json"
"log/slog"
"strings"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/anthropics/anthropic-sdk-go/option"
"github.com/sausheong/harness/llm"
)
// AnthropicProvider implements llm.LLMProvider using the Anthropic Messages API.
type AnthropicProvider struct {
client anthropic.Client
}
// NewAnthropicProvider creates a new Anthropic LLM provider.
// If baseURL is non-empty, the client points to that endpoint.
func NewAnthropicProvider(apiKey, baseURL string) *AnthropicProvider {
opts := []option.RequestOption{option.WithAPIKey(apiKey)}
if baseURL != "" {
opts = append(opts, option.WithBaseURL(baseURL))
}
client := anthropic.NewClient(opts...)
return &AnthropicProvider{client: client}
}
func (p *AnthropicProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "claude-sonnet-4-5-20250514", Name: "Claude Sonnet 4.5", Provider: "anthropic"},
{ID: "claude-opus-4-0-20250514", Name: "Claude Opus 4", Provider: "anthropic"},
{ID: "claude-haiku-3-5-20241022", Name: "Claude Haiku 3.5", Provider: "anthropic"},
}
}
// buildMessageParams assembles the anthropic.MessageNewParams shared by
// ChatStream and ChatNonStreaming. Pure: same input → same output (so a
// stream-fallback non-streaming retry sends the same bytes the streaming
// call did, preserving the prompt cache prefix).
func (p *AnthropicProvider) buildMessageParams(req llm.ChatRequest) anthropic.MessageNewParams {
msgs := buildAnthropicMessages(req.Messages, req.CacheLastMessage)
tools := make([]anthropic.ToolUnionParam, 0, len(req.Tools))
for _, t := range req.Tools {
var props any
var required []string
var schema struct {
Properties any `json:"properties"`
Required []string `json:"required"`
}
if err := json.Unmarshal(t.Parameters, &schema); err == nil {
props = schema.Properties
required = schema.Required
}
tools = append(tools, anthropic.ToolUnionParam{
OfTool: &anthropic.ToolParam{
Name: t.Name,
Description: anthropic.String(t.Description),
InputSchema: anthropic.ToolInputSchemaParam{
Properties: props,
Required: required,
},
},
})
}
maxTokens := int64(req.MaxTokens)
if maxTokens == 0 {
maxTokens = 4096
}
model := req.Model
if model == "" {
model = "claude-sonnet-4-5-20250514"
}
params := anthropic.MessageNewParams{
Model: anthropic.Model(model),
MaxTokens: maxTokens,
Messages: msgs,
}
if len(tools) > 0 {
params.Tools = tools
}
if sys := buildAnthropicSystem(req); len(sys) > 0 {
params.System = sys
}
if req.Temperature > 0 {
params.Temperature = anthropic.Float(req.Temperature)
}
if cfg, ok := p.BuildThinkingConfig(model, req.Reasoning); ok {
required := cfg.BudgetTokens + 4096
if maxTokens < required {
maxTokens = required
params.MaxTokens = maxTokens
}
params.Thinking = anthropic.ThinkingConfigParamUnion{
OfEnabled: &anthropic.ThinkingConfigEnabledParam{
BudgetTokens: cfg.BudgetTokens,
},
}
slog.Info("anthropic thinking enabled",
"model", model,
"budget_tokens", cfg.BudgetTokens,
"max_tokens", maxTokens)
} else if req.Reasoning != llm.ReasoningOff {
slog.Info("reasoning ignored",
"provider", "anthropic",
"model", model,
"requested", string(req.Reasoning),
"reason", "model does not support thinking")
}
return params
}
func (p *AnthropicProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
params := p.buildMessageParams(req)
// Create stream
stream := p.client.Messages.NewStreaming(ctx, params)
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
defer stream.Close()
// Track tool calls being built up across events.
//
// startInput captures any input that arrives on content_block_start.
// Canonical Anthropic streams send `{}` here and stream the real
// input via input_json_delta events, but Anthropic-shaped proxies
// that route non-Anthropic responses (e.g., platformai routing
// Gemini-Pro/Flash through an Anthropic API) emit the FULL tool
// input on content_block_start with NO subsequent deltas — Gemini
// doesn't natively stream tool arguments. Without capturing it
// here we'd hand the MCP tool an empty input and the server would
// reject the JSON-RPC envelope as Bad Request.
type pendingTC struct {
id string
name string
inputJSON string // built from input_json_delta events
startInput string // captured from content_block_start (proxy fallback)
}
var pendingTools []pendingTC
var currentBlockType string
var inputTokens, cacheCreationTokens, cacheReadTokens int64
for stream.Next() {
event := stream.Current()
switch event.Type {
case "message_start":
u := event.Message.Usage
inputTokens = u.InputTokens
cacheCreationTokens = u.CacheCreationInputTokens
cacheReadTokens = u.CacheReadInputTokens
case "content_block_start":
cb := event.ContentBlock
switch cb.Type {
case "text":
currentBlockType = "text"
case "tool_use":
currentBlockType = "tool_use"
pending := pendingTC{
id: cb.ID,
name: cb.Name,
}
if cb.Input != nil {
if data, err := json.Marshal(cb.Input); err == nil {
s := string(data)
if s != "null" && s != "{}" {
pending.startInput = s
}
}
}
pendingTools = append(pendingTools, pending)
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: cb.ID,
Name: cb.Name,
},
}
}
case "content_block_delta":
delta := event.Delta
switch delta.Type {
case "text_delta":
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: delta.Text,
}
case "input_json_delta":
if len(pendingTools) > 0 {
pendingTools[len(pendingTools)-1].inputJSON += delta.PartialJSON
}
}
case "content_block_stop":
if currentBlockType == "tool_use" && len(pendingTools) > 0 {
tc := pendingTools[len(pendingTools)-1]
// Prefer streamed deltas (canonical Anthropic). Fall
// back to start-time input (proxy emitting full input
// upfront). Default to "{}" so MCP servers receive a
// valid empty-args envelope rather than null/empty.
inp := tc.inputJSON
if inp == "" {
inp = tc.startInput
}
if inp == "" {
inp = "{}"
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(inp),
},
}
}
currentBlockType = ""
case "message_delta":
if event.Usage.OutputTokens > 0 || cacheCreationTokens > 0 || cacheReadTokens > 0 {
slog.Info("anthropic stream usage",
"input_tokens", inputTokens,
"output_tokens", event.Usage.OutputTokens,
"cache_creation_input_tokens", cacheCreationTokens,
"cache_read_input_tokens", cacheReadTokens,
)
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(inputTokens),
OutputTokens: int(event.Usage.OutputTokens),
CacheCreationInputTokens: int(cacheCreationTokens),
CacheReadInputTokens: int(cacheReadTokens),
},
}
}
case "message_stop":
// Final event — nothing extra to emit
case "error":
slog.Error("anthropic stream error", "event", event.Type)
}
}
if err := stream.Err(); err != nil {
events <- llm.ChatEvent{
Type: llm.EventError,
Error: err,
}
}
}()
return events, nil
}
// ChatNonStreaming implements llm.NonStreamingProvider — same request
// shape as ChatStream, but uses the non-streaming Messages.New endpoint
// and synthesises the same event sequence the streaming path would have
// emitted on success. The runtime falls back to this when a stream dies
// mid-flight; the partial output of the failed stream is discarded so
// the prompt cache prefix on the next turn stays byte-identical.
//
// Note: thinking blocks (when reasoning is enabled) are NOT surfaced —
// matches the streaming path which also doesn't emit thinking deltas.
// Tool-use input is converted to JSON via the SDK's RawJSON field.
func (p *AnthropicProvider) ChatNonStreaming(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
params := p.buildMessageParams(req)
msg, err := p.client.Messages.New(ctx, params)
if err != nil {
return nil, err
}
events := make(chan llm.ChatEvent, 16)
go func() {
defer close(events)
for _, block := range msg.Content {
switch block.Type {
case "text":
if block.Text != "" {
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: block.Text}
}
case "tool_use":
// Stream path emits Start then Done; mirror that so the
// runtime's collection loop sees the same event ordering
// either way.
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: block.ID,
Name: block.Name,
},
}
inputJSON, mErr := json.Marshal(block.Input)
if mErr != nil || len(inputJSON) == 0 || string(inputJSON) == "null" {
// Default to "{}" so MCP / tool adapters never receive
// null/empty inputs that would be rejected at the
// transport layer (Bad Request).
inputJSON = []byte("{}")
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: block.ID,
Name: block.Name,
Input: json.RawMessage(inputJSON),
},
}
}
}
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(msg.Usage.InputTokens),
OutputTokens: int(msg.Usage.OutputTokens),
CacheCreationInputTokens: int(msg.Usage.CacheCreationInputTokens),
CacheReadInputTokens: int(msg.Usage.CacheReadInputTokens),
},
}
}()
return events, nil
}
// NormalizeToolSchema returns tools unchanged. The Anthropic Messages
// API accepts the full JSON Schema draft-7 dialect (including anyOf,
// oneOf, format, $ref, and definitions), so no fields need stripping
// to be portable. Identity behavior is intentional and durable, not a
// placeholder.
func (p *AnthropicProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return tools, nil
}
// AnthropicThinkingConfig is a provider-internal representation of
// Anthropic's thinking config. Exported for testability — production
// code uses BuildThinkingConfig and wires the result into the SDK
// inside ChatStream.
type AnthropicThinkingConfig struct {
BudgetTokens int64
}
// BuildThinkingConfig maps a llm.ReasoningMode to Anthropic's thinking
// budget. Returns (nil, false) when reasoning is off or the model
// doesn't support thinking. Mapping: low=1024, medium=4096, high=16384.
//
// Models without thinking support (legacy claude-3.x except 3-7-sonnet)
// always return (nil, false); when the caller sees this for a non-off
// mode it should emit an "ignored" diagnostic.
func (p *AnthropicProvider) BuildThinkingConfig(model string, mode llm.ReasoningMode) (*AnthropicThinkingConfig, bool) {
if mode == llm.ReasoningOff {
return nil, false
}
if !anthropicSupportsThinking(model) {
return nil, false
}
switch mode {
case llm.ReasoningLow:
return &AnthropicThinkingConfig{BudgetTokens: 1024}, true
case llm.ReasoningMedium:
return &AnthropicThinkingConfig{BudgetTokens: 4096}, true
case llm.ReasoningHigh:
return &AnthropicThinkingConfig{BudgetTokens: 16384}, true
default:
return nil, false
}
}
// anthropicSupportsThinking returns true for Claude models that accept
// extended thinking. Conservative — unknown IDs default to true so we
// let the API decide rather than silently drop a knob the user set.
func anthropicSupportsThinking(model string) bool {
noThink := []string{
"claude-3-haiku", "claude-3-5-haiku",
"claude-3-sonnet", "claude-3-5-sonnet",
"claude-3-opus",
}
for _, prefix := range noThink {
if strings.HasPrefix(model, prefix) {
return false
}
}
return true
}
// buildAnthropicMessages converts the provider-neutral []llm.Message into
// Anthropic's []MessageParam. Consecutive tool-result user messages are
// coalesced into a single user message with multiple tool_result content
// blocks, which is what the Anthropic Messages API requires when an
// assistant turn contained multiple tool_use blocks (e.g. parallel tool
// calls). Without coalescing, the API rejects the second tool_result
// because the immediately preceding message is itself a tool_result, not
// an assistant message containing the matching tool_use.
func buildAnthropicMessages(in []llm.Message, cacheLast bool) []anthropic.MessageParam {
msgs := make([]anthropic.MessageParam, 0, len(in))
for i := 0; i < len(in); i++ {
m := in[i]
switch m.Role {
case "user":
if m.ToolCallID != "" {
// Collect a run of consecutive tool_result user messages.
var blocks []anthropic.ContentBlockParamUnion
for ; i < len(in); i++ {
cur := in[i]
if cur.Role != "user" || cur.ToolCallID == "" {
i-- // un-consume; outer loop will re-process
break
}
blocks = append(blocks, buildToolResultBlock(cur))
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else if len(m.Images) > 0 {
var blocks []anthropic.ContentBlockParamUnion
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
blocks = append(blocks, anthropic.NewImageBlockBase64(img.MimeType, encoded))
}
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
msgs = append(msgs, anthropic.NewUserMessage(blocks...))
} else {
msgs = append(msgs, anthropic.NewUserMessage(anthropic.NewTextBlock(m.Content)))
}
case "assistant":
var blocks []anthropic.ContentBlockParamUnion
if m.Content != "" {
blocks = append(blocks, anthropic.NewTextBlock(m.Content))
}
for _, tc := range m.ToolCalls {
var input any
if err := json.Unmarshal(tc.Input, &input); err != nil {
input = map[string]any{}
}
blocks = append(blocks, anthropic.NewToolUseBlock(tc.ID, input, tc.Name))
}
if len(blocks) > 0 {
msgs = append(msgs, anthropic.NewAssistantMessage(blocks...))
}
}
}
// Cache marker on the last block of the last message. Anthropic accepts
// up to 4 cache_control markers per request; combined with the static
// system block this is at most 2.
if cacheLast && len(msgs) > 0 {
tail := &msgs[len(msgs)-1]
if len(tail.Content) > 0 {
setCacheControlOnBlock(&tail.Content[len(tail.Content)-1])
}
}
return msgs
}
// setCacheControlOnBlock attaches an ephemeral cache_control marker to the
// underlying param of any ContentBlockParamUnion variant that has a
// CacheControl field. The SDK union type does not expose a direct setter,
// so we mutate the variant struct directly. Variants other than text /
// tool_result / image / tool_use are out of scope; the runtime never
// produces them as the tail of a user message.
func setCacheControlOnBlock(block *anthropic.ContentBlockParamUnion) {
cc := anthropic.NewCacheControlEphemeralParam()
switch {
case block.OfText != nil:
block.OfText.CacheControl = cc
case block.OfToolResult != nil:
block.OfToolResult.CacheControl = cc
case block.OfImage != nil:
block.OfImage.CacheControl = cc
case block.OfToolUse != nil:
block.OfToolUse.CacheControl = cc
}
}
// buildToolResultBlock converts a single tool_result llm.Message (a user
// message with ToolCallID set) into an Anthropic ContentBlockParamUnion
// suitable for inclusion in a NewUserMessage. Preserves the
// with-images and without-images branches: image-bearing results build
// a structured content slice; plain results use the SDK helper.
func buildToolResultBlock(m llm.Message) anthropic.ContentBlockParamUnion {
if len(m.Images) > 0 {
var content []anthropic.ToolResultBlockParamContentUnion
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfImage: &anthropic.ImageBlockParam{
Source: anthropic.ImageBlockParamSourceUnion{
OfBase64: &anthropic.Base64ImageSourceParam{
Data: encoded,
MediaType: anthropic.Base64ImageSourceMediaType(img.MimeType),
},
},
},
})
}
if m.Content != "" {
content = append(content, anthropic.ToolResultBlockParamContentUnion{
OfText: &anthropic.TextBlockParam{Text: m.Content},
})
}
toolBlock := anthropic.ToolResultBlockParam{
ToolUseID: m.ToolCallID,
IsError: anthropic.Bool(m.IsError),
Content: content,
}
return anthropic.ContentBlockParamUnion{OfToolResult: &toolBlock}
}
return anthropic.NewToolResultBlock(m.ToolCallID, m.Content, m.IsError)
}
// buildAnthropicSystem builds the System param array from a llm.ChatRequest.
// Prefers SystemPromptParts when set: each non-empty part becomes one
// TextBlockParam; parts with Cache=true get an ephemeral cache_control marker.
// Falls back to a single un-cached block built from SystemPrompt when parts
// are absent. Returns nil when both inputs are empty.
func buildAnthropicSystem(req llm.ChatRequest) []anthropic.TextBlockParam {
if len(req.SystemPromptParts) > 0 {
blocks := make([]anthropic.TextBlockParam, 0, len(req.SystemPromptParts))
for _, p := range req.SystemPromptParts {
if p.Text == "" {
continue
}
b := anthropic.TextBlockParam{Text: p.Text}
if p.Cache {
b.CacheControl = anthropic.NewCacheControlEphemeralParam()
}
blocks = append(blocks, b)
}
if len(blocks) > 0 {
return blocks
}
return nil
}
if req.SystemPrompt != "" {
return []anthropic.TextBlockParam{{Text: req.SystemPrompt}}
}
return nil
}
+523
View File
@@ -0,0 +1,523 @@
package anthropic
import (
"context"
"encoding/base64"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
anthropic "github.com/anthropics/anthropic-sdk-go"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// helper: extract tool_use IDs (in order) from an assistant MessageParam.
func toolUseIDs(t *testing.T, m anthropic.MessageParam) []string {
t.Helper()
require.Equal(t, anthropic.MessageParamRoleAssistant, m.Role)
var ids []string
for _, b := range m.Content {
if b.OfToolUse != nil {
ids = append(ids, b.OfToolUse.ID)
}
}
return ids
}
// helper: extract tool_result IDs (in order) from a user MessageParam.
func toolResultIDs(t *testing.T, m anthropic.MessageParam) []string {
t.Helper()
require.Equal(t, anthropic.MessageParamRoleUser, m.Role)
var ids []string
for _, b := range m.Content {
if b.OfToolResult != nil {
ids = append(ids, b.OfToolResult.ToolUseID)
}
}
return ids
}
// TestAnthropic_ConsecutiveToolResultsCoalesce verifies that when the
// LLM emits N tool_use blocks in a single assistant turn (e.g. parallel
// MCP calls), the N resulting tool_result user messages produced by the
// agent are coalesced into ONE user message with N tool_result content
// blocks. The Anthropic Messages API requires this — it rejects each
// tool_result needing the immediately preceding message to contain the
// matching tool_use.
func TestAnthropic_ConsecutiveToolResultsCoalesce(t *testing.T) {
in := []llm.Message{
{Role: "user", Content: "do three things in parallel"},
{
Role: "assistant",
Content: "ok",
ToolCalls: []llm.ToolCall{
{ID: "A", Name: "search", Input: []byte(`{"q":"a"}`)},
{ID: "B", Name: "search", Input: []byte(`{"q":"b"}`)},
{ID: "C", Name: "search", Input: []byte(`{"q":"c"}`)},
},
},
// Results may arrive in any order — agent dispatches in parallel.
{Role: "user", ToolCallID: "B", Content: "result B"},
{Role: "user", ToolCallID: "A", Content: "result A"},
{Role: "user", ToolCallID: "C", Content: "result C"},
{Role: "assistant", Content: "done"},
}
got := buildAnthropicMessages(in, false)
// Expected shape: user(text), assistant(3 tool_uses), user(3 tool_results), assistant
require.Len(t, got, 4, "expected 4 messages, got %d", len(got))
assert.Equal(t, anthropic.MessageParamRoleUser, got[0].Role)
assert.Equal(t, []string{"A", "B", "C"}, toolUseIDs(t, got[1]))
assert.Equal(t, []string{"B", "A", "C"}, toolResultIDs(t, got[2]),
"three tool_results must coalesce into one user message preserving order")
assert.Equal(t, anthropic.MessageParamRoleAssistant, got[3].Role)
}
// TestAnthropic_SingleToolResultStillSeparate pins the existing
// behavior: a single tool_result still produces a single user message
// containing one tool_result block.
func TestAnthropic_SingleToolResultStillSeparate(t *testing.T) {
in := []llm.Message{
{Role: "user", Content: "search"},
{
Role: "assistant",
ToolCalls: []llm.ToolCall{
{ID: "X", Name: "search", Input: []byte(`{"q":"x"}`)},
},
},
{Role: "user", ToolCallID: "X", Content: "result X"},
{Role: "assistant", Content: "done"},
}
got := buildAnthropicMessages(in, false)
require.Len(t, got, 4)
assert.Equal(t, []string{"X"}, toolUseIDs(t, got[1]))
assert.Equal(t, []string{"X"}, toolResultIDs(t, got[2]),
"single tool_result still produces one user message with one block")
}
// TestAnthropic_ToolResultRunInterspersedWithText verifies that
// coalescing only spans a contiguous run of tool_result messages and
// stops at non-tool-result boundaries (e.g. a plain user text turn).
func TestAnthropic_ToolResultRunInterspersedWithText(t *testing.T) {
in := []llm.Message{
{
Role: "assistant",
ToolCalls: []llm.ToolCall{
{ID: "T1", Name: "f", Input: []byte(`{}`)},
},
},
{Role: "user", ToolCallID: "T1", Content: "r1"},
{Role: "user", Content: "interjection"},
{
Role: "assistant",
ToolCalls: []llm.ToolCall{
{ID: "T2", Name: "f", Input: []byte(`{}`)},
{ID: "T3", Name: "f", Input: []byte(`{}`)},
},
},
{Role: "user", ToolCallID: "T2", Content: "r2"},
{Role: "user", ToolCallID: "T3", Content: "r3"},
{Role: "user", Content: "trailing text"},
}
got := buildAnthropicMessages(in, false)
// Expected: assistant, user(1 tr), user(text), assistant, user(2 tr), user(text)
require.Len(t, got, 6)
assert.Equal(t, []string{"T1"}, toolUseIDs(t, got[0]))
assert.Equal(t, []string{"T1"}, toolResultIDs(t, got[1]))
// got[2] is the plain text interjection — user role, no tool_result.
assert.Equal(t, anthropic.MessageParamRoleUser, got[2].Role)
require.Len(t, got[2].Content, 1)
require.NotNil(t, got[2].Content[0].OfText)
assert.Equal(t, "interjection", got[2].Content[0].OfText.Text)
assert.Equal(t, []string{"T2", "T3"}, toolUseIDs(t, got[3]))
assert.Equal(t, []string{"T2", "T3"}, toolResultIDs(t, got[4]),
"the 2-element tool_result run must coalesce")
// got[5] is the trailing plain text.
assert.Equal(t, anthropic.MessageParamRoleUser, got[5].Role)
require.Len(t, got[5].Content, 1)
require.NotNil(t, got[5].Content[0].OfText)
assert.Equal(t, "trailing text", got[5].Content[0].OfText.Text)
}
// TestAnthropic_ToolResultsWithImages verifies that a coalesced run
// containing both plain-text and image-bearing tool_results preserves
// each block's images. The image-bearing branch builds a structured
// content slice; the plain branch uses the SDK helper. Both must end up
// inside the same user message.
func TestAnthropic_ToolResultsWithImages(t *testing.T) {
pngBytes := []byte{0x89, 0x50, 0x4E, 0x47}
in := []llm.Message{
{
Role: "assistant",
ToolCalls: []llm.ToolCall{
{ID: "P1", Name: "snap", Input: []byte(`{}`)},
{ID: "P2", Name: "snap", Input: []byte(`{}`)},
{ID: "P3", Name: "snap", Input: []byte(`{}`)},
},
},
// Plain text result.
{Role: "user", ToolCallID: "P1", Content: "no image"},
// Image-bearing result with caption.
{
Role: "user",
ToolCallID: "P2",
Content: "see attached",
Images: []llm.ImageContent{
{MimeType: "image/png", Data: pngBytes},
},
},
// Image-bearing result, error.
{
Role: "user",
ToolCallID: "P3",
IsError: true,
Images: []llm.ImageContent{
{MimeType: "image/png", Data: pngBytes},
},
},
}
got := buildAnthropicMessages(in, false)
// Expected: assistant(3 tool_uses), user(3 tool_results coalesced).
require.Len(t, got, 2)
assert.Equal(t, []string{"P1", "P2", "P3"}, toolUseIDs(t, got[0]))
assert.Equal(t, []string{"P1", "P2", "P3"}, toolResultIDs(t, got[1]))
// P1: no image — built via NewToolResultBlock helper, content is
// either nil/empty or carries text — we don't assert on its shape
// beyond ID. The key assertion is presence in the same user message.
require.NotNil(t, got[1].Content[0].OfToolResult)
// P2: image + text caption.
p2 := got[1].Content[1].OfToolResult
require.NotNil(t, p2)
require.Len(t, p2.Content, 2, "image + text caption -> 2 content items")
require.NotNil(t, p2.Content[0].OfImage)
assert.Equal(t,
base64.StdEncoding.EncodeToString(pngBytes),
p2.Content[0].OfImage.Source.OfBase64.Data)
require.NotNil(t, p2.Content[1].OfText)
assert.Equal(t, "see attached", p2.Content[1].OfText.Text)
// P3: image only, IsError set.
p3 := got[1].Content[2].OfToolResult
require.NotNil(t, p3)
require.Len(t, p3.Content, 1, "image only -> 1 content item")
require.NotNil(t, p3.Content[0].OfImage)
assert.True(t, p3.IsError.Value)
}
func TestAnthropicSystemPromptPartsEmitCacheControl(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{
SystemPromptParts: []llm.SystemPromptPart{
{Text: "static-cached", Cache: true},
{Text: "dynamic", Cache: false},
},
})
require.Len(t, got, 2)
require.Equal(t, "static-cached", got[0].Text)
require.Equal(t, "ephemeral", string(got[0].CacheControl.Type))
require.Equal(t, "dynamic", got[1].Text)
require.Empty(t, string(got[1].CacheControl.Type), "second block must not be cache-marked")
}
func TestAnthropicSystemPromptStringFallback(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{SystemPrompt: "legacy"})
require.Len(t, got, 1)
require.Equal(t, "legacy", got[0].Text)
require.Empty(t, string(got[0].CacheControl.Type))
}
func TestAnthropicSystemEmptyWhenBothEmpty(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{})
require.Empty(t, got)
}
func TestAnthropicSystemSkipsEmptyParts(t *testing.T) {
got := buildAnthropicSystem(llm.ChatRequest{
SystemPromptParts: []llm.SystemPromptPart{
{Text: ""},
{Text: "real", Cache: true},
},
})
require.Len(t, got, 1)
require.Equal(t, "real", got[0].Text)
}
func TestBuildAnthropicMessagesCacheLastTextBlock(t *testing.T) {
in := []llm.Message{
{Role: "user", Content: "first"},
{Role: "assistant", Content: "ok"},
{Role: "user", Content: "second"},
}
got := buildAnthropicMessages(in, true)
require.Len(t, got, 3)
last := got[len(got)-1]
blocks := last.Content
require.NotEmpty(t, blocks)
cc := blocks[len(blocks)-1].GetCacheControl()
require.NotNil(t, cc)
require.Equal(t, "ephemeral", string(cc.Type))
}
func TestBuildAnthropicMessagesNoMarkerWhenCacheLastFalse(t *testing.T) {
in := []llm.Message{{Role: "user", Content: "hi"}}
got := buildAnthropicMessages(in, false)
require.Len(t, got, 1)
blocks := got[0].Content
require.NotEmpty(t, blocks)
cc := blocks[len(blocks)-1].GetCacheControl()
if cc != nil {
require.Empty(t, string(cc.Type), "no cache_control should be emitted when CacheLastMessage=false")
}
}
func TestBuildAnthropicMessagesCacheLastToolResult(t *testing.T) {
in := []llm.Message{
{Role: "assistant", Content: "thinking"},
{Role: "user", ToolCallID: "tc_1", Content: "tool output"},
}
got := buildAnthropicMessages(in, true)
last := got[len(got)-1]
require.NotEmpty(t, last.Content)
cc := last.Content[len(last.Content)-1].GetCacheControl()
require.NotNil(t, cc)
require.Equal(t, "ephemeral", string(cc.Type))
}
func TestBuildAnthropicMessagesCacheLastImageBlock(t *testing.T) {
// Image-bearing user message: the SDK lays out blocks as [image..., text?].
// With Content="" the trailing block is the image, so cache_control must
// land on the OfImage variant.
in := []llm.Message{{
Role: "user",
Images: []llm.ImageContent{
{MimeType: "image/png", Data: []byte{0x89, 'P', 'N', 'G'}},
},
}}
got := buildAnthropicMessages(in, true)
require.Len(t, got, 1)
last := got[0]
require.NotEmpty(t, last.Content)
tail := last.Content[len(last.Content)-1]
require.NotNil(t, tail.OfImage, "expected last block to be an image variant")
cc := tail.GetCacheControl()
require.NotNil(t, cc)
require.Equal(t, "ephemeral", string(cc.Type))
}
// TestAnthropicStreamSurfacesCacheTokens points the SDK at an httptest
// server that serves a canned SSE response with cache_creation_input_tokens
// and cache_read_input_tokens populated, and asserts the emitted
// llm.Usage carries them through.
func TestAnthropicStreamSurfacesCacheTokens(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_1","type":"message","role":"assistant","content":[],"model":"claude-test","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":10,"output_tokens":0,"cache_creation_input_tokens":42,"cache_read_input_tokens":17}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":5}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-test"})
require.NoError(t, err)
var done *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventDone {
done = &ev
}
}
require.NotNil(t, done, "expected llm.EventDone")
require.NotNil(t, done.Usage, "expected llm.Usage on llm.EventDone")
require.Equal(t, 42, done.Usage.CacheCreationInputTokens)
require.Equal(t, 17, done.Usage.CacheReadInputTokens)
require.Equal(t, 5, done.Usage.OutputTokens)
require.Equal(t, 10, done.Usage.InputTokens)
}
// TestBuildMessageParamsIsPure protects the cache-prefix invariant
// behind the stream-fallback feature: when a stream dies mid-flight
// the runtime retries via ChatNonStreaming with the SAME llm.ChatRequest,
// and both call sites share buildMessageParams. If buildMessageParams
// were non-deterministic (timestamp, RNG, map iteration leaking into
// output) the retry would send different bytes and Anthropic would
// invalidate the prompt cache. We compare wire-form JSON to catch
// drift the Go struct's `==` would miss (e.g. nil vs empty slice).
func TestBuildMessageParamsIsPure(t *testing.T) {
p := NewAnthropicProvider("test-key", "")
req := llm.ChatRequest{
Model: "claude-sonnet-4-5",
MaxTokens: 4096,
Temperature: 0.7,
SystemPromptParts: []llm.SystemPromptPart{
{Text: "you are felix", Cache: true},
{Text: "today is 2026-05-01"},
},
Messages: []llm.Message{
{Role: "user", Content: "hello"},
{
Role: "assistant",
Content: "ok",
ToolCalls: []llm.ToolCall{
{ID: "A", Name: "search", Input: []byte(`{"q":"a"}`)},
{ID: "B", Name: "search", Input: []byte(`{"q":"b"}`)},
},
},
{Role: "tool", Content: "ra", ToolCallID: "A"},
{Role: "tool", Content: "rb", ToolCallID: "B"},
},
Tools: []llm.ToolDef{
{Name: "search", Description: "search the web", Parameters: json.RawMessage(`{"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}`)},
},
CacheLastMessage: true,
}
first := p.buildMessageParams(req)
second := p.buildMessageParams(req)
firstJSON, err := json.Marshal(first)
require.NoError(t, err)
secondJSON, err := json.Marshal(second)
require.NoError(t, err)
assert.Equal(t, string(firstJSON), string(secondJSON),
"buildMessageParams must be a pure function — the stream-fallback "+
"non-streaming retry depends on byte-identical params to keep the "+
"prompt cache prefix valid")
}
// TestAnthropicStream_ToolUseInputOnContentBlockStart verifies the
// proxy-fallback path: some Anthropic-shaped gateways (e.g. platformai
// routing Gemini-Pro / Flash through the Anthropic API) emit the FULL
// tool input on content_block_start with NO subsequent input_json_delta
// events, because Gemini doesn't natively stream tool arguments.
//
// Without the fallback, the parser would emit `Input: ""` and the
// downstream MCP adapter would forward an empty/null `arguments`
// payload — which the gateway rejects with HTTP 400 (Bad Request).
// This was the actual production failure for the assistantai server
// only-when-using-Gemini.
func TestAnthropicStream_ToolUseInputOnContentBlockStart(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_g","type":"message","role":"assistant","content":[],"model":"gemini-3.1-pro","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":12,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_abc","name":"nl_search_ms_mail","input":{"query":"latest","limit":5}}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":11}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "gemini-test"})
require.NoError(t, err)
var done *llm.ChatEvent
var toolDone *llm.ChatEvent
for ev := range stream {
switch ev.Type {
case llm.EventToolCallDone:
ev := ev // capture
toolDone = &ev
case llm.EventDone:
ev := ev
done = &ev
}
}
require.NotNil(t, done, "expected llm.EventDone")
require.NotNil(t, toolDone, "expected llm.EventToolCallDone")
require.NotNil(t, toolDone.ToolCall)
assert.Equal(t, "call_abc", toolDone.ToolCall.ID)
assert.Equal(t, "nl_search_ms_mail", toolDone.ToolCall.Name)
assert.JSONEq(t, `{"query":"latest","limit":5}`, string(toolDone.ToolCall.Input),
"input from content_block_start must be captured when no input_json_delta arrives — "+
"otherwise Gemini-via-Anthropic-proxy tool calls reach MCP with empty args and 400")
}
// TestAnthropicStream_EmptyToolInputDefaultsToObject verifies that a
// tool_use that genuinely has no arguments still produces a valid empty
// object instead of an empty string, so MCP adapters always send a
// well-formed `arguments` field over the wire.
func TestAnthropicStream_EmptyToolInputDefaultsToObject(t *testing.T) {
const sseBody = `event: message_start
data: {"type":"message_start","message":{"id":"msg_e","type":"message","role":"assistant","content":[],"model":"claude-test","stop_reason":null,"stop_sequence":null,"usage":{"input_tokens":1,"output_tokens":0}}}
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"tool_use","id":"call_e","name":"ping","input":{}}}
event: content_block_stop
data: {"type":"content_block_stop","index":0}
event: message_delta
data: {"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":1}}
event: message_stop
data: {"type":"message_stop"}
`
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte(sseBody))
}))
t.Cleanup(srv.Close)
p := NewAnthropicProvider("test-key", srv.URL)
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "claude-test"})
require.NoError(t, err)
var toolDone *llm.ChatEvent
for ev := range stream {
if ev.Type == llm.EventToolCallDone {
ev := ev
toolDone = &ev
}
}
require.NotNil(t, toolDone)
require.NotNil(t, toolDone.ToolCall)
assert.Equal(t, `{}`, string(toolDone.ToolCall.Input),
"argument-less tool call must serialize as {} so MCP transport accepts it")
}
+307
View File
@@ -0,0 +1,307 @@
package gemini
import (
"context"
"encoding/json"
"fmt"
"log/slog"
"strings"
"google.golang.org/genai"
"github.com/sausheong/harness/llm"
)
// GeminiProvider implements llm.LLMProvider using the Google Gemini API.
type GeminiProvider struct {
client *genai.Client
}
// NewGeminiProvider creates a new Gemini LLM provider.
func NewGeminiProvider(ctx context.Context, apiKey string) (*GeminiProvider, error) {
client, err := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: apiKey,
Backend: genai.BackendGeminiAPI,
})
if err != nil {
return nil, fmt.Errorf("create gemini client: %w", err)
}
return &GeminiProvider{client: client}, nil
}
func (p *GeminiProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "gemini-2.5-flash", Name: "Gemini 2.5 Flash", Provider: "gemini"},
{ID: "gemini-2.5-pro", Name: "Gemini 2.5 Pro", Provider: "gemini"},
{ID: "gemini-2.0-flash", Name: "Gemini 2.0 Flash", Provider: "gemini"},
}
}
func (p *GeminiProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
// Build a map from tool call ID to function name for resolving tool results.
toolIDToName := make(map[string]string)
for _, m := range req.Messages {
for _, tc := range m.ToolCalls {
toolIDToName[tc.ID] = tc.Name
}
}
// Build contents
var contents []*genai.Content
for _, m := range req.Messages {
switch m.Role {
case "user":
if m.ToolCallID != "" {
// Tool result — send as function response
funcName := m.ToolCallID
if name, ok := toolIDToName[m.ToolCallID]; ok {
funcName = name
}
var response map[string]any
if m.IsError {
response = map[string]any{"error": m.Content}
} else {
response = map[string]any{"output": m.Content}
}
contents = append(contents, &genai.Content{
Role: "user",
Parts: []*genai.Part{
{FunctionResponse: &genai.FunctionResponse{
Name: funcName,
ID: m.ToolCallID,
Response: response,
}},
},
})
} else {
var parts []*genai.Part
for _, img := range m.Images {
parts = append(parts, &genai.Part{
InlineData: &genai.Blob{
Data: img.Data,
MIMEType: img.MimeType,
},
})
}
if m.Content != "" {
parts = append(parts, genai.NewPartFromText(m.Content))
}
contents = append(contents, &genai.Content{
Role: "user",
Parts: parts,
})
}
case "assistant":
var parts []*genai.Part
if m.Content != "" {
parts = append(parts, genai.NewPartFromText(m.Content))
}
for _, tc := range m.ToolCalls {
var args map[string]any
if err := json.Unmarshal(tc.Input, &args); err != nil {
args = map[string]any{}
}
parts = append(parts, &genai.Part{
FunctionCall: &genai.FunctionCall{
ID: tc.ID,
Name: tc.Name,
Args: args,
},
})
}
if len(parts) > 0 {
contents = append(contents, &genai.Content{
Role: "model",
Parts: parts,
})
}
}
}
// Build tool declarations
var tools []*genai.Tool
if len(req.Tools) > 0 {
var decls []*genai.FunctionDeclaration
for _, t := range req.Tools {
var schema any
if err := json.Unmarshal(t.Parameters, &schema); err != nil {
schema = map[string]any{"type": "object", "properties": map[string]any{}}
}
decls = append(decls, &genai.FunctionDeclaration{
Name: t.Name,
Description: t.Description,
ParametersJsonSchema: schema,
})
}
tools = append(tools, &genai.Tool{FunctionDeclarations: decls})
}
// Build config
model := req.Model
if model == "" {
model = "gemini-2.5-flash"
}
config := &genai.GenerateContentConfig{}
if sysPrompt := geminiResolveSystemPrompt(req); sysPrompt != "" {
config.SystemInstruction = genai.NewContentFromText(sysPrompt, "user")
}
if req.MaxTokens > 0 {
config.MaxOutputTokens = int32(req.MaxTokens)
}
if req.Temperature > 0 {
temp := float32(req.Temperature)
config.Temperature = &temp
}
if len(tools) > 0 {
config.Tools = tools
}
if budget, ok := p.BuildThinkingBudget(model, req.Reasoning); ok {
b := budget // need addressable int32 for *int32 field
config.ThinkingConfig = &genai.ThinkingConfig{
ThinkingBudget: &b,
}
slog.Info("gemini thinking enabled",
"model", model,
"budget_tokens", budget)
} else if req.Reasoning != llm.ReasoningOff {
slog.Info("reasoning ignored",
"provider", "gemini",
"model", model,
"requested", string(req.Reasoning),
"reason", "model does not support thinking")
}
// Stream responses
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
for resp, err := range p.client.Models.GenerateContentStream(ctx, model, contents, config) {
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
return
}
if resp.UsageMetadata != nil {
events <- llm.ChatEvent{
Type: llm.EventDone,
Usage: &llm.Usage{
InputTokens: int(resp.UsageMetadata.PromptTokenCount),
OutputTokens: int(resp.UsageMetadata.CandidatesTokenCount),
},
}
}
for _, cand := range resp.Candidates {
if cand.Content == nil {
continue
}
for _, part := range cand.Content.Parts {
if part.Text != "" {
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: part.Text,
}
}
if part.FunctionCall != nil {
fc := part.FunctionCall
argsJSON, err := json.Marshal(fc.Args)
if err != nil {
argsJSON = []byte("{}")
}
id := fc.ID
if id == "" {
id = fc.Name
}
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: id,
Name: fc.Name,
},
}
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: id,
Name: fc.Name,
Input: json.RawMessage(argsJSON),
},
}
}
}
}
}
// Ensure a Done event is always sent
events <- llm.ChatEvent{Type: llm.EventDone}
}()
return events, nil
}
// geminiUnsupportedFields are JSON Schema fields Gemini's "OpenAPI 3.0
// subset" rejects. This is the broadest strip set across the four
// providers — most of the cross-provider portability gap shows up here.
var geminiUnsupportedFields = []string{"anyOf", "oneOf", "not", "$ref", "format"}
// NormalizeToolSchema strips fields incompatible with Gemini's OpenAPI
// 3.0 subset. Diagnostics list every stripped occurrence with a
// dotted JSON path.
func (p *GeminiProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return llm.ApplyStripList(tools, geminiUnsupportedFields)
}
// BuildThinkingBudget maps a llm.ReasoningMode to Gemini's thinking budget
// (in tokens). Returns (0, false) when reasoning is off or the model
// does not support thinking. Mapping: low=1024, medium=4096, high=16384.
func (p *GeminiProvider) BuildThinkingBudget(model string, mode llm.ReasoningMode) (int32, bool) {
if mode == llm.ReasoningOff {
return 0, false
}
if !geminiSupportsThinking(model) {
return 0, false
}
switch mode {
case llm.ReasoningLow:
return 1024, true
case llm.ReasoningMedium:
return 4096, true
case llm.ReasoningHigh:
return 16384, true
default:
return 0, false
}
}
// geminiSupportsThinking returns true for Gemini models that accept the
// ThinkingConfig field. Conservative — unknown IDs default to false
// (Gemini's thinking is tightly bound to 2.0-flash-thinking and 2.5
// families; other models reject the field).
func geminiSupportsThinking(model string) bool {
prefixes := []string{"gemini-2.0-flash-thinking", "gemini-2.5"}
for _, prefix := range prefixes {
if strings.HasPrefix(model, prefix) {
return true
}
}
return false
}
// geminiResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
// resolution path but the per-provider helper avoids importing the
// genai SDK in test code.
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
if len(req.SystemPromptParts) > 0 {
return llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return req.SystemPrompt
}
+26
View File
@@ -0,0 +1,26 @@
package gemini
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestGeminiResolveSystemPromptPrefersParts(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{
SystemPrompt: "legacy",
SystemPromptParts: []llm.SystemPromptPart{{Text: "alpha"}, {Text: "beta"}},
})
require.Equal(t, "alpha\nbeta", got)
}
func TestGeminiResolveSystemPromptFallsBackToString(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "only-string"})
require.Equal(t, "only-string", got)
}
func TestGeminiResolveSystemPromptEmpty(t *testing.T) {
got := geminiResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}
+419
View File
@@ -0,0 +1,419 @@
package openai
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"strings"
openai "github.com/sashabaranov/go-openai"
"github.com/sausheong/harness/llm"
)
// logOpenAIError unwraps the go-openai SDK error into a structured slog.WARN
// record so we can see exactly why LiteLLM/OpenAI rejected the request — the
// SDK's flat error string drops Param, Type, Code, and the raw response body
// that often pinpoints which JSON field is invalid (e.g. "max_tokens" vs
// "max_completion_tokens" on gpt-5 family).
func logOpenAIError(err error, model string, msgCount, toolCount, maxTokens int, temp float32, hasStream bool) {
attrs := []any{
"model", model,
"msg_count", msgCount,
"tool_count", toolCount,
"max_completion_tokens", maxTokens,
"temperature", temp,
"stream", hasStream,
"err", err.Error(),
}
var apiErr *openai.APIError
if errors.As(err, &apiErr) {
attrs = append(attrs,
"http_status", apiErr.HTTPStatusCode,
"api_type", apiErr.Type,
"api_code", fmt.Sprintf("%v", apiErr.Code),
"api_message", apiErr.Message,
)
if apiErr.Param != nil {
attrs = append(attrs, "api_param", *apiErr.Param)
}
}
var reqErr *openai.RequestError
if errors.As(err, &reqErr) {
body := reqErr.Body
if len(body) > 2000 {
body = body[:2000]
}
attrs = append(attrs,
"http_status", reqErr.HTTPStatusCode,
"body", string(body),
)
}
slog.Warn("openai chat error", attrs...)
}
// OpenAIProvider holds the OpenAI client + the resolved provider kind.
// Kind is "openai", "openai-compatible", or "local"; affects reasoning
// suppression — compat and local endpoints (e.g. Ollama, LiteLLM) may
// not support reasoning_effort, so it's suppressed there with a diag.
type OpenAIProvider struct {
client *openai.Client
kind string
}
// NewOpenAIProvider returns an OpenAIProvider with kind="openai".
// If baseURL is non-empty, the client points to that endpoint (e.g. LiteLLM).
func NewOpenAIProvider(apiKey, baseURL string) *OpenAIProvider {
return NewOpenAIProviderWithKind(apiKey, baseURL, "openai")
}
// NewOpenAIProviderWithKind returns an OpenAIProvider for a specific
// provider kind. Use kind="openai-compatible" for proxies (LiteLLM)
// or kind="local" for Ollama. Reasoning is suppressed for non-"openai"
// kinds because those endpoints typically don't honor reasoning_effort.
func NewOpenAIProviderWithKind(apiKey, baseURL, kind string) *OpenAIProvider {
cfg := openai.DefaultConfig(apiKey)
if baseURL != "" {
cfg.BaseURL = baseURL
}
return &OpenAIProvider{
client: openai.NewClientWithConfig(cfg),
kind: kind,
}
}
func (p *OpenAIProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "gpt-4o", Name: "GPT-4o", Provider: "openai"},
{ID: "gpt-4o-mini", Name: "GPT-4o Mini", Provider: "openai"},
{ID: "gpt-4-turbo", Name: "GPT-4 Turbo", Provider: "openai"},
}
}
func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
// Build messages
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
sysPrompt := req.SystemPrompt
if len(req.SystemPromptParts) > 0 {
sysPrompt = llm.JoinSystemPromptParts(req.SystemPromptParts)
}
if sysPrompt != "" {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleSystem,
Content: sysPrompt,
})
}
for _, m := range req.Messages {
switch m.Role {
case "user":
if m.ToolCallID != "" {
// Tool results: always send text-only as the tool message.
// OpenAI vision (and ollama's vision-capable models) only
// look at images on user-role messages — image content on a
// tool message is silently ignored. So when the tool
// returned images, we emit them as a follow-up user message.
toolText := m.Content
if toolText == "" && len(m.Images) > 0 {
toolText = "(image attached in following message)"
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: toolText,
ToolCallID: m.ToolCallID,
})
if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: "(Image returned by the previous tool call.)",
})
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
})
}
} else if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: m.Content,
})
}
case "assistant":
msg := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: m.Content,
}
for _, tc := range m.ToolCalls {
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
ID: tc.ID,
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: tc.Name,
Arguments: string(tc.Input),
},
})
}
msgs = append(msgs, msg)
}
}
// Build tools
var tools []openai.Tool
for _, t := range req.Tools {
var params any
if err := json.Unmarshal(t.Parameters, &params); err != nil {
params = map[string]any{"type": "object", "properties": map[string]any{}}
}
tools = append(tools, openai.Tool{
Type: openai.ToolTypeFunction,
Function: &openai.FunctionDefinition{
Name: t.Name,
Description: t.Description,
Parameters: params,
},
})
}
model := req.Model
if model == "" {
model = "gpt-4o"
}
maxTokens := req.MaxTokens
if maxTokens == 0 {
maxTokens = 4096
}
openaiReq := openai.ChatCompletionRequest{
Model: model,
Messages: msgs,
MaxCompletionTokens: maxTokens,
Stream: true,
StreamOptions: &openai.StreamOptions{IncludeUsage: true},
}
if len(tools) > 0 {
openaiReq.Tools = tools
}
if req.Temperature > 0 {
openaiReq.Temperature = float32(req.Temperature)
}
if effort, ok := p.BuildReasoningEffort(model, req.Reasoning); ok {
openaiReq.ReasoningEffort = effort
slog.Info("openai reasoning enabled",
"model", model,
"effort", effort)
} else if req.Reasoning != llm.ReasoningOff {
reason := "model does not support reasoning_effort"
if p.kind == "openai-compatible" || p.kind == "local" {
reason = "endpoint may not support reasoning_effort"
}
slog.Info("reasoning ignored",
"provider", "openai",
"kind", p.kind,
"model", model,
"requested", string(req.Reasoning),
"reason", reason)
}
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
if err != nil {
logOpenAIError(err, model, len(msgs), len(tools), maxTokens, openaiReq.Temperature, true)
return nil, err
}
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
for {
resp, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
logOpenAIError(err, model, len(msgs), len(tools), maxTokens, openaiReq.Temperature, true)
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
return
}
// Capture usage when the provider finally sends it (typically on
// the final chunk thanks to StreamOptions.IncludeUsage=true).
if resp.Usage != nil && resp.Usage.TotalTokens > 0 {
lastUsage = &llm.Usage{
InputTokens: resp.Usage.PromptTokens,
OutputTokens: resp.Usage.CompletionTokens,
}
}
for _, choice := range resp.Choices {
delta := choice.Delta
// Text content
if delta.Content != "" {
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: delta.Content,
}
}
// Tool calls
for _, tc := range delta.ToolCalls {
idx := 0
if tc.Index != nil {
idx = *tc.Index
}
pending, exists := toolCalls[idx]
if !exists {
pending = &pendingTC{}
toolCalls[idx] = pending
}
if tc.ID != "" {
pending.id = tc.ID
}
if tc.Function.Name != "" {
pending.name = tc.Function.Name
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: pending.id,
Name: pending.name,
},
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
}()
return events, nil
}
// openaiUnsupportedFields are JSON Schema fields the OpenAI function-
// calling schema rejects. anyOf/oneOf/format are accepted and kept.
var openaiUnsupportedFields = []string{"$ref", "definitions"}
// NormalizeToolSchema strips $ref and definitions from each tool's
// JSON Schema. The OpenAI function-calling endpoint rejects schemas
// that contain these (it accepts a restricted JSON Schema subset).
// Diagnostics list every stripped occurrence with a dotted JSON path.
func (p *OpenAIProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return llm.ApplyStripList(tools, openaiUnsupportedFields)
}
// BuildReasoningEffort maps a llm.ReasoningMode to OpenAI's reasoning_effort
// string. Returns ("", false) when reasoning is off, the model doesn't
// support it, or the provider Kind suppresses it (openai-compatible /
// local).
func (p *OpenAIProvider) BuildReasoningEffort(model string, mode llm.ReasoningMode) (string, bool) {
if mode == llm.ReasoningOff {
return "", false
}
if p.kind == "openai-compatible" || p.kind == "local" {
return "", false
}
if !openaiSupportsReasoning(model) {
return "", false
}
switch mode {
case llm.ReasoningLow:
return "low", true
case llm.ReasoningMedium:
return "medium", true
case llm.ReasoningHigh:
return "high", true
default:
return "", false
}
}
// openaiSupportsReasoning returns true for OpenAI models that accept
// reasoning_effort. Conservative — unknown IDs default to false (these
// values are tightly bounded to specific model families; unlike
// Anthropic, OpenAI's older models reject the field).
func openaiSupportsReasoning(model string) bool {
prefixes := []string{"o1-", "o3-", "o4-", "gpt-5"}
for _, prefix := range prefixes {
if strings.HasPrefix(model, prefix) {
return true
}
}
return false
}
+75
View File
@@ -0,0 +1,75 @@
package openai
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
openai "github.com/sashabaranov/go-openai"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
// captureOpenAIRequest points an OpenAI provider at an httptest server,
// drives one ChatStream call, and returns the captured request body.
// Surfaces any unmarshal error after the stream drains so a silent SDK
// shape change shows up as a clean test failure rather than a nil-pointer
// panic at the call site.
func captureOpenAIRequest(t *testing.T, req llm.ChatRequest) *openai.ChatCompletionRequest {
t.Helper()
var (
captured openai.ChatCompletionRequest
unmarshalErr error
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
unmarshalErr = json.Unmarshal(body, &captured)
w.Header().Set("Content-Type", "text/event-stream")
_, _ = w.Write([]byte("data: [DONE]\n\n"))
}))
t.Cleanup(srv.Close)
p := NewOpenAIProviderWithKind("test-key", srv.URL+"/v1", "openai-compatible")
stream, err := p.ChatStream(context.Background(), req)
require.NoError(t, err)
for range stream {
}
require.NoError(t, unmarshalErr, "captured request body did not parse as openai.ChatCompletionRequest")
return &captured
}
func TestOpenAIChatStreamUsesSystemPromptParts(t *testing.T) {
captured := captureOpenAIRequest(t, llm.ChatRequest{
SystemPromptParts: []llm.SystemPromptPart{
{Text: "static"},
{Text: "dynamic"},
},
})
require.NotNil(t, captured)
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "system", string(captured.Messages[0].Role))
require.Equal(t, "static\ndynamic", captured.Messages[0].Content)
}
func TestOpenAIChatStreamFallsBackToSystemPromptString(t *testing.T) {
captured := captureOpenAIRequest(t, llm.ChatRequest{
SystemPrompt: "legacy",
})
require.NotNil(t, captured)
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "system", string(captured.Messages[0].Role))
require.Equal(t, "legacy", captured.Messages[0].Content)
}
func TestOpenAIChatStreamPartsBeatString(t *testing.T) {
captured := captureOpenAIRequest(t, llm.ChatRequest{
SystemPrompt: "legacy",
SystemPromptParts: []llm.SystemPromptPart{{Text: "new"}},
})
require.NotNil(t, captured)
require.GreaterOrEqual(t, len(captured.Messages), 1)
require.Equal(t, "new", captured.Messages[0].Content)
}
+350
View File
@@ -0,0 +1,350 @@
package qwen
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"strings"
openai "github.com/sashabaranov/go-openai"
"github.com/sausheong/harness/llm"
)
// QwenProvider implements llm.LLMProvider using the Qwen Chat Completions API.
// Qwen uses an OpenAI-compatible API, so we reuse the go-openai client.
type QwenProvider struct {
client *openai.Client
}
// NewQwenProvider creates a new Qwen LLM provider.
// The Qwen API is OpenAI-compatible, so we use the go-openai client
// with Qwen's base URL.
func NewQwenProvider(apiKey, baseURL string) *QwenProvider {
cfg := openai.DefaultConfig(apiKey)
if baseURL != "" {
cfg.BaseURL = baseURL
} else {
// Default to Qwen's official API endpoint
cfg.BaseURL = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
}
client := openai.NewClientWithConfig(cfg)
return &QwenProvider{client: client}
}
func (p *QwenProvider) Models() []llm.ModelInfo {
return []llm.ModelInfo{
{ID: "qwen-plus", Name: "Qwen Plus", Provider: "qwen"},
{ID: "qwen-turbo", Name: "Qwen Turbo", Provider: "qwen"},
{ID: "qwen-max", Name: "Qwen Max", Provider: "qwen"},
{ID: "qwen-coder-plus", Name: "Qwen Coder Plus", Provider: "qwen"},
{ID: "qwen-vl-plus", Name: "Qwen VL Plus", Provider: "qwen"},
}
}
func (p *QwenProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
// Build messages
msgs := make([]openai.ChatCompletionMessage, 0, len(req.Messages)+1)
if sysPrompt := qwenResolveSystemPrompt(req); sysPrompt != "" {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleSystem,
Content: sysPrompt,
})
}
for _, m := range req.Messages {
switch m.Role {
case "user":
if m.ToolCallID != "" {
if len(m.Images) > 0 {
// Tool result with images: use multi-content parts
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
MultiContent: parts,
ToolCallID: m.ToolCallID,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleTool,
Content: m.Content,
ToolCallID: m.ToolCallID,
})
}
} else if len(m.Images) > 0 {
var parts []openai.ChatMessagePart
for _, img := range m.Images {
encoded := base64.StdEncoding.EncodeToString(img.Data)
dataURI := fmt.Sprintf("data:%s;base64,%s", img.MimeType, encoded)
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeImageURL,
ImageURL: &openai.ChatMessageImageURL{
URL: dataURI,
Detail: openai.ImageURLDetailAuto,
},
})
}
if m.Content != "" {
parts = append(parts, openai.ChatMessagePart{
Type: openai.ChatMessagePartTypeText,
Text: m.Content,
})
}
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
MultiContent: parts,
})
} else {
msgs = append(msgs, openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleUser,
Content: m.Content,
})
}
case "assistant":
msg := openai.ChatCompletionMessage{
Role: openai.ChatMessageRoleAssistant,
Content: m.Content,
}
for _, tc := range m.ToolCalls {
msg.ToolCalls = append(msg.ToolCalls, openai.ToolCall{
ID: tc.ID,
Type: openai.ToolTypeFunction,
Function: openai.FunctionCall{
Name: tc.Name,
Arguments: string(tc.Input),
},
})
}
msgs = append(msgs, msg)
}
}
// Build tools
var tools []openai.Tool
for _, t := range req.Tools {
var params any
if err := json.Unmarshal(t.Parameters, &params); err != nil {
params = map[string]any{"type": "object", "properties": map[string]any{}}
}
tools = append(tools, openai.Tool{
Type: openai.ToolTypeFunction,
Function: &openai.FunctionDefinition{
Name: t.Name,
Description: t.Description,
Parameters: params,
},
})
}
model := req.Model
if model == "" {
model = "qwen-plus"
}
maxTokens := req.MaxTokens
if maxTokens == 0 {
maxTokens = 4096
}
openaiReq := openai.ChatCompletionRequest{
Model: model,
Messages: msgs,
MaxTokens: maxTokens,
Stream: true,
}
if len(tools) > 0 {
openaiReq.Tools = tools
}
if req.Temperature > 0 {
openaiReq.Temperature = float32(req.Temperature)
}
if enabled, diag, ok := p.BuildEnableThinking(model, req.Reasoning); ok {
// TODO: Qwen DashScope expects a custom top-level "enable_thinking"
// JSON field that go-openai v1.41 does not expose via any
// ExtraBody/RawJSON mechanism. Wiring it requires either upgrading
// to a go-openai version with custom-field support or adding a
// custom HTTP roundtripper. Tracked as a Phase 2 follow-up.
_ = enabled
_ = diag
slog.Info("qwen thinking requested",
"model", model,
"requested", string(req.Reasoning),
"clamped_to_bool", true,
"reason", diag.Reason,
"sdk_limitation", "enable_thinking not yet wired to wire format")
} else if req.Reasoning != llm.ReasoningOff {
slog.Info("reasoning ignored",
"provider", "qwen",
"model", model,
"requested", string(req.Reasoning),
"reason", "model does not support thinking")
}
stream, err := p.client.CreateChatCompletionStream(ctx, openaiReq)
if err != nil {
return nil, err
}
events := make(chan llm.ChatEvent, 100)
go func() {
defer close(events)
defer stream.Close()
// Track tool calls being built up across deltas
type pendingTC struct {
id string
name string
argsJSON string
}
toolCalls := make(map[int]*pendingTC)
for {
resp, err := stream.Recv()
if errors.Is(err, io.EOF) {
break
}
if err != nil {
events <- llm.ChatEvent{Type: llm.EventError, Error: err}
return
}
for _, choice := range resp.Choices {
delta := choice.Delta
// Text content
if delta.Content != "" {
events <- llm.ChatEvent{
Type: llm.EventTextDelta,
Text: delta.Content,
}
}
// Tool calls
for _, tc := range delta.ToolCalls {
idx := 0
if tc.Index != nil {
idx = *tc.Index
}
pending, exists := toolCalls[idx]
if !exists {
pending = &pendingTC{}
toolCalls[idx] = pending
}
if tc.ID != "" {
pending.id = tc.ID
}
if tc.Function.Name != "" {
pending.name = tc.Function.Name
events <- llm.ChatEvent{
Type: llm.EventToolCallStart,
ToolCall: &llm.ToolCall{
ID: pending.id,
Name: pending.name,
},
}
}
if tc.Function.Arguments != "" {
pending.argsJSON += tc.Function.Arguments
}
}
// Finish reason
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
// Emit completed tool calls
for _, tc := range toolCalls {
if tc.name != "" {
events <- llm.ChatEvent{
Type: llm.EventToolCallDone,
ToolCall: &llm.ToolCall{
ID: tc.id,
Name: tc.name,
Input: json.RawMessage(tc.argsJSON),
},
}
}
}
}
}
}
events <- llm.ChatEvent{Type: llm.EventDone}
}()
return events, nil
}
// NormalizeToolSchema strips $ref and definitions from each tool's
// JSON Schema. Qwen DashScope tracks the OpenAI function-calling
// shape, so the same restricted JSON Schema subset applies (and the
// same openaiUnsupportedFields list is reused).
func (p *QwenProvider) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
return llm.ApplyStripList(tools, []string{"$ref", "definitions"})
}
// BuildEnableThinking maps a llm.ReasoningMode to Qwen's enable_thinking
// boolean. Returns (false, empty diag, false) when off or the model
// doesn't support thinking. For any non-off mode on a supported model,
// returns (true, clamped diag, true) — the boolean toggle loses the
// requested low/medium/high granularity, so the diag always fires.
func (p *QwenProvider) BuildEnableThinking(model string, mode llm.ReasoningMode) (bool, llm.Diagnostic, bool) {
if mode == llm.ReasoningOff {
return false, llm.Diagnostic{}, false
}
if !qwenSupportsThinking(model) {
return false, llm.Diagnostic{}, false
}
return true, llm.Diagnostic{
Action: "clamped",
Reason: "qwen reasoning is boolean; granularity ignored",
}, true
}
// qwenSupportsThinking returns true for Qwen models that support the
// enable_thinking parameter. Conservative — unknown IDs default to
// false (only QwQ and Qwen3 family models accept this field).
func qwenSupportsThinking(model string) bool {
prefixes := []string{"qwen-qwq", "qwen3"}
for _, prefix := range prefixes {
if strings.HasPrefix(model, prefix) {
return true
}
}
return false
}
// qwenResolveSystemPrompt returns the effective system prompt string,
// preferring SystemPromptParts when present. Mirrors the OpenAI/Gemini
// resolution helpers.
func qwenResolveSystemPrompt(req llm.ChatRequest) string {
if len(req.SystemPromptParts) > 0 {
return llm.JoinSystemPromptParts(req.SystemPromptParts)
}
return req.SystemPrompt
}
+26
View File
@@ -0,0 +1,26 @@
package qwen
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/llm"
)
func TestQwenResolveSystemPromptPrefersParts(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{
SystemPrompt: "legacy",
SystemPromptParts: []llm.SystemPromptPart{{Text: "new-a"}, {Text: "new-b"}},
})
require.Equal(t, "new-a\nnew-b", got)
}
func TestQwenResolveSystemPromptFallback(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{SystemPrompt: "legacy"})
require.Equal(t, "legacy", got)
}
func TestQwenResolveSystemPromptEmpty(t *testing.T) {
got := qwenResolveSystemPrompt(llm.ChatRequest{})
require.Equal(t, "", got)
}