ai_tongyi.go 2.0 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. "time"
  12. )
  13. // 阿里通义
  14. func PostTongYiAI(content string) map[string]interface{} {
  15. // API的URL
  16. apiURL := "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions"
  17. // 构造请求数据
  18. messages := []map[string]interface{}{}
  19. messages = append(messages, map[string]interface{}{
  20. "role": "user",
  21. "content": content,
  22. })
  23. //qwen-plus qwen2-72b-instruct
  24. requestData := map[string]interface{}{
  25. "model": "qwen2-72b-instruct",
  26. "messages": messages,
  27. }
  28. jsonData, _ := json.Marshal(requestData)
  29. // 创建HTTP请求
  30. req, err := http.NewRequest("POST", apiURL, bytes.NewBuffer(jsonData))
  31. if err != nil {
  32. log.Debug("Error: %s", err)
  33. return map[string]interface{}{}
  34. }
  35. // 设置请求头
  36. req.Header.Set("Content-Type", "application/json")
  37. // 如果API需要认证,可以在这里设置认证信息
  38. req.Header.Set("Authorization", "Bearer sk-5db8cfa345754e329c492973b0ecad27")
  39. // 发起请求
  40. client := &http.Client{}
  41. client.Timeout = 180 * time.Second
  42. resp, err := client.Do(req)
  43. if err != nil {
  44. log.Debug("Error: %s", err)
  45. return map[string]interface{}{}
  46. }
  47. defer resp.Body.Close()
  48. // 解析响应
  49. body, _ := ioutil.ReadAll(resp.Body)
  50. res := make(map[string]interface{})
  51. json.Unmarshal(body, &res)
  52. if res != nil {
  53. if choices := ul.IsMarkInterfaceMap(res["choices"]); len(choices) > 0 {
  54. if message := qu.ObjToMap(choices[0]["message"]); message != nil {
  55. result := qu.ObjToString((*message)["content"])
  56. result = ul.Escape.ReplaceAllString(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. }