common.go 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. package helper
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gorilla/websocket"
  8. "net/http"
  9. "one-api/common"
  10. "one-api/dto"
  11. )
  12. func SetEventStreamHeaders(c *gin.Context) {
  13. // 检查是否已经设置过头部
  14. if _, exists := c.Get("event_stream_headers_set"); exists {
  15. return
  16. }
  17. c.Writer.Header().Set("Content-Type", "text/event-stream")
  18. c.Writer.Header().Set("Cache-Control", "no-cache")
  19. c.Writer.Header().Set("Connection", "keep-alive")
  20. c.Writer.Header().Set("Transfer-Encoding", "chunked")
  21. c.Writer.Header().Set("X-Accel-Buffering", "no")
  22. // 设置标志,表示头部已经设置过
  23. c.Set("event_stream_headers_set", true)
  24. }
  25. func ClaudeData(c *gin.Context, resp dto.ClaudeResponse) error {
  26. jsonData, err := json.Marshal(resp)
  27. if err != nil {
  28. common.SysError("error marshalling stream response: " + err.Error())
  29. } else {
  30. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("event: %s\n", resp.Type)})
  31. c.Render(-1, common.CustomEvent{Data: "data: " + string(jsonData)})
  32. }
  33. if flusher, ok := c.Writer.(http.Flusher); ok {
  34. flusher.Flush()
  35. } else {
  36. return errors.New("streaming error: flusher not found")
  37. }
  38. return nil
  39. }
  40. func ClaudeChunkData(c *gin.Context, resp dto.ClaudeResponse, data string) {
  41. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("event: %s\n", resp.Type)})
  42. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("data: %s\n", data)})
  43. if flusher, ok := c.Writer.(http.Flusher); ok {
  44. flusher.Flush()
  45. }
  46. }
  47. func ResponseChunkData(c *gin.Context, resp dto.ResponsesStreamResponse, data string) {
  48. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("event: %s\n", resp.Type)})
  49. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("data: %s", data)})
  50. if flusher, ok := c.Writer.(http.Flusher); ok {
  51. flusher.Flush()
  52. }
  53. }
  54. func StringData(c *gin.Context, str string) error {
  55. //str = strings.TrimPrefix(str, "data: ")
  56. //str = strings.TrimSuffix(str, "\r")
  57. c.Render(-1, common.CustomEvent{Data: "data: " + str})
  58. if flusher, ok := c.Writer.(http.Flusher); ok {
  59. flusher.Flush()
  60. } else {
  61. return errors.New("streaming error: flusher not found")
  62. }
  63. return nil
  64. }
  65. func PingData(c *gin.Context) error {
  66. c.Writer.Write([]byte(": PING\n\n"))
  67. if flusher, ok := c.Writer.(http.Flusher); ok {
  68. flusher.Flush()
  69. } else {
  70. return errors.New("streaming error: flusher not found")
  71. }
  72. return nil
  73. }
  74. func ObjectData(c *gin.Context, object interface{}) error {
  75. if object == nil {
  76. return errors.New("object is nil")
  77. }
  78. jsonData, err := json.Marshal(object)
  79. if err != nil {
  80. return fmt.Errorf("error marshalling object: %w", err)
  81. }
  82. return StringData(c, string(jsonData))
  83. }
  84. func Done(c *gin.Context) {
  85. _ = StringData(c, "[DONE]")
  86. }
  87. func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
  88. if ws == nil {
  89. common.LogError(c, "websocket connection is nil")
  90. return errors.New("websocket connection is nil")
  91. }
  92. //common.LogInfo(c, fmt.Sprintf("sending message: %s", str))
  93. return ws.WriteMessage(1, []byte(str))
  94. }
  95. func WssObject(c *gin.Context, ws *websocket.Conn, object interface{}) error {
  96. jsonData, err := json.Marshal(object)
  97. if err != nil {
  98. return fmt.Errorf("error marshalling object: %w", err)
  99. }
  100. if ws == nil {
  101. common.LogError(c, "websocket connection is nil")
  102. return errors.New("websocket connection is nil")
  103. }
  104. //common.LogInfo(c, fmt.Sprintf("sending message: %s", jsonData))
  105. return ws.WriteMessage(1, jsonData)
  106. }
  107. func WssError(c *gin.Context, ws *websocket.Conn, openaiError dto.OpenAIError) {
  108. errorObj := &dto.RealtimeEvent{
  109. Type: "error",
  110. EventId: GetLocalRealtimeID(c),
  111. Error: &openaiError,
  112. }
  113. _ = WssObject(c, ws, errorObj)
  114. }
  115. func GetResponseID(c *gin.Context) string {
  116. logID := c.GetString(common.RequestIdKey)
  117. return fmt.Sprintf("chatcmpl-%s", logID)
  118. }
  119. func GetLocalRealtimeID(c *gin.Context) string {
  120. logID := c.GetString(common.RequestIdKey)
  121. return fmt.Sprintf("evt_%s", logID)
  122. }
  123. func GenerateStopResponse(id string, createAt int64, model string, finishReason string) *dto.ChatCompletionsStreamResponse {
  124. return &dto.ChatCompletionsStreamResponse{
  125. Id: id,
  126. Object: "chat.completion.chunk",
  127. Created: createAt,
  128. Model: model,
  129. SystemFingerprint: nil,
  130. Choices: []dto.ChatCompletionsStreamResponseChoice{
  131. {
  132. FinishReason: &finishReason,
  133. },
  134. },
  135. }
  136. }
  137. func GenerateFinalUsageResponse(id string, createAt int64, model string, usage dto.Usage) *dto.ChatCompletionsStreamResponse {
  138. return &dto.ChatCompletionsStreamResponse{
  139. Id: id,
  140. Object: "chat.completion.chunk",
  141. Created: createAt,
  142. Model: model,
  143. SystemFingerprint: nil,
  144. Choices: make([]dto.ChatCompletionsStreamResponseChoice, 0),
  145. Usage: &usage,
  146. }
  147. }