2022-12-19 22:51:56 +08:00
|
|
|
import logging
|
|
|
|
|
2022-12-07 22:27:05 +08:00
|
|
|
import openai
|
|
|
|
|
2022-12-13 16:04:51 +08:00
|
|
|
import config
|
|
|
|
|
2022-12-15 17:52:41 +08:00
|
|
|
import pkg.openai.keymgr
|
2022-12-28 00:05:25 +08:00
|
|
|
import pkg.openai.pricing as pricing
|
2023-01-01 23:18:32 +08:00
|
|
|
import pkg.utils.context
|
2022-12-07 22:27:05 +08:00
|
|
|
|
|
|
|
|
2022-12-11 16:10:12 +08:00
|
|
|
# 为其他模块提供与OpenAI交互的接口
|
2022-12-07 22:27:05 +08:00
|
|
|
class OpenAIInteract:
|
|
|
|
api_params = {}
|
|
|
|
|
2022-12-15 17:52:41 +08:00
|
|
|
key_mgr = None
|
|
|
|
|
2022-12-27 22:52:53 +08:00
|
|
|
default_image_api_params = {
|
|
|
|
"size": "256x256",
|
|
|
|
}
|
|
|
|
|
|
|
|
def __init__(self, api_key: str):
|
2022-12-15 17:52:41 +08:00
|
|
|
# self.api_key = api_key
|
2022-12-07 22:27:05 +08:00
|
|
|
|
2022-12-15 17:52:41 +08:00
|
|
|
self.key_mgr = pkg.openai.keymgr.KeysManager(api_key)
|
|
|
|
|
|
|
|
openai.api_key = self.key_mgr.get_using_key()
|
2022-12-07 22:27:05 +08:00
|
|
|
|
2023-01-01 23:18:32 +08:00
|
|
|
pkg.utils.context.set_openai_manager(self)
|
2022-12-07 22:27:05 +08:00
|
|
|
|
2022-12-11 16:10:12 +08:00
|
|
|
# 请求OpenAI Completion
|
2022-12-07 22:27:05 +08:00
|
|
|
def request_completion(self, prompt, stop):
|
|
|
|
response = openai.Completion.create(
|
|
|
|
prompt=prompt,
|
|
|
|
stop=stop,
|
2022-12-13 16:04:51 +08:00
|
|
|
timeout=config.process_message_timeout,
|
2022-12-27 22:52:53 +08:00
|
|
|
**config.completion_api_params
|
2022-12-07 22:27:05 +08:00
|
|
|
)
|
2022-12-28 00:05:25 +08:00
|
|
|
|
|
|
|
switched = self.key_mgr.report_fee(pricing.language_base_price(config.completion_api_params['model'],
|
|
|
|
prompt + response['choices'][0]['text']))
|
2022-12-15 17:52:41 +08:00
|
|
|
if switched:
|
|
|
|
openai.api_key = self.key_mgr.get_using_key()
|
|
|
|
|
2022-12-07 22:27:05 +08:00
|
|
|
return response
|
|
|
|
|
2022-12-27 22:52:53 +08:00
|
|
|
def request_image(self, prompt):
|
2022-12-28 00:05:25 +08:00
|
|
|
|
|
|
|
params = config.image_api_params if hasattr(config, "image_api_params") else self.default_image_api_params
|
|
|
|
|
2022-12-27 22:52:53 +08:00
|
|
|
response = openai.Image.create(
|
|
|
|
prompt=prompt,
|
|
|
|
n=1,
|
2022-12-28 00:05:25 +08:00
|
|
|
**params
|
2022-12-27 22:52:53 +08:00
|
|
|
)
|
|
|
|
|
2022-12-28 00:05:25 +08:00
|
|
|
switched = self.key_mgr.report_fee(pricing.image_price(params['size']))
|
|
|
|
|
|
|
|
if switched:
|
|
|
|
openai.api_key = self.key_mgr.get_using_key()
|
|
|
|
|
2022-12-27 22:52:53 +08:00
|
|
|
return response
|
|
|
|
|