1 Commits
Author SHA1 Message Date
sausheong 3ca0994437 Reject empty and truncated answers and expose complete tool calls 2026-09-11 23:48:25 +08:00
14 changed files with 278 additions and 7 deletions

No files matched your search

+6
View File
@@ -119,6 +119,7 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
}
var sb strings.Builder
var terminalReason string
for ev := range stream {
switch ev.Type {
case llm.EventTextDelta:
@@ -126,6 +127,8 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
return "", errors.New("summariser response exceeds 256 KiB")
}
sb.WriteString(ev.Text)
case llm.EventDone:
terminalReason = ev.StopReason
case llm.EventError:
return "", fmt.Errorf("compaction: stream error: %w", ev.Error)
}
@@ -133,6 +136,9 @@ func (s *Summarizer) callOnce(ctx context.Context, transcript, additionalInstruc
if err := callCtx.Err(); err != nil {
return "", err
}
if terminalReason == "length" || terminalReason == "max_tokens" {
return "", errors.New("summariser reached its output limit; original history retained")
}
out := strings.TrimSpace(sb.String())
if out == "" {
return "", ErrEmptySummary
+26
View File
@@ -0,0 +1,26 @@
package compaction
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"strings"
"testing"
)
type truncatedSummaryProvider struct{ llmtest.Base }
func (truncatedSummaryProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Incomplete summary"}
ch <- llm.ChatEvent{Type: llm.EventDone, StopReason: "length"}
close(ch)
return ch, nil
}
func TestRejectTruncatedSummary(t *testing.T) {
s := Summarizer{Provider: truncatedSummaryProvider{}, Model: "fixture"}
out, err := s.callOnce(context.Background(), "history", "")
if err == nil || out != "" || !strings.Contains(err.Error(), "output limit") {
t.Fatalf("%q %v", out, err)
}
}
+42
View File
@@ -0,0 +1,42 @@
package openai
import (
"context"
"fmt"
"github.com/sausheong/harness/llm"
"net/http"
"net/http/httptest"
"testing"
)
func TestPreservesOutputLimitAndTrailingUsage(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
fmt.Fprint(w, `data: {"choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"partial","type":"function","function":{"name":"bash","arguments":"{\"command\":"}}]},"finish_reason":"length"}]}`+"\n\n")
fmt.Fprint(w, `data: {"choices":[],"usage":{"prompt_tokens":50,"completion_tokens":2048,"total_tokens":2098}}`+"\n\ndata: [DONE]\n\n")
}))
defer srv.Close()
p := NewOpenAIProviderWithKind("fixture", srv.URL, "openai-compatible")
events, err := p.ChatStream(context.Background(), llm.ChatRequest{Model: "fixture"})
if err != nil {
t.Fatal(err)
}
found := false
for e := range events {
if e.Type == llm.EventToolCallDone {
t.Fatal("truncated tool accepted")
}
if e.Type == llm.EventError {
t.Fatal(e.Error)
}
if e.Type == llm.EventDone {
found = true
if e.StopReason != "length" || e.Usage == nil || e.Usage.OutputTokens != 2048 {
t.Fatalf("%+v", e)
}
}
}
if !found {
t.Fatal("missing terminal event")
}
}
+5 -1
View File
@@ -274,6 +274,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
toolCalls := make(map[int]*pendingTC)
var lastUsage *llm.Usage
var finishReason string
for {
resp, err := stream.Recv()
@@ -337,6 +338,9 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
// Finish reason
if choice.FinishReason != "" {
finishReason = string(choice.FinishReason)
}
if choice.FinishReason == openai.FinishReasonToolCalls || choice.FinishReason == openai.FinishReasonStop {
emitToolCalls(events, toolCalls)
clear(toolCalls)
@@ -344,7 +348,7 @@ func (p *OpenAIProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<
}
}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage}
events <- llm.ChatEvent{Type: llm.EventDone, Usage: lastUsage, StopReason: finishReason}
}()
return events, nil
+2 -1
View File
@@ -24,7 +24,8 @@ func (p *attachmentReplayProvider) ChatStream(_ context.Context, req llm.ChatReq
for _, msg := range req.Messages {
p.images = append(p.images, msg.Images...)
}
events := make(chan llm.ChatEvent, 1)
events := make(chan llm.ChatEvent, 2)
events <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
events <- llm.ChatEvent{Type: llm.EventDone}
close(events)
return events, nil
+95
View File
@@ -0,0 +1,95 @@
package runtime
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/llm/llmtest"
"github.com/sausheong/harness/session"
"strings"
"testing"
)
type emptyResponseProvider struct {
llmtest.Base
responses [][]llm.ChatEvent
calls int
limits []int
}
func (p *emptyResponseProvider) ChatStream(ctx context.Context, req llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.limits = append(p.limits, req.MaxTokens)
i := min(p.calls, len(p.responses)-1)
p.calls++
ch := make(chan llm.ChatEvent, len(p.responses[i]))
for _, e := range p.responses[i] {
ch <- e
}
close(ch)
return ch, nil
}
func TestEmptyAndTruncatedResponses(t *testing.T) {
done := llm.ChatEvent{Type: llm.EventDone, StopReason: "stop"}
text := llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
for _, tc := range []struct {
name string
responses [][]llm.ChatEvent
calls int
want string
}{
{"empty", [][]llm.ChatEvent{{done}}, 2, "no answer"},
{"recovery", [][]llm.ChatEvent{{done}, {text, done}}, 2, ""},
{"normal", [][]llm.ChatEvent{{text, done}}, 1, ""},
{"length", [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: "length", Usage: &llm.Usage{OutputTokens: 2048}}}}, 1, "output limit"},
{"partial", [][]llm.ChatEvent{{text, {Type: llm.EventDone, StopReason: "max_tokens"}}}, 1, "output limit"},
{"whitespace", [][]llm.ChatEvent{{{Type: llm.EventTextDelta, Text: " \n"}, done}}, 1, "no answer"},
{"thinking", [][]llm.ChatEvent{{{Type: llm.EventThinkingBlock, ThinkingBlock: &llm.ThinkingBlock{Thinking: "opaque"}}, done}}, 2, "no answer"},
} {
t.Run(tc.name, func(t *testing.T) {
p := &emptyResponseProvider{responses: tc.responses}
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "test"), Model: "fixture", MaxOutputTokens: 2048, MaxTurns: 2}
reason := ""
rt.AgentLoop.Hooks.OnStop = func(_ context.Context, r string) { reason = r }
events, err := rt.Run(context.Background(), "question", nil)
if err != nil {
t.Fatal(err)
}
var failure error
for e := range events {
if e.Type == EventError {
failure = e.Error
}
}
if tc.want == "" {
if failure != nil || reason != "completed" {
t.Fatalf("%v %s", failure, reason)
}
} else if failure == nil || !strings.Contains(failure.Error(), tc.want) || reason == "completed" {
t.Fatalf("%v %s", failure, reason)
}
if p.calls != tc.calls {
t.Fatalf("calls %d", p.calls)
}
for _, limit := range p.limits {
if limit != 2048 {
t.Fatalf("changed limit %d", limit)
}
}
})
}
}
func TestSingleTurnRejectsEmptyAndTruncatedResponses(t *testing.T) {
for _, reason := range []string{"stop", "length", "max_tokens"} {
t.Run(reason, func(t *testing.T) {
p := &emptyResponseProvider{responses: [][]llm.ChatEvent{{{Type: llm.EventDone, StopReason: reason}}}}
rt := &Runtime{LLM: p, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "single"), Model: "fixture", MaxOutputTokens: 2048}
result, err := rt.RunTurn(context.Background(), "question", nil, nil)
if err != nil {
t.Fatal(err)
}
if result.Err == nil || result.StopReason == "completed" || p.calls != 1 {
t.Fatalf("%+v calls=%d", result, p.calls)
}
})
}
}
+2 -1
View File
@@ -20,7 +20,8 @@ func (p *outputLimitProvider) ChatStream(_ context.Context, r llm.ChatRequest) (
if p.fallback && len(p.limits) == 1 {
return nil, errors.New("529 overloaded")
}
ch := make(chan llm.ChatEvent, 1)
ch := make(chan llm.ChatEvent, 2)
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
return ch, nil
+7 -1
View File
@@ -29,6 +29,9 @@ func (p *requestUsageProvider) ChatStream(_ context.Context, req llm.ChatRequest
if p.calls < p.total {
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: req.Model, Name: "noop", Input: json.RawMessage(`{}`)}}
}
if p.calls >= p.total {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
}
usage := &llm.Usage{InputTokens: 20000, OutputTokens: 100, CacheReadInputTokens: 15000}
if p.missingLast && p.calls == p.total {
usage = nil
@@ -87,7 +90,10 @@ type refusalUsageProvider struct {
func (p *refusalUsageProvider) ChatStream(context.Context, llm.ChatRequest) (<-chan llm.ChatEvent, error) {
p.calls++
ch := make(chan llm.ChatEvent, 1)
ch := make(chan llm.ChatEvent, 2)
if p.calls > 1 {
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
}
e := llm.ChatEvent{Type: llm.EventDone, Usage: &llm.Usage{InputTokens: 10000}}
if p.calls == 1 {
e.StopReason = llm.StopReasonRefusal
+1 -1
View File
@@ -30,7 +30,7 @@ func TestRunLifecycleStartFailureAndFinishCannotChangeOutcome(t *testing.T) {
t.Error("finish unbounded")
}
panic("observer cannot rewrite outcome")
}}, []llm.ChatEvent{{Type: llm.EventDone}}, nil)
}}, []llm.ChatEvent{{Type: llm.EventTextDelta, Text: "Answer"}, {Type: llm.EventDone}}, nil)
defer rt.Close()
defer rt.Session.Close()
failed := false
+34
View File
@@ -34,6 +34,8 @@ const (
EventCompactionDone
EventCompactionSkipped
EventRequestUsage
// EventToolCallReady carries complete arguments before tool execution.
EventToolCallReady
)
// AgentEvent is a single streaming event from the agent.
@@ -687,6 +689,8 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
preTokenRetried := false
retriedRefusal := false
var refused bool
retriedEmpty := false
var terminalReason string
var refusalCategory string
streamLoop:
for {
@@ -728,6 +732,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}
break streamLoop
}
r.emit(AgentEvent{Type: EventToolCallReady, ToolCall: &tc})
toolCalls = append(toolCalls, tc)
if !streamingOn || kickoffStopped {
continue
@@ -746,6 +751,7 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
}()
case llm.EventDone:
terminalReason = event.StopReason
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
if event.Usage != nil && r.calibrator != nil {
@@ -871,6 +877,22 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
textContent.WriteString(note)
r.emit(AgentEvent{Type: EventTextDelta, Text: note})
}
// Retry only an empty, non-truncated response with no tool activity.
// Keep the same request and output allowance; never replay tools.
limited := terminalReason == "length" || terminalReason == "max_tokens"
if !limited && !refused && strings.TrimSpace(textContent.String()) == "" && len(toolCalls) == 0 && len(kickoffs) == 0 && !gotFirstToken && !retriedEmpty {
retriedEmpty = true
terminalReason = ""
thinkingBlocks = nil
retryStream, retryErr := r.observeChat(ctx, req, llm.CallRetry, r.LLM.ChatStream)
if retryErr != nil {
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: retryErr})
return
}
streamSource = retryStream
continue streamLoop
}
break streamLoop
}
tr.Mark("llm.stream_end", "turn", turn,
@@ -909,6 +931,18 @@ func (r *Runtime) Run(ctx context.Context, userMsg string, images []llm.ImageCon
return
}
if len(toolCalls) == 0 {
var responseErr error
if terminalReason == "length" || terminalReason == "max_tokens" {
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
} else if strings.TrimSpace(textContent.String()) == "" {
responseErr = errors.New("model returned no answer; try again or choose another model")
}
if responseErr != nil {
drainKickoffs(kickoffs)
stopReason = "error"
r.emit(AgentEvent{Type: EventError, Error: responseErr})
return
}
if len(kickoffs) > 0 {
drainKickoffs(kickoffs)
}
+13
View File
@@ -173,6 +173,7 @@ func (r *Runtime) RunTurn(ctx context.Context, userMsg string, images []llm.Imag
var toolCalls []llm.ToolCall
var thinkingBlocks []session.ThinkingBlockData
retriedRefusal := false
var terminalReason string
streamLoop:
for {
toolIDs := make(map[string]bool)
@@ -205,9 +206,11 @@ streamLoop:
emit(AgentEvent{Type: EventError, Error: err})
return r.turnSlice(startLen, true, "error", ledger.Total(), err), nil
}
emit(AgentEvent{Type: EventToolCallReady, ToolCall: event.ToolCall})
toolCalls = append(toolCalls, *event.ToolCall)
}
case llm.EventDone:
terminalReason = event.StopReason
refused = event.StopReason == llm.StopReasonRefusal
refusalCategory = event.StopCategory
case llm.EventError:
@@ -257,6 +260,16 @@ streamLoop:
}
if len(toolCalls) == 0 {
var responseErr error
if terminalReason == "length" || terminalReason == "max_tokens" {
responseErr = fmt.Errorf("model reached its output limit (%d tokens) before finishing; increase max_output or use a model with a larger output allowance", req.MaxTokens)
} else if strings.TrimSpace(textContent.String()) == "" {
responseErr = fmt.Errorf("model returned no answer; try again or choose another model")
}
if responseErr != nil {
emit(AgentEvent{Type: EventError, Error: responseErr})
return r.turnSlice(startLen, true, "error", ledger.Total(), responseErr), nil
}
// Exchange complete: ingest the full thread once. Background + best-effort
// (the KG spawns its own bounded goroutine), so it never delays the turn.
// context.Background() because the request ctx may be cancelling and the
+2
View File
@@ -27,6 +27,8 @@ func (p *authoringProvider) ChatStream(_ context.Context, req llm.ChatRequest) (
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "author", Name: "skill_manage", Input: json.RawMessage(`{"action":"create","name":"authored-skill","body":"---\ndescription: newly authored workflow\n---\nunique procedure body"}`)}}
case 2:
ch <- llm.ChatEvent{Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "load", Name: "load_skill", Input: json.RawMessage(`{"name":"authored-skill"}`)}}
default:
ch <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Skill created and loaded."}
}
ch <- llm.ChatEvent{Type: llm.EventDone}
close(ch)
+3 -2
View File
@@ -102,7 +102,8 @@ func (s *scriptedStreamLLM) ChatStream(ctx context.Context, _ llm.ChatRequest) (
go func() {
defer close(out)
if n != 1 {
// Subsequent turns: terminate quickly with no tool calls.
// Subsequent turns: answer without further tool calls.
out <- llm.ChatEvent{Type: llm.EventTextDelta, Text: "Answer"}
out <- llm.ChatEvent{Type: llm.EventDone}
return
}
@@ -791,7 +792,7 @@ func TestRun_StreamingCortexAppendIsRaceClean(t *testing.T) {
Model: "test",
MaxTurns: 2,
KG: neverRecallKG{}, // non-nil sentinel; never invoked
IngestSource: "cron", // disables deferred IngestThreadAsync
IngestSource: "cron", // disables deferred IngestThreadAsync
}
// Trivial userMsg "ok" → ShouldRecall returns false → no Recall call on
+40
View File
@@ -0,0 +1,40 @@
package runtime
import (
"context"
"github.com/sausheong/harness/llm"
"github.com/sausheong/harness/session"
"testing"
)
func TestToolReadyCarriesArgumentsBeforeResult(t *testing.T) {
provider := &emptyResponseProvider{responses: [][]llm.ChatEvent{
{{Type: llm.EventToolCallStart, ToolCall: &llm.ToolCall{ID: "one", Name: "noop"}}, {Type: llm.EventToolCallDone, ToolCall: &llm.ToolCall{ID: "one", Name: "noop", Input: []byte(`{"command":"echo hi"}`)}}, {Type: llm.EventDone}},
{{Type: llm.EventTextDelta, Text: "Done"}, {Type: llm.EventDone}},
}}
rt := &Runtime{LLM: provider, Tools: usageNoopExecutor{}, Session: session.NewSession("test", "ready"), Model: "fixture", MaxTurns: 2}
stream, err := rt.Run(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
ready, results := 0, 0
for e := range stream {
switch e.Type {
case EventToolCallReady:
ready++
if e.ToolCall == nil || string(e.ToolCall.Input) != `{"command":"echo hi"}` {
t.Fatalf("%+v", e)
}
case EventToolResult:
results++
if ready != 1 {
t.Fatal("result before arguments")
}
case EventError:
t.Fatal(e.Error)
}
}
if ready != 1 || results != 1 {
t.Fatalf("ready=%d results=%d", ready, results)
}
}