assistant_cot_runner.py 26 KB

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