playground.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package controller
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/constant"
  8. "github.com/QuantumNous/new-api/middleware"
  9. "github.com/QuantumNous/new-api/model"
  10. relaycommon "github.com/QuantumNous/new-api/relay/common"
  11. "github.com/QuantumNous/new-api/types"
  12. "github.com/gin-gonic/gin"
  13. )
  14. func Playground(c *gin.Context) {
  15. var newAPIError *types.NewAPIError
  16. defer func() {
  17. if newAPIError != nil {
  18. c.JSON(newAPIError.StatusCode, gin.H{
  19. "error": newAPIError.ToOpenAIError(),
  20. })
  21. }
  22. }()
  23. useAccessToken := c.GetBool("use_access_token")
  24. if useAccessToken {
  25. newAPIError = types.NewError(errors.New("暂不支持使用 access token"), types.ErrorCodeAccessDenied, types.ErrOptionWithSkipRetry())
  26. return
  27. }
  28. relayInfo, err := relaycommon.GenRelayInfo(c, types.RelayFormatOpenAI, nil, nil)
  29. if err != nil {
  30. newAPIError = types.NewError(err, types.ErrorCodeInvalidRequest, types.ErrOptionWithSkipRetry())
  31. return
  32. }
  33. userId := c.GetInt("id")
  34. // Write user context to ensure acceptUnsetRatio is available
  35. userCache, err := model.GetUserCache(userId)
  36. if err != nil {
  37. newAPIError = types.NewError(err, types.ErrorCodeQueryDataError, types.ErrOptionWithSkipRetry())
  38. return
  39. }
  40. userCache.WriteContext(c)
  41. tempToken := &model.Token{
  42. UserId: userId,
  43. Name: fmt.Sprintf("playground-%s", relayInfo.UsingGroup),
  44. Group: relayInfo.UsingGroup,
  45. }
  46. _ = middleware.SetupContextForToken(c, tempToken)
  47. _, newAPIError = getChannel(c, relayInfo, 0)
  48. if newAPIError != nil {
  49. return
  50. }
  51. //middleware.SetupContextForSelectedChannel(c, channel, playgroundRequest.Model)
  52. common.SetContextKey(c, constant.ContextKeyRequestStartTime, time.Now())
  53. Relay(c, types.RelayFormatOpenAI)
  54. }