openai.go 24 KB

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