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

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