chatApi.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package model
  2. import (
  3. "aiChat/internal/consts"
  4. "bufio"
  5. "context"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/net/gclient"
  8. "github.com/gogf/gf/v2/util/gconv"
  9. "net/http"
  10. "strings"
  11. )
  12. type GPTReq struct {
  13. *BaseQuestion
  14. Identity string `json:"identity"`
  15. }
  16. // SimpleRes 语义服务,响应常用问题
  17. type SimpleRes struct {
  18. Status int `json:"status"`
  19. Result struct {
  20. Prompt string `json:"prompt"`
  21. Answer string `json:"answer"`
  22. } `json:"result"`
  23. }
  24. // GPTRes 业务及扩展聊天响应
  25. type GPTRes struct {
  26. Status int `json:"status"`
  27. Response string `json:"response"`
  28. History [][]string `json:"history"`
  29. Time string `json:"time"`
  30. }
  31. var (
  32. ChatGpt = &cChatGpt{}
  33. )
  34. type cChatGpt struct {
  35. }
  36. func (c *cChatGpt) SimpleDo(ctx context.Context, qReq *QuestionReq) (res *SimpleRes, err error) {
  37. gReq := GPTReq{
  38. BaseQuestion: qReq.BaseQuestion,
  39. Identity: g.Config().MustGet(ctx, "chat.api.identity", "剑鱼chat").String(),
  40. }
  41. var gRes *gclient.Response
  42. gRes, err = g.Client().Header(consts.RequestJsonHeader).Post(ctx, g.Config().MustGet(ctx, "chat.api.addr_simple", "").String(), gReq)
  43. if err != nil {
  44. return nil, err
  45. }
  46. res = &SimpleRes{}
  47. err = gconv.Struct(gRes.ReadAll(), res)
  48. //g.Dump("SimpleDo", gReq, res)
  49. if err != nil {
  50. return nil, err
  51. }
  52. return
  53. }
  54. func (c *cChatGpt) GPTDo(ctx context.Context, qReq *QuestionReq) (res *bufio.Reader, err error) {
  55. gReq := GPTReq{
  56. BaseQuestion: qReq.BaseQuestion,
  57. Identity: g.Config().MustGet(ctx, "chat.api.identity", "剑鱼chat").String(),
  58. }
  59. if gReq.History == nil {
  60. gReq.History = [][]string{}
  61. }
  62. req, err := http.NewRequest("POST", g.Config().MustGet(ctx, "chat.api.addr_answer", "").String(), strings.NewReader(gconv.String(gReq)))
  63. client := &http.Client{}
  64. req.Header.Set("Accept", "text/event-stream")
  65. resp, err := client.Do(req)
  66. return bufio.NewReader(resp.Body), nil
  67. }
  68. type BufRes struct {
  69. Delta string `json:"delta"`
  70. Response string `json:"response"`
  71. Finished bool `json:"finished"`
  72. }
  73. func readEvent(res *bufio.Reader) (string, error) {
  74. event := ""
  75. buf := make([]byte, 1024)
  76. for {
  77. n, err := res.Read(buf)
  78. if err != nil {
  79. return "", err
  80. }
  81. // 解析Event-Stream消息
  82. for _, b := range buf[:n] {
  83. if b == '\n' {
  84. return event, nil
  85. }
  86. event += string(b)
  87. }
  88. }
  89. }