Get up and running with Kimi, GLM, MiniMax, DeepSeek, gpt-oss, Qwen, Gemma and other models.
openai: match openai's streaming wire format for chat completions (#17485)
Bruce MacDonald8edecb5c69cd
diff --git a/middleware/openai.go b/middleware/openai.goindex dcc45af35..1715fe54f 100644--- a/middleware/openai.go+++ b/middleware/openai.go@@ -5,7 +5,6 @@ import ("encoding/json""fmt""io"- "log/slog""math/rand""net/http""strings"@@ -26,10 +25,14 @@ type BaseWriter struct {}type ChatWriter struct {- stream bool- streamOptions *openai.StreamOptions- id string- toolCallSent bool+ stream bool+ streamOptions *openai.StreamOptions+ id string+ toolCallSent bool+ firstChunkSent bool+ // createdAt pins the shared timestamp for every chunk in the stream,+ // captured from the first response.+ createdAt time.TimeBaseWriter}@@ -80,34 +83,66 @@ func (w *ChatWriter) writeResponse(data []byte) (int, error) {// chat chunkif w.stream {- chunks := openai.ToChunks(w.id, chatResponse, w.toolCallSent)w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")- for _, c := range chunks {- d, err := json.Marshal(c)++ // OpenAI stamps one created value on every chunk in a stream; pin the+ // timestamp from the first response (the server stamps each response).+ if chatResponse.CreatedAt.IsZero() {+ chatResponse.CreatedAt = time.Now().UTC()+ }+ if w.createdAt.IsZero() {+ w.createdAt = chatResponse.CreatedAt+ }+ chatResponse.CreatedAt = w.createdAt++ // A Done response with an empty message is the metrics-only trailer.+ // OpenAI goes straight from the last content chunk to the finish chunk,+ // so don't emit an empty content chunk for it. If this is the stream's+ // first response, fall through so a wholly empty completion still opens+ // with a role chunk.+ isEmptyTrailer := chatResponse.Done && w.firstChunkSent &&+ chatResponse.Message.Content == "" &&+ chatResponse.Message.Thinking == "" &&+ len(chatResponse.Message.ToolCalls) == 0 &&+ len(chatResponse.Logprobs) == 0++ if !isEmptyTrailer {+ includeRole := !w.firstChunkSent+ chunks := openai.ToStreamChunks(w.id, chatResponse, includeRole)+ for _, c := range chunks {+ d, err := json.Marshal(c)+ if err != nil {+ return 0, err+ }+ if !w.toolCallSent && len(c.Choices) > 0 && len(c.Choices[0].Delta.ToolCalls) > 0 {+ w.toolCallSent = true+ }+ _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))+ if err != nil {+ return 0, err+ }+ }++ // ToStreamChunks always emits at least one chunk.+ w.firstChunkSent = true+ }++ if chatResponse.Done {+ finishChunk := openai.FinishChunk(w.id, chatResponse, w.toolCallSent)+ d, err := json.Marshal(finishChunk)if err != nil {return 0, err}- if !w.toolCallSent && len(c.Choices) > 0 && len(c.Choices[0].Delta.ToolCalls) > 0 {- w.toolCallSent = true- }_, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))if err != nil {return 0, err}- }- if chatResponse.Done {- c := openai.ToChunk(w.id, chatResponse, w.toolCallSent)- if len(chunks) > 0 {- c = chunks[len(chunks)-1]- } else {- slog.Warn("ToChunks returned no chunks; falling back to ToChunk for usage chunk", "id", w.id, "model", chatResponse.Model)- }if w.streamOptions != nil && w.streamOptions.IncludeUsage {u := openai.ToUsage(chatResponse)- c.Usage = &u- c.Choices = []openai.ChunkChoice{}- d, err := json.Marshal(c)+ finishChunk.Usage = &u+ finishChunk.Choices = []openai.ChunkChoice{}+ d, err := json.Marshal(finishChunk)if err != nil {return 0, err}diff --git a/middleware/openai_test.go b/middleware/openai_test.goindex f7b3e9e69..2d50e2464 100644--- a/middleware/openai_test.go+++ b/middleware/openai_test.go@@ -129,11 +129,24 @@ func TestChatWriter_StreamMixedThinkingAndContentEmitsSplitChunks(t *testing.T)}frames := sseDataFrames(recorder.Body.String())- if len(frames) != 4 {- t.Fatalf("expected 4 SSE data frames (2 chunks + usage + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())+ if len(frames) != 5 {+ t.Fatalf("expected 5 SSE data frames (2 content chunks + finish + usage + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())}- if frames[3] != "[DONE]" {- t.Fatalf("expected final frame [DONE], got %q", frames[3])+ if frames[4] != "[DONE]" {+ t.Fatalf("expected final frame [DONE], got %q", frames[4])+ }++ // Wire-format checks that struct round-tripping cannot catch: the finish+ // chunk serializes an empty delta object with no content key, and the usage+ // chunk carries an explicit empty choices array (not null).+ if !strings.Contains(frames[2], `"delta":{}`) {+ t.Fatalf("expected finish frame to contain \"delta\":{}, got %s", frames[2])+ }+ if strings.Contains(frames[2], `"content"`) {+ t.Fatalf("expected finish frame to omit content, got %s", frames[2])+ }+ if !strings.Contains(frames[3], `"choices":[]`) {+ t.Fatalf("expected usage frame to contain \"choices\":[], got %s", frames[3])}var reasoningChunk openai.ChatCompletionChunk@@ -146,8 +159,13 @@ func TestChatWriter_StreamMixedThinkingAndContentEmitsSplitChunks(t *testing.T)t.Fatalf("unmarshal content chunk: %v", err)}+ var finishChunk openai.ChatCompletionChunk+ if err := json.Unmarshal([]byte(frames[2]), &finishChunk); err != nil {+ t.Fatalf("unmarshal finish chunk: %v", err)+ }+var usageChunk openai.ChatCompletionChunk- if err := json.Unmarshal([]byte(frames[2]), &usageChunk); err != nil {+ if err := json.Unmarshal([]byte(frames[3]), &usageChunk); err != nil {t.Fatalf("unmarshal usage chunk: %v", err)}@@ -157,8 +175,8 @@ func TestChatWriter_StreamMixedThinkingAndContentEmitsSplitChunks(t *testing.T)if reasoningChunk.Choices[0].Delta.Reasoning != "reasoning" {t.Fatalf("expected reasoning chunk reasoning %q, got %q", "reasoning", reasoningChunk.Choices[0].Delta.Reasoning)}- if reasoningChunk.Choices[0].Delta.Content != "" {- t.Fatalf("expected reasoning chunk content to be empty, got %v", reasoningChunk.Choices[0].Delta.Content)+ if reasoningChunk.Choices[0].Delta.Content != nil {+ t.Fatalf("expected reasoning chunk content to be nil, got %v", reasoningChunk.Choices[0].Delta.Content)}if reasoningChunk.Choices[0].FinishReason != nil {t.Fatalf("expected reasoning chunk finish reason nil, got %v", reasoningChunk.Choices[0].FinishReason)@@ -173,8 +191,18 @@ func TestChatWriter_StreamMixedThinkingAndContentEmitsSplitChunks(t *testing.T)if contentChunk.Choices[0].Delta.Content != "final answer" {t.Fatalf("expected content chunk content %q, got %v", "final answer", contentChunk.Choices[0].Delta.Content)}- if contentChunk.Choices[0].FinishReason == nil || *contentChunk.Choices[0].FinishReason != "stop" {- t.Fatalf("expected content chunk finish reason %q, got %v", "stop", contentChunk.Choices[0].FinishReason)+ if contentChunk.Choices[0].FinishReason != nil {+ t.Fatalf("expected content chunk finish reason nil, got %v", contentChunk.Choices[0].FinishReason)+ }++ if len(finishChunk.Choices) != 1 {+ t.Fatalf("expected 1 finish choice, got %d", len(finishChunk.Choices))+ }+ if finishChunk.Choices[0].FinishReason == nil || *finishChunk.Choices[0].FinishReason != "stop" {+ t.Fatalf("expected finish reason %q, got %v", "stop", finishChunk.Choices[0].FinishReason)+ }+ if finishChunk.Choices[0].Delta.Content != nil {+ t.Fatalf("expected finish chunk delta to be empty, got %+v", finishChunk.Choices[0].Delta)}if usageChunk.Usage == nil {@@ -218,22 +246,36 @@ func TestChatWriter_StreamSingleChunkPathStillEmitsOneChunk(t *testing.T) {}frames := sseDataFrames(recorder.Body.String())- if len(frames) != 2 {- t.Fatalf("expected 2 SSE data frames (1 chunk + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())+ if len(frames) != 3 {+ t.Fatalf("expected 3 SSE data frames (1 content chunk + finish + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())}- if frames[1] != "[DONE]" {- t.Fatalf("expected final frame [DONE], got %q", frames[1])+ if frames[2] != "[DONE]" {+ t.Fatalf("expected final frame [DONE], got %q", frames[2])}- var chunk openai.ChatCompletionChunk- if err := json.Unmarshal([]byte(frames[0]), &chunk); err != nil {- t.Fatalf("unmarshal chunk: %v", err)+ var contentChunk openai.ChatCompletionChunk+ if err := json.Unmarshal([]byte(frames[0]), &contentChunk); err != nil {+ t.Fatalf("unmarshal content chunk: %v", err)+ }+ if len(contentChunk.Choices) != 1 {+ t.Fatalf("expected 1 chunk choice, got %d", len(contentChunk.Choices))}- if len(chunk.Choices) != 1 {- t.Fatalf("expected 1 chunk choice, got %d", len(chunk.Choices))+ if contentChunk.Choices[0].Delta.Content != "single chunk" {+ t.Fatalf("expected chunk content %q, got %v", "single chunk", contentChunk.Choices[0].Delta.Content)+ }+ if contentChunk.Choices[0].FinishReason != nil {+ t.Fatalf("expected content chunk finish reason nil, got %v", contentChunk.Choices[0].FinishReason)+ }++ var finishChunk openai.ChatCompletionChunk+ if err := json.Unmarshal([]byte(frames[1]), &finishChunk); err != nil {+ t.Fatalf("unmarshal finish chunk: %v", err)}- if chunk.Choices[0].Delta.Content != "single chunk" {- t.Fatalf("expected chunk content %q, got %v", "single chunk", chunk.Choices[0].Delta.Content)+ if len(finishChunk.Choices) != 1 {+ t.Fatalf("expected 1 finish choice, got %d", len(finishChunk.Choices))+ }+ if finishChunk.Choices[0].FinishReason == nil || *finishChunk.Choices[0].FinishReason != "stop" {+ t.Fatalf("expected finish reason %q, got %v", "stop", finishChunk.Choices[0].FinishReason)}}@@ -369,6 +411,406 @@ func TestChatWriter_StreamMixedThinkingAndContentWithoutDoneEmitsChunksOnly(t *t}}+func TestChatWriter_StreamRoleOnlyOnFirstChunk(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ first := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "Hello"},+ Done: false,+ }+ data, _ := json.Marshal(first)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write first: %v", err)+ }++ second := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: " world"},+ Done: false,+ }+ data, _ = json.Marshal(second)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write second: %v", err)+ }++ third := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "!"},+ Done: true,+ DoneReason: "stop",+ }+ data, _ = json.Marshal(third)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write third: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // Expect: chunk1 (content+role) + chunk2 (content) + chunk3 (content) + finish + [DONE]+ if len(frames) != 5 {+ t.Fatalf("expected 5 SSE data frames, got %d:\n%s", len(frames), recorder.Body.String())+ }++ var firstRaw map[string]any+ json.Unmarshal([]byte(frames[0]), &firstRaw)+ firstDelta := firstRaw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)+ if firstDelta["role"] != "assistant" {+ t.Fatalf("expected first chunk to have role 'assistant', got %v", firstDelta["role"])+ }++ var secondRaw map[string]any+ json.Unmarshal([]byte(frames[1]), &secondRaw)+ secondDelta := secondRaw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)+ if _, hasRole := secondDelta["role"]; hasRole {+ t.Fatalf("expected second chunk to omit role, got %v", secondDelta["role"])+ }++ var thirdRaw map[string]any+ json.Unmarshal([]byte(frames[2]), &thirdRaw)+ thirdDelta := thirdRaw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)+ if _, hasRole := thirdDelta["role"]; hasRole {+ t.Fatalf("expected third chunk to omit role, got %v", thirdDelta["role"])+ }++ var finishRaw map[string]any+ json.Unmarshal([]byte(frames[3]), &finishRaw)+ finishDelta := finishRaw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)+ if len(finishDelta) != 0 {+ t.Fatalf("expected finish chunk to have empty delta {}, got %v", finishDelta)+ }+ finishReason := finishRaw["choices"].([]any)[0].(map[string]any)["finish_reason"]+ if finishReason != "stop" {+ t.Fatalf("expected finish_reason %q, got %v", "stop", finishReason)+ }+}++func TestChatWriter_StreamSharesOneTimestamp(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ first := api.ChatResponse{+ Model: "test-model",+ CreatedAt: time.Unix(1700000000, 0),+ Message: api.Message{Content: "Hello"},+ Done: false,+ }+ data, _ := json.Marshal(first)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write first: %v", err)+ }++ // The server stamps each streamed response; later responses must not+ // change the stream's created value.+ second := api.ChatResponse{+ Model: "test-model",+ CreatedAt: time.Unix(1700000010, 0),+ Message: api.Message{Content: " world"},+ Done: false,+ }+ data, _ = json.Marshal(second)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write second: %v", err)+ }++ third := api.ChatResponse{+ Model: "test-model",+ CreatedAt: time.Unix(1700000020, 0),+ Done: true,+ DoneReason: "stop",+ }+ data, _ = json.Marshal(third)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write third: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // chunk1 + chunk2 + finish + [DONE]+ if len(frames) != 4 {+ t.Fatalf("expected 4 SSE data frames, got %d:\n%s", len(frames), recorder.Body.String())+ }++ for _, frame := range frames[:3] {+ var raw map[string]any+ if err := json.Unmarshal([]byte(frame), &raw); err != nil {+ t.Fatalf("unmarshal frame: %v", err)+ }+ if got := raw["created"]; got != float64(1700000000) {+ t.Fatalf("expected all chunks to share created=1700000000, got %v in %s", got, frame)+ }+ }+}++func TestChatWriter_StreamFinishReasonLength(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ // Simulate a max_tokens truncation+ resp := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "partial"},+ Done: true,+ DoneReason: "length",+ }+ data, _ := json.Marshal(resp)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // content + finish + [DONE]+ if len(frames) != 3 {+ t.Fatalf("expected 3 frames, got %d:\n%s", len(frames), recorder.Body.String())+ }++ var finishRaw map[string]any+ json.Unmarshal([]byte(frames[1]), &finishRaw)+ finishReason := finishRaw["choices"].([]any)[0].(map[string]any)["finish_reason"]+ if finishReason != "length" {+ t.Fatalf("expected finish_reason %q, got %v", "length", finishReason)+ }++ var contentRaw map[string]any+ json.Unmarshal([]byte(frames[0]), &contentRaw)+ contentFinish := contentRaw["choices"].([]any)[0].(map[string]any)["finish_reason"]+ if contentFinish != nil {+ t.Fatalf("expected content chunk finish_reason to be null, got %v", contentFinish)+ }+}++func TestChatWriter_StreamToolCallsFinishReason(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ resp := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{+ ToolCalls: []api.ToolCall{+ {+ ID: "call_abc",+ Function: api.ToolCallFunction{+ Index: 0,+ Name: "get_weather",+ Arguments: testArgs(map[string]any{+ "city": "Paris",+ }),+ },+ },+ },+ },+ Done: true,+ DoneReason: "stop",+ }+ data, _ := json.Marshal(resp)+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // tool_call_content + finish + [DONE]+ if len(frames) != 3 {+ t.Fatalf("expected 3 frames, got %d:\n%s", len(frames), recorder.Body.String())+ }++ var finishRaw map[string]any+ json.Unmarshal([]byte(frames[1]), &finishRaw)+ finishReason := finishRaw["choices"].([]any)[0].(map[string]any)["finish_reason"]+ if finishReason != "tool_calls" {+ t.Fatalf("expected finish_reason %q, got %v", "tool_calls", finishReason)+ }++ finishDelta := finishRaw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)+ if len(finishDelta) != 0 {+ t.Fatalf("expected empty finish delta, got %v", finishDelta)+ }+}++func TestChatWriter_StreamMetricsTrailerSkipsEmptyContentChunk(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ streamOptions: &openai.StreamOptions{IncludeUsage: true},+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ content := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "Hi"},+ }+ data, err := json.Marshal(content)+ if err != nil {+ t.Fatalf("marshal content: %v", err)+ }+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write content: %v", err)+ }++ // Real streams end with a metrics-only response: Done with an empty message.+ trailer := api.ChatResponse{+ Model: "test-model",+ Done: true,+ DoneReason: "stop",+ Metrics: api.Metrics{+ PromptEvalCount: 3,+ EvalCount: 1,+ },+ }+ data, err = json.Marshal(trailer)+ if err != nil {+ t.Fatalf("marshal trailer: %v", err)+ }+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write trailer: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // content + finish + usage + [DONE] — no delta:{"content":""} frame between+ // the last content chunk and the finish chunk.+ if len(frames) != 4 {+ t.Fatalf("expected 4 SSE data frames (content + finish + usage + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())+ }+ if !strings.Contains(frames[0], `"content":"Hi"`) {+ t.Fatalf("expected content frame to carry the content, got %s", frames[0])+ }+ if !strings.Contains(frames[1], `"delta":{}`) || !strings.Contains(frames[1], `"finish_reason":"stop"`) {+ t.Fatalf("expected finish frame with empty delta and stop reason, got %s", frames[1])+ }+ if !strings.Contains(frames[2], `"choices":[]`) {+ t.Fatalf("expected usage frame with empty choices, got %s", frames[2])+ }+ if frames[3] != "[DONE]" {+ t.Fatalf("expected final frame [DONE], got %q", frames[3])+ }+}++func TestChatWriter_StreamDoneWithLogprobsNotTreatedAsTrailer(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ content := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "Hi"},+ }+ data, err := json.Marshal(content)+ if err != nil {+ t.Fatalf("marshal content: %v", err)+ }+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write content: %v", err)+ }++ // A final response can carry the last token's logprobs with an empty+ // message; its logprobs must be streamed, not dropped with the trailer.+ final := api.ChatResponse{+ Model: "test-model",+ Done: true,+ DoneReason: "stop",+ Logprobs: []api.Logprob{+ {TokenLogprob: api.TokenLogprob{Token: "Hi", Logprob: -0.1}},+ },+ }+ data, err = json.Marshal(final)+ if err != nil {+ t.Fatalf("marshal final: %v", err)+ }+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write final: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // content + logprobs chunk + finish + [DONE]+ if len(frames) != 4 {+ t.Fatalf("expected 4 SSE data frames (content + logprobs + finish + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())+ }+ if !strings.Contains(frames[1], `"logprob":-0.1`) {+ t.Fatalf("expected logprobs chunk to carry the logprobs, got %s", frames[1])+ }+ if !strings.Contains(frames[2], `"delta":{}`) || !strings.Contains(frames[2], `"finish_reason":"stop"`) {+ t.Fatalf("expected finish frame with empty delta and stop reason, got %s", frames[2])+ }+}++func TestChatWriter_StreamEmptyCompletionStillEmitsRoleChunk(t *testing.T) {+ gin.SetMode(gin.TestMode)+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)++ writer := &ChatWriter{+ stream: true,+ id: "chatcmpl-test",+ BaseWriter: BaseWriter{ResponseWriter: context.Writer},+ }++ // A completion that is empty from the start must still open with a role chunk+ // before the finish chunk.+ resp := api.ChatResponse{+ Model: "test-model",+ Done: true,+ DoneReason: "stop",+ }+ data, err := json.Marshal(resp)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ if _, err := writer.Write(data); err != nil {+ t.Fatalf("write: %v", err)+ }++ frames := sseDataFrames(recorder.Body.String())+ // role/content chunk + finish + [DONE]+ if len(frames) != 3 {+ t.Fatalf("expected 3 SSE data frames (role chunk + finish + [DONE]), got %d:\n%s", len(frames), recorder.Body.String())+ }+ if !strings.Contains(frames[0], `"role":"assistant"`) || !strings.Contains(frames[0], `"content":""`) {+ t.Fatalf("expected initial role chunk with empty content, got %s", frames[0])+ }+ if !strings.Contains(frames[1], `"delta":{}`) || !strings.Contains(frames[1], `"finish_reason":"stop"`) {+ t.Fatalf("expected finish frame with empty delta and stop reason, got %s", frames[1])+ }+ if frames[2] != "[DONE]" {+ t.Fatalf("expected final frame [DONE], got %q", frames[2])+ }+}+func TestChatMiddleware(t *testing.T) {type testCase struct {name stringdiff --git a/openai/openai.go b/openai/openai.goindex 553381136..9dbeb3a05 100644--- a/openai/openai.go+++ b/openai/openai.go@@ -3,6 +3,7 @@ package openaiimport ("bytes"+ "cmp""encoding/base64""encoding/binary""encoding/json"@@ -18,8 +19,6 @@ import ("github.com/ollama/ollama/types/model")-var finishReasonToolCalls = "tool_calls"-type Error struct {Message string `json:"message"`Type string `json:"type"`@@ -40,6 +39,15 @@ type Message struct {ToolCallID string `json:"tool_call_id,omitempty"`}+// Delta is used in streaming chunk responses. All fields use omitempty so+// that a finish chunk produces a truly empty delta `{}` matching the OpenAI spec.+type Delta struct {+ Role string `json:"role,omitempty"`+ Content any `json:"content,omitempty"`+ Reasoning string `json:"reasoning,omitempty"`+ ToolCalls []ToolCall `json:"tool_calls,omitempty"`+}+type ChoiceLogprobs struct {Content []api.Logprob `json:"content"`}@@ -53,7 +61,7 @@ type Choice struct {type ChunkChoice struct {Index int `json:"index"`- Delta Message `json:"delta"`+ Delta Delta `json:"delta"`FinishReason *string `json:"finish_reason"`Logprobs *ChoiceLogprobs `json:"logprobs,omitempty"`}@@ -277,7 +285,7 @@ func ToChatCompletion(id string, r api.ChatResponse) ChatCompletion {Index: 0,Message: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls, Reasoning: r.Message.Thinking},FinishReason: func(reason string) *string {- if len(toolCalls) > 0 {+ if reason == "stop" && len(toolCalls) > 0 {reason = "tool_calls"}if len(reason) > 0 {@@ -291,7 +299,7 @@ func ToChatCompletion(id string, r api.ChatResponse) ChatCompletion {}}-func toChunk(id string, r api.ChatResponse, toolCallSent bool) ChatCompletionChunk {+func toChunk(id string, r api.ChatResponse, includeRole bool) ChatCompletionChunk {toolCalls := ToToolCalls(r.Message.ToolCalls)var logprobs *ChoiceLogprobs@@ -299,43 +307,53 @@ func toChunk(id string, r api.ChatResponse, toolCallSent bool) ChatCompletionChulogprobs = &ChoiceLogprobs{Content: r.Logprobs}}+ var role string+ if includeRole {+ role = "assistant"+ }++ // Content is typed as any with omitempty: nil is omitted, "" is kept.+ // Use the string value from the response so empty-string content (e.g. first+ // chunk or reasoning-only) is explicitly serialized as "content":"".+ var content any = r.Message.Content++ // Stamp the chunk with the response's timestamp; OpenAI reuses one created+ // value across a stream. Fall back to now when the response carries none+ // (e.g. synthetic responses).+ created := r.CreatedAt.Unix()+ if r.CreatedAt.IsZero() {+ created = time.Now().Unix()+ }+return ChatCompletionChunk{Id: id,Object: "chat.completion.chunk",- Created: time.Now().Unix(),+ Created: created,Model: r.Model,SystemFingerprint: "fp_ollama",Choices: []ChunkChoice{{- Index: 0,- Delta: Message{Role: "assistant", Content: r.Message.Content, ToolCalls: toolCalls, Reasoning: r.Message.Thinking},- FinishReason: func(reason string) *string {- if len(reason) > 0 {- if toolCallSent || len(toolCalls) > 0 {- return &finishReasonToolCalls- }- return &reason- }- return nil- }(r.DoneReason),+ Index: 0,+ Delta: Delta{Role: role, Content: content, ToolCalls: toolCalls, Reasoning: r.Message.Thinking},Logprobs: logprobs,}},}}-// ToChunks converts an api.ChatResponse to one or more ChatCompletionChunk values.-func ToChunks(id string, r api.ChatResponse, toolCallSent bool) []ChatCompletionChunk {+// ToStreamChunks converts an api.ChatResponse to one or more ChatCompletionChunk values.+// includeRole controls whether the "role" field appears in the delta (should be true+// only for the first chunk in a stream, matching the OpenAI spec).+func ToStreamChunks(id string, r api.ChatResponse, includeRole bool) []ChatCompletionChunk {hasMixedResponse := r.Message.Thinking != "" && (r.Message.Content != "" || len(r.Message.ToolCalls) > 0)if !hasMixedResponse {- return []ChatCompletionChunk{toChunk(id, r, toolCallSent)}+ return []ChatCompletionChunk{toChunk(id, r, includeRole)}}- reasoningChunk := toChunk(id, r, toolCallSent)+ reasoningChunk := toChunk(id, r, includeRole)// The logprobs here might include tokens not in this chunk because we now split between thinking and content/tool calls.- reasoningChunk.Choices[0].Delta.Content = ""+ reasoningChunk.Choices[0].Delta.Content = nilreasoningChunk.Choices[0].Delta.ToolCalls = nil- reasoningChunk.Choices[0].FinishReason = nil- contentOrToolCallsChunk := toChunk(id, r, toolCallSent)+ contentOrToolCallsChunk := toChunk(id, r, false)// Keep both split chunks on the same timestamp since they represent one logical emission.contentOrToolCallsChunk.Created = reasoningChunk.CreatedcontentOrToolCallsChunk.Choices[0].Delta.Reasoning = ""@@ -347,9 +365,34 @@ func ToChunks(id string, r api.ChatResponse, toolCallSent bool) []ChatCompletion}}-// Deprecated: use ToChunks for streaming conversion.-func ToChunk(id string, r api.ChatResponse, toolCallSent bool) ChatCompletionChunk {- return toChunk(id, r, toolCallSent)+// FinishChunk creates a dedicated finish-reason chunk with an empty delta,+// matching the OpenAI spec where finish_reason is sent on its own chunk.+func FinishChunk(id string, r api.ChatResponse, toolCallSent bool) ChatCompletionChunk {+ // Only remap known terminal reasons; pass anything else through untouched.+ // tool_calls only overrides stop — an unfinished or unknown done reason+ // must not be relabeled tool_calls.+ reason := cmp.Or(r.DoneReason, "stop")+ if reason == "stop" && toolCallSent {+ reason = "tool_calls"+ }+ // Stamp the chunk with the completion's timestamp like OpenAI does; fall+ // back to now when the response carries none (e.g. synthetic responses).+ created := r.CreatedAt.Unix()+ if r.CreatedAt.IsZero() {+ created = time.Now().Unix()+ }+ return ChatCompletionChunk{+ Id: id,+ Object: "chat.completion.chunk",+ Created: created,+ Model: r.Model,+ SystemFingerprint: "fp_ollama",+ Choices: []ChunkChoice{{+ Index: 0,+ Delta: Delta{},+ FinishReason: &reason,+ }},+ }}// ToUsageGenerate converts an api.GenerateResponse to Usagediff --git a/openai/openai_test.go b/openai/openai_test.goindex f57de8873..ceed11bae 100644--- a/openai/openai_test.go+++ b/openai/openai_test.go@@ -2,6 +2,7 @@ package openaiimport ("encoding/base64"+ "encoding/json""testing""time"@@ -506,7 +507,7 @@ func TestToChatCompletion_WithoutLogprobs(t *testing.T) {}}-func TestToChunks_SplitsThinkingAndContent(t *testing.T) {+func TestToStreamChunks_SplitsThinkingAndContent(t *testing.T) {resp := api.ChatResponse{Model: "test-model",Message: api.Message{@@ -517,7 +518,7 @@ func TestToChunks_SplitsThinkingAndContent(t *testing.T) {DoneReason: "stop",}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 2 {t.Fatalf("expected 2 chunks, got %d", len(chunks))}@@ -526,8 +527,8 @@ func TestToChunks_SplitsThinkingAndContent(t *testing.T) {if reasoning.Delta.Reasoning != "step-by-step" {t.Fatalf("expected reasoning chunk to contain thinking, got %q", reasoning.Delta.Reasoning)}- if reasoning.Delta.Content != "" {- t.Fatalf("expected reasoning chunk content to be empty, got %v", reasoning.Delta.Content)+ if reasoning.Delta.Content != nil {+ t.Fatalf("expected reasoning chunk content to be nil, got %v", reasoning.Delta.Content)}if len(reasoning.Delta.ToolCalls) != 0 {t.Fatalf("expected reasoning chunk tool calls to be empty, got %d", len(reasoning.Delta.ToolCalls))@@ -535,6 +536,9 @@ func TestToChunks_SplitsThinkingAndContent(t *testing.T) {if reasoning.FinishReason != nil {t.Fatalf("expected reasoning chunk finish reason to be nil, got %q", *reasoning.FinishReason)}+ if reasoning.Delta.Role != "assistant" {+ t.Fatalf("expected reasoning chunk role %q, got %q", "assistant", reasoning.Delta.Role)+ }content := chunks[1].Choices[0]if content.Delta.Reasoning != "" {@@ -543,12 +547,15 @@ func TestToChunks_SplitsThinkingAndContent(t *testing.T) {if content.Delta.Content != "final answer" {t.Fatalf("expected content chunk content %q, got %v", "final answer", content.Delta.Content)}- if content.FinishReason == nil || *content.FinishReason != "stop" {- t.Fatalf("expected content chunk finish reason %q, got %v", "stop", content.FinishReason)+ if content.FinishReason != nil {+ t.Fatalf("expected content chunk finish reason to be nil, got %v", content.FinishReason)+ }+ if content.Delta.Role != "" {+ t.Fatalf("expected content chunk role to be empty, got %q", content.Delta.Role)}}-func TestToChunks_SplitsThinkingAndToolCalls(t *testing.T) {+func TestToStreamChunks_SplitsThinkingAndToolCalls(t *testing.T) {resp := api.ChatResponse{Model: "test-model",Message: api.Message{@@ -570,7 +577,7 @@ func TestToChunks_SplitsThinkingAndToolCalls(t *testing.T) {DoneReason: "stop",}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 2 {t.Fatalf("expected 2 chunks, got %d", len(chunks))}@@ -596,12 +603,12 @@ func TestToChunks_SplitsThinkingAndToolCalls(t *testing.T) {if toolCallChunk.Delta.ToolCalls[0].ID != "call_123" {t.Fatalf("expected tool call id %q, got %q", "call_123", toolCallChunk.Delta.ToolCalls[0].ID)}- if toolCallChunk.FinishReason == nil || *toolCallChunk.FinishReason != finishReasonToolCalls {- t.Fatalf("expected tool-call chunk finish reason %q, got %v", finishReasonToolCalls, toolCallChunk.FinishReason)+ if toolCallChunk.FinishReason != nil {+ t.Fatalf("expected tool-call chunk finish reason to be nil, got %v", toolCallChunk.FinishReason)}}-func TestToChunks_SingleChunkForNonMixedResponses(t *testing.T) {+func TestToStreamChunks_SingleChunkForNonMixedResponses(t *testing.T) {toolCalls := []api.ToolCall{{ID: "call_456",@@ -640,7 +647,7 @@ func TestToChunks_SingleChunkForNonMixedResponses(t *testing.T) {Message: tt.message,}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 1 {t.Fatalf("expected 1 chunk, got %d", len(chunks))}@@ -648,7 +655,7 @@ func TestToChunks_SingleChunkForNonMixedResponses(t *testing.T) {}}-func TestToChunks_SplitsThinkingAndToolCallsWhenNotDone(t *testing.T) {+func TestToStreamChunks_SplitsThinkingAndToolCallsWhenNotDone(t *testing.T) {resp := api.ChatResponse{Model: "test-model",Message: api.Message{@@ -669,7 +676,7 @@ func TestToChunks_SplitsThinkingAndToolCallsWhenNotDone(t *testing.T) {Done: false,}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 2 {t.Fatalf("expected 2 chunks, got %d", len(chunks))}@@ -694,7 +701,7 @@ func TestToChunks_SplitsThinkingAndToolCallsWhenNotDone(t *testing.T) {}}-func TestToChunks_SplitsThinkingAndContentWhenNotDone(t *testing.T) {+func TestToStreamChunks_SplitsThinkingAndContentWhenNotDone(t *testing.T) {resp := api.ChatResponse{Model: "test-model",Message: api.Message{@@ -704,7 +711,7 @@ func TestToChunks_SplitsThinkingAndContentWhenNotDone(t *testing.T) {Done: false,}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 2 {t.Fatalf("expected 2 chunks, got %d", len(chunks))}@@ -726,7 +733,7 @@ func TestToChunks_SplitsThinkingAndContentWhenNotDone(t *testing.T) {}}-func TestToChunks_SplitSendsLogprobsOnlyOnFirstChunk(t *testing.T) {+func TestToStreamChunks_SplitSendsLogprobsOnlyOnFirstChunk(t *testing.T) {resp := api.ChatResponse{Model: "test-model",Message: api.Message{@@ -745,7 +752,7 @@ func TestToChunks_SplitSendsLogprobsOnlyOnFirstChunk(t *testing.T) {DoneReason: "stop",}- chunks := ToChunks("test-id", resp, false)+ chunks := ToStreamChunks("test-id", resp, true)if len(chunks) != 2 {t.Fatalf("expected 2 chunks, got %d", len(chunks))}@@ -764,28 +771,244 @@ func TestToChunks_SplitSendsLogprobsOnlyOnFirstChunk(t *testing.T) {}}-func TestToChunk_LegacyMixedThinkingAndContentSingleChunk(t *testing.T) {- resp := api.ChatResponse{- Model: "test-model",- Message: api.Message{- Thinking: "reasoning",- Content: "answer",+func TestFinishChunk(t *testing.T) {+ tests := []struct {+ name string+ doneReason string+ toolCallSent bool+ expectedReason string+ }{+ {+ name: "stop",+ doneReason: "stop",+ toolCallSent: false,+ expectedReason: "stop",},- Done: true,- DoneReason: "stop",+ {+ name: "length",+ doneReason: "length",+ toolCallSent: false,+ expectedReason: "length",+ },+ {+ name: "tool_calls",+ doneReason: "stop",+ toolCallSent: true,+ expectedReason: "tool_calls",+ },+ {+ name: "length_with_tool_calls",+ doneReason: "length",+ toolCallSent: true,+ expectedReason: "length",+ },+ {+ name: "empty_reason_defaults_to_stop",+ doneReason: "",+ toolCallSent: false,+ expectedReason: "stop",+ },+ {+ name: "unknown_reason_passes_through",+ doneReason: "unload",+ toolCallSent: false,+ expectedReason: "unload",+ },+ {+ name: "unknown_reason_not_relabeled_tool_calls",+ doneReason: "unload",+ toolCallSent: true,+ expectedReason: "unload",+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ chunk := FinishChunk("test-id", api.ChatResponse{Model: "test-model", DoneReason: tt.doneReason}, tt.toolCallSent)+ if len(chunk.Choices) != 1 {+ t.Fatalf("expected 1 choice, got %d", len(chunk.Choices))+ }+ choice := chunk.Choices[0]+ if choice.Delta.Content != nil || choice.Delta.Reasoning != "" || len(choice.Delta.ToolCalls) != 0 || choice.Delta.Role != "" {+ t.Fatalf("expected empty delta, got %+v", choice.Delta)+ }+ if choice.FinishReason == nil || *choice.FinishReason != tt.expectedReason {+ t.Fatalf("expected finish reason %q, got %v", tt.expectedReason, choice.FinishReason)+ }+ })+ }+}++func TestFinishChunk_JSONDeltaEmpty(t *testing.T) {+ chunk := FinishChunk("test-id", api.ChatResponse{Model: "test-model", DoneReason: "stop"}, false)+ d, err := json.Marshal(chunk)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }++ // Parse back as generic JSON to inspect the delta field+ var raw map[string]any+ if err := json.Unmarshal(d, &raw); err != nil {+ t.Fatalf("unmarshal raw: %v", err)+ }++ choices := raw["choices"].([]any)+ choice := choices[0].(map[string]any)+ delta := choice["delta"].(map[string]any)++ // The delta must be completely empty {} — no role, content, or other fields+ if len(delta) != 0 {+ t.Fatalf("expected empty delta {}, got %v", delta)+ }++ if choice["finish_reason"] != "stop" {+ t.Fatalf("expected finish_reason %q, got %v", "stop", choice["finish_reason"])+ }+}++func TestToStreamChunks_RoleOnlyWhenRequested(t *testing.T) {+ resp := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "hello"},}- chunk := ToChunk("test-id", resp, false)- if len(chunk.Choices) != 1 {- t.Fatalf("expected 1 choice, got %d", len(chunk.Choices))+ // With includeRole=true, delta should have role+ withRole := ToStreamChunks("test-id", resp, true)+ if withRole[0].Choices[0].Delta.Role != "assistant" {+ t.Fatalf("expected role %q, got %q", "assistant", withRole[0].Choices[0].Delta.Role)}- delta := chunk.Choices[0].Delta- if delta.Reasoning != "reasoning" {- t.Fatalf("expected reasoning %q, got %q", "reasoning", delta.Reasoning)+ // With includeRole=false, delta should omit role+ withoutRole := ToStreamChunks("test-id", resp, false)+ if withoutRole[0].Choices[0].Delta.Role != "" {+ t.Fatalf("expected empty role, got %q", withoutRole[0].Choices[0].Delta.Role)}- if delta.Content != "answer" {- t.Fatalf("expected content %q, got %v", "answer", delta.Content)+}++func TestToStreamChunks_ContentChunkJSON(t *testing.T) {+ resp := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: "Hi"},+ }++ chunks := ToStreamChunks("test-id", resp, false)+ d, err := json.Marshal(chunks[0])+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }++ var raw map[string]any+ if err := json.Unmarshal(d, &raw); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ choices := raw["choices"].([]any)+ delta := choices[0].(map[string]any)["delta"].(map[string]any)++ // Content should be present+ if delta["content"] != "Hi" {+ t.Fatalf("expected content %q, got %v", "Hi", delta["content"])+ }+ // Role should be absent (includeRole=false)+ if _, hasRole := delta["role"]; hasRole {+ t.Fatalf("expected role to be absent, got %v", delta["role"])+ }+ // Reasoning should be absent+ if _, hasReasoning := delta["reasoning"]; hasReasoning {+ t.Fatalf("expected reasoning to be absent, got %v", delta["reasoning"])+ }+}++func TestToStreamChunks_EmptyContentChunkJSON(t *testing.T) {+ resp := api.ChatResponse{+ Model: "test-model",+ Message: api.Message{Content: ""},+ }++ chunks := ToStreamChunks("test-id", resp, true)+ if len(chunks) != 1 {+ t.Fatalf("expected 1 chunk, got %d", len(chunks))+ }++ d, err := json.Marshal(chunks[0])+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }++ var raw map[string]any+ if err := json.Unmarshal(d, &raw); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ delta := raw["choices"].([]any)[0].(map[string]any)["delta"].(map[string]any)++ // Empty-string content must serialize explicitly as "content":"" (OpenAI's+ // first chunk is {"role":"assistant","content":""}); only nil content is omitted.+ content, hasContent := delta["content"]+ if !hasContent {+ t.Fatalf("expected content key to be present for empty-string content, got %v", delta)+ }+ if content != "" {+ t.Fatalf("expected content %q, got %v", "", content)+ }+ if delta["role"] != "assistant" {+ t.Fatalf("expected role %q, got %v", "assistant", delta["role"])+ }+ if _, hasReasoning := delta["reasoning"]; hasReasoning {+ t.Fatalf("expected reasoning to be absent, got %v", delta["reasoning"])+ }+}++func TestToChatCompletion_FinishReasonPrecedence(t *testing.T) {+ newToolCallResponse := func(doneReason string) api.ChatResponse {+ return api.ChatResponse{+ Model: "test-model",+ Message: api.Message{+ Role: "assistant",+ ToolCalls: []api.ToolCall{+ {+ ID: "call_123",+ Function: api.ToolCallFunction{+ Index: 0,+ Name: "get_weather",+ Arguments: testArgs(map[string]any{+ "location": "Seattle",+ }),+ },+ },+ },+ },+ Done: true,+ DoneReason: doneReason,+ }+ }++ // A truncated tool-call response keeps "length" rather than "tool_calls".+ if got := *ToChatCompletion("test-id", newToolCallResponse("length")).Choices[0].FinishReason; got != "length" {+ t.Fatalf("expected finish reason %q for truncated tool-call response, got %q", "length", got)+ }+ // A completed tool-call response reports "tool_calls".+ if got := *ToChatCompletion("test-id", newToolCallResponse("stop")).Choices[0].FinishReason; got != "tool_calls" {+ t.Fatalf("expected finish reason %q for completed tool-call response, got %q", "tool_calls", got)+ }+ // An unrelated finish reason passes through unchanged.+ if got := *ToChatCompletion("test-id", newToolCallResponse("unload")).Choices[0].FinishReason; got != "unload" {+ t.Fatalf("expected unknown finish reason %q to pass through, got %q", "unload", got)+ }+}++func TestFinishChunk_UsesResponseCreatedAt(t *testing.T) {+ resp := api.ChatResponse{+ Model: "test-model",+ DoneReason: "stop",+ CreatedAt: time.Unix(1700000000, 0),+ }+ if got := FinishChunk("test-id", resp, false).Created; got != 1700000000 {+ t.Fatalf("expected created %d, got %d", 1700000000, got)+ }++ // A zero CreatedAt falls back to the current time.+ zero := api.ChatResponse{Model: "test-model", DoneReason: "stop"}+ if got := FinishChunk("test-id", zero, false).Created; got <= 1700000000 {+ t.Fatalf("expected fallback created to be the current time, got %d", got)}}