func.go 6.3 KB

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