openai.go 22 KB

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