common.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  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\n", data)})
  37. if flusher, ok := c.Writer.(http.Flusher); ok {
  38. flusher.Flush()
  39. }
  40. }
  41. func StringData(c *gin.Context, str string) error {
  42. //str = strings.TrimPrefix(str, "data: ")
  43. //str = strings.TrimSuffix(str, "\r")
  44. c.Render(-1, common.CustomEvent{Data: "data: " + str})
  45. if flusher, ok := c.Writer.(http.Flusher); ok {
  46. flusher.Flush()
  47. } else {
  48. return errors.New("streaming error: flusher not found")
  49. }
  50. return nil
  51. }
  52. func PingData(c *gin.Context) error {
  53. c.Writer.Write([]byte(": PING\n\n"))
  54. if flusher, ok := c.Writer.(http.Flusher); ok {
  55. flusher.Flush()
  56. } else {
  57. return errors.New("streaming error: flusher not found")
  58. }
  59. return nil
  60. }
  61. func ObjectData(c *gin.Context, object interface{}) error {
  62. if object == nil {
  63. return errors.New("object is nil")
  64. }
  65. jsonData, err := json.Marshal(object)
  66. if err != nil {
  67. return fmt.Errorf("error marshalling object: %w", err)
  68. }
  69. return StringData(c, string(jsonData))
  70. }
  71. func Done(c *gin.Context) {
  72. _ = StringData(c, "[DONE]")
  73. }
  74. func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
  75. if ws == nil {
  76. common.LogError(c, "websocket connection is nil")
  77. return errors.New("websocket connection is nil")
  78. }
  79. //common.LogInfo(c, fmt.Sprintf("sending message: %s", str))
  80. return ws.WriteMessage(1, []byte(str))
  81. }
  82. func WssObject(c *gin.Context, ws *websocket.Conn, object interface{}) error {
  83. jsonData, err := json.Marshal(object)
  84. if err != nil {
  85. return fmt.Errorf("error marshalling object: %w", err)
  86. }
  87. if ws == nil {
  88. common.LogError(c, "websocket connection is nil")
  89. return errors.New("websocket connection is nil")
  90. }
  91. //common.LogInfo(c, fmt.Sprintf("sending message: %s", jsonData))
  92. return ws.WriteMessage(1, jsonData)
  93. }
  94. func WssError(c *gin.Context, ws *websocket.Conn, openaiError dto.OpenAIError) {
  95. errorObj := &dto.RealtimeEvent{
  96. Type: "error",
  97. EventId: GetLocalRealtimeID(c),
  98. Error: &openaiError,
  99. }
  100. _ = WssObject(c, ws, errorObj)
  101. }
  102. func GetResponseID(c *gin.Context) string {
  103. logID := c.GetString(common.RequestIdKey)
  104. return fmt.Sprintf("chatcmpl-%s", logID)
  105. }
  106. func GetLocalRealtimeID(c *gin.Context) string {
  107. logID := c.GetString(common.RequestIdKey)
  108. return fmt.Sprintf("evt_%s", logID)
  109. }
  110. func GenerateStopResponse(id string, createAt int64, model string, finishReason string) *dto.ChatCompletionsStreamResponse {
  111. return &dto.ChatCompletionsStreamResponse{
  112. Id: id,
  113. Object: "chat.completion.chunk",
  114. Created: createAt,
  115. Model: model,
  116. SystemFingerprint: nil,
  117. Choices: []dto.ChatCompletionsStreamResponseChoice{
  118. {
  119. FinishReason: &finishReason,
  120. },
  121. },
  122. }
  123. }
  124. func GenerateFinalUsageResponse(id string, createAt int64, model string, usage dto.Usage) *dto.ChatCompletionsStreamResponse {
  125. return &dto.ChatCompletionsStreamResponse{
  126. Id: id,
  127. Object: "chat.completion.chunk",
  128. Created: createAt,
  129. Model: model,
  130. SystemFingerprint: nil,
  131. Choices: make([]dto.ChatCompletionsStreamResponseChoice, 0),
  132. Usage: &usage,
  133. }
  134. }