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.

45 lines
1.8KB

  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. openai.api_base = conf().get("open_ai_api_base")
  12. if conf().get("rate_limit_dalle"):
  13. self.tb4dalle = TokenBucket(conf().get("rate_limit_dalle", 50))
  14. def create_img(self, query, retry_count=0, api_key=None):
  15. try:
  16. if conf().get("rate_limit_dalle") and not self.tb4dalle.get_token():
  17. return False, "请求太快了,请休息一下再问我吧"
  18. logger.info("[OPEN_AI] image_query={}".format(query))
  19. response = openai.Image.create(
  20. api_key=api_key,
  21. prompt=query, # 图片描述
  22. n=1, # 每次生成图片的数量
  23. model=conf().get("text_to_image") or "dall-e-2",
  24. # size=conf().get("image_create_size", "256x256"), # 图片大小,可选有 256x256, 512x512, 1024x1024
  25. )
  26. image_url = response["data"][0]["url"]
  27. logger.info("[OPEN_AI] image_url={}".format(image_url))
  28. return True, image_url
  29. except openai.error.RateLimitError as e:
  30. logger.warn(e)
  31. if retry_count < 1:
  32. time.sleep(5)
  33. logger.warn("[OPEN_AI] ImgCreate RateLimit exceed, 第{}次重试".format(retry_count + 1))
  34. return self.create_img(query, retry_count + 1)
  35. else:
  36. return False, "画图出现问题,请休息一下再问我吧"
  37. except Exception as e:
  38. logger.exception(e)
  39. return False, "画图出现问题,请休息一下再问我吧"