model_manager.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import logging
  2. import os
  3. from collections.abc import Callable, Generator
  4. from typing import IO, Optional, Union, cast
  5. from core.entities.provider_configuration import ProviderConfiguration, ProviderModelBundle
  6. from core.entities.provider_entities import ModelLoadBalancingConfiguration
  7. from core.errors.error import ProviderTokenNotInitError
  8. from core.model_runtime.callbacks.base_callback import Callback
  9. from core.model_runtime.entities.llm_entities import LLMResult
  10. from core.model_runtime.entities.message_entities import PromptMessage, PromptMessageTool
  11. from core.model_runtime.entities.model_entities import ModelType
  12. from core.model_runtime.entities.rerank_entities import RerankResult
  13. from core.model_runtime.entities.text_embedding_entities import TextEmbeddingResult
  14. from core.model_runtime.errors.invoke import InvokeAuthorizationError, InvokeConnectionError, InvokeRateLimitError
  15. from core.model_runtime.model_providers.__base.large_language_model import LargeLanguageModel
  16. from core.model_runtime.model_providers.__base.moderation_model import ModerationModel
  17. from core.model_runtime.model_providers.__base.rerank_model import RerankModel
  18. from core.model_runtime.model_providers.__base.speech2text_model import Speech2TextModel
  19. from core.model_runtime.model_providers.__base.text_embedding_model import TextEmbeddingModel
  20. from core.model_runtime.model_providers.__base.tts_model import TTSModel
  21. from core.provider_manager import ProviderManager
  22. from extensions.ext_redis import redis_client
  23. from models.provider import ProviderType
  24. logger = logging.getLogger(__name__)
  25. class ModelInstance:
  26. """
  27. Model instance class
  28. """
  29. def __init__(self, provider_model_bundle: ProviderModelBundle, model: str) -> None:
  30. self.provider_model_bundle = provider_model_bundle
  31. self.model = model
  32. self.provider = provider_model_bundle.configuration.provider.provider
  33. self.credentials = self._fetch_credentials_from_bundle(provider_model_bundle, model)
  34. self.model_type_instance = self.provider_model_bundle.model_type_instance
  35. self.load_balancing_manager = self._get_load_balancing_manager(
  36. configuration=provider_model_bundle.configuration,
  37. model_type=provider_model_bundle.model_type_instance.model_type,
  38. model=model,
  39. credentials=self.credentials
  40. )
  41. @staticmethod
  42. def _fetch_credentials_from_bundle(provider_model_bundle: ProviderModelBundle, model: str) -> dict:
  43. """
  44. Fetch credentials from provider model bundle
  45. :param provider_model_bundle: provider model bundle
  46. :param model: model name
  47. :return:
  48. """
  49. configuration = provider_model_bundle.configuration
  50. model_type = provider_model_bundle.model_type_instance.model_type
  51. credentials = configuration.get_current_credentials(
  52. model_type=model_type,
  53. model=model
  54. )
  55. if credentials is None:
  56. raise ProviderTokenNotInitError(f"Model {model} credentials is not initialized.")
  57. return credentials
  58. @staticmethod
  59. def _get_load_balancing_manager(configuration: ProviderConfiguration,
  60. model_type: ModelType,
  61. model: str,
  62. credentials: dict) -> Optional["LBModelManager"]:
  63. """
  64. Get load balancing model credentials
  65. :param configuration: provider configuration
  66. :param model_type: model type
  67. :param model: model name
  68. :param credentials: model credentials
  69. :return:
  70. """
  71. if configuration.model_settings and configuration.using_provider_type == ProviderType.CUSTOM:
  72. current_model_setting = None
  73. # check if model is disabled by admin
  74. for model_setting in configuration.model_settings:
  75. if (model_setting.model_type == model_type
  76. and model_setting.model == model):
  77. current_model_setting = model_setting
  78. break
  79. # check if load balancing is enabled
  80. if current_model_setting and current_model_setting.load_balancing_configs:
  81. # use load balancing proxy to choose credentials
  82. lb_model_manager = LBModelManager(
  83. tenant_id=configuration.tenant_id,
  84. provider=configuration.provider.provider,
  85. model_type=model_type,
  86. model=model,
  87. load_balancing_configs=current_model_setting.load_balancing_configs,
  88. managed_credentials=credentials if configuration.custom_configuration.provider else None
  89. )
  90. return lb_model_manager
  91. return None
  92. def invoke_llm(self, prompt_messages: list[PromptMessage], model_parameters: Optional[dict] = None,
  93. tools: Optional[list[PromptMessageTool]] = None, stop: Optional[list[str]] = None,
  94. stream: bool = True, user: Optional[str] = None, callbacks: Optional[list[Callback]] = None) \
  95. -> Union[LLMResult, Generator]:
  96. """
  97. Invoke large language model
  98. :param prompt_messages: prompt messages
  99. :param model_parameters: model parameters
  100. :param tools: tools for tool calling
  101. :param stop: stop words
  102. :param stream: is stream response
  103. :param user: unique user id
  104. :param callbacks: callbacks
  105. :return: full response or stream response chunk generator result
  106. """
  107. if not isinstance(self.model_type_instance, LargeLanguageModel):
  108. raise Exception("Model type instance is not LargeLanguageModel")
  109. self.model_type_instance = cast(LargeLanguageModel, self.model_type_instance)
  110. return self._round_robin_invoke(
  111. function=self.model_type_instance.invoke,
  112. model=self.model,
  113. credentials=self.credentials,
  114. prompt_messages=prompt_messages,
  115. model_parameters=model_parameters,
  116. tools=tools,
  117. stop=stop,
  118. stream=stream,
  119. user=user,
  120. callbacks=callbacks
  121. )
  122. def get_llm_num_tokens(self, prompt_messages: list[PromptMessage],
  123. tools: Optional[list[PromptMessageTool]] = None) -> int:
  124. """
  125. Get number of tokens for llm
  126. :param prompt_messages: prompt messages
  127. :param tools: tools for tool calling
  128. :return:
  129. """
  130. if not isinstance(self.model_type_instance, LargeLanguageModel):
  131. raise Exception("Model type instance is not LargeLanguageModel")
  132. self.model_type_instance = cast(LargeLanguageModel, self.model_type_instance)
  133. return self._round_robin_invoke(
  134. function=self.model_type_instance.get_num_tokens,
  135. model=self.model,
  136. credentials=self.credentials,
  137. prompt_messages=prompt_messages,
  138. tools=tools
  139. )
  140. def invoke_text_embedding(self, texts: list[str], user: Optional[str] = None) \
  141. -> TextEmbeddingResult:
  142. """
  143. Invoke large language model
  144. :param texts: texts to embed
  145. :param user: unique user id
  146. :return: embeddings result
  147. """
  148. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  149. raise Exception("Model type instance is not TextEmbeddingModel")
  150. self.model_type_instance = cast(TextEmbeddingModel, self.model_type_instance)
  151. return self._round_robin_invoke(
  152. function=self.model_type_instance.invoke,
  153. model=self.model,
  154. credentials=self.credentials,
  155. texts=texts,
  156. user=user
  157. )
  158. def get_text_embedding_num_tokens(self, texts: list[str]) -> int:
  159. """
  160. Get number of tokens for text embedding
  161. :param texts: texts to embed
  162. :return:
  163. """
  164. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  165. raise Exception("Model type instance is not TextEmbeddingModel")
  166. self.model_type_instance = cast(TextEmbeddingModel, self.model_type_instance)
  167. return self._round_robin_invoke(
  168. function=self.model_type_instance.get_num_tokens,
  169. model=self.model,
  170. credentials=self.credentials,
  171. texts=texts
  172. )
  173. def invoke_rerank(self, query: str, docs: list[str], score_threshold: Optional[float] = None,
  174. top_n: Optional[int] = None,
  175. user: Optional[str] = None) \
  176. -> RerankResult:
  177. """
  178. Invoke rerank model
  179. :param query: search query
  180. :param docs: docs for reranking
  181. :param score_threshold: score threshold
  182. :param top_n: top n
  183. :param user: unique user id
  184. :return: rerank result
  185. """
  186. if not isinstance(self.model_type_instance, RerankModel):
  187. raise Exception("Model type instance is not RerankModel")
  188. self.model_type_instance = cast(RerankModel, self.model_type_instance)
  189. return self._round_robin_invoke(
  190. function=self.model_type_instance.invoke,
  191. model=self.model,
  192. credentials=self.credentials,
  193. query=query,
  194. docs=docs,
  195. score_threshold=score_threshold,
  196. top_n=top_n,
  197. user=user
  198. )
  199. def invoke_moderation(self, text: str, user: Optional[str] = None) \
  200. -> bool:
  201. """
  202. Invoke moderation model
  203. :param text: text to moderate
  204. :param user: unique user id
  205. :return: false if text is safe, true otherwise
  206. """
  207. if not isinstance(self.model_type_instance, ModerationModel):
  208. raise Exception("Model type instance is not ModerationModel")
  209. self.model_type_instance = cast(ModerationModel, self.model_type_instance)
  210. return self._round_robin_invoke(
  211. function=self.model_type_instance.invoke,
  212. model=self.model,
  213. credentials=self.credentials,
  214. text=text,
  215. user=user
  216. )
  217. def invoke_speech2text(self, file: IO[bytes], user: Optional[str] = None) \
  218. -> str:
  219. """
  220. Invoke large language model
  221. :param file: audio file
  222. :param user: unique user id
  223. :return: text for given audio file
  224. """
  225. if not isinstance(self.model_type_instance, Speech2TextModel):
  226. raise Exception("Model type instance is not Speech2TextModel")
  227. self.model_type_instance = cast(Speech2TextModel, self.model_type_instance)
  228. return self._round_robin_invoke(
  229. function=self.model_type_instance.invoke,
  230. model=self.model,
  231. credentials=self.credentials,
  232. file=file,
  233. user=user
  234. )
  235. def invoke_tts(self, content_text: str, tenant_id: str, voice: str, user: Optional[str] = None) \
  236. -> str:
  237. """
  238. Invoke large language tts model
  239. :param content_text: text content to be translated
  240. :param tenant_id: user tenant id
  241. :param voice: model timbre
  242. :param user: unique user id
  243. :return: text for given audio file
  244. """
  245. if not isinstance(self.model_type_instance, TTSModel):
  246. raise Exception("Model type instance is not TTSModel")
  247. self.model_type_instance = cast(TTSModel, self.model_type_instance)
  248. return self._round_robin_invoke(
  249. function=self.model_type_instance.invoke,
  250. model=self.model,
  251. credentials=self.credentials,
  252. content_text=content_text,
  253. user=user,
  254. tenant_id=tenant_id,
  255. voice=voice
  256. )
  257. def _round_robin_invoke(self, function: Callable, *args, **kwargs):
  258. """
  259. Round-robin invoke
  260. :param function: function to invoke
  261. :param args: function args
  262. :param kwargs: function kwargs
  263. :return:
  264. """
  265. if not self.load_balancing_manager:
  266. return function(*args, **kwargs)
  267. last_exception = None
  268. while True:
  269. lb_config = self.load_balancing_manager.fetch_next()
  270. if not lb_config:
  271. if not last_exception:
  272. raise ProviderTokenNotInitError("Model credentials is not initialized.")
  273. else:
  274. raise last_exception
  275. try:
  276. if 'credentials' in kwargs:
  277. del kwargs['credentials']
  278. return function(*args, **kwargs, credentials=lb_config.credentials)
  279. except InvokeRateLimitError as e:
  280. # expire in 60 seconds
  281. self.load_balancing_manager.cooldown(lb_config, expire=60)
  282. last_exception = e
  283. continue
  284. except (InvokeAuthorizationError, InvokeConnectionError) as e:
  285. # expire in 10 seconds
  286. self.load_balancing_manager.cooldown(lb_config, expire=10)
  287. last_exception = e
  288. continue
  289. except Exception as e:
  290. raise e
  291. def get_tts_voices(self, language: Optional[str] = None) -> list:
  292. """
  293. Invoke large language tts model voices
  294. :param language: tts language
  295. :return: tts model voices
  296. """
  297. if not isinstance(self.model_type_instance, TTSModel):
  298. raise Exception("Model type instance is not TTSModel")
  299. self.model_type_instance = cast(TTSModel, self.model_type_instance)
  300. return self.model_type_instance.get_tts_model_voices(
  301. model=self.model,
  302. credentials=self.credentials,
  303. language=language
  304. )
  305. class ModelManager:
  306. def __init__(self) -> None:
  307. self._provider_manager = ProviderManager()
  308. def get_model_instance(self, tenant_id: str, provider: str, model_type: ModelType, model: str) -> ModelInstance:
  309. """
  310. Get model instance
  311. :param tenant_id: tenant id
  312. :param provider: provider name
  313. :param model_type: model type
  314. :param model: model name
  315. :return:
  316. """
  317. if not provider:
  318. return self.get_default_model_instance(tenant_id, model_type)
  319. provider_model_bundle = self._provider_manager.get_provider_model_bundle(
  320. tenant_id=tenant_id,
  321. provider=provider,
  322. model_type=model_type
  323. )
  324. return ModelInstance(provider_model_bundle, model)
  325. def get_default_provider_model_name(self, tenant_id: str, model_type: ModelType) -> tuple[str, str]:
  326. """
  327. Return first provider and the first model in the provider
  328. :param tenant_id: tenant id
  329. :param model_type: model type
  330. :return: provider name, model name
  331. """
  332. return self._provider_manager.get_first_provider_first_model(tenant_id, model_type)
  333. def get_default_model_instance(self, tenant_id: str, model_type: ModelType) -> ModelInstance:
  334. """
  335. Get default model instance
  336. :param tenant_id: tenant id
  337. :param model_type: model type
  338. :return:
  339. """
  340. default_model_entity = self._provider_manager.get_default_model(
  341. tenant_id=tenant_id,
  342. model_type=model_type
  343. )
  344. if not default_model_entity:
  345. raise ProviderTokenNotInitError(f"Default model not found for {model_type}")
  346. return self.get_model_instance(
  347. tenant_id=tenant_id,
  348. provider=default_model_entity.provider.provider,
  349. model_type=model_type,
  350. model=default_model_entity.model
  351. )
  352. class LBModelManager:
  353. def __init__(self, tenant_id: str,
  354. provider: str,
  355. model_type: ModelType,
  356. model: str,
  357. load_balancing_configs: list[ModelLoadBalancingConfiguration],
  358. managed_credentials: Optional[dict] = None) -> None:
  359. """
  360. Load balancing model manager
  361. :param tenant_id: tenant_id
  362. :param provider: provider
  363. :param model_type: model_type
  364. :param model: model name
  365. :param load_balancing_configs: all load balancing configurations
  366. :param managed_credentials: credentials if load balancing configuration name is __inherit__
  367. """
  368. self._tenant_id = tenant_id
  369. self._provider = provider
  370. self._model_type = model_type
  371. self._model = model
  372. self._load_balancing_configs = load_balancing_configs
  373. for load_balancing_config in self._load_balancing_configs[:]: # Iterate over a shallow copy of the list
  374. if load_balancing_config.name == "__inherit__":
  375. if not managed_credentials:
  376. # remove __inherit__ if managed credentials is not provided
  377. self._load_balancing_configs.remove(load_balancing_config)
  378. else:
  379. load_balancing_config.credentials = managed_credentials
  380. def fetch_next(self) -> Optional[ModelLoadBalancingConfiguration]:
  381. """
  382. Get next model load balancing config
  383. Strategy: Round Robin
  384. :return:
  385. """
  386. cache_key = "model_lb_index:{}:{}:{}:{}".format(
  387. self._tenant_id,
  388. self._provider,
  389. self._model_type.value,
  390. self._model
  391. )
  392. cooldown_load_balancing_configs = []
  393. max_index = len(self._load_balancing_configs)
  394. while True:
  395. current_index = redis_client.incr(cache_key)
  396. current_index = cast(int, current_index)
  397. if current_index >= 10000000:
  398. current_index = 1
  399. redis_client.set(cache_key, current_index)
  400. redis_client.expire(cache_key, 3600)
  401. if current_index > max_index:
  402. current_index = current_index % max_index
  403. real_index = current_index - 1
  404. if real_index > max_index:
  405. real_index = 0
  406. config = self._load_balancing_configs[real_index]
  407. if self.in_cooldown(config):
  408. cooldown_load_balancing_configs.append(config)
  409. if len(cooldown_load_balancing_configs) >= len(self._load_balancing_configs):
  410. # all configs are in cooldown
  411. return None
  412. continue
  413. if bool(os.environ.get("DEBUG", 'False').lower() == 'true'):
  414. logger.info(f"Model LB\nid: {config.id}\nname:{config.name}\n"
  415. f"tenant_id: {self._tenant_id}\nprovider: {self._provider}\n"
  416. f"model_type: {self._model_type.value}\nmodel: {self._model}")
  417. return config
  418. return None
  419. def cooldown(self, config: ModelLoadBalancingConfiguration, expire: int = 60) -> None:
  420. """
  421. Cooldown model load balancing config
  422. :param config: model load balancing config
  423. :param expire: cooldown time
  424. :return:
  425. """
  426. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  427. self._tenant_id,
  428. self._provider,
  429. self._model_type.value,
  430. self._model,
  431. config.id
  432. )
  433. redis_client.setex(cooldown_cache_key, expire, 'true')
  434. def in_cooldown(self, config: ModelLoadBalancingConfiguration) -> bool:
  435. """
  436. Check if model load balancing config is in cooldown
  437. :param config: model load balancing config
  438. :return:
  439. """
  440. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  441. self._tenant_id,
  442. self._provider,
  443. self._model_type.value,
  444. self._model,
  445. config.id
  446. )
  447. res = redis_client.exists(cooldown_cache_key)
  448. res = cast(bool, res)
  449. return res
  450. @staticmethod
  451. def get_config_in_cooldown_and_ttl(tenant_id: str,
  452. provider: str,
  453. model_type: ModelType,
  454. model: str,
  455. config_id: str) -> tuple[bool, int]:
  456. """
  457. Get model load balancing config is in cooldown and ttl
  458. :param tenant_id: workspace id
  459. :param provider: provider name
  460. :param model_type: model type
  461. :param model: model name
  462. :param config_id: model load balancing config id
  463. :return:
  464. """
  465. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  466. tenant_id,
  467. provider,
  468. model_type.value,
  469. model,
  470. config_id
  471. )
  472. ttl = redis_client.ttl(cooldown_cache_key)
  473. if ttl == -2:
  474. return False, 0
  475. ttl = cast(int, ttl)
  476. return True, ttl