ERNIE_utils.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import requests
  2. import json
  3. def get_access_token():
  4. """
  5. 使用 API Key,Secret Key 获取access_token,替换下列示例中的应用API Key、应用Secret Key
  6. """
  7. url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=gnwVXv96An9qMYqq9eWbeNqk&client_secret=mDsRQbCPsV4N7x28LbwkhTAaLmrrDnXk"
  8. payload = json.dumps("")
  9. headers = {
  10. 'Content-Type': 'application/json',
  11. 'Accept': 'application/json'
  12. }
  13. response = requests.request("POST", url, headers=headers, data=payload)
  14. return response.json().get("access_token")
  15. def main():
  16. # _token = get_access_token()
  17. _token = "24.93c9d66ffc94ffaef6c6c9d35770a5f5.2592000.1701242081.282335-37357318"
  18. url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + _token
  19. payload = json.dumps({
  20. "messages": [
  21. {
  22. "role": "user",
  23. "content": '''
  24. 假设分类是建筑建材-建筑涂料的相关产品词“面漆”
  25. 请拓展其相关行业产品词,列举30个
  26. '''
  27. }
  28. ]
  29. })
  30. headers = {
  31. 'Content-Type': 'application/json'
  32. }
  33. response = requests.request("POST", url, headers=headers, data=payload)
  34. print(response.text)
  35. def chat(message):
  36. _token = "24.93c9d66ffc94ffaef6c6c9d35770a5f5.2592000.1701242081.282335-37357318"
  37. url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token=" + _token
  38. payload = json.dumps({
  39. "messages": [
  40. {
  41. "role": "user",
  42. "content": '''
  43. %s
  44. '''%message
  45. }
  46. ]
  47. })
  48. headers = {
  49. 'Content-Type': 'application/json'
  50. }
  51. response = requests.request("POST", url, headers=headers, data=payload)
  52. return response
  53. if __name__ == '__main__':
  54. main()