Replace Qwen provider with LiteLLM and OpenRouter aggregators
Adding one bespoke provider package per vendor doesn't scale. LiteLLM proxy and OpenRouter both speak the OpenAI chat-completions wire format and each front dozens-to-hundreds of underlying models, so supporting them once gets that whole catalog instead of one more one-off integration — providers/qwen turns out to have been exactly that pattern hand-rolled a second time (its own copy of the OpenAI-compatible translation, just pointed at DashScope's base URL). providers/litellm and providers/openrouter are both thin constructors over the OpenAI provider's existing NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible") — no new request/stream-translation code. OpenRouter defaults to its public endpoint when baseURL is empty; LiteLLM has none (self-hosted), so callers must supply one. Context-window detection (tokens.ContextWindow) already keys off the model ID's family rather than the provider prefix, specifically so a model exposed under a custom/proxy provider name still gets the right window — so litellm/openrouter models need zero changes there.
This commit is contained in:
1 parent
0ba1b4dbcc
commit
f624e4c7bd
11 files changed
+143
-431
No files matched your search
@@ -87,8 +87,9 @@ a lot. The package is optimized for the use cases above, not these.
|
||||
hardened in 1.25. Older toolchains will fail at `go build`.
|
||||
- **An LLM API key**, depending on which provider(s) you wire in:
|
||||
`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, Google ADC for Gemini, or a
|
||||
Qwen DashScope key. For local models, point `openai.NewOpenAIProviderWithKind`
|
||||
at an Ollama endpoint — no key required.
|
||||
LiteLLM/OpenRouter key for those aggregators. For local models, point
|
||||
`openai.NewOpenAIProviderWithKind` at an Ollama endpoint — no key
|
||||
required.
|
||||
- **Optional: an MCP server** for `tools/mcp` integrations (any
|
||||
binary that speaks the Model Context Protocol — `npx
|
||||
@modelcontextprotocol/server-filesystem`, etc.).
|
||||
@@ -121,7 +122,8 @@ github.com/sausheong/harness/
|
||||
│ ├── anthropic/ # Anthropic LLMProvider (with prompt caching)
|
||||
│ ├── openai/ # OpenAI / OpenAI-compatible / local Ollama
|
||||
│ ├── gemini/ # Google Gemini via google.golang.org/genai
|
||||
│ └── qwen/ # Alibaba Qwen (OpenAI-compatible endpoint)
|
||||
│ ├── litellm/ # Self-hosted LiteLLM proxy (OpenAI-compatible)
|
||||
│ └── openrouter/ # OpenRouter aggregator (OpenAI-compatible)
|
||||
└── tools/ # Batteries-included concrete tools (each importable separately)
|
||||
├── file/ # read_file (with vision), write_file, edit_file
|
||||
├── bash/ # bash (with ExecPolicy: deny | allowlist | full)
|
||||
@@ -313,9 +315,12 @@ Deliberately not in scope (numbers from the same conceptual list):
|
||||
`clientcredentials.Config.Client(ctx)`) as `HTTPClient` —
|
||||
auto-refresh comes for free. Call `Runtime.Close()` to release
|
||||
sessions.
|
||||
- **Four providers, one interface.** Anthropic, OpenAI (and
|
||||
OpenAI-compatible / local Ollama), Gemini, and Qwen ship built-in.
|
||||
Adding a fifth is implementing `llm.Provider` (~300 LOC).
|
||||
- **Five providers, one interface.** Anthropic, OpenAI (and
|
||||
OpenAI-compatible / local Ollama), Gemini, LiteLLM, and OpenRouter ship
|
||||
built-in — LiteLLM and OpenRouter cost none of that ~300 LOC each,
|
||||
since both are thin constructors over the existing OpenAI-compatible
|
||||
path. Adding a genuinely new wire format is implementing
|
||||
`llm.Provider` (~300 LOC).
|
||||
|
||||
See [`developer.md`](./developer.md) for a step-by-step guide to
|
||||
building agents on top of Harness, including diagrams of the
|
||||
|
||||
+5
-3
@@ -59,7 +59,8 @@ required pieces are inside `inputs`; everything in `deps` is optional;
|
||||
The four mandatory pieces:
|
||||
|
||||
* **`llm.LLMProvider`** (in `RuntimeInputs.Provider`) — a streaming
|
||||
chat client (Anthropic / OpenAI / Gemini / Qwen, or your own).
|
||||
chat client (Anthropic / OpenAI / Gemini / LiteLLM / OpenRouter, or
|
||||
your own).
|
||||
* **`tool.Registry`** (in `RuntimeInputs.Tools`) — the tools the LLM
|
||||
may invoke. Each tool implements `tool.Tool`.
|
||||
* **`session.Session`** (in `RuntimeInputs.Session`) — append-only
|
||||
@@ -387,9 +388,10 @@ Each provider has its own constructor. All return an `llm.LLMProvider`.
|
||||
|--------------|--------------------------------------------------------|-------------------------------------|
|
||||
| Anthropic | `anthropic.NewAnthropicProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI | `openai.NewOpenAIProvider(apiKey, baseURL)` | `baseURL == ""` → official endpoint |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "ollama"\|"compat")` | for local Ollama, etc. |
|
||||
| OpenAI-compat| `openai.NewOpenAIProviderWithKind(apiKey, baseURL, "local"\|"openai-compatible")` | for local Ollama, etc. |
|
||||
| Gemini | `gemini.NewGeminiProvider(ctx, apiKey)` | takes `context.Context` |
|
||||
| Qwen | `qwen.NewQwenProvider(apiKey, baseURL)` | OpenAI-compatible endpoint |
|
||||
| LiteLLM | `litellm.NewLiteLLMProvider(apiKey, baseURL)` | `baseURL` required (self-hosted) |
|
||||
| OpenRouter | `openrouter.NewOpenRouterProvider(apiKey, baseURL)` | `baseURL == ""` → OpenRouter's public endpoint |
|
||||
|
||||
The provider you pass on `RuntimeInputs.Provider` only needs to match the
|
||||
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
|
||||
|
||||
+2
-2
@@ -34,8 +34,8 @@ const stripCacheMax = 256
|
||||
// ApplyStripList runs StripFields over each tool's Parameters with the
|
||||
// given field-strip list, preserving input order and accumulating
|
||||
// diagnostics across all tools. The per-provider NormalizeToolSchema
|
||||
// methods (OpenAI, Qwen, Gemini) are thin wrappers over this helper —
|
||||
// only the strip list differs. Anthropic doesn't use this (identity).
|
||||
// methods (OpenAI, Gemini) are thin wrappers over this helper — only the
|
||||
// strip list differs. Anthropic doesn't use this (identity).
|
||||
//
|
||||
// Memoized: identical inputs return cached output without re-walking
|
||||
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
|
||||
|
||||
+4
-4
@@ -98,7 +98,7 @@ type SystemPromptPart struct {
|
||||
// Zero value (ReasoningOff) means no extended reasoning — safe default
|
||||
// for existing call sites that don't set the field. Each provider maps
|
||||
// this to its native config (Anthropic thinking budget, OpenAI
|
||||
// reasoning_effort, Gemini ThinkingConfig, Qwen enable_thinking).
|
||||
// reasoning_effort, Gemini ThinkingConfig).
|
||||
type ReasoningMode string
|
||||
|
||||
const (
|
||||
@@ -295,10 +295,10 @@ func JoinSystemPromptParts(parts []SystemPromptPart) string {
|
||||
// ProviderOptions holds connection details for creating an LLM provider.
|
||||
// Kept here so consumers can pass a single struct around even though the
|
||||
// concrete provider constructors live in subpackages
|
||||
// (harness/providers/{anthropic,openai,gemini,qwen}). Each subpackage's
|
||||
// New() takes the relevant fields directly.
|
||||
// (harness/providers/{anthropic,openai,gemini,litellm,openrouter}). Each
|
||||
// subpackage's New() takes the relevant fields directly.
|
||||
type ProviderOptions struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini"
|
||||
}
|
||||
@@ -339,7 +339,7 @@ func geminiSupportsThinking(model string) bool {
|
||||
}
|
||||
|
||||
// geminiResolveSystemPrompt returns the effective system prompt string,
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI/Qwen
|
||||
// preferring SystemPromptParts when present. Mirrors the OpenAI
|
||||
// resolution path but the per-provider helper avoids importing the
|
||||
// genai SDK in test code.
|
||||
func geminiResolveSystemPrompt(req llm.ChatRequest) string {
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
// Package litellm provides an llm.LLMProvider for a self-hosted LiteLLM
|
||||
// proxy. LiteLLM speaks the OpenAI chat-completions wire format and
|
||||
// itself routes to dozens of underlying vendors, so this package adds no
|
||||
// new request/stream-translation code of its own — it's a thin
|
||||
// constructor around harness's existing OpenAI-compatible support.
|
||||
package litellm
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// NewLiteLLMProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, a self-hosted LiteLLM proxy endpoint. Unlike OpenRouter,
|
||||
// LiteLLM has no public default endpoint — callers must supply a
|
||||
// non-empty baseURL (cmd/hand's buildProvider, for example, rejects an
|
||||
// empty one with a clear error before ever reaching here).
|
||||
// kind="openai-compatible" suppresses reasoning_effort, since not every
|
||||
// model LiteLLM routes a request to is guaranteed to support it.
|
||||
func NewLiteLLMProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package litellm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// TestNewLiteLLMProvider_HitsGivenBaseURL confirms the provider actually
|
||||
// targets the baseURL it was constructed with, and that a streamed
|
||||
// response comes back through it — not re-testing OpenAI wire-format
|
||||
// translation itself (already covered by providers/openai's own tests),
|
||||
// just that this thin constructor wires the base URL through correctly.
|
||||
func TestNewLiteLLMProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewLiteLLMProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// Package openrouter provides an llm.LLMProvider for OpenRouter, an
|
||||
// aggregator that fronts hundreds of underlying models behind one
|
||||
// OpenAI-compatible endpoint. Like providers/litellm, this adds no new
|
||||
// request/stream-translation code of its own — it's a thin constructor
|
||||
// around harness's existing OpenAI-compatible support.
|
||||
package openrouter
|
||||
|
||||
import "github.com/sausheong/harness/providers/openai"
|
||||
|
||||
// DefaultBaseURL is OpenRouter's public API endpoint, used when
|
||||
// NewOpenRouterProvider is called with an empty baseURL.
|
||||
const DefaultBaseURL = "https://openrouter.ai/api/v1"
|
||||
|
||||
// NewOpenRouterProvider returns an OpenAI-compatible provider pointed at
|
||||
// baseURL, or DefaultBaseURL when baseURL is empty. kind="openai-compatible"
|
||||
// suppresses reasoning_effort, since OpenRouter's underlying models don't
|
||||
// uniformly support it.
|
||||
func NewOpenRouterProvider(apiKey, baseURL string) *openai.OpenAIProvider {
|
||||
if baseURL == "" {
|
||||
baseURL = DefaultBaseURL
|
||||
}
|
||||
return openai.NewOpenAIProviderWithKind(apiKey, baseURL, "openai-compatible")
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package openrouter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
func TestDefaultBaseURL(t *testing.T) {
|
||||
require.Equal(t, "https://openrouter.ai/api/v1", DefaultBaseURL)
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_HitsGivenBaseURL confirms a custom baseURL
|
||||
// overrides the default and is actually what the provider talks to.
|
||||
func TestNewOpenRouterProvider_HitsGivenBaseURL(t *testing.T) {
|
||||
var hit bool
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
hit = true
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
_, _ = w.Write([]byte("data: [DONE]\n\n"))
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
p := NewOpenRouterProvider("test-key", srv.URL+"/v1")
|
||||
stream, err := p.ChatStream(context.Background(), llm.ChatRequest{SystemPrompt: "hi"})
|
||||
require.NoError(t, err)
|
||||
for range stream {
|
||||
}
|
||||
require.True(t, hit, "provider did not hit the configured baseURL")
|
||||
}
|
||||
|
||||
// TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic confirms the empty
|
||||
// -> DefaultBaseURL fallback path constructs a usable provider (the
|
||||
// actual outbound host isn't inspectable from outside the openai
|
||||
// package — OpenAIProvider's client config is unexported — so this
|
||||
// checks the fallback doesn't panic or return nil, and DefaultBaseURL's
|
||||
// own value is asserted separately above).
|
||||
func TestNewOpenRouterProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
|
||||
p := NewOpenRouterProvider("test-key", "")
|
||||
require.NotNil(t, p)
|
||||
}
|
||||
@@ -1,370 +0,0 @@
|
||||
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"
|
||||
)
|
||||
|
||||
// pendingTC accumulates a streamed tool call across deltas. args uses
|
||||
// strings.Builder so repeated argument fragments append in O(n) total
|
||||
// (not O(n²) from string concatenation).
|
||||
type pendingTC struct {
|
||||
id string
|
||||
name string
|
||||
args strings.Builder
|
||||
}
|
||||
|
||||
// emitToolCalls sends EventToolCallDone for each completed tool call in
|
||||
// ascending index order so tool_use block order is deterministic across
|
||||
// turns (prompt-cache stability).
|
||||
func emitToolCalls(events chan<- llm.ChatEvent, toolCalls map[int]*pendingTC) {
|
||||
maxIdx := -1
|
||||
for idx := range toolCalls {
|
||||
if idx > maxIdx {
|
||||
maxIdx = idx
|
||||
}
|
||||
}
|
||||
for idx := 0; idx <= maxIdx; idx++ {
|
||||
tc, ok := toolCalls[idx]
|
||||
if !ok || tc.name == "" {
|
||||
continue
|
||||
}
|
||||
events <- llm.ChatEvent{
|
||||
Type: llm.EventToolCallDone,
|
||||
ToolCall: &llm.ToolCall{
|
||||
ID: tc.id,
|
||||
Name: tc.name,
|
||||
Input: json.RawMessage(tc.args.String()),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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, ¶ms); 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,
|
||||
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 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
|
||||
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.args.WriteString(tc.Function.Arguments)
|
||||
}
|
||||
}
|
||||
|
||||
// Finish reason
|
||||
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
|
||||
// Emit completed tool calls in index order.
|
||||
emitToolCalls(events, toolCalls)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
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)
|
||||
}
|
||||
|
||||
func TestEmitToolCalls_OrderedByIndex(t *testing.T) {
|
||||
mk := func(id, name string) *pendingTC {
|
||||
p := &pendingTC{id: id, name: name}
|
||||
p.args.WriteString("{}")
|
||||
return p
|
||||
}
|
||||
toolCalls := map[int]*pendingTC{1: mk("b", "second"), 0: mk("a", "first")}
|
||||
ch := make(chan llm.ChatEvent, 10)
|
||||
emitToolCalls(ch, toolCalls)
|
||||
close(ch)
|
||||
var ids []string
|
||||
for ev := range ch {
|
||||
if ev.Type == llm.EventToolCallDone {
|
||||
ids = append(ids, ev.ToolCall.ID)
|
||||
}
|
||||
}
|
||||
require.Equal(t, []string{"a", "b"}, ids)
|
||||
}
|
||||
Reference in new issue
Block a user