Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions internal/providers/ollama.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,21 +170,25 @@ func (p *OllamaProvider) Chat(ctx context.Context, req ChatRequest) (*ChatRespon
// ChatStream sends a streaming chat request to Ollama, calling onChunk for each
// content delta, and returns the accumulated final response.
func (p *OllamaProvider) ChatStream(ctx context.Context, req ChatRequest, onChunk func(StreamChunk)) (*ChatResponse, error) {
result := &ChatResponse{FinishReason: "stop"}
// Set when the stream fails after output already reached the caller.
var partialErr error

fn := func() (*ChatResponse, error) {
acc := &ChatResponse{FinishReason: "stop"}
emitted := false

streamFn := func(resp ollamaapi.ChatResponse) error {
delta := resp.Message.Content
if delta != "" {
acc.Content += delta
emitted = true
onChunk(StreamChunk{Content: delta})
}

thinking := resp.Message.Thinking
if thinking != "" {
acc.Thinking += thinking
emitted = true
onChunk(StreamChunk{Thinking: thinking})
}

Expand Down Expand Up @@ -220,13 +224,22 @@ func (p *OllamaProvider) ChatStream(ctx context.Context, req ChatRequest, onChun
}

if err := p.client.Chat(ctx, p.buildRequest(ctx, req, true), streamFn); err != nil {
return nil, fmt.Errorf("%s: chat stream: %w", p.name, err)
err = fmt.Errorf("%s: chat stream: %w", p.name, err)
// Replaying would duplicate the chunks already delivered, so
// hide the error from RetryDo and surface it below.
if emitted {
partialErr = err
return nil, nil
}
return nil, err
}
return acc, nil
}

var chatErr error
result, chatErr = RetryDo(ctx, p.retryConfig, fn)
result, chatErr := RetryDo(ctx, p.retryConfig, fn)
if partialErr != nil {
return nil, partialErr
}
return result, chatErr
}

Expand Down
30 changes: 30 additions & 0 deletions internal/providers/ollama_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
"io"
"net/http"
"net/http/httptest"
"sync/atomic"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -183,3 +185,31 @@ func TestOllamaBuildRequest_ToolSchemaPreserved(t *testing.T) {
assert.True(t, ok)
assert.Equal(t, []string{"x"}, opts.Required)
}

// A stream that breaks after output reached the caller must not be replayed,
// otherwise the already delivered text is emitted a second time.
func TestOllamaChatStream_NoRetryAfterChunkEmitted(t *testing.T) {
var calls atomic.Int32
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls.Add(1)
w.Header().Set("Content-Type", "application/x-ndjson")
_, _ = io.WriteString(w, `{"model":"m","message":{"role":"assistant","content":"Hel"},"done":false}`+"\n")
w.(http.Flusher).Flush()
panic(http.ErrAbortHandler) // cut the connection mid-stream
}))
defer srv.Close()

numCtx := 4096
p := NewOllamaProvider("ollama", srv.URL, "m", &numCtx, nil)
p.retryConfig = RetryConfig{Attempts: 3, MinDelay: time.Millisecond, MaxDelay: time.Millisecond}

var got string
_, err := p.ChatStream(context.Background(), ChatRequest{
Messages: []Message{{Role: "user", Content: "hi"}},
Options: map[string]any{},
}, func(c StreamChunk) { got += c.Content })

require.Error(t, err)
assert.Equal(t, int32(1), calls.Load(), "chat requests")
assert.Equal(t, "Hel", got)
}
Loading