openai.go 22 KB

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