model_manager.py 21 KB

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