base.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  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. case "form":
  59. actFace = &FormClient{StdClient: StdClient{Client: me}}
  60. default:
  61. actFace = &FastgptClient{StdClient: StdClient{Client: me}}
  62. }
  63. return actFace, err
  64. }
  65. func (me *Client) NewOAC() {
  66. opts := []option.RequestOption{}
  67. if len(me.Config.ApiKey) > 0 {
  68. opts = append(opts, option.WithAPIKey(me.Config.ApiKey))
  69. }
  70. if len(me.Config.ApiBase) > 0 {
  71. opts = append(opts, option.WithBaseURL(me.Config.ApiBase))
  72. }
  73. oac := openai.NewClient(opts...)
  74. me.OAC = &oac
  75. }
  76. func (me *Client) Callback(clientType string, callbackUrl string, params any) (map[string]any, error) {
  77. actFace, err := me.getClientActFace(clientType)
  78. if err != nil {
  79. return nil, err
  80. }
  81. /*
  82. switch actFace.(type) {
  83. case *MismatchClient:
  84. fmt.Printf("MismatchClient.Callback() for EventType:'%s'\n", clientType)
  85. case *FastgptClient:
  86. fmt.Printf("FastgptClient.Callback() for EventType:'%s'\n", clientType)
  87. default:
  88. fmt.Printf("maybe StdClient.Callback() for EventType:'%s'\n", clientType)
  89. }
  90. */
  91. var newParams []byte
  92. if newParams, err = actFace.CallbackPrepare(params); err != nil {
  93. return nil, err
  94. }
  95. //Post(ctx context.Context, path string, params interface{}, res interface{}, opts ...option.RequestOption)
  96. resp := map[string]any{}
  97. err = me.OAC.Post(me.ctx, callbackUrl, newParams, &resp)
  98. if err != nil {
  99. return nil, err
  100. }
  101. return resp, nil
  102. }
  103. func (me *Client) Chat(chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  104. var (
  105. err error
  106. actFace clientActionFace
  107. apiResp *types.CompOpenApiResp
  108. )
  109. actFace, err = me.getClientActFace(chatInfo.EventType)
  110. if err != nil {
  111. return nil, err
  112. }
  113. /*
  114. switch actFace.(type) {
  115. case *MismatchClient:
  116. fmt.Printf("MismatchClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  117. case *FastgptClient:
  118. fmt.Printf("FastgptClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  119. default:
  120. fmt.Printf("maybe StdClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  121. }
  122. */
  123. err = actFace.BuildRequest(chatInfo)
  124. if err != nil {
  125. return nil, err
  126. }
  127. if chatInfo.Stream {
  128. apiResp, err = actFace.DoRequestStream(chatInfo)
  129. } else {
  130. apiResp, err = actFace.DoRequest(chatInfo)
  131. }
  132. return apiResp, err
  133. }
  134. func GenerateSchema[T any]() interface{} {
  135. // Structured Outputs uses a subset of JSON schema
  136. // These flags are necessary to comply with the subset
  137. reflector := jsonschema.Reflector{
  138. AllowAdditionalProperties: false,
  139. DoNotReference: true,
  140. }
  141. var v T
  142. schema := reflector.Reflect(v)
  143. return schema
  144. }
  145. func getHttpResponseTools(ctx context.Context) (*http.ResponseWriter, *http.Flusher, error) {
  146. hw, ok := contextkey.HttpResponseWriterKey.GetValue(ctx) //context取出http.ResponseWriter
  147. if !ok {
  148. return nil, nil, errors.New("content get http writer err")
  149. }
  150. flusher, ok := (hw).(http.Flusher)
  151. if !ok {
  152. return nil, nil, errors.New("streaming unsupported")
  153. }
  154. return &hw, &flusher, nil
  155. }
  156. func streamOut(ctx context.Context, res *http.Response) {
  157. var ehw http.ResponseWriter
  158. hw, flusher, err := getHttpResponseTools(ctx)
  159. if err != nil {
  160. http.Error(ehw, "Streaming unsupported!", http.StatusInternalServerError)
  161. }
  162. //获取API返回结果流
  163. chatStream := ssestream.NewStream[ApiRespStreamChunk](ApiRespStreamDecoder(res), err)
  164. defer chatStream.Close()
  165. //设置流式输出头 http1.1
  166. (*hw).Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  167. (*hw).Header().Set("Connection", "keep-alive")
  168. (*hw).Header().Set("Cache-Control", "no-cache")
  169. for chatStream.Next() {
  170. chunk := chatStream.Current()
  171. fmt.Fprintf((*hw), "data:%s\n\n", chunk.Data.RAW)
  172. (*flusher).Flush()
  173. //time.Sleep(1 * time.Millisecond)
  174. }
  175. fmt.Fprintf((*hw), "data:%s\n\n", "[DONE]")
  176. (*flusher).Flush()
  177. httpx.Ok((*hw))
  178. }