diff --git a/compaction/summarizer.go b/compaction/summarizer.go index 9b0d064..a53d64a 100644 --- a/compaction/summarizer.go +++ b/compaction/summarizer.go @@ -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 diff --git a/compaction/truncated_summary_test.go b/compaction/truncated_summary_test.go new file mode 100644 index 0000000..7473071 --- /dev/null +++ b/compaction/truncated_summary_test.go @@ -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) + } +} diff --git a/providers/openai/finish_reason_test.go b/providers/openai/finish_reason_test.go new file mode 100644 index 0000000..9989232 --- /dev/null +++ b/providers/openai/finish_reason_test.go @@ -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") + } +} diff --git a/providers/openai/openai.go b/providers/openai/openai.go index 0e614db..332f022 100644 --- a/providers/openai/openai.go +++ b/providers/openai/openai.go @@ -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 diff --git a/runtime/attachment_replay_test.go b/runtime/attachment_replay_test.go index 0324df2..5691e78 100644 --- a/runtime/attachment_replay_test.go +++ b/runtime/attachment_replay_test.go @@ -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 diff --git a/runtime/empty_response_test.go b/runtime/empty_response_test.go new file mode 100644 index 0000000..4b2409b --- /dev/null +++ b/runtime/empty_response_test.go @@ -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) + } + }) + } +} diff --git a/runtime/output_tokens_test.go b/runtime/output_tokens_test.go index 0336551..7f51a5f 100644 --- a/runtime/output_tokens_test.go +++ b/runtime/output_tokens_test.go @@ -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 diff --git a/runtime/request_usage_test.go b/runtime/request_usage_test.go index 7e1cff8..ac6b710 100644 --- a/runtime/request_usage_test.go +++ b/runtime/request_usage_test.go @@ -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 diff --git a/runtime/run_lifecycle_test.go b/runtime/run_lifecycle_test.go index 3b57de5..7685f32 100644 --- a/runtime/run_lifecycle_test.go +++ b/runtime/run_lifecycle_test.go @@ -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 diff --git a/runtime/runtime.go b/runtime/runtime.go index 8112544..53d0b46 100644 --- a/runtime/runtime.go +++ b/runtime/runtime.go @@ -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) } diff --git a/runtime/runturn.go b/runtime/runturn.go index 4c788f4..f527574 100644 --- a/runtime/runturn.go +++ b/runtime/runturn.go @@ -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 diff --git a/runtime/skills_authoring_test.go b/runtime/skills_authoring_test.go index 891f175..8078126 100644 --- a/runtime/skills_authoring_test.go +++ b/runtime/skills_authoring_test.go @@ -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) diff --git a/runtime/streaming_test.go b/runtime/streaming_test.go index 31112f9..40d3960 100644 --- a/runtime/streaming_test.go +++ b/runtime/streaming_test.go @@ -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 diff --git a/runtime/tool_ready_test.go b/runtime/tool_ready_test.go new file mode 100644 index 0000000..75fccdc --- /dev/null +++ b/runtime/tool_ready_test.go @@ -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) + } +}