diff --git a/agent/conntest_tools_test.go b/agent/conntest_tools_test.go index 13e99af7..6e21dcbe 100644 --- a/agent/conntest_tools_test.go +++ b/agent/conntest_tools_test.go @@ -6,6 +6,7 @@ import ( "io" "net/http" "net/http/httptest" + "strings" "testing" ) @@ -36,3 +37,76 @@ func TestConnectionSendsNoTools(t *testing.T) { t.Fatalf("connection test sent %d tools, want none:\n%s", len(req.Tools), body) } } + +// Regression for #526: Ollama returning a tool call (with or without accompanying +// text) or finish_reason="tool_calls", or whitespace-only content, must fail +// TestConnection instead of reporting Connected. +func TestConnectionRejectsToolCallsAndWhitespaceReplies(t *testing.T) { + cases := []struct { + name string + stream bool + statusBody string + wantErrSub string + }{ + { + name: "ollama_nonstream_tool_call_with_text", + stream: false, + statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`, + wantErrSub: "tool call", + }, + { + name: "ollama_nonstream_tool_call_only", + stream: false, + statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"","tool_calls":[{"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":10,"total_tokens":30}}`, + wantErrSub: "tool call", + }, + { + name: "ollama_nonstream_finish_reason_tool_calls_without_array", + stream: false, + statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":"OK"},"finish_reason":"tool_calls"}],"usage":{"prompt_tokens":20,"completion_tokens":2,"total_tokens":22}}`, + wantErrSub: "tool call", + }, + { + name: "ollama_stream_tool_call_with_text", + stream: true, + statusBody: strings.Join([]string{ + `data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"role":"assistant","content":"OK"}}]}`, + `data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"id":"call_1","type":"function","function":{"name":"TaskOutput","arguments":"{}"}}]}}]}`, + `data: {"id":"x","object":"chat.completion.chunk","model":"baronllm","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}`, + `data: [DONE]`, + ``, + }, "\n\n"), + wantErrSub: "tool call", + }, + { + name: "ollama_whitespace_only_content", + stream: false, + statusBody: `{"id":"x","object":"chat.completion","model":"baronllm","choices":[{"index":0,"message":{"role":"assistant","content":" \n\t "},"finish_reason":"stop"}],"usage":{"prompt_tokens":20,"completion_tokens":3,"total_tokens":23}}`, + wantErrSub: "no content", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if tc.stream { + w.Header().Set("Content-Type", "text/event-stream") + } else { + w.Header().Set("Content-Type", "application/json") + } + _, _ = w.Write([]byte(tc.statusBody)) + })) + defer srv.Close() + + cfg := ConfigFrom("ollama", "baronllm", srv.URL+"/v1", "", "") + cfg.Stream = tc.stream + _, reply, err := TestConnection(context.Background(), cfg) + if err == nil { + t.Fatalf("expected TestConnection to reject %s, got Connected with reply=%q", tc.name, reply) + } + if !strings.Contains(strings.ToLower(err.Error()), tc.wantErrSub) { + t.Fatalf("unexpected error for %s: %v (want substring %q)", tc.name, err, tc.wantErrSub) + } + }) + } +} diff --git a/agent/provider.go b/agent/provider.go index 6fba6875..96d92ee4 100644 --- a/agent/provider.go +++ b/agent/provider.go @@ -14,6 +14,7 @@ import ( "context" "fmt" "io" + "iter" "log/slog" "net/http" "net/url" @@ -689,8 +690,9 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error // budget to emit OK cleanly (finish=stop). // EscalateMaxTokens stays false: don't raise the cap and retry on truncation, to // avoid burning tokens in a resume loop. + probe := &connTestProvider{inner: prov} reply, err := agentcore.Run(ctx, agentcore.Options{ - Provider: prov, + Provider: probe, SystemPrompt: []string{"You are a connection test. Just output the two characters OK — no thinking, no explanation, nothing else."}, Tools: []actool.CoreTool{}, // not nil: nil means the SDK's unconfined file and shell tools PermissionMode: acperm.ModeBypass, @@ -712,6 +714,12 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error } return lat, "", err } + // Reject tool-call replies (#526): the connection test asks for plain text + // with no tools; a model answering with a tool call or tool_calls/tool_use + // finish reason must not be reported as Connected even if it also emitted text. + if probe.sawToolCall || isToolCallStopReason(probe.stopReason) { + return lat, "", fmt.Errorf("the model returned a tool call instead of a text reply (finish_reason=%q)", probe.stopReason) + } // err==nil is not enough: requests that go through while the model emits nothing // at all really happen (thinking burned the whole budget, the body got swallowed // by a safety policy, a compatibility layer dropped the content). Such a config @@ -723,3 +731,51 @@ func TestConnection(ctx context.Context, c Config) (time.Duration, string, error } return lat, reply, nil } + +// connTestProvider observes the raw provider response during TestConnection so +// tool-call replies and tool_calls/tool_use stop reasons are rejected (#526). +type connTestProvider struct { + inner llm.Provider + sawToolCall bool + stopReason string +} + +func (p *connTestProvider) Stream(ctx context.Context, req llm.CompletionRequest) iter.Seq2[llm.StreamEvent, error] { + return func(yield func(llm.StreamEvent, error) bool) { + for ev, err := range p.inner.Stream(ctx, req) { + if err == nil { + if ev.Type == llm.SEToolUseStart { + p.sawToolCall = true + } + if ev.StopReason != "" { + p.stopReason = ev.StopReason + } + } + if !yield(ev, err) { + return + } + } + } +} + +func (p *connTestProvider) Complete(ctx context.Context, req llm.CompletionRequest) (llm.Message, string, llm.Usage, error) { + msg, stopReason, usage, err := p.inner.Complete(ctx, req) + if err == nil { + if len(msg.ToolUses()) > 0 { + p.sawToolCall = true + } + if stopReason != "" { + p.stopReason = stopReason + } + } + return msg, stopReason, usage, err +} + +func isToolCallStopReason(stopReason string) bool { + switch strings.ToLower(strings.TrimSpace(stopReason)) { + case "tool_use", "tool_calls": + return true + default: + return false + } +}