build: 内置 norma 模块,构建不再依赖上游仓库
把 github.com/Autumn-27/norma v0.4.3(commit 320ae32)的源码复制到 third_party/norma,并用 go.mod 的 replace 指向本地副本。上游删除仓库或 改写 tag 都不再影响本仓库构建。 - 已验证 GOPROXY=off 下可完整编译并打出发行包 - go.sum 中该模块的两条校验记录随之删除(本地 replace 不需要哈希) - 升级方法与授权注意事项见 third_party/README.md
This commit is contained in:
1 parent
a819fa3230
commit
f782b612ec
213 files changed
+37401
-2
No files matched your search
Vendored
+106
@@ -0,0 +1,106 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Accumulator reassembles a complete assistant Message from a stream of
|
||||
// normalized StreamEvents. The harness feeds every event to Add; once the
|
||||
// stream ends, Message returns the finished assistant turn (text, thinking, and
|
||||
// tool_use blocks in arrival order).
|
||||
type Accumulator struct {
|
||||
blocks []ContentBlock
|
||||
toolInputs []*strings.Builder
|
||||
textBuf *strings.Builder
|
||||
thinkBuf *strings.Builder
|
||||
thinkSig string // signature for the current thinking block
|
||||
StopReason string
|
||||
Usage Usage
|
||||
}
|
||||
|
||||
// NewAccumulator returns an empty Accumulator.
|
||||
func NewAccumulator() *Accumulator { return &Accumulator{} }
|
||||
|
||||
// Add folds one event into the accumulator.
|
||||
func (a *Accumulator) Add(ev StreamEvent) {
|
||||
switch ev.Type {
|
||||
case SEMessageStart:
|
||||
a.Usage.Add(ev.Usage)
|
||||
case SETextDelta:
|
||||
if a.textBuf == nil {
|
||||
a.flushThinking()
|
||||
a.textBuf = &strings.Builder{}
|
||||
}
|
||||
a.textBuf.WriteString(ev.Text)
|
||||
case SEThinkingDelta:
|
||||
if a.thinkBuf == nil {
|
||||
a.flushText()
|
||||
a.thinkBuf = &strings.Builder{}
|
||||
}
|
||||
a.thinkBuf.WriteString(ev.Text)
|
||||
case SEThinkingSignature:
|
||||
a.thinkSig = ev.Text
|
||||
case SEToolUseStart:
|
||||
a.flushText()
|
||||
a.flushThinking()
|
||||
a.blocks = append(a.blocks, ContentBlock{Type: BlockToolUse, ID: ev.ToolID, Name: ev.ToolName})
|
||||
a.toolInputs = append(a.toolInputs, &strings.Builder{})
|
||||
case SEToolInputJSON:
|
||||
if n := len(a.toolInputs); n > 0 {
|
||||
a.toolInputs[n-1].WriteString(ev.Text)
|
||||
}
|
||||
case SEMessageDelta:
|
||||
if ev.StopReason != "" {
|
||||
a.StopReason = ev.StopReason
|
||||
}
|
||||
a.Usage.Add(ev.Usage)
|
||||
case SEMessageStop:
|
||||
a.flushText()
|
||||
a.flushThinking()
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Accumulator) flushText() {
|
||||
if a.textBuf != nil {
|
||||
if s := a.textBuf.String(); s != "" {
|
||||
a.blocks = append(a.blocks, TextBlock(s))
|
||||
}
|
||||
a.textBuf = nil
|
||||
}
|
||||
}
|
||||
|
||||
func (a *Accumulator) flushThinking() {
|
||||
if a.thinkBuf != nil {
|
||||
if s := a.thinkBuf.String(); s != "" {
|
||||
a.blocks = append(a.blocks, ContentBlock{
|
||||
Type: BlockThinking,
|
||||
Thinking: s,
|
||||
Signature: a.thinkSig,
|
||||
})
|
||||
}
|
||||
a.thinkBuf = nil
|
||||
a.thinkSig = ""
|
||||
}
|
||||
}
|
||||
|
||||
// Message finalizes and returns the assembled assistant message. Partial tool
|
||||
// inputs are validated; malformed JSON falls back to "{}".
|
||||
func (a *Accumulator) Message() Message {
|
||||
a.flushText()
|
||||
a.flushThinking()
|
||||
ti := 0
|
||||
out := make([]ContentBlock, len(a.blocks))
|
||||
for i, b := range a.blocks {
|
||||
if b.Type == BlockToolUse {
|
||||
raw := strings.TrimSpace(a.toolInputs[ti].String())
|
||||
ti++
|
||||
if raw == "" || !json.Valid([]byte(raw)) {
|
||||
raw = "{}"
|
||||
}
|
||||
b.Input = json.RawMessage(raw)
|
||||
}
|
||||
out[i] = b
|
||||
}
|
||||
return Message{Role: RoleAssistant, Content: out}
|
||||
}
|
||||
Vendored
+386
@@ -0,0 +1,386 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type anthropicProvider struct{ cfg Config }
|
||||
|
||||
type anthropicSystemBlock struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
CacheControl map[string]any `json:"cache_control,omitempty"`
|
||||
}
|
||||
|
||||
type anthropicReq struct {
|
||||
Model string `json:"model"`
|
||||
System []anthropicSystemBlock `json:"system,omitempty"`
|
||||
Messages []Message `json:"messages"`
|
||||
Tools []anthropicTool `json:"tools,omitempty"`
|
||||
MaxTokens int `json:"max_tokens"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
StopSequences []string `json:"stop_sequences,omitempty"`
|
||||
Thinking *anthropicThinking `json:"thinking,omitempty"`
|
||||
OutputConfig *anthropicOutputConfig `json:"output_config,omitempty"`
|
||||
Stream bool `json:"stream"`
|
||||
}
|
||||
|
||||
// anthropicThinking is the "thinking":{"type":"enabled"|"disabled"} switch.
|
||||
type anthropicThinking struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
// anthropicOutputConfig carries the reasoning strength via
|
||||
// "output_config":{"effort":"low"|"medium"|"high"|"max"}.
|
||||
type anthropicOutputConfig struct {
|
||||
Effort string `json:"effort"`
|
||||
}
|
||||
|
||||
type anthropicTool struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"input_schema"`
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) buildBody(req CompletionRequest, stream bool) ([]byte, error) {
|
||||
maxTok := req.MaxTokens
|
||||
if maxTok == 0 {
|
||||
maxTok = 8192
|
||||
}
|
||||
// Effective thinking mode: a non-empty per-request override (req.Thinking)
|
||||
// wins over Config.ThinkingType. Thinking-type content blocks may be replayed
|
||||
// only when thinking is actively "enabled"; any other mode (incl. "disabled")
|
||||
// strips them so Anthropic does not reject the request.
|
||||
thinkingType := p.cfg.ThinkingType
|
||||
thinkingEnabled := thinkingType != ""
|
||||
if req.Thinking != "" {
|
||||
thinkingType = req.Thinking
|
||||
thinkingEnabled = req.Thinking == "enabled"
|
||||
}
|
||||
body := anthropicReq{
|
||||
Model: p.cfg.Model,
|
||||
Messages: mergeAdjacentSameRole(filterThinkingBlocks(req.Messages, thinkingEnabled)),
|
||||
MaxTokens: maxTok,
|
||||
Temperature: req.Temperature,
|
||||
StopSequences: req.Stop,
|
||||
Stream: stream,
|
||||
System: buildAnthropicSystem(req),
|
||||
}
|
||||
for _, t := range req.Tools {
|
||||
body.Tools = append(body.Tools, anthropicTool{Name: t.Name, Description: t.Description, InputSchema: t.InputSchema})
|
||||
}
|
||||
if thinkingType != "" {
|
||||
body.Thinking = &anthropicThinking{Type: thinkingType}
|
||||
}
|
||||
if p.cfg.ReasoningEffort != "" {
|
||||
body.OutputConfig = &anthropicOutputConfig{Effort: p.cfg.ReasoningEffort}
|
||||
}
|
||||
return json.Marshal(body)
|
||||
}
|
||||
|
||||
// buildAnthropicSystem splits the system prompt at DynamicBoundary, placing a
|
||||
// cache breakpoint on the static prefix (FR-02.2).
|
||||
func buildAnthropicSystem(req CompletionRequest) []anthropicSystemBlock {
|
||||
if len(req.System) == 0 {
|
||||
return nil
|
||||
}
|
||||
b := req.DynamicBoundary
|
||||
if b <= 0 {
|
||||
// No boundary set → no cache breakpoint.
|
||||
return []anthropicSystemBlock{{Type: "text", Text: joinSystem(req.System)}}
|
||||
}
|
||||
if b >= len(req.System) {
|
||||
// Boundary at/after the end → the whole system prompt is static; cache it
|
||||
// all in one block (an all-static prompt should still be cacheable).
|
||||
return []anthropicSystemBlock{{Type: "text", Text: joinSystem(req.System), CacheControl: map[string]any{"type": "ephemeral"}}}
|
||||
}
|
||||
return []anthropicSystemBlock{
|
||||
{Type: "text", Text: joinSystem(req.System[:b]), CacheControl: map[string]any{"type": "ephemeral"}},
|
||||
{Type: "text", Text: joinSystem(req.System[b:])},
|
||||
}
|
||||
}
|
||||
|
||||
func (p *anthropicProvider) Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error] {
|
||||
return func(yield func(StreamEvent, error) bool) {
|
||||
body, err := p.buildBody(req, true)
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/v1/messages", body, func(r *http.Request) {
|
||||
r.Header.Set("content-type", "application/json")
|
||||
r.Header.Set("x-api-key", p.cfg.APIKey)
|
||||
r.Header.Set("anthropic-version", p.cfg.APIVersion)
|
||||
r.Header.Set("accept", "text/event-stream")
|
||||
}, "anthropic")
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scan := newSSEScanner(resp.Body)
|
||||
for {
|
||||
_, data, serr := scan.next()
|
||||
if serr == io.EOF {
|
||||
return
|
||||
}
|
||||
if serr != nil {
|
||||
yield(StreamEvent{}, serr)
|
||||
return
|
||||
}
|
||||
if data == "" {
|
||||
continue
|
||||
}
|
||||
ev, ok, perr := parseAnthropicFrame(data)
|
||||
if perr != nil {
|
||||
yield(StreamEvent{}, perr)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if !yield(ev, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Complete performs a real non-streaming completion: it sends stream:false and
|
||||
// parses the single JSON response from /v1/messages into a full assistant
|
||||
// Message, returning it with the stop reason and normalized usage.
|
||||
func (p *anthropicProvider) Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error) {
|
||||
body, err := p.buildBody(req, false)
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/v1/messages", body, func(r *http.Request) {
|
||||
r.Header.Set("content-type", "application/json")
|
||||
r.Header.Set("x-api-key", p.cfg.APIKey)
|
||||
r.Header.Set("anthropic-version", p.cfg.APIVersion)
|
||||
r.Header.Set("accept", "application/json")
|
||||
}, "anthropic")
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
return parseAnthropicResponse(raw)
|
||||
}
|
||||
|
||||
// parseAnthropicResponse decodes a non-streaming Messages API response into the
|
||||
// neutral Message model. Anthropic already speaks the content-block shape, so
|
||||
// text/thinking/tool_use blocks map across directly.
|
||||
func parseAnthropicResponse(raw []byte) (Message, string, Usage, error) {
|
||||
var r struct {
|
||||
Type string `json:"type"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Input json.RawMessage `json:"input"`
|
||||
} `json:"content"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
Usage *anthropicUsage `json:"usage"`
|
||||
Error *struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return Message{}, "", Usage{}, fmt.Errorf("anthropic: decode response: %w (body: %s)", err, truncate(string(raw), 500))
|
||||
}
|
||||
if r.Error != nil || r.Type == "error" {
|
||||
msg := "error response"
|
||||
if r.Error != nil {
|
||||
msg = r.Error.Message
|
||||
}
|
||||
return Message{}, "", Usage{}, fmt.Errorf("anthropic: %s", msg)
|
||||
}
|
||||
var usage Usage
|
||||
if r.Usage != nil {
|
||||
usage = r.Usage.norm()
|
||||
}
|
||||
var blocks []ContentBlock
|
||||
for _, b := range r.Content {
|
||||
switch b.Type {
|
||||
case "text":
|
||||
if b.Text != "" {
|
||||
blocks = append(blocks, TextBlock(b.Text))
|
||||
}
|
||||
case "thinking":
|
||||
blocks = append(blocks, ContentBlock{Type: BlockThinking, Thinking: b.Thinking, Signature: b.Signature})
|
||||
case "tool_use":
|
||||
in := b.Input
|
||||
if len(in) == 0 {
|
||||
in = json.RawMessage("{}")
|
||||
}
|
||||
blocks = append(blocks, ContentBlock{Type: BlockToolUse, ID: b.ID, Name: b.Name, Input: in})
|
||||
}
|
||||
}
|
||||
return Message{Role: RoleAssistant, Content: blocks}, r.StopReason, usage, nil
|
||||
}
|
||||
|
||||
func parseAnthropicFrame(data string) (StreamEvent, bool, error) {
|
||||
var f struct {
|
||||
Type string `json:"type"`
|
||||
ContentBlock struct {
|
||||
Type string `json:"type"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
} `json:"content_block"`
|
||||
Delta struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
PartialJSON string `json:"partial_json"`
|
||||
Thinking string `json:"thinking"`
|
||||
Signature string `json:"signature"`
|
||||
StopReason string `json:"stop_reason"`
|
||||
} `json:"delta"`
|
||||
Usage *anthropicUsage `json:"usage"`
|
||||
Message struct {
|
||||
Usage *anthropicUsage `json:"usage"`
|
||||
} `json:"message"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &f); err != nil {
|
||||
return StreamEvent{}, false, nil // tolerate non-JSON keepalives
|
||||
}
|
||||
switch f.Type {
|
||||
case "message_start":
|
||||
if f.Message.Usage != nil {
|
||||
// Anthropic reports the full input side (input + cache read/creation) in
|
||||
// BOTH message_start and message_delta. To avoid double-counting when the
|
||||
// accumulator folds both events, message_start carries ONLY the input side
|
||||
// and message_delta carries ONLY output. The initial output_tokens here is
|
||||
// a placeholder (≈1), so drop it — the real output comes from message_delta.
|
||||
u := f.Message.Usage.norm()
|
||||
u.OutputTokens = 0
|
||||
return StreamEvent{Type: SEMessageStart, Usage: u}, true, nil
|
||||
}
|
||||
case "content_block_start":
|
||||
if f.ContentBlock.Type == "tool_use" {
|
||||
return StreamEvent{Type: SEToolUseStart, ToolID: f.ContentBlock.ID, ToolName: f.ContentBlock.Name}, true, nil
|
||||
}
|
||||
case "content_block_delta":
|
||||
switch f.Delta.Type {
|
||||
case "text_delta":
|
||||
return StreamEvent{Type: SETextDelta, Text: f.Delta.Text}, true, nil
|
||||
case "thinking_delta":
|
||||
return StreamEvent{Type: SEThinkingDelta, Text: f.Delta.Thinking}, true, nil
|
||||
case "signature_delta":
|
||||
return StreamEvent{Type: SEThinkingSignature, Text: f.Delta.Signature}, true, nil
|
||||
case "input_json_delta":
|
||||
return StreamEvent{Type: SEToolInputJSON, Text: f.Delta.PartialJSON}, true, nil
|
||||
}
|
||||
case "message_delta":
|
||||
ev := StreamEvent{Type: SEMessageDelta, StopReason: f.Delta.StopReason}
|
||||
if f.Usage != nil {
|
||||
// Only output here — the input side (input/cache) was already counted at
|
||||
// message_start; message_delta re-echoes it, so counting it again would
|
||||
// double the input/cache totals.
|
||||
ev.Usage = Usage{OutputTokens: f.Usage.OutputTokens}
|
||||
}
|
||||
return ev, true, nil
|
||||
case "message_stop":
|
||||
return StreamEvent{Type: SEMessageStop}, true, nil
|
||||
case "error":
|
||||
msg := "stream error"
|
||||
if f.Error != nil {
|
||||
msg = f.Error.Message
|
||||
}
|
||||
return StreamEvent{}, false, fmt.Errorf("anthropic: %s", msg)
|
||||
}
|
||||
return StreamEvent{}, false, nil
|
||||
}
|
||||
|
||||
type anthropicUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheReadInputTokens int `json:"cache_read_input_tokens"`
|
||||
CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
|
||||
}
|
||||
|
||||
// norm maps Anthropic usage to the canonical Usage. InputTokens is the TOTAL input
|
||||
// INCLUDING cached tokens (OpenAI-style: prompt_tokens semantics) — Anthropic's raw
|
||||
// input_tokens counts only the non-cached portion, so cache read+creation are folded
|
||||
// in. CacheReadTokens/CacheWriteTokens are the cached SUBSET (⊆ InputTokens).
|
||||
func (u anthropicUsage) norm() Usage {
|
||||
return Usage{
|
||||
InputTokens: u.InputTokens + u.CacheReadInputTokens + u.CacheCreationInputTokens,
|
||||
OutputTokens: u.OutputTokens,
|
||||
CacheReadTokens: u.CacheReadInputTokens,
|
||||
CacheWriteTokens: u.CacheCreationInputTokens,
|
||||
}
|
||||
}
|
||||
|
||||
// filterThinkingBlocks normalizes message history before it is sent to the
|
||||
// Anthropic Messages API. It strips thinking-type content blocks when thinking
|
||||
// is disabled (Anthropic rejects replayed thinking blocks without the thinking
|
||||
// parameter enabled), and drops any message left with no content blocks —
|
||||
// Anthropic rejects an empty content array. An empty message arrives here two
|
||||
// ways: a thinking-only turn that collapses to empty once thinking is stripped,
|
||||
// or an empty/truncated assistant turn (only reasoning, or nothing) that was
|
||||
// recorded with no text or tool_use. (A thinking-only turn WITH thinking
|
||||
// enabled keeps its thinking block — that is valid content and must be
|
||||
// replayed.)
|
||||
func filterThinkingBlocks(msgs []Message, thinkingEnabled bool) []Message {
|
||||
out := make([]Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
content := m.Content
|
||||
if !thinkingEnabled {
|
||||
filtered := make([]ContentBlock, 0, len(content))
|
||||
for _, b := range content {
|
||||
if b.Type != BlockThinking {
|
||||
filtered = append(filtered, b)
|
||||
}
|
||||
}
|
||||
content = filtered
|
||||
}
|
||||
if len(content) == 0 {
|
||||
continue // empty content array is rejected by Anthropic — drop it
|
||||
}
|
||||
if len(content) == len(m.Content) {
|
||||
out = append(out, m)
|
||||
} else {
|
||||
out = append(out, Message{Role: m.Role, Content: content})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// mergeAdjacentSameRole coalesces consecutive same-role messages into one by
|
||||
// concatenating their content blocks. Anthropic requires messages to alternate
|
||||
// user/assistant; dropping an empty turn in filterThinkingBlocks can leave two
|
||||
// adjacent user messages (e.g. a tool result followed by a resume nudge, once
|
||||
// the empty assistant between them is gone), which the API would reject with
|
||||
// "roles must alternate". Merging preserves alternation without losing content.
|
||||
// A fresh content slice is built on merge so the caller's message backing
|
||||
// arrays are never mutated.
|
||||
func mergeAdjacentSameRole(msgs []Message) []Message {
|
||||
out := make([]Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
if n := len(out); n > 0 && out[n-1].Role == m.Role {
|
||||
merged := make([]ContentBlock, 0, len(out[n-1].Content)+len(m.Content))
|
||||
merged = append(merged, out[n-1].Content...)
|
||||
merged = append(merged, m.Content...)
|
||||
out[n-1].Content = merged
|
||||
continue
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package llm
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBuildAnthropicSystemCacheBoundary(t *testing.T) {
|
||||
sys := []string{"a", "b", "c"}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
boundary int
|
||||
wantBlocks int
|
||||
wantCached []bool // per-block: has cache_control
|
||||
}{
|
||||
{"no boundary (0) → single uncached", 0, 1, []bool{false}},
|
||||
{"negative → single uncached", -1, 1, []bool{false}},
|
||||
{"mid split → cached prefix + dynamic tail", 2, 2, []bool{true, false}},
|
||||
{"boundary == len → whole thing cached", 3, 1, []bool{true}},
|
||||
{"boundary > len → whole thing cached", 5, 1, []bool{true}},
|
||||
}
|
||||
for _, c := range cases {
|
||||
t.Run(c.name, func(t *testing.T) {
|
||||
blocks := buildAnthropicSystem(CompletionRequest{System: sys, DynamicBoundary: c.boundary})
|
||||
if len(blocks) != c.wantBlocks {
|
||||
t.Fatalf("blocks=%d want %d", len(blocks), c.wantBlocks)
|
||||
}
|
||||
for i, wantCached := range c.wantCached {
|
||||
gotCached := blocks[i].CacheControl != nil
|
||||
if gotCached != wantCached {
|
||||
t.Fatalf("block %d cached=%v want %v", i, gotCached, wantCached)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
package llm
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Compact boundaries make context compaction non-destructive: the full
|
||||
// conversation is retained in the message array, a boundary marker is inserted,
|
||||
// and only the messages from the last boundary onward are sent to the model
|
||||
// (the boundary marker itself is never sent — it only marks position).
|
||||
|
||||
// BlockCompactBoundary marks a compaction point. A message consisting solely of
|
||||
// this block is a boundary marker; the summary that follows is a normal message.
|
||||
const BlockCompactBoundary BlockType = "compact_boundary"
|
||||
|
||||
// BoundaryMeta is the structured payload of a compact boundary. It records
|
||||
// why compaction ran and what it condensed, for diagnostics, analytics, and
|
||||
// transcript replay.
|
||||
type BoundaryMeta struct {
|
||||
// Trigger is what caused compaction: "auto" (proactive threshold),
|
||||
// "reactive" (recovery from a prompt-too-long error), or "manual".
|
||||
Trigger string `json:"trigger,omitempty"`
|
||||
// PreTokens is the token count just before compaction.
|
||||
PreTokens int `json:"pre_tokens"`
|
||||
// MessagesSummarized is how many messages were condensed into the summary.
|
||||
MessagesSummarized int `json:"messages_summarized,omitempty"`
|
||||
// ActiveSkills names the invoked skills re-injected verbatim after this
|
||||
// boundary (diagnostics; the instructions themselves ride in the messages).
|
||||
ActiveSkills []string `json:"active_skills,omitempty"`
|
||||
}
|
||||
|
||||
// BoundaryMessage builds a compact-boundary marker carrying its metadata. It
|
||||
// carries no model-visible text (the marker is stripped before the API call).
|
||||
func BoundaryMessage(meta BoundaryMeta) Message {
|
||||
payload, _ := json.Marshal(meta)
|
||||
return Message{Role: RoleUser, Content: []ContentBlock{{
|
||||
Type: BlockCompactBoundary,
|
||||
Input: payload,
|
||||
}}}
|
||||
}
|
||||
|
||||
// ParseBoundaryMeta extracts the metadata from a boundary marker. It accepts
|
||||
// both the structured object form and the legacy bare-integer form (which
|
||||
// encoded only the pre-compaction token count).
|
||||
func ParseBoundaryMeta(m Message) (BoundaryMeta, bool) {
|
||||
if !IsBoundaryMarker(m) {
|
||||
return BoundaryMeta{}, false
|
||||
}
|
||||
raw := m.Content[0].Input
|
||||
var meta BoundaryMeta
|
||||
if err := json.Unmarshal(raw, &meta); err == nil {
|
||||
return meta, true
|
||||
}
|
||||
var pre int
|
||||
if err := json.Unmarshal(raw, &pre); err == nil {
|
||||
return BoundaryMeta{PreTokens: pre}, true
|
||||
}
|
||||
return BoundaryMeta{}, true
|
||||
}
|
||||
|
||||
// IsBoundaryMarker reports whether m is a compact-boundary marker.
|
||||
func IsBoundaryMarker(m Message) bool {
|
||||
return len(m.Content) == 1 && m.Content[0].Type == BlockCompactBoundary
|
||||
}
|
||||
|
||||
// LastBoundaryIndex returns the index of the last boundary marker, or -1.
|
||||
func LastBoundaryIndex(msgs []Message) int {
|
||||
for i := len(msgs) - 1; i >= 0; i-- {
|
||||
if IsBoundaryMarker(msgs[i]) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
// MessagesAfterBoundary returns the slice from the last boundary marker onward
|
||||
// (boundary marker included), or all messages if there is no boundary. This is
|
||||
// the post-compaction "working set"; everything before it is retained history.
|
||||
func MessagesAfterBoundary(msgs []Message) []Message {
|
||||
i := LastBoundaryIndex(msgs)
|
||||
if i < 0 {
|
||||
return msgs
|
||||
}
|
||||
return msgs[i:]
|
||||
}
|
||||
|
||||
// MessagesForAPI returns the messages actually sent to the model: the working
|
||||
// set after the last boundary, with boundary markers stripped (they are
|
||||
// position markers, not content) and any tool block left unpaired by the
|
||||
// boundary cut dropped (PairToolBlocks). The summary that follows a boundary is
|
||||
// kept.
|
||||
func MessagesForAPI(msgs []Message) []Message {
|
||||
working := MessagesAfterBoundary(msgs)
|
||||
out := make([]Message, 0, len(working))
|
||||
for _, m := range working {
|
||||
if IsBoundaryMarker(m) {
|
||||
continue
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return PairToolBlocks(out)
|
||||
}
|
||||
|
||||
// PairToolBlocks drops tool blocks left unpaired within msgs: a tool_result
|
||||
// whose tool_use is absent, or a tool_use whose tool_result is absent. The
|
||||
// working set is sliced at the last boundary, and that cut can fall inside a
|
||||
// tool exchange — leaving the post-boundary view starting with a tool_result
|
||||
// whose tool_use was summarized away (or ending with a tool_use whose result
|
||||
// is beyond the tail). Sent verbatim, the first makes the gateway 400 ("a
|
||||
// message with role 'tool' must be a response to a preceding message with
|
||||
// 'tool_calls'"). Well-formed histories have no unpaired blocks and pass through
|
||||
// unchanged; this also repairs a resumed transcript that already baked in an
|
||||
// orphan from an earlier compaction. Drops (not synthesizes), matching the
|
||||
// summarizer's pairForReplay.
|
||||
func PairToolBlocks(msgs []Message) []Message {
|
||||
useIDs := make(map[string]bool)
|
||||
resIDs := make(map[string]bool)
|
||||
for _, m := range msgs {
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case BlockToolUse:
|
||||
useIDs[b.ID] = true
|
||||
case BlockToolResult:
|
||||
resIDs[b.ToolUseID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]Message, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
kept := make([]ContentBlock, 0, len(m.Content))
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case BlockToolUse:
|
||||
if !resIDs[b.ID] {
|
||||
continue
|
||||
}
|
||||
case BlockToolResult:
|
||||
if !useIDs[b.ToolUseID] {
|
||||
continue
|
||||
}
|
||||
}
|
||||
kept = append(kept, b)
|
||||
}
|
||||
if len(kept) > 0 {
|
||||
out = append(out, Message{Role: m.Role, Content: kept})
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
package llm
|
||||
|
||||
import "testing"
|
||||
|
||||
func toolUseMsg(id string) Message {
|
||||
return Message{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockToolUse, ID: id, Name: "Bash", Input: []byte(`{}`)},
|
||||
}}
|
||||
}
|
||||
|
||||
func toolResultMsg(id string) Message {
|
||||
return Message{Role: RoleUser, Content: []ContentBlock{
|
||||
{Type: BlockToolResult, ToolUseID: id, Content: []ContentBlock{TextBlock("ok")}},
|
||||
}}
|
||||
}
|
||||
|
||||
// The reported failure: compaction slices the working set right before a
|
||||
// tool_result whose tool_use was summarized away. MessagesForAPI must not emit
|
||||
// that orphan — it is what makes the gateway 400.
|
||||
func TestMessagesForAPIDropsOrphanToolResult(t *testing.T) {
|
||||
msgs := []Message{
|
||||
toolUseMsg("t1"), // pre-boundary: summarized away
|
||||
BoundaryMessage(BoundaryMeta{Trigger: "auto"}),
|
||||
UserText("Summary: ..."),
|
||||
toolResultMsg("t1"), // orphan: its tool_use is before the boundary
|
||||
UserText("continue"),
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
for _, m := range out {
|
||||
for _, b := range m.Content {
|
||||
if b.Type == BlockToolResult {
|
||||
t.Fatalf("orphan tool_result survived: %+v", out)
|
||||
}
|
||||
}
|
||||
}
|
||||
// The empty message left by dropping the orphan block is removed, so the view
|
||||
// is [summary, continue].
|
||||
if len(out) != 2 || out[0].Content[0].Text != "Summary: ..." || out[1].Content[0].Text != "continue" {
|
||||
t.Fatalf("view=%+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A dangling tool_use (result beyond the view) is dropped symmetrically.
|
||||
func TestMessagesForAPIDropsDanglingToolUse(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
toolUseMsg("t9"), // no matching tool_result anywhere in the view
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) != 1 || out[0].Content[0].Text != "hi" {
|
||||
t.Fatalf("view=%+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// A well-formed, intact tool exchange must pass through untouched.
|
||||
func TestMessagesForAPIKeepsPairedExchange(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("go"),
|
||||
toolUseMsg("t1"),
|
||||
toolResultMsg("t1"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{TextBlock("done")}},
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) != 4 {
|
||||
t.Fatalf("want 4 messages unchanged, got %d: %+v", len(out), out)
|
||||
}
|
||||
if out[1].Content[0].Type != BlockToolUse || out[2].Content[0].Type != BlockToolResult {
|
||||
t.Fatalf("paired exchange altered: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// One user message can carry several tool_results (parallel tools). If some are
|
||||
// orphaned and some are not, the valid ones survive and the message is kept.
|
||||
func TestMessagesForAPIMixedToolResultsInOneMessage(t *testing.T) {
|
||||
msgs := []Message{
|
||||
toolUseMsg("keep"), // in-view tool_use for the valid result
|
||||
{Role: RoleUser, Content: []ContentBlock{
|
||||
{Type: BlockToolResult, ToolUseID: "orphan", Content: []ContentBlock{TextBlock("x")}},
|
||||
{Type: BlockToolResult, ToolUseID: "keep", Content: []ContentBlock{TextBlock("y")}},
|
||||
}},
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
// [assistant tool_use "keep", user with only the "keep" result]
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("want 2 messages, got %d: %+v", len(out), out)
|
||||
}
|
||||
last := out[1].Content
|
||||
if len(last) != 1 || last[0].ToolUseID != "keep" {
|
||||
t.Fatalf("valid result not kept / orphan not dropped: %+v", last)
|
||||
}
|
||||
}
|
||||
|
||||
// One assistant message can carry several tool_use blocks (parallel calls). A
|
||||
// block whose result is missing is dropped; the one with a result is kept.
|
||||
func TestMessagesForAPIMixedToolUsesInOneMessage(t *testing.T) {
|
||||
msgs := []Message{
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockToolUse, ID: "done", Name: "Bash", Input: []byte(`{}`)},
|
||||
{Type: BlockToolUse, ID: "dangling", Name: "Bash", Input: []byte(`{}`)},
|
||||
}},
|
||||
toolResultMsg("done"),
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) != 2 {
|
||||
t.Fatalf("want 2 messages, got %d: %+v", len(out), out)
|
||||
}
|
||||
uses := out[0].Content
|
||||
if len(uses) != 1 || uses[0].ID != "done" {
|
||||
t.Fatalf("dangling tool_use not dropped / paired one not kept: %+v", uses)
|
||||
}
|
||||
}
|
||||
|
||||
// Only the LAST boundary defines the working set; an orphan after it is dropped.
|
||||
func TestMessagesForAPIMultipleBoundaries(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("old"),
|
||||
BoundaryMessage(BoundaryMeta{Trigger: "auto"}),
|
||||
toolUseMsg("t1"),
|
||||
BoundaryMessage(BoundaryMeta{Trigger: "auto"}),
|
||||
UserText("Summary 2"),
|
||||
toolResultMsg("t1"), // its tool_use is before the LAST boundary → orphan
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) != 1 || out[0].Content[0].Text != "Summary 2" {
|
||||
t.Fatalf("view=%+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// No tools, no boundary: the pass is a no-op and returns the conversation as-is.
|
||||
func TestMessagesForAPINoToolsNoOp(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{TextBlock("hello")}},
|
||||
UserText("bye"),
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) != 3 || out[0].Content[0].Text != "hi" || out[2].Content[0].Text != "bye" {
|
||||
t.Fatalf("view changed: %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// After compaction the view begins with the summary (a user message), so
|
||||
// dropping the orphaned tool_result that follows it never leaves the view
|
||||
// starting with an assistant turn.
|
||||
func TestMessagesForAPIStaysUserFirstAfterDrop(t *testing.T) {
|
||||
msgs := []Message{
|
||||
toolUseMsg("t1"),
|
||||
BoundaryMessage(BoundaryMeta{Trigger: "auto"}),
|
||||
UserText("Summary"),
|
||||
toolResultMsg("t1"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{TextBlock("next")}},
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
if len(out) == 0 || out[0].Role != RoleUser {
|
||||
t.Fatalf("view must start with a user message, got %+v", out)
|
||||
}
|
||||
}
|
||||
|
||||
// The pair kept together in the tail (both after the boundary) stays intact —
|
||||
// only the boundary-straddling one is dropped.
|
||||
func TestMessagesForAPIKeepsInTailPair(t *testing.T) {
|
||||
msgs := []Message{
|
||||
toolUseMsg("old"), // pre-boundary
|
||||
BoundaryMessage(BoundaryMeta{Trigger: "auto"}),
|
||||
UserText("Summary"),
|
||||
toolResultMsg("old"), // orphan → dropped
|
||||
toolUseMsg("new"), // in-tail pair → kept
|
||||
toolResultMsg("new"),
|
||||
}
|
||||
out := MessagesForAPI(msgs)
|
||||
var uses, results int
|
||||
for _, m := range out {
|
||||
for _, b := range m.Content {
|
||||
if b.Type == BlockToolUse {
|
||||
uses++
|
||||
}
|
||||
if b.Type == BlockToolResult {
|
||||
results++
|
||||
}
|
||||
}
|
||||
}
|
||||
if uses != 1 || results != 1 {
|
||||
t.Fatalf("want the in-tail pair kept and the orphan dropped, got uses=%d results=%d: %+v", uses, results, out)
|
||||
}
|
||||
}
|
||||
Vendored
+316
@@ -0,0 +1,316 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func collect(t *testing.T, p Provider, req CompletionRequest) Message {
|
||||
t.Helper()
|
||||
acc := NewAccumulator()
|
||||
for ev, err := range p.Stream(context.Background(), req) {
|
||||
if err != nil {
|
||||
t.Fatalf("stream error: %v", err)
|
||||
}
|
||||
acc.Add(ev)
|
||||
}
|
||||
return acc.Message()
|
||||
}
|
||||
|
||||
func TestAccumulator(t *testing.T) {
|
||||
acc := NewAccumulator()
|
||||
for _, ev := range []StreamEvent{
|
||||
{Type: SETextDelta, Text: "Hel"},
|
||||
{Type: SETextDelta, Text: "lo"},
|
||||
{Type: SEToolUseStart, ToolID: "t1", ToolName: "Bash"},
|
||||
{Type: SEToolInputJSON, Text: `{"command":`},
|
||||
{Type: SEToolInputJSON, Text: `"ls"}`},
|
||||
{Type: SEMessageStop},
|
||||
} {
|
||||
acc.Add(ev)
|
||||
}
|
||||
msg := acc.Message()
|
||||
if msg.Text() != "Hello" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
uses := msg.ToolUses()
|
||||
if len(uses) != 1 || uses[0].Name != "Bash" || string(uses[0].Input) != `{"command":"ls"}` {
|
||||
t.Fatalf("tooluse=%+v", uses)
|
||||
}
|
||||
}
|
||||
|
||||
func sse(lines ...string) string {
|
||||
var b strings.Builder
|
||||
for _, l := range lines {
|
||||
b.WriteString(l)
|
||||
b.WriteString("\n")
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func TestAnthropicAdapter(t *testing.T) {
|
||||
body := sse(
|
||||
`event: content_block_start`,
|
||||
`data: {"type":"content_block_start","index":0,"content_block":{"type":"text"}}`,
|
||||
``,
|
||||
`data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Hi "}}`,
|
||||
``,
|
||||
`data: {"type":"content_block_start","index":1,"content_block":{"type":"tool_use","id":"tu1","name":"Read"}}`,
|
||||
``,
|
||||
`data: {"type":"content_block_delta","index":1,"delta":{"type":"input_json_delta","partial_json":"{\"file_path\":\"a\"}"}}`,
|
||||
``,
|
||||
`data: {"type":"message_delta","delta":{"stop_reason":"tool_use"},"usage":{"output_tokens":9}}`,
|
||||
``,
|
||||
`data: {"type":"message_stop"}`,
|
||||
``,
|
||||
)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/messages" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatAnthropic, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if msg.Text() != "Hi " {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].Name != "Read" || string(u[0].Input) != `{"file_path":"a"}` {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
// captureBody runs one request against a stub server and returns the raw request
|
||||
// body the provider sent, so we can assert request-shaping (thinking/effort).
|
||||
func captureBody(t *testing.T, cfg Config, stubSSE string) map[string]any {
|
||||
t.Helper()
|
||||
var raw []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ = io.ReadAll(r.Body)
|
||||
w.Write([]byte(stubSSE))
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg.BaseURL, cfg.APIKey, cfg.Model = srv.URL, "k", "m"
|
||||
p, err := NewProvider(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("NewProvider: %v", err)
|
||||
}
|
||||
collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatalf("unmarshal request body: %v\n%s", err, raw)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
func TestThinkingParamsAnthropic(t *testing.T) {
|
||||
stub := sse(`data: {"type":"message_stop"}`, ``)
|
||||
// set → fields present
|
||||
m := captureBody(t, Config{Format: FormatAnthropic, ThinkingType: "enabled", ReasoningEffort: "high"}, stub)
|
||||
if th, _ := m["thinking"].(map[string]any); th["type"] != "enabled" {
|
||||
t.Fatalf("thinking=%v", m["thinking"])
|
||||
}
|
||||
if oc, _ := m["output_config"].(map[string]any); oc["effort"] != "high" {
|
||||
t.Fatalf("output_config=%v", m["output_config"])
|
||||
}
|
||||
// unset → both omitted
|
||||
m = captureBody(t, Config{Format: FormatAnthropic}, stub)
|
||||
if _, ok := m["thinking"]; ok {
|
||||
t.Fatalf("thinking should be omitted: %v", m["thinking"])
|
||||
}
|
||||
if _, ok := m["output_config"]; ok {
|
||||
t.Fatalf("output_config should be omitted: %v", m["output_config"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestThinkingParamsOpenAI(t *testing.T) {
|
||||
// Non-empty stub so the empty-response retry doesn't fire (this test only
|
||||
// inspects the request body).
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
// set → fields present
|
||||
m := captureBody(t, Config{Format: FormatOpenAI, ThinkingType: "disabled", ReasoningEffort: "max"}, stub)
|
||||
if th, _ := m["thinking"].(map[string]any); th["type"] != "disabled" {
|
||||
t.Fatalf("thinking=%v", m["thinking"])
|
||||
}
|
||||
if m["reasoning_effort"] != "max" {
|
||||
t.Fatalf("reasoning_effort=%v", m["reasoning_effort"])
|
||||
}
|
||||
// unset → both omitted
|
||||
m = captureBody(t, Config{Format: FormatOpenAI}, stub)
|
||||
if _, ok := m["thinking"]; ok {
|
||||
t.Fatalf("thinking should be omitted: %v", m["thinking"])
|
||||
}
|
||||
if _, ok := m["reasoning_effort"]; ok {
|
||||
t.Fatalf("reasoning_effort should be omitted: %v", m["reasoning_effort"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIAdapter(t *testing.T) {
|
||||
body := sse(
|
||||
`data: {"choices":[{"delta":{"content":"Hi "},"finish_reason":null}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"id":"c1","type":"function","function":{"name":"Read","arguments":""}}]}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"file_path\":\"a\"}"}}]}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"delta":{},"finish_reason":"tool_calls"}]}`,
|
||||
``,
|
||||
`data: {"choices":[],"usage":{"prompt_tokens":3,"completion_tokens":7}}`,
|
||||
``,
|
||||
`data: [DONE]`,
|
||||
``,
|
||||
)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/chat/completions" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if msg.Text() != "Hi " {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].Name != "Read" || string(u[0].Input) != `{"file_path":"a"}` {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToOpenAIMessagesThreadsToolResults(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockText, Text: "calling"},
|
||||
{Type: BlockToolUse, ID: "c1", Name: "Bash", Input: []byte(`{"command":"ls"}`)},
|
||||
}},
|
||||
{Role: RoleUser, Content: []ContentBlock{ToolResultText("c1", "file.txt", false)}},
|
||||
}
|
||||
oa := toOpenAIMessages("sys", msgs)
|
||||
if len(oa) != 4 || oa[0].Role != "system" || oa[2].Role != "assistant" || oa[3].Role != "tool" {
|
||||
t.Fatalf("roles=%+v", oa)
|
||||
}
|
||||
if oa[2].ToolCalls[0].ID != "c1" || oa[3].ToolCallID != "c1" {
|
||||
t.Fatalf("pairing wrong: %+v", oa)
|
||||
}
|
||||
}
|
||||
|
||||
// A thinking-only assistant turn is kept (not dropped) with a placeholder
|
||||
// content and its reasoning_content passed back: DeepSeek-style thinking mode
|
||||
// requires the reasoning to be echoed, and keeping the turn preserves
|
||||
// user/assistant alternation for gateways that enforce it. A bare
|
||||
// {"role":"assistant"} would 400 with "content or tool_calls must be set".
|
||||
func TestToOpenAIMessagesKeepsThinkingOnlyAssistant(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockThinking, Thinking: "pondering, no answer emitted"},
|
||||
}},
|
||||
UserText("still there?"),
|
||||
}
|
||||
oa := toOpenAIMessages("", msgs)
|
||||
// All three turns survive (the assistant is kept, not dropped).
|
||||
if len(oa) != 3 || oa[1].Role != "assistant" {
|
||||
t.Fatalf("want 3 messages with assistant kept, got %d: %+v", len(oa), oa)
|
||||
}
|
||||
if oa[1].Content == "" && len(oa[1].ToolCalls) == 0 {
|
||||
t.Fatalf("assistant must carry content or tool_calls: %+v", oa[1])
|
||||
}
|
||||
// The reasoning must be passed back verbatim (from b.Thinking, not b.Text).
|
||||
if oa[1].ReasoningContent != "pondering, no answer emitted" {
|
||||
t.Fatalf("reasoning_content not passed back: %+v", oa[1])
|
||||
}
|
||||
}
|
||||
|
||||
// A multi-turn assistant turn with BOTH text and thinking must serialize the
|
||||
// text as content and the thinking as reasoning_content (the DeepSeek-thinking
|
||||
// multi-turn 400 this fixes).
|
||||
func TestToOpenAIMessagesPassesReasoningWithText(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("q"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockThinking, Thinking: "reasoning trace"},
|
||||
{Type: BlockText, Text: "the answer"},
|
||||
}},
|
||||
UserText("next"),
|
||||
}
|
||||
oa := toOpenAIMessages("", msgs)
|
||||
if oa[1].Role != "assistant" || oa[1].Content != "the answer" {
|
||||
t.Fatalf("content wrong: %+v", oa[1])
|
||||
}
|
||||
if oa[1].ReasoningContent != "reasoning trace" {
|
||||
t.Fatalf("reasoning_content wrong: %+v", oa[1])
|
||||
}
|
||||
}
|
||||
|
||||
// filterThinkingBlocks must drop messages left with no content — Anthropic
|
||||
// rejects an empty content array. Covers both a thinking-only turn collapsing
|
||||
// once thinking is stripped and a genuinely empty (truncated) turn.
|
||||
func TestFilterThinkingBlocksDropsEmpty(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{{Type: BlockThinking, Thinking: "only thinking"}}},
|
||||
{Role: RoleAssistant, Content: []ContentBlock{}}, // empty/truncated turn
|
||||
UserText("bye"),
|
||||
}
|
||||
|
||||
// Thinking disabled: thinking-only turn collapses to empty and drops; the
|
||||
// already-empty turn drops too. Two user turns remain.
|
||||
got := filterThinkingBlocks(msgs, false)
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("thinking-disabled: want 2, got %d: %+v", len(got), got)
|
||||
}
|
||||
for _, m := range got {
|
||||
if len(m.Content) == 0 {
|
||||
t.Fatalf("thinking-disabled: emitted empty message: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Thinking enabled: the thinking-only turn is kept (valid, must be
|
||||
// replayed); only the genuinely empty turn drops. Three messages remain.
|
||||
got = filterThinkingBlocks(msgs, true)
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("thinking-enabled: want 3, got %d: %+v", len(got), got)
|
||||
}
|
||||
for _, m := range got {
|
||||
if len(m.Content) == 0 {
|
||||
t.Fatalf("thinking-enabled: emitted empty message: %+v", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Dropping an empty assistant that sat between a tool result and a resume nudge
|
||||
// leaves two adjacent user turns; mergeAdjacentSameRole must coalesce them so
|
||||
// the sequence still alternates (Anthropic rejects non-alternating roles).
|
||||
func TestMergeAdjacentSameRoleAfterDrop(t *testing.T) {
|
||||
history := []Message{
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockText, Text: "calling"},
|
||||
{Type: BlockToolUse, ID: "c1", Name: "Bash", Input: []byte(`{"command":"ls"}`)},
|
||||
}},
|
||||
{Role: RoleUser, Content: []ContentBlock{ToolResultText("c1", "file.txt", false)}},
|
||||
{Role: RoleAssistant, Content: []ContentBlock{}}, // empty/truncated turn → dropped
|
||||
UserText("continue where you left off"), // resume nudge
|
||||
}
|
||||
|
||||
merged := mergeAdjacentSameRole(filterThinkingBlocks(history, false))
|
||||
|
||||
// assistant(tool_use) → user(tool_result + nudge, coalesced). Alternation holds.
|
||||
if len(merged) != 2 {
|
||||
t.Fatalf("want 2 messages, got %d: %+v", len(merged), merged)
|
||||
}
|
||||
for i := 1; i < len(merged); i++ {
|
||||
if merged[i].Role == merged[i-1].Role {
|
||||
t.Fatalf("adjacent same-role at %d: %+v", i, merged)
|
||||
}
|
||||
}
|
||||
if merged[1].Role != RoleUser || len(merged[1].Content) != 2 {
|
||||
t.Fatalf("user turns not coalesced: %+v", merged[1])
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestOpenAICompleteNonStreaming verifies the real non-streaming path: the wire
|
||||
// carries stream:false (and no stream_options), and a single JSON response is
|
||||
// parsed into text + thinking + tool_use with usage and stop reason.
|
||||
func TestOpenAICompleteNonStreaming(t *testing.T) {
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/chat/completions" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.Header().Set("content-type", "application/json")
|
||||
w.Write([]byte(`{"choices":[{"message":{"content":"Hello","reasoning_content":"let me think","tool_calls":[{"id":"c1","type":"function","function":{"name":"Read","arguments":"{\"file_path\":\"a\"}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":12,"completion_tokens":8,"prompt_tokens_details":{"cached_tokens":4}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg, stop, usage, err := p.Complete(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if err != nil {
|
||||
t.Fatalf("Complete err: %v", err)
|
||||
}
|
||||
// Wire must be non-streaming.
|
||||
if gotBody["stream"] != false {
|
||||
t.Fatalf("stream=%v, want false", gotBody["stream"])
|
||||
}
|
||||
if _, ok := gotBody["stream_options"]; ok {
|
||||
t.Fatal("stream_options must be omitted on a non-streaming request")
|
||||
}
|
||||
if msg.Text() != "Hello" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
// reasoning_content → thinking block.
|
||||
var thinking string
|
||||
for _, b := range msg.Content {
|
||||
if b.Type == BlockThinking {
|
||||
thinking = b.Thinking
|
||||
}
|
||||
}
|
||||
if thinking != "let me think" {
|
||||
t.Fatalf("thinking=%q", thinking)
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].Name != "Read" || string(u[0].Input) != `{"file_path":"a"}` {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
if stop != "tool_use" { // mapped from finish_reason "tool_calls"
|
||||
t.Fatalf("stop=%q", stop)
|
||||
}
|
||||
if usage.InputTokens != 12 || usage.OutputTokens != 8 || usage.CacheReadTokens != 4 {
|
||||
t.Fatalf("usage=%+v", usage)
|
||||
}
|
||||
}
|
||||
|
||||
// A 200 response whose body is an error object must surface as an error, not an
|
||||
// empty completion — this is the failure mode that made flaky gateways look like
|
||||
// a silently "completed" empty turn on the streaming path.
|
||||
func TestOpenAICompleteErrorBody(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
w.Write([]byte(`{"error":{"message":"content filtered","type":"invalid_request_error"}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
_, _, _, err := p.Complete(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if err == nil || !strings.Contains(err.Error(), "content filtered") {
|
||||
t.Fatalf("want error surfacing the body, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAnthropicCompleteNonStreaming verifies the Messages API non-streaming path.
|
||||
func TestAnthropicCompleteNonStreaming(t *testing.T) {
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/v1/messages" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.Header().Set("content-type", "application/json")
|
||||
w.Write([]byte(`{"type":"message","content":[{"type":"thinking","thinking":"hmm","signature":"sig"},{"type":"text","text":"Hi"},{"type":"tool_use","id":"t1","name":"Bash","input":{"command":"ls"}}],"stop_reason":"tool_use","usage":{"input_tokens":10,"output_tokens":5,"cache_read_input_tokens":2}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p, _ := NewProvider(Config{Format: FormatAnthropic, BaseURL: srv.URL, APIKey: "k", Model: "m", APIVersion: "2023-06-01"})
|
||||
msg, stop, usage, err := p.Complete(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if err != nil {
|
||||
t.Fatalf("Complete err: %v", err)
|
||||
}
|
||||
if gotBody["stream"] != false {
|
||||
t.Fatalf("stream=%v, want false", gotBody["stream"])
|
||||
}
|
||||
if msg.Text() != "Hi" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].Name != "Bash" || string(u[0].Input) != `{"command":"ls"}` {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
if stop != "tool_use" {
|
||||
t.Fatalf("stop=%q", stop)
|
||||
}
|
||||
// InputTokens includes cache-read (OpenAI-style total input semantics).
|
||||
if usage.InputTokens != 12 || usage.OutputTokens != 5 || usage.CacheReadTokens != 2 {
|
||||
t.Fatalf("usage=%+v", usage)
|
||||
}
|
||||
}
|
||||
Vendored
+578
@@ -0,0 +1,578 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type openaiProvider struct{ cfg Config }
|
||||
|
||||
type oaMessage struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content,omitempty"`
|
||||
ReasoningContent string `json:"reasoning_content,omitempty"`
|
||||
ToolCalls []oaToolCall `json:"tool_calls,omitempty"`
|
||||
ToolCallID string `json:"tool_call_id,omitempty"`
|
||||
}
|
||||
|
||||
type oaToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"`
|
||||
Index int `json:"index,omitempty"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
type oaTool struct {
|
||||
Type string `json:"type"`
|
||||
Function struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]any `json:"parameters"`
|
||||
} `json:"function"`
|
||||
}
|
||||
|
||||
type oaThinking struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
|
||||
type oaReq struct {
|
||||
Model string `json:"model"`
|
||||
Messages []oaMessage `json:"messages"`
|
||||
Tools []oaTool `json:"tools,omitempty"`
|
||||
// MaxTokens and MaxCompletionTokens are mutually exclusive: buildBody fills
|
||||
// exactly one of them per Config.MaxTokensField, and omitempty drops the
|
||||
// other. Sending both would make OpenAI reject the request.
|
||||
MaxTokens int `json:"max_tokens,omitempty"`
|
||||
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
Stop []string `json:"stop,omitempty"`
|
||||
Thinking *oaThinking `json:"thinking,omitempty"`
|
||||
ReasoningEffort string `json:"reasoning_effort,omitempty"`
|
||||
Stream bool `json:"stream"`
|
||||
StreamOptions *oaStreamOpts `json:"stream_options,omitempty"`
|
||||
}
|
||||
|
||||
type oaStreamOpts struct {
|
||||
IncludeUsage bool `json:"include_usage"`
|
||||
}
|
||||
|
||||
// toOpenAIMessages flattens the unified model into OpenAI's role-based format:
|
||||
// assistant tool_use → tool_calls; user-embedded tool_result → standalone
|
||||
// role:tool messages; system prompt → leading system message (FR-03.6).
|
||||
func toOpenAIMessages(system string, msgs []Message) []oaMessage {
|
||||
out := make([]oaMessage, 0, len(msgs)+1)
|
||||
if system != "" {
|
||||
out = append(out, oaMessage{Role: "system", Content: system})
|
||||
}
|
||||
for _, m := range msgs {
|
||||
switch m.Role {
|
||||
case RoleAssistant:
|
||||
om := oaMessage{Role: "assistant"}
|
||||
var text strings.Builder
|
||||
var reasoning strings.Builder
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case BlockText:
|
||||
text.WriteString(b.Text)
|
||||
case BlockThinking:
|
||||
// DeepSeek-style thinking mode requires the previous turn's
|
||||
// reasoning_content to be passed back verbatim; dropping it
|
||||
// makes the API reject the request with a 400. Thinking text
|
||||
// lives in b.Thinking (not b.Text) — see ContentBlock.
|
||||
reasoning.WriteString(b.Thinking)
|
||||
case BlockToolUse:
|
||||
tc := oaToolCall{ID: b.ID, Type: "function"}
|
||||
tc.Function.Name = b.Name
|
||||
tc.Function.Arguments = string(b.Input)
|
||||
if tc.Function.Arguments == "" {
|
||||
tc.Function.Arguments = "{}"
|
||||
}
|
||||
om.ToolCalls = append(om.ToolCalls, tc)
|
||||
}
|
||||
}
|
||||
om.Content = text.String()
|
||||
if s := reasoning.String(); s != "" {
|
||||
om.ReasoningContent = s
|
||||
}
|
||||
// OpenAI requires every assistant message to carry content or
|
||||
// tool_calls; Content's omitempty would otherwise serialize a
|
||||
// content-less turn to a bare {"role":"assistant"} and the API 400s
|
||||
// with "content or tool_calls must be set". Rather than drop such a
|
||||
// turn, keep it with a minimal placeholder: a thinking-only turn must
|
||||
// stay so its reasoning_content is passed back (DeepSeek-style
|
||||
// thinking mode requires it), and keeping the assistant turn also
|
||||
// preserves user/assistant alternation for gateways that enforce it
|
||||
// (dropping it would leave two adjacent user messages).
|
||||
if om.Content == "" && len(om.ToolCalls) == 0 {
|
||||
om.Content = "…"
|
||||
}
|
||||
out = append(out, om)
|
||||
case RoleUser:
|
||||
var text strings.Builder
|
||||
var toolMsgs []oaMessage
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case BlockText:
|
||||
text.WriteString(b.Text)
|
||||
case BlockToolResult:
|
||||
toolMsgs = append(toolMsgs, oaMessage{Role: "tool", ToolCallID: b.ToolUseID, Content: flattenText(b.Content)})
|
||||
}
|
||||
}
|
||||
out = append(out, toolMsgs...)
|
||||
if s := text.String(); s != "" {
|
||||
out = append(out, oaMessage{Role: "user", Content: s})
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// reasoningElidedPlaceholder stands in for a thinking turn's reasoning_content
|
||||
// when it was lost upstream (context compaction) yet the turn still replays
|
||||
// tool_calls. Sending a minimal non-empty value keeps the request valid for
|
||||
// providers that only require the field to be present; the real content is
|
||||
// preserved by the compaction layer, so this path is a last resort.
|
||||
const reasoningElidedPlaceholder = "(reasoning elided by context compaction)"
|
||||
|
||||
// sanitizeOpenAIMessages enforces, at the provider boundary, the two structural
|
||||
// invariants OpenAI-compatible endpoints validate — regardless of what produced
|
||||
// req.Messages (noa compaction, the built-in compactor, or a host that assembled
|
||||
// them directly):
|
||||
//
|
||||
// - Every assistant tool_call is answered by a following role:tool message,
|
||||
// and every role:tool answers a tool_call still present. A half-pair in
|
||||
// either direction is a 400 ("tool_calls must be followed by tool messages"
|
||||
// / an unexpected tool message).
|
||||
// - In thinking mode, an assistant message replaying tool_calls carries
|
||||
// reasoning_content. If a gap slips through despite the upstream repair, a
|
||||
// minimal placeholder is sent rather than letting a strict provider reject
|
||||
// the bare tool_calls turn.
|
||||
//
|
||||
// It is a defensive backstop, not the primary repair: the fixes that keep the
|
||||
// real content whole upstream should mean the placeholder path never runs. The
|
||||
// input slice is mutated in place and also returned.
|
||||
func sanitizeOpenAIMessages(msgs []oaMessage, thinking bool) []oaMessage {
|
||||
// Which tool_call ids actually have a role:tool response.
|
||||
responded := map[string]bool{}
|
||||
for _, m := range msgs {
|
||||
if m.Role == "tool" && m.ToolCallID != "" {
|
||||
responded[m.ToolCallID] = true
|
||||
}
|
||||
}
|
||||
// Pass 1: drop unanswered tool_calls from each assistant message.
|
||||
for i := range msgs {
|
||||
if msgs[i].Role != "assistant" || len(msgs[i].ToolCalls) == 0 {
|
||||
continue
|
||||
}
|
||||
kept := make([]oaToolCall, 0, len(msgs[i].ToolCalls))
|
||||
for _, tc := range msgs[i].ToolCalls {
|
||||
if responded[tc.ID] {
|
||||
kept = append(kept, tc)
|
||||
}
|
||||
}
|
||||
msgs[i].ToolCalls = kept
|
||||
if thinking && len(kept) > 0 && msgs[i].ReasoningContent == "" {
|
||||
msgs[i].ReasoningContent = reasoningElidedPlaceholder
|
||||
}
|
||||
// An assistant message must carry content or tool_calls; a turn emptied by
|
||||
// the drop above would serialize to a bare {"role":"assistant"} and 400.
|
||||
if msgs[i].Content == "" && len(msgs[i].ToolCalls) == 0 {
|
||||
msgs[i].Content = "…"
|
||||
}
|
||||
}
|
||||
// Pass 2: drop role:tool messages whose call no longer survives.
|
||||
surviving := map[string]bool{}
|
||||
for _, m := range msgs {
|
||||
if m.Role == "assistant" {
|
||||
for _, tc := range m.ToolCalls {
|
||||
surviving[tc.ID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out := make([]oaMessage, 0, len(msgs))
|
||||
for _, m := range msgs {
|
||||
if m.Role == "tool" && m.ToolCallID != "" && !surviving[m.ToolCallID] {
|
||||
continue
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func flattenText(blocks []ContentBlock) string {
|
||||
var s strings.Builder
|
||||
for _, b := range blocks {
|
||||
if b.Type == BlockText {
|
||||
s.WriteString(b.Text)
|
||||
}
|
||||
}
|
||||
return s.String()
|
||||
}
|
||||
|
||||
func (p *openaiProvider) buildBody(req CompletionRequest, stream bool) ([]byte, error) {
|
||||
// A non-empty per-request override (req.Thinking) wins over Config.ThinkingType.
|
||||
thinkingType := p.cfg.ThinkingType
|
||||
if req.Thinking != "" {
|
||||
thinkingType = req.Thinking
|
||||
}
|
||||
// The request is in thinking mode when either a thinking type is set (a
|
||||
// `thinking` body field goes out) or a reasoning effort is configured — the
|
||||
// same providers that then demand reasoning_content be echoed back.
|
||||
thinking := thinkingType != "" || p.cfg.ReasoningEffort != ""
|
||||
|
||||
msgs := toOpenAIMessages(joinSystem(req.System), req.Messages)
|
||||
msgs = sanitizeOpenAIMessages(msgs, thinking)
|
||||
|
||||
body := oaReq{
|
||||
Model: p.cfg.Model,
|
||||
Messages: msgs,
|
||||
Temperature: req.Temperature,
|
||||
Stop: req.Stop,
|
||||
Stream: stream,
|
||||
}
|
||||
// The output cap goes into exactly one key. Reasoning models accept only
|
||||
// "max_completion_tokens"; everything else still takes "max_tokens", which
|
||||
// stays the default so existing configs are untouched.
|
||||
if p.cfg.MaxTokensField == MaxTokensFieldCompletion {
|
||||
body.MaxCompletionTokens = req.MaxTokens
|
||||
} else {
|
||||
body.MaxTokens = req.MaxTokens
|
||||
}
|
||||
// stream_options.include_usage is a streaming-only field; some gateways reject
|
||||
// it on a non-streaming request, so send it only when streaming.
|
||||
if stream {
|
||||
body.StreamOptions = &oaStreamOpts{IncludeUsage: true}
|
||||
}
|
||||
if thinkingType != "" {
|
||||
body.Thinking = &oaThinking{Type: thinkingType}
|
||||
}
|
||||
body.ReasoningEffort = p.cfg.ReasoningEffort // omitempty drops it when unset
|
||||
for _, t := range req.Tools {
|
||||
var ot oaTool
|
||||
ot.Type = "function"
|
||||
ot.Function.Name = t.Name
|
||||
ot.Function.Description = t.Description
|
||||
ot.Function.Parameters = t.InputSchema
|
||||
body.Tools = append(body.Tools, ot)
|
||||
}
|
||||
return json.Marshal(body)
|
||||
}
|
||||
|
||||
// emptyResponseRetries is the DEFAULT bound on how many times a completed-but-
|
||||
// empty response is re-requested before it is surfaced as-is (override per
|
||||
// Config with EmptyResponseRetries). Kept low and separate from the
|
||||
// network-level retries() knob: an empty-response retry re-sends the whole
|
||||
// prompt (expensive on large contexts), and the failure is effectively binary —
|
||||
// a transient parser/sampling glitch clears on the next attempt, a deterministic
|
||||
// stall never does — so a third+ attempt mostly burns tokens.
|
||||
const emptyResponseRetries = 2
|
||||
|
||||
// isEmptyResponseRetryable reports whether a completed response that produced no
|
||||
// content blocks should be retried. Only a normal stop qualifies: a max_tokens
|
||||
// truncation is the harness's to escalate (retrying would fight that), and any
|
||||
// stop that actually carried content never reaches this check.
|
||||
func isEmptyResponseRetryable(stopReason string) bool {
|
||||
return stopReason == "end_turn" || stopReason == ""
|
||||
}
|
||||
|
||||
func (p *openaiProvider) Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error] {
|
||||
return func(yield func(StreamEvent, error) bool) {
|
||||
body, err := p.buildBody(req, true)
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/chat/completions", body, func(r *http.Request) {
|
||||
r.Header.Set("content-type", "application/json")
|
||||
r.Header.Set("authorization", "Bearer "+p.cfg.APIKey)
|
||||
r.Header.Set("accept", "text/event-stream")
|
||||
}, "openai")
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
|
||||
// Consume one attempt's stream. State is fresh per attempt (a retry
|
||||
// re-reads from a new response). emitted tracks whether any content
|
||||
// event was yielded — a retry only happens when nothing was, so the
|
||||
// consumer never sees duplicated content across attempts.
|
||||
scan := newSSEScanner(resp.Body)
|
||||
started := map[int]bool{}
|
||||
var stopReason string
|
||||
var usage Usage
|
||||
emitted := false
|
||||
consumerStopped := false
|
||||
var streamErr error
|
||||
for {
|
||||
_, data, serr := scan.next()
|
||||
if serr == io.EOF {
|
||||
break
|
||||
}
|
||||
if serr != nil {
|
||||
streamErr = serr
|
||||
break
|
||||
}
|
||||
data = strings.TrimSpace(data)
|
||||
if data == "" {
|
||||
continue
|
||||
}
|
||||
if data == "[DONE]" {
|
||||
break
|
||||
}
|
||||
evs, sr, u, ok := parseOpenAIFrame(data, started)
|
||||
if sr != "" {
|
||||
stopReason = sr
|
||||
}
|
||||
if ok {
|
||||
usage = u
|
||||
}
|
||||
for _, ev := range evs {
|
||||
emitted = true
|
||||
if !yield(ev, nil) {
|
||||
consumerStopped = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if consumerStopped {
|
||||
break
|
||||
}
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
if consumerStopped {
|
||||
return
|
||||
}
|
||||
if streamErr != nil {
|
||||
yield(StreamEvent{}, streamErr)
|
||||
return
|
||||
}
|
||||
// Empty completion: re-request a few times before surfacing it. Safe
|
||||
// to retry because nothing was yielded downstream this attempt.
|
||||
if !emitted && isEmptyResponseRetryable(stopReason) && attempt < p.cfg.emptyRetries() {
|
||||
if !backoffSleep(ctx, p.cfg.emptyRetryDelay(attempt)) {
|
||||
yield(StreamEvent{}, ctx.Err())
|
||||
return
|
||||
}
|
||||
continue
|
||||
}
|
||||
if !yield(StreamEvent{Type: SEMessageDelta, StopReason: stopReason, Usage: usage}, nil) {
|
||||
return
|
||||
}
|
||||
yield(StreamEvent{Type: SEMessageStop}, nil)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Complete performs a real non-streaming completion: it sends stream:false and
|
||||
// parses the single JSON response body into a full assistant Message. It returns
|
||||
// the assembled message, the normalized stop reason, and token usage. A 200
|
||||
// response whose body is an error object (some gateways do this instead of a 4xx)
|
||||
// is surfaced as an error rather than an empty completion.
|
||||
func (p *openaiProvider) Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error) {
|
||||
body, err := p.buildBody(req, false)
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
for attempt := 0; ; attempt++ {
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/chat/completions", body, func(r *http.Request) {
|
||||
r.Header.Set("content-type", "application/json")
|
||||
r.Header.Set("authorization", "Bearer "+p.cfg.APIKey)
|
||||
r.Header.Set("accept", "application/json")
|
||||
}, "openai")
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
raw, rerr := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if rerr != nil {
|
||||
return Message{}, "", Usage{}, rerr
|
||||
}
|
||||
msg, stop, usage, perr := parseOpenAIResponse(raw)
|
||||
if perr != nil {
|
||||
return Message{}, "", Usage{}, perr
|
||||
}
|
||||
// Empty completion (no content blocks): re-request a few times before
|
||||
// returning it, mirroring the streaming path.
|
||||
if len(msg.Content) == 0 && isEmptyResponseRetryable(stop) && attempt < p.cfg.emptyRetries() {
|
||||
if !backoffSleep(ctx, p.cfg.emptyRetryDelay(attempt)) {
|
||||
return Message{}, "", Usage{}, ctx.Err()
|
||||
}
|
||||
continue
|
||||
}
|
||||
return msg, stop, usage, nil
|
||||
}
|
||||
}
|
||||
|
||||
// parseOpenAIResponse decodes a non-streaming Chat Completions response body into
|
||||
// the neutral Message model. reasoning_content/reasoning (a reasoning model's
|
||||
// thinking) is mapped to a thinking block; content to a text block; tool_calls to
|
||||
// tool_use blocks — the same shape the streaming path accumulates.
|
||||
func parseOpenAIResponse(raw []byte) (Message, string, Usage, error) {
|
||||
var r struct {
|
||||
Choices []struct {
|
||||
Message struct {
|
||||
Content string `json:"content"`
|
||||
ReasoningContent string `json:"reasoning_content"`
|
||||
Reasoning string `json:"reasoning"`
|
||||
ReasoningText string `json:"reasoning_text"`
|
||||
Refusal string `json:"refusal"`
|
||||
ToolCalls []oaToolCall `json:"tool_calls"`
|
||||
} `json:"message"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
Usage *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
PromptTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
} `json:"prompt_tokens_details"`
|
||||
} `json:"usage"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
Type string `json:"type"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return Message{}, "", Usage{}, fmt.Errorf("openai: decode response: %w (body: %s)", err, truncate(string(raw), 500))
|
||||
}
|
||||
if r.Error != nil {
|
||||
return Message{}, "", Usage{}, fmt.Errorf("openai: %s", r.Error.Message)
|
||||
}
|
||||
var usage Usage
|
||||
if r.Usage != nil {
|
||||
usage = Usage{
|
||||
InputTokens: r.Usage.PromptTokens,
|
||||
OutputTokens: r.Usage.CompletionTokens,
|
||||
CacheReadTokens: r.Usage.PromptTokensDetails.CachedTokens,
|
||||
}
|
||||
}
|
||||
if len(r.Choices) == 0 {
|
||||
return Message{}, "", usage, fmt.Errorf("openai: empty response (no choices; body: %s)", truncate(string(raw), 500))
|
||||
}
|
||||
ch := r.Choices[0]
|
||||
var blocks []ContentBlock
|
||||
if think := pickReasoning(ch.Message.ReasoningContent, ch.Message.Reasoning, ch.Message.ReasoningText); think != "" {
|
||||
blocks = append(blocks, ContentBlock{Type: BlockThinking, Thinking: think})
|
||||
}
|
||||
if ch.Message.Content != "" {
|
||||
blocks = append(blocks, TextBlock(ch.Message.Content))
|
||||
} else if ch.Message.Refusal != "" {
|
||||
// A refused turn carries content:null and the reason in `refusal`. Reading
|
||||
// only content would hand the caller an empty assistant turn — the model
|
||||
// did answer, it just declined.
|
||||
blocks = append(blocks, TextBlock(ch.Message.Refusal))
|
||||
}
|
||||
for _, tc := range ch.Message.ToolCalls {
|
||||
in := tc.Function.Arguments
|
||||
if strings.TrimSpace(in) == "" {
|
||||
in = "{}"
|
||||
}
|
||||
blocks = append(blocks, ContentBlock{Type: BlockToolUse, ID: tc.ID, Name: tc.Function.Name, Input: []byte(in)})
|
||||
}
|
||||
return Message{Role: RoleAssistant, Content: blocks}, mapOpenAIFinish(ch.FinishReason), usage, nil
|
||||
}
|
||||
|
||||
func truncate(s string, max int) string {
|
||||
if len(s) <= max {
|
||||
return s
|
||||
}
|
||||
return s[:max] + "…"
|
||||
}
|
||||
|
||||
// pickReasoning returns the thinking text a Chat Completions payload carries,
|
||||
// taking the first non-empty field in priority order. Gateways disagree on the
|
||||
// name: reasoning_content is the DeepSeek style; `reasoning` is what OpenRouter
|
||||
// and vLLM's reasoning parsers emit; `reasoning_text` shows up on some others.
|
||||
// Reading only one silently drops a whole turn of thinking — and when the model
|
||||
// puts everything there (an unclosed </think>), the turn decodes to an empty
|
||||
// message that looks like the model just said nothing. Trying them in order also
|
||||
// deduplicates: a gateway that echoes the same text in two fields (e.g. chutes.ai
|
||||
// sends reasoning_content AND reasoning) contributes it once, not twice.
|
||||
func pickReasoning(fields ...string) string {
|
||||
for _, f := range fields {
|
||||
if f != "" {
|
||||
return f
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func parseOpenAIFrame(data string, started map[int]bool) (evs []StreamEvent, stopReason string, usage Usage, hasUsage bool) {
|
||||
var f struct {
|
||||
Choices []struct {
|
||||
Delta struct {
|
||||
Content string `json:"content"`
|
||||
ReasoningContent string `json:"reasoning_content"`
|
||||
Reasoning string `json:"reasoning"`
|
||||
ReasoningText string `json:"reasoning_text"`
|
||||
Refusal string `json:"refusal"`
|
||||
ToolCalls []oaToolCall `json:"tool_calls"`
|
||||
} `json:"delta"`
|
||||
FinishReason string `json:"finish_reason"`
|
||||
} `json:"choices"`
|
||||
Usage *struct {
|
||||
PromptTokens int `json:"prompt_tokens"`
|
||||
CompletionTokens int `json:"completion_tokens"`
|
||||
PromptTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
} `json:"prompt_tokens_details"`
|
||||
} `json:"usage"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &f); err != nil {
|
||||
return nil, "", Usage{}, false
|
||||
}
|
||||
if f.Usage != nil {
|
||||
usage = Usage{InputTokens: f.Usage.PromptTokens, OutputTokens: f.Usage.CompletionTokens, CacheReadTokens: f.Usage.PromptTokensDetails.CachedTokens}
|
||||
hasUsage = true
|
||||
}
|
||||
if len(f.Choices) == 0 {
|
||||
return nil, "", usage, hasUsage
|
||||
}
|
||||
ch := f.Choices[0]
|
||||
if think := pickReasoning(ch.Delta.ReasoningContent, ch.Delta.Reasoning, ch.Delta.ReasoningText); think != "" {
|
||||
evs = append(evs, StreamEvent{Type: SEThinkingDelta, Text: think})
|
||||
}
|
||||
if ch.Delta.Content != "" {
|
||||
evs = append(evs, StreamEvent{Type: SETextDelta, Text: ch.Delta.Content})
|
||||
}
|
||||
if ch.Delta.Refusal != "" {
|
||||
// See parseOpenAIResponse: a refusal streams in `refusal`, not `content`.
|
||||
evs = append(evs, StreamEvent{Type: SETextDelta, Text: ch.Delta.Refusal})
|
||||
}
|
||||
for _, tc := range ch.Delta.ToolCalls {
|
||||
if !started[tc.Index] && (tc.ID != "" || tc.Function.Name != "") {
|
||||
started[tc.Index] = true
|
||||
evs = append(evs, StreamEvent{Type: SEToolUseStart, ToolID: tc.ID, ToolName: tc.Function.Name})
|
||||
}
|
||||
if tc.Function.Arguments != "" {
|
||||
evs = append(evs, StreamEvent{Type: SEToolInputJSON, Text: tc.Function.Arguments})
|
||||
}
|
||||
}
|
||||
if ch.FinishReason != "" {
|
||||
stopReason = mapOpenAIFinish(ch.FinishReason)
|
||||
}
|
||||
return evs, stopReason, usage, hasUsage
|
||||
}
|
||||
|
||||
func mapOpenAIFinish(r string) string {
|
||||
switch r {
|
||||
case "tool_calls":
|
||||
return "tool_use"
|
||||
case "stop":
|
||||
return "end_turn"
|
||||
case "length":
|
||||
return "max_tokens"
|
||||
default:
|
||||
return r
|
||||
}
|
||||
}
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// emptyStop is a completed stream that produced no content (a normal `stop` with
|
||||
// nothing before it) — the degenerate empty completion the retry targets.
|
||||
var emptyStop = sse(`data: {"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}`, ``, `data: [DONE]`, ``)
|
||||
|
||||
// A streamed empty completion is re-requested; a subsequent non-empty attempt
|
||||
// surfaces normally. Exactly two requests: one empty, one recovered.
|
||||
func TestOpenAIStreamEmptyResponseRetries(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if calls.Add(1) == 1 {
|
||||
w.Write([]byte(emptyStop))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(sse(`data: {"choices":[{"index":0,"delta":{"content":"recovered"}}]}`, ``, `data: [DONE]`, ``)))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if msg.Text() != "recovered" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("calls=%d, want 2 (one empty + one retry)", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// An always-empty stream is retried a bounded number of times, then surfaced as
|
||||
// an empty message rather than looping forever.
|
||||
func TestOpenAIStreamEmptyResponseExhausts(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Write([]byte(emptyStop))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if len(msg.Content) != 0 {
|
||||
t.Fatalf("want empty message after exhaustion, got %+v", msg.Content)
|
||||
}
|
||||
if calls.Load() != int32(emptyResponseRetries+1) {
|
||||
t.Fatalf("calls=%d, want %d", calls.Load(), emptyResponseRetries+1)
|
||||
}
|
||||
}
|
||||
|
||||
// A max_tokens truncation with no content must NOT retry — that recovery is the
|
||||
// harness's to drive, and re-requesting would fight it.
|
||||
func TestOpenAIStreamEmptyMaxTokensNoRetry(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Write([]byte(sse(`data: {"choices":[{"index":0,"delta":{},"finish_reason":"length"}]}`, ``, `data: [DONE]`, ``)))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
_ = collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("calls=%d, want 1 (max_tokens must not retry)", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A stream that produces content on the first attempt is never retried.
|
||||
func TestOpenAIStreamContentNoRetry(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Write([]byte(sse(`data: {"choices":[{"index":0,"delta":{"content":"hi"},"finish_reason":"stop"}]}`, ``, `data: [DONE]`, ``)))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if msg.Text() != "hi" || calls.Load() != 1 {
|
||||
t.Fatalf("text=%q calls=%d", msg.Text(), calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// The non-streaming path retries an empty completion the same way.
|
||||
func TestOpenAICompleteEmptyResponseRetries(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("content-type", "application/json")
|
||||
if calls.Add(1) == 1 {
|
||||
w.Write([]byte(`{"choices":[{"message":{"content":""},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":0}}`))
|
||||
return
|
||||
}
|
||||
w.Write([]byte(`{"choices":[{"message":{"content":"recovered"},"finish_reason":"stop"}],"usage":{"prompt_tokens":1,"completion_tokens":2}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg, _, _, err := p.Complete(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if err != nil {
|
||||
t.Fatalf("Complete err: %v", err)
|
||||
}
|
||||
if msg.Text() != "recovered" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("calls=%d, want 2", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmptyResponseRetryable(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
stop string
|
||||
want bool
|
||||
}{
|
||||
{"end_turn", true},
|
||||
{"", true},
|
||||
{"max_tokens", false},
|
||||
{"tool_use", false},
|
||||
} {
|
||||
if got := isEmptyResponseRetryable(tc.stop); got != tc.want {
|
||||
t.Fatalf("isEmptyResponseRetryable(%q)=%v, want %v", tc.stop, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// maxTokensKeys reports which of the two mutually exclusive output-cap keys the
|
||||
// request body carried, and with what value.
|
||||
func maxTokensKeys(m map[string]any) (old, new_ float64, oldSet, newSet bool) {
|
||||
old, oldSet = m["max_tokens"].(float64)
|
||||
new_, newSet = m["max_completion_tokens"].(float64)
|
||||
return
|
||||
}
|
||||
|
||||
// Default config keeps the classic key, so upgrading the SDK cannot change what
|
||||
// existing gateways receive.
|
||||
func TestOpenAIMaxTokensDefaultsToClassicKey(t *testing.T) {
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
req := CompletionRequest{MaxTokens: 4096, Messages: []Message{UserText("hi")}}
|
||||
_, m := captureReq(t, Config{Format: FormatOpenAI}, req, stub)
|
||||
|
||||
old, _, oldSet, newSet := maxTokensKeys(m)
|
||||
if !oldSet || old != 4096 {
|
||||
t.Fatalf("max_tokens=%v set=%v, want 4096", old, oldSet)
|
||||
}
|
||||
if newSet {
|
||||
t.Fatal("max_completion_tokens must be absent by default")
|
||||
}
|
||||
}
|
||||
|
||||
// Opting in moves the cap onto the new key — and drops the old one entirely,
|
||||
// since OpenAI rejects a request carrying both.
|
||||
func TestOpenAIMaxCompletionTokensOptIn(t *testing.T) {
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
req := CompletionRequest{MaxTokens: 8192, Messages: []Message{UserText("hi")}}
|
||||
cfg := Config{Format: FormatOpenAI, MaxTokensField: MaxTokensFieldCompletion}
|
||||
_, m := captureReq(t, cfg, req, stub)
|
||||
|
||||
_, new_, oldSet, newSet := maxTokensKeys(m)
|
||||
if !newSet || new_ != 8192 {
|
||||
t.Fatalf("max_completion_tokens=%v set=%v, want 8192", new_, newSet)
|
||||
}
|
||||
if oldSet {
|
||||
t.Fatal("max_tokens must be dropped when the new key is selected")
|
||||
}
|
||||
}
|
||||
|
||||
// An unrecognized value is not a request-breaking error: it falls back to the
|
||||
// classic key rather than emitting a bogus one.
|
||||
func TestOpenAIMaxTokensFieldUnknownFallsBack(t *testing.T) {
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
req := CompletionRequest{MaxTokens: 512, Messages: []Message{UserText("hi")}}
|
||||
_, m := captureReq(t, Config{Format: FormatOpenAI, MaxTokensField: "nonsense"}, req, stub)
|
||||
|
||||
old, _, oldSet, newSet := maxTokensKeys(m)
|
||||
if !oldSet || old != 512 || newSet {
|
||||
t.Fatalf("want max_tokens=512 only, got old=%v/%v new set=%v", old, oldSet, newSet)
|
||||
}
|
||||
}
|
||||
|
||||
// MaxTokens==0 means "no cap": neither key may appear, whichever is selected.
|
||||
func TestOpenAIMaxTokensZeroOmitsBothKeys(t *testing.T) {
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
req := CompletionRequest{Messages: []Message{UserText("hi")}} // MaxTokens == 0
|
||||
for _, field := range []string{"", MaxTokensFieldCompletion} {
|
||||
_, m := captureReq(t, Config{Format: FormatOpenAI, MaxTokensField: field}, req, stub)
|
||||
if _, _, oldSet, newSet := maxTokensKeys(m); oldSet || newSet {
|
||||
t.Fatalf("field=%q: no cap should be sent, got old=%v new=%v", field, oldSet, newSet)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The non-streaming path builds the same body, so the switch must hold there too.
|
||||
func TestOpenAIMaxCompletionTokensNonStreaming(t *testing.T) {
|
||||
var got map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &got)
|
||||
w.Header().Set("content-type", "application/json")
|
||||
w.Write([]byte(`{"choices":[{"message":{"content":"ok"},"finish_reason":"stop"}]}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p, err := NewProvider(Config{
|
||||
Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m",
|
||||
MaxTokensField: MaxTokensFieldCompletion,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("NewProvider: %v", err)
|
||||
}
|
||||
if _, _, _, err := p.Complete(context.Background(), CompletionRequest{
|
||||
MaxTokens: 2048, Messages: []Message{UserText("go")},
|
||||
}); err != nil {
|
||||
t.Fatalf("Complete: %v", err)
|
||||
}
|
||||
_, new_, oldSet, newSet := maxTokensKeys(got)
|
||||
if !newSet || new_ != 2048 || oldSet {
|
||||
t.Fatalf("want max_completion_tokens=2048 only, got new=%v/%v old set=%v", new_, newSet, oldSet)
|
||||
}
|
||||
}
|
||||
|
||||
// Anthropic names the field itself; the OpenAI-only switch must not leak into it.
|
||||
func TestAnthropicIgnoresMaxTokensField(t *testing.T) {
|
||||
stub := sse(`data: {"type":"message_stop"}`, ``)
|
||||
req := CompletionRequest{MaxTokens: 1024, Messages: []Message{UserText("hi")}}
|
||||
cfg := Config{Format: FormatAnthropic, MaxTokensField: MaxTokensFieldCompletion}
|
||||
_, m := captureReq(t, cfg, req, stub)
|
||||
|
||||
old, _, oldSet, newSet := maxTokensKeys(m)
|
||||
if !oldSet || old != 1024 {
|
||||
t.Fatalf("anthropic max_tokens=%v set=%v, want 1024", old, oldSet)
|
||||
}
|
||||
if newSet {
|
||||
t.Fatal("anthropic must never send max_completion_tokens")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// Some gateways (OpenRouter) and vLLM's reasoning parsers put a reasoning
|
||||
// model's thinking in delta.reasoning rather than delta.reasoning_content.
|
||||
// Reading only the latter dropped the whole turn's thinking: a turn that emitted
|
||||
// nothing but reasoning + tool_calls surfaced as an empty message, which the
|
||||
// caller then rendered as a text-less run.
|
||||
func TestOpenAIStreamReasoningAlias(t *testing.T) {
|
||||
started := map[int]bool{}
|
||||
evs, _, _, _ := parseOpenAIFrame(`{"choices":[{"index":0,"delta":{"reasoning":"I need to verify"}}]}`, started)
|
||||
if len(evs) != 1 || evs[0].Type != SEThinkingDelta || evs[0].Text != "I need to verify" {
|
||||
t.Fatalf("evs=%+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
// reasoning_content wins when a provider sends both, so DeepSeek-style payloads
|
||||
// keep their existing behaviour.
|
||||
func TestOpenAIStreamReasoningContentWins(t *testing.T) {
|
||||
started := map[int]bool{}
|
||||
evs, _, _, _ := parseOpenAIFrame(`{"choices":[{"index":0,"delta":{"reasoning":"alias","reasoning_content":"canonical"}}]}`, started)
|
||||
if len(evs) != 1 || evs[0].Text != "canonical" {
|
||||
t.Fatalf("evs=%+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
// reasoning_text is the third field name some gateways use; it is read when the
|
||||
// other two are absent.
|
||||
func TestOpenAIStreamReasoningTextField(t *testing.T) {
|
||||
started := map[int]bool{}
|
||||
evs, _, _, _ := parseOpenAIFrame(`{"choices":[{"index":0,"delta":{"reasoning_text":"third field"}}]}`, started)
|
||||
if len(evs) != 1 || evs[0].Type != SEThinkingDelta || evs[0].Text != "third field" {
|
||||
t.Fatalf("evs=%+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
// The three reasoning fields are tried in priority order — a gateway that echoes
|
||||
// the same text in more than one field contributes it once, not concatenated.
|
||||
func TestOpenAIStreamReasoningDedup(t *testing.T) {
|
||||
started := map[int]bool{}
|
||||
evs, _, _, _ := parseOpenAIFrame(`{"choices":[{"index":0,"delta":{"reasoning_content":"once","reasoning":"once","reasoning_text":"once"}}]}`, started)
|
||||
if len(evs) != 1 || evs[0].Text != "once" {
|
||||
t.Fatalf("evs=%+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
// End-to-end replay of a vLLM (qwen) stream whose whole turn is reasoning +
|
||||
// tool_calls: the accumulated message must carry the thinking, not come back
|
||||
// empty.
|
||||
func TestOpenAIStreamVLLMReasoningReplay(t *testing.T) {
|
||||
body := sse(
|
||||
`data: {"choices":[{"index":0,"delta":{"role":"assistant","content":""}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"index":0,"delta":{"reasoning":"I"}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"index":0,"delta":{"reasoning":" need to verify"}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"index":0,"delta":{"tool_calls":[{"id":"call-1","type":"function","index":0,"function":{"name":"list_facts"}}]}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{}"}}]}}]}`,
|
||||
``,
|
||||
`data: {"choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`,
|
||||
``,
|
||||
`data: {"choices":[],"usage":{"prompt_tokens":20860,"total_tokens":20899,"completion_tokens":39}}`,
|
||||
``,
|
||||
`data: [DONE]`,
|
||||
``,
|
||||
)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if thinking := thinkingOf(msg); thinking != "I need to verify" {
|
||||
t.Fatalf("thinking=%q", thinking)
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].Name != "list_facts" {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIResponseReasoningAlias(t *testing.T) {
|
||||
msg, stop, _, err := parseOpenAIResponse([]byte(`{"choices":[{"message":{"content":"","reasoning":"let me think"},"finish_reason":"stop"}]}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse err: %v", err)
|
||||
}
|
||||
if stop != "end_turn" {
|
||||
t.Fatalf("stop=%q", stop)
|
||||
}
|
||||
if thinking := thinkingOf(msg); thinking != "let me think" {
|
||||
t.Fatalf("thinking=%q", thinking)
|
||||
}
|
||||
}
|
||||
|
||||
// A refused turn carries content:null and the reason in `refusal`; it must not
|
||||
// decode to an empty assistant message.
|
||||
func TestOpenAIRefusalBecomesText(t *testing.T) {
|
||||
msg, _, _, err := parseOpenAIResponse([]byte(`{"choices":[{"message":{"content":null,"refusal":"I can't help with that."},"finish_reason":"stop"}]}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse err: %v", err)
|
||||
}
|
||||
if msg.Text() != "I can't help with that." {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIStreamRefusalBecomesText(t *testing.T) {
|
||||
started := map[int]bool{}
|
||||
evs, _, _, _ := parseOpenAIFrame(`{"choices":[{"index":0,"delta":{"refusal":"I can't"}}]}`, started)
|
||||
if len(evs) != 1 || evs[0].Type != SETextDelta || evs[0].Text != "I can't" {
|
||||
t.Fatalf("evs=%+v", evs)
|
||||
}
|
||||
}
|
||||
|
||||
func thinkingOf(msg Message) string {
|
||||
var s string
|
||||
for _, b := range msg.Content {
|
||||
if b.Type == BlockThinking {
|
||||
s += b.Thinking
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
+372
@@ -0,0 +1,372 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"iter"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// openaiResponsesProvider speaks the OpenAI Responses API (POST /v1/responses),
|
||||
// a different wire protocol from Chat Completions: the system prompt is a
|
||||
// top-level `instructions`, history is a flat `input` array of items
|
||||
// (message / function_call / function_call_output), tools are flattened, the
|
||||
// output cap is `max_output_tokens`, reasoning strength is `reasoning.effort`,
|
||||
// and streaming uses many named SSE events (response.output_text.delta, …)
|
||||
// instead of choices[].delta. It translates all of that to and from the neutral
|
||||
// content-block model so the harness is unchanged.
|
||||
//
|
||||
// It is stateless: store is false and the full history is sent every call, so it
|
||||
// composes with the host's own transcript/compaction (no previous_response_id).
|
||||
type openaiResponsesProvider struct{ cfg Config }
|
||||
|
||||
// ---- request ----
|
||||
|
||||
type orReq struct {
|
||||
Model string `json:"model"`
|
||||
Instructions string `json:"instructions,omitempty"`
|
||||
Input []orInputItem `json:"input"`
|
||||
Tools []orTool `json:"tools,omitempty"`
|
||||
MaxOutputTokens int `json:"max_output_tokens,omitempty"`
|
||||
Reasoning *orReasoning `json:"reasoning,omitempty"`
|
||||
Temperature *float64 `json:"temperature,omitempty"`
|
||||
Stream bool `json:"stream"`
|
||||
Store bool `json:"store"`
|
||||
}
|
||||
|
||||
type orReasoning struct {
|
||||
Effort string `json:"effort"`
|
||||
}
|
||||
|
||||
// orInputItem is a union: a message (Role+Content string, no Type) or a typed
|
||||
// function_call / function_call_output item. omitempty keeps each shape minimal
|
||||
// so the API sees exactly one well-formed variant per item.
|
||||
type orInputItem struct {
|
||||
Type string `json:"type,omitempty"`
|
||||
Role string `json:"role,omitempty"`
|
||||
Content string `json:"content,omitempty"`
|
||||
CallID string `json:"call_id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Arguments string `json:"arguments,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
}
|
||||
|
||||
type orTool struct {
|
||||
Type string `json:"type"` // "function"
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Parameters map[string]any `json:"parameters,omitempty"`
|
||||
}
|
||||
|
||||
func (p *openaiResponsesProvider) buildBody(req CompletionRequest, stream bool) ([]byte, error) {
|
||||
body := orReq{
|
||||
Model: p.cfg.Model,
|
||||
Instructions: joinSystem(req.System),
|
||||
Input: toResponsesInput(req.Messages),
|
||||
MaxOutputTokens: req.MaxTokens,
|
||||
Temperature: req.Temperature,
|
||||
Stream: stream,
|
||||
Store: false, // stateless: full history sent each call
|
||||
}
|
||||
// reasoning.effort is the Responses equivalent of reasoning_effort. A
|
||||
// per-request "disabled" (compaction's summary call) suppresses it; otherwise
|
||||
// send it only when configured.
|
||||
if req.Thinking != "disabled" && p.cfg.ReasoningEffort != "" {
|
||||
body.Reasoning = &orReasoning{Effort: p.cfg.ReasoningEffort}
|
||||
}
|
||||
for _, t := range req.Tools {
|
||||
body.Tools = append(body.Tools, orTool{Type: "function", Name: t.Name, Description: t.Description, Parameters: t.InputSchema})
|
||||
}
|
||||
return json.Marshal(body)
|
||||
}
|
||||
|
||||
// toResponsesInput flattens neutral messages into Responses input items: text
|
||||
// becomes a role message (string content), tool_use becomes a function_call, and
|
||||
// tool_result becomes a function_call_output. Thinking blocks are dropped on
|
||||
// replay (mirrors the Chat Completions adapter's default and avoids echoing
|
||||
// provider-specific reasoning state the Responses API manages itself).
|
||||
func toResponsesInput(msgs []Message) []orInputItem {
|
||||
var out []orInputItem
|
||||
for _, m := range msgs {
|
||||
role := string(m.Role)
|
||||
var text strings.Builder
|
||||
// flushText emits accumulated text as a role message, preserving block
|
||||
// order: a text block that precedes a tool_use/tool_result must appear
|
||||
// before that item in the input array, not after it.
|
||||
flushText := func() {
|
||||
if s := text.String(); s != "" {
|
||||
out = append(out, orInputItem{Role: role, Content: s})
|
||||
text.Reset()
|
||||
}
|
||||
}
|
||||
for _, b := range m.Content {
|
||||
switch b.Type {
|
||||
case BlockText:
|
||||
text.WriteString(b.Text)
|
||||
case BlockToolUse:
|
||||
flushText()
|
||||
args := string(b.Input)
|
||||
if strings.TrimSpace(args) == "" {
|
||||
args = "{}"
|
||||
}
|
||||
out = append(out, orInputItem{Type: "function_call", CallID: b.ID, Name: b.Name, Arguments: args})
|
||||
case BlockToolResult:
|
||||
flushText()
|
||||
out = append(out, orInputItem{Type: "function_call_output", CallID: b.ToolUseID, Output: flattenText(b.Content)})
|
||||
}
|
||||
}
|
||||
flushText()
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (p *openaiResponsesProvider) setHeaders(r *http.Request) {
|
||||
r.Header.Set("content-type", "application/json")
|
||||
r.Header.Set("authorization", "Bearer "+p.cfg.APIKey)
|
||||
}
|
||||
|
||||
// ---- streaming ----
|
||||
|
||||
func (p *openaiResponsesProvider) Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error] {
|
||||
return func(yield func(StreamEvent, error) bool) {
|
||||
body, err := p.buildBody(req, true)
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/responses", body, func(r *http.Request) {
|
||||
p.setHeaders(r)
|
||||
r.Header.Set("accept", "text/event-stream")
|
||||
}, "openai-responses")
|
||||
if err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
scan := newSSEScanner(resp.Body)
|
||||
for {
|
||||
event, data, serr := scan.next()
|
||||
if serr == io.EOF {
|
||||
return
|
||||
}
|
||||
if serr != nil {
|
||||
yield(StreamEvent{}, serr)
|
||||
return
|
||||
}
|
||||
if data == "" {
|
||||
continue
|
||||
}
|
||||
ev, ok, perr := parseResponsesFrame(event, data)
|
||||
if perr != nil {
|
||||
yield(StreamEvent{}, perr)
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if !yield(ev, nil) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseResponsesFrame maps one named Responses SSE event to a neutral
|
||||
// StreamEvent. Unrecognized events (response.created, *.in_progress, item.done,
|
||||
// content_part.*, etc.) return ok=false and are skipped.
|
||||
func parseResponsesFrame(event, data string) (StreamEvent, bool, error) {
|
||||
// The event name is authoritative; some gateways omit the SSE `event:` line
|
||||
// and put the discriminator only in the JSON `type` field, so fall back to it.
|
||||
var f struct {
|
||||
Type string `json:"type"`
|
||||
// output_item.added: item carries the function_call id/name.
|
||||
Item struct {
|
||||
Type string `json:"type"`
|
||||
CallID string `json:"call_id"`
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"item"`
|
||||
Delta string `json:"delta"` // *_text.delta / function_call_arguments.delta
|
||||
Response struct {
|
||||
Status string `json:"status"`
|
||||
IncompleteDetails *struct {
|
||||
Reason string `json:"reason"`
|
||||
} `json:"incomplete_details"`
|
||||
Usage *orUsage `json:"usage"`
|
||||
} `json:"response"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(data), &f); err != nil {
|
||||
return StreamEvent{}, false, nil // tolerate keepalives / non-JSON
|
||||
}
|
||||
kind := event
|
||||
if kind == "" {
|
||||
kind = f.Type
|
||||
}
|
||||
switch kind {
|
||||
case "response.output_item.added":
|
||||
if f.Item.Type == "function_call" {
|
||||
return StreamEvent{Type: SEToolUseStart, ToolID: f.Item.CallID, ToolName: f.Item.Name}, true, nil
|
||||
}
|
||||
case "response.output_text.delta":
|
||||
if f.Delta != "" {
|
||||
return StreamEvent{Type: SETextDelta, Text: f.Delta}, true, nil
|
||||
}
|
||||
case "response.reasoning_summary_text.delta", "response.reasoning_text.delta":
|
||||
if f.Delta != "" {
|
||||
return StreamEvent{Type: SEThinkingDelta, Text: f.Delta}, true, nil
|
||||
}
|
||||
case "response.function_call_arguments.delta":
|
||||
if f.Delta != "" {
|
||||
return StreamEvent{Type: SEToolInputJSON, Text: f.Delta}, true, nil
|
||||
}
|
||||
case "response.completed", "response.incomplete":
|
||||
ev := StreamEvent{Type: SEMessageDelta, StopReason: "end_turn"}
|
||||
if f.Response.IncompleteDetails != nil && f.Response.IncompleteDetails.Reason == "max_output_tokens" {
|
||||
ev.StopReason = "max_tokens"
|
||||
}
|
||||
if f.Response.Usage != nil {
|
||||
ev.Usage = f.Response.Usage.norm()
|
||||
}
|
||||
return ev, true, nil
|
||||
case "response.failed", "error":
|
||||
msg := "stream error"
|
||||
if f.Error != nil {
|
||||
msg = f.Error.Message
|
||||
}
|
||||
return StreamEvent{}, false, fmt.Errorf("openai-responses: %s", msg)
|
||||
}
|
||||
return StreamEvent{}, false, nil
|
||||
}
|
||||
|
||||
// ---- non-streaming ----
|
||||
|
||||
func (p *openaiResponsesProvider) Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error) {
|
||||
body, err := p.buildBody(req, false)
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
resp, err := doStream(ctx, p.cfg, p.cfg.BaseURL+"/responses", body, func(r *http.Request) {
|
||||
p.setHeaders(r)
|
||||
r.Header.Set("accept", "application/json")
|
||||
}, "openai-responses")
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
return parseResponsesResponse(raw)
|
||||
}
|
||||
|
||||
type orUsage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
InputTokensDetails struct {
|
||||
CachedTokens int `json:"cached_tokens"`
|
||||
} `json:"input_tokens_details"`
|
||||
}
|
||||
|
||||
// norm maps Responses usage to the canonical Usage. InputTokens already counts
|
||||
// the full input including cached tokens (OpenAI semantics); CacheReadTokens is
|
||||
// the cached subset.
|
||||
func (u orUsage) norm() Usage {
|
||||
return Usage{
|
||||
InputTokens: u.InputTokens,
|
||||
OutputTokens: u.OutputTokens,
|
||||
CacheReadTokens: u.InputTokensDetails.CachedTokens,
|
||||
}
|
||||
}
|
||||
|
||||
// parseResponsesResponse decodes a non-streaming /v1/responses body into the
|
||||
// neutral Message: output message text → text block, reasoning summary →
|
||||
// thinking block, function_call → tool_use block (ID = call_id).
|
||||
func parseResponsesResponse(raw []byte) (Message, string, Usage, error) {
|
||||
var r struct {
|
||||
Output []struct {
|
||||
Type string `json:"type"`
|
||||
Role string `json:"role"`
|
||||
Content []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"content"`
|
||||
Summary []struct {
|
||||
Type string `json:"type"`
|
||||
Text string `json:"text"`
|
||||
} `json:"summary"`
|
||||
CallID string `json:"call_id"`
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"`
|
||||
} `json:"output"`
|
||||
Status string `json:"status"`
|
||||
IncompleteDetails *struct {
|
||||
Reason string `json:"reason"`
|
||||
} `json:"incomplete_details"`
|
||||
Usage *orUsage `json:"usage"`
|
||||
Error *struct {
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &r); err != nil {
|
||||
return Message{}, "", Usage{}, fmt.Errorf("openai-responses: decode response: %w (body: %s)", err, truncate(string(raw), 500))
|
||||
}
|
||||
if r.Error != nil {
|
||||
return Message{}, "", Usage{}, fmt.Errorf("openai-responses: %s", r.Error.Message)
|
||||
}
|
||||
var usage Usage
|
||||
if r.Usage != nil {
|
||||
usage = r.Usage.norm()
|
||||
}
|
||||
var blocks []ContentBlock
|
||||
hasToolCall := false
|
||||
for _, item := range r.Output {
|
||||
switch item.Type {
|
||||
case "message":
|
||||
for _, c := range item.Content {
|
||||
if c.Type == "output_text" && c.Text != "" {
|
||||
blocks = append(blocks, TextBlock(c.Text))
|
||||
}
|
||||
}
|
||||
case "reasoning":
|
||||
// A reasoning item carries its thinking in `summary` (summary_text parts)
|
||||
// and/or in `content` (reasoning_text parts). The streaming path already
|
||||
// accepts both — response.reasoning_summary_text.delta and
|
||||
// response.reasoning_text.delta — so read both here too; taking only
|
||||
// `summary` drops the whole turn's thinking on models that fill `content`.
|
||||
var think strings.Builder
|
||||
for _, s := range item.Summary {
|
||||
think.WriteString(s.Text)
|
||||
}
|
||||
for _, c := range item.Content {
|
||||
if c.Type == "reasoning_text" {
|
||||
think.WriteString(c.Text)
|
||||
}
|
||||
}
|
||||
if think.Len() > 0 {
|
||||
blocks = append(blocks, ContentBlock{Type: BlockThinking, Thinking: think.String()})
|
||||
}
|
||||
case "function_call":
|
||||
args := item.Arguments
|
||||
if strings.TrimSpace(args) == "" {
|
||||
args = "{}"
|
||||
}
|
||||
blocks = append(blocks, ContentBlock{Type: BlockToolUse, ID: item.CallID, Name: item.Name, Input: []byte(args)})
|
||||
hasToolCall = true
|
||||
}
|
||||
}
|
||||
stop := "end_turn"
|
||||
if hasToolCall {
|
||||
stop = "tool_use"
|
||||
}
|
||||
if r.IncompleteDetails != nil && r.IncompleteDetails.Reason == "max_output_tokens" {
|
||||
stop = "max_tokens"
|
||||
}
|
||||
return Message{Role: RoleAssistant, Content: blocks}, stop, usage, nil
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestResponsesStreaming drives the Responses SSE event vocabulary through the
|
||||
// adapter and asserts the neutral message it accumulates: reasoning summary →
|
||||
// thinking, output_text → text, function_call added + arg deltas → tool_use.
|
||||
func TestResponsesStreaming(t *testing.T) {
|
||||
body := sse2(
|
||||
event("response.created", `{"type":"response.created"}`),
|
||||
event("response.reasoning_summary_text.delta", `{"type":"response.reasoning_summary_text.delta","delta":"thinking…"}`),
|
||||
event("response.output_text.delta", `{"type":"response.output_text.delta","delta":"Hello "}`),
|
||||
event("response.output_item.added", `{"type":"response.output_item.added","item":{"type":"function_call","call_id":"call_1","name":"Read"}}`),
|
||||
event("response.function_call_arguments.delta", `{"type":"response.function_call_arguments.delta","delta":"{\"file_path\":\"a\"}"}`),
|
||||
event("response.completed", `{"type":"response.completed","response":{"status":"completed","usage":{"input_tokens":11,"output_tokens":6,"input_tokens_details":{"cached_tokens":3}}}}`),
|
||||
)
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/responses" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.Write([]byte(body))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAIResponses, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
acc := NewAccumulator()
|
||||
var usage Usage
|
||||
for ev, err := range p.Stream(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}}) {
|
||||
if err != nil {
|
||||
t.Fatalf("stream err: %v", err)
|
||||
}
|
||||
if ev.Type == SEMessageDelta {
|
||||
usage = ev.Usage
|
||||
}
|
||||
acc.Add(ev)
|
||||
}
|
||||
// stateless wire: store must be false, and the system prompt is top-level.
|
||||
if gotBody["store"] != false {
|
||||
t.Fatalf("store=%v, want false", gotBody["store"])
|
||||
}
|
||||
msg := acc.Message()
|
||||
if msg.Text() != "Hello " {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].ID != "call_1" || u[0].Name != "Read" || string(u[0].Input) != `{"file_path":"a"}` {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
if usage.InputTokens != 11 || usage.OutputTokens != 6 || usage.CacheReadTokens != 3 {
|
||||
t.Fatalf("usage=%+v", usage)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResponsesComplete verifies the non-streaming path parses output[] items
|
||||
// (message / reasoning / function_call) and sends a stateless stream:false body.
|
||||
func TestResponsesComplete(t *testing.T) {
|
||||
var gotBody map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path != "/responses" {
|
||||
t.Errorf("path=%s", r.URL.Path)
|
||||
}
|
||||
raw, _ := io.ReadAll(r.Body)
|
||||
_ = json.Unmarshal(raw, &gotBody)
|
||||
w.Header().Set("content-type", "application/json")
|
||||
w.Write([]byte(`{"status":"completed","output":[{"type":"reasoning","summary":[{"type":"summary_text","text":"hmm"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hi"}]},{"type":"function_call","call_id":"c9","name":"Bash","arguments":"{\"command\":\"ls\"}"}],"usage":{"input_tokens":10,"output_tokens":5,"input_tokens_details":{"cached_tokens":2}}}`))
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
p, _ := NewProvider(Config{Format: FormatOpenAIResponses, BaseURL: srv.URL, APIKey: "k", Model: "m"})
|
||||
msg, stop, usage, err := p.Complete(context.Background(), CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if err != nil {
|
||||
t.Fatalf("Complete err: %v", err)
|
||||
}
|
||||
if gotBody["stream"] != false {
|
||||
t.Fatalf("stream=%v, want false", gotBody["stream"])
|
||||
}
|
||||
if msg.Text() != "Hi" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
var think string
|
||||
for _, b := range msg.Content {
|
||||
if b.Type == BlockThinking {
|
||||
think = b.Thinking
|
||||
}
|
||||
}
|
||||
if think != "hmm" {
|
||||
t.Fatalf("thinking=%q", think)
|
||||
}
|
||||
if u := msg.ToolUses(); len(u) != 1 || u[0].ID != "c9" || u[0].Name != "Bash" {
|
||||
t.Fatalf("tooluse=%+v", u)
|
||||
}
|
||||
if stop != "tool_use" {
|
||||
t.Fatalf("stop=%q", stop)
|
||||
}
|
||||
if usage.InputTokens != 10 || usage.OutputTokens != 5 || usage.CacheReadTokens != 2 {
|
||||
t.Fatalf("usage=%+v", usage)
|
||||
}
|
||||
}
|
||||
|
||||
// A reasoning item may carry its thinking in `content` (reasoning_text parts)
|
||||
// instead of `summary`. The streaming path already handles both event kinds;
|
||||
// the non-streaming parse must not drop the content variant.
|
||||
func TestResponsesReasoningTextContent(t *testing.T) {
|
||||
msg, _, _, err := parseResponsesResponse([]byte(`{"status":"completed","output":[{"type":"reasoning","content":[{"type":"reasoning_text","text":"deep thought"}]},{"type":"message","role":"assistant","content":[{"type":"output_text","text":"Hi"}]}]}`))
|
||||
if err != nil {
|
||||
t.Fatalf("parse err: %v", err)
|
||||
}
|
||||
var think string
|
||||
for _, b := range msg.Content {
|
||||
if b.Type == BlockThinking {
|
||||
think = b.Thinking
|
||||
}
|
||||
}
|
||||
if think != "deep thought" {
|
||||
t.Fatalf("thinking=%q", think)
|
||||
}
|
||||
if msg.Text() != "Hi" {
|
||||
t.Fatalf("text=%q", msg.Text())
|
||||
}
|
||||
}
|
||||
|
||||
// TestToResponsesInput checks the neutral→input-item translation: tool_use →
|
||||
// function_call, tool_result → function_call_output (call_id paired), text →
|
||||
// role message, thinking dropped.
|
||||
func TestToResponsesInput(t *testing.T) {
|
||||
msgs := []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockThinking, Thinking: "dropped"},
|
||||
{Type: BlockText, Text: "calling"},
|
||||
{Type: BlockToolUse, ID: "c1", Name: "Bash", Input: []byte(`{"command":"ls"}`)},
|
||||
}},
|
||||
{Role: RoleUser, Content: []ContentBlock{ToolResultText("c1", "file.txt", false)}},
|
||||
}
|
||||
in := toResponsesInput(msgs)
|
||||
// user message, assistant text message, function_call, function_call_output.
|
||||
if len(in) != 4 {
|
||||
t.Fatalf("items=%d: %+v", len(in), in)
|
||||
}
|
||||
if in[0].Role != "user" || in[0].Content != "hi" {
|
||||
t.Fatalf("item0=%+v", in[0])
|
||||
}
|
||||
if in[1].Role != "assistant" || in[1].Content != "calling" {
|
||||
t.Fatalf("item1=%+v", in[1])
|
||||
}
|
||||
if in[2].Type != "function_call" || in[2].CallID != "c1" || in[2].Name != "Bash" {
|
||||
t.Fatalf("item2=%+v", in[2])
|
||||
}
|
||||
if in[3].Type != "function_call_output" || in[3].CallID != "c1" || in[3].Output != "file.txt" {
|
||||
t.Fatalf("item3=%+v", in[3])
|
||||
}
|
||||
// thinking must not leak into any item.
|
||||
for _, it := range in {
|
||||
if strings.Contains(it.Content, "dropped") {
|
||||
t.Fatalf("thinking leaked: %+v", it)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// event wraps a data payload with a named SSE event line (Responses uses these).
|
||||
func event(name, data string) string { return "event: " + name + "\ndata: " + data + "\n" }
|
||||
|
||||
// sse2 joins named SSE frames into one response body.
|
||||
func sse2(frames ...string) string { return strings.Join(frames, "\n") + "\n" }
|
||||
Vendored
+253
@@ -0,0 +1,253 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"iter"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// StreamEventType enumerates the normalized streaming events every adapter
|
||||
// emits, regardless of wire format.
|
||||
type StreamEventType string
|
||||
|
||||
const (
|
||||
SEMessageStart StreamEventType = "message_start"
|
||||
SETextDelta StreamEventType = "text_delta"
|
||||
SEThinkingDelta StreamEventType = "thinking_delta"
|
||||
SEThinkingSignature StreamEventType = "thinking_signature"
|
||||
SEToolUseStart StreamEventType = "tool_use_start"
|
||||
SEToolInputJSON StreamEventType = "tool_input_delta"
|
||||
SEMessageDelta StreamEventType = "message_delta" // carries stop_reason / usage
|
||||
SEMessageStop StreamEventType = "message_stop"
|
||||
)
|
||||
|
||||
// StreamEvent is one normalized model-level streaming event (FR-03.5).
|
||||
type StreamEvent struct {
|
||||
Type StreamEventType
|
||||
Text string // text/thinking/tool_input JSON fragment
|
||||
ToolID string // tool_use_start
|
||||
ToolName string // tool_use_start
|
||||
StopReason string // message_delta
|
||||
Usage Usage // message_start / message_delta
|
||||
}
|
||||
|
||||
// Format selects the wire protocol of a Provider.
|
||||
type Format string
|
||||
|
||||
const (
|
||||
FormatAnthropic Format = "anthropic"
|
||||
FormatOpenAI Format = "openai"
|
||||
// FormatOpenAIResponses speaks the OpenAI Responses API (POST /v1/responses),
|
||||
// distinct from FormatOpenAI's Chat Completions (/chat/completions).
|
||||
FormatOpenAIResponses Format = "openai-responses"
|
||||
)
|
||||
|
||||
// MaxTokensFieldCompletion is the Config.MaxTokensField value that moves the
|
||||
// OpenAI Chat Completions output cap onto "max_completion_tokens". Any other
|
||||
// value keeps the classic "max_tokens".
|
||||
const MaxTokensFieldCompletion = "max_completion_tokens"
|
||||
|
||||
// Config configures the built-in providers (FR-03.4).
|
||||
type Config struct {
|
||||
Format Format
|
||||
BaseURL string
|
||||
APIKey string
|
||||
Model string
|
||||
APIVersion string // Anthropic only; default 2023-06-01
|
||||
HTTPClient *http.Client
|
||||
// Proxy, when set, routes all model requests through the given proxy URL —
|
||||
// "http://", "https://" or "socks5://" (optionally with user:pass@). It only
|
||||
// affects the built-in client: when empty, the built-in client falls back to
|
||||
// the standard HTTP_PROXY / HTTPS_PROXY / NO_PROXY environment variables.
|
||||
// Ignored when the caller supplies its own HTTPClient.
|
||||
Proxy string
|
||||
// MaxRetries bounds transient-failure retries on the model request
|
||||
// establishment (connection reset / timeout / 429 / 5xx). 0 = default 3;
|
||||
// negative disables retrying. Only the pre-stream phase is retried (safe);
|
||||
// a mid-stream drop is surfaced as an error.
|
||||
MaxRetries int
|
||||
// RetryInterval, when > 0, replaces the exponential backoff between
|
||||
// establishment retries with this FIXED wait. 0 (default) keeps the
|
||||
// 0.5s/1s/2s… ladder capped at 8s. A host that wants a predictable,
|
||||
// operator-set cadence sets both MaxRetries and this.
|
||||
RetryInterval time.Duration
|
||||
// EmptyResponseRetries bounds how many times a completed-but-EMPTY response
|
||||
// is re-requested (FormatOpenAI only; see emptyResponseRetries). 0 = default
|
||||
// 2; negative disables. Separate from MaxRetries because an empty-response
|
||||
// retry re-sends the whole prompt rather than re-establishing a request.
|
||||
EmptyResponseRetries int
|
||||
// EmptyResponseInterval, when > 0, replaces the exponential backoff before
|
||||
// each empty-response retry with this FIXED wait. 0 keeps the ladder.
|
||||
EmptyResponseInterval time.Duration
|
||||
// RateLimit, when set, bounds the request rate shared across every caller of
|
||||
// the built Provider (per-second and/or per-minute). Retries do not count.
|
||||
RateLimit *RateLimit
|
||||
|
||||
// ThinkingType toggles extended/reasoning mode via the request's
|
||||
// "thinking":{"type":...} field, for both formats. "" omits it (provider
|
||||
// default); "enabled"/"disabled" are sent verbatim.
|
||||
ThinkingType string
|
||||
// ReasoningEffort sets the reasoning strength. "" omits it. For OpenAI it maps
|
||||
// to "reasoning_effort"; for Anthropic to "output_config":{"effort":...}.
|
||||
// Typical values: low / medium / high / max.
|
||||
ReasoningEffort string
|
||||
// MaxTokensField selects which request key carries the output cap on
|
||||
// FormatOpenAI (Chat Completions). "" (default) sends the classic
|
||||
// "max_tokens"; MaxTokensFieldCompletion sends "max_completion_tokens"
|
||||
// instead. OpenAI's reasoning models reject "max_tokens" outright
|
||||
// (unsupported_parameter) and accept only the newer key, whose budget covers
|
||||
// reasoning tokens plus visible output; most OpenAI-compatible gateways still
|
||||
// take the old one, hence the opt-in default. Exactly one key is ever sent.
|
||||
// Ignored by the Anthropic and Responses formats, which name the field
|
||||
// themselves ("max_tokens" / "max_output_tokens").
|
||||
MaxTokensField string
|
||||
|
||||
limiter *rateLimiter // built from RateLimit by NewProvider; shared via the provider
|
||||
}
|
||||
|
||||
// retries returns the effective retry count (0 → default 3; negative → 0).
|
||||
func (c Config) retries() int {
|
||||
if c.MaxRetries == 0 {
|
||||
return 3
|
||||
}
|
||||
if c.MaxRetries < 0 {
|
||||
return 0
|
||||
}
|
||||
return c.MaxRetries
|
||||
}
|
||||
|
||||
// retryDelay is the wait before establishment retry number attempt (0-based):
|
||||
// the configured fixed interval when set, the exponential ladder otherwise.
|
||||
func (c Config) retryDelay(attempt int) time.Duration {
|
||||
if c.RetryInterval > 0 {
|
||||
return c.RetryInterval
|
||||
}
|
||||
return expBackoff(attempt)
|
||||
}
|
||||
|
||||
// emptyRetries returns the effective empty-response retry count
|
||||
// (0 → default emptyResponseRetries; negative → 0).
|
||||
func (c Config) emptyRetries() int {
|
||||
if c.EmptyResponseRetries == 0 {
|
||||
return emptyResponseRetries
|
||||
}
|
||||
if c.EmptyResponseRetries < 0 {
|
||||
return 0
|
||||
}
|
||||
return c.EmptyResponseRetries
|
||||
}
|
||||
|
||||
// emptyRetryDelay is the wait before empty-response retry number attempt.
|
||||
func (c Config) emptyRetryDelay(attempt int) time.Duration {
|
||||
if c.EmptyResponseInterval > 0 {
|
||||
return c.EmptyResponseInterval
|
||||
}
|
||||
return expBackoff(attempt)
|
||||
}
|
||||
|
||||
// Provider produces a completion, either streamed (Stream) or in a single
|
||||
// non-streaming round-trip (Complete). Hosts may implement this interface to
|
||||
// plug in private RPC backends (FR-03.7). Stream's iterator yields normalized
|
||||
// events; a terminal error is delivered as (zero, err) and ends iteration.
|
||||
// Complete performs a real non-streaming request (the wire carries
|
||||
// stream:false and the whole JSON body is parsed at once) and returns the fully
|
||||
// assembled assistant message, the provider stop reason, and cumulative usage.
|
||||
type Provider interface {
|
||||
Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error]
|
||||
Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error)
|
||||
}
|
||||
|
||||
// NewProvider builds a built-in provider for cfg.Format. Missing APIKey/BaseURL
|
||||
// fall back to standard environment variables and public endpoints.
|
||||
func NewProvider(cfg Config) (Provider, error) {
|
||||
if cfg.HTTPClient == nil {
|
||||
client, err := defaultHTTPClient(cfg.Proxy)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cfg.HTTPClient = client
|
||||
}
|
||||
if cfg.RateLimit != nil {
|
||||
cfg.limiter = newRateLimiter(*cfg.RateLimit) // shared by the provider (cfg copies the pointer)
|
||||
}
|
||||
switch cfg.Format {
|
||||
case FormatAnthropic:
|
||||
if cfg.APIKey == "" {
|
||||
cfg.APIKey = os.Getenv("ANTHROPIC_API_KEY")
|
||||
}
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = envOr("ANTHROPIC_BASE_URL", "https://api.anthropic.com")
|
||||
}
|
||||
if cfg.APIVersion == "" {
|
||||
cfg.APIVersion = "2023-06-01"
|
||||
}
|
||||
return &anthropicProvider{cfg: cfg}, nil
|
||||
case FormatOpenAI:
|
||||
if cfg.APIKey == "" {
|
||||
cfg.APIKey = os.Getenv("OPENAI_API_KEY")
|
||||
}
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = envOr("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
||||
}
|
||||
return &openaiProvider{cfg: cfg}, nil
|
||||
case FormatOpenAIResponses:
|
||||
if cfg.APIKey == "" {
|
||||
cfg.APIKey = os.Getenv("OPENAI_API_KEY")
|
||||
}
|
||||
if cfg.BaseURL == "" {
|
||||
cfg.BaseURL = envOr("OPENAI_BASE_URL", "https://api.openai.com/v1")
|
||||
}
|
||||
return &openaiResponsesProvider{cfg: cfg}, nil
|
||||
default:
|
||||
return nil, fmt.Errorf("llm: unknown format %q (use anthropic, openai or openai-responses)", cfg.Format)
|
||||
}
|
||||
}
|
||||
|
||||
// defaultHTTPClient builds the built-in HTTP client. A non-empty proxy
|
||||
// ("http://", "https://" or "socks5://") routes every request through it;
|
||||
// an empty proxy falls back to the standard *_PROXY environment variables
|
||||
// (net/http's ProxyFromEnvironment). The transport is cloned from
|
||||
// http.DefaultTransport so it keeps the standard timeouts and connection pool.
|
||||
func defaultHTTPClient(proxy string) (*http.Client, error) {
|
||||
tr := http.DefaultTransport.(*http.Transport).Clone()
|
||||
if proxy == "" {
|
||||
tr.Proxy = http.ProxyFromEnvironment
|
||||
return &http.Client{Transport: tr}, nil
|
||||
}
|
||||
u, err := url.Parse(proxy)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("llm: invalid proxy %q: %w", proxy, err)
|
||||
}
|
||||
switch u.Scheme {
|
||||
case "http", "https", "socks5": // supported by net/http's Transport.Proxy
|
||||
case "":
|
||||
return nil, fmt.Errorf("llm: proxy %q missing scheme (use http://, https:// or socks5://)", proxy)
|
||||
default:
|
||||
return nil, fmt.Errorf("llm: unsupported proxy scheme %q (use http, https or socks5)", u.Scheme)
|
||||
}
|
||||
tr.Proxy = http.ProxyURL(u)
|
||||
return &http.Client{Transport: tr}, nil
|
||||
}
|
||||
|
||||
func envOr(key, def string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// joinSystem renders the system segments into a single string.
|
||||
func joinSystem(segs []string) string {
|
||||
parts := make([]string, 0, len(segs))
|
||||
for _, s := range segs {
|
||||
if s = strings.TrimSpace(s); s != "" {
|
||||
parts = append(parts, s)
|
||||
}
|
||||
}
|
||||
return strings.Join(parts, "\n\n")
|
||||
}
|
||||
Vendored
+160
@@ -0,0 +1,160 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"iter"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RateLimit configures a shared request-rate limit for a Provider. A window with
|
||||
// a zero value is unlimited. The limit is enforced across ALL callers that share
|
||||
// the same Provider instance (one limiter per provider), so any number of
|
||||
// concurrent agents using one Provider are bounded by a single limit.
|
||||
//
|
||||
// Only the logical request is counted: retries inside a single Stream call do
|
||||
// not consume additional tokens.
|
||||
type RateLimit struct {
|
||||
PerSecond float64 // max requests per second (0 = unlimited)
|
||||
PerMinute float64 // max requests per minute (0 = unlimited)
|
||||
// Burst is the per-second bucket capacity (how many may go at once before
|
||||
// smoothing). 0 = default to PerSecond.
|
||||
Burst float64
|
||||
// OnWait, when set, is called once per acquired request with how long the
|
||||
// caller blocked on the limiter (0 if it passed immediately). Observability
|
||||
// hook; nil disables it.
|
||||
OnWait func(blocked time.Duration)
|
||||
}
|
||||
|
||||
// rateLimiter enforces PerSecond AND PerMinute simultaneously. Safe for
|
||||
// concurrent use by many goroutines. A nil *rateLimiter is a no-op (unlimited).
|
||||
type rateLimiter struct {
|
||||
sec *bucket
|
||||
min *bucket
|
||||
onWait func(time.Duration)
|
||||
}
|
||||
|
||||
func newRateLimiter(rl RateLimit) *rateLimiter {
|
||||
if rl.PerSecond <= 0 && rl.PerMinute <= 0 {
|
||||
return nil // unlimited
|
||||
}
|
||||
l := &rateLimiter{onWait: rl.OnWait}
|
||||
if rl.PerSecond > 0 {
|
||||
burst := rl.Burst
|
||||
if burst <= 0 {
|
||||
burst = rl.PerSecond
|
||||
}
|
||||
l.sec = newBucket(rl.PerSecond, burst)
|
||||
}
|
||||
if rl.PerMinute > 0 {
|
||||
l.min = newBucket(rl.PerMinute/60.0, rl.PerMinute) // burst = a full minute
|
||||
}
|
||||
return l
|
||||
}
|
||||
|
||||
// Wait blocks until one request is permitted by both windows, or ctx is done.
|
||||
// A nil receiver returns immediately (unlimited).
|
||||
func (l *rateLimiter) Wait(ctx context.Context) error {
|
||||
if l == nil {
|
||||
return nil
|
||||
}
|
||||
var d time.Duration
|
||||
if l.sec != nil {
|
||||
d = l.sec.reserve()
|
||||
}
|
||||
if l.min != nil {
|
||||
if dm := l.min.reserve(); dm > d {
|
||||
d = dm
|
||||
}
|
||||
}
|
||||
if d <= 0 {
|
||||
l.report(0)
|
||||
return nil
|
||||
}
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
// The caller bailed; the reserved tokens are not returned (a minor
|
||||
// over-count under cancellation), which only makes the limiter slightly
|
||||
// more conservative — never less.
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
l.report(d)
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (l *rateLimiter) report(d time.Duration) {
|
||||
if l.onWait != nil {
|
||||
l.onWait(d)
|
||||
}
|
||||
}
|
||||
|
||||
// bucket is a token bucket: tokens refill at rate/sec up to burst; reserve()
|
||||
// takes one token (going negative to reserve future capacity) and returns how
|
||||
// long the caller must wait for it.
|
||||
type bucket struct {
|
||||
mu sync.Mutex
|
||||
rate float64 // tokens per second
|
||||
burst float64
|
||||
tokens float64
|
||||
last time.Time
|
||||
}
|
||||
|
||||
func newBucket(rate, burst float64) *bucket {
|
||||
return &bucket{rate: rate, burst: burst, tokens: burst, last: time.Now()}
|
||||
}
|
||||
|
||||
func (b *bucket) reserve() time.Duration {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
now := time.Now()
|
||||
b.tokens += now.Sub(b.last).Seconds() * b.rate
|
||||
if b.tokens > b.burst {
|
||||
b.tokens = b.burst
|
||||
}
|
||||
b.last = now
|
||||
b.tokens--
|
||||
if b.tokens >= 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(-b.tokens / b.rate * float64(time.Second))
|
||||
}
|
||||
|
||||
// RateLimited wraps any Provider so that all of its Stream calls share one rate
|
||||
// limit. Use it for custom Provider implementations; the built-in providers take
|
||||
// a RateLimit via Config. Returns p unchanged if rl imposes no limit.
|
||||
func RateLimited(p Provider, rl RateLimit) Provider {
|
||||
l := newRateLimiter(rl)
|
||||
if l == nil {
|
||||
return p
|
||||
}
|
||||
return &rateLimitedProvider{p: p, l: l}
|
||||
}
|
||||
|
||||
type rateLimitedProvider struct {
|
||||
p Provider
|
||||
l *rateLimiter
|
||||
}
|
||||
|
||||
func (rp *rateLimitedProvider) Stream(ctx context.Context, req CompletionRequest) iter.Seq2[StreamEvent, error] {
|
||||
return func(yield func(StreamEvent, error) bool) {
|
||||
if err := rp.l.Wait(ctx); err != nil {
|
||||
yield(StreamEvent{}, err)
|
||||
return
|
||||
}
|
||||
for ev, e := range rp.p.Stream(ctx, req) {
|
||||
if !yield(ev, e) {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (rp *rateLimitedProvider) Complete(ctx context.Context, req CompletionRequest) (Message, string, Usage, error) {
|
||||
if err := rp.l.Wait(ctx); err != nil {
|
||||
return Message{}, "", Usage{}, err
|
||||
}
|
||||
return rp.p.Complete(ctx, req)
|
||||
}
|
||||
Vendored
+101
@@ -0,0 +1,101 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// doStream sends the streaming request with retries on transient failures and
|
||||
// returns a 200 response (caller reads + closes the body). Only the request
|
||||
// establishment phase is retried — connection reset / timeout / 429 / 5xx before
|
||||
// any stream data is consumed — so retrying is safe (it can't duplicate
|
||||
// partially-streamed assistant output). A mid-stream drop is the caller's to
|
||||
// surface. Context cancellation is never retried and interrupts the backoff.
|
||||
// Count comes from cfg.retries(), the wait between attempts from
|
||||
// cfg.retryDelay() (exponential by default, fixed when Config.RetryInterval is set).
|
||||
func doStream(ctx context.Context, cfg Config, url string, body []byte, setHeaders func(*http.Request), errPrefix string) (*http.Response, error) {
|
||||
// Rate limit once per logical request (outside the retry loop, so retries do
|
||||
// not consume additional tokens). Shared across all callers of this provider.
|
||||
if err := cfg.limiter.Wait(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
retries := cfg.retries()
|
||||
for attempt := 0; ; attempt++ {
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
setHeaders(req)
|
||||
|
||||
resp, err := cfg.HTTPClient.Do(req)
|
||||
if err == nil && resp.StatusCode == http.StatusOK {
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
retryable := false
|
||||
switch {
|
||||
case err != nil:
|
||||
retryable = ctx.Err() == nil // transient network error (not cancellation)
|
||||
case isRetryableStatus(resp.StatusCode):
|
||||
retryable = true
|
||||
}
|
||||
if attempt >= retries || !retryable {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
return nil, fmt.Errorf("%s: status %d: %s", errPrefix, resp.StatusCode, strings.TrimSpace(string(data)))
|
||||
}
|
||||
if resp != nil {
|
||||
resp.Body.Close()
|
||||
}
|
||||
if !backoffSleep(ctx, cfg.retryDelay(attempt)) {
|
||||
return nil, ctx.Err() // context cancelled during backoff
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func isRetryableStatus(code int) bool {
|
||||
switch code {
|
||||
case http.StatusRequestTimeout, // 408
|
||||
http.StatusTooManyRequests, // 429
|
||||
http.StatusInternalServerError, // 500
|
||||
http.StatusBadGateway, // 502
|
||||
http.StatusServiceUnavailable, // 503
|
||||
http.StatusGatewayTimeout: // 504
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// expBackoff is the default retry ladder: 0.5s, 1s, 2s, … capped at 8s. Used
|
||||
// whenever the caller did not pin a fixed interval on the Config.
|
||||
func expBackoff(attempt int) time.Duration {
|
||||
d := 500 * time.Millisecond * (1 << attempt)
|
||||
if d > 8*time.Second {
|
||||
d = 8 * time.Second
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// backoffSleep waits d, interruptible by ctx. Returns false if the context was
|
||||
// cancelled (or d is non-positive, which never happens for a real wait).
|
||||
func backoffSleep(ctx context.Context, d time.Duration) bool {
|
||||
if d <= 0 {
|
||||
return ctx.Err() == nil
|
||||
}
|
||||
t := time.NewTimer(d)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return false
|
||||
case <-t.C:
|
||||
return true
|
||||
}
|
||||
}
|
||||
+122
@@ -0,0 +1,122 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// An unset Config keeps the historical defaults: 3 establishment retries on the
|
||||
// exponential ladder, 2 empty-response retries on the same ladder.
|
||||
func TestRetryDefaultsUnchanged(t *testing.T) {
|
||||
var c Config
|
||||
if got := c.retries(); got != 3 {
|
||||
t.Fatalf("retries=%d, want 3", got)
|
||||
}
|
||||
if got := c.emptyRetries(); got != emptyResponseRetries {
|
||||
t.Fatalf("emptyRetries=%d, want %d", got, emptyResponseRetries)
|
||||
}
|
||||
for attempt, want := range []time.Duration{500 * time.Millisecond, time.Second, 2 * time.Second, 8 * time.Second} {
|
||||
a := attempt
|
||||
if a == 3 {
|
||||
a = 5 // past the cap
|
||||
}
|
||||
if got := c.retryDelay(a); got != want {
|
||||
t.Fatalf("retryDelay(%d)=%v, want %v", a, got, want)
|
||||
}
|
||||
if got := c.emptyRetryDelay(a); got != want {
|
||||
t.Fatalf("emptyRetryDelay(%d)=%v, want %v", a, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A configured interval replaces the ladder with a FIXED wait, on both knobs,
|
||||
// and negative counts disable the respective retry entirely.
|
||||
func TestRetryFixedIntervalAndDisable(t *testing.T) {
|
||||
c := Config{
|
||||
MaxRetries: 5, RetryInterval: 250 * time.Millisecond,
|
||||
EmptyResponseRetries: -1, EmptyResponseInterval: 700 * time.Millisecond,
|
||||
}
|
||||
if got := c.retries(); got != 5 {
|
||||
t.Fatalf("retries=%d, want 5", got)
|
||||
}
|
||||
if got := c.emptyRetries(); got != 0 {
|
||||
t.Fatalf("emptyRetries=%d, want 0 (disabled)", got)
|
||||
}
|
||||
for _, attempt := range []int{0, 1, 7} {
|
||||
if got := c.retryDelay(attempt); got != 250*time.Millisecond {
|
||||
t.Fatalf("retryDelay(%d)=%v, want fixed 250ms", attempt, got)
|
||||
}
|
||||
if got := c.emptyRetryDelay(attempt); got != 700*time.Millisecond {
|
||||
t.Fatalf("emptyRetryDelay(%d)=%v, want fixed 700ms", attempt, got)
|
||||
}
|
||||
}
|
||||
if got := (Config{MaxRetries: -1}).retries(); got != 0 {
|
||||
t.Fatalf("retries=%d, want 0 (disabled)", got)
|
||||
}
|
||||
}
|
||||
|
||||
// MaxRetries bounds the establishment attempts end to end: a server that always
|
||||
// 503s is hit exactly MaxRetries+1 times, and the fixed interval keeps the test
|
||||
// fast (the default ladder would spend 0.5+1+2s here).
|
||||
func TestDoStreamHonorsConfiguredRetries(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg := Config{
|
||||
Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m",
|
||||
MaxRetries: 1, RetryInterval: time.Millisecond,
|
||||
}
|
||||
if _, err := doStream(context.Background(), cfg, srv.URL, []byte(`{}`), func(*http.Request) {}, "openai"); err == nil {
|
||||
t.Fatal("want error after retries are exhausted")
|
||||
}
|
||||
if calls.Load() != 2 {
|
||||
t.Fatalf("calls=%d, want 2 (1 attempt + 1 retry)", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// EmptyResponseRetries bounds the empty-completion re-requests; the fixed
|
||||
// interval applies between them.
|
||||
func TestOpenAIStreamHonorsConfiguredEmptyRetries(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Write([]byte(emptyStop))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{
|
||||
Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m",
|
||||
EmptyResponseRetries: 4, EmptyResponseInterval: time.Millisecond,
|
||||
})
|
||||
msg := collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if len(msg.Content) != 0 {
|
||||
t.Fatalf("want empty message after exhaustion, got %+v", msg.Content)
|
||||
}
|
||||
if calls.Load() != 5 {
|
||||
t.Fatalf("calls=%d, want 5 (1 attempt + 4 retries)", calls.Load())
|
||||
}
|
||||
}
|
||||
|
||||
// A disabled empty-response retry surfaces the first empty completion as-is.
|
||||
func TestOpenAIStreamEmptyRetryDisabled(t *testing.T) {
|
||||
var calls atomic.Int32
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls.Add(1)
|
||||
w.Write([]byte(emptyStop))
|
||||
}))
|
||||
defer srv.Close()
|
||||
p, _ := NewProvider(Config{
|
||||
Format: FormatOpenAI, BaseURL: srv.URL, APIKey: "k", Model: "m",
|
||||
EmptyResponseRetries: -1,
|
||||
})
|
||||
collect(t, p, CompletionRequest{Messages: []Message{UserText("go")}})
|
||||
if calls.Load() != 1 {
|
||||
t.Fatalf("calls=%d, want 1 (retry disabled)", calls.Load())
|
||||
}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func oaCall(id string) oaToolCall {
|
||||
tc := oaToolCall{ID: id, Type: "function"}
|
||||
tc.Function.Name = "Read"
|
||||
tc.Function.Arguments = "{}"
|
||||
return tc
|
||||
}
|
||||
|
||||
func countRole(msgs []oaMessage, role string) int {
|
||||
n := 0
|
||||
for _, m := range msgs {
|
||||
if m.Role == role {
|
||||
n++
|
||||
}
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// An assistant message carrying a tool_call with no matching role:tool response
|
||||
// is what a half-covered compaction leaves behind; the unanswered call must go
|
||||
// so the provider does not 400 with "tool_calls must be followed by tool
|
||||
// messages".
|
||||
func TestSanitizeDropsUnansweredToolCall(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "assistant", ToolCalls: []oaToolCall{oaCall("a"), oaCall("b")}},
|
||||
{Role: "tool", ToolCallID: "a", Content: "ok"},
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, false)
|
||||
if len(got[0].ToolCalls) != 1 || got[0].ToolCalls[0].ID != "a" {
|
||||
t.Fatalf("assistant tool_calls = %+v, want only the answered call a", got[0].ToolCalls)
|
||||
}
|
||||
if countRole(got, "tool") != 1 {
|
||||
t.Fatalf("tool messages = %d, want 1", countRole(got, "tool"))
|
||||
}
|
||||
}
|
||||
|
||||
// A role:tool message whose call is gone (its assistant turn was compressed
|
||||
// away) is an orphan a strict provider also rejects.
|
||||
func TestSanitizeDropsOrphanToolResult(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "assistant", Content: "hi"},
|
||||
{Role: "tool", ToolCallID: "ghost", Content: "stale"},
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, false)
|
||||
if countRole(got, "tool") != 0 {
|
||||
t.Fatalf("orphan tool result survived: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
// In thinking mode an assistant turn replaying tool_calls must carry
|
||||
// reasoning_content; when it was lost upstream the guard fills a placeholder
|
||||
// rather than let the request fail.
|
||||
func TestSanitizeFillsReasoningInThinkingMode(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "assistant", ToolCalls: []oaToolCall{oaCall("a")}},
|
||||
{Role: "tool", ToolCallID: "a", Content: "ok"},
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, true)
|
||||
if got[0].ReasoningContent == "" {
|
||||
t.Fatalf("thinking-mode assistant with tool_calls must carry reasoning_content")
|
||||
}
|
||||
}
|
||||
|
||||
// The placeholder is a thinking-mode-only concession: without thinking, a
|
||||
// content-less tool_calls turn is valid and must be left as it is.
|
||||
func TestSanitizeNoReasoningFillWhenNotThinking(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "assistant", ToolCalls: []oaToolCall{oaCall("a")}},
|
||||
{Role: "tool", ToolCallID: "a", Content: "ok"},
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, false)
|
||||
if got[0].ReasoningContent != "" {
|
||||
t.Fatalf("reasoning_content = %q, want empty when not in thinking mode", got[0].ReasoningContent)
|
||||
}
|
||||
}
|
||||
|
||||
// An assistant message emptied by dropping its only (unanswered) tool_call would
|
||||
// serialize to a bare {"role":"assistant"} and 400; it must gain placeholder
|
||||
// content instead.
|
||||
func TestSanitizeEmptiedAssistantGainsContent(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "assistant", ToolCalls: []oaToolCall{oaCall("a")}}, // no tool response
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, false)
|
||||
if len(got[0].ToolCalls) != 0 {
|
||||
t.Fatalf("unanswered call survived: %+v", got[0].ToolCalls)
|
||||
}
|
||||
if got[0].Content == "" {
|
||||
t.Fatalf("emptied assistant has no content — would serialize to a bare assistant message")
|
||||
}
|
||||
}
|
||||
|
||||
// A well-formed transcript must pass through untouched: pairs intact, real
|
||||
// reasoning_content preserved, nothing added or removed.
|
||||
func TestSanitizeLeavesValidTranscriptIntact(t *testing.T) {
|
||||
msgs := []oaMessage{
|
||||
{Role: "user", Content: "task"},
|
||||
{Role: "assistant", ReasoningContent: "real thinking", ToolCalls: []oaToolCall{oaCall("a")}},
|
||||
{Role: "tool", ToolCallID: "a", Content: "ok"},
|
||||
{Role: "assistant", Content: "done"},
|
||||
}
|
||||
got := sanitizeOpenAIMessages(msgs, true)
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("len = %d, want 4 (nothing dropped): %+v", len(got), got)
|
||||
}
|
||||
if got[1].ReasoningContent != "real thinking" {
|
||||
t.Fatalf("real reasoning_content was clobbered: %q", got[1].ReasoningContent)
|
||||
}
|
||||
if len(got[1].ToolCalls) != 1 {
|
||||
t.Fatalf("valid tool_call was dropped: %+v", got[1].ToolCalls)
|
||||
}
|
||||
}
|
||||
|
||||
// End-to-end: the two failures from issue #174 in one transcript — an unanswered
|
||||
// tool_call and a thinking turn that lost its reasoning — both repaired by the
|
||||
// guard reached through buildBody.
|
||||
func TestBuildBodyAppliesSendGuard(t *testing.T) {
|
||||
p := &openaiProvider{cfg: Config{Model: "glm-4.6", ThinkingType: "enabled"}}
|
||||
req := CompletionRequest{
|
||||
Messages: []Message{
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockToolUse, ID: "x", Name: "Read", Input: []byte(`{}`)},
|
||||
}},
|
||||
// No tool_result for "x" — the half-covered case.
|
||||
UserText("continue"),
|
||||
},
|
||||
}
|
||||
raw, err := p.buildBody(req, false)
|
||||
if err != nil {
|
||||
t.Fatalf("buildBody: %v", err)
|
||||
}
|
||||
s := string(raw)
|
||||
// The unanswered tool_call must not reach the wire.
|
||||
if strings.Contains(s, `"tool_calls"`) {
|
||||
t.Fatalf("unanswered tool_call was sent: %s", s)
|
||||
}
|
||||
}
|
||||
Vendored
+87
@@ -0,0 +1,87 @@
|
||||
package llm
|
||||
|
||||
import "strings"
|
||||
|
||||
// Skill-invocation messages carry an invoked skill's full instructions in the
|
||||
// conversation as an independent user message (not a tool_result), wrapped in a
|
||||
// <system-reminder> so the model reads them as standing guidance. They are
|
||||
// self-identifying via the <invoked-skill …> envelope so compaction can find the
|
||||
// latest invocation of each skill in the retained (non-destructive) history and
|
||||
// re-inject it verbatim after a summary boundary — keeping skill instructions
|
||||
// alive across compactions even though the transcript copy gets summarized.
|
||||
|
||||
const (
|
||||
skillReminderLead = "The following skill was invoked in this session. Continue to follow these guidelines:"
|
||||
skillOpenPrefix = "<invoked-skill name=\""
|
||||
skillFooter = "\n</invoked-skill>\n</system-reminder>"
|
||||
skillTruncNote = "\n…[skill instructions truncated to save context — re-read the skill's base directory for the full text]"
|
||||
)
|
||||
|
||||
// SkillInvocationMessage builds the independent user message that carries a
|
||||
// skill's instructions. name is required; path (the skill's base directory) is
|
||||
// optional and, when present, is surfaced both as an attribute (for detection)
|
||||
// and as a human-readable "Base directory:" line. body is the instructions plus
|
||||
// any caller-supplied context.
|
||||
func SkillInvocationMessage(name, path, body string) Message {
|
||||
var b strings.Builder
|
||||
b.WriteString("<system-reminder>\n")
|
||||
b.WriteString(skillReminderLead)
|
||||
b.WriteString("\n\n")
|
||||
b.WriteString(skillOpenPrefix)
|
||||
b.WriteString(name)
|
||||
b.WriteString("\"")
|
||||
if path != "" {
|
||||
b.WriteString(" path=\"")
|
||||
b.WriteString(path)
|
||||
b.WriteString("\"")
|
||||
}
|
||||
b.WriteString(">\n")
|
||||
if path != "" {
|
||||
b.WriteString("Base directory: ")
|
||||
b.WriteString(path)
|
||||
b.WriteString("\n\n")
|
||||
}
|
||||
b.WriteString(body)
|
||||
b.WriteString(skillFooter)
|
||||
return Message{Role: RoleUser, Content: []ContentBlock{TextBlock(b.String())}}
|
||||
}
|
||||
|
||||
// SkillInvocationName reports whether m is a skill-invocation message and, if so,
|
||||
// returns the invoked skill's name (used by compaction to dedupe to the latest
|
||||
// invocation per skill).
|
||||
func SkillInvocationName(m Message) (string, bool) {
|
||||
if m.Role != RoleUser || len(m.Content) != 1 || m.Content[0].Type != BlockText {
|
||||
return "", false
|
||||
}
|
||||
_, rest, ok := strings.Cut(m.Content[0].Text, skillOpenPrefix)
|
||||
if !ok {
|
||||
return "", false
|
||||
}
|
||||
name, _, ok := strings.Cut(rest, "\"")
|
||||
if !ok || name == "" {
|
||||
return "", false
|
||||
}
|
||||
return name, true
|
||||
}
|
||||
|
||||
// TruncateSkillMessage returns m with its instructions body clipped so the whole
|
||||
// message stays within roughly maxChars, preserving the envelope tags and
|
||||
// appending a truncation note. Messages already within budget are returned
|
||||
// unchanged.
|
||||
func TruncateSkillMessage(m Message, maxChars int) Message {
|
||||
if maxChars <= 0 || len(m.Content) != 1 || m.Content[0].Type != BlockText {
|
||||
return m
|
||||
}
|
||||
text := m.Content[0].Text
|
||||
if len(text) <= maxChars {
|
||||
return m
|
||||
}
|
||||
head := text
|
||||
if k := strings.LastIndex(text, skillFooter); k >= 0 {
|
||||
head = text[:k] // header + open tag + body, without the footer
|
||||
}
|
||||
if len(head) > maxChars {
|
||||
head = head[:maxChars]
|
||||
}
|
||||
return Message{Role: m.Role, Content: []ContentBlock{TextBlock(head + skillTruncNote + skillFooter)}}
|
||||
}
|
||||
Vendored
+52
@@ -0,0 +1,52 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// sseScanner reads Server-Sent Events from a response body, yielding the
|
||||
// (event, data) pair of each message. Anthropic uses named events; OpenAI uses
|
||||
// bare data lines. Both are handled.
|
||||
type sseScanner struct {
|
||||
r *bufio.Reader
|
||||
}
|
||||
|
||||
func newSSEScanner(body io.Reader) *sseScanner {
|
||||
return &sseScanner{r: bufio.NewReaderSize(body, 64*1024)}
|
||||
}
|
||||
|
||||
// next returns the next event's (type, data). event is "" for bare-data streams.
|
||||
// Returns io.EOF at end of stream.
|
||||
func (s *sseScanner) next() (event, data string, err error) {
|
||||
var buf bytes.Buffer
|
||||
for {
|
||||
line, rerr := s.r.ReadString('\n')
|
||||
if rerr != nil {
|
||||
if rerr == io.EOF && (buf.Len() > 0 || event != "") {
|
||||
return event, strings.TrimRight(buf.String(), "\n"), nil
|
||||
}
|
||||
return "", "", rerr
|
||||
}
|
||||
line = strings.TrimRight(line, "\r\n")
|
||||
if line == "" {
|
||||
if buf.Len() > 0 || event != "" {
|
||||
return event, strings.TrimRight(buf.String(), "\n"), nil
|
||||
}
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case strings.HasPrefix(line, "event:"):
|
||||
event = strings.TrimSpace(line[len("event:"):])
|
||||
case strings.HasPrefix(line, "data:"):
|
||||
d := line[len("data:"):]
|
||||
d = strings.TrimPrefix(d, " ")
|
||||
buf.WriteString(d)
|
||||
buf.WriteByte('\n')
|
||||
default:
|
||||
// comment / unknown field — ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
+114
@@ -0,0 +1,114 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// captureReq runs one arbitrary request and returns the raw + parsed request body.
|
||||
func captureReq(t *testing.T, cfg Config, req CompletionRequest, stub string) (string, map[string]any) {
|
||||
t.Helper()
|
||||
var raw []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
raw, _ = io.ReadAll(r.Body)
|
||||
w.Write([]byte(stub))
|
||||
}))
|
||||
defer srv.Close()
|
||||
cfg.BaseURL, cfg.APIKey, cfg.Model = srv.URL, "k", "m"
|
||||
p, err := NewProvider(cfg)
|
||||
if err != nil {
|
||||
t.Fatalf("NewProvider: %v", err)
|
||||
}
|
||||
collect(t, p, req)
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(raw, &m); err != nil {
|
||||
t.Fatalf("unmarshal: %v\n%s", err, raw)
|
||||
}
|
||||
return string(raw), m
|
||||
}
|
||||
|
||||
func thinkingType(m map[string]any) string {
|
||||
if th, ok := m["thinking"].(map[string]any); ok {
|
||||
s, _ := th["type"].(string)
|
||||
return s
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// A per-request Thinking="disabled" override must win over an enabled config AND
|
||||
// strip replayed thinking blocks (Anthropic rejects them when thinking is off).
|
||||
func TestAnthropicPerRequestThinkingDisabledStrips(t *testing.T) {
|
||||
stub := sse(`data: {"type":"message_stop"}`, ``)
|
||||
req := CompletionRequest{
|
||||
Thinking: "disabled",
|
||||
Messages: []Message{
|
||||
UserText("hi"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{
|
||||
{Type: BlockThinking, Thinking: "SECRET_THOUGHT"},
|
||||
TextBlock("answer"),
|
||||
}},
|
||||
},
|
||||
}
|
||||
raw, m := captureReq(t, Config{Format: FormatAnthropic, ThinkingType: "enabled"}, req, stub)
|
||||
if thinkingType(m) != "disabled" {
|
||||
t.Fatalf("override should force disabled, got %q", thinkingType(m))
|
||||
}
|
||||
if strings.Contains(raw, "SECRET_THOUGHT") {
|
||||
t.Fatal("thinking block must be stripped when thinking is disabled")
|
||||
}
|
||||
if !strings.Contains(raw, "answer") {
|
||||
t.Fatal("sibling text block should survive")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicPerRequestThinkingEnabledKeeps(t *testing.T) {
|
||||
stub := sse(`data: {"type":"message_stop"}`, ``)
|
||||
req := CompletionRequest{
|
||||
Thinking: "enabled",
|
||||
Messages: []Message{
|
||||
{Role: RoleAssistant, Content: []ContentBlock{{Type: BlockThinking, Thinking: "KEPT_THOUGHT", Signature: "s"}, TextBlock("a")}},
|
||||
},
|
||||
}
|
||||
raw, m := captureReq(t, Config{Format: FormatAnthropic}, req, stub) // cfg thinking unset
|
||||
if thinkingType(m) != "enabled" {
|
||||
t.Fatalf("override should force enabled, got %q", thinkingType(m))
|
||||
}
|
||||
if !strings.Contains(raw, "KEPT_THOUGHT") {
|
||||
t.Fatal("thinking block should be replayed when enabled")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnthropicThinkingInheritsConfigWhenUnset(t *testing.T) {
|
||||
stub := sse(`data: {"type":"message_stop"}`, ``)
|
||||
req := CompletionRequest{Messages: []Message{UserText("hi")}} // Thinking == ""
|
||||
_, m := captureReq(t, Config{Format: FormatAnthropic, ThinkingType: "enabled"}, req, stub)
|
||||
if thinkingType(m) != "enabled" {
|
||||
t.Fatalf("empty override should inherit config, got %q", thinkingType(m))
|
||||
}
|
||||
// And with config also unset, thinking is omitted entirely.
|
||||
_, m2 := captureReq(t, Config{Format: FormatAnthropic}, req, stub)
|
||||
if _, ok := m2["thinking"]; ok {
|
||||
t.Fatalf("thinking should be omitted, got %v", m2["thinking"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenAIPerRequestThinkingOverride(t *testing.T) {
|
||||
// A non-empty stub: an empty completion would trip the empty-response retry
|
||||
// (this test only inspects the request body, so give it minimal content).
|
||||
stub := sse(`data: {"choices":[{"index":0,"delta":{"content":"ok"}}]}`, ``, `data: [DONE]`, ``)
|
||||
req := CompletionRequest{Thinking: "disabled", Messages: []Message{UserText("hi")}}
|
||||
_, m := captureReq(t, Config{Format: FormatOpenAI, ThinkingType: "enabled"}, req, stub)
|
||||
if thinkingType(m) != "disabled" {
|
||||
t.Fatalf("override should force disabled, got %q", thinkingType(m))
|
||||
}
|
||||
// Empty override inherits config.
|
||||
req2 := CompletionRequest{Messages: []Message{UserText("hi")}}
|
||||
_, m2 := captureReq(t, Config{Format: FormatOpenAI, ThinkingType: "enabled"}, req2, stub)
|
||||
if thinkingType(m2) != "enabled" {
|
||||
t.Fatalf("empty override should inherit config, got %q", thinkingType(m2))
|
||||
}
|
||||
}
|
||||
Vendored
+36
@@ -0,0 +1,36 @@
|
||||
package llm
|
||||
|
||||
import "strings"
|
||||
|
||||
// Todo-reminder messages re-surface the current todo list as standing guidance
|
||||
// when the model hasn't touched TodoWrite in a while. Like the skill-invocation
|
||||
// message, it is a self-identifying <system-reminder> user message: the harness
|
||||
// derives its throttle ("turns since last reminder") by scanning history for it,
|
||||
// and it is regenerated from live state each eligible turn so it survives
|
||||
// compaction. Mirrors claude-code's todo_reminder attachment.
|
||||
|
||||
// todoReminderLead is the fixed nag text — also the detection sentinel (a normal
|
||||
// user message is exceedingly unlikely to contain this exact system phrasing).
|
||||
const todoReminderLead = "The TodoWrite tool hasn't been used recently. If you're working on tasks that would benefit from tracking progress, consider using the TodoWrite tool to track progress. Also consider cleaning up the todo list if it has become stale and no longer matches what you are working on. Only use it if it's relevant to the current work. This is just a gentle reminder - ignore if not applicable. Make sure that you NEVER mention this reminder to the user."
|
||||
|
||||
// TodoReminderMessage builds the <system-reminder> user message carrying the
|
||||
// current todo list. listText is the rendered list (see tool.RenderTodoReminder).
|
||||
func TodoReminderMessage(listText string) Message {
|
||||
var b strings.Builder
|
||||
b.WriteString("<system-reminder>\n")
|
||||
b.WriteString(todoReminderLead)
|
||||
b.WriteString("\n\nHere are the existing contents of your todo list:\n\n")
|
||||
b.WriteString(listText)
|
||||
b.WriteString("\n</system-reminder>")
|
||||
return Message{Role: RoleUser, Content: []ContentBlock{TextBlock(b.String())}}
|
||||
}
|
||||
|
||||
// IsTodoReminder reports whether m is a todo-reminder message (used to derive the
|
||||
// throttle "turns since last reminder").
|
||||
func IsTodoReminder(m Message) bool {
|
||||
if m.Role != RoleUser || len(m.Content) != 1 || m.Content[0].Type != BlockText {
|
||||
return false
|
||||
}
|
||||
t := m.Content[0].Text
|
||||
return strings.HasPrefix(t, "<system-reminder>") && strings.Contains(t, todoReminderLead)
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package llm
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTodoReminderMessageRoundTrip(t *testing.T) {
|
||||
m := TodoReminderMessage("1. [in_progress] build\n2. [pending] test")
|
||||
if m.Role != RoleUser {
|
||||
t.Fatalf("todo reminder must be a user message, got %q", m.Role)
|
||||
}
|
||||
if !strings.HasPrefix(m.Text(), "<system-reminder>") {
|
||||
t.Fatalf("must be wrapped in <system-reminder>: %q", m.Text())
|
||||
}
|
||||
if !strings.Contains(m.Text(), "build") || !strings.Contains(m.Text(), "test") {
|
||||
t.Fatalf("list content missing: %q", m.Text())
|
||||
}
|
||||
if !IsTodoReminder(m) {
|
||||
t.Fatal("IsTodoReminder should detect its own message")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsTodoReminderNoFalsePositive(t *testing.T) {
|
||||
// Ordinary user text, a plain system-reminder, and an assistant message must
|
||||
// not be mistaken for a todo reminder.
|
||||
cases := []Message{
|
||||
UserText("please update the todo list"),
|
||||
UserText("<system-reminder>\n# currentDate\nToday is 2026-01-01.\n</system-reminder>"),
|
||||
{Role: RoleAssistant, Content: []ContentBlock{TextBlock("<system-reminder>...</system-reminder>")}},
|
||||
}
|
||||
for i, m := range cases {
|
||||
if IsTodoReminder(m) {
|
||||
t.Fatalf("case %d falsely detected as todo reminder: %q", i, m.Text())
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
// Package llm defines a vendor-neutral message model and a pluggable Provider
|
||||
// interface, with adapters that speak the Anthropic Messages API and the OpenAI
|
||||
// Chat Completions API. The internal model mirrors Anthropic's content-block
|
||||
// shape (the richer superset, including thinking and structured tool results);
|
||||
// the OpenAI adapter translates at its boundary. This lets the harness be
|
||||
// written once against a single representation while remaining compatible with
|
||||
// any model reachable through either wire format.
|
||||
package llm
|
||||
|
||||
import "encoding/json"
|
||||
|
||||
// Role identifies the author of a message.
|
||||
type Role string
|
||||
|
||||
const (
|
||||
RoleUser Role = "user"
|
||||
RoleAssistant Role = "assistant"
|
||||
)
|
||||
|
||||
// BlockType enumerates the kinds of content a message block may carry.
|
||||
type BlockType string
|
||||
|
||||
const (
|
||||
BlockText BlockType = "text"
|
||||
BlockThinking BlockType = "thinking"
|
||||
BlockToolUse BlockType = "tool_use"
|
||||
BlockToolResult BlockType = "tool_result"
|
||||
)
|
||||
|
||||
// ContentBlock is one piece of message content. Which fields are populated
|
||||
// depends on Type. This is the Anthropic content-block union.
|
||||
type ContentBlock struct {
|
||||
Type BlockType `json:"type"`
|
||||
|
||||
// Text block.
|
||||
Text string `json:"text,omitempty"`
|
||||
|
||||
// Thinking block (extended thinking). Anthropic requires the field to be
|
||||
// named "thinking" (not "text") and requires "signature" when replaying
|
||||
// the block in multi-turn history.
|
||||
Thinking string `json:"thinking,omitempty"`
|
||||
Signature string `json:"signature,omitempty"`
|
||||
|
||||
// ToolUse: a model request to invoke a tool.
|
||||
ID string `json:"id,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
Input json.RawMessage `json:"input,omitempty"`
|
||||
|
||||
// ToolResult: the outcome of a tool, fed back to the model.
|
||||
ToolUseID string `json:"tool_use_id,omitempty"`
|
||||
Content []ContentBlock `json:"content,omitempty"`
|
||||
IsError bool `json:"is_error,omitempty"`
|
||||
}
|
||||
|
||||
// TextBlock builds a text content block.
|
||||
func TextBlock(s string) ContentBlock { return ContentBlock{Type: BlockText, Text: s} }
|
||||
|
||||
// ToolResultText builds a tool_result block carrying a single text block.
|
||||
func ToolResultText(toolUseID, text string, isError bool) ContentBlock {
|
||||
return ContentBlock{
|
||||
Type: BlockToolResult,
|
||||
ToolUseID: toolUseID,
|
||||
Content: []ContentBlock{TextBlock(text)},
|
||||
IsError: isError,
|
||||
}
|
||||
}
|
||||
|
||||
// Message is a single conversation turn.
|
||||
type Message struct {
|
||||
Role Role `json:"role"`
|
||||
Content []ContentBlock `json:"content"`
|
||||
}
|
||||
|
||||
// UserText builds a user message with one text block.
|
||||
func UserText(s string) Message {
|
||||
return Message{Role: RoleUser, Content: []ContentBlock{TextBlock(s)}}
|
||||
}
|
||||
|
||||
// ToolUses returns the tool_use blocks of a message.
|
||||
func (m Message) ToolUses() []ContentBlock {
|
||||
var out []ContentBlock
|
||||
for _, b := range m.Content {
|
||||
if b.Type == BlockToolUse {
|
||||
out = append(out, b)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Text concatenates all text blocks of a message.
|
||||
func (m Message) Text() string {
|
||||
var s string
|
||||
for _, b := range m.Content {
|
||||
if b.Type == BlockText {
|
||||
s += b.Text
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
// Usage reports token accounting, including prompt-cache tokens (FR-03.8).
|
||||
type Usage struct {
|
||||
InputTokens int `json:"input_tokens"`
|
||||
OutputTokens int `json:"output_tokens"`
|
||||
CacheReadTokens int `json:"cache_read_tokens"`
|
||||
CacheWriteTokens int `json:"cache_write_tokens"`
|
||||
}
|
||||
|
||||
// Add accumulates token counts from another Usage.
|
||||
func (u *Usage) Add(o Usage) {
|
||||
u.InputTokens += o.InputTokens
|
||||
u.OutputTokens += o.OutputTokens
|
||||
u.CacheReadTokens += o.CacheReadTokens
|
||||
u.CacheWriteTokens += o.CacheWriteTokens
|
||||
}
|
||||
|
||||
// ToolSchema is a tool definition exposed to the model.
|
||||
type ToolSchema struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
InputSchema map[string]any `json:"input_schema"`
|
||||
}
|
||||
|
||||
// CompletionRequest is a single, provider-neutral model invocation.
|
||||
type CompletionRequest struct {
|
||||
// System is the host-controlled system prompt, in segments. The SDK injects
|
||||
// no presets (design decision 1). Segments are joined with blank lines.
|
||||
System []string
|
||||
// DynamicBoundary is the index in System separating cacheable static prefix
|
||||
// from per-request dynamic content; providers may set a cache breakpoint
|
||||
// there (FR-02.2). 0 disables.
|
||||
DynamicBoundary int
|
||||
Messages []Message
|
||||
Tools []ToolSchema
|
||||
MaxTokens int
|
||||
Temperature *float64
|
||||
Stop []string
|
||||
// Thinking overrides the provider's thinking mode for THIS request only:
|
||||
// "" inherits Config.ThinkingType; "enabled"/"disabled" force that mode.
|
||||
// Compaction's summary call sets "disabled" so the summarizer never spends
|
||||
// tokens on reasoning and never replays thinking blocks (which Anthropic
|
||||
// rejects when thinking is off).
|
||||
Thinking string
|
||||
}
|
||||
Reference in new issue
Block a user