assistant_cot_runner.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import json
  2. import re
  3. from collections.abc import Generator
  4. from typing import Literal, Union
  5. from core.application_queue_manager import PublishFrom
  6. from core.entities.application_entities import AgentPromptEntity, AgentScratchpadUnit
  7. from core.features.assistant_base_runner import BaseAssistantApplicationRunner
  8. from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
  9. from core.model_runtime.entities.message_entities import (
  10. AssistantPromptMessage,
  11. PromptMessage,
  12. PromptMessageTool,
  13. SystemPromptMessage,
  14. UserPromptMessage,
  15. )
  16. from core.model_runtime.utils.encoders import jsonable_encoder
  17. from core.tools.errors import (
  18. ToolInvokeError,
  19. ToolNotFoundError,
  20. ToolNotSupportedError,
  21. ToolParameterValidationError,
  22. ToolProviderCredentialValidationError,
  23. ToolProviderNotFoundError,
  24. )
  25. from models.model import Conversation, Message
  26. class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
  27. def run(self, conversation: Conversation,
  28. message: Message,
  29. query: str,
  30. inputs: dict[str, str],
  31. ) -> Union[Generator, LLMResult]:
  32. """
  33. Run Cot agent application
  34. """
  35. app_orchestration_config = self.app_orchestration_config
  36. self._repack_app_orchestration_config(app_orchestration_config)
  37. agent_scratchpad: list[AgentScratchpadUnit] = []
  38. # check model mode
  39. if self.app_orchestration_config.model_config.mode == "completion":
  40. # TODO: stop words
  41. if 'Observation' not in app_orchestration_config.model_config.stop:
  42. app_orchestration_config.model_config.stop.append('Observation')
  43. # override inputs
  44. inputs = inputs or {}
  45. instruction = self.app_orchestration_config.prompt_template.simple_prompt_template
  46. instruction = self._fill_in_inputs_from_external_data_tools(instruction, inputs)
  47. iteration_step = 1
  48. max_iteration_steps = min(self.app_orchestration_config.agent.max_iteration, 5) + 1
  49. prompt_messages = self.history_prompt_messages
  50. # convert tools into ModelRuntime Tool format
  51. prompt_messages_tools: list[PromptMessageTool] = []
  52. tool_instances = {}
  53. for tool in self.app_orchestration_config.agent.tools if self.app_orchestration_config.agent else []:
  54. try:
  55. prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
  56. except Exception:
  57. # api tool may be deleted
  58. continue
  59. # save tool entity
  60. tool_instances[tool.tool_name] = tool_entity
  61. # save prompt tool
  62. prompt_messages_tools.append(prompt_tool)
  63. # convert dataset tools into ModelRuntime Tool format
  64. for dataset_tool in self.dataset_tools:
  65. prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
  66. # save prompt tool
  67. prompt_messages_tools.append(prompt_tool)
  68. # save tool entity
  69. tool_instances[dataset_tool.identity.name] = dataset_tool
  70. function_call_state = True
  71. llm_usage = {
  72. 'usage': None
  73. }
  74. final_answer = ''
  75. def increase_usage(final_llm_usage_dict: dict[str, LLMUsage], usage: LLMUsage):
  76. if not final_llm_usage_dict['usage']:
  77. final_llm_usage_dict['usage'] = usage
  78. else:
  79. llm_usage = final_llm_usage_dict['usage']
  80. llm_usage.prompt_tokens += usage.prompt_tokens
  81. llm_usage.completion_tokens += usage.completion_tokens
  82. llm_usage.prompt_price += usage.prompt_price
  83. llm_usage.completion_price += usage.completion_price
  84. model_instance = self.model_instance
  85. while function_call_state and iteration_step <= max_iteration_steps:
  86. # continue to run until there is not any tool call
  87. function_call_state = False
  88. if iteration_step == max_iteration_steps:
  89. # the last iteration, remove all tools
  90. prompt_messages_tools = []
  91. message_file_ids = []
  92. agent_thought = self.create_agent_thought(
  93. message_id=message.id,
  94. message='',
  95. tool_name='',
  96. tool_input='',
  97. messages_ids=message_file_ids
  98. )
  99. if iteration_step > 1:
  100. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  101. # update prompt messages
  102. prompt_messages = self._organize_cot_prompt_messages(
  103. mode=app_orchestration_config.model_config.mode,
  104. prompt_messages=prompt_messages,
  105. tools=prompt_messages_tools,
  106. agent_scratchpad=agent_scratchpad,
  107. agent_prompt_message=app_orchestration_config.agent.prompt,
  108. instruction=instruction,
  109. input=query
  110. )
  111. # recale llm max tokens
  112. self.recale_llm_max_tokens(self.model_config, prompt_messages)
  113. # invoke model
  114. llm_result: LLMResult = model_instance.invoke_llm(
  115. prompt_messages=prompt_messages,
  116. model_parameters=app_orchestration_config.model_config.parameters,
  117. tools=[],
  118. stop=app_orchestration_config.model_config.stop,
  119. stream=False,
  120. user=self.user_id,
  121. callbacks=[],
  122. )
  123. # check llm result
  124. if not llm_result:
  125. raise ValueError("failed to invoke llm")
  126. # get scratchpad
  127. scratchpad = self._extract_response_scratchpad(llm_result.message.content)
  128. agent_scratchpad.append(scratchpad)
  129. # get llm usage
  130. if llm_result.usage:
  131. increase_usage(llm_usage, llm_result.usage)
  132. # publish agent thought if it's first iteration
  133. if iteration_step == 1:
  134. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  135. self.save_agent_thought(agent_thought=agent_thought,
  136. tool_name=scratchpad.action.action_name if scratchpad.action else '',
  137. tool_input=scratchpad.action.action_input if scratchpad.action else '',
  138. thought=scratchpad.thought,
  139. observation='',
  140. answer=llm_result.message.content,
  141. messages_ids=[],
  142. llm_usage=llm_result.usage)
  143. if scratchpad.action and scratchpad.action.action_name.lower() != "final answer":
  144. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  145. # publish agent thought if it's not empty and there is a action
  146. if scratchpad.thought and scratchpad.action:
  147. # check if final answer
  148. if not scratchpad.action.action_name.lower() == "final answer":
  149. yield LLMResultChunk(
  150. model=model_instance.model,
  151. prompt_messages=prompt_messages,
  152. delta=LLMResultChunkDelta(
  153. index=0,
  154. message=AssistantPromptMessage(
  155. content=scratchpad.thought
  156. ),
  157. usage=llm_result.usage,
  158. ),
  159. system_fingerprint=''
  160. )
  161. if not scratchpad.action:
  162. # failed to extract action, return final answer directly
  163. final_answer = scratchpad.agent_response or ''
  164. else:
  165. if scratchpad.action.action_name.lower() == "final answer":
  166. # action is final answer, return final answer directly
  167. try:
  168. final_answer = scratchpad.action.action_input if \
  169. isinstance(scratchpad.action.action_input, str) else \
  170. json.dumps(scratchpad.action.action_input)
  171. except json.JSONDecodeError:
  172. final_answer = f'{scratchpad.action.action_input}'
  173. else:
  174. function_call_state = True
  175. # action is tool call, invoke tool
  176. tool_call_name = scratchpad.action.action_name
  177. tool_call_args = scratchpad.action.action_input
  178. tool_instance = tool_instances.get(tool_call_name)
  179. if not tool_instance:
  180. answer = f"there is not a tool named {tool_call_name}"
  181. self.save_agent_thought(agent_thought=agent_thought,
  182. tool_name='',
  183. tool_input='',
  184. thought=None,
  185. observation=answer,
  186. answer=answer,
  187. messages_ids=[])
  188. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  189. else:
  190. # invoke tool
  191. error_response = None
  192. try:
  193. tool_response = tool_instance.invoke(
  194. user_id=self.user_id,
  195. tool_parameters=tool_call_args if isinstance(tool_call_args, dict) else json.loads(tool_call_args)
  196. )
  197. # transform tool response to llm friendly response
  198. tool_response = self.transform_tool_invoke_messages(tool_response)
  199. # extract binary data from tool invoke message
  200. binary_files = self.extract_tool_response_binary(tool_response)
  201. # create message file
  202. message_files = self.create_message_files(binary_files)
  203. # publish files
  204. for message_file, save_as in message_files:
  205. if save_as:
  206. self.variables_pool.set_file(tool_name=tool_call_name,
  207. value=message_file.id,
  208. name=save_as)
  209. self.queue_manager.publish_message_file(message_file, PublishFrom.APPLICATION_MANAGER)
  210. message_file_ids = [message_file.id for message_file, _ in message_files]
  211. except ToolProviderCredentialValidationError as e:
  212. error_response = "Please check your tool provider credentials"
  213. except (
  214. ToolNotFoundError, ToolNotSupportedError, ToolProviderNotFoundError
  215. ) as e:
  216. error_response = f"there is not a tool named {tool_call_name}"
  217. except (
  218. ToolParameterValidationError
  219. ) as e:
  220. error_response = f"tool parameters validation error: {e}, please check your tool parameters"
  221. except ToolInvokeError as e:
  222. error_response = f"tool invoke error: {e}"
  223. except Exception as e:
  224. error_response = f"unknown error: {e}"
  225. if error_response:
  226. observation = error_response
  227. else:
  228. observation = self._convert_tool_response_to_str(tool_response)
  229. # save scratchpad
  230. scratchpad.observation = observation
  231. scratchpad.agent_response = llm_result.message.content
  232. # save agent thought
  233. self.save_agent_thought(
  234. agent_thought=agent_thought,
  235. tool_name=tool_call_name,
  236. tool_input=tool_call_args,
  237. thought=None,
  238. observation=observation,
  239. answer=llm_result.message.content,
  240. messages_ids=message_file_ids,
  241. )
  242. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  243. # update prompt tool message
  244. for prompt_tool in prompt_messages_tools:
  245. self.update_prompt_message_tool(tool_instances[prompt_tool.name], prompt_tool)
  246. iteration_step += 1
  247. yield LLMResultChunk(
  248. model=model_instance.model,
  249. prompt_messages=prompt_messages,
  250. delta=LLMResultChunkDelta(
  251. index=0,
  252. message=AssistantPromptMessage(
  253. content=final_answer
  254. ),
  255. usage=llm_usage['usage']
  256. ),
  257. system_fingerprint=''
  258. )
  259. # save agent thought
  260. self.save_agent_thought(
  261. agent_thought=agent_thought,
  262. tool_name='',
  263. tool_input='',
  264. thought=final_answer,
  265. observation='',
  266. answer=final_answer,
  267. messages_ids=[]
  268. )
  269. self.update_db_variables(self.variables_pool, self.db_variables_pool)
  270. # publish end event
  271. self.queue_manager.publish_message_end(LLMResult(
  272. model=model_instance.model,
  273. prompt_messages=prompt_messages,
  274. message=AssistantPromptMessage(
  275. content=final_answer
  276. ),
  277. usage=llm_usage['usage'] if llm_usage['usage'] else LLMUsage.empty_usage(),
  278. system_fingerprint=''
  279. ), PublishFrom.APPLICATION_MANAGER)
  280. def _fill_in_inputs_from_external_data_tools(self, instruction: str, inputs: dict) -> str:
  281. """
  282. fill in inputs from external data tools
  283. """
  284. for key, value in inputs.items():
  285. try:
  286. instruction = instruction.replace(f'{{{{{key}}}}}', str(value))
  287. except Exception as e:
  288. continue
  289. return instruction
  290. def _extract_response_scratchpad(self, content: str) -> AgentScratchpadUnit:
  291. """
  292. extract response from llm response
  293. """
  294. def extra_quotes() -> AgentScratchpadUnit:
  295. agent_response = content
  296. # try to extract all quotes
  297. pattern = re.compile(r'```(.*?)```', re.DOTALL)
  298. quotes = pattern.findall(content)
  299. # try to extract action from end to start
  300. for i in range(len(quotes) - 1, 0, -1):
  301. """
  302. 1. use json load to parse action
  303. 2. use plain text `Action: xxx` to parse action
  304. """
  305. try:
  306. action = json.loads(quotes[i].replace('```', ''))
  307. action_name = action.get("action")
  308. action_input = action.get("action_input")
  309. agent_thought = agent_response.replace(quotes[i], '')
  310. if action_name and action_input:
  311. return AgentScratchpadUnit(
  312. agent_response=content,
  313. thought=agent_thought,
  314. action_str=quotes[i],
  315. action=AgentScratchpadUnit.Action(
  316. action_name=action_name,
  317. action_input=action_input,
  318. )
  319. )
  320. except:
  321. # try to parse action from plain text
  322. action_name = re.findall(r'action: (.*)', quotes[i], re.IGNORECASE)
  323. action_input = re.findall(r'action input: (.*)', quotes[i], re.IGNORECASE)
  324. # delete action from agent response
  325. agent_thought = agent_response.replace(quotes[i], '')
  326. # remove extra quotes
  327. agent_thought = re.sub(r'```(json)*\n*```', '', agent_thought, flags=re.DOTALL)
  328. # remove Action: xxx from agent thought
  329. agent_thought = re.sub(r'Action:.*', '', agent_thought, flags=re.IGNORECASE)
  330. if action_name and action_input:
  331. return AgentScratchpadUnit(
  332. agent_response=content,
  333. thought=agent_thought,
  334. action_str=quotes[i],
  335. action=AgentScratchpadUnit.Action(
  336. action_name=action_name[0],
  337. action_input=action_input[0],
  338. )
  339. )
  340. def extra_json():
  341. agent_response = content
  342. # try to extract all json
  343. structures, pair_match_stack = [], []
  344. started_at, end_at = 0, 0
  345. for i in range(len(content)):
  346. if content[i] == '{':
  347. pair_match_stack.append(i)
  348. if len(pair_match_stack) == 1:
  349. started_at = i
  350. elif content[i] == '}':
  351. begin = pair_match_stack.pop()
  352. if not pair_match_stack:
  353. end_at = i + 1
  354. structures.append((content[begin:i+1], (started_at, end_at)))
  355. # handle the last character
  356. if pair_match_stack:
  357. end_at = len(content)
  358. structures.append((content[pair_match_stack[0]:], (started_at, end_at)))
  359. for i in range(len(structures), 0, -1):
  360. try:
  361. json_content, (started_at, end_at) = structures[i - 1]
  362. action = json.loads(json_content)
  363. action_name = action.get("action")
  364. action_input = action.get("action_input")
  365. # delete json content from agent response
  366. agent_thought = agent_response[:started_at] + agent_response[end_at:]
  367. # remove extra quotes like ```(json)*\n\n```
  368. agent_thought = re.sub(r'```(json)*\n*```', '', agent_thought, flags=re.DOTALL)
  369. # remove Action: xxx from agent thought
  370. agent_thought = re.sub(r'Action:.*', '', agent_thought, flags=re.IGNORECASE)
  371. if action_name and action_input is not None:
  372. return AgentScratchpadUnit(
  373. agent_response=content,
  374. thought=agent_thought,
  375. action_str=json_content,
  376. action=AgentScratchpadUnit.Action(
  377. action_name=action_name,
  378. action_input=action_input,
  379. )
  380. )
  381. except:
  382. pass
  383. agent_scratchpad = extra_quotes()
  384. if agent_scratchpad:
  385. return agent_scratchpad
  386. agent_scratchpad = extra_json()
  387. if agent_scratchpad:
  388. return agent_scratchpad
  389. return AgentScratchpadUnit(
  390. agent_response=content,
  391. thought=content,
  392. action_str='',
  393. action=None
  394. )
  395. def _check_cot_prompt_messages(self, mode: Literal["completion", "chat"],
  396. agent_prompt_message: AgentPromptEntity,
  397. ):
  398. """
  399. check chain of thought prompt messages, a standard prompt message is like:
  400. Respond to the human as helpfully and accurately as possible.
  401. {{instruction}}
  402. You have access to the following tools:
  403. {{tools}}
  404. Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
  405. Valid action values: "Final Answer" or {{tool_names}}
  406. Provide only ONE action per $JSON_BLOB, as shown:
  407. ```
  408. {
  409. "action": $TOOL_NAME,
  410. "action_input": $ACTION_INPUT
  411. }
  412. ```
  413. """
  414. # parse agent prompt message
  415. first_prompt = agent_prompt_message.first_prompt
  416. next_iteration = agent_prompt_message.next_iteration
  417. if not isinstance(first_prompt, str) or not isinstance(next_iteration, str):
  418. raise ValueError("first_prompt or next_iteration is required in CoT agent mode")
  419. # check instruction, tools, and tool_names slots
  420. if not first_prompt.find("{{instruction}}") >= 0:
  421. raise ValueError("{{instruction}} is required in first_prompt")
  422. if not first_prompt.find("{{tools}}") >= 0:
  423. raise ValueError("{{tools}} is required in first_prompt")
  424. if not first_prompt.find("{{tool_names}}") >= 0:
  425. raise ValueError("{{tool_names}} is required in first_prompt")
  426. if mode == "completion":
  427. if not first_prompt.find("{{query}}") >= 0:
  428. raise ValueError("{{query}} is required in first_prompt")
  429. if not first_prompt.find("{{agent_scratchpad}}") >= 0:
  430. raise ValueError("{{agent_scratchpad}} is required in first_prompt")
  431. if mode == "completion":
  432. if not next_iteration.find("{{observation}}") >= 0:
  433. raise ValueError("{{observation}} is required in next_iteration")
  434. def _convert_scratchpad_list_to_str(self, agent_scratchpad: list[AgentScratchpadUnit]) -> str:
  435. """
  436. convert agent scratchpad list to str
  437. """
  438. next_iteration = self.app_orchestration_config.agent.prompt.next_iteration
  439. result = ''
  440. for scratchpad in agent_scratchpad:
  441. result += scratchpad.thought + next_iteration.replace("{{observation}}", scratchpad.observation or '') + "\n"
  442. return result
  443. def _organize_cot_prompt_messages(self, mode: Literal["completion", "chat"],
  444. prompt_messages: list[PromptMessage],
  445. tools: list[PromptMessageTool],
  446. agent_scratchpad: list[AgentScratchpadUnit],
  447. agent_prompt_message: AgentPromptEntity,
  448. instruction: str,
  449. input: str,
  450. ) -> list[PromptMessage]:
  451. """
  452. organize chain of thought prompt messages, a standard prompt message is like:
  453. Respond to the human as helpfully and accurately as possible.
  454. {{instruction}}
  455. You have access to the following tools:
  456. {{tools}}
  457. Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
  458. Valid action values: "Final Answer" or {{tool_names}}
  459. Provide only ONE action per $JSON_BLOB, as shown:
  460. ```
  461. {{{{
  462. "action": $TOOL_NAME,
  463. "action_input": $ACTION_INPUT
  464. }}}}
  465. ```
  466. """
  467. self._check_cot_prompt_messages(mode, agent_prompt_message)
  468. # parse agent prompt message
  469. first_prompt = agent_prompt_message.first_prompt
  470. # parse tools
  471. tools_str = self._jsonify_tool_prompt_messages(tools)
  472. # parse tools name
  473. tool_names = '"' + '","'.join([tool.name for tool in tools]) + '"'
  474. # get system message
  475. system_message = first_prompt.replace("{{instruction}}", instruction) \
  476. .replace("{{tools}}", tools_str) \
  477. .replace("{{tool_names}}", tool_names)
  478. # organize prompt messages
  479. if mode == "chat":
  480. # override system message
  481. overrided = False
  482. prompt_messages = prompt_messages.copy()
  483. for prompt_message in prompt_messages:
  484. if isinstance(prompt_message, SystemPromptMessage):
  485. prompt_message.content = system_message
  486. overrided = True
  487. break
  488. if not overrided:
  489. prompt_messages.insert(0, SystemPromptMessage(
  490. content=system_message,
  491. ))
  492. # add assistant message
  493. if len(agent_scratchpad) > 0:
  494. prompt_messages.append(AssistantPromptMessage(
  495. content=(agent_scratchpad[-1].thought or '')
  496. ))
  497. # add user message
  498. if len(agent_scratchpad) > 0:
  499. prompt_messages.append(UserPromptMessage(
  500. content=(agent_scratchpad[-1].observation or ''),
  501. ))
  502. return prompt_messages
  503. elif mode == "completion":
  504. # parse agent scratchpad
  505. agent_scratchpad_str = self._convert_scratchpad_list_to_str(agent_scratchpad)
  506. # parse prompt messages
  507. return [UserPromptMessage(
  508. content=first_prompt.replace("{{instruction}}", instruction)
  509. .replace("{{tools}}", tools_str)
  510. .replace("{{tool_names}}", tool_names)
  511. .replace("{{query}}", input)
  512. .replace("{{agent_scratchpad}}", agent_scratchpad_str),
  513. )]
  514. else:
  515. raise ValueError(f"mode {mode} is not supported")
  516. def _jsonify_tool_prompt_messages(self, tools: list[PromptMessageTool]) -> str:
  517. """
  518. jsonify tool prompt messages
  519. """
  520. tools = jsonable_encoder(tools)
  521. try:
  522. return json.dumps(tools, ensure_ascii=False)
  523. except json.JSONDecodeError:
  524. return json.dumps(tools)