playground.go 1.4 KB

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