openai.go 24 KB

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