openai.go 26.8 KB
Newer Older
1
2
3
4
5
// openai package provides middleware for partial compatibility with the OpenAI REST API
package openai

import (
	"bytes"
6
	"encoding/base64"
7
	"encoding/json"
Michael Yang's avatar
lint  
Michael Yang committed
8
	"errors"
9
10
	"fmt"
	"io"
royjhan's avatar
royjhan committed
11
	"log/slog"
12
13
	"math/rand"
	"net/http"
14
	"strings"
15
16
17
	"time"

	"github.com/gin-gonic/gin"
Michael Yang's avatar
lint  
Michael Yang committed
18

19
	"github.com/ollama/ollama/api"
20
	"github.com/ollama/ollama/types/model"
21
22
)

23
24
var finishReasonToolCalls = "tool_calls"

25
type Error struct {
26
27
28
29
	Message string  `json:"message"`
	Type    string  `json:"type"`
	Param   any     `json:"param"`
	Code    *string `json:"code"`
30
31
32
33
34
35
36
}

type ErrorResponse struct {
	Error Error `json:"error"`
}

type Message struct {
37
38
39
40
41
42
	Role       string     `json:"role"`
	Content    any        `json:"content"`
	Reasoning  string     `json:"reasoning,omitempty"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
	Name       string     `json:"name,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
43
44
45
46
47
48
49
50
51
52
53
54
55
56
}

type Choice struct {
	Index        int     `json:"index"`
	Message      Message `json:"message"`
	FinishReason *string `json:"finish_reason"`
}

type ChunkChoice struct {
	Index        int     `json:"index"`
	Delta        Message `json:"delta"`
	FinishReason *string `json:"finish_reason"`
}

57
58
59
60
61
62
type CompleteChunkChoice struct {
	Text         string  `json:"text"`
	Index        int     `json:"index"`
	FinishReason *string `json:"finish_reason"`
}

63
64
65
66
67
68
69
type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

type ResponseFormat struct {
70
71
72
73
74
	Type       string      `json:"type"`
	JsonSchema *JsonSchema `json:"json_schema,omitempty"`
}

type JsonSchema struct {
75
	Schema json.RawMessage `json:"schema"`
76
77
}

78
type EmbedRequest struct {
79
80
81
	Input      any    `json:"input"`
	Model      string `json:"model"`
	Dimensions int    `json:"dimensions,omitempty"`
82
83
}

84
85
86
87
type StreamOptions struct {
	IncludeUsage bool `json:"include_usage"`
}

Michael Yang's avatar
Michael Yang committed
88
89
90
91
type Reasoning struct {
	Effort *string `json:"effort,omitempty"`
}

92
93
94
95
type ChatCompletionRequest struct {
	Model            string          `json:"model"`
	Messages         []Message       `json:"messages"`
	Stream           bool            `json:"stream"`
96
	StreamOptions    *StreamOptions  `json:"stream_options"`
97
98
99
100
101
	MaxTokens        *int            `json:"max_tokens"`
	Seed             *int            `json:"seed"`
	Stop             any             `json:"stop"`
	Temperature      *float64        `json:"temperature"`
	FrequencyPenalty *float64        `json:"frequency_penalty"`
102
	PresencePenalty  *float64        `json:"presence_penalty"`
103
104
	TopP             *float64        `json:"top_p"`
	ResponseFormat   *ResponseFormat `json:"response_format"`
royjhan's avatar
royjhan committed
105
	Tools            []api.Tool      `json:"tools"`
Michael Yang's avatar
Michael Yang committed
106
	Reasoning        *Reasoning      `json:"reasoning,omitempty"`
107
	ReasoningEffort  *string         `json:"reasoning_effort,omitempty"`
Devon Rifkin's avatar
Devon Rifkin committed
108
	DebugRenderOnly  bool            `json:"_debug_render_only"`
109
110
111
}

type ChatCompletion struct {
Devon Rifkin's avatar
Devon Rifkin committed
112
113
114
115
116
117
118
119
	Id                string         `json:"id"`
	Object            string         `json:"object"`
	Created           int64          `json:"created"`
	Model             string         `json:"model"`
	SystemFingerprint string         `json:"system_fingerprint"`
	Choices           []Choice       `json:"choices"`
	Usage             Usage          `json:"usage,omitempty"`
	DebugInfo         *api.DebugInfo `json:"_debug_info,omitempty"`
120
121
122
123
124
125
126
127
128
}

type ChatCompletionChunk struct {
	Id                string        `json:"id"`
	Object            string        `json:"object"`
	Created           int64         `json:"created"`
	Model             string        `json:"model"`
	SystemFingerprint string        `json:"system_fingerprint"`
	Choices           []ChunkChoice `json:"choices"`
129
	Usage             *Usage        `json:"usage,omitempty"`
130
131
}

132
133
// TODO (https://github.com/ollama/ollama/issues/5259): support []string, []int and [][]int
type CompletionRequest struct {
134
135
136
137
138
139
140
141
142
143
144
145
	Model            string         `json:"model"`
	Prompt           string         `json:"prompt"`
	FrequencyPenalty float32        `json:"frequency_penalty"`
	MaxTokens        *int           `json:"max_tokens"`
	PresencePenalty  float32        `json:"presence_penalty"`
	Seed             *int           `json:"seed"`
	Stop             any            `json:"stop"`
	Stream           bool           `json:"stream"`
	StreamOptions    *StreamOptions `json:"stream_options"`
	Temperature      *float32       `json:"temperature"`
	TopP             float32        `json:"top_p"`
	Suffix           string         `json:"suffix"`
Devon Rifkin's avatar
Devon Rifkin committed
146
	DebugRenderOnly  bool           `json:"_debug_render_only"`
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
}

type Completion struct {
	Id                string                `json:"id"`
	Object            string                `json:"object"`
	Created           int64                 `json:"created"`
	Model             string                `json:"model"`
	SystemFingerprint string                `json:"system_fingerprint"`
	Choices           []CompleteChunkChoice `json:"choices"`
	Usage             Usage                 `json:"usage,omitempty"`
}

type CompletionChunk struct {
	Id                string                `json:"id"`
	Object            string                `json:"object"`
	Created           int64                 `json:"created"`
	Choices           []CompleteChunkChoice `json:"choices"`
	Model             string                `json:"model"`
	SystemFingerprint string                `json:"system_fingerprint"`
166
	Usage             *Usage                `json:"usage,omitempty"`
167
168
}

royjhan's avatar
royjhan committed
169
170
type ToolCall struct {
	ID       string `json:"id"`
171
	Index    int    `json:"index"`
royjhan's avatar
royjhan committed
172
173
174
175
176
177
178
	Type     string `json:"type"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

179
180
181
182
183
184
185
type Model struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	OwnedBy string `json:"owned_by"`
}

186
187
188
189
190
191
type Embedding struct {
	Object    string    `json:"object"`
	Embedding []float32 `json:"embedding"`
	Index     int       `json:"index"`
}

192
193
194
195
196
type ListCompletion struct {
	Object string  `json:"object"`
	Data   []Model `json:"data"`
}

197
type EmbeddingList struct {
198
199
200
201
202
203
204
205
206
	Object string         `json:"object"`
	Data   []Embedding    `json:"data"`
	Model  string         `json:"model"`
	Usage  EmbeddingUsage `json:"usage,omitempty"`
}

type EmbeddingUsage struct {
	PromptTokens int `json:"prompt_tokens"`
	TotalTokens  int `json:"total_tokens"`
207
208
}

209
210
211
212
213
214
215
216
217
218
219
220
221
222
func NewError(code int, message string) ErrorResponse {
	var etype string
	switch code {
	case http.StatusBadRequest:
		etype = "invalid_request_error"
	case http.StatusNotFound:
		etype = "not_found_error"
	default:
		etype = "api_error"
	}

	return ErrorResponse{Error{Type: etype, Message: message}}
}

223
224
225
226
227
228
229
230
func toUsage(r api.ChatResponse) Usage {
	return Usage{
		PromptTokens:     r.PromptEvalCount,
		CompletionTokens: r.EvalCount,
		TotalTokens:      r.PromptEvalCount + r.EvalCount,
	}
}

royjhan's avatar
royjhan committed
231
232
233
234
235
236
237
238
239
func toolCallId() string {
	const letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789"
	b := make([]byte, 8)
	for i := range b {
		b[i] = letterBytes[rand.Intn(len(letterBytes))]
	}
	return "call_" + strings.ToLower(string(b))
}

240
241
242
func toToolCalls(tc []api.ToolCall) []ToolCall {
	toolCalls := make([]ToolCall, len(tc))
	for i, tc := range tc {
royjhan's avatar
royjhan committed
243
244
245
		toolCalls[i].ID = toolCallId()
		toolCalls[i].Type = "function"
		toolCalls[i].Function.Name = tc.Function.Name
246
		toolCalls[i].Index = tc.Function.Index
royjhan's avatar
royjhan committed
247
248
249
250
251
252
253
254
255

		args, err := json.Marshal(tc.Function.Arguments)
		if err != nil {
			slog.Error("could not marshall function arguments to json", "error", err)
			continue
		}

		toolCalls[i].Function.Arguments = string(args)
	}
256
257
	return toolCalls
}
royjhan's avatar
royjhan committed
258

259
260
func toChatCompletion(id string, r api.ChatResponse) ChatCompletion {
	toolCalls := toToolCalls(r.Message.ToolCalls)
261
262
263
264
265
266
267
	return ChatCompletion{
		Id:                id,
		Object:            "chat.completion",
		Created:           r.CreatedAt.Unix(),
		Model:             r.Model,
		SystemFingerprint: "fp_ollama",
		Choices: []Choice{{
268
			Index:   0,
Michael Yang's avatar
Michael Yang committed
269
			Message: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls, Reasoning: r.Message.Thinking},
270
			FinishReason: func(reason string) *string {
271
272
273
				if len(toolCalls) > 0 {
					reason = "tool_calls"
				}
274
275
276
277
278
				if len(reason) > 0 {
					return &reason
				}
				return nil
			}(r.DoneReason),
Devon Rifkin's avatar
Devon Rifkin committed
279
280
		}}, Usage: toUsage(r),
		DebugInfo: r.DebugInfo,
281
282
283
	}
}

284
func toChunk(id string, r api.ChatResponse, toolCallSent bool) ChatCompletionChunk {
285
	toolCalls := toToolCalls(r.Message.ToolCalls)
286
287
288
289
290
291
	return ChatCompletionChunk{
		Id:                id,
		Object:            "chat.completion.chunk",
		Created:           time.Now().Unix(),
		Model:             r.Model,
		SystemFingerprint: "fp_ollama",
292
293
		Choices: []ChunkChoice{{
			Index: 0,
Michael Yang's avatar
Michael Yang committed
294
			Delta: Message{Role: "assistant", Content: r.Message.Content, ToolCalls: toolCalls, Reasoning: r.Message.Thinking},
295
296
			FinishReason: func(reason string) *string {
				if len(reason) > 0 {
Michael Yang's avatar
Michael Yang committed
297
					if toolCallSent || len(toolCalls) > 0 {
298
299
						return &finishReasonToolCalls
					}
300
301
302
303
304
					return &reason
				}
				return nil
			}(r.DoneReason),
		}},
305
306
307
	}
}

308
309
310
311
312
313
314
315
func toUsageGenerate(r api.GenerateResponse) Usage {
	return Usage{
		PromptTokens:     r.PromptEvalCount,
		CompletionTokens: r.EvalCount,
		TotalTokens:      r.PromptEvalCount + r.EvalCount,
	}
}

316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
func toCompletion(id string, r api.GenerateResponse) Completion {
	return Completion{
		Id:                id,
		Object:            "text_completion",
		Created:           r.CreatedAt.Unix(),
		Model:             r.Model,
		SystemFingerprint: "fp_ollama",
		Choices: []CompleteChunkChoice{{
			Text:  r.Response,
			Index: 0,
			FinishReason: func(reason string) *string {
				if len(reason) > 0 {
					return &reason
				}
				return nil
			}(r.DoneReason),
		}},
333
		Usage: toUsageGenerate(r),
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
	}
}

func toCompleteChunk(id string, r api.GenerateResponse) CompletionChunk {
	return CompletionChunk{
		Id:                id,
		Object:            "text_completion",
		Created:           time.Now().Unix(),
		Model:             r.Model,
		SystemFingerprint: "fp_ollama",
		Choices: []CompleteChunkChoice{{
			Text:  r.Response,
			Index: 0,
			FinishReason: func(reason string) *string {
				if len(reason) > 0 {
					return &reason
				}
				return nil
			}(r.DoneReason),
		}},
	}
}

357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
func toListCompletion(r api.ListResponse) ListCompletion {
	var data []Model
	for _, m := range r.Models {
		data = append(data, Model{
			Id:      m.Name,
			Object:  "model",
			Created: m.ModifiedAt.Unix(),
			OwnedBy: model.ParseName(m.Name).Namespace,
		})
	}

	return ListCompletion{
		Object: "list",
		Data:   data,
	}
}

374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
func toEmbeddingList(model string, r api.EmbedResponse) EmbeddingList {
	if r.Embeddings != nil {
		var data []Embedding
		for i, e := range r.Embeddings {
			data = append(data, Embedding{
				Object:    "embedding",
				Embedding: e,
				Index:     i,
			})
		}

		return EmbeddingList{
			Object: "list",
			Data:   data,
			Model:  model,
389
390
391
392
			Usage: EmbeddingUsage{
				PromptTokens: r.PromptEvalCount,
				TotalTokens:  r.PromptEvalCount,
			},
393
394
395
396
397
398
		}
	}

	return EmbeddingList{}
}

399
400
401
402
403
404
405
406
407
func toModel(r api.ShowResponse, m string) Model {
	return Model{
		Id:      m,
		Object:  "model",
		Created: r.ModifiedAt.Unix(),
		OwnedBy: model.ParseName(m).Namespace,
	}
}

408
func fromChatRequest(r ChatCompletionRequest) (*api.ChatRequest, error) {
409
410
	var messages []api.Message
	for _, msg := range r.Messages {
411
412
413
414
415
416
417
		toolName := ""
		if strings.ToLower(msg.Role) == "tool" {
			toolName = msg.Name
			if toolName == "" && msg.ToolCallID != "" {
				toolName = nameFromToolCallID(r.Messages, msg.ToolCallID)
			}
		}
418
419
		switch content := msg.Content.(type) {
		case string:
420
421
422
423
			toolCalls, err := fromCompletionToolCall(msg.ToolCalls)
			if err != nil {
				return nil, err
			}
424
			messages = append(messages, api.Message{Role: msg.Role, Content: content, Thinking: msg.Reasoning, ToolCalls: toolCalls, ToolName: toolName})
425
426
427
428
		case []any:
			for _, c := range content {
				data, ok := c.(map[string]any)
				if !ok {
Michael Yang's avatar
lint  
Michael Yang committed
429
					return nil, errors.New("invalid message format")
430
431
432
433
434
				}
				switch data["type"] {
				case "text":
					text, ok := data["text"].(string)
					if !ok {
Michael Yang's avatar
lint  
Michael Yang committed
435
						return nil, errors.New("invalid message format")
436
					}
437
					messages = append(messages, api.Message{Role: msg.Role, Content: text})
438
439
440
441
				case "image_url":
					var url string
					if urlMap, ok := data["image_url"].(map[string]any); ok {
						if url, ok = urlMap["url"].(string); !ok {
Michael Yang's avatar
lint  
Michael Yang committed
442
							return nil, errors.New("invalid message format")
443
444
445
						}
					} else {
						if url, ok = data["image_url"].(string); !ok {
Michael Yang's avatar
lint  
Michael Yang committed
446
							return nil, errors.New("invalid message format")
447
448
449
						}
					}

450
					types := []string{"jpeg", "jpg", "png", "webp"}
451
452
453
454
455
456
457
458
459
460
461
					valid := false
					for _, t := range types {
						prefix := "data:image/" + t + ";base64,"
						if strings.HasPrefix(url, prefix) {
							url = strings.TrimPrefix(url, prefix)
							valid = true
							break
						}
					}

					if !valid {
Michael Yang's avatar
lint  
Michael Yang committed
462
						return nil, errors.New("invalid image input")
463
464
465
466
					}

					img, err := base64.StdEncoding.DecodeString(url)
					if err != nil {
Michael Yang's avatar
lint  
Michael Yang committed
467
						return nil, errors.New("invalid message format")
468
					}
469
470

					messages = append(messages, api.Message{Role: msg.Role, Images: []api.ImageData{img}})
471
				default:
Michael Yang's avatar
lint  
Michael Yang committed
472
					return nil, errors.New("invalid message format")
473
474
				}
			}
475
476
477
478
479
480
481
482
			// since we might have added multiple messages above, if we have tools
			// calls we'll add them to the last message
			if len(messages) > 0 && len(msg.ToolCalls) > 0 {
				toolCalls, err := fromCompletionToolCall(msg.ToolCalls)
				if err != nil {
					return nil, err
				}
				messages[len(messages)-1].ToolCalls = toolCalls
483
484
485
				if toolName != "" {
					messages[len(messages)-1].ToolName = toolName
				}
486
				messages[len(messages)-1].Thinking = msg.Reasoning
487
			}
488
		default:
489
			// content is only optional if tool calls are present
royjhan's avatar
royjhan committed
490
491
492
493
494
495
496
497
498
			if msg.ToolCalls == nil {
				return nil, fmt.Errorf("invalid message content type: %T", content)
			}

			toolCalls := make([]api.ToolCall, len(msg.ToolCalls))
			for i, tc := range msg.ToolCalls {
				toolCalls[i].Function.Name = tc.Function.Name
				err := json.Unmarshal([]byte(tc.Function.Arguments), &toolCalls[i].Function.Arguments)
				if err != nil {
Michael Yang's avatar
lint  
Michael Yang committed
499
					return nil, errors.New("invalid tool call arguments")
royjhan's avatar
royjhan committed
500
501
				}
			}
502
			messages = append(messages, api.Message{Role: msg.Role, Thinking: msg.Reasoning, ToolCalls: toolCalls})
503
		}
504
505
	}

506
	options := make(map[string]any)
507
508
509
510

	switch stop := r.Stop.(type) {
	case string:
		options["stop"] = []string{stop}
511
	case []any:
512
513
514
515
516
517
518
519
520
521
522
523
524
525
		var stops []string
		for _, s := range stop {
			if str, ok := s.(string); ok {
				stops = append(stops, str)
			}
		}
		options["stop"] = stops
	}

	if r.MaxTokens != nil {
		options["num_predict"] = *r.MaxTokens
	}

	if r.Temperature != nil {
526
		options["temperature"] = *r.Temperature
527
528
529
530
531
532
533
534
535
	} else {
		options["temperature"] = 1.0
	}

	if r.Seed != nil {
		options["seed"] = *r.Seed
	}

	if r.FrequencyPenalty != nil {
536
		options["frequency_penalty"] = *r.FrequencyPenalty
537
538
539
	}

	if r.PresencePenalty != nil {
540
		options["presence_penalty"] = *r.PresencePenalty
541
542
543
544
545
546
547
548
	}

	if r.TopP != nil {
		options["top_p"] = *r.TopP
	} else {
		options["top_p"] = 1.0
	}

549
550
551
552
553
554
555
556
	var format json.RawMessage
	if r.ResponseFormat != nil {
		switch strings.ToLower(strings.TrimSpace(r.ResponseFormat.Type)) {
		// Support the old "json_object" type for OpenAI compatibility
		case "json_object":
			format = json.RawMessage(`"json"`)
		case "json_schema":
			if r.ResponseFormat.JsonSchema != nil {
557
				format = r.ResponseFormat.JsonSchema.Schema
558
559
			}
		}
560
561
	}

Michael Yang's avatar
Michael Yang committed
562
563
564
565
566
	var think *api.ThinkValue
	if r.Reasoning != nil {
		think = &api.ThinkValue{
			Value: *r.Reasoning.Effort,
		}
567
568
569
570
	} else if r.ReasoningEffort != nil {
		think = &api.ThinkValue{
			Value: *r.ReasoningEffort,
		}
Michael Yang's avatar
Michael Yang committed
571
572
	}

573
	return &api.ChatRequest{
Devon Rifkin's avatar
Devon Rifkin committed
574
575
576
577
578
579
580
581
		Model:           r.Model,
		Messages:        messages,
		Format:          format,
		Options:         options,
		Stream:          &r.Stream,
		Tools:           r.Tools,
		Think:           think,
		DebugRenderOnly: r.DebugRenderOnly,
582
	}, nil
583
584
}

585
586
587
588
589
590
591
592
593
594
595
596
597
598
func nameFromToolCallID(messages []Message, toolCallID string) string {
	// iterate backwards to be more resilient to duplicate tool call IDs (this
	// follows "last one wins")
	for i := len(messages) - 1; i >= 0; i-- {
		msg := messages[i]
		for _, tc := range msg.ToolCalls {
			if tc.ID == toolCallID {
				return tc.Function.Name
			}
		}
	}
	return ""
}

599
600
601
602
603
604
605
606
607
608
609
610
611
func fromCompletionToolCall(toolCalls []ToolCall) ([]api.ToolCall, error) {
	apiToolCalls := make([]api.ToolCall, len(toolCalls))
	for i, tc := range toolCalls {
		apiToolCalls[i].Function.Name = tc.Function.Name
		err := json.Unmarshal([]byte(tc.Function.Arguments), &apiToolCalls[i].Function.Arguments)
		if err != nil {
			return nil, errors.New("invalid tool call arguments")
		}
	}

	return apiToolCalls, nil
}

612
613
614
615
616
617
func fromCompleteRequest(r CompletionRequest) (api.GenerateRequest, error) {
	options := make(map[string]any)

	switch stop := r.Stop.(type) {
	case string:
		options["stop"] = []string{stop}
618
619
620
621
622
623
624
625
	case []any:
		var stops []string
		for _, s := range stop {
			if str, ok := s.(string); ok {
				stops = append(stops, str)
			} else {
				return api.GenerateRequest{}, fmt.Errorf("invalid type for 'stop' field: %T", s)
			}
626
		}
627
		options["stop"] = stops
628
629
630
631
632
633
634
	}

	if r.MaxTokens != nil {
		options["num_predict"] = *r.MaxTokens
	}

	if r.Temperature != nil {
635
		options["temperature"] = *r.Temperature
636
637
638
639
640
641
642
643
	} else {
		options["temperature"] = 1.0
	}

	if r.Seed != nil {
		options["seed"] = *r.Seed
	}

644
	options["frequency_penalty"] = r.FrequencyPenalty
645

646
	options["presence_penalty"] = r.PresencePenalty
647
648
649
650
651
652
653
654

	if r.TopP != 0.0 {
		options["top_p"] = r.TopP
	} else {
		options["top_p"] = 1.0
	}

	return api.GenerateRequest{
Devon Rifkin's avatar
Devon Rifkin committed
655
656
657
658
659
660
		Model:           r.Model,
		Prompt:          r.Prompt,
		Options:         options,
		Stream:          &r.Stream,
		Suffix:          r.Suffix,
		DebugRenderOnly: r.DebugRenderOnly,
661
662
663
	}, nil
}

664
665
666
667
668
type BaseWriter struct {
	gin.ResponseWriter
}

type ChatWriter struct {
669
670
671
	stream        bool
	streamOptions *StreamOptions
	id            string
672
	toolCallSent  bool
673
	BaseWriter
674
675
}

676
type CompleteWriter struct {
677
678
679
	stream        bool
	streamOptions *StreamOptions
	id            string
680
681
682
	BaseWriter
}

683
684
685
686
687
688
689
690
691
type ListWriter struct {
	BaseWriter
}

type RetrieveWriter struct {
	BaseWriter
	model string
}

692
693
694
695
696
type EmbedWriter struct {
	BaseWriter
	model string
}

697
func (w *BaseWriter) writeError(data []byte) (int, error) {
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
	var serr api.StatusError
	err := json.Unmarshal(data, &serr)
	if err != nil {
		return 0, err
	}

	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(NewError(http.StatusInternalServerError, serr.Error()))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

713
func (w *ChatWriter) writeResponse(data []byte) (int, error) {
714
715
716
717
718
719
720
721
	var chatResponse api.ChatResponse
	err := json.Unmarshal(data, &chatResponse)
	if err != nil {
		return 0, err
	}

	// chat chunk
	if w.stream {
722
		c := toChunk(w.id, chatResponse, w.toolCallSent)
723
		d, err := json.Marshal(c)
724
725
726
		if err != nil {
			return 0, err
		}
727
728
729
		if !w.toolCallSent && len(c.Choices) > 0 && len(c.Choices[0].Delta.ToolCalls) > 0 {
			w.toolCallSent = true
		}
730
731
732
733
734
735
736
737

		w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
		_, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
		if err != nil {
			return 0, err
		}

		if chatResponse.Done {
738
739
740
741
742
743
744
745
746
747
748
749
750
			if w.streamOptions != nil && w.streamOptions.IncludeUsage {
				u := toUsage(chatResponse)
				c.Usage = &u
				c.Choices = []ChunkChoice{}
				d, err := json.Marshal(c)
				if err != nil {
					return 0, err
				}
				_, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
				if err != nil {
					return 0, err
				}
			}
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
			_, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
			if err != nil {
				return 0, err
			}
		}

		return len(data), nil
	}

	// chat completion
	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(toChatCompletion(w.id, chatResponse))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

770
func (w *ChatWriter) Write(data []byte) (int, error) {
771
772
	code := w.ResponseWriter.Status()
	if code != http.StatusOK {
773
		return w.writeError(data)
774
775
776
777
778
	}

	return w.writeResponse(data)
}

779
780
781
782
783
784
785
786
787
func (w *CompleteWriter) writeResponse(data []byte) (int, error) {
	var generateResponse api.GenerateResponse
	err := json.Unmarshal(data, &generateResponse)
	if err != nil {
		return 0, err
	}

	// completion chunk
	if w.stream {
788
789
790
791
792
		c := toCompleteChunk(w.id, generateResponse)
		if w.streamOptions != nil && w.streamOptions.IncludeUsage {
			c.Usage = &Usage{}
		}
		d, err := json.Marshal(c)
793
794
795
796
797
798
799
800
801
802
803
		if err != nil {
			return 0, err
		}

		w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
		_, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
		if err != nil {
			return 0, err
		}

		if generateResponse.Done {
804
805
806
807
808
809
810
811
812
813
814
815
816
			if w.streamOptions != nil && w.streamOptions.IncludeUsage {
				u := toUsageGenerate(generateResponse)
				c.Usage = &u
				c.Choices = []CompleteChunkChoice{}
				d, err := json.Marshal(c)
				if err != nil {
					return 0, err
				}
				_, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
				if err != nil {
					return 0, err
				}
			}
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
			_, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
			if err != nil {
				return 0, err
			}
		}

		return len(data), nil
	}

	// completion
	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(toCompletion(w.id, generateResponse))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

func (w *CompleteWriter) Write(data []byte) (int, error) {
	code := w.ResponseWriter.Status()
	if code != http.StatusOK {
839
		return w.writeError(data)
840
841
842
843
844
	}

	return w.writeResponse(data)
}

845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
func (w *ListWriter) writeResponse(data []byte) (int, error) {
	var listResponse api.ListResponse
	err := json.Unmarshal(data, &listResponse)
	if err != nil {
		return 0, err
	}

	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(toListCompletion(listResponse))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

func (w *ListWriter) Write(data []byte) (int, error) {
	code := w.ResponseWriter.Status()
	if code != http.StatusOK {
864
		return w.writeError(data)
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
	}

	return w.writeResponse(data)
}

func (w *RetrieveWriter) writeResponse(data []byte) (int, error) {
	var showResponse api.ShowResponse
	err := json.Unmarshal(data, &showResponse)
	if err != nil {
		return 0, err
	}

	// retrieve completion
	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(toModel(showResponse, w.model))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

func (w *RetrieveWriter) Write(data []byte) (int, error) {
	code := w.ResponseWriter.Status()
	if code != http.StatusOK {
890
		return w.writeError(data)
891
892
893
894
895
	}

	return w.writeResponse(data)
}

896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
func (w *EmbedWriter) writeResponse(data []byte) (int, error) {
	var embedResponse api.EmbedResponse
	err := json.Unmarshal(data, &embedResponse)
	if err != nil {
		return 0, err
	}

	w.ResponseWriter.Header().Set("Content-Type", "application/json")
	err = json.NewEncoder(w.ResponseWriter).Encode(toEmbeddingList(w.model, embedResponse))
	if err != nil {
		return 0, err
	}

	return len(data), nil
}

func (w *EmbedWriter) Write(data []byte) (int, error) {
	code := w.ResponseWriter.Status()
	if code != http.StatusOK {
915
		return w.writeError(data)
916
917
918
919
920
	}

	return w.writeResponse(data)
}

921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
func ListMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		w := &ListWriter{
			BaseWriter: BaseWriter{ResponseWriter: c.Writer},
		}

		c.Writer = w

		c.Next()
	}
}

func RetrieveMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var b bytes.Buffer
		if err := json.NewEncoder(&b).Encode(api.ShowRequest{Name: c.Param("model")}); err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
			return
		}

		c.Request.Body = io.NopCloser(&b)

		// response writer
		w := &RetrieveWriter{
			BaseWriter: BaseWriter{ResponseWriter: c.Writer},
			model:      c.Param("model"),
		}

		c.Writer = w

		c.Next()
	}
}

955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
func CompletionsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req CompletionRequest
		err := c.ShouldBindJSON(&req)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
			return
		}

		var b bytes.Buffer
		genReq, err := fromCompleteRequest(req)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
			return
		}

		if err := json.NewEncoder(&b).Encode(genReq); err != nil {
			c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
			return
		}

		c.Request.Body = io.NopCloser(&b)

		w := &CompleteWriter{
979
980
981
982
			BaseWriter:    BaseWriter{ResponseWriter: c.Writer},
			stream:        req.Stream,
			id:            fmt.Sprintf("cmpl-%d", rand.Intn(999)),
			streamOptions: req.StreamOptions,
983
984
		}

985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
		c.Writer = w
		c.Next()
	}
}

func EmbeddingsMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		var req EmbedRequest
		err := c.ShouldBindJSON(&req)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
			return
		}

		if req.Input == "" {
			req.Input = []string{""}
		}

		if req.Input == nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
			return
		}

		if v, ok := req.Input.([]any); ok && len(v) == 0 {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
			return
		}

		var b bytes.Buffer
1014
		if err := json.NewEncoder(&b).Encode(api.EmbedRequest{Model: req.Model, Input: req.Input, Dimensions: req.Dimensions}); err != nil {
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
			c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
			return
		}

		c.Request.Body = io.NopCloser(&b)

		w := &EmbedWriter{
			BaseWriter: BaseWriter{ResponseWriter: c.Writer},
			model:      req.Model,
		}

1026
1027
1028
1029
1030
1031
		c.Writer = w

		c.Next()
	}
}

1032
func ChatMiddleware() gin.HandlerFunc {
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
	return func(c *gin.Context) {
		var req ChatCompletionRequest
		err := c.ShouldBindJSON(&req)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
			return
		}

		if len(req.Messages) == 0 {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "[] is too short - 'messages'"))
			return
		}

		var b bytes.Buffer
1047
1048
1049
1050

		chatReq, err := fromChatRequest(req)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
1051
			return
1052
1053
1054
		}

		if err := json.NewEncoder(&b).Encode(chatReq); err != nil {
1055
1056
1057
1058
1059
1060
			c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
			return
		}

		c.Request.Body = io.NopCloser(&b)

1061
		w := &ChatWriter{
1062
1063
1064
1065
			BaseWriter:    BaseWriter{ResponseWriter: c.Writer},
			stream:        req.Stream,
			id:            fmt.Sprintf("chatcmpl-%d", rand.Intn(999)),
			streamOptions: req.StreamOptions,
1066
1067
1068
1069
1070
1071
1072
		}

		c.Writer = w

		c.Next()
	}
}