You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

пре 1 година
1234567891011121314151617181920212223242526272829303132333435363738
  1. import time
  2. import openai
  3. import openai.error
  4. from common.token_bucket import TokenBucket
  5. from common.log import logger
  6. from config import conf
  7. # OPENAI提供的画图接口
  8. class OpenAIImage(object):
  9. def __init__(self):
  10. openai.api_key = conf().get('open_ai_api_key')
  11. if conf().get('rate_limit_dalle'):
  12. self.tb4dalle = TokenBucket(conf().get('rate_limit_dalle', 50))
  13. def create_img(self, query, retry_count=0):
  14. try:
  15. if conf().get('rate_limit_dalle') and not self.tb4dalle.get_token():
  16. return False, "请求太快了,请休息一下再问我吧"
  17. logger.info("[OPEN_AI] image_query={}".format(query))
  18. response = openai.Image.create(
  19. prompt=query, #图片描述
  20. n=1, #每次生成图片的数量
  21. size="256x256" #图片大小,可选有 256x256, 512x512, 1024x1024
  22. )
  23. image_url = response['data'][0]['url']
  24. logger.info("[OPEN_AI] image_url={}".format(image_url))
  25. return True, image_url
  26. except openai.error.RateLimitError as e:
  27. logger.warn(e)
  28. if retry_count < 1:
  29. time.sleep(5)
  30. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count+1))
  31. return self.create_img(query, retry_count+1)
  32. else:
  33. return False, "提问太快啦,请休息一下再问我吧"
  34. except Exception as e:
  35. logger.exception(e)
  36. return False, str(e)