openai.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997
  1. // openai package provides middleware for partial compatibility with the OpenAI REST API
  2. package openai
  3. import (
  4. "bytes"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "log/slog"
  11. "math/rand"
  12. "net/http"
  13. "strings"
  14. "time"
  15. "github.com/gin-gonic/gin"
  16. "github.com/ollama/ollama/api"
  17. "github.com/ollama/ollama/types/model"
  18. )
  19. type Error struct {
  20. Message string `json:"message"`
  21. Type string `json:"type"`
  22. Param interface{} `json:"param"`
  23. Code *string `json:"code"`
  24. }
  25. type ErrorResponse struct {
  26. Error Error `json:"error"`
  27. }
  28. type Message struct {
  29. Role string `json:"role"`
  30. Content any `json:"content"`
  31. ToolCalls []ToolCall `json:"tool_calls,omitempty"`
  32. }
  33. type Choice struct {
  34. Index int `json:"index"`
  35. Message Message `json:"message"`
  36. FinishReason *string `json:"finish_reason"`
  37. }
  38. type ChunkChoice struct {
  39. Index int `json:"index"`
  40. Delta Message `json:"delta"`
  41. FinishReason *string `json:"finish_reason"`
  42. }
  43. type CompleteChunkChoice struct {
  44. Text string `json:"text"`
  45. Index int `json:"index"`
  46. FinishReason *string `json:"finish_reason"`
  47. }
  48. type Usage struct {
  49. PromptTokens int `json:"prompt_tokens"`
  50. CompletionTokens int `json:"completion_tokens"`
  51. TotalTokens int `json:"total_tokens"`
  52. }
  53. type ResponseFormat struct {
  54. Type string `json:"type"`
  55. JsonSchema *JsonSchema `json:"json_schema,omitempty"`
  56. }
  57. type JsonSchema struct {
  58. Schema json.RawMessage `json:"schema"`
  59. }
  60. type EmbedRequest struct {
  61. Input any `json:"input"`
  62. Model string `json:"model"`
  63. }
  64. type StreamOptions struct {
  65. IncludeUsage bool `json:"include_usage"`
  66. }
  67. type ChatCompletionRequest struct {
  68. Model string `json:"model"`
  69. Messages []Message `json:"messages"`
  70. Stream bool `json:"stream"`
  71. StreamOptions *StreamOptions `json:"stream_options"`
  72. MaxCompletionTokens *int `json:"max_completion_tokens"`
  73. // Deprecated: Use [ChatCompletionRequest.MaxCompletionTokens]
  74. MaxTokens *int `json:"max_tokens"`
  75. Seed *int `json:"seed"`
  76. Stop any `json:"stop"`
  77. Temperature *float64 `json:"temperature"`
  78. FrequencyPenalty *float64 `json:"frequency_penalty"`
  79. PresencePenalty *float64 `json:"presence_penalty"`
  80. TopP *float64 `json:"top_p"`
  81. ResponseFormat *ResponseFormat `json:"response_format"`
  82. Tools []api.Tool `json:"tools"`
  83. ContextLength *int `json:"context_length"`
  84. }
  85. type ChatCompletion struct {
  86. Id string `json:"id"`
  87. Object string `json:"object"`
  88. Created int64 `json:"created"`
  89. Model string `json:"model"`
  90. SystemFingerprint string `json:"system_fingerprint"`
  91. Choices []Choice `json:"choices"`
  92. Usage Usage `json:"usage,omitempty"`
  93. }
  94. type ChatCompletionChunk struct {
  95. Id string `json:"id"`
  96. Object string `json:"object"`
  97. Created int64 `json:"created"`
  98. Model string `json:"model"`
  99. SystemFingerprint string `json:"system_fingerprint"`
  100. Choices []ChunkChoice `json:"choices"`
  101. Usage *Usage `json:"usage,omitempty"`
  102. }
  103. // TODO (https://github.com/ollama/ollama/issues/5259): support []string, []int and [][]int
  104. type CompletionRequest struct {
  105. Model string `json:"model"`
  106. Prompt string `json:"prompt"`
  107. FrequencyPenalty float32 `json:"frequency_penalty"`
  108. MaxTokens *int `json:"max_tokens"`
  109. PresencePenalty float32 `json:"presence_penalty"`
  110. Seed *int `json:"seed"`
  111. Stop any `json:"stop"`
  112. Stream bool `json:"stream"`
  113. StreamOptions *StreamOptions `json:"stream_options"`
  114. Temperature *float32 `json:"temperature"`
  115. TopP float32 `json:"top_p"`
  116. Suffix string `json:"suffix"`
  117. }
  118. type Completion struct {
  119. Id string `json:"id"`
  120. Object string `json:"object"`
  121. Created int64 `json:"created"`
  122. Model string `json:"model"`
  123. SystemFingerprint string `json:"system_fingerprint"`
  124. Choices []CompleteChunkChoice `json:"choices"`
  125. Usage Usage `json:"usage,omitempty"`
  126. }
  127. type CompletionChunk struct {
  128. Id string `json:"id"`
  129. Object string `json:"object"`
  130. Created int64 `json:"created"`
  131. Choices []CompleteChunkChoice `json:"choices"`
  132. Model string `json:"model"`
  133. SystemFingerprint string `json:"system_fingerprint"`
  134. Usage *Usage `json:"usage,omitempty"`
  135. }
  136. type ToolCall struct {
  137. ID string `json:"id"`
  138. Index int `json:"index"`
  139. Type string `json:"type"`
  140. Function struct {
  141. Name string `json:"name"`
  142. Arguments string `json:"arguments"`
  143. } `json:"function"`
  144. }
  145. type Model struct {
  146. Id string `json:"id"`
  147. Object string `json:"object"`
  148. Created int64 `json:"created"`
  149. OwnedBy string `json:"owned_by"`
  150. }
  151. type Embedding struct {
  152. Object string `json:"object"`
  153. Embedding []float32 `json:"embedding"`
  154. Index int `json:"index"`
  155. }
  156. type ListCompletion struct {
  157. Object string `json:"object"`
  158. Data []Model `json:"data"`
  159. }
  160. type EmbeddingList struct {
  161. Object string `json:"object"`
  162. Data []Embedding `json:"data"`
  163. Model string `json:"model"`
  164. Usage EmbeddingUsage `json:"usage,omitempty"`
  165. }
  166. type EmbeddingUsage struct {
  167. PromptTokens int `json:"prompt_tokens"`
  168. TotalTokens int `json:"total_tokens"`
  169. }
  170. func NewError(code int, message string) ErrorResponse {
  171. var etype string
  172. switch code {
  173. case http.StatusBadRequest:
  174. etype = "invalid_request_error"
  175. case http.StatusNotFound:
  176. etype = "not_found_error"
  177. default:
  178. etype = "api_error"
  179. }
  180. return ErrorResponse{Error{Type: etype, Message: message}}
  181. }
  182. func toUsage(r api.ChatResponse) Usage {
  183. return Usage{
  184. PromptTokens: r.PromptEvalCount,
  185. CompletionTokens: r.EvalCount,
  186. TotalTokens: r.PromptEvalCount + r.EvalCount,
  187. }
  188. }
  189. func toolCallId() string {
  190. const letterBytes = "abcdefghijklmnopqrstuvwxyz0123456789"
  191. b := make([]byte, 8)
  192. for i := range b {
  193. b[i] = letterBytes[rand.Intn(len(letterBytes))]
  194. }
  195. return "call_" + strings.ToLower(string(b))
  196. }
  197. func toToolCalls(tc []api.ToolCall) []ToolCall {
  198. toolCalls := make([]ToolCall, len(tc))
  199. for i, tc := range tc {
  200. toolCalls[i].ID = toolCallId()
  201. toolCalls[i].Type = "function"
  202. toolCalls[i].Function.Name = tc.Function.Name
  203. toolCalls[i].Index = tc.Function.Index
  204. args, err := json.Marshal(tc.Function.Arguments)
  205. if err != nil {
  206. slog.Error("could not marshall function arguments to json", "error", err)
  207. continue
  208. }
  209. toolCalls[i].Function.Arguments = string(args)
  210. }
  211. return toolCalls
  212. }
  213. func toChatCompletion(id string, r api.ChatResponse) ChatCompletion {
  214. toolCalls := toToolCalls(r.Message.ToolCalls)
  215. return ChatCompletion{
  216. Id: id,
  217. Object: "chat.completion",
  218. Created: r.CreatedAt.Unix(),
  219. Model: r.Model,
  220. SystemFingerprint: "fp_ollama",
  221. Choices: []Choice{{
  222. Index: 0,
  223. Message: Message{Role: r.Message.Role, Content: r.Message.Content, ToolCalls: toolCalls},
  224. FinishReason: func(reason string) *string {
  225. if len(toolCalls) > 0 {
  226. reason = "tool_calls"
  227. }
  228. if len(reason) > 0 {
  229. return &reason
  230. }
  231. return nil
  232. }(r.DoneReason),
  233. }},
  234. Usage: toUsage(r),
  235. }
  236. }
  237. func toChunk(id string, r api.ChatResponse) ChatCompletionChunk {
  238. toolCalls := toToolCalls(r.Message.ToolCalls)
  239. return ChatCompletionChunk{
  240. Id: id,
  241. Object: "chat.completion.chunk",
  242. Created: time.Now().Unix(),
  243. Model: r.Model,
  244. SystemFingerprint: "fp_ollama",
  245. Choices: []ChunkChoice{{
  246. Index: 0,
  247. Delta: Message{Role: "assistant", Content: r.Message.Content, ToolCalls: toolCalls},
  248. FinishReason: func(reason string) *string {
  249. if len(reason) > 0 {
  250. return &reason
  251. }
  252. return nil
  253. }(r.DoneReason),
  254. }},
  255. }
  256. }
  257. func toUsageGenerate(r api.GenerateResponse) Usage {
  258. return Usage{
  259. PromptTokens: r.PromptEvalCount,
  260. CompletionTokens: r.EvalCount,
  261. TotalTokens: r.PromptEvalCount + r.EvalCount,
  262. }
  263. }
  264. func toCompletion(id string, r api.GenerateResponse) Completion {
  265. return Completion{
  266. Id: id,
  267. Object: "text_completion",
  268. Created: r.CreatedAt.Unix(),
  269. Model: r.Model,
  270. SystemFingerprint: "fp_ollama",
  271. Choices: []CompleteChunkChoice{{
  272. Text: r.Response,
  273. Index: 0,
  274. FinishReason: func(reason string) *string {
  275. if len(reason) > 0 {
  276. return &reason
  277. }
  278. return nil
  279. }(r.DoneReason),
  280. }},
  281. Usage: toUsageGenerate(r),
  282. }
  283. }
  284. func toCompleteChunk(id string, r api.GenerateResponse) CompletionChunk {
  285. return CompletionChunk{
  286. Id: id,
  287. Object: "text_completion",
  288. Created: time.Now().Unix(),
  289. Model: r.Model,
  290. SystemFingerprint: "fp_ollama",
  291. Choices: []CompleteChunkChoice{{
  292. Text: r.Response,
  293. Index: 0,
  294. FinishReason: func(reason string) *string {
  295. if len(reason) > 0 {
  296. return &reason
  297. }
  298. return nil
  299. }(r.DoneReason),
  300. }},
  301. }
  302. }
  303. func toListCompletion(r api.ListResponse) ListCompletion {
  304. var data []Model
  305. for _, m := range r.Models {
  306. data = append(data, Model{
  307. Id: m.Name,
  308. Object: "model",
  309. Created: m.ModifiedAt.Unix(),
  310. OwnedBy: model.ParseName(m.Name).Namespace,
  311. })
  312. }
  313. return ListCompletion{
  314. Object: "list",
  315. Data: data,
  316. }
  317. }
  318. func toEmbeddingList(model string, r api.EmbedResponse) EmbeddingList {
  319. if r.Embeddings != nil {
  320. var data []Embedding
  321. for i, e := range r.Embeddings {
  322. data = append(data, Embedding{
  323. Object: "embedding",
  324. Embedding: e,
  325. Index: i,
  326. })
  327. }
  328. return EmbeddingList{
  329. Object: "list",
  330. Data: data,
  331. Model: model,
  332. Usage: EmbeddingUsage{
  333. PromptTokens: r.PromptEvalCount,
  334. TotalTokens: r.PromptEvalCount,
  335. },
  336. }
  337. }
  338. return EmbeddingList{}
  339. }
  340. func toModel(r api.ShowResponse, m string) Model {
  341. return Model{
  342. Id: m,
  343. Object: "model",
  344. Created: r.ModifiedAt.Unix(),
  345. OwnedBy: model.ParseName(m).Namespace,
  346. }
  347. }
  348. func fromChatRequest(r ChatCompletionRequest) (*api.ChatRequest, error) {
  349. var messages []api.Message
  350. for _, msg := range r.Messages {
  351. switch content := msg.Content.(type) {
  352. case string:
  353. messages = append(messages, api.Message{Role: msg.Role, Content: content})
  354. case []any:
  355. for _, c := range content {
  356. data, ok := c.(map[string]any)
  357. if !ok {
  358. return nil, errors.New("invalid message format")
  359. }
  360. switch data["type"] {
  361. case "text":
  362. text, ok := data["text"].(string)
  363. if !ok {
  364. return nil, errors.New("invalid message format")
  365. }
  366. messages = append(messages, api.Message{Role: msg.Role, Content: text})
  367. case "image_url":
  368. var url string
  369. if urlMap, ok := data["image_url"].(map[string]any); ok {
  370. if url, ok = urlMap["url"].(string); !ok {
  371. return nil, errors.New("invalid message format")
  372. }
  373. } else {
  374. if url, ok = data["image_url"].(string); !ok {
  375. return nil, errors.New("invalid message format")
  376. }
  377. }
  378. types := []string{"jpeg", "jpg", "png"}
  379. valid := false
  380. for _, t := range types {
  381. prefix := "data:image/" + t + ";base64,"
  382. if strings.HasPrefix(url, prefix) {
  383. url = strings.TrimPrefix(url, prefix)
  384. valid = true
  385. break
  386. }
  387. }
  388. if !valid {
  389. return nil, errors.New("invalid image input")
  390. }
  391. img, err := base64.StdEncoding.DecodeString(url)
  392. if err != nil {
  393. return nil, errors.New("invalid message format")
  394. }
  395. messages = append(messages, api.Message{Role: msg.Role, Images: []api.ImageData{img}})
  396. default:
  397. return nil, errors.New("invalid message format")
  398. }
  399. }
  400. default:
  401. if msg.ToolCalls == nil {
  402. return nil, fmt.Errorf("invalid message content type: %T", content)
  403. }
  404. toolCalls := make([]api.ToolCall, len(msg.ToolCalls))
  405. for i, tc := range msg.ToolCalls {
  406. toolCalls[i].Function.Name = tc.Function.Name
  407. err := json.Unmarshal([]byte(tc.Function.Arguments), &toolCalls[i].Function.Arguments)
  408. if err != nil {
  409. return nil, errors.New("invalid tool call arguments")
  410. }
  411. }
  412. messages = append(messages, api.Message{Role: msg.Role, ToolCalls: toolCalls})
  413. }
  414. }
  415. options := make(map[string]interface{})
  416. switch stop := r.Stop.(type) {
  417. case string:
  418. options["stop"] = []string{stop}
  419. case []any:
  420. var stops []string
  421. for _, s := range stop {
  422. if str, ok := s.(string); ok {
  423. stops = append(stops, str)
  424. }
  425. }
  426. options["stop"] = stops
  427. }
  428. if r.ContextLength != nil {
  429. options["num_ctx"] = *r.ContextLength
  430. }
  431. // Deprecated: MaxTokens is deprecated, use MaxCompletionTokens instead
  432. if r.MaxTokens != nil {
  433. r.MaxCompletionTokens = r.MaxTokens
  434. }
  435. if r.MaxCompletionTokens != nil {
  436. options["num_predict"] = *r.MaxCompletionTokens
  437. }
  438. if r.Temperature != nil {
  439. options["temperature"] = *r.Temperature
  440. } else {
  441. options["temperature"] = 1.0
  442. }
  443. if r.Seed != nil {
  444. options["seed"] = *r.Seed
  445. }
  446. if r.FrequencyPenalty != nil {
  447. options["frequency_penalty"] = *r.FrequencyPenalty
  448. }
  449. if r.PresencePenalty != nil {
  450. options["presence_penalty"] = *r.PresencePenalty
  451. }
  452. if r.TopP != nil {
  453. options["top_p"] = *r.TopP
  454. } else {
  455. options["top_p"] = 1.0
  456. }
  457. var format json.RawMessage
  458. if r.ResponseFormat != nil {
  459. switch strings.ToLower(strings.TrimSpace(r.ResponseFormat.Type)) {
  460. // Support the old "json_object" type for OpenAI compatibility
  461. case "json_object":
  462. format = json.RawMessage(`"json"`)
  463. case "json_schema":
  464. if r.ResponseFormat.JsonSchema != nil {
  465. format = r.ResponseFormat.JsonSchema.Schema
  466. }
  467. }
  468. }
  469. return &api.ChatRequest{
  470. Model: r.Model,
  471. Messages: messages,
  472. Format: format,
  473. Options: options,
  474. Stream: &r.Stream,
  475. Tools: r.Tools,
  476. }, nil
  477. }
  478. func fromCompleteRequest(r CompletionRequest) (api.GenerateRequest, error) {
  479. options := make(map[string]any)
  480. switch stop := r.Stop.(type) {
  481. case string:
  482. options["stop"] = []string{stop}
  483. case []any:
  484. var stops []string
  485. for _, s := range stop {
  486. if str, ok := s.(string); ok {
  487. stops = append(stops, str)
  488. } else {
  489. return api.GenerateRequest{}, fmt.Errorf("invalid type for 'stop' field: %T", s)
  490. }
  491. }
  492. options["stop"] = stops
  493. }
  494. if r.MaxTokens != nil {
  495. options["num_predict"] = *r.MaxTokens
  496. }
  497. if r.Temperature != nil {
  498. options["temperature"] = *r.Temperature
  499. } else {
  500. options["temperature"] = 1.0
  501. }
  502. if r.Seed != nil {
  503. options["seed"] = *r.Seed
  504. }
  505. options["frequency_penalty"] = r.FrequencyPenalty
  506. options["presence_penalty"] = r.PresencePenalty
  507. if r.TopP != 0.0 {
  508. options["top_p"] = r.TopP
  509. } else {
  510. options["top_p"] = 1.0
  511. }
  512. return api.GenerateRequest{
  513. Model: r.Model,
  514. Prompt: r.Prompt,
  515. Options: options,
  516. Stream: &r.Stream,
  517. Suffix: r.Suffix,
  518. }, nil
  519. }
  520. type BaseWriter struct {
  521. gin.ResponseWriter
  522. }
  523. type ChatWriter struct {
  524. stream bool
  525. streamOptions *StreamOptions
  526. id string
  527. BaseWriter
  528. }
  529. type CompleteWriter struct {
  530. stream bool
  531. streamOptions *StreamOptions
  532. id string
  533. BaseWriter
  534. }
  535. type ListWriter struct {
  536. BaseWriter
  537. }
  538. type RetrieveWriter struct {
  539. BaseWriter
  540. model string
  541. }
  542. type EmbedWriter struct {
  543. BaseWriter
  544. model string
  545. }
  546. func (w *BaseWriter) writeError(data []byte) (int, error) {
  547. var serr api.StatusError
  548. err := json.Unmarshal(data, &serr)
  549. if err != nil {
  550. return 0, err
  551. }
  552. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  553. err = json.NewEncoder(w.ResponseWriter).Encode(NewError(http.StatusInternalServerError, serr.Error()))
  554. if err != nil {
  555. return 0, err
  556. }
  557. return len(data), nil
  558. }
  559. func (w *ChatWriter) writeResponse(data []byte) (int, error) {
  560. var chatResponse api.ChatResponse
  561. err := json.Unmarshal(data, &chatResponse)
  562. if err != nil {
  563. return 0, err
  564. }
  565. // chat chunk
  566. if w.stream {
  567. c := toChunk(w.id, chatResponse)
  568. d, err := json.Marshal(c)
  569. if err != nil {
  570. return 0, err
  571. }
  572. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  573. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  574. if err != nil {
  575. return 0, err
  576. }
  577. if chatResponse.Done {
  578. if w.streamOptions != nil && w.streamOptions.IncludeUsage {
  579. u := toUsage(chatResponse)
  580. c.Usage = &u
  581. c.Choices = []ChunkChoice{}
  582. d, err := json.Marshal(c)
  583. if err != nil {
  584. return 0, err
  585. }
  586. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  587. if err != nil {
  588. return 0, err
  589. }
  590. }
  591. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  592. if err != nil {
  593. return 0, err
  594. }
  595. }
  596. return len(data), nil
  597. }
  598. // chat completion
  599. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  600. err = json.NewEncoder(w.ResponseWriter).Encode(toChatCompletion(w.id, chatResponse))
  601. if err != nil {
  602. return 0, err
  603. }
  604. return len(data), nil
  605. }
  606. func (w *ChatWriter) Write(data []byte) (int, error) {
  607. code := w.ResponseWriter.Status()
  608. if code != http.StatusOK {
  609. return w.writeError(data)
  610. }
  611. return w.writeResponse(data)
  612. }
  613. func (w *CompleteWriter) writeResponse(data []byte) (int, error) {
  614. var generateResponse api.GenerateResponse
  615. err := json.Unmarshal(data, &generateResponse)
  616. if err != nil {
  617. return 0, err
  618. }
  619. // completion chunk
  620. if w.stream {
  621. c := toCompleteChunk(w.id, generateResponse)
  622. if w.streamOptions != nil && w.streamOptions.IncludeUsage {
  623. c.Usage = &Usage{}
  624. }
  625. d, err := json.Marshal(c)
  626. if err != nil {
  627. return 0, err
  628. }
  629. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  630. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  631. if err != nil {
  632. return 0, err
  633. }
  634. if generateResponse.Done {
  635. if w.streamOptions != nil && w.streamOptions.IncludeUsage {
  636. u := toUsageGenerate(generateResponse)
  637. c.Usage = &u
  638. c.Choices = []CompleteChunkChoice{}
  639. d, err := json.Marshal(c)
  640. if err != nil {
  641. return 0, err
  642. }
  643. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  644. if err != nil {
  645. return 0, err
  646. }
  647. }
  648. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  649. if err != nil {
  650. return 0, err
  651. }
  652. }
  653. return len(data), nil
  654. }
  655. // completion
  656. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  657. err = json.NewEncoder(w.ResponseWriter).Encode(toCompletion(w.id, generateResponse))
  658. if err != nil {
  659. return 0, err
  660. }
  661. return len(data), nil
  662. }
  663. func (w *CompleteWriter) Write(data []byte) (int, error) {
  664. code := w.ResponseWriter.Status()
  665. if code != http.StatusOK {
  666. return w.writeError(data)
  667. }
  668. return w.writeResponse(data)
  669. }
  670. func (w *ListWriter) writeResponse(data []byte) (int, error) {
  671. var listResponse api.ListResponse
  672. err := json.Unmarshal(data, &listResponse)
  673. if err != nil {
  674. return 0, err
  675. }
  676. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  677. err = json.NewEncoder(w.ResponseWriter).Encode(toListCompletion(listResponse))
  678. if err != nil {
  679. return 0, err
  680. }
  681. return len(data), nil
  682. }
  683. func (w *ListWriter) Write(data []byte) (int, error) {
  684. code := w.ResponseWriter.Status()
  685. if code != http.StatusOK {
  686. return w.writeError(data)
  687. }
  688. return w.writeResponse(data)
  689. }
  690. func (w *RetrieveWriter) writeResponse(data []byte) (int, error) {
  691. var showResponse api.ShowResponse
  692. err := json.Unmarshal(data, &showResponse)
  693. if err != nil {
  694. return 0, err
  695. }
  696. // retrieve completion
  697. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  698. err = json.NewEncoder(w.ResponseWriter).Encode(toModel(showResponse, w.model))
  699. if err != nil {
  700. return 0, err
  701. }
  702. return len(data), nil
  703. }
  704. func (w *RetrieveWriter) Write(data []byte) (int, error) {
  705. code := w.ResponseWriter.Status()
  706. if code != http.StatusOK {
  707. return w.writeError(data)
  708. }
  709. return w.writeResponse(data)
  710. }
  711. func (w *EmbedWriter) writeResponse(data []byte) (int, error) {
  712. var embedResponse api.EmbedResponse
  713. err := json.Unmarshal(data, &embedResponse)
  714. if err != nil {
  715. return 0, err
  716. }
  717. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  718. err = json.NewEncoder(w.ResponseWriter).Encode(toEmbeddingList(w.model, embedResponse))
  719. if err != nil {
  720. return 0, err
  721. }
  722. return len(data), nil
  723. }
  724. func (w *EmbedWriter) Write(data []byte) (int, error) {
  725. code := w.ResponseWriter.Status()
  726. if code != http.StatusOK {
  727. return w.writeError(data)
  728. }
  729. return w.writeResponse(data)
  730. }
  731. func ListMiddleware() gin.HandlerFunc {
  732. return func(c *gin.Context) {
  733. w := &ListWriter{
  734. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  735. }
  736. c.Writer = w
  737. c.Next()
  738. }
  739. }
  740. func RetrieveMiddleware() gin.HandlerFunc {
  741. return func(c *gin.Context) {
  742. var b bytes.Buffer
  743. if err := json.NewEncoder(&b).Encode(api.ShowRequest{Name: c.Param("model")}); err != nil {
  744. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  745. return
  746. }
  747. c.Request.Body = io.NopCloser(&b)
  748. // response writer
  749. w := &RetrieveWriter{
  750. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  751. model: c.Param("model"),
  752. }
  753. c.Writer = w
  754. c.Next()
  755. }
  756. }
  757. func CompletionsMiddleware() gin.HandlerFunc {
  758. return func(c *gin.Context) {
  759. var req CompletionRequest
  760. err := c.ShouldBindJSON(&req)
  761. if err != nil {
  762. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  763. return
  764. }
  765. var b bytes.Buffer
  766. genReq, err := fromCompleteRequest(req)
  767. if err != nil {
  768. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  769. return
  770. }
  771. if err := json.NewEncoder(&b).Encode(genReq); err != nil {
  772. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  773. return
  774. }
  775. c.Request.Body = io.NopCloser(&b)
  776. w := &CompleteWriter{
  777. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  778. stream: req.Stream,
  779. id: fmt.Sprintf("cmpl-%d", rand.Intn(999)),
  780. streamOptions: req.StreamOptions,
  781. }
  782. c.Writer = w
  783. c.Next()
  784. }
  785. }
  786. func EmbeddingsMiddleware() gin.HandlerFunc {
  787. return func(c *gin.Context) {
  788. var req EmbedRequest
  789. err := c.ShouldBindJSON(&req)
  790. if err != nil {
  791. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  792. return
  793. }
  794. if req.Input == "" {
  795. req.Input = []string{""}
  796. }
  797. if req.Input == nil {
  798. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  799. return
  800. }
  801. if v, ok := req.Input.([]any); ok && len(v) == 0 {
  802. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  803. return
  804. }
  805. var b bytes.Buffer
  806. if err := json.NewEncoder(&b).Encode(api.EmbedRequest{Model: req.Model, Input: req.Input}); err != nil {
  807. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  808. return
  809. }
  810. c.Request.Body = io.NopCloser(&b)
  811. w := &EmbedWriter{
  812. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  813. model: req.Model,
  814. }
  815. c.Writer = w
  816. c.Next()
  817. }
  818. }
  819. func ChatMiddleware() gin.HandlerFunc {
  820. return func(c *gin.Context) {
  821. var req ChatCompletionRequest
  822. err := c.ShouldBindJSON(&req)
  823. if err != nil {
  824. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  825. return
  826. }
  827. if len(req.Messages) == 0 {
  828. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "[] is too short - 'messages'"))
  829. return
  830. }
  831. var b bytes.Buffer
  832. chatReq, err := fromChatRequest(req)
  833. if err != nil {
  834. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  835. return
  836. }
  837. slog.Info("num_ctx", "num_ctx", chatReq.Options["num_ctx"])
  838. if err := json.NewEncoder(&b).Encode(chatReq); err != nil {
  839. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  840. return
  841. }
  842. c.Request.Body = io.NopCloser(&b)
  843. w := &ChatWriter{
  844. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  845. stream: req.Stream,
  846. id: fmt.Sprintf("chatcmpl-%d", rand.Intn(999)),
  847. streamOptions: req.StreamOptions,
  848. }
  849. c.Writer = w
  850. c.Next()
  851. }
  852. }