Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

model_manager.py 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585
  1. import logging
  2. from collections.abc import Callable, Generator, Iterable, Sequence
  3. from typing import IO, Any, Literal, Optional, Union, cast, overload
  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):
  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):
  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. @overload
  89. def invoke_llm(
  90. self,
  91. prompt_messages: Sequence[PromptMessage],
  92. model_parameters: Optional[dict] = None,
  93. tools: Sequence[PromptMessageTool] | None = None,
  94. stop: Optional[list[str]] = None,
  95. stream: Literal[True] = True,
  96. user: Optional[str] = None,
  97. callbacks: Optional[list[Callback]] = None,
  98. ) -> Generator: ...
  99. @overload
  100. def invoke_llm(
  101. self,
  102. prompt_messages: list[PromptMessage],
  103. model_parameters: Optional[dict] = None,
  104. tools: Sequence[PromptMessageTool] | None = None,
  105. stop: Optional[list[str]] = None,
  106. stream: Literal[False] = False,
  107. user: Optional[str] = None,
  108. callbacks: Optional[list[Callback]] = None,
  109. ) -> LLMResult: ...
  110. @overload
  111. def invoke_llm(
  112. self,
  113. prompt_messages: list[PromptMessage],
  114. model_parameters: Optional[dict] = None,
  115. tools: Sequence[PromptMessageTool] | None = None,
  116. stop: Optional[list[str]] = None,
  117. stream: bool = True,
  118. user: Optional[str] = None,
  119. callbacks: Optional[list[Callback]] = None,
  120. ) -> Union[LLMResult, Generator]: ...
  121. def invoke_llm(
  122. self,
  123. prompt_messages: Sequence[PromptMessage],
  124. model_parameters: Optional[dict] = None,
  125. tools: Sequence[PromptMessageTool] | None = None,
  126. stop: Optional[Sequence[str]] = None,
  127. stream: bool = True,
  128. user: Optional[str] = None,
  129. callbacks: Optional[list[Callback]] = None,
  130. ) -> Union[LLMResult, Generator]:
  131. """
  132. Invoke large language model
  133. :param prompt_messages: prompt messages
  134. :param model_parameters: model parameters
  135. :param tools: tools for tool calling
  136. :param stop: stop words
  137. :param stream: is stream response
  138. :param user: unique user id
  139. :param callbacks: callbacks
  140. :return: full response or stream response chunk generator result
  141. """
  142. if not isinstance(self.model_type_instance, LargeLanguageModel):
  143. raise Exception("Model type instance is not LargeLanguageModel")
  144. return cast(
  145. Union[LLMResult, Generator],
  146. self._round_robin_invoke(
  147. function=self.model_type_instance.invoke,
  148. model=self.model,
  149. credentials=self.credentials,
  150. prompt_messages=prompt_messages,
  151. model_parameters=model_parameters,
  152. tools=tools,
  153. stop=stop,
  154. stream=stream,
  155. user=user,
  156. callbacks=callbacks,
  157. ),
  158. )
  159. def get_llm_num_tokens(
  160. self, prompt_messages: Sequence[PromptMessage], tools: Optional[Sequence[PromptMessageTool]] = None
  161. ) -> int:
  162. """
  163. Get number of tokens for llm
  164. :param prompt_messages: prompt messages
  165. :param tools: tools for tool calling
  166. :return:
  167. """
  168. if not isinstance(self.model_type_instance, LargeLanguageModel):
  169. raise Exception("Model type instance is not LargeLanguageModel")
  170. return cast(
  171. int,
  172. self._round_robin_invoke(
  173. function=self.model_type_instance.get_num_tokens,
  174. model=self.model,
  175. credentials=self.credentials,
  176. prompt_messages=prompt_messages,
  177. tools=tools,
  178. ),
  179. )
  180. def invoke_text_embedding(
  181. self, texts: list[str], user: Optional[str] = None, input_type: EmbeddingInputType = EmbeddingInputType.DOCUMENT
  182. ) -> TextEmbeddingResult:
  183. """
  184. Invoke large language model
  185. :param texts: texts to embed
  186. :param user: unique user id
  187. :param input_type: input type
  188. :return: embeddings result
  189. """
  190. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  191. raise Exception("Model type instance is not TextEmbeddingModel")
  192. return cast(
  193. TextEmbeddingResult,
  194. self._round_robin_invoke(
  195. function=self.model_type_instance.invoke,
  196. model=self.model,
  197. credentials=self.credentials,
  198. texts=texts,
  199. user=user,
  200. input_type=input_type,
  201. ),
  202. )
  203. def get_text_embedding_num_tokens(self, texts: list[str]) -> list[int]:
  204. """
  205. Get number of tokens for text embedding
  206. :param texts: texts to embed
  207. :return:
  208. """
  209. if not isinstance(self.model_type_instance, TextEmbeddingModel):
  210. raise Exception("Model type instance is not TextEmbeddingModel")
  211. return cast(
  212. list[int],
  213. self._round_robin_invoke(
  214. function=self.model_type_instance.get_num_tokens,
  215. model=self.model,
  216. credentials=self.credentials,
  217. texts=texts,
  218. ),
  219. )
  220. def invoke_rerank(
  221. self,
  222. query: str,
  223. docs: list[str],
  224. score_threshold: Optional[float] = None,
  225. top_n: Optional[int] = None,
  226. user: Optional[str] = None,
  227. ) -> RerankResult:
  228. """
  229. Invoke rerank model
  230. :param query: search query
  231. :param docs: docs for reranking
  232. :param score_threshold: score threshold
  233. :param top_n: top n
  234. :param user: unique user id
  235. :return: rerank result
  236. """
  237. if not isinstance(self.model_type_instance, RerankModel):
  238. raise Exception("Model type instance is not RerankModel")
  239. return cast(
  240. RerankResult,
  241. self._round_robin_invoke(
  242. function=self.model_type_instance.invoke,
  243. model=self.model,
  244. credentials=self.credentials,
  245. query=query,
  246. docs=docs,
  247. score_threshold=score_threshold,
  248. top_n=top_n,
  249. user=user,
  250. ),
  251. )
  252. def invoke_moderation(self, text: str, user: Optional[str] = None) -> bool:
  253. """
  254. Invoke moderation model
  255. :param text: text to moderate
  256. :param user: unique user id
  257. :return: false if text is safe, true otherwise
  258. """
  259. if not isinstance(self.model_type_instance, ModerationModel):
  260. raise Exception("Model type instance is not ModerationModel")
  261. return cast(
  262. bool,
  263. self._round_robin_invoke(
  264. function=self.model_type_instance.invoke,
  265. model=self.model,
  266. credentials=self.credentials,
  267. text=text,
  268. user=user,
  269. ),
  270. )
  271. def invoke_speech2text(self, file: IO[bytes], user: Optional[str] = None) -> str:
  272. """
  273. Invoke large language model
  274. :param file: audio file
  275. :param user: unique user id
  276. :return: text for given audio file
  277. """
  278. if not isinstance(self.model_type_instance, Speech2TextModel):
  279. raise Exception("Model type instance is not Speech2TextModel")
  280. return cast(
  281. str,
  282. self._round_robin_invoke(
  283. function=self.model_type_instance.invoke,
  284. model=self.model,
  285. credentials=self.credentials,
  286. file=file,
  287. user=user,
  288. ),
  289. )
  290. def invoke_tts(self, content_text: str, tenant_id: str, voice: str, user: Optional[str] = None) -> Iterable[bytes]:
  291. """
  292. Invoke large language tts model
  293. :param content_text: text content to be translated
  294. :param tenant_id: user tenant id
  295. :param voice: model timbre
  296. :param user: unique user id
  297. :return: text for given audio file
  298. """
  299. if not isinstance(self.model_type_instance, TTSModel):
  300. raise Exception("Model type instance is not TTSModel")
  301. return cast(
  302. Iterable[bytes],
  303. self._round_robin_invoke(
  304. function=self.model_type_instance.invoke,
  305. model=self.model,
  306. credentials=self.credentials,
  307. content_text=content_text,
  308. user=user,
  309. tenant_id=tenant_id,
  310. voice=voice,
  311. ),
  312. )
  313. def _round_robin_invoke(self, function: Callable[..., Any], *args, **kwargs):
  314. """
  315. Round-robin invoke
  316. :param function: function to invoke
  317. :param args: function args
  318. :param kwargs: function kwargs
  319. :return:
  320. """
  321. if not self.load_balancing_manager:
  322. return function(*args, **kwargs)
  323. last_exception: Union[InvokeRateLimitError, InvokeAuthorizationError, InvokeConnectionError, None] = None
  324. while True:
  325. lb_config = self.load_balancing_manager.fetch_next()
  326. if not lb_config:
  327. if not last_exception:
  328. raise ProviderTokenNotInitError("Model credentials is not initialized.")
  329. else:
  330. raise last_exception
  331. try:
  332. if "credentials" in kwargs:
  333. del kwargs["credentials"]
  334. return function(*args, **kwargs, credentials=lb_config.credentials)
  335. except InvokeRateLimitError as e:
  336. # expire in 60 seconds
  337. self.load_balancing_manager.cooldown(lb_config, expire=60)
  338. last_exception = e
  339. continue
  340. except (InvokeAuthorizationError, InvokeConnectionError) as e:
  341. # expire in 10 seconds
  342. self.load_balancing_manager.cooldown(lb_config, expire=10)
  343. last_exception = e
  344. continue
  345. except Exception as e:
  346. raise e
  347. def get_tts_voices(self, language: Optional[str] = None):
  348. """
  349. Invoke large language tts model voices
  350. :param language: tts language
  351. :return: tts model voices
  352. """
  353. if not isinstance(self.model_type_instance, TTSModel):
  354. raise Exception("Model type instance is not TTSModel")
  355. return self.model_type_instance.get_tts_model_voices(
  356. model=self.model, credentials=self.credentials, language=language
  357. )
  358. class ModelManager:
  359. def __init__(self):
  360. self._provider_manager = ProviderManager()
  361. def get_model_instance(self, tenant_id: str, provider: str, model_type: ModelType, model: str) -> ModelInstance:
  362. """
  363. Get model instance
  364. :param tenant_id: tenant id
  365. :param provider: provider name
  366. :param model_type: model type
  367. :param model: model name
  368. :return:
  369. """
  370. if not provider:
  371. return self.get_default_model_instance(tenant_id, model_type)
  372. provider_model_bundle = self._provider_manager.get_provider_model_bundle(
  373. tenant_id=tenant_id, provider=provider, model_type=model_type
  374. )
  375. return ModelInstance(provider_model_bundle, model)
  376. def get_default_provider_model_name(self, tenant_id: str, model_type: ModelType) -> tuple[str | None, str | None]:
  377. """
  378. Return first provider and the first model in the provider
  379. :param tenant_id: tenant id
  380. :param model_type: model type
  381. :return: provider name, model name
  382. """
  383. return self._provider_manager.get_first_provider_first_model(tenant_id, model_type)
  384. def get_default_model_instance(self, tenant_id: str, model_type: ModelType) -> ModelInstance:
  385. """
  386. Get default model instance
  387. :param tenant_id: tenant id
  388. :param model_type: model type
  389. :return:
  390. """
  391. default_model_entity = self._provider_manager.get_default_model(tenant_id=tenant_id, model_type=model_type)
  392. if not default_model_entity:
  393. raise ProviderTokenNotInitError(f"Default model not found for {model_type}")
  394. return self.get_model_instance(
  395. tenant_id=tenant_id,
  396. provider=default_model_entity.provider.provider,
  397. model_type=model_type,
  398. model=default_model_entity.model,
  399. )
  400. class LBModelManager:
  401. def __init__(
  402. self,
  403. tenant_id: str,
  404. provider: str,
  405. model_type: ModelType,
  406. model: str,
  407. load_balancing_configs: list[ModelLoadBalancingConfiguration],
  408. managed_credentials: Optional[dict] = None,
  409. ):
  410. """
  411. Load balancing model manager
  412. :param tenant_id: tenant_id
  413. :param provider: provider
  414. :param model_type: model_type
  415. :param model: model name
  416. :param load_balancing_configs: all load balancing configurations
  417. :param managed_credentials: credentials if load balancing configuration name is __inherit__
  418. """
  419. self._tenant_id = tenant_id
  420. self._provider = provider
  421. self._model_type = model_type
  422. self._model = model
  423. self._load_balancing_configs = load_balancing_configs
  424. for load_balancing_config in self._load_balancing_configs[:]: # Iterate over a shallow copy of the list
  425. if load_balancing_config.name == "__inherit__":
  426. if not managed_credentials:
  427. # remove __inherit__ if managed credentials is not provided
  428. self._load_balancing_configs.remove(load_balancing_config)
  429. else:
  430. load_balancing_config.credentials = managed_credentials
  431. def fetch_next(self) -> Optional[ModelLoadBalancingConfiguration]:
  432. """
  433. Get next model load balancing config
  434. Strategy: Round Robin
  435. :return:
  436. """
  437. cache_key = "model_lb_index:{}:{}:{}:{}".format(
  438. self._tenant_id, self._provider, self._model_type.value, self._model
  439. )
  440. cooldown_load_balancing_configs = []
  441. max_index = len(self._load_balancing_configs)
  442. while True:
  443. current_index = redis_client.incr(cache_key)
  444. current_index = cast(int, current_index)
  445. if current_index >= 10000000:
  446. current_index = 1
  447. redis_client.set(cache_key, current_index)
  448. redis_client.expire(cache_key, 3600)
  449. if current_index > max_index:
  450. current_index = current_index % max_index
  451. real_index = current_index - 1
  452. if real_index > max_index:
  453. real_index = 0
  454. config: ModelLoadBalancingConfiguration = self._load_balancing_configs[real_index]
  455. if self.in_cooldown(config):
  456. cooldown_load_balancing_configs.append(config)
  457. if len(cooldown_load_balancing_configs) >= len(self._load_balancing_configs):
  458. # all configs are in cooldown
  459. return None
  460. continue
  461. if dify_config.DEBUG:
  462. logger.info(
  463. """Model LB
  464. id: %s
  465. name:%s
  466. tenant_id: %s
  467. provider: %s
  468. model_type: %s
  469. model: %s""",
  470. config.id,
  471. config.name,
  472. self._tenant_id,
  473. self._provider,
  474. self._model_type.value,
  475. self._model,
  476. )
  477. return config
  478. def cooldown(self, config: ModelLoadBalancingConfiguration, expire: int = 60):
  479. """
  480. Cooldown model load balancing config
  481. :param config: model load balancing config
  482. :param expire: cooldown time
  483. :return:
  484. """
  485. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  486. self._tenant_id, self._provider, self._model_type.value, self._model, config.id
  487. )
  488. redis_client.setex(cooldown_cache_key, expire, "true")
  489. def in_cooldown(self, config: ModelLoadBalancingConfiguration) -> bool:
  490. """
  491. Check if model load balancing config is in cooldown
  492. :param config: model load balancing config
  493. :return:
  494. """
  495. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  496. self._tenant_id, self._provider, self._model_type.value, self._model, config.id
  497. )
  498. res: bool = redis_client.exists(cooldown_cache_key)
  499. return res
  500. @staticmethod
  501. def get_config_in_cooldown_and_ttl(
  502. tenant_id: str, provider: str, model_type: ModelType, model: str, config_id: str
  503. ) -> tuple[bool, int]:
  504. """
  505. Get model load balancing config is in cooldown and ttl
  506. :param tenant_id: workspace id
  507. :param provider: provider name
  508. :param model_type: model type
  509. :param model: model name
  510. :param config_id: model load balancing config id
  511. :return:
  512. """
  513. cooldown_cache_key = "model_lb_index:cooldown:{}:{}:{}:{}:{}".format(
  514. tenant_id, provider, model_type.value, model, config_id
  515. )
  516. ttl = redis_client.ttl(cooldown_cache_key)
  517. if ttl == -2:
  518. return False, 0
  519. ttl = cast(int, ttl)
  520. return True, ttl