base.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  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. fmt.Printf("Callback Post(%s) By Params:'%s' error\n", callbackUrl, string(newParams))
  98. return nil, err
  99. }
  100. return resp, nil
  101. }
  102. func (me *Client) Chat(chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  103. var (
  104. err error
  105. actFace clientActionFace
  106. apiResp *types.CompOpenApiResp
  107. )
  108. actFace, err = me.getClientActFace(chatInfo.EventType)
  109. if err != nil {
  110. return nil, err
  111. }
  112. /*
  113. switch actFace.(type) {
  114. case *MismatchClient:
  115. fmt.Printf("MismatchClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  116. case *FastgptClient:
  117. fmt.Printf("FastgptClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  118. default:
  119. fmt.Printf("maybe StdClient.Chat() for EventType:'%s'\n", chatInfo.EventType)
  120. }
  121. */
  122. err = actFace.BuildRequest(chatInfo)
  123. if err != nil {
  124. return nil, err
  125. }
  126. if chatInfo.Stream {
  127. apiResp, err = actFace.DoRequestStream(chatInfo)
  128. } else {
  129. apiResp, err = actFace.DoRequest(chatInfo)
  130. }
  131. return apiResp, err
  132. }
  133. func GenerateSchema[T any]() interface{} {
  134. // Structured Outputs uses a subset of JSON schema
  135. // These flags are necessary to comply with the subset
  136. reflector := jsonschema.Reflector{
  137. AllowAdditionalProperties: false,
  138. DoNotReference: true,
  139. }
  140. var v T
  141. schema := reflector.Reflect(v)
  142. return schema
  143. }
  144. func getHttpResponseTools(ctx context.Context) (*http.ResponseWriter, *http.Flusher, error) {
  145. hw, ok := contextkey.HttpResponseWriterKey.GetValue(ctx) //context取出http.ResponseWriter
  146. if !ok {
  147. return nil, nil, errors.New("content get http writer err")
  148. }
  149. flusher, ok := (hw).(http.Flusher)
  150. if !ok {
  151. return nil, nil, errors.New("streaming unsupported")
  152. }
  153. return &hw, &flusher, nil
  154. }
  155. func streamOut(ctx context.Context, res *http.Response) {
  156. var ehw http.ResponseWriter
  157. hw, flusher, err := getHttpResponseTools(ctx)
  158. if err != nil {
  159. http.Error(ehw, "Streaming unsupported!", http.StatusInternalServerError)
  160. }
  161. //获取API返回结果流
  162. chatStream := ssestream.NewStream[ApiRespStreamChunk](ApiRespStreamDecoder(res), err)
  163. defer chatStream.Close()
  164. //设置流式输出头 http1.1
  165. (*hw).Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  166. (*hw).Header().Set("Connection", "keep-alive")
  167. (*hw).Header().Set("Cache-Control", "no-cache")
  168. for chatStream.Next() {
  169. chunk := chatStream.Current()
  170. fmt.Fprintf((*hw), "data:%s\n\n", chunk.Data.RAW)
  171. (*flusher).Flush()
  172. //time.Sleep(1 * time.Millisecond)
  173. }
  174. fmt.Fprintf((*hw), "data:%s\n\n", "[DONE]")
  175. (*flusher).Flush()
  176. httpx.Ok((*hw))
  177. }