adaptor.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package tencent
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/gin-gonic/gin"
  6. "io"
  7. "net/http"
  8. "one-api/dto"
  9. "one-api/relay/channel"
  10. relaycommon "one-api/relay/common"
  11. "one-api/service"
  12. "strings"
  13. )
  14. type Adaptor struct {
  15. Sign string
  16. }
  17. func (a *Adaptor) Init(info *relaycommon.RelayInfo, request dto.GeneralOpenAIRequest) {
  18. }
  19. func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
  20. return fmt.Sprintf("%s/hyllm/v1/chat/completions", info.BaseUrl), nil
  21. }
  22. func (a *Adaptor) SetupRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  23. channel.SetupApiRequestHeader(info, c, req)
  24. req.Header.Set("Authorization", a.Sign)
  25. req.Header.Set("X-TC-Action", info.UpstreamModelName)
  26. return nil
  27. }
  28. func (a *Adaptor) ConvertRequest(c *gin.Context, relayMode int, request *dto.GeneralOpenAIRequest) (any, error) {
  29. if request == nil {
  30. return nil, errors.New("request is nil")
  31. }
  32. apiKey := c.Request.Header.Get("Authorization")
  33. apiKey = strings.TrimPrefix(apiKey, "Bearer ")
  34. appId, secretId, secretKey, err := parseTencentConfig(apiKey)
  35. if err != nil {
  36. return nil, err
  37. }
  38. tencentRequest := requestOpenAI2Tencent(*request)
  39. tencentRequest.AppId = appId
  40. tencentRequest.SecretId = secretId
  41. // we have to calculate the sign here
  42. a.Sign = getTencentSign(*tencentRequest, secretKey)
  43. return tencentRequest, nil
  44. }
  45. func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  46. return channel.DoApiRequest(a, c, info, requestBody)
  47. }
  48. func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage *dto.Usage, err *dto.OpenAIErrorWithStatusCode) {
  49. if info.IsStream {
  50. var responseText string
  51. err, responseText = tencentStreamHandler(c, resp)
  52. usage, _ = service.ResponseText2Usage(responseText, info.UpstreamModelName, info.PromptTokens)
  53. } else {
  54. err, usage = tencentHandler(c, resp)
  55. }
  56. return
  57. }
  58. func (a *Adaptor) GetModelList() []string {
  59. return ModelList
  60. }
  61. func (a *Adaptor) GetChannelName() string {
  62. return ChannelName
  63. }