assistant_cot_runner.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import json
  2. import logging
  3. import re
  4. from typing import Literal, Union, Generator, Dict, List
  5. from core.entities.application_entities import AgentPromptEntity, AgentScratchpadUnit
  6. from core.application_queue_manager import PublishFrom
  7. from core.model_runtime.utils.encoders import jsonable_encoder
  8. from core.model_runtime.entities.message_entities import PromptMessageTool, PromptMessage, \
  9. UserPromptMessage, SystemPromptMessage, AssistantPromptMessage
  10. from core.model_runtime.entities.llm_entities import LLMResult, LLMUsage, LLMResultChunk, LLMResultChunkDelta
  11. from core.model_manager import ModelInstance
  12. from core.tools.errors import ToolInvokeError, ToolNotFoundError, \
  13. ToolNotSupportedError, ToolProviderNotFoundError, ToolParamterValidationError, \
  14. ToolProviderCredentialValidationError
  15. from core.features.assistant_base_runner import BaseAssistantApplicationRunner
  16. from models.model import Conversation, Message
  17. logger = logging.getLogger(__name__)
  18. class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
  19. def run(self, model_instance: ModelInstance,
  20. conversation: Conversation,
  21. message: Message,
  22. query: str,
  23. ) -> Union[Generator, LLMResult]:
  24. """
  25. Run Cot agent application
  26. """
  27. app_orchestration_config = self.app_orchestration_config
  28. self._repacket_app_orchestration_config(app_orchestration_config)
  29. agent_scratchpad: List[AgentScratchpadUnit] = []
  30. # check model mode
  31. if self.app_orchestration_config.model_config.mode == "completion":
  32. # TODO: stop words
  33. if 'Observation' not in app_orchestration_config.model_config.stop:
  34. app_orchestration_config.model_config.stop.append('Observation')
  35. iteration_step = 1
  36. max_iteration_steps = min(self.app_orchestration_config.agent.max_iteration, 5) + 1
  37. prompt_messages = self.history_prompt_messages
  38. # convert tools into ModelRuntime Tool format
  39. prompt_messages_tools: List[PromptMessageTool] = []
  40. tool_instances = {}
  41. for tool in self.app_orchestration_config.agent.tools if self.app_orchestration_config.agent else []:
  42. try:
  43. prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
  44. except Exception:
  45. # api tool may be deleted
  46. continue
  47. # save tool entity
  48. tool_instances[tool.tool_name] = tool_entity
  49. # save prompt tool
  50. prompt_messages_tools.append(prompt_tool)
  51. # convert dataset tools into ModelRuntime Tool format
  52. for dataset_tool in self.dataset_tools:
  53. prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
  54. # save prompt tool
  55. prompt_messages_tools.append(prompt_tool)
  56. # save tool entity
  57. tool_instances[dataset_tool.identity.name] = dataset_tool
  58. function_call_state = True
  59. llm_usage = {
  60. 'usage': None
  61. }
  62. final_answer = ''
  63. def increse_usage(final_llm_usage_dict: Dict[str, 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.prompt_price += usage.prompt_price
  71. llm_usage.completion_price += usage.completion_price
  72. while function_call_state and iteration_step <= max_iteration_steps:
  73. # continue to run until there is not any tool call
  74. function_call_state = False
  75. if iteration_step == max_iteration_steps:
  76. # the last iteration, remove all tools
  77. prompt_messages_tools = []
  78. message_file_ids = []
  79. agent_thought = self.create_agent_thought(
  80. message_id=message.id,
  81. message='',
  82. tool_name='',
  83. tool_input='',
  84. messages_ids=message_file_ids
  85. )
  86. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  87. # update prompt messages
  88. prompt_messages = self._originze_cot_prompt_messages(
  89. mode=app_orchestration_config.model_config.mode,
  90. prompt_messages=prompt_messages,
  91. tools=prompt_messages_tools,
  92. agent_scratchpad=agent_scratchpad,
  93. agent_prompt_message=app_orchestration_config.agent.prompt,
  94. instruction=app_orchestration_config.prompt_template.simple_prompt_template,
  95. input=query
  96. )
  97. # recale llm max tokens
  98. self.recale_llm_max_tokens(self.model_config, prompt_messages)
  99. # invoke model
  100. llm_result: LLMResult = model_instance.invoke_llm(
  101. prompt_messages=prompt_messages,
  102. model_parameters=app_orchestration_config.model_config.parameters,
  103. tools=[],
  104. stop=app_orchestration_config.model_config.stop,
  105. stream=False,
  106. user=self.user_id,
  107. callbacks=[],
  108. )
  109. # check llm result
  110. if not llm_result:
  111. raise ValueError("failed to invoke llm")
  112. # get scratchpad
  113. scratchpad = self._extract_response_scratchpad(llm_result.message.content)
  114. agent_scratchpad.append(scratchpad)
  115. # get llm usage
  116. if llm_result.usage:
  117. increse_usage(llm_usage, llm_result.usage)
  118. self.save_agent_thought(agent_thought=agent_thought,
  119. tool_name=scratchpad.action.action_name if scratchpad.action else '',
  120. tool_input=scratchpad.action.action_input if scratchpad.action else '',
  121. thought=scratchpad.thought,
  122. observation='',
  123. answer=llm_result.message.content,
  124. messages_ids=[],
  125. llm_usage=llm_result.usage)
  126. if scratchpad.action and scratchpad.action.action_name.lower() != "final answer":
  127. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  128. # publish agent thought if it's not empty and there is a action
  129. if scratchpad.thought and scratchpad.action:
  130. # check if final answer
  131. if not scratchpad.action.action_name.lower() == "final answer":
  132. yield LLMResultChunk(
  133. model=model_instance.model,
  134. prompt_messages=prompt_messages,
  135. delta=LLMResultChunkDelta(
  136. index=0,
  137. message=AssistantPromptMessage(
  138. content=scratchpad.thought
  139. ),
  140. usage=llm_result.usage,
  141. ),
  142. system_fingerprint=''
  143. )
  144. if not scratchpad.action:
  145. # failed to extract action, return final answer directly
  146. final_answer = scratchpad.agent_response or ''
  147. else:
  148. if scratchpad.action.action_name.lower() == "final answer":
  149. # action is final answer, return final answer directly
  150. try:
  151. final_answer = scratchpad.action.action_input if \
  152. isinstance(scratchpad.action.action_input, str) else \
  153. json.dumps(scratchpad.action.action_input)
  154. except json.JSONDecodeError:
  155. final_answer = f'{scratchpad.action.action_input}'
  156. else:
  157. function_call_state = True
  158. # action is tool call, invoke tool
  159. tool_call_name = scratchpad.action.action_name
  160. tool_call_args = scratchpad.action.action_input
  161. tool_instance = tool_instances.get(tool_call_name)
  162. if not tool_instance:
  163. logger.error(f"failed to find tool instance: {tool_call_name}")
  164. answer = f"there is not a tool named {tool_call_name}"
  165. self.save_agent_thought(agent_thought=agent_thought,
  166. tool_name='',
  167. tool_input='',
  168. thought=None,
  169. observation=answer,
  170. answer=answer,
  171. messages_ids=[])
  172. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  173. else:
  174. # invoke tool
  175. error_response = None
  176. try:
  177. tool_response = tool_instance.invoke(
  178. user_id=self.user_id,
  179. tool_paramters=tool_call_args if isinstance(tool_call_args, dict) else json.loads(tool_call_args)
  180. )
  181. # transform tool response to llm friendly response
  182. tool_response = self.transform_tool_invoke_messages(tool_response)
  183. # extract binary data from tool invoke message
  184. binary_files = self.extract_tool_response_binary(tool_response)
  185. # create message file
  186. message_files = self.create_message_files(binary_files)
  187. # publish files
  188. for message_file, save_as in message_files:
  189. if save_as:
  190. self.variables_pool.set_file(tool_name=tool_call_name,
  191. value=message_file.id,
  192. name=save_as)
  193. self.queue_manager.publish_message_file(message_file, PublishFrom.APPLICATION_MANAGER)
  194. message_file_ids = [message_file.id for message_file, _ in message_files]
  195. except ToolProviderCredentialValidationError as e:
  196. error_response = f"Plese check your tool provider credentials"
  197. except (
  198. ToolNotFoundError, ToolNotSupportedError, ToolProviderNotFoundError
  199. ) as e:
  200. error_response = f"there is not a tool named {tool_call_name}"
  201. except (
  202. ToolParamterValidationError
  203. ) as e:
  204. error_response = f"tool paramters validation error: {e}, please check your tool paramters"
  205. except ToolInvokeError as e:
  206. error_response = f"tool invoke error: {e}"
  207. except Exception as e:
  208. error_response = f"unknown error: {e}"
  209. if error_response:
  210. observation = error_response
  211. logger.error(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'],
  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:
  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_strachpad_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) + "\n"
  417. return result
  418. def _originze_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. originze 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. # originze 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 + "\n" + agent_scratchpad[-1].observation
  471. ))
  472. # add user message
  473. if len(agent_scratchpad) > 0:
  474. prompt_messages.append(UserPromptMessage(
  475. content=input,
  476. ))
  477. return prompt_messages
  478. elif mode == "completion":
  479. # parse agent scratchpad
  480. agent_scratchpad_str = self._convert_strachpad_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)