common.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120
  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 ClaudeChunkData(c *gin.Context, resp dto.ClaudeResponse, data string) {
  20. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("event: %s\n", resp.Type)})
  21. c.Render(-1, common.CustomEvent{Data: fmt.Sprintf("data: %s\n", data)})
  22. if flusher, ok := c.Writer.(http.Flusher); ok {
  23. flusher.Flush()
  24. }
  25. }
  26. func StringData(c *gin.Context, str string) error {
  27. //str = strings.TrimPrefix(str, "data: ")
  28. //str = strings.TrimSuffix(str, "\r")
  29. c.Render(-1, common.CustomEvent{Data: "data: " + str})
  30. if flusher, ok := c.Writer.(http.Flusher); ok {
  31. flusher.Flush()
  32. } else {
  33. return errors.New("streaming error: flusher not found")
  34. }
  35. return nil
  36. }
  37. func ObjectData(c *gin.Context, object interface{}) error {
  38. jsonData, err := json.Marshal(object)
  39. if err != nil {
  40. return fmt.Errorf("error marshalling object: %w", err)
  41. }
  42. return StringData(c, string(jsonData))
  43. }
  44. func Done(c *gin.Context) {
  45. _ = StringData(c, "[DONE]")
  46. }
  47. func WssString(c *gin.Context, ws *websocket.Conn, str string) error {
  48. if ws == nil {
  49. common.LogError(c, "websocket connection is nil")
  50. return errors.New("websocket connection is nil")
  51. }
  52. //common.LogInfo(c, fmt.Sprintf("sending message: %s", str))
  53. return ws.WriteMessage(1, []byte(str))
  54. }
  55. func WssObject(c *gin.Context, ws *websocket.Conn, object interface{}) error {
  56. jsonData, err := json.Marshal(object)
  57. if err != nil {
  58. return fmt.Errorf("error marshalling object: %w", err)
  59. }
  60. if ws == nil {
  61. common.LogError(c, "websocket connection is nil")
  62. return errors.New("websocket connection is nil")
  63. }
  64. //common.LogInfo(c, fmt.Sprintf("sending message: %s", jsonData))
  65. return ws.WriteMessage(1, jsonData)
  66. }
  67. func WssError(c *gin.Context, ws *websocket.Conn, openaiError dto.OpenAIError) {
  68. errorObj := &dto.RealtimeEvent{
  69. Type: "error",
  70. EventId: GetLocalRealtimeID(c),
  71. Error: &openaiError,
  72. }
  73. _ = WssObject(c, ws, errorObj)
  74. }
  75. func GetResponseID(c *gin.Context) string {
  76. logID := c.GetString(common.RequestIdKey)
  77. return fmt.Sprintf("chatcmpl-%s", logID)
  78. }
  79. func GetLocalRealtimeID(c *gin.Context) string {
  80. logID := c.GetString(common.RequestIdKey)
  81. return fmt.Sprintf("evt_%s", logID)
  82. }
  83. func GenerateStopResponse(id string, createAt int64, model string, finishReason string) *dto.ChatCompletionsStreamResponse {
  84. return &dto.ChatCompletionsStreamResponse{
  85. Id: id,
  86. Object: "chat.completion.chunk",
  87. Created: createAt,
  88. Model: model,
  89. SystemFingerprint: nil,
  90. Choices: []dto.ChatCompletionsStreamResponseChoice{
  91. {
  92. FinishReason: &finishReason,
  93. },
  94. },
  95. }
  96. }
  97. func GenerateFinalUsageResponse(id string, createAt int64, model string, usage dto.Usage) *dto.ChatCompletionsStreamResponse {
  98. return &dto.ChatCompletionsStreamResponse{
  99. Id: id,
  100. Object: "chat.completion.chunk",
  101. Created: createAt,
  102. Model: model,
  103. SystemFingerprint: nil,
  104. Choices: make([]dto.ChatCompletionsStreamResponseChoice, 0),
  105. Usage: &usage,
  106. }
  107. }