orchestrator_rule_parser.py 14 KB

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