relay.go 3.1 KB

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