您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

cot_agent_runner.py 17KB

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