openai.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937
  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 map[string]any `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. schema, err := json.Marshal(r.ResponseFormat.JsonSchema.Schema)
  443. if err != nil {
  444. return nil, fmt.Errorf("failed to marshal json schema: %w", err)
  445. }
  446. format = schema
  447. }
  448. }
  449. }
  450. return &api.ChatRequest{
  451. Model: r.Model,
  452. Messages: messages,
  453. Format: format,
  454. Options: options,
  455. Stream: &r.Stream,
  456. Tools: r.Tools,
  457. }, nil
  458. }
  459. func fromCompleteRequest(r CompletionRequest) (api.GenerateRequest, error) {
  460. options := make(map[string]any)
  461. switch stop := r.Stop.(type) {
  462. case string:
  463. options["stop"] = []string{stop}
  464. case []any:
  465. var stops []string
  466. for _, s := range stop {
  467. if str, ok := s.(string); ok {
  468. stops = append(stops, str)
  469. } else {
  470. return api.GenerateRequest{}, fmt.Errorf("invalid type for 'stop' field: %T", s)
  471. }
  472. }
  473. options["stop"] = stops
  474. }
  475. if r.MaxTokens != nil {
  476. options["num_predict"] = *r.MaxTokens
  477. }
  478. if r.Temperature != nil {
  479. options["temperature"] = *r.Temperature
  480. } else {
  481. options["temperature"] = 1.0
  482. }
  483. if r.Seed != nil {
  484. options["seed"] = *r.Seed
  485. }
  486. options["frequency_penalty"] = r.FrequencyPenalty
  487. options["presence_penalty"] = r.PresencePenalty
  488. if r.TopP != 0.0 {
  489. options["top_p"] = r.TopP
  490. } else {
  491. options["top_p"] = 1.0
  492. }
  493. return api.GenerateRequest{
  494. Model: r.Model,
  495. Prompt: r.Prompt,
  496. Options: options,
  497. Stream: &r.Stream,
  498. Suffix: r.Suffix,
  499. }, nil
  500. }
  501. type BaseWriter struct {
  502. gin.ResponseWriter
  503. }
  504. type ChatWriter struct {
  505. stream bool
  506. id string
  507. BaseWriter
  508. }
  509. type CompleteWriter struct {
  510. stream bool
  511. id string
  512. BaseWriter
  513. }
  514. type ListWriter struct {
  515. BaseWriter
  516. }
  517. type RetrieveWriter struct {
  518. BaseWriter
  519. model string
  520. }
  521. type EmbedWriter struct {
  522. BaseWriter
  523. model string
  524. }
  525. func (w *BaseWriter) writeError(data []byte) (int, error) {
  526. var serr api.StatusError
  527. err := json.Unmarshal(data, &serr)
  528. if err != nil {
  529. return 0, err
  530. }
  531. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  532. err = json.NewEncoder(w.ResponseWriter).Encode(NewError(http.StatusInternalServerError, serr.Error()))
  533. if err != nil {
  534. return 0, err
  535. }
  536. return len(data), nil
  537. }
  538. func (w *ChatWriter) writeResponse(data []byte) (int, error) {
  539. var chatResponse api.ChatResponse
  540. err := json.Unmarshal(data, &chatResponse)
  541. if err != nil {
  542. return 0, err
  543. }
  544. // chat chunk
  545. if w.stream {
  546. d, err := json.Marshal(toChunk(w.id, chatResponse))
  547. if err != nil {
  548. return 0, err
  549. }
  550. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  551. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  552. if err != nil {
  553. return 0, err
  554. }
  555. if chatResponse.Done {
  556. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  557. if err != nil {
  558. return 0, err
  559. }
  560. }
  561. return len(data), nil
  562. }
  563. // chat completion
  564. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  565. err = json.NewEncoder(w.ResponseWriter).Encode(toChatCompletion(w.id, chatResponse))
  566. if err != nil {
  567. return 0, err
  568. }
  569. return len(data), nil
  570. }
  571. func (w *ChatWriter) Write(data []byte) (int, error) {
  572. code := w.ResponseWriter.Status()
  573. if code != http.StatusOK {
  574. return w.writeError(data)
  575. }
  576. return w.writeResponse(data)
  577. }
  578. func (w *CompleteWriter) writeResponse(data []byte) (int, error) {
  579. var generateResponse api.GenerateResponse
  580. err := json.Unmarshal(data, &generateResponse)
  581. if err != nil {
  582. return 0, err
  583. }
  584. // completion chunk
  585. if w.stream {
  586. d, err := json.Marshal(toCompleteChunk(w.id, generateResponse))
  587. if err != nil {
  588. return 0, err
  589. }
  590. w.ResponseWriter.Header().Set("Content-Type", "text/event-stream")
  591. _, err = w.ResponseWriter.Write([]byte(fmt.Sprintf("data: %s\n\n", d)))
  592. if err != nil {
  593. return 0, err
  594. }
  595. if generateResponse.Done {
  596. _, err = w.ResponseWriter.Write([]byte("data: [DONE]\n\n"))
  597. if err != nil {
  598. return 0, err
  599. }
  600. }
  601. return len(data), nil
  602. }
  603. // completion
  604. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  605. err = json.NewEncoder(w.ResponseWriter).Encode(toCompletion(w.id, generateResponse))
  606. if err != nil {
  607. return 0, err
  608. }
  609. return len(data), nil
  610. }
  611. func (w *CompleteWriter) Write(data []byte) (int, error) {
  612. code := w.ResponseWriter.Status()
  613. if code != http.StatusOK {
  614. return w.writeError(data)
  615. }
  616. return w.writeResponse(data)
  617. }
  618. func (w *ListWriter) writeResponse(data []byte) (int, error) {
  619. var listResponse api.ListResponse
  620. err := json.Unmarshal(data, &listResponse)
  621. if err != nil {
  622. return 0, err
  623. }
  624. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  625. err = json.NewEncoder(w.ResponseWriter).Encode(toListCompletion(listResponse))
  626. if err != nil {
  627. return 0, err
  628. }
  629. return len(data), nil
  630. }
  631. func (w *ListWriter) Write(data []byte) (int, error) {
  632. code := w.ResponseWriter.Status()
  633. if code != http.StatusOK {
  634. return w.writeError(data)
  635. }
  636. return w.writeResponse(data)
  637. }
  638. func (w *RetrieveWriter) writeResponse(data []byte) (int, error) {
  639. var showResponse api.ShowResponse
  640. err := json.Unmarshal(data, &showResponse)
  641. if err != nil {
  642. return 0, err
  643. }
  644. // retrieve completion
  645. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  646. err = json.NewEncoder(w.ResponseWriter).Encode(toModel(showResponse, w.model))
  647. if err != nil {
  648. return 0, err
  649. }
  650. return len(data), nil
  651. }
  652. func (w *RetrieveWriter) Write(data []byte) (int, error) {
  653. code := w.ResponseWriter.Status()
  654. if code != http.StatusOK {
  655. return w.writeError(data)
  656. }
  657. return w.writeResponse(data)
  658. }
  659. func (w *EmbedWriter) writeResponse(data []byte) (int, error) {
  660. var embedResponse api.EmbedResponse
  661. err := json.Unmarshal(data, &embedResponse)
  662. if err != nil {
  663. return 0, err
  664. }
  665. w.ResponseWriter.Header().Set("Content-Type", "application/json")
  666. err = json.NewEncoder(w.ResponseWriter).Encode(toEmbeddingList(w.model, embedResponse))
  667. if err != nil {
  668. return 0, err
  669. }
  670. return len(data), nil
  671. }
  672. func (w *EmbedWriter) Write(data []byte) (int, error) {
  673. code := w.ResponseWriter.Status()
  674. if code != http.StatusOK {
  675. return w.writeError(data)
  676. }
  677. return w.writeResponse(data)
  678. }
  679. func ListMiddleware() gin.HandlerFunc {
  680. return func(c *gin.Context) {
  681. w := &ListWriter{
  682. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  683. }
  684. c.Writer = w
  685. c.Next()
  686. }
  687. }
  688. func RetrieveMiddleware() gin.HandlerFunc {
  689. return func(c *gin.Context) {
  690. var b bytes.Buffer
  691. if err := json.NewEncoder(&b).Encode(api.ShowRequest{Name: c.Param("model")}); err != nil {
  692. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  693. return
  694. }
  695. c.Request.Body = io.NopCloser(&b)
  696. // response writer
  697. w := &RetrieveWriter{
  698. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  699. model: c.Param("model"),
  700. }
  701. c.Writer = w
  702. c.Next()
  703. }
  704. }
  705. func CompletionsMiddleware() gin.HandlerFunc {
  706. return func(c *gin.Context) {
  707. var req CompletionRequest
  708. err := c.ShouldBindJSON(&req)
  709. if err != nil {
  710. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  711. return
  712. }
  713. var b bytes.Buffer
  714. genReq, err := fromCompleteRequest(req)
  715. if err != nil {
  716. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  717. return
  718. }
  719. if err := json.NewEncoder(&b).Encode(genReq); err != nil {
  720. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  721. return
  722. }
  723. c.Request.Body = io.NopCloser(&b)
  724. w := &CompleteWriter{
  725. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  726. stream: req.Stream,
  727. id: fmt.Sprintf("cmpl-%d", rand.Intn(999)),
  728. }
  729. c.Writer = w
  730. c.Next()
  731. }
  732. }
  733. func EmbeddingsMiddleware() gin.HandlerFunc {
  734. return func(c *gin.Context) {
  735. var req EmbedRequest
  736. err := c.ShouldBindJSON(&req)
  737. if err != nil {
  738. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  739. return
  740. }
  741. if req.Input == "" {
  742. req.Input = []string{""}
  743. }
  744. if req.Input == nil {
  745. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  746. return
  747. }
  748. if v, ok := req.Input.([]any); ok && len(v) == 0 {
  749. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "invalid input"))
  750. return
  751. }
  752. var b bytes.Buffer
  753. if err := json.NewEncoder(&b).Encode(api.EmbedRequest{Model: req.Model, Input: req.Input}); err != nil {
  754. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  755. return
  756. }
  757. c.Request.Body = io.NopCloser(&b)
  758. w := &EmbedWriter{
  759. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  760. model: req.Model,
  761. }
  762. c.Writer = w
  763. c.Next()
  764. }
  765. }
  766. func ChatMiddleware() gin.HandlerFunc {
  767. return func(c *gin.Context) {
  768. var req ChatCompletionRequest
  769. err := c.ShouldBindJSON(&req)
  770. if err != nil {
  771. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  772. return
  773. }
  774. if len(req.Messages) == 0 {
  775. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, "[] is too short - 'messages'"))
  776. return
  777. }
  778. var b bytes.Buffer
  779. chatReq, err := fromChatRequest(req)
  780. if err != nil {
  781. c.AbortWithStatusJSON(http.StatusBadRequest, NewError(http.StatusBadRequest, err.Error()))
  782. return
  783. }
  784. if err := json.NewEncoder(&b).Encode(chatReq); err != nil {
  785. c.AbortWithStatusJSON(http.StatusInternalServerError, NewError(http.StatusInternalServerError, err.Error()))
  786. return
  787. }
  788. c.Request.Body = io.NopCloser(&b)
  789. w := &ChatWriter{
  790. BaseWriter: BaseWriter{ResponseWriter: c.Writer},
  791. stream: req.Stream,
  792. id: fmt.Sprintf("chatcmpl-%d", rand.Intn(999)),
  793. }
  794. c.Writer = w
  795. c.Next()
  796. }
  797. }