openai.go 21 KB

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