cot_agent_runner.py 17 KB

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