oai.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import asyncio
  2. from typing import Dict
  3. import aiohttp
  4. from openai import OpenAI, AsyncOpenAI
  5. from openai.types import ResponseFormatJSONSchema
  6. from openai.types.chat import completion_create_params
  7. from pydantic import BaseModel
  8. from common.log import log
  9. async def generate_text(api_key: str, openai_base: str, model: str, messages: list[dict]):
  10. try:
  11. client_args = {}
  12. if api_key:
  13. client_args["api_key"] = api_key
  14. if openai_base:
  15. client_args["base_url"] = openai_base
  16. oai_client = AsyncOpenAI(**client_args)
  17. completion = await oai_client.chat.completions.create(
  18. model=model,
  19. temperature=0,
  20. messages=messages
  21. )
  22. if completion and isinstance(completion.choices, list) and len(completion.choices) > 0:
  23. first_choice = completion.choices[0]
  24. if first_choice and first_choice.message:
  25. return completion
  26. except Exception as e:
  27. log.error(f"[oai] generate_json failed: {e}")
  28. async def generate_json(api_key: str, openai_base: str, model: str, messages: list[dict], json_schema: dict):
  29. try:
  30. client_args = {}
  31. if api_key:
  32. client_args["api_key"] = api_key
  33. if openai_base:
  34. client_args["base_url"] = openai_base
  35. oai_client = AsyncOpenAI(**client_args)
  36. completion = await oai_client.chat.completions.create(
  37. model=model,
  38. messages=messages,
  39. response_format={
  40. "type": "json_schema",
  41. "json_schema": json_schema
  42. }
  43. )
  44. if completion and isinstance(completion.choices, list) and len(completion.choices) > 0:
  45. first_choice = completion.choices[0]
  46. if first_choice and first_choice.message:
  47. # return first_choice.message.content
  48. return completion
  49. except Exception as e:
  50. log.error(f"[oai] generate_json failed: {e}")
  51. async def generate_json_by_class(api_key: str, openai_base: str, model: str, messages: list[dict], json_schema: any):
  52. try:
  53. client_args = {}
  54. if api_key:
  55. client_args["api_key"] = api_key
  56. if openai_base:
  57. client_args["base_url"] = openai_base
  58. oai_client = AsyncOpenAI(**client_args)
  59. completion = await oai_client.beta.chat.completions.parse(
  60. model=model,
  61. messages=messages,
  62. response_format=json_schema
  63. )
  64. if completion and isinstance(completion.choices, list) and len(completion.choices) > 0:
  65. first_choice = completion.choices[0]
  66. if first_choice and first_choice.message:
  67. # return first_choice.message.content
  68. return completion
  69. except Exception as e:
  70. log.error(f"[oai] generate_json failed: {e}")
  71. async def send_request_with_retry(url: str, data: Dict, headers: Dict[str, str], max_retries: int, delay_between_retries: int) -> bool:
  72. for attempt in range(max_retries):
  73. try:
  74. async with aiohttp.ClientSession() as session:
  75. async with session.post(url, json=data, headers=headers, timeout=10) as response:
  76. response_data = await response.json()
  77. log.info(f"send_request_with_retry {url}: {response_data}")
  78. if response.status == 200:
  79. return True
  80. except (aiohttp.ClientError, asyncio.TimeoutError) as e:
  81. log.error(f"请求异常:{e}")
  82. if attempt < max_retries - 1:
  83. print("重试中...")
  84. await asyncio.sleep(delay_between_retries)
  85. return False