orchestrator_rule_parser.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. import math
  2. from typing import Optional
  3. from langchain import WikipediaAPIWrapper
  4. from langchain.callbacks.manager import Callbacks
  5. from langchain.memory.chat_memory import BaseChatMemory
  6. from langchain.tools import BaseTool, Tool, WikipediaQueryRun
  7. from pydantic import BaseModel, Field
  8. from core.agent.agent_executor import AgentExecutor, PlanningStrategy, AgentConfiguration
  9. from core.callback_handler.agent_loop_gather_callback_handler import AgentLoopGatherCallbackHandler
  10. from core.callback_handler.dataset_tool_callback_handler import DatasetToolCallbackHandler
  11. from core.callback_handler.main_chain_gather_callback_handler import MainChainGatherCallbackHandler
  12. from core.callback_handler.std_out_callback_handler import DifyStdOutCallbackHandler
  13. from core.chain.sensitive_word_avoidance_chain import SensitiveWordAvoidanceChain, SensitiveWordAvoidanceRule
  14. from core.conversation_message_task import ConversationMessageTask
  15. from core.model_providers.error import ProviderTokenNotInitError
  16. from core.model_providers.model_factory import ModelFactory
  17. from core.model_providers.models.entity.model_params import ModelKwargs, ModelMode
  18. from core.model_providers.models.llm.base import BaseLLM
  19. from core.tool.current_datetime_tool import DatetimeTool
  20. from core.tool.dataset_retriever_tool import DatasetRetrieverTool
  21. from core.tool.provider.serpapi_provider import SerpAPIToolProvider
  22. from core.tool.serpapi_wrapper import OptimizedSerpAPIWrapper, OptimizedSerpAPIInput
  23. from core.tool.web_reader_tool import WebReaderTool
  24. from extensions.ext_database import db
  25. from models.dataset import Dataset, DatasetProcessRule
  26. from models.model import AppModelConfig
  27. class OrchestratorRuleParser:
  28. """Parse the orchestrator rule to entities."""
  29. def __init__(self, tenant_id: str, app_model_config: AppModelConfig):
  30. self.tenant_id = tenant_id
  31. self.app_model_config = app_model_config
  32. def to_agent_executor(self, conversation_message_task: ConversationMessageTask, memory: Optional[BaseChatMemory],
  33. rest_tokens: int, chain_callback: MainChainGatherCallbackHandler,
  34. retriever_from: str = 'dev') -> Optional[AgentExecutor]:
  35. if not self.app_model_config.agent_mode_dict:
  36. return None
  37. agent_mode_config = self.app_model_config.agent_mode_dict
  38. model_dict = self.app_model_config.model_dict
  39. return_resource = self.app_model_config.retriever_resource_dict.get('enabled', False)
  40. chain = None
  41. if agent_mode_config and agent_mode_config.get('enabled'):
  42. tool_configs = agent_mode_config.get('tools', [])
  43. agent_provider_name = model_dict.get('provider', 'openai')
  44. agent_model_name = model_dict.get('name', 'gpt-4')
  45. agent_model_instance = ModelFactory.get_text_generation_model(
  46. tenant_id=self.tenant_id,
  47. model_provider_name=agent_provider_name,
  48. model_name=agent_model_name,
  49. model_kwargs=ModelKwargs(
  50. temperature=0.2,
  51. top_p=0.3,
  52. max_tokens=1500
  53. )
  54. )
  55. # add agent callback to record agent thoughts
  56. agent_callback = AgentLoopGatherCallbackHandler(
  57. model_instance=agent_model_instance,
  58. conversation_message_task=conversation_message_task
  59. )
  60. chain_callback.agent_callback = agent_callback
  61. agent_model_instance.add_callbacks([agent_callback])
  62. planning_strategy = PlanningStrategy(agent_mode_config.get('strategy', 'router'))
  63. # only OpenAI chat model (include Azure) support function call, use ReACT instead
  64. if agent_model_instance.model_mode != ModelMode.CHAT \
  65. or agent_model_instance.model_provider.provider_name not in ['openai', 'azure_openai']:
  66. if planning_strategy == PlanningStrategy.FUNCTION_CALL:
  67. planning_strategy = PlanningStrategy.REACT
  68. elif planning_strategy == PlanningStrategy.ROUTER:
  69. planning_strategy = PlanningStrategy.REACT_ROUTER
  70. try:
  71. summary_model_instance = ModelFactory.get_text_generation_model(
  72. tenant_id=self.tenant_id,
  73. model_provider_name=agent_provider_name,
  74. model_name=agent_model_name,
  75. model_kwargs=ModelKwargs(
  76. temperature=0,
  77. max_tokens=500
  78. ),
  79. deduct_quota=False
  80. )
  81. except ProviderTokenNotInitError as e:
  82. summary_model_instance = None
  83. tools = self.to_tools(
  84. agent_model_instance=agent_model_instance,
  85. tool_configs=tool_configs,
  86. conversation_message_task=conversation_message_task,
  87. rest_tokens=rest_tokens,
  88. callbacks=[agent_callback, DifyStdOutCallbackHandler()],
  89. return_resource=return_resource,
  90. retriever_from=retriever_from
  91. )
  92. if len(tools) == 0:
  93. return None
  94. agent_configuration = AgentConfiguration(
  95. strategy=planning_strategy,
  96. model_instance=agent_model_instance,
  97. tools=tools,
  98. summary_model_instance=summary_model_instance,
  99. memory=memory,
  100. callbacks=[chain_callback, agent_callback],
  101. max_iterations=10,
  102. max_execution_time=400.0,
  103. early_stopping_method="generate"
  104. )
  105. return AgentExecutor(agent_configuration)
  106. return chain
  107. def to_sensitive_word_avoidance_chain(self, model_instance: BaseLLM, callbacks: Callbacks = None, **kwargs) \
  108. -> Optional[SensitiveWordAvoidanceChain]:
  109. """
  110. Convert app sensitive word avoidance config to chain
  111. :param model_instance: model instance
  112. :param callbacks: callbacks for the chain
  113. :param kwargs:
  114. :return:
  115. """
  116. sensitive_word_avoidance_rule = None
  117. if self.app_model_config.sensitive_word_avoidance_dict:
  118. sensitive_word_avoidance_config = self.app_model_config.sensitive_word_avoidance_dict
  119. if sensitive_word_avoidance_config.get("enabled", False):
  120. if sensitive_word_avoidance_config.get('type') == 'moderation':
  121. sensitive_word_avoidance_rule = SensitiveWordAvoidanceRule(
  122. type=SensitiveWordAvoidanceRule.Type.MODERATION,
  123. canned_response=sensitive_word_avoidance_config.get("canned_response")
  124. if sensitive_word_avoidance_config.get("canned_response")
  125. else 'Your content violates our usage policy. Please revise and try again.',
  126. )
  127. else:
  128. sensitive_words = sensitive_word_avoidance_config.get("words", "")
  129. if sensitive_words:
  130. sensitive_word_avoidance_rule = SensitiveWordAvoidanceRule(
  131. type=SensitiveWordAvoidanceRule.Type.KEYWORDS,
  132. canned_response=sensitive_word_avoidance_config.get("canned_response")
  133. if sensitive_word_avoidance_config.get("canned_response")
  134. else 'Your content violates our usage policy. Please revise and try again.',
  135. extra_params={
  136. 'sensitive_words': sensitive_words.split(','),
  137. }
  138. )
  139. if sensitive_word_avoidance_rule:
  140. return SensitiveWordAvoidanceChain(
  141. model_instance=model_instance,
  142. sensitive_word_avoidance_rule=sensitive_word_avoidance_rule,
  143. output_key="sensitive_word_avoidance_output",
  144. callbacks=callbacks,
  145. **kwargs
  146. )
  147. return None
  148. def to_tools(self, agent_model_instance: BaseLLM, tool_configs: list,
  149. conversation_message_task: ConversationMessageTask,
  150. rest_tokens: int, callbacks: Callbacks = None, return_resource: bool = False,
  151. retriever_from: str = 'dev') -> list[BaseTool]:
  152. """
  153. Convert app agent tool configs to tools
  154. :param agent_model_instance:
  155. :param rest_tokens:
  156. :param tool_configs: app agent tool configs
  157. :param conversation_message_task:
  158. :param callbacks:
  159. :param return_resource:
  160. :param retriever_from:
  161. :return:
  162. """
  163. tools = []
  164. for tool_config in tool_configs:
  165. tool_type = list(tool_config.keys())[0]
  166. tool_val = list(tool_config.values())[0]
  167. if not tool_val.get("enabled") or tool_val.get("enabled") is not True:
  168. continue
  169. tool = None
  170. if tool_type == "dataset":
  171. tool = self.to_dataset_retriever_tool(tool_val, conversation_message_task, rest_tokens, return_resource, retriever_from)
  172. elif tool_type == "web_reader":
  173. tool = self.to_web_reader_tool(agent_model_instance)
  174. elif tool_type == "google_search":
  175. tool = self.to_google_search_tool()
  176. elif tool_type == "wikipedia":
  177. tool = self.to_wikipedia_tool()
  178. elif tool_type == "current_datetime":
  179. tool = self.to_current_datetime_tool()
  180. if tool:
  181. if tool.callbacks is not None:
  182. tool.callbacks.extend(callbacks)
  183. else:
  184. tool.callbacks = callbacks
  185. tools.append(tool)
  186. return tools
  187. def to_dataset_retriever_tool(self, tool_config: dict, conversation_message_task: ConversationMessageTask,
  188. rest_tokens: int, return_resource: bool = False, retriever_from: str = 'dev') \
  189. -> Optional[BaseTool]:
  190. """
  191. A dataset tool is a tool that can be used to retrieve information from a dataset
  192. :param rest_tokens:
  193. :param tool_config:
  194. :param conversation_message_task:
  195. :param return_resource:
  196. :param retriever_from:
  197. :return:
  198. """
  199. # get dataset from dataset id
  200. dataset = db.session.query(Dataset).filter(
  201. Dataset.tenant_id == self.tenant_id,
  202. Dataset.id == tool_config.get("id")
  203. ).first()
  204. if not dataset:
  205. return None
  206. if dataset and dataset.available_document_count == 0 and dataset.available_document_count == 0:
  207. return None
  208. k = self._dynamic_calc_retrieve_k(dataset, rest_tokens)
  209. tool = DatasetRetrieverTool.from_dataset(
  210. dataset=dataset,
  211. k=k,
  212. callbacks=[DatasetToolCallbackHandler(conversation_message_task)],
  213. conversation_message_task=conversation_message_task,
  214. return_resource=return_resource,
  215. retriever_from=retriever_from
  216. )
  217. return tool
  218. def to_web_reader_tool(self, agent_model_instance: BaseLLM) -> Optional[BaseTool]:
  219. """
  220. A tool for reading web pages
  221. :return:
  222. """
  223. try:
  224. summary_model_instance = ModelFactory.get_text_generation_model(
  225. tenant_id=self.tenant_id,
  226. model_provider_name=agent_model_instance.model_provider.provider_name,
  227. model_name=agent_model_instance.name,
  228. model_kwargs=ModelKwargs(
  229. temperature=0,
  230. max_tokens=500
  231. ),
  232. deduct_quota=False
  233. )
  234. except ProviderTokenNotInitError:
  235. summary_model_instance = None
  236. tool = WebReaderTool(
  237. model_instance=summary_model_instance if summary_model_instance else None,
  238. max_chunk_length=4000,
  239. continue_reading=True
  240. )
  241. return tool
  242. def to_google_search_tool(self) -> Optional[BaseTool]:
  243. tool_provider = SerpAPIToolProvider(tenant_id=self.tenant_id)
  244. func_kwargs = tool_provider.credentials_to_func_kwargs()
  245. if not func_kwargs:
  246. return None
  247. tool = Tool(
  248. name="google_search",
  249. description="A tool for performing a Google search and extracting snippets and webpages "
  250. "when you need to search for something you don't know or when your information "
  251. "is not up to date. "
  252. "Input should be a search query.",
  253. func=OptimizedSerpAPIWrapper(**func_kwargs).run,
  254. args_schema=OptimizedSerpAPIInput
  255. )
  256. return tool
  257. def to_current_datetime_tool(self) -> Optional[BaseTool]:
  258. tool = DatetimeTool()
  259. return tool
  260. def to_wikipedia_tool(self) -> Optional[BaseTool]:
  261. class WikipediaInput(BaseModel):
  262. query: str = Field(..., description="search query.")
  263. return WikipediaQueryRun(
  264. name="wikipedia",
  265. api_wrapper=WikipediaAPIWrapper(doc_content_chars_max=4000),
  266. args_schema=WikipediaInput
  267. )
  268. @classmethod
  269. def _dynamic_calc_retrieve_k(cls, dataset: Dataset, rest_tokens: int) -> int:
  270. DEFAULT_K = 2
  271. CONTEXT_TOKENS_PERCENT = 0.3
  272. MAX_K = 10
  273. if rest_tokens == -1:
  274. return DEFAULT_K
  275. processing_rule = dataset.latest_process_rule
  276. if not processing_rule:
  277. return DEFAULT_K
  278. if processing_rule.mode == "custom":
  279. rules = processing_rule.rules_dict
  280. if not rules:
  281. return DEFAULT_K
  282. segmentation = rules["segmentation"]
  283. segment_max_tokens = segmentation["max_tokens"]
  284. else:
  285. segment_max_tokens = DatasetProcessRule.AUTOMATIC_RULES['segmentation']['max_tokens']
  286. # when rest_tokens is less than default context tokens
  287. if rest_tokens < segment_max_tokens * DEFAULT_K:
  288. return rest_tokens // segment_max_tokens
  289. context_limit_tokens = math.floor(rest_tokens * CONTEXT_TOKENS_PERCENT)
  290. # when context_limit_tokens is less than default context tokens, use default_k
  291. if context_limit_tokens <= segment_max_tokens * DEFAULT_K:
  292. return DEFAULT_K
  293. # Expand the k value when there's still some room left in the 30% rest tokens space, but less than the MAX_K
  294. return min(context_limit_tokens // segment_max_tokens, MAX_K)