@@ -20,6 +20,8 @@ import (
20
20
"github.com/ollama/ollama/types/model"
21
21
)
22
22
23
+ var finishReasonToolCalls = "tool_calls"
24
+
23
25
type Error struct {
24
26
Message string `json:"message"`
25
27
Type string `json:"type"`
@@ -266,7 +268,7 @@ func toChatCompletion(id string, r api.ChatResponse) ChatCompletion {
266
268
}
267
269
}
268
270
269
- func toChunk (id string , r api.ChatResponse ) ChatCompletionChunk {
271
+ func toChunk (id string , r api.ChatResponse , toolCallSent bool ) ChatCompletionChunk {
270
272
toolCalls := toToolCalls (r .Message .ToolCalls )
271
273
return ChatCompletionChunk {
272
274
Id : id ,
@@ -279,6 +281,9 @@ func toChunk(id string, r api.ChatResponse) ChatCompletionChunk {
279
281
Delta : Message {Role : "assistant" , Content : r .Message .Content , ToolCalls : toolCalls },
280
282
FinishReason : func (reason string ) * string {
281
283
if len (reason ) > 0 {
284
+ if toolCallSent {
285
+ return & finishReasonToolCalls
286
+ }
282
287
return & reason
283
288
}
284
289
return nil
@@ -585,6 +590,7 @@ type ChatWriter struct {
585
590
stream bool
586
591
streamOptions * StreamOptions
587
592
id string
593
+ toolCallSent bool
588
594
BaseWriter
589
595
}
590
596
@@ -634,11 +640,14 @@ func (w *ChatWriter) writeResponse(data []byte) (int, error) {
634
640
635
641
// chat chunk
636
642
if w .stream {
637
- c := toChunk (w .id , chatResponse )
643
+ c := toChunk (w .id , chatResponse , w . toolCallSent )
638
644
d , err := json .Marshal (c )
639
645
if err != nil {
640
646
return 0 , err
641
647
}
648
+ if ! w .toolCallSent && len (c .Choices ) > 0 && len (c .Choices [0 ].Delta .ToolCalls ) > 0 {
649
+ w .toolCallSent = true
650
+ }
642
651
643
652
w .ResponseWriter .Header ().Set ("Content-Type" , "text/event-stream" )
644
653
_ , err = w .ResponseWriter .Write ([]byte (fmt .Sprintf ("data: %s\n \n " , d )))
0 commit comments