ai_tongyi.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package ai
  2. import (
  3. "bytes"
  4. "data_ai/ul"
  5. "encoding/json"
  6. log "github.com/donnie4w/go-logger/logger"
  7. "io/ioutil"
  8. qu "jygit.jydev.jianyu360.cn/data_processing/common_utils"
  9. "net/http"
  10. "strings"
  11. )
  12. // 阿里通义
  13. func PostTongYiAI(content string) map[string]interface{} {
  14. // API的URL
  15. apiURL := "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
  16. // 构造请求数据
  17. messages := []map[string]interface{}{}
  18. messages = append(messages, map[string]interface{}{
  19. "role": "user",
  20. "content": content,
  21. })
  22. //qwen-plus qwen2-72b-instruct
  23. requestData := map[string]interface{}{
  24. "model": "qwen2-72b-instruct",
  25. "messages": messages,
  26. }
  27. jsonData, _ := json.Marshal(requestData)
  28. // 创建HTTP请求
  29. req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
  30. if err != nil {
  31. log.Debug("Error: %s", err)
  32. return map[string]interface{}{}
  33. }
  34. // 设置请求头
  35. req.Header.Set("Content-Type", "application/json")
  36. // 如果API需要认证,可以在这里设置认证信息
  37. req.Header.Set("Authorization", "Bearer sk-5db8cfa345754e329c492973b0ecad27")
  38. // 发起请求
  39. client := &http.Client{}
  40. resp, err := client.Do(req)
  41. if err != nil {
  42. log.Debug("Error: %s", err)
  43. return map[string]interface{}{}
  44. }
  45. defer resp.Body.Close()
  46. // 解析响应
  47. body, _ := ioutil.ReadAll(resp.Body)
  48. res := make(map[string]interface{})
  49. json.Unmarshal(body, &res)
  50. if res != nil {
  51. if choices := ul.IsMarkInterfaceMap(res["choices"]); len(choices) > 0 {
  52. if message := qu.ObjToMap(choices[0]["message"]); message != nil {
  53. result := qu.ObjToString((*message)["content"])
  54. result = strings.ReplaceAll(result, "\n", "")
  55. result = strings.ReplaceAll(result, "json", "")
  56. result = strings.ReplaceAll(result, "`", "")
  57. result = strings.ReplaceAll(result, "[", "")
  58. result = strings.ReplaceAll(result, "]", "")
  59. if new_result := ul.SaveResultReg.FindString(result); new_result != "" {
  60. result = new_result
  61. }
  62. dict := make(map[string]interface{})
  63. json.Unmarshal([]byte(result), &dict)
  64. return dict
  65. }
  66. }
  67. }
  68. return map[string]interface{}{}
  69. }