std.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. package compapi
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "wechat-api/ent"
  7. "wechat-api/internal/types"
  8. "github.com/openai/openai-go"
  9. "github.com/openai/openai-go/option"
  10. )
  11. type StdClient struct {
  12. *Client
  13. }
  14. func (me *StdClient) CallbackPrepare(params any) ([]byte, error) {
  15. taskData, ok := params.(*ent.CompapiAsynctask)
  16. if !ok {
  17. return nil, errors.New("invalid callback taskdata")
  18. }
  19. return AnyToBytes(taskData.ResponseRaw)
  20. }
  21. func (me *StdClient) DoRequestBS(req []byte,
  22. customResp any, isSteam bool) (*openai.ChatCompletion, error) {
  23. opts := []option.RequestOption{}
  24. if len(req) > 0 {
  25. opts = append(opts, option.WithRequestBody("application/json", req))
  26. } else {
  27. return nil, errors.New("request body empty")
  28. }
  29. if customResp != nil {
  30. opts = append(opts, option.WithResponseBodyInto(customResp))
  31. }
  32. if isSteam {
  33. opts = append(opts, option.WithJSONSet("stream", true))
  34. }
  35. emptyParams := openai.ChatCompletionNewParams{}
  36. return me.OAC.Chat.Completions.New(me.ctx, emptyParams, opts...)
  37. }
  38. func (me *StdClient) DoRequest(req *types.CompApiReq) (*types.CompOpenApiResp, error) {
  39. //fmt.Println(typekit.PrettyPrint(req))
  40. jsonBytes, err := req.ToBytes()
  41. if err != nil {
  42. return nil, err
  43. }
  44. customResp := types.CompOpenApiResp{}
  45. if _, err = me.DoRequestBS(jsonBytes, &customResp, req.Stream); err != nil {
  46. return nil, err
  47. }
  48. if customResp.FgtErrCode != nil && customResp.FgtErrStatusTxt != nil { //针对fastgpt出错但New()不返回错误的情况
  49. return nil, fmt.Errorf("%s(%d)", *customResp.FgtErrStatusTxt, *customResp.FgtErrCode)
  50. }
  51. return &customResp, nil
  52. }
  53. func (me *StdClient) DoRequestStream(req *types.CompApiReq) (*types.CompOpenApiResp, error) {
  54. var (
  55. //raw []byte
  56. raw *http.Response
  57. jsonBytes []byte
  58. err error
  59. )
  60. jsonBytes, err = req.ToBytes()
  61. if err != nil {
  62. return nil, err
  63. }
  64. if _, err = me.DoRequestBS(jsonBytes, &raw, req.Stream); err != nil {
  65. return nil, err
  66. }
  67. streamOut(me.ctx, raw)
  68. return nil, nil
  69. }
  70. func (me *StdClient) BuildRequest(req *types.CompApiReq) error {
  71. return nil
  72. }