std.go 1.9 KB

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