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. message := api.Message{Role: msg.Role}
  316. for _, c := range content {
  317. data, ok := c.(map[string]any)
  318. if !ok {
  319. return nil, fmt.Errorf("invalid message format")
  320. }
  321. switch data["type"] {
  322. case "text":
  323. text, ok := data["text"].(string)
  324. if !ok {
  325. return nil, fmt.Errorf("invalid message format")
  326. }
  327. message.Content = text
  328. case "image_url":
  329. var url string
  330. if urlMap, ok := data["image_url"].(map[string]any); ok {
  331. if url, ok = urlMap["url"].(string); !ok {
  332. return nil, fmt.Errorf("invalid message format")
  333. }
  334. } else {
  335. if url, ok = data["image_url"].(string); !ok {
  336. return nil, fmt.Errorf("invalid message format")
  337. }
  338. }
  339. types := []string{"jpeg", "jpg", "png"}
  340. valid := false
  341. for _, t := range types {
  342. prefix := "data:image/" + t + ";base64,"
  343. if strings.HasPrefix(url, prefix) {
  344. url = strings.TrimPrefix(url, prefix)
  345. valid = true
  346. break
  347. }
  348. }
  349. if !valid {
  350. return nil, fmt.Errorf("invalid image input")
  351. }
  352. img, err := base64.StdEncoding.DecodeString(url)
  353. if err != nil {
  354. return nil, fmt.Errorf("invalid message format")
  355. }
  356. message.Images = append(message.Images, img)
  357. default:
  358. return nil, fmt.Errorf("invalid message format")
  359. }
  360. }
  361. messages = append(messages, message)
  362. default:
  363. if msg.ToolCalls == nil {
  364. return nil, fmt.Errorf("invalid message content type: %T", content)
  365. }
  366. toolCalls := make([]api.ToolCall, len(msg.ToolCalls))
  367. for i, tc := range msg.ToolCalls {
  368. toolCalls[i].Function.Name = tc.Function.Name
  369. err := json.Unmarshal([]byte(tc.Function.Arguments), &toolCalls[i].Function.Arguments)
  370. if err != nil {
  371. return nil, fmt.Errorf("invalid tool call arguments")
  372. }
  373. }
  374. messages = append(messages, api.Message{Role: msg.Role, ToolCalls: toolCalls})
  375. }
  376. }
  377. options := make(map[string]interface{})
  378. switch stop := r.Stop.(type) {
  379. case string:
  380. options["stop"] = []string{stop}
  381. case []any:
  382. var stops []string
  383. for _, s := range stop {
  384. if str, ok := s.(string); ok {
  385. stops = append(stops, str)
  386. }
  387. }
  388. options["stop"] = stops
  389. }
  390. if r.MaxTokens != nil {
  391. options["num_predict"] = *r.MaxTokens
  392. }
  393. if r.Temperature != nil {
  394. options["temperature"] = *r.Temperature * 2.0
  395. } else {
  396. options["temperature"] = 1.0
  397. }
  398. if r.Seed != nil {
  399. options["seed"] = *r.Seed
  400. }
  401. if r.FrequencyPenalty != nil {
  402. options["frequency_penalty"] = *r.FrequencyPenalty * 2.0
  403. }
  404. if r.PresencePenalty != nil {
  405. options["presence_penalty"] = *r.PresencePenalty * 2.0
  406. }
  407. if r.TopP != nil {
  408. options["top_p"] = *r.TopP
  409. } else {
  410. options["top_p"] = 1.0
  411. }
  412. var format string
  413. if r.ResponseFormat != nil && r.ResponseFormat.Type == "json_object" {
  414. format = "json"
  415. }
  416. return &api.ChatRequest{
  417. Model: r.Model,
  418. Messages: messages,
  419. Format: format,
  420. Options: options,
  421. Stream: &r.Stream,
  422. Tools: r.Tools,
  423. }, nil
  424. }
  425. func fromCompleteRequest(r CompletionRequest) (api.GenerateRequest, error) {
  426. options := make(map[string]any)
  427. switch stop := r.Stop.(type) {
  428. case string:
  429. options["stop"] = []string{stop}
  430. case []any:
  431. var stops []string
  432. for _, s := range stop {
  433. if str, ok := s.(string); ok {
  434. stops = append(stops, str)
  435. } else {
  436. return api.GenerateRequest{}, fmt.Errorf("invalid type for 'stop' field: %T", s)
  437. }
  438. }
  439. options["stop"] = stops
  440. }
  441. if r.MaxTokens != nil {
  442. options["num_predict"] = *r.MaxTokens
  443. }
  444. if r.Temperature != nil {
  445. options["temperature"] = *r.Temperature * 2.0
  446. } else {
  447. options["temperature"] = 1.0
  448. }
  449. if r.Seed != nil {
  450. options["seed"] = *r.Seed
  451. }
  452. options["frequency_penalty"] = r.FrequencyPenalty * 2.0
  453. options["presence_penalty"] = r.PresencePenalty * 2.0
  454. if r.TopP != 0.0 {
  455. options["top_p"] = r.TopP
  456. } else {
  457. options["top_p"] = 1.0
  458. }
  459. return api.GenerateRequest{
  460. Model: r.Model,
  461. Prompt: r.Prompt,
  462. Options: options,
  463. Stream: &r.Stream,
  464. Suffix: r.Suffix,
  465. }, nil
  466. }
  467. type BaseWriter struct {
  468. gin.ResponseWriter
  469. }
  470. type ChatWriter struct {
  471. stream bool
  472. id string
  473. BaseWriter
  474. }
  475. type CompleteWriter struct {
  476. stream bool
  477. id string
  478. BaseWriter
  479. }
  480. type ListWriter struct {
  481. BaseWriter
  482. }
  483. type RetrieveWriter struct {
  484. BaseWriter
  485. model string
  486. }
  487. type EmbedWriter struct {
  488. BaseWriter
  489. model string
  490. }
  491. func (w *BaseWriter) writeError(code int, data []byte) (int, error) {
  492. var serr api.StatusError
  493. err := json.Unmarshal(data, &serr)
  494. if err != nil {
  495. return 0, err
  496. }
  497. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  498. err = json.NewEncoder(w.ResponseWriter).Encode(NewError(http.StatusInternalServerError, serr.Error()))
  499. if err != nil {
  500. return 0, err
  501. }
  502. return len(data), nil
  503. }
  504. func (w *ChatWriter) writeResponse(data []byte) (int, error) {
  505. var chatResponse api.ChatResponse
  506. err := json.Unmarshal(data, &chatResponse)
  507. if err != nil {
  508. return 0, err
  509. }
  510. // chat chunk
  511. if w.stream {
  512. d, err := json.Marshal(toChunk(w.id, chatResponse))
  513. if err != nil {
  514. return 0, err
  515. }
  516. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  517. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  518. if err != nil {
  519. return 0, err
  520. }
  521. if chatResponse.Done {
  522. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  523. if err != nil {
  524. return 0, err
  525. }
  526. }
  527. return len(data), nil
  528. }
  529. // chat completion
  530. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  531. err = json.NewEncoder(w.ResponseWriter).Encode(toChatCompletion(w.id, chatResponse))
  532. if err != nil {
  533. return 0, err
  534. }
  535. return len(data), nil
  536. }
  537. func (w *ChatWriter) Write(data []byte) (int, error) {
  538. code := w.ResponseWriter.Status()
  539. if code != http.StatusOK {
  540. return w.writeError(code, data)
  541. }
  542. return w.writeResponse(data)
  543. }
  544. func (w *CompleteWriter) writeResponse(data []byte) (int, error) {
  545. var generateResponse api.GenerateResponse
  546. err := json.Unmarshal(data, &generateResponse)
  547. if err != nil {
  548. return 0, err
  549. }
  550. // completion chunk
  551. if w.stream {
  552. d, err := json.Marshal(toCompleteChunk(w.id, generateResponse))
  553. if err != nil {
  554. return 0, err
  555. }
  556. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  557. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  558. if err != nil {
  559. return 0, err
  560. }
  561. if generateResponse.Done {
  562. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  563. if err != nil {
  564. return 0, err
  565. }
  566. }
  567. return len(data), nil
  568. }
  569. // completion
  570. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  571. err = json.NewEncoder(w.ResponseWriter).Encode(toCompletion(w.id, generateResponse))
  572. if err != nil {
  573. return 0, err
  574. }
  575. return len(data), nil
  576. }
  577. func (w *CompleteWriter) Write(data []byte) (int, error) {
  578. code := w.ResponseWriter.Status()
  579. if code != http.StatusOK {
  580. return w.writeError(code, data)
  581. }
  582. return w.writeResponse(data)
  583. }
  584. func (w *ListWriter) writeResponse(data []byte) (int, error) {
  585. var listResponse api.ListResponse
  586. err := json.Unmarshal(data, &listResponse)
  587. if err != nil {
  588. return 0, err
  589. }
  590. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  591. err = json.NewEncoder(w.ResponseWriter).Encode(toListCompletion(listResponse))
  592. if err != nil {
  593. return 0, err
  594. }
  595. return len(data), nil
  596. }
  597. func (w *ListWriter) Write(data []byte) (int, error) {
  598. code := w.ResponseWriter.Status()
  599. if code != http.StatusOK {
  600. return w.writeError(code, data)
  601. }
  602. return w.writeResponse(data)
  603. }
  604. func (w *RetrieveWriter) writeResponse(data []byte) (int, error) {
  605. var showResponse api.ShowResponse
  606. err := json.Unmarshal(data, &showResponse)
  607. if err != nil {
  608. return 0, err
  609. }
  610. // retrieve completion
  611. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  612. err = json.NewEncoder(w.ResponseWriter).Encode(toModel(showResponse, w.model))
  613. if err != nil {
  614. return 0, err
  615. }
  616. return len(data), nil
  617. }
  618. func (w *RetrieveWriter) Write(data []byte) (int, error) {
  619. code := w.ResponseWriter.Status()
  620. if code != http.StatusOK {
  621. return w.writeError(code, data)
  622. }
  623. return w.writeResponse(data)
  624. }
  625. func (w *EmbedWriter) writeResponse(data []byte) (int, error) {
  626. var embedResponse api.EmbedResponse
  627. err := json.Unmarshal(data, &embedResponse)
  628. if err != nil {
  629. return 0, err
  630. }
  631. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  632. err = json.NewEncoder(w.ResponseWriter).Encode(toEmbeddingList(w.model, embedResponse))
  633. if err != nil {
  634. return 0, err
  635. }
  636. return len(data), nil
  637. }
  638. func (w *EmbedWriter) Write(data []byte) (int, error) {
  639. code := w.ResponseWriter.Status()
  640. if code != http.StatusOK {
  641. return w.writeError(code, data)
  642. }
  643. return w.writeResponse(data)
  644. }
  645. func ListMiddleware() gin.HandlerFunc {
  646. return func(c *gin.Context) {
  647. w := &ListWriter{
  648. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  649. }
  650. c.Writer = w
  651. c.Next()
  652. }
  653. }
  654. func RetrieveMiddleware() gin.HandlerFunc {
  655. return func(c *gin.Context) {
  656. var b bytes.Buffer
  657. if err := json.NewEncoder(&b).Encode(api.ShowRequest{Name: c.Param("model")}); err != nil {
  658. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  659. return
  660. }
  661. c.Request.Body = io.NopCloser(&b)
  662. // response writer
  663. w := &RetrieveWriter{
  664. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  665. model: c.Param("model"),
  666. }
  667. c.Writer = w
  668. c.Next()
  669. }
  670. }
  671. func CompletionsMiddleware() gin.HandlerFunc {
  672. return func(c *gin.Context) {
  673. var req CompletionRequest
  674. err := c.ShouldBindJSON(&req)
  675. if err != nil {
  676. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  677. return
  678. }
  679. var b bytes.Buffer
  680. genReq, err := fromCompleteRequest(req)
  681. if err != nil {
  682. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  683. return
  684. }
  685. if err := json.NewEncoder(&b).Encode(genReq); err != nil {
  686. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  687. return
  688. }
  689. c.Request.Body = io.NopCloser(&b)
  690. w := &CompleteWriter{
  691. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  692. stream: req.Stream,
  693. id: fmt.Sprintf("cmpl-%d", rand.Intn(999)),
  694. }
  695. c.Writer = w
  696. c.Next()
  697. }
  698. }
  699. func EmbeddingsMiddleware() gin.HandlerFunc {
  700. return func(c *gin.Context) {
  701. var req EmbedRequest
  702. err := c.ShouldBindJSON(&req)
  703. if err != nil {
  704. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  705. return
  706. }
  707. if req.Input == "" {
  708. req.Input = []string{""}
  709. }
  710. if req.Input == nil {
  711. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  712. return
  713. }
  714. if v, ok := req.Input.([]any); ok && len(v) == 0 {
  715. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  716. return
  717. }
  718. var b bytes.Buffer
  719. if err := json.NewEncoder(&b).Encode(api.EmbedRequest{Model: req.Model, Input: req.Input}); err != nil {
  720. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  721. return
  722. }
  723. c.Request.Body = io.NopCloser(&b)
  724. w := &EmbedWriter{
  725. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  726. model: req.Model,
  727. }
  728. c.Writer = w
  729. c.Next()
  730. }
  731. }
  732. func ChatMiddleware() gin.HandlerFunc {
  733. return func(c *gin.Context) {
  734. var req ChatCompletionRequest
  735. err := c.ShouldBindJSON(&req)
  736. if err != nil {
  737. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  738. return
  739. }
  740. if len(req.Messages) == 0 {
  741. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "[] is too short - 'messages'"))
  742. return
  743. }
  744. var b bytes.Buffer
  745. chatReq, err := fromChatRequest(req)
  746. if err != nil {
  747. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  748. }
  749. if err := json.NewEncoder(&b).Encode(chatReq); err != nil {
  750. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  751. return
  752. }
  753. c.Request.Body = io.NopCloser(&b)
  754. w := &ChatWriter{
  755. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  756. stream: req.Stream,
  757. id: fmt.Sprintf("chatcmpl-%d", rand.Intn(999)),
  758. }
  759. c.Writer = w
  760. c.Next()
  761. }
  762. }