cot_agent_runner.py 17 KB

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