Initial commit: Go agentic harness extracted from Felix
This commit is contained in:
commit
1f2c471ff9
89 files changed
+19388
No files matched your search
@@ -0,0 +1,80 @@
|
||||
// Package llmtest provides shared test helpers for LLMProvider stubs.
|
||||
//
|
||||
// Two pieces:
|
||||
// - Base: an embeddable struct that supplies default no-op
|
||||
// implementations of every LLMProvider method except ChatStream.
|
||||
// Test stubs that need custom ChatStream behavior should embed Base
|
||||
// so the LLMProvider interface can grow without churning every stub.
|
||||
// - Stub: a fully-configurable LLMProvider for the common case
|
||||
// (canned text response, optional delay, observable requests).
|
||||
package llmtest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
)
|
||||
|
||||
// Base provides default implementations of every LLMProvider method
|
||||
// except ChatStream. Embed this in test stubs to avoid having to update
|
||||
// every stub when the interface widens.
|
||||
type Base struct{}
|
||||
|
||||
// Models returns an empty slice (non-nil so callers can range safely).
|
||||
func (Base) Models() []llm.ModelInfo { return []llm.ModelInfo{} }
|
||||
|
||||
// NormalizeToolSchema is identity by default — no fields stripped, no
|
||||
// diagnostics emitted. Per-provider implementations strip fields their
|
||||
// API rejects.
|
||||
func (Base) NormalizeToolSchema(tools []llm.ToolDef) ([]llm.ToolDef, []llm.Diagnostic) {
|
||||
return tools, nil
|
||||
}
|
||||
|
||||
// Stub is a configurable LLMProvider for tests.
|
||||
type Stub struct {
|
||||
Base
|
||||
|
||||
// Text is the canned text response emitted on every ChatStream call.
|
||||
Text string
|
||||
// Delay sleeps before emitting the response. Zero means immediate.
|
||||
Delay time.Duration
|
||||
// Started is closed (once) just before the response is delayed/emitted.
|
||||
// Useful for synchronizing concurrent tests.
|
||||
Started chan struct{}
|
||||
// ChatErr, if non-nil, is returned synchronously from ChatStream.
|
||||
ChatErr error
|
||||
// ChatHook, if non-nil, observes every ChatStream request before
|
||||
// emission. Hook executes synchronously inside ChatStream.
|
||||
ChatHook func(req llm.ChatRequest)
|
||||
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (s *Stub) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
|
||||
if s.ChatHook != nil {
|
||||
s.ChatHook(req)
|
||||
}
|
||||
if s.ChatErr != nil {
|
||||
return nil, s.ChatErr
|
||||
}
|
||||
if s.Started != nil {
|
||||
s.once.Do(func() { close(s.Started) })
|
||||
}
|
||||
ch := make(chan llm.ChatEvent, 4)
|
||||
go func() {
|
||||
defer close(ch)
|
||||
if s.Delay > 0 {
|
||||
select {
|
||||
case <-time.After(s.Delay):
|
||||
case <-ctx.Done():
|
||||
ch <- llm.ChatEvent{Type: llm.EventError, Error: ctx.Err()}
|
||||
return
|
||||
}
|
||||
}
|
||||
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: s.Text}
|
||||
ch <- llm.ChatEvent{Type: llm.EventDone}
|
||||
}()
|
||||
return ch, nil
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package llmtest_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/sausheong/harness/llm"
|
||||
"github.com/sausheong/harness/llm/llmtest"
|
||||
)
|
||||
|
||||
func TestBaseDefaults(t *testing.T) {
|
||||
type stub struct {
|
||||
llmtest.Base
|
||||
}
|
||||
s := &stub{}
|
||||
// Models must be non-nil-empty (callers may range over it).
|
||||
assert.NotNil(t, s.Models())
|
||||
}
|
||||
|
||||
func TestStubCannedText(t *testing.T) {
|
||||
s := &llmtest.Stub{Text: "hello"}
|
||||
ch, err := s.ChatStream(context.Background(), llm.ChatRequest{})
|
||||
require.NoError(t, err)
|
||||
var got string
|
||||
for ev := range ch {
|
||||
if ev.Type == llm.EventTextDelta {
|
||||
got += ev.Text
|
||||
}
|
||||
}
|
||||
assert.Equal(t, "hello", got)
|
||||
}
|
||||
|
||||
func TestStubChatHookObservesRequests(t *testing.T) {
|
||||
var seen []llm.ChatRequest
|
||||
s := &llmtest.Stub{
|
||||
Text: "ok",
|
||||
ChatHook: func(req llm.ChatRequest) { seen = append(seen, req) },
|
||||
}
|
||||
_, _ = s.ChatStream(context.Background(), llm.ChatRequest{Model: "m1"})
|
||||
_, _ = s.ChatStream(context.Background(), llm.ChatRequest{Model: "m2"})
|
||||
require.Len(t, seen, 2)
|
||||
assert.Equal(t, "m1", seen[0].Model)
|
||||
assert.Equal(t, "m2", seen[1].Model)
|
||||
}
|
||||
|
||||
func TestStubChatErrShortCircuits(t *testing.T) {
|
||||
s := &llmtest.Stub{ChatErr: assert.AnError}
|
||||
_, err := s.ChatStream(context.Background(), llm.ChatRequest{})
|
||||
assert.Equal(t, assert.AnError, err)
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
"strings"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// normalizedEntry is one cached normalization result.
|
||||
type normalizedEntry struct {
|
||||
Tools []ToolDef
|
||||
Diags []Diagnostic
|
||||
}
|
||||
|
||||
// stripCache memoizes ApplyStripList by a hash of (fields, tools). The
|
||||
// agent runtime calls NormalizeToolSchema once per turn with a
|
||||
// deterministic tool list (alphabetically sorted by Registry.ToolDefs),
|
||||
// which means turn 1 computes the strip and turns 2..N hit the cache.
|
||||
//
|
||||
// Cache size is bounded by the cardinality of distinct tool sets across
|
||||
// the process. In practice this is small: one entry per (provider strip
|
||||
// list, agent tool allowlist). A 256-entry hard cap with random
|
||||
// eviction protects against pathological churn.
|
||||
var (
|
||||
stripCacheMu sync.RWMutex
|
||||
stripCache = map[string]normalizedEntry{}
|
||||
)
|
||||
|
||||
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).
|
||||
//
|
||||
// Memoized: identical inputs return cached output without re-walking
|
||||
// the JSON Schema. Cache key is a SHA-256 over (sorted fields, tool
|
||||
// names+parameters). Returned slices are copies so callers can safely
|
||||
// mutate them.
|
||||
func ApplyStripList(tools []ToolDef, fields []string) ([]ToolDef, []Diagnostic) {
|
||||
if len(tools) == 0 {
|
||||
return tools, nil
|
||||
}
|
||||
key := stripCacheKey(tools, fields)
|
||||
|
||||
stripCacheMu.RLock()
|
||||
if hit, ok := stripCache[key]; ok {
|
||||
stripCacheMu.RUnlock()
|
||||
return cloneToolDefs(hit.Tools), cloneDiags(hit.Diags)
|
||||
}
|
||||
stripCacheMu.RUnlock()
|
||||
|
||||
out := make([]ToolDef, len(tools))
|
||||
var allDiags []Diagnostic
|
||||
for i, t := range tools {
|
||||
newParams, diags := StripFields(t.Name, t.Parameters, fields)
|
||||
td := t
|
||||
td.Parameters = newParams
|
||||
out[i] = td
|
||||
allDiags = append(allDiags, diags...)
|
||||
}
|
||||
|
||||
stripCacheMu.Lock()
|
||||
if len(stripCache) >= stripCacheMax {
|
||||
// Drop one arbitrary entry to keep the map bounded. Map iteration
|
||||
// order is randomized, so this is effectively random eviction.
|
||||
for k := range stripCache {
|
||||
delete(stripCache, k)
|
||||
break
|
||||
}
|
||||
}
|
||||
stripCache[key] = normalizedEntry{Tools: cloneToolDefs(out), Diags: cloneDiags(allDiags)}
|
||||
stripCacheMu.Unlock()
|
||||
|
||||
return out, allDiags
|
||||
}
|
||||
|
||||
// stripCacheKey hashes the inputs into a stable string. Sorts the fields
|
||||
// list because the per-provider strip lists are stable but defensively
|
||||
// supports unsorted input.
|
||||
func stripCacheKey(tools []ToolDef, fields []string) string {
|
||||
sortedFields := make([]string, len(fields))
|
||||
copy(sortedFields, fields)
|
||||
sort.Strings(sortedFields)
|
||||
h := sha256.New()
|
||||
h.Write([]byte(strings.Join(sortedFields, "\x00")))
|
||||
h.Write([]byte("\x01"))
|
||||
for _, t := range tools {
|
||||
h.Write([]byte(t.Name))
|
||||
h.Write([]byte("\x02"))
|
||||
h.Write(t.Parameters)
|
||||
h.Write([]byte("\x03"))
|
||||
}
|
||||
return hex.EncodeToString(h.Sum(nil))
|
||||
}
|
||||
|
||||
func cloneToolDefs(in []ToolDef) []ToolDef {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]ToolDef, len(in))
|
||||
copy(out, in)
|
||||
return out
|
||||
}
|
||||
|
||||
func cloneDiags(in []Diagnostic) []Diagnostic {
|
||||
if in == nil {
|
||||
return nil
|
||||
}
|
||||
out := make([]Diagnostic, len(in))
|
||||
copy(out, in)
|
||||
return out
|
||||
}
|
||||
|
||||
// ResetStripCache is exported for tests so they can verify cache
|
||||
// behavior without process restart. Production code should not call
|
||||
// this — the cache is bounded by stripCacheMax and otherwise lives for
|
||||
// the process lifetime.
|
||||
func ResetStripCache() {
|
||||
stripCacheMu.Lock()
|
||||
stripCache = map[string]normalizedEntry{}
|
||||
stripCacheMu.Unlock()
|
||||
}
|
||||
|
||||
// StripFields removes the given field names from a JSON Schema document
|
||||
// recursively. It descends into "properties.*", "items", and
|
||||
// "additionalProperties" (the standard JSON Schema schema-bearing
|
||||
// positions). Returns the rewritten schema as JSON bytes and one
|
||||
// Diagnostic per stripped occurrence (ToolName set, Field set to the
|
||||
// dotted JSON path).
|
||||
//
|
||||
// Determinism: the walker visits map keys in sorted order so output
|
||||
// and diagnostics are reproducible across calls. Required for prompt
|
||||
// cache stability — the agent runtime calls NormalizeToolSchema once
|
||||
// per turn, and any non-determinism here would invalidate the cache.
|
||||
//
|
||||
// Malformed schemas are returned unchanged with no diagnostics; the
|
||||
// provider SDK will produce its own error.
|
||||
func StripFields(toolName string, schema json.RawMessage, fields []string) (json.RawMessage, []Diagnostic) {
|
||||
if len(fields) == 0 || len(schema) == 0 {
|
||||
return schema, nil
|
||||
}
|
||||
stripSet := make(map[string]bool, len(fields))
|
||||
for _, f := range fields {
|
||||
stripSet[f] = true
|
||||
}
|
||||
var doc any
|
||||
if err := json.Unmarshal(schema, &doc); err != nil {
|
||||
return schema, nil
|
||||
}
|
||||
var diags []Diagnostic
|
||||
stripped := walkStrip(doc, "", toolName, stripSet, &diags)
|
||||
out, err := json.Marshal(stripped)
|
||||
if err != nil {
|
||||
return schema, nil
|
||||
}
|
||||
return out, diags
|
||||
}
|
||||
|
||||
// walkStrip is the recursive worker. Returns the (possibly rewritten)
|
||||
// node and appends any diagnostics for stripped fields.
|
||||
func walkStrip(node any, path string, toolName string, stripSet map[string]bool, diags *[]Diagnostic) any {
|
||||
m, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
return node
|
||||
}
|
||||
keys := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, k := range keys {
|
||||
fieldPath := joinPath(path, k)
|
||||
if stripSet[k] {
|
||||
*diags = append(*diags, Diagnostic{
|
||||
ToolName: toolName,
|
||||
Field: fieldPath,
|
||||
Action: "stripped",
|
||||
Reason: "field not supported by provider",
|
||||
})
|
||||
delete(m, k)
|
||||
continue
|
||||
}
|
||||
switch k {
|
||||
case "properties":
|
||||
if props, ok := m[k].(map[string]any); ok {
|
||||
propKeys := make([]string, 0, len(props))
|
||||
for pk := range props {
|
||||
propKeys = append(propKeys, pk)
|
||||
}
|
||||
sort.Strings(propKeys)
|
||||
for _, pk := range propKeys {
|
||||
props[pk] = walkStrip(props[pk], joinPath(fieldPath, pk), toolName, stripSet, diags)
|
||||
}
|
||||
}
|
||||
case "items", "additionalProperties":
|
||||
m[k] = walkStrip(m[k], fieldPath, toolName, stripSet, diags)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func joinPath(base, leaf string) string {
|
||||
if base == "" {
|
||||
return leaf
|
||||
}
|
||||
return base + "." + leaf
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestStripFieldsTopLevel(t *testing.T) {
|
||||
in := json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {"x": {"type": "string"}},
|
||||
"$ref": "#/defs/foo"
|
||||
}`)
|
||||
out, diags := StripFields("mytool", in, []string{"$ref"})
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(out, &parsed))
|
||||
_, hasRef := parsed["$ref"]
|
||||
assert.False(t, hasRef, "$ref must be stripped")
|
||||
require.Len(t, diags, 1)
|
||||
assert.Equal(t, "mytool", diags[0].ToolName)
|
||||
assert.Equal(t, "$ref", diags[0].Field)
|
||||
assert.Equal(t, "stripped", diags[0].Action)
|
||||
}
|
||||
|
||||
func TestStripFieldsNested(t *testing.T) {
|
||||
in := json.RawMessage(`{
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"url": {"type": "string", "format": "uri"},
|
||||
"items": {
|
||||
"type": "array",
|
||||
"items": {"type": "string", "format": "email"}
|
||||
}
|
||||
}
|
||||
}`)
|
||||
out, diags := StripFields("read", in, []string{"format"})
|
||||
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(out, &parsed))
|
||||
props := parsed["properties"].(map[string]any)
|
||||
url := props["url"].(map[string]any)
|
||||
_, hasFormat := url["format"]
|
||||
assert.False(t, hasFormat, "nested format under properties.url must be stripped")
|
||||
items := props["items"].(map[string]any)
|
||||
itemsItems := items["items"].(map[string]any)
|
||||
_, hasNestedFormat := itemsItems["format"]
|
||||
assert.False(t, hasNestedFormat, "format under properties.items.items must be stripped")
|
||||
require.Len(t, diags, 2)
|
||||
// Keys are visited in sorted order: "items" < "url" alphabetically,
|
||||
// so the items.items.format diagnostic comes first.
|
||||
assert.Equal(t, "properties.items.items.format", diags[0].Field)
|
||||
assert.Equal(t, "properties.url.format", diags[1].Field)
|
||||
}
|
||||
|
||||
func TestStripFieldsAdditionalProperties(t *testing.T) {
|
||||
in := json.RawMessage(`{
|
||||
"type": "object",
|
||||
"additionalProperties": {"type": "string", "$ref": "#/x"}
|
||||
}`)
|
||||
out, diags := StripFields("t", in, []string{"$ref"})
|
||||
var parsed map[string]any
|
||||
require.NoError(t, json.Unmarshal(out, &parsed))
|
||||
addl := parsed["additionalProperties"].(map[string]any)
|
||||
_, has := addl["$ref"]
|
||||
assert.False(t, has)
|
||||
require.Len(t, diags, 1)
|
||||
assert.Equal(t, "additionalProperties.$ref", diags[0].Field)
|
||||
}
|
||||
|
||||
func TestStripFieldsNoOp(t *testing.T) {
|
||||
in := json.RawMessage(`{"type":"object","properties":{"a":{"type":"string"}}}`)
|
||||
out, diags := StripFields("t", in, []string{"$ref", "format"})
|
||||
// Output bytes may differ from input due to re-marshal, but parsing
|
||||
// both must produce the same structure and no fields are removed.
|
||||
var inDoc, outDoc any
|
||||
require.NoError(t, json.Unmarshal(in, &inDoc))
|
||||
require.NoError(t, json.Unmarshal(out, &outDoc))
|
||||
assert.Equal(t, inDoc, outDoc, "no fields to strip → structurally unchanged")
|
||||
assert.Empty(t, diags)
|
||||
}
|
||||
|
||||
func TestStripFieldsDeterministic(t *testing.T) {
|
||||
// Same input must produce the same output and diagnostic order
|
||||
// across repeated calls. Required for cache stability.
|
||||
in := json.RawMessage(`{
|
||||
"properties": {
|
||||
"a": {"format": "uri"},
|
||||
"b": {"format": "email"},
|
||||
"c": {"format": "date"}
|
||||
}
|
||||
}`)
|
||||
out1, diags1 := StripFields("t", in, []string{"format"})
|
||||
out2, diags2 := StripFields("t", in, []string{"format"})
|
||||
assert.Equal(t, string(out1), string(out2))
|
||||
assert.Equal(t, diags1, diags2)
|
||||
}
|
||||
|
||||
func TestStripFieldsEmptyInputs(t *testing.T) {
|
||||
// Empty fields list → no-op, returns input unchanged.
|
||||
out, diags := StripFields("t", json.RawMessage(`{"x":1}`), nil)
|
||||
assert.Equal(t, `{"x":1}`, string(out))
|
||||
assert.Nil(t, diags)
|
||||
// Empty schema → no-op.
|
||||
out2, diags2 := StripFields("t", nil, []string{"$ref"})
|
||||
assert.Nil(t, out2)
|
||||
assert.Nil(t, diags2)
|
||||
}
|
||||
|
||||
func TestStripFieldsMalformedSchema(t *testing.T) {
|
||||
// Malformed JSON → return as-is, no diagnostic. Provider SDK will
|
||||
// reject with its own error.
|
||||
bad := json.RawMessage(`{"unclosed`)
|
||||
out, diags := StripFields("t", bad, []string{"$ref"})
|
||||
assert.Equal(t, bad, out)
|
||||
assert.Empty(t, diags)
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// EventType identifies the kind of streaming event from the LLM.
|
||||
type EventType int
|
||||
|
||||
const (
|
||||
EventTextDelta EventType = iota
|
||||
EventToolCallStart
|
||||
EventToolCallDelta
|
||||
EventToolCallDone
|
||||
EventDone
|
||||
EventError
|
||||
)
|
||||
|
||||
// ImageContent holds image data for multimodal messages.
|
||||
type ImageContent struct {
|
||||
MimeType string // "image/jpeg", "image/png", etc.
|
||||
Data []byte // raw image bytes
|
||||
}
|
||||
|
||||
// Message represents a conversation message.
|
||||
type Message struct {
|
||||
Role string `json:"role"` // "user", "assistant", "system"
|
||||
Content string `json:"content,omitempty"`
|
||||
Images []ImageContent `json:"-"` // image attachments (not serialized)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // for tool results
|
||||
IsError bool `json:"is_error,omitempty"` // for tool results
|
||||
}
|
||||
|
||||
// ToolCall represents a tool invocation requested by the LLM.
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
|
||||
// ToolDef defines a tool for the LLM.
|
||||
type ToolDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters json.RawMessage `json:"parameters"` // JSON Schema
|
||||
}
|
||||
|
||||
// Diagnostic describes a single normalization or clamping event emitted
|
||||
// by NormalizeToolSchema or per-provider reasoning mapping. The runtime
|
||||
// logs these via slog; they are advisory, not fatal.
|
||||
type Diagnostic struct {
|
||||
ToolName string // empty for non-tool diagnostics (e.g., reasoning)
|
||||
Field string // dotted JSON path: "properties.url.format" — empty for whole-tool actions
|
||||
Action string // "stripped" | "rewritten" | "rejected" | "clamped" | "ignored"
|
||||
Reason string // human-readable; safe to log
|
||||
}
|
||||
|
||||
// SystemPromptPart is one segment of the system prompt. Providers that
|
||||
// support prompt caching attach a cache marker to parts where Cache=true;
|
||||
// providers that don't simply concatenate Text fields together.
|
||||
type SystemPromptPart struct {
|
||||
Text string
|
||||
// Cache requests that the prefix up to and including this part be cached.
|
||||
// Anthropic-only; ignored elsewhere.
|
||||
Cache bool
|
||||
}
|
||||
|
||||
// ReasoningMode is the unified reasoning/thinking knob across providers.
|
||||
// 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).
|
||||
type ReasoningMode string
|
||||
|
||||
const (
|
||||
ReasoningOff ReasoningMode = ""
|
||||
ReasoningLow ReasoningMode = "low"
|
||||
ReasoningMedium ReasoningMode = "medium"
|
||||
ReasoningHigh ReasoningMode = "high"
|
||||
)
|
||||
|
||||
// ParseReasoningMode parses a config string into a ReasoningMode.
|
||||
// Accepts "" or "off" for ReasoningOff; "low", "medium", "high" for
|
||||
// the named levels. Case-sensitive. Returns an error for unknown values.
|
||||
func ParseReasoningMode(s string) (ReasoningMode, error) {
|
||||
switch s {
|
||||
case "", "off":
|
||||
return ReasoningOff, nil
|
||||
case "low":
|
||||
return ReasoningLow, nil
|
||||
case "medium":
|
||||
return ReasoningMedium, nil
|
||||
case "high":
|
||||
return ReasoningHigh, nil
|
||||
default:
|
||||
return ReasoningOff, fmt.Errorf("unknown reasoning mode %q (want off|low|medium|high)", s)
|
||||
}
|
||||
}
|
||||
|
||||
// ChatRequest is the input to a streaming chat call.
|
||||
type ChatRequest struct {
|
||||
Model string
|
||||
Messages []Message
|
||||
Tools []ToolDef
|
||||
MaxTokens int
|
||||
Temperature float64
|
||||
SystemPrompt string
|
||||
// SystemPromptParts, when non-empty, replaces SystemPrompt. Providers
|
||||
// that support caching emit one block per part, attaching cache markers
|
||||
// per Cache flag. Providers that don't support caching concatenate
|
||||
// Text fields with "\n" separators.
|
||||
SystemPromptParts []SystemPromptPart
|
||||
// CacheLastMessage requests that the final block of the final user
|
||||
// message also be cache-marked. Anthropic-only; ignored elsewhere.
|
||||
CacheLastMessage bool
|
||||
Reasoning ReasoningMode // zero value = ReasoningOff; safe default
|
||||
}
|
||||
|
||||
// Usage tracks token usage.
|
||||
type Usage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens,omitempty"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens,omitempty"`
|
||||
}
|
||||
|
||||
// ChatEvent is a single streaming event from the LLM.
|
||||
type ChatEvent struct {
|
||||
Type EventType
|
||||
Text string
|
||||
ToolCall *ToolCall
|
||||
Usage *Usage
|
||||
Error error
|
||||
}
|
||||
|
||||
// ModelInfo describes an available model.
|
||||
type ModelInfo struct {
|
||||
ID string
|
||||
Name string
|
||||
Provider string
|
||||
}
|
||||
|
||||
// LLMProvider is the interface for all LLM backends.
|
||||
type LLMProvider interface {
|
||||
ChatStream(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
|
||||
Models() []ModelInfo
|
||||
// NormalizeToolSchema rewrites tool JSON Schemas to the subset the
|
||||
// provider accepts. Returns the normalized tool list (input order
|
||||
// preserved) and a diagnostic per stripped/rewritten/rejected field.
|
||||
// Implementations must be deterministic — same input → same output
|
||||
// in the same diagnostic order — to preserve prompt cache stability.
|
||||
NormalizeToolSchema(tools []ToolDef) ([]ToolDef, []Diagnostic)
|
||||
}
|
||||
|
||||
// NonStreamingProvider is an optional capability some providers implement
|
||||
// alongside ChatStream. The runtime type-asserts to it when a stream
|
||||
// dies mid-flight (some tokens received, then EventError before
|
||||
// EventDone) and retries the same request as a non-streaming call —
|
||||
// the partial output is discarded so the prompt cache prefix stays
|
||||
// byte-identical to what would have been there on a clean stream.
|
||||
//
|
||||
// Returns the events the provider would have emitted on a successful
|
||||
// stream (text deltas, tool_call_start, tool_call_done, done with
|
||||
// usage). Caller drains the channel as it would for ChatStream;
|
||||
// channel closes when complete.
|
||||
type NonStreamingProvider interface {
|
||||
ChatNonStreaming(ctx context.Context, req ChatRequest) (<-chan ChatEvent, error)
|
||||
}
|
||||
|
||||
// ParseProviderModel splits "provider/model" into (provider, model).
|
||||
// If no slash is present, returns ("", name) and the caller should use a default.
|
||||
func ParseProviderModel(name string) (provider, model string) {
|
||||
parts := strings.SplitN(name, "/", 2)
|
||||
if len(parts) == 2 {
|
||||
return parts[0], parts[1]
|
||||
}
|
||||
return "", name
|
||||
}
|
||||
|
||||
// concatSystemPromptParts joins parts back into a single string with "\n"
|
||||
// separators. Used by every provider that doesn't implement caching.
|
||||
// Empty Text fields are skipped. Returns "" for a nil/empty slice.
|
||||
func concatSystemPromptParts(parts []SystemPromptPart) string {
|
||||
if len(parts) == 0 {
|
||||
return ""
|
||||
}
|
||||
var nonEmpty []string
|
||||
for _, p := range parts {
|
||||
if p.Text != "" {
|
||||
nonEmpty = append(nonEmpty, p.Text)
|
||||
}
|
||||
}
|
||||
return strings.Join(nonEmpty, "\n")
|
||||
}
|
||||
|
||||
// JoinSystemPromptParts is the exported variant of concatSystemPromptParts
|
||||
// for callers outside the llm package (e.g., agent runtime token estimation
|
||||
// that needs the joined string for tokens.Estimate).
|
||||
func JoinSystemPromptParts(parts []SystemPromptPart) string {
|
||||
return concatSystemPromptParts(parts)
|
||||
}
|
||||
|
||||
// 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.
|
||||
type ProviderOptions struct {
|
||||
APIKey string
|
||||
BaseURL string
|
||||
Kind string // "anthropic" | "openai" | "openai-compatible" | "local" | "gemini" | "qwen"
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
)
|
||||
|
||||
// IsRetryableModelError reports whether err is a transient capacity
|
||||
// failure from a hosted LLM provider — the kind of error a fallback
|
||||
// model can plausibly succeed at. Recognised:
|
||||
//
|
||||
// - Anthropic 429 (rate limit) and 529 (overloaded)
|
||||
// - OpenAI 429 (rate limit) and 5xx (server / overloaded)
|
||||
//
|
||||
// Anything else (including 4xx auth/validation errors) returns false:
|
||||
// retrying with a different model wouldn't fix the underlying problem.
|
||||
//
|
||||
// Errors from local providers (Ollama, etc.) and Gemini are NOT
|
||||
// classified as retryable here; their failure modes are different
|
||||
// and a model swap rarely helps. Add cases as new providers
|
||||
// accumulate retry experience.
|
||||
func IsRetryableModelError(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
// Typed-error path: when ANY known SDK error type matches, return
|
||||
// its decision authoritatively. Falling through to substring
|
||||
// matching after a typed "not retryable" verdict would mask
|
||||
// 4xx auth/validation failures whose .Error() text happens to
|
||||
// contain numbers like "429" in unrelated contexts (e.g., a
|
||||
// quota path or a request id).
|
||||
var anthErr *anthropic.Error
|
||||
if errors.As(err, &anthErr) {
|
||||
return anthErr.StatusCode == 429 || anthErr.StatusCode == 529
|
||||
}
|
||||
var openaiAPIErr *openai.APIError
|
||||
if errors.As(err, &openaiAPIErr) {
|
||||
return openaiAPIErr.HTTPStatusCode == 429 ||
|
||||
(openaiAPIErr.HTTPStatusCode >= 500 && openaiAPIErr.HTTPStatusCode < 600)
|
||||
}
|
||||
var openaiReqErr *openai.RequestError
|
||||
if errors.As(err, &openaiReqErr) {
|
||||
return openaiReqErr.HTTPStatusCode == 429 ||
|
||||
(openaiReqErr.HTTPStatusCode >= 500 && openaiReqErr.HTTPStatusCode < 600)
|
||||
}
|
||||
|
||||
// Last-ditch: substring match on common SDK error wrappers that
|
||||
// don't unwrap cleanly to typed errors. Cheap belt-and-braces;
|
||||
// only reached when no typed match found above.
|
||||
msg := strings.ToLower(err.Error())
|
||||
if strings.Contains(msg, "429") || strings.Contains(msg, "529") ||
|
||||
strings.Contains(msg, "rate limit") || strings.Contains(msg, "overloaded") {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
anthropic "github.com/anthropics/anthropic-sdk-go"
|
||||
openai "github.com/sashabaranov/go-openai"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic429(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic529(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 529}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic400NotRetryable(t *testing.T) {
|
||||
// Bad-request, validation errors etc. — fallback model can't fix
|
||||
// these, so we must NOT swap models. Critical: a flag flip here
|
||||
// would silently mask config bugs by pretending the second call
|
||||
// succeeded against a different model.
|
||||
err := &anthropic.Error{StatusCode: 400}
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorAnthropic401NotRetryable(t *testing.T) {
|
||||
err := &anthropic.Error{StatusCode: 401}
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOpenAI429(t *testing.T) {
|
||||
err := &openai.APIError{HTTPStatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOpenAI500(t *testing.T) {
|
||||
err := &openai.APIError{HTTPStatusCode: 500}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOpenAI503(t *testing.T) {
|
||||
err := &openai.APIError{HTTPStatusCode: 503}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOpenAI400NotRetryable(t *testing.T) {
|
||||
err := &openai.APIError{HTTPStatusCode: 400}
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOpenAIRequestError(t *testing.T) {
|
||||
// RequestError is the SDK's wrapper for non-API HTTP failures.
|
||||
err := &openai.RequestError{HTTPStatusCode: 429}
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorWrappedError(t *testing.T) {
|
||||
// errors.As must traverse fmt.Errorf %w wrappers — the runtime
|
||||
// wraps SDK errors in fmt.Errorf("llm error: %w", err), which
|
||||
// landed past the classifier in an earlier draft.
|
||||
wrapped := fmt.Errorf("transient: %w", &anthropic.Error{StatusCode: 529})
|
||||
assert.True(t, IsRetryableModelError(wrapped))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorNil(t *testing.T) {
|
||||
assert.False(t, IsRetryableModelError(nil))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOtherErrorString429(t *testing.T) {
|
||||
// Substring fallback: an SDK that returns a plain wrapped error
|
||||
// without typed-error interfaces should still be classified
|
||||
// correctly. Belt-and-braces.
|
||||
err := errors.New("api request failed: 429 Too Many Requests")
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorOtherErrorStringRateLimit(t *testing.T) {
|
||||
err := errors.New("rate limit exceeded")
|
||||
assert.True(t, IsRetryableModelError(err))
|
||||
}
|
||||
|
||||
func TestIsRetryableModelErrorUnrelatedError(t *testing.T) {
|
||||
err := errors.New("some other failure")
|
||||
assert.False(t, IsRetryableModelError(err))
|
||||
}
|
||||
Reference in new issue
Block a user