You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cot_agent_runner.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  1. import json
  2. from abc import ABC, abstractmethod
  3. from collections.abc import Generator, Mapping, Sequence
  4. from typing import Any, Optional
  5. from core.agent.base_agent_runner import BaseAgentRunner
  6. from core.agent.entities import AgentScratchpadUnit
  7. from core.agent.output_parser.cot_output_parser import CotAgentOutputParser
  8. from core.app.apps.base_app_queue_manager import PublishFrom
  9. from core.app.entities.queue_entities import QueueAgentThoughtEvent, QueueMessageEndEvent, QueueMessageFileEvent
  10. from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
  11. from core.model_runtime.entities.message_entities import (
  12. AssistantPromptMessage,
  13. PromptMessage,
  14. PromptMessageTool,
  15. ToolPromptMessage,
  16. UserPromptMessage,
  17. )
  18. from core.ops.ops_trace_manager import TraceQueueManager
  19. from core.prompt.agent_history_prompt_transform import AgentHistoryPromptTransform
  20. from core.tools.__base.tool import Tool
  21. from core.tools.entities.tool_entities import ToolInvokeMeta
  22. from core.tools.tool_engine import ToolEngine
  23. from models.model import Message
  24. class CotAgentRunner(BaseAgentRunner, ABC):
  25. _is_first_iteration = True
  26. _ignore_observation_providers = ["wenxin"]
  27. _historic_prompt_messages: list[PromptMessage]
  28. _agent_scratchpad: list[AgentScratchpadUnit]
  29. _instruction: str
  30. _query: str
  31. _prompt_messages_tools: Sequence[PromptMessageTool]
  32. def run(
  33. self,
  34. message: Message,
  35. query: str,
  36. inputs: Mapping[str, str],
  37. ) -> Generator:
  38. """
  39. Run Cot agent application
  40. """
  41. app_generate_entity = self.application_generate_entity
  42. self._repack_app_generate_entity(app_generate_entity)
  43. self._init_react_state(query)
  44. trace_manager = app_generate_entity.trace_manager
  45. # check model mode
  46. if "Observation" not in app_generate_entity.model_conf.stop:
  47. if app_generate_entity.model_conf.provider not in self._ignore_observation_providers:
  48. app_generate_entity.model_conf.stop.append("Observation")
  49. app_config = self.app_config
  50. assert app_config.agent
  51. # init instruction
  52. inputs = inputs or {}
  53. instruction = app_config.prompt_template.simple_prompt_template or ""
  54. self._instruction = self._fill_in_inputs_from_external_data_tools(instruction, inputs)
  55. iteration_step = 1
  56. max_iteration_steps = min(app_config.agent.max_iteration if app_config.agent else 5, 5) + 1
  57. # convert tools into ModelRuntime Tool format
  58. tool_instances, prompt_messages_tools = self._init_prompt_tools()
  59. self._prompt_messages_tools = prompt_messages_tools
  60. # fix metadata filter not work
  61. if app_config.dataset is not None:
  62. metadata_filtering_conditions = app_config.dataset.retrieve_config.metadata_filtering_conditions
  63. for key, dataset_retriever_tool in tool_instances.items():
  64. if hasattr(dataset_retriever_tool, "retrieval_tool"):
  65. dataset_retriever_tool.retrieval_tool.metadata_filtering_conditions = metadata_filtering_conditions
  66. function_call_state = True
  67. llm_usage: dict[str, Optional[LLMUsage]] = {"usage": None}
  68. final_answer = ""
  69. def increase_usage(final_llm_usage_dict: dict[str, Optional[LLMUsage]], usage: LLMUsage):
  70. if not final_llm_usage_dict["usage"]:
  71. final_llm_usage_dict["usage"] = usage
  72. else:
  73. llm_usage = final_llm_usage_dict["usage"]
  74. llm_usage.prompt_tokens += usage.prompt_tokens
  75. llm_usage.completion_tokens += usage.completion_tokens
  76. llm_usage.prompt_price += usage.prompt_price
  77. llm_usage.completion_price += usage.completion_price
  78. llm_usage.total_price += usage.total_price
  79. model_instance = self.model_instance
  80. while function_call_state and iteration_step <= max_iteration_steps:
  81. # continue to run until there is not any tool call
  82. function_call_state = False
  83. if iteration_step == max_iteration_steps:
  84. # the last iteration, remove all tools
  85. self._prompt_messages_tools = []
  86. message_file_ids: list[str] = []
  87. agent_thought = self.create_agent_thought(
  88. message_id=message.id, message="", tool_name="", tool_input="", messages_ids=message_file_ids
  89. )
  90. if iteration_step > 1:
  91. self.queue_manager.publish(
  92. QueueAgentThoughtEvent(agent_thought_id=agent_thought.id), PublishFrom.APPLICATION_MANAGER
  93. )
  94. # recalc llm max tokens
  95. prompt_messages = self._organize_prompt_messages()
  96. self.recalc_llm_max_tokens(self.model_config, prompt_messages)
  97. # invoke model
  98. chunks = model_instance.invoke_llm(
  99. prompt_messages=prompt_messages,
  100. model_parameters=app_generate_entity.model_conf.parameters,
  101. tools=[],
  102. stop=app_generate_entity.model_conf.stop,
  103. stream=True,
  104. user=self.user_id,
  105. callbacks=[],
  106. )
  107. usage_dict: dict[str, Optional[LLMUsage]] = {}
  108. react_chunks = CotAgentOutputParser.handle_react_stream_output(chunks, usage_dict)
  109. scratchpad = AgentScratchpadUnit(
  110. agent_response="",
  111. thought="",
  112. action_str="",
  113. observation="",
  114. action=None,
  115. )
  116. # publish agent thought if it's first iteration
  117. if iteration_step == 1:
  118. self.queue_manager.publish(
  119. QueueAgentThoughtEvent(agent_thought_id=agent_thought.id), PublishFrom.APPLICATION_MANAGER
  120. )
  121. for chunk in react_chunks:
  122. if isinstance(chunk, AgentScratchpadUnit.Action):
  123. action = chunk
  124. # detect action
  125. assert scratchpad.agent_response is not None
  126. scratchpad.agent_response += json.dumps(chunk.model_dump())
  127. scratchpad.action_str = json.dumps(chunk.model_dump())
  128. scratchpad.action = action
  129. else:
  130. assert scratchpad.agent_response is not None
  131. scratchpad.agent_response += chunk
  132. assert scratchpad.thought is not None
  133. scratchpad.thought += chunk
  134. yield LLMResultChunk(
  135. model=self.model_config.model,
  136. prompt_messages=prompt_messages,
  137. system_fingerprint="",
  138. delta=LLMResultChunkDelta(index=0, message=AssistantPromptMessage(content=chunk), usage=None),
  139. )
  140. assert scratchpad.thought is not None
  141. scratchpad.thought = scratchpad.thought.strip() or "I am thinking about how to help you"
  142. self._agent_scratchpad.append(scratchpad)
  143. # get llm usage
  144. if "usage" in usage_dict:
  145. if usage_dict["usage"] is not None:
  146. increase_usage(llm_usage, usage_dict["usage"])
  147. else:
  148. usage_dict["usage"] = LLMUsage.empty_usage()
  149. self.save_agent_thought(
  150. agent_thought=agent_thought,
  151. tool_name=(scratchpad.action.action_name if scratchpad.action and not scratchpad.is_final() else ""),
  152. tool_input={scratchpad.action.action_name: scratchpad.action.action_input} if scratchpad.action else {},
  153. tool_invoke_meta={},
  154. thought=scratchpad.thought or "",
  155. observation="",
  156. answer=scratchpad.agent_response or "",
  157. messages_ids=[],
  158. llm_usage=usage_dict["usage"],
  159. )
  160. if not scratchpad.is_final():
  161. self.queue_manager.publish(
  162. QueueAgentThoughtEvent(agent_thought_id=agent_thought.id), PublishFrom.APPLICATION_MANAGER
  163. )
  164. if not scratchpad.action:
  165. # failed to extract action, return final answer directly
  166. final_answer = ""
  167. else:
  168. if scratchpad.action.action_name.lower() == "final answer":
  169. # action is final answer, return final answer directly
  170. try:
  171. if isinstance(scratchpad.action.action_input, dict):
  172. final_answer = json.dumps(scratchpad.action.action_input, ensure_ascii=False)
  173. elif isinstance(scratchpad.action.action_input, str):
  174. final_answer = scratchpad.action.action_input
  175. else:
  176. final_answer = f"{scratchpad.action.action_input}"
  177. except json.JSONDecodeError:
  178. final_answer = f"{scratchpad.action.action_input}"
  179. else:
  180. function_call_state = True
  181. # action is tool call, invoke tool
  182. tool_invoke_response, tool_invoke_meta = self._handle_invoke_action(
  183. action=scratchpad.action,
  184. tool_instances=tool_instances,
  185. message_file_ids=message_file_ids,
  186. trace_manager=trace_manager,
  187. )
  188. scratchpad.observation = tool_invoke_response
  189. scratchpad.agent_response = tool_invoke_response
  190. self.save_agent_thought(
  191. agent_thought=agent_thought,
  192. tool_name=scratchpad.action.action_name,
  193. tool_input={scratchpad.action.action_name: scratchpad.action.action_input},
  194. thought=scratchpad.thought or "",
  195. observation={scratchpad.action.action_name: tool_invoke_response},
  196. tool_invoke_meta={scratchpad.action.action_name: tool_invoke_meta.to_dict()},
  197. answer=scratchpad.agent_response,
  198. messages_ids=message_file_ids,
  199. llm_usage=usage_dict["usage"],
  200. )
  201. self.queue_manager.publish(
  202. QueueAgentThoughtEvent(agent_thought_id=agent_thought.id), PublishFrom.APPLICATION_MANAGER
  203. )
  204. # update prompt tool message
  205. for prompt_tool in self._prompt_messages_tools:
  206. self.update_prompt_message_tool(tool_instances[prompt_tool.name], prompt_tool)
  207. iteration_step += 1
  208. yield LLMResultChunk(
  209. model=model_instance.model,
  210. prompt_messages=prompt_messages,
  211. delta=LLMResultChunkDelta(
  212. index=0, message=AssistantPromptMessage(content=final_answer), usage=llm_usage["usage"]
  213. ),
  214. system_fingerprint="",
  215. )
  216. # save agent thought
  217. self.save_agent_thought(
  218. agent_thought=agent_thought,
  219. tool_name="",
  220. tool_input={},
  221. tool_invoke_meta={},
  222. thought=final_answer,
  223. observation={},
  224. answer=final_answer,
  225. messages_ids=[],
  226. )
  227. # publish end event
  228. self.queue_manager.publish(
  229. QueueMessageEndEvent(
  230. llm_result=LLMResult(
  231. model=model_instance.model,
  232. prompt_messages=prompt_messages,
  233. message=AssistantPromptMessage(content=final_answer),
  234. usage=llm_usage["usage"] or LLMUsage.empty_usage(),
  235. system_fingerprint="",
  236. )
  237. ),
  238. PublishFrom.APPLICATION_MANAGER,
  239. )
  240. def _handle_invoke_action(
  241. self,
  242. action: AgentScratchpadUnit.Action,
  243. tool_instances: Mapping[str, Tool],
  244. message_file_ids: list[str],
  245. trace_manager: Optional[TraceQueueManager] = None,
  246. ) -> tuple[str, ToolInvokeMeta]:
  247. """
  248. handle invoke action
  249. :param action: action
  250. :param tool_instances: tool instances
  251. :param message_file_ids: message file ids
  252. :param trace_manager: trace manager
  253. :return: observation, meta
  254. """
  255. # action is tool call, invoke tool
  256. tool_call_name = action.action_name
  257. tool_call_args = action.action_input
  258. tool_instance = tool_instances.get(tool_call_name)
  259. if not tool_instance:
  260. answer = f"there is not a tool named {tool_call_name}"
  261. return answer, ToolInvokeMeta.error_instance(answer)
  262. if isinstance(tool_call_args, str):
  263. try:
  264. tool_call_args = json.loads(tool_call_args)
  265. except json.JSONDecodeError:
  266. pass
  267. # invoke tool
  268. tool_invoke_response, message_files, tool_invoke_meta = ToolEngine.agent_invoke(
  269. tool=tool_instance,
  270. tool_parameters=tool_call_args,
  271. user_id=self.user_id,
  272. tenant_id=self.tenant_id,
  273. message=self.message,
  274. invoke_from=self.application_generate_entity.invoke_from,
  275. agent_tool_callback=self.agent_callback,
  276. trace_manager=trace_manager,
  277. )
  278. # publish files
  279. for message_file_id in message_files:
  280. # publish message file
  281. self.queue_manager.publish(
  282. QueueMessageFileEvent(message_file_id=message_file_id), PublishFrom.APPLICATION_MANAGER
  283. )
  284. # add message file ids
  285. message_file_ids.append(message_file_id)
  286. return tool_invoke_response, tool_invoke_meta
  287. def _convert_dict_to_action(self, action: dict) -> AgentScratchpadUnit.Action:
  288. """
  289. convert dict to action
  290. """
  291. return AgentScratchpadUnit.Action(action_name=action["action"], action_input=action["action_input"])
  292. def _fill_in_inputs_from_external_data_tools(self, instruction: str, inputs: Mapping[str, Any]) -> str:
  293. """
  294. fill in inputs from external data tools
  295. """
  296. for key, value in inputs.items():
  297. try:
  298. instruction = instruction.replace(f"{{{{{key}}}}}", str(value))
  299. except Exception:
  300. continue
  301. return instruction
  302. def _init_react_state(self, query) -> None:
  303. """
  304. init agent scratchpad
  305. """
  306. self._query = query
  307. self._agent_scratchpad = []
  308. self._historic_prompt_messages = self._organize_historic_prompt_messages()
  309. @abstractmethod
  310. def _organize_prompt_messages(self) -> list[PromptMessage]:
  311. """
  312. organize prompt messages
  313. """
  314. def _format_assistant_message(self, agent_scratchpad: list[AgentScratchpadUnit]) -> str:
  315. """
  316. format assistant message
  317. """
  318. message = ""
  319. for scratchpad in agent_scratchpad:
  320. if scratchpad.is_final():
  321. message += f"Final Answer: {scratchpad.agent_response}"
  322. else:
  323. message += f"Thought: {scratchpad.thought}\n\n"
  324. if scratchpad.action_str:
  325. message += f"Action: {scratchpad.action_str}\n\n"
  326. if scratchpad.observation:
  327. message += f"Observation: {scratchpad.observation}\n\n"
  328. return message
  329. def _organize_historic_prompt_messages(
  330. self, current_session_messages: list[PromptMessage] | None = None
  331. ) -> list[PromptMessage]:
  332. """
  333. organize historic prompt messages
  334. """
  335. result: list[PromptMessage] = []
  336. scratchpads: list[AgentScratchpadUnit] = []
  337. current_scratchpad: AgentScratchpadUnit | None = None
  338. for message in self.history_prompt_messages:
  339. if isinstance(message, AssistantPromptMessage):
  340. if not current_scratchpad:
  341. assert isinstance(message.content, str)
  342. current_scratchpad = AgentScratchpadUnit(
  343. agent_response=message.content,
  344. thought=message.content or "I am thinking about how to help you",
  345. action_str="",
  346. action=None,
  347. observation=None,
  348. )
  349. scratchpads.append(current_scratchpad)
  350. if message.tool_calls:
  351. try:
  352. current_scratchpad.action = AgentScratchpadUnit.Action(
  353. action_name=message.tool_calls[0].function.name,
  354. action_input=json.loads(message.tool_calls[0].function.arguments),
  355. )
  356. current_scratchpad.action_str = json.dumps(current_scratchpad.action.to_dict())
  357. except:
  358. pass
  359. elif isinstance(message, ToolPromptMessage):
  360. if current_scratchpad:
  361. assert isinstance(message.content, str)
  362. current_scratchpad.observation = message.content
  363. else:
  364. raise NotImplementedError("expected str type")
  365. elif isinstance(message, UserPromptMessage):
  366. if scratchpads:
  367. result.append(AssistantPromptMessage(content=self._format_assistant_message(scratchpads)))
  368. scratchpads = []
  369. current_scratchpad = None
  370. result.append(message)
  371. if scratchpads:
  372. result.append(AssistantPromptMessage(content=self._format_assistant_message(scratchpads)))
  373. historic_prompts = AgentHistoryPromptTransform(
  374. model_config=self.model_config,
  375. prompt_messages=current_session_messages or [],
  376. history_messages=result,
  377. memory=self.memory,
  378. ).get_prompt()
  379. return historic_prompts