5 Commits
Author SHA1 Message Date
sausheong 3b5aadb31f Add an ollama provider for local models
Thin constructor over the existing OpenAI-compatible path, same shape
as litellm/openrouter: NewOllamaProvider(baseURL) defaults to Ollama's
local endpoint (http://localhost:11434/v1) and needs no API key, since
Ollama doesn't authenticate requests. Also covers other local servers
that share Ollama's OpenAI-compatible endpoint shape (LM Studio,
llama.cpp's server, vLLM).
2026-09-07 11:57:56 +08:00
sausheong 897643db18 Add a regression test proving a mid-session model switch is real
Verifies, at the Runtime.Run level, that mutating Model and
DynamicIdentityHint between two Run calls in the same session (exactly
what hand's tui.Controller.SwitchModel does) actually changes the
ChatRequest.Model sent on the next call, not just the system prompt
text. If this ever regressed, a caller-side "/model" fix would look
correct in its own unit tests while the model actually being queried
silently stayed the old one.
2026-09-07 00:22:07 +08:00
sausheong 0ccfdb2a24 Add Runtime.DynamicIdentityHint, a live, per-turn identity fact
Runtime.StaticSystemPrompt is cached and reused verbatim every turn —
right for anything that doesn't change mid-conversation, wrong for a
fact a caller needs to update live (e.g. after a runtime model switch)
and have the model actually notice. A model tends to just repeat what
it already told the user earlier in the same conversation over a
background instruction it read once near the top of a large cached
block, so updating only the static prompt after a switch left the
model insisting it was still whatever it started as.

DynamicIdentityHint rides the same per-turn (uncached) system prompt
slot Run/RunTurn already use for the date line and KG hint, so setting
it takes effect on the very next turn with the same recency the model
grants its own last statement.
2026-09-07 00:15:23 +08:00
sausheong f624e4c7bd 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.
2026-09-06 16:13:30 +08:00
sausheong 0ba1b4dbcc fix(tokens): generalize Gemini context-window detection by tier
windowByModelFamily matched Gemini models by exact version substring
("gemini-1.5-pro", "gemini-1.5-flash", "gemini-2"), so any newer
generation (3.x and beyond) fell through to defaultRemoteUnknownWindow
(128k) purely because this table hadn't been updated yet — observed
via hand's status line showing a >100% context gauge for a
"gemini-3.8-flash"-family model whose real window is far larger, and
which made harness's own preventive compaction unreachable (the
threshold check never fires against a window this far off).

Match on tier (Pro vs. everything else) instead of enumerating every
version: every Pro-tier Gemini release so far ships 2M, everything
else at least 1M, and both hold for a model this table has never seen
the exact version string of.
2026-09-05 22:06:59 +08:00
21 changed files with 358 additions and 448 deletions

No files matched your search

+10 -6
View File
@@ -87,8 +87,8 @@ 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,
`ollama.NewOllamaProvider` needs no key at all.
- **Optional: an MCP server** for `tools/mcp` integrations (any
binary that speaks the Model Context Protocol — `npx
@modelcontextprotocol/server-filesystem`, etc.).
@@ -121,7 +121,9 @@ 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)
│ └── ollama/ # Local Ollama server (OpenAI-compatible, no API key)
└── 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,11 @@ 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).
- **Six providers, one interface.** Anthropic, OpenAI, Gemini, LiteLLM,
OpenRouter, and Ollama ship built-in — LiteLLM, OpenRouter, and Ollama
cost none of that ~300 LOC each, since all three 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
+6 -3
View File
@@ -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 /
Ollama, 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,11 @@ 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 |
| Ollama | `ollama.NewOllamaProvider(baseURL)` | `baseURL == ""` → `http://localhost:11434/v1`; no API key |
The provider you pass on `RuntimeInputs.Provider` only needs to match the
provider prefix in `AgentSpec.Model` — `runtime.BuildRuntime` parses
+2 -2
View File
@@ -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
View File
@@ -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"
}
+1 -1
View File
@@ -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 {
+19
View File
@@ -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")
}
+33
View File
@@ -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")
}
+26
View File
@@ -0,0 +1,26 @@
// Package ollama provides an llm.LLMProvider for a local Ollama server
// (or any other local server sharing Ollama's OpenAI-compatible endpoint
// shape — LM Studio, llama.cpp's server, vLLM). Like providers/litellm
// and providers/openrouter, this adds no new request/stream-translation
// code of its own — it's a thin constructor around harness's existing
// OpenAI-compatible support.
package ollama
import "github.com/sausheong/harness/providers/openai"
// DefaultBaseURL is Ollama's local OpenAI-compatible endpoint, used when
// NewOllamaProvider is called with an empty baseURL.
const DefaultBaseURL = "http://localhost:11434/v1"
// NewOllamaProvider returns an OpenAI-compatible provider pointed at
// baseURL, or DefaultBaseURL when baseURL is empty. No API key is
// needed — Ollama doesn't authenticate requests. kind="local" suppresses
// reasoning_effort, since locally-served models don't uniformly support
// it, and keeps retryable-error classification from treating a down
// local server the way it would a hosted API outage (see llm/retry.go).
func NewOllamaProvider(baseURL string) *openai.OpenAIProvider {
if baseURL == "" {
baseURL = DefaultBaseURL
}
return openai.NewOpenAIProviderWithKind("", baseURL, "local")
}
+46
View File
@@ -0,0 +1,46 @@
package ollama
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, "http://localhost:11434/v1", DefaultBaseURL)
}
// TestNewOllamaProvider_HitsGivenBaseURL confirms a custom baseURL
// overrides the default and is actually what the provider talks to.
func TestNewOllamaProvider_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 := NewOllamaProvider(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")
}
// TestNewOllamaProvider_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 TestNewOllamaProvider_EmptyBaseURLDoesNotPanic(t *testing.T) {
p := NewOllamaProvider("")
require.NotNil(t, p)
}
+23
View File
@@ -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")
}
+45
View File
@@ -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)
}
-370
View File
@@ -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, &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,
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
}
-45
View File
@@ -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)
}
+2 -2
View File
@@ -443,8 +443,8 @@ func TestRuntimeDynamicSuffixIncludesDate(t *testing.T) {
// this proves the date is stable across turns of a single Run.
func TestRuntimeDateLineComputedOncePerRun(t *testing.T) {
dl := "Today's date is 2026-05-01."
a := buildDynamicSystemPromptSuffix(dl, "")
b := buildDynamicSystemPromptSuffix(dl, "")
a := buildDynamicSystemPromptSuffix("", dl, "")
b := buildDynamicSystemPromptSuffix("", dl, "")
require.Equal(t, a, b)
}
+10 -5
View File
@@ -142,18 +142,23 @@ func BuildStaticSystemPrompt(
}
// buildDynamicSystemPromptSuffix concatenates the per-turn dynamic context
// — the date line and the cortex hint — into a single string the runtime
// sends as the second (un-cached) SystemPromptPart. The date line, when
// non-empty, appears at the top so the model anchors on "today" before
// the per-turn content. Returns "" when all inputs are empty/nil.
// — the identity hint, date line, and cortex hint — into a single string
// the runtime sends as the second (un-cached) SystemPromptPart. identityHint
// leads (see Runtime.DynamicIdentityHint: it needs to outweigh the model's
// own prior in-conversation statements, so it gets the most prominent
// position), then the date line so the model anchors on "today" before the
// per-turn content. Returns "" when all inputs are empty/nil.
//
// As of sub-project 5, skill bodies and memory entries are no longer
// auto-injected here. Their indices live in the cached static prompt
// and the agent loads bodies on demand via the load_skill / load_memory
// tools. This trims 5–15 KB of speculative skill bodies and 5–10 KB of
// speculative memory bodies from every prefill.
func buildDynamicSystemPromptSuffix(dateLine, cortexContext string) string {
func buildDynamicSystemPromptSuffix(identityHint, dateLine, cortexContext string) string {
var sb strings.Builder
if identityHint != "" {
sb.WriteString(identityHint)
}
if dateLine != "" {
sb.WriteString(dateLine)
}
+12 -4
View File
@@ -85,17 +85,17 @@ func TestBuildStaticSystemPromptIncludesMemoryFiles(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixEmpty(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "")
got := buildDynamicSystemPromptSuffix("", "", "")
require.Equal(t, "", got)
}
func TestBuildDynamicSystemPromptSuffixHintOnly(t *testing.T) {
got := buildDynamicSystemPromptSuffix("", "\n\nHINT")
got := buildDynamicSystemPromptSuffix("", "", "\n\nHINT")
require.Equal(t, "\n\nHINT", got)
}
func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "\n\nKG_HINT")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "\n\nKG_HINT")
dateIdx := strings.Index(got, "Today's date is")
hintIdx := strings.Index(got, "KG_HINT")
require.True(t, dateIdx >= 0 && hintIdx > dateIdx,
@@ -103,11 +103,19 @@ func TestBuildDynamicSystemPromptSuffixDateAndHint(t *testing.T) {
}
func TestBuildDynamicSystemPromptSuffixIncludesDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("Today's date is 2026-05-01.", "")
got := buildDynamicSystemPromptSuffix("", "Today's date is 2026-05-01.", "")
require.True(t, strings.HasPrefix(got, "Today's date is 2026-05-01."),
"date line must appear at the top of the dynamic suffix")
}
func TestBuildDynamicSystemPromptSuffixIdentityHintLeadsDate(t *testing.T) {
got := buildDynamicSystemPromptSuffix("IDENTITY_HINT", "Today's date is 2026-05-01.", "\n\nKG_HINT")
identityIdx := strings.Index(got, "IDENTITY_HINT")
dateIdx := strings.Index(got, "Today's date is")
require.True(t, identityIdx == 0 && dateIdx > identityIdx,
"order must be identity hint < date; got %d %d", identityIdx, dateIdx)
}
func TestFormatDateLine(t *testing.T) {
cases := []struct {
name string
+62
View File
@@ -0,0 +1,62 @@
package runtime
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/sausheong/harness/session"
"github.com/sausheong/harness/tool"
)
// TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint reproduces,
// at the harness level, exactly what a caller like hand's tui.Controller
// does on a live model switch: mutate Model and DynamicIdentityHint on an
// already-running Runtime between two Run calls in the same session. This
// is the mechanism a caller-side fix for "the model still thinks it's the
// old one" ultimately rests on — if the second Run's actual ChatRequest
// didn't target the new model, no amount of system-prompt wording could
// have fixed the symptom, since the model actually being queried would
// still be the old one.
func TestModelSwitchMidSession_ActuallyChangesRequestModelAndHint(t *testing.T) {
rec := &recordingProvider{reply: "ok"}
sess := session.NewSession("test-agent", "test-key")
reg := tool.NewRegistry()
rt := &Runtime{
LLM: rec,
Tools: reg,
Session: sess,
Model: "meta/muse-spark-1.3",
Provider: "openrouter",
Workspace: t.TempDir(),
MaxTurns: 5,
DynamicIdentityHint: "You are running as the model \"openrouter/meta/muse-spark-1.3\".",
}
events, err := rt.Run(context.Background(), "which model am I using", nil)
require.NoError(t, err)
for range events {
}
// Simulate exactly what Controller.SwitchModel does.
rt.Model = "anthropic/claude-sonnet-5"
rt.DynamicIdentityHint = "You are running as the model \"openrouter/anthropic/claude-sonnet-5\"."
events, err = rt.Run(context.Background(), "which model am I using now", nil)
require.NoError(t, err)
for range events {
}
rec.mu.Lock()
defer rec.mu.Unlock()
require.Len(t, rec.requests, 2)
require.Equal(t, "meta/muse-spark-1.3", rec.requests[0].Model)
require.Equal(t, "anthropic/claude-sonnet-5", rec.requests[1].Model, "second request must target the switched model")
part2 := rec.requests[1].SystemPromptParts
require.Len(t, part2, 2, "expected static + dynamic system prompt parts")
require.Contains(t, part2[1].Text, "openrouter/anthropic/claude-sonnet-5")
require.NotContains(t, part2[1].Text, "muse-spark-1.3", "dynamic hint must not still name the old model")
}
+14 -1
View File
@@ -85,6 +85,19 @@ type Runtime struct {
// prompt cache hits.
StaticSystemPrompt string
// DynamicIdentityHint is caller-set text re-sent, uncached, in every
// turn's system prompt (see buildDynamicSystemPromptSuffix) — unlike
// StaticSystemPrompt, safe to mutate mid-conversation (e.g. after a
// live model switch) and have the very next turn pick it up. Exists
// because a fact baked only into the cached static prompt competes
// poorly against the model's own prior statements already visible in
// message history: asked "which model are you" a second time, a model
// tends to just repeat what it told the user earlier in the same
// conversation over a background instruction it read once at the top
// of a large cached block. Resending the fact fresh, every turn, gives
// it the same recency the model grants its own last answer.
DynamicIdentityHint string
// Permission gates tool execution at dispatch time. nil → allow-all.
Permission tool.PermissionChecker
@@ -437,7 +450,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
kgCh = nil
}
dynamicSuffix := buildDynamicSystemPromptSuffix(dateLine, kgContext)
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, dateLine, kgContext)
staticText := r.StaticSystemPrompt
parts := []llm.SystemPromptPart{
+3 -2
View File
@@ -84,9 +84,10 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
cancel()
}
dynamicSuffix := buildDynamicSystemPromptSuffix(r.DynamicIdentityHint, "", kgHint)
parts := []llm.SystemPromptPart{{Text: r.StaticSystemPrompt, Cache: true}}
if kgHint != "" {
parts = append(parts, llm.SystemPromptPart{Text: kgHint, Cache: false})
if dynamicSuffix != "" {
parts = append(parts, llm.SystemPromptPart{Text: dynamicSuffix, Cache: false})
}
req := llm.ChatRequest{
Model: r.Model,
+17 -3
View File
@@ -141,10 +141,24 @@ func windowByModelFamily(modelID string) int {
return 8192
case strings.HasPrefix(leaf, "gpt-3.5"):
return 16385
case strings.Contains(id, "gemini-1.5-pro"):
case strings.Contains(id, "gemini") && strings.Contains(id, "pro"):
// Every "Pro"-tier Gemini release so far (1.5 Pro onward) has
// shipped the largest window in its generation. Matching on the
// tier rather than enumerating each version keeps a future Pro
// release (2.5, 3, ...) from falling through to the
// flash/other-tier case below, let alone all the way to
// defaultRemoteUnknownWindow.
return 2000000
case strings.Contains(id, "gemini-1.5-flash"),
strings.Contains(id, "gemini-2"):
case strings.Contains(id, "gemini"):
// Every non-Pro Gemini model since 1.5 (Flash and other tiers)
// has shipped at least a 1M window. Matching on the family alone
// — not "gemini-1.5-flash"/"gemini-2" by exact version — means a
// new Gemini generation (3.x and beyond) gets a realistic window
// immediately instead of silently falling back to
// defaultRemoteUnknownWindow (128k), which made preventive
// compaction fire far too early and the context-usage gauge
// read a nonsensical >100% for a model this table simply hadn't
// been updated for yet.
return 1000000
}
return 0
+23
View File
@@ -52,6 +52,29 @@ func TestContextWindowKnown(t *testing.T) {
}
}
// Regression: a Gemini generation newer than the ones explicitly
// enumerated (3.x and beyond) must not fall through to
// defaultRemoteUnknownWindow (128k) just because this table hasn't been
// updated with its exact version string yet — every non-Pro Gemini
// model since 1.5 has shipped at least a 1M window, and every Pro-tier
// release has shipped at least 2M.
func TestContextWindowGeminiFutureGenerationsDefaultByTier(t *testing.T) {
tests := []struct {
model string
want int
}{
{"openai/gemini-3.8-flash-global", 1000000}, // proxied under an unrelated provider label, as via a LiteLLM gateway
{"google/gemini-3-flash", 1000000},
{"google/gemini-3-pro", 2000000},
{"google/gemini-4.0-flash-lite", 1000000},
}
for _, tc := range tests {
t.Run(tc.model, func(t *testing.T) {
assert.Equal(t, tc.want, ContextWindow(tc.model))
})
}
}
func TestContextWindowUnknownRemoteReturnsRemoteFallback(t *testing.T) {
// Non-local unknown models default to 128k — frontier proxies are
// overwhelmingly 128k+, and reactive compaction handles overflow.