relay-palm.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. package controller
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "net/http"
  8. "one-api/common"
  9. )
  10. // https://developers.generativeai.google/api/rest/generativelanguage/models/generateMessage#request-body
  11. // https://developers.generativeai.google/api/rest/generativelanguage/models/generateMessage#response-body
  12. type PaLMChatMessage struct {
  13. Author string `json:"author"`
  14. Content string `json:"content"`
  15. }
  16. type PaLMFilter struct {
  17. Reason string `json:"reason"`
  18. Message string `json:"message"`
  19. }
  20. type PaLMPrompt struct {
  21. Messages []PaLMChatMessage `json:"messages"`
  22. }
  23. type PaLMChatRequest struct {
  24. Prompt PaLMPrompt `json:"prompt"`
  25. Temperature float64 `json:"temperature,omitempty"`
  26. CandidateCount int `json:"candidateCount,omitempty"`
  27. TopP float64 `json:"topP,omitempty"`
  28. TopK int `json:"topK,omitempty"`
  29. }
  30. type PaLMError struct {
  31. Code int `json:"code"`
  32. Message string `json:"message"`
  33. Status string `json:"status"`
  34. }
  35. type PaLMChatResponse struct {
  36. Candidates []PaLMChatMessage `json:"candidates"`
  37. Messages []Message `json:"messages"`
  38. Filters []PaLMFilter `json:"filters"`
  39. Error PaLMError `json:"error"`
  40. }
  41. func requestOpenAI2PaLM(textRequest GeneralOpenAIRequest) *PaLMChatRequest {
  42. palmRequest := PaLMChatRequest{
  43. Prompt: PaLMPrompt{
  44. Messages: make([]PaLMChatMessage, 0, len(textRequest.Messages)),
  45. },
  46. Temperature: textRequest.Temperature,
  47. CandidateCount: textRequest.N,
  48. TopP: textRequest.TopP,
  49. TopK: textRequest.MaxTokens,
  50. }
  51. for _, message := range textRequest.Messages {
  52. palmMessage := PaLMChatMessage{
  53. Content: message.Content,
  54. }
  55. if message.Role == "user" {
  56. palmMessage.Author = "0"
  57. } else {
  58. palmMessage.Author = "1"
  59. }
  60. palmRequest.Prompt.Messages = append(palmRequest.Prompt.Messages, palmMessage)
  61. }
  62. return &palmRequest
  63. }
  64. func responsePaLM2OpenAI(response *PaLMChatResponse) *OpenAITextResponse {
  65. fullTextResponse := OpenAITextResponse{
  66. Choices: make([]OpenAITextResponseChoice, 0, len(response.Candidates)),
  67. }
  68. for i, candidate := range response.Candidates {
  69. choice := OpenAITextResponseChoice{
  70. Index: i,
  71. Message: Message{
  72. Role: "assistant",
  73. Content: candidate.Content,
  74. },
  75. FinishReason: "stop",
  76. }
  77. fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
  78. }
  79. return &fullTextResponse
  80. }
  81. func streamResponsePaLM2OpenAI(palmResponse *PaLMChatResponse) *ChatCompletionsStreamResponse {
  82. var choice ChatCompletionsStreamResponseChoice
  83. if len(palmResponse.Candidates) > 0 {
  84. choice.Delta.Content = palmResponse.Candidates[0].Content
  85. }
  86. choice.FinishReason = &stopFinishReason
  87. var response ChatCompletionsStreamResponse
  88. response.Object = "chat.completion.chunk"
  89. response.Model = "palm2"
  90. response.Choices = []ChatCompletionsStreamResponseChoice{choice}
  91. return &response
  92. }
  93. func palmStreamHandler(c *gin.Context, resp *http.Response) (*OpenAIErrorWithStatusCode, string) {
  94. responseText := ""
  95. responseId := fmt.Sprintf("chatcmpl-%s", common.GetUUID())
  96. createdTime := common.GetTimestamp()
  97. dataChan := make(chan string)
  98. stopChan := make(chan bool)
  99. go func() {
  100. responseBody, err := io.ReadAll(resp.Body)
  101. if err != nil {
  102. common.SysError("error reading stream response: " + err.Error())
  103. stopChan <- true
  104. return
  105. }
  106. err = resp.Body.Close()
  107. if err != nil {
  108. common.SysError("error closing stream response: " + err.Error())
  109. stopChan <- true
  110. return
  111. }
  112. var palmResponse PaLMChatResponse
  113. err = json.Unmarshal(responseBody, &palmResponse)
  114. if err != nil {
  115. common.SysError("error unmarshalling stream response: " + err.Error())
  116. stopChan <- true
  117. return
  118. }
  119. fullTextResponse := streamResponsePaLM2OpenAI(&palmResponse)
  120. fullTextResponse.Id = responseId
  121. fullTextResponse.Created = createdTime
  122. if len(palmResponse.Candidates) > 0 {
  123. responseText = palmResponse.Candidates[0].Content
  124. }
  125. jsonResponse, err := json.Marshal(fullTextResponse)
  126. if err != nil {
  127. common.SysError("error marshalling stream response: " + err.Error())
  128. stopChan <- true
  129. return
  130. }
  131. dataChan <- string(jsonResponse)
  132. stopChan <- true
  133. }()
  134. setEventStreamHeaders(c)
  135. c.Stream(func(w io.Writer) bool {
  136. select {
  137. case data := <-dataChan:
  138. c.Render(-1, common.CustomEvent{Data: "data: " + data})
  139. return true
  140. case <-stopChan:
  141. c.Render(-1, common.CustomEvent{Data: "data: [DONE]"})
  142. return false
  143. }
  144. })
  145. err := resp.Body.Close()
  146. if err != nil {
  147. return errorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), ""
  148. }
  149. return nil, responseText
  150. }
  151. func palmHandler(c *gin.Context, resp *http.Response, promptTokens int, model string) (*OpenAIErrorWithStatusCode, *Usage) {
  152. responseBody, err := io.ReadAll(resp.Body)
  153. if err != nil {
  154. return errorWrapper(err, "read_response_body_failed", http.StatusInternalServerError), nil
  155. }
  156. err = resp.Body.Close()
  157. if err != nil {
  158. return errorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
  159. }
  160. var palmResponse PaLMChatResponse
  161. err = json.Unmarshal(responseBody, &palmResponse)
  162. if err != nil {
  163. return errorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil
  164. }
  165. if palmResponse.Error.Code != 0 || len(palmResponse.Candidates) == 0 {
  166. return &OpenAIErrorWithStatusCode{
  167. OpenAIError: OpenAIError{
  168. Message: palmResponse.Error.Message,
  169. Type: palmResponse.Error.Status,
  170. Param: "",
  171. Code: palmResponse.Error.Code,
  172. },
  173. StatusCode: resp.StatusCode,
  174. }, nil
  175. }
  176. fullTextResponse := responsePaLM2OpenAI(&palmResponse)
  177. completionTokens := countTokenText(palmResponse.Candidates[0].Content, model)
  178. usage := Usage{
  179. PromptTokens: promptTokens,
  180. CompletionTokens: completionTokens,
  181. TotalTokens: promptTokens + completionTokens,
  182. }
  183. fullTextResponse.Usage = usage
  184. jsonResponse, err := json.Marshal(fullTextResponse)
  185. if err != nil {
  186. return errorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
  187. }
  188. c.Writer.Header().Set("Content-Type", "application/json")
  189. c.Writer.WriteHeader(resp.StatusCode)
  190. _, err = c.Writer.Write(jsonResponse)
  191. return nil, &usage
  192. }