common.go 4.5 KB

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