func.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. package compapi
  2. import (
  3. "context"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "net/http"
  8. "wechat-api/internal/types"
  9. "wechat-api/internal/utils/contextkey"
  10. openai "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 StdChatClient struct {
  16. *openai.Client
  17. }
  18. func NewStdChatClient(apiKey string, apiBase string) *StdChatClient {
  19. opts := []option.RequestOption{}
  20. if len(apiKey) > 0 {
  21. opts = append(opts, option.WithAPIKey(apiKey))
  22. }
  23. opts = append(opts, option.WithBaseURL(apiBase))
  24. client := openai.NewClient(opts...)
  25. return &StdChatClient{&client}
  26. }
  27. func NewAiClient(apiKey string, apiBase string) *openai.Client {
  28. opts := []option.RequestOption{}
  29. if len(apiKey) > 0 {
  30. opts = append(opts, option.WithAPIKey(apiKey))
  31. }
  32. opts = append(opts, option.WithBaseURL(apiBase))
  33. client := openai.NewClient(opts...)
  34. return &client
  35. }
  36. func NewFastgptClient(apiKey string) *openai.Client {
  37. //http://fastgpt.ascrm.cn/api/v1/
  38. client := openai.NewClient(option.WithAPIKey(apiKey),
  39. option.WithBaseURL("http://fastgpt.ascrm.cn/api/v1/"))
  40. return &client
  41. }
  42. func NewDeepSeekClient(apiKey string) *openai.Client {
  43. client := openai.NewClient(option.WithAPIKey(apiKey),
  44. option.WithBaseURL("https://api.deepseek.com"))
  45. return &client
  46. }
  47. func DoChatCompletions(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  48. var (
  49. jsonBytes []byte
  50. err error
  51. )
  52. emptyParams := openai.ChatCompletionNewParams{}
  53. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  54. return nil, err
  55. }
  56. //fmt.Printf("In DoChatCompletions, req: '%s'\n", string(jsonBytes))
  57. //也许应该对请求体不规范成员名进行检查
  58. customResp := types.CompOpenApiResp{}
  59. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  60. respBodyOps := option.WithResponseBodyInto(&customResp)
  61. if _, err = client.Chat.Completions.New(ctx, emptyParams, reqBodyOps, respBodyOps); err != nil {
  62. return nil, err
  63. }
  64. if customResp.FgtErrCode != nil && customResp.FgtErrStatusTxt != nil { //针对fastgpt出错但New()不返回错误的情况
  65. return nil, fmt.Errorf("%s(%d)", *customResp.FgtErrStatusTxt, *customResp.FgtErrCode)
  66. }
  67. return &customResp, nil
  68. }
  69. func DoChatCompletionsStream(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (res *types.CompOpenApiResp, err error) {
  70. var (
  71. jsonBytes []byte
  72. raw *http.Response
  73. //raw []byte
  74. ok bool
  75. hw http.ResponseWriter
  76. )
  77. hw, ok = contextkey.HttpResponseWriterKey.GetValue(ctx) //context取出http.ResponseWriter
  78. if !ok {
  79. return nil, errors.New("content get http writer err")
  80. }
  81. flusher, ok := (hw).(http.Flusher)
  82. if !ok {
  83. http.Error(hw, "Streaming unsupported!", http.StatusInternalServerError)
  84. }
  85. emptyParams := openai.ChatCompletionNewParams{}
  86. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  87. return nil, err
  88. }
  89. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  90. respBodyOps := option.WithResponseBodyInto(&raw)
  91. if _, err = client.Chat.Completions.New(ctx, emptyParams, reqBodyOps, respBodyOps, option.WithJSONSet("stream", true)); err != nil {
  92. return nil, err
  93. }
  94. //设置流式输出头 http1.1
  95. hw.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  96. hw.Header().Set("Connection", "keep-alive")
  97. hw.Header().Set("Cache-Control", "no-cache")
  98. chatStream := ssestream.NewStream[ApiRespStreamChunk](ApiRespStreamDecoder(raw), err)
  99. defer chatStream.Close()
  100. for chatStream.Next() {
  101. chunk := chatStream.Current()
  102. fmt.Fprintf(hw, "data:%s\n\n", chunk.Data.RAW)
  103. flusher.Flush()
  104. //time.Sleep(1 * time.Millisecond)
  105. }
  106. fmt.Fprintf(hw, "data:%s\n\n", "[DONE]")
  107. flusher.Flush()
  108. httpx.Ok(hw)
  109. return nil, nil
  110. }
  111. func NewChatCompletions(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  112. if chatInfo.Stream {
  113. return DoChatCompletionsStream(ctx, client, chatInfo)
  114. } else {
  115. return DoChatCompletions(ctx, client, chatInfo)
  116. }
  117. }
  118. func NewMismatchChatCompletions(ctx context.Context, apiKey string, apiBase string, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  119. client := NewAiClient(apiKey, apiBase)
  120. return NewChatCompletions(ctx, client, chatInfo)
  121. }
  122. func NewFastgptChatCompletions(ctx context.Context, apiKey string, apiBase string, chatInfo *types.CompApiReq) (*types.CompOpenApiResp, error) {
  123. client := NewAiClient(apiKey, apiBase)
  124. return NewChatCompletions(ctx, client, chatInfo)
  125. }
  126. func NewDeepSeekChatCompletions(ctx context.Context, apiKey string, chatInfo *types.CompApiReq, chatModel openai.ChatModel) (res *types.CompOpenApiResp, err error) {
  127. client := NewDeepSeekClient(apiKey)
  128. if chatModel != ChatModelDeepSeekV3 {
  129. chatModel = ChatModelDeepSeekR1
  130. }
  131. chatInfo.Model = chatModel
  132. return NewChatCompletions(ctx, client, chatInfo)
  133. }
  134. func DoChatCompletionsStreamOld(ctx context.Context, client *openai.Client, chatInfo *types.CompApiReq) (res *types.CompOpenApiResp, err error) {
  135. var (
  136. jsonBytes []byte
  137. )
  138. emptyParams := openai.ChatCompletionNewParams{}
  139. if jsonBytes, err = json.Marshal(chatInfo); err != nil {
  140. return nil, err
  141. }
  142. reqBodyOps := option.WithRequestBody("application/json", jsonBytes)
  143. //customResp := types.CompOpenApiResp{}
  144. //respBodyOps := option.WithResponseBodyInto(&customResp)
  145. //chatStream := client.Chat.Completions.NewStreaming(ctx, emptyParams, reqBodyOps, respBodyOps)
  146. chatStream := client.Chat.Completions.NewStreaming(ctx, emptyParams, reqBodyOps)
  147. // optionally, an accumulator helper can be used
  148. acc := openai.ChatCompletionAccumulator{}
  149. httpWriter, ok := ctx.Value("HttpResp-Writer").(http.ResponseWriter)
  150. if !ok {
  151. return nil, errors.New("content get writer err")
  152. }
  153. //httpWriter.Header().Set("Content-Type", "text/event-stream;charset=utf-8")
  154. //httpWriter.Header().Set("Connection", "keep-alive")
  155. //httpWriter.Header().Set("Cache-Control", "no-cache")
  156. idx := 0
  157. for chatStream.Next() {
  158. chunk := chatStream.Current()
  159. acc.AddChunk(chunk)
  160. fmt.Printf("=====>get %d chunk:%v\n", idx, chunk)
  161. if _, err := fmt.Fprintf(httpWriter, "%v", chunk); err != nil {
  162. fmt.Printf("Error writing to client:%v \n", err)
  163. break
  164. }
  165. if content, ok := acc.JustFinishedContent(); ok {
  166. println("Content stream finished:", content)
  167. }
  168. // if using tool calls
  169. if tool, ok := acc.JustFinishedToolCall(); ok {
  170. println("Tool call stream finished:", tool.Index, tool.Name, tool.Arguments)
  171. }
  172. if refusal, ok := acc.JustFinishedRefusal(); ok {
  173. println("Refusal stream finished:", refusal)
  174. }
  175. // it's best to use chunks after handling JustFinished events
  176. if len(chunk.Choices) > 0 {
  177. idx++
  178. fmt.Printf("idx:%d get =>'%s'\n", idx, chunk.Choices[0].Delta.Content)
  179. }
  180. }
  181. if err := chatStream.Err(); err != nil {
  182. return nil, err
  183. }
  184. return nil, nil
  185. }
  186. func GetWorkInfoByID(eventType string, workId string) (string, uint) {
  187. val, exist := fastgptWorkIdMap[workId]
  188. if !exist {
  189. val = fastgptWorkIdMap["default"]
  190. }
  191. return val.Id, val.Idx
  192. }
  193. // 获取workToken
  194. func GetWorkTokenByID(eventType string, workId string) string {
  195. id, _ := GetWorkInfoByID(eventType, workId)
  196. return id
  197. }
  198. // 获取workIdx
  199. func GetWorkIdxByID(eventType string, workId string) uint {
  200. _, idx := GetWorkInfoByID(eventType, workId)
  201. return idx
  202. }