base.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. package compapi
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "wechat-api/internal/types"
  8. "wechat-api/internal/utils/contextkey"
  9. "github.com/invopop/jsonschema"
  10. "github.com/openai/openai-go"
  11. "github.com/openai/openai-go/option"
  12. "github.com/openai/openai-go/packages/ssestream"
  13. "github.com/zeromicro/go-zero/rest/httpx"
  14. )
  15. type ClientConfig struct {
  16. ApiKey string
  17. ApiBase string
  18. }
  19. type ClientOption func(*ClientConfig)
  20. func WithApiKey(ApiKey string) ClientOption {
  21. return func(cfg *ClientConfig) {
  22. cfg.ApiKey = ApiKey
  23. }
  24. }
  25. func WithApiBase(ApiBase string) ClientOption {
  26. return func(cfg *ClientConfig) {
  27. cfg.ApiBase = ApiBase
  28. }
  29. }
  30. type clientActionFace interface {
  31. DoRequest(req *types.CompApiReq) (*types.CompOpenApiResp, error)
  32. DoRequestStream(req *types.CompApiReq) (*types.CompOpenApiResp, error)
  33. BuildRequest(req *types.CompApiReq) error
  34. CallbackPrepare(params any) ([]byte, error)
  35. }
  36. type Client struct {
  37. OAC *openai.Client
  38. Config ClientConfig
  39. ctx context.Context
  40. }
  41. func NewClient(ctx context.Context, opts ...ClientOption) *Client {
  42. client := Client{}
  43. for _, opt := range opts {
  44. opt(&client.Config)
  45. }
  46. client.NewOAC() //初始化openai client
  47. client.ctx = ctx
  48. return &client
  49. }
  50. func (me *Client) getClientActFace(clientType string) (clientActionFace, error) {
  51. var (
  52. err error
  53. actFace clientActionFace
  54. )
  55. switch clientType {
  56. case "mismatch":
  57. actFace = &MismatchClient{StdClient: StdClient{Client: me}}
  58. default:
  59. actFace = &FastgptClient{StdClient: StdClient{Client: me}}
  60. }
  61. return actFace, err
  62. }
  63. func (me *Client) NewOAC() {
  64. opts := []option.RequestOption{}
  65. if len(me.Config.ApiKey) > 0 {
  66. opts = append(opts, option.WithAPIKey(me.Config.ApiKey))
  67. }
  68. if len(me.Config.ApiBase) > 0 {
  69. opts = append(opts, option.WithBaseURL(me.Config.ApiBase))
  70. }
  71. oac := openai.NewClient(opts...)
  72. me.OAC = &oac
  73. }
  74. func (me *Client) Callback(clientType string, callbackUrl string, params any) (map[string]any, error) {
  75. actFace, err := me.getClientActFace(clientType)
  76. if err != nil {
  77. return nil, err
  78. }
  79. /*
  80. switch actFace.(type) {
  81. case *MismatchClient:
  82. fmt.Printf("MismatchClient.Callback() for EventType:'%s'\n", clientType)
  83. case *FastgptClient:
  84. fmt.Printf("FastgptClient.Callback() for EventType:'%s'\n", clientType)
  85. default:
  86. fmt.Printf("maybe StdClient.Callback() for EventType:'%s'\n", clientType)
  87. }
  88. */
  89. var newParams []byte
  90. if newParams, err = actFace.CallbackPrepare(params); err != nil {
  91. return nil, err
  92. }
  93. //Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption)
  94. resp := map[string]any{}
  95. err = me.OAC.Post(me.ctx, callbackUrl, newParams, &resp)
  96. if err != nil {
  97. return nil, err
  98. }
  99. return resp, nil
  100. }
  101. func (me *Client) Chat(chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  102. var (
  103. err error
  104. actFace clientActionFace
  105. apiResp *types.CompOpenApiResp
  106. )
  107. actFace, err = me.getClientActFace(chatInfo.EventType)
  108. if err != nil {
  109. return nil, err
  110. }
  111. /*
  112. switch actFace.(type) {
  113. case *MismatchClient:
  114. fmt.Printf("MismatchClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  115. case *FastgptClient:
  116. fmt.Printf("FastgptClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  117. default:
  118. fmt.Printf("maybe StdClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  119. }
  120. */
  121. err = actFace.BuildRequest(chatInfo)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if chatInfo.Stream {
  126. apiResp, err = actFace.DoRequestStream(chatInfo)
  127. } else {
  128. apiResp, err = actFace.DoRequest(chatInfo)
  129. }
  130. return apiResp, err
  131. }
  132. func GenerateSchema[T any]() interface{} {
  133. // Structured Outputs uses a subset of JSON schema
  134. // These flags are necessary to comply with the subset
  135. reflector := jsonschema.Reflector{
  136. AllowAdditionalProperties: false,
  137. DoNotReference: true,
  138. }
  139. var v T
  140. schema := reflector.Reflect(v)
  141. return schema
  142. }
  143. func getHttpResponseTools(ctx context.Context) (*http.ResponseWriter, *http.Flusher, error) {
  144. hw, ok := contextkey.HttpResponseWriterKey.GetValue(ctx) //context取出http.ResponseWriter
  145. if !ok {
  146. return nil, nil, errors.New("content get http writer err")
  147. }
  148. flusher, ok := (hw).(http.Flusher)
  149. if !ok {
  150. return nil, nil, errors.New("streaming unsupported")
  151. }
  152. return &hw, &flusher, nil
  153. }
  154. func streamOut(ctx context.Context, res *http.Response) {
  155. var ehw http.ResponseWriter
  156. hw, flusher, err := getHttpResponseTools(ctx)
  157. if err != nil {
  158. http.Error(ehw, "Streaming unsupported!", http.StatusInternalServerError)
  159. }
  160. //获取API返回结果流
  161. chatStream := ssestream.NewStream[ApiRespStreamChunk](ApiRespStreamDecoder(res), err)
  162. defer chatStream.Close()
  163. //设置流式输出头 http1.1
  164. (*hw).Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  165. (*hw).Header().Set("Connection", "keep-alive")
  166. (*hw).Header().Set("Cache-Control", "no-cache")
  167. for chatStream.Next() {
  168. chunk := chatStream.Current()
  169. fmt.Fprintf((*hw), "data:%s\n\n", chunk.Data.RAW)
  170. (*flusher).Flush()
  171. //time.Sleep(1 * time.Millisecond)
  172. }
  173. fmt.Fprintf((*hw), "data:%s\n\n", "[DONE]")
  174. (*flusher).Flush()
  175. httpx.Ok((*hw))
  176. }