openai.go 22 KB

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