Reject empty and truncated answers and expose complete tool calls
This commit is contained in:
1 parent
019a38f111
commit
3ca0994437
14 files changed
+278
-7
No files matched your search
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user