Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

43 lines
1.6KB

  1. import time
  2. import openai
  3. import openai.error
  4. from common.log import logger
  5. from common.token_bucket import TokenBucket
  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, api_key=None):
  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. api_key=api_key,
  20. prompt=query, # 图片描述
  21. n=1, # 每次生成图片的数量
  22. size=conf().get("image_create_size", "256x256"), # 图片大小,可选有 256x256, 512x512, 1024x1024
  23. )
  24. image_url = response["data"][0]["url"]
  25. logger.info("[OPEN_AI] image_url={}".format(image_url))
  26. return True, image_url
  27. except openai.error.RateLimitError as e:
  28. logger.warn(e)
  29. if retry_count < 1:
  30. time.sleep(5)
  31. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count + 1))
  32. return self.create_img(query, retry_count + 1)
  33. else:
  34. return False, "提问太快啦,请休息一下再问我吧"
  35. except Exception as e:
  36. logger.exception(e)
  37. return False, str(e)