chatgpt调用.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # File : chatgpt调用.py
  4. # Author: DaShenHan&道长-----先苦后甜,任凭晚风拂柳颜------
  5. # Date : 2023/2/7
  6. import json
  7. import time
  8. # 文档地址: https://platform.openai.com/docs/api-reference/completions/create
  9. import requests
  10. API_KEY = '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'
  11. AUTH = f'Bearer {API_KEY}'
  12. def ask_chatpgt(word):
  13. """
  14. 问chatgpt得到答案
  15. """
  16. headers = {
  17. 'Content-Type':'application/json',
  18. 'Authorization':AUTH,
  19. }
  20. # print(headers)
  21. pdata = {
  22. "model": "text-davinci-003",
  23. "prompt": word,
  24. "temperature": 0.9,
  25. "max_tokens": 1000,
  26. "top_p": 1,
  27. "frequency_penalty": 0.0,
  28. "presence_penalty": 0.6,
  29. "stop": [" AI:"]
  30. }
  31. # print(pdata)
  32. t1 = time.time()
  33. ret = ''
  34. try:
  35. r = requests.post('https://api.openai.com/v1/completions',data=json.dumps(pdata),headers=headers)
  36. ret = r.json()
  37. answer = ret['choices'][0]['text']
  38. except Exception as e:
  39. answer = f'发生了错误:{e} {ret}'
  40. # print(ret)
  41. # print(answer)
  42. t2 = time.time()
  43. sec = round((t2 - t1)*1000,2)
  44. print(f'共计耗时:{sec}毫秒,{answer}')
  45. return [answer,sec]
  46. if __name__ == '__main__':
  47. print(ask_chatpgt('1+1等于几'))
  48. # https://chat.openai.com/auth/login
  49. # http://fastapi.frp.mudery.com/other_request/chatgpt
  50. # http://spider.scwinbao.com:8274/other_request/chatgpt
  51. # print(ask_chatpgt('假如我处于一个荒岛,现在我来扮演玩家,你来扮演电脑,你给我选项,我们玩一个荒岛求生的游戏'))
  52. # print(ask_chatpgt('以 背影为题,写一篇400字的作文'))