openai.go 21 KB

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