2024-07-07 01:58:23 +08:00
|
|
|
|
import os
|
2025-09-18 20:34:10 +08:00
|
|
|
|
import traceback
|
2025-09-01 22:37:03 +08:00
|
|
|
|
|
|
|
|
|
|
from openai import OpenAI
|
2025-09-19 01:10:20 +08:00
|
|
|
|
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type, before_sleep_log, after_log
|
2025-09-01 22:37:03 +08:00
|
|
|
|
|
2025-09-18 20:34:10 +08:00
|
|
|
|
from src import config
|
2025-09-01 22:37:03 +08:00
|
|
|
|
from src.utils import get_docker_safe_url, logger
|
|
|
|
|
|
|
2024-07-07 01:58:23 +08:00
|
|
|
|
|
2025-05-24 11:29:45 +08:00
|
|
|
|
class OpenAIBase:
|
2025-07-02 02:38:36 +08:00
|
|
|
|
def __init__(self, api_key, base_url, model_name, **kwargs):
|
2025-03-10 16:33:40 +08:00
|
|
|
|
self.api_key = api_key
|
|
|
|
|
|
self.base_url = base_url
|
2024-07-07 01:58:23 +08:00
|
|
|
|
self.client = OpenAI(api_key=api_key, base_url=base_url)
|
|
|
|
|
|
self.model_name = model_name
|
2025-04-09 11:47:08 +08:00
|
|
|
|
self.info = kwargs
|
2024-07-07 01:58:23 +08:00
|
|
|
|
|
2025-09-19 01:10:20 +08:00
|
|
|
|
@retry(
|
|
|
|
|
|
stop=stop_after_attempt(3),
|
|
|
|
|
|
wait=wait_exponential(multiplier=1, min=1, max=10),
|
|
|
|
|
|
retry=retry_if_exception_type((Exception,)),
|
|
|
|
|
|
before_sleep=before_sleep_log(logger, log_level="WARNING"),
|
|
|
|
|
|
reraise=True
|
|
|
|
|
|
)
|
2025-09-19 00:57:53 +08:00
|
|
|
|
def call(self, message, stream=False):
|
2024-07-07 01:58:23 +08:00
|
|
|
|
if isinstance(message, str):
|
2025-09-01 22:37:03 +08:00
|
|
|
|
messages = [{"role": "user", "content": message}]
|
2024-07-07 01:58:23 +08:00
|
|
|
|
else:
|
|
|
|
|
|
messages = message
|
|
|
|
|
|
|
2025-05-09 14:48:32 +08:00
|
|
|
|
try:
|
2025-09-19 01:10:20 +08:00
|
|
|
|
if stream:
|
|
|
|
|
|
response = self._stream_response(messages)
|
|
|
|
|
|
else:
|
|
|
|
|
|
response = self._get_response(messages)
|
2025-05-09 14:48:32 +08:00
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
2025-09-02 01:08:42 +08:00
|
|
|
|
err = (
|
|
|
|
|
|
f"Error streaming response: {e}, URL: {self.base_url}, "
|
|
|
|
|
|
f"API Key: {self.api_key[:5]}***, Model: {self.model_name}"
|
|
|
|
|
|
)
|
2025-05-09 14:48:32 +08:00
|
|
|
|
logger.error(err)
|
|
|
|
|
|
raise Exception(err)
|
2024-07-07 01:58:23 +08:00
|
|
|
|
|
2025-09-19 01:10:20 +08:00
|
|
|
|
return response
|
|
|
|
|
|
|
|
|
|
|
|
def _stream_response(self, messages):
|
|
|
|
|
|
response = self.client.chat.completions.create(
|
|
|
|
|
|
model=self.model_name,
|
|
|
|
|
|
messages=messages,
|
|
|
|
|
|
stream=True,
|
|
|
|
|
|
)
|
|
|
|
|
|
for chunk in response:
|
|
|
|
|
|
if len(chunk.choices) > 0:
|
|
|
|
|
|
yield chunk.choices[0].delta
|
|
|
|
|
|
|
|
|
|
|
|
|
2024-07-07 01:58:23 +08:00
|
|
|
|
def _get_response(self, messages):
|
|
|
|
|
|
response = self.client.chat.completions.create(
|
|
|
|
|
|
model=self.model_name,
|
|
|
|
|
|
messages=messages,
|
|
|
|
|
|
stream=False,
|
|
|
|
|
|
)
|
|
|
|
|
|
return response.choices[0].message
|
2025-03-24 19:07:51 +08:00
|
|
|
|
|
2025-03-10 16:33:40 +08:00
|
|
|
|
def get_models(self):
|
|
|
|
|
|
try:
|
2025-09-01 22:37:03 +08:00
|
|
|
|
return self.client.models.list(extra_query={"type": "text"})
|
2025-03-10 16:33:40 +08:00
|
|
|
|
except Exception as e:
|
|
|
|
|
|
logger.error(f"Error getting models: {e}")
|
|
|
|
|
|
return []
|
2024-07-07 01:58:23 +08:00
|
|
|
|
|
|
|
|
|
|
|
2024-09-09 17:07:03 +08:00
|
|
|
|
class OpenModel(OpenAIBase):
|
|
|
|
|
|
def __init__(self, model_name=None):
|
|
|
|
|
|
model_name = model_name or "gpt-4o-mini"
|
|
|
|
|
|
api_key = os.getenv("OPENAI_API_KEY")
|
|
|
|
|
|
base_url = os.getenv("OPENAI_API_BASE")
|
|
|
|
|
|
super().__init__(api_key=api_key, base_url=base_url, model_name=model_name)
|
|
|
|
|
|
|
|
|
|
|
|
|
2024-10-08 22:16:17 +08:00
|
|
|
|
class CustomModel(OpenAIBase):
|
|
|
|
|
|
def __init__(self, model_info):
|
|
|
|
|
|
model_name = model_info["name"]
|
2025-03-29 19:19:43 +08:00
|
|
|
|
api_key = model_info.get("api_key") or "custom_model"
|
2025-02-28 14:39:03 +08:00
|
|
|
|
base_url = get_docker_safe_url(model_info["api_base"])
|
2025-03-11 14:18:48 +08:00
|
|
|
|
logger.info(f"> Custom model: {model_name}, base_url: {base_url}")
|
2025-02-28 14:39:03 +08:00
|
|
|
|
|
2024-10-08 22:16:17 +08:00
|
|
|
|
super().__init__(api_key=api_key, base_url=base_url, model_name=model_name)
|
|
|
|
|
|
|
2024-07-07 17:21:07 +08:00
|
|
|
|
|
2024-07-31 20:22:05 +08:00
|
|
|
|
class GeneralResponse:
|
2024-07-07 17:21:07 +08:00
|
|
|
|
def __init__(self, content):
|
|
|
|
|
|
self.content = content
|
2024-07-31 20:22:05 +08:00
|
|
|
|
self.is_full = False
|
2024-07-07 17:21:07 +08:00
|
|
|
|
|
2025-09-01 22:37:03 +08:00
|
|
|
|
|
2025-09-18 20:34:10 +08:00
|
|
|
|
def select_model(model_provider, model_name=None):
|
|
|
|
|
|
"""根据模型提供者选择模型"""
|
|
|
|
|
|
assert model_provider is not None, "Model provider not specified"
|
|
|
|
|
|
model_info = config.model_names.get(model_provider, {})
|
|
|
|
|
|
model_name = model_name or model_info.get("default", "")
|
|
|
|
|
|
|
|
|
|
|
|
logger.info(f"Selecting model from `{model_provider}` with `{model_name}`")
|
|
|
|
|
|
|
|
|
|
|
|
if model_provider == "openai":
|
|
|
|
|
|
return OpenModel(model_name)
|
|
|
|
|
|
|
|
|
|
|
|
if model_provider == "custom":
|
|
|
|
|
|
model_info = get_custom_model(model_name)
|
|
|
|
|
|
return CustomModel(model_info)
|
|
|
|
|
|
|
|
|
|
|
|
# 其他模型,默认使用OpenAIBase
|
|
|
|
|
|
try:
|
|
|
|
|
|
model = OpenAIBase(
|
|
|
|
|
|
api_key=os.getenv(model_info["env"][0]),
|
|
|
|
|
|
base_url=model_info["base_url"],
|
|
|
|
|
|
model_name=model_name,
|
|
|
|
|
|
)
|
|
|
|
|
|
return model
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
|
raise ValueError(f"Model provider {model_provider} load failed, {e} \n {traceback.format_exc()}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def get_custom_model(model_id):
|
|
|
|
|
|
"""return model_info"""
|
|
|
|
|
|
assert config.custom_models is not None, "custom_models is not set"
|
|
|
|
|
|
modle_info = next((x for x in config.custom_models if x["custom_id"] == model_id), None)
|
|
|
|
|
|
if modle_info is None:
|
|
|
|
|
|
raise ValueError(f"Model {model_id} not found in custom models")
|
|
|
|
|
|
return modle_info
|
|
|
|
|
|
|
|
|
|
|
|
|
2024-07-31 20:22:05 +08:00
|
|
|
|
if __name__ == "__main__":
|
2025-05-24 11:29:45 +08:00
|
|
|
|
pass
|