assistant_fc_runner.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. import json
  2. import logging
  3. from typing import Union, Generator, Dict, Any, Tuple, List
  4. from core.model_runtime.entities.message_entities import PromptMessage, UserPromptMessage,\
  5. SystemPromptMessage, AssistantPromptMessage, ToolPromptMessage, PromptMessageTool
  6. from core.model_runtime.entities.llm_entities import LLMResultChunk, LLMResult, LLMUsage, LLMResultChunkDelta
  7. from core.model_manager import ModelInstance
  8. from core.application_queue_manager import PublishFrom
  9. from core.tools.errors import ToolInvokeError, ToolNotFoundError, \
  10. ToolNotSupportedError, ToolProviderNotFoundError, ToolParameterValidationError, \
  11. ToolProviderCredentialValidationError
  12. from core.features.assistant_base_runner import BaseAssistantApplicationRunner
  13. from models.model import Conversation, Message, MessageAgentThought
  14. logger = logging.getLogger(__name__)
  15. class AssistantFunctionCallApplicationRunner(BaseAssistantApplicationRunner):
  16. def run(self, conversation: Conversation,
  17. message: Message,
  18. query: str,
  19. ) -> Generator[LLMResultChunk, None, None]:
  20. """
  21. Run FunctionCall agent application
  22. """
  23. app_orchestration_config = self.app_orchestration_config
  24. prompt_template = self.app_orchestration_config.prompt_template.simple_prompt_template or ''
  25. prompt_messages = self.history_prompt_messages
  26. prompt_messages = self.organize_prompt_messages(
  27. prompt_template=prompt_template,
  28. query=query,
  29. prompt_messages=prompt_messages
  30. )
  31. # convert tools into ModelRuntime Tool format
  32. prompt_messages_tools: List[PromptMessageTool] = []
  33. tool_instances = {}
  34. for tool in self.app_orchestration_config.agent.tools if self.app_orchestration_config.agent else []:
  35. try:
  36. prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
  37. except Exception:
  38. # api tool may be deleted
  39. continue
  40. # save tool entity
  41. tool_instances[tool.tool_name] = tool_entity
  42. # save prompt tool
  43. prompt_messages_tools.append(prompt_tool)
  44. # convert dataset tools into ModelRuntime Tool format
  45. for dataset_tool in self.dataset_tools:
  46. prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
  47. # save prompt tool
  48. prompt_messages_tools.append(prompt_tool)
  49. # save tool entity
  50. tool_instances[dataset_tool.identity.name] = dataset_tool
  51. iteration_step = 1
  52. max_iteration_steps = min(app_orchestration_config.agent.max_iteration, 5) + 1
  53. # continue to run until there is not any tool call
  54. function_call_state = True
  55. agent_thoughts: List[MessageAgentThought] = []
  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. function_call_state = False
  72. if iteration_step == max_iteration_steps:
  73. # the last iteration, remove all tools
  74. 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. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  84. # recale llm max tokens
  85. self.recale_llm_max_tokens(self.model_config, prompt_messages)
  86. # invoke model
  87. chunks: Union[Generator[LLMResultChunk, None, None], LLMResult] = model_instance.invoke_llm(
  88. prompt_messages=prompt_messages,
  89. model_parameters=app_orchestration_config.model_config.parameters,
  90. tools=prompt_messages_tools,
  91. stop=app_orchestration_config.model_config.stop,
  92. stream=self.stream_tool_call,
  93. user=self.user_id,
  94. callbacks=[],
  95. )
  96. tool_calls: List[Tuple[str, str, Dict[str, Any]]] = []
  97. # save full response
  98. response = ''
  99. # save tool call names and inputs
  100. tool_call_names = ''
  101. tool_call_inputs = ''
  102. current_llm_usage = None
  103. if self.stream_tool_call:
  104. for chunk in chunks:
  105. # check if there is any tool call
  106. if self.check_tool_calls(chunk):
  107. function_call_state = True
  108. tool_calls.extend(self.extract_tool_calls(chunk))
  109. tool_call_names = ';'.join([tool_call[1] for tool_call in tool_calls])
  110. try:
  111. tool_call_inputs = json.dumps({
  112. tool_call[1]: tool_call[2] for tool_call in tool_calls
  113. }, ensure_ascii=False)
  114. except json.JSONDecodeError as e:
  115. # ensure ascii to avoid encoding error
  116. tool_call_inputs = json.dumps({
  117. tool_call[1]: tool_call[2] for tool_call in tool_calls
  118. })
  119. if chunk.delta.message and chunk.delta.message.content:
  120. if isinstance(chunk.delta.message.content, list):
  121. for content in chunk.delta.message.content:
  122. response += content.data
  123. else:
  124. response += chunk.delta.message.content
  125. if chunk.delta.usage:
  126. increase_usage(llm_usage, chunk.delta.usage)
  127. current_llm_usage = chunk.delta.usage
  128. yield chunk
  129. else:
  130. result: LLMResult = chunks
  131. # check if there is any tool call
  132. if self.check_blocking_tool_calls(result):
  133. function_call_state = True
  134. tool_calls.extend(self.extract_blocking_tool_calls(result))
  135. tool_call_names = ';'.join([tool_call[1] for tool_call in tool_calls])
  136. try:
  137. tool_call_inputs = json.dumps({
  138. tool_call[1]: tool_call[2] for tool_call in tool_calls
  139. }, ensure_ascii=False)
  140. except json.JSONDecodeError as e:
  141. # ensure ascii to avoid encoding error
  142. tool_call_inputs = json.dumps({
  143. tool_call[1]: tool_call[2] for tool_call in tool_calls
  144. })
  145. if result.usage:
  146. increase_usage(llm_usage, result.usage)
  147. current_llm_usage = result.usage
  148. if result.message and result.message.content:
  149. if isinstance(result.message.content, list):
  150. for content in result.message.content:
  151. response += content.data
  152. else:
  153. response += result.message.content
  154. if not result.message.content:
  155. result.message.content = ''
  156. yield LLMResultChunk(
  157. model=model_instance.model,
  158. prompt_messages=result.prompt_messages,
  159. system_fingerprint=result.system_fingerprint,
  160. delta=LLMResultChunkDelta(
  161. index=0,
  162. message=result.message,
  163. usage=result.usage,
  164. )
  165. )
  166. if tool_calls:
  167. prompt_messages.append(AssistantPromptMessage(
  168. content='',
  169. name='',
  170. tool_calls=[AssistantPromptMessage.ToolCall(
  171. id=tool_call[0],
  172. type='function',
  173. function=AssistantPromptMessage.ToolCall.ToolCallFunction(
  174. name=tool_call[1],
  175. arguments=json.dumps(tool_call[2], ensure_ascii=False)
  176. )
  177. ) for tool_call in tool_calls]
  178. ))
  179. # save thought
  180. self.save_agent_thought(
  181. agent_thought=agent_thought,
  182. tool_name=tool_call_names,
  183. tool_input=tool_call_inputs,
  184. thought=response,
  185. observation=None,
  186. answer=response,
  187. messages_ids=[],
  188. llm_usage=current_llm_usage
  189. )
  190. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  191. final_answer += response + '\n'
  192. # update prompt messages
  193. if response.strip():
  194. prompt_messages.append(AssistantPromptMessage(
  195. content=response,
  196. ))
  197. # call tools
  198. tool_responses = []
  199. for tool_call_id, tool_call_name, tool_call_args in tool_calls:
  200. tool_instance = tool_instances.get(tool_call_name)
  201. if not tool_instance:
  202. tool_response = {
  203. "tool_call_id": tool_call_id,
  204. "tool_call_name": tool_call_name,
  205. "tool_response": f"there is not a tool named {tool_call_name}"
  206. }
  207. tool_responses.append(tool_response)
  208. else:
  209. # invoke tool
  210. error_response = None
  211. try:
  212. tool_invoke_message = tool_instance.invoke(
  213. user_id=self.user_id,
  214. tool_parameters=tool_call_args,
  215. )
  216. # transform tool invoke message to get LLM friendly message
  217. tool_invoke_message = self.transform_tool_invoke_messages(tool_invoke_message)
  218. # extract binary data from tool invoke message
  219. binary_files = self.extract_tool_response_binary(tool_invoke_message)
  220. # create message file
  221. message_files = self.create_message_files(binary_files)
  222. # publish files
  223. for message_file, save_as in message_files:
  224. if save_as:
  225. self.variables_pool.set_file(tool_name=tool_call_name, value=message_file.id, name=save_as)
  226. # publish message file
  227. self.queue_manager.publish_message_file(message_file, PublishFrom.APPLICATION_MANAGER)
  228. # add message file ids
  229. message_file_ids.append(message_file.id)
  230. except ToolProviderCredentialValidationError as e:
  231. error_response = f"Plese check your tool provider credentials"
  232. except (
  233. ToolNotFoundError, ToolNotSupportedError, ToolProviderNotFoundError
  234. ) as e:
  235. error_response = f"there is not a tool named {tool_call_name}"
  236. except (
  237. ToolParameterValidationError
  238. ) as e:
  239. error_response = f"tool parameters validation error: {e}, please check your tool parameters"
  240. except ToolInvokeError as e:
  241. error_response = f"tool invoke error: {e}"
  242. except Exception as e:
  243. error_response = f"unknown error: {e}"
  244. if error_response:
  245. observation = error_response
  246. tool_response = {
  247. "tool_call_id": tool_call_id,
  248. "tool_call_name": tool_call_name,
  249. "tool_response": error_response
  250. }
  251. tool_responses.append(tool_response)
  252. else:
  253. observation = self._convert_tool_response_to_str(tool_invoke_message)
  254. tool_response = {
  255. "tool_call_id": tool_call_id,
  256. "tool_call_name": tool_call_name,
  257. "tool_response": observation
  258. }
  259. tool_responses.append(tool_response)
  260. prompt_messages = self.organize_prompt_messages(
  261. prompt_template=prompt_template,
  262. query=None,
  263. tool_call_id=tool_call_id,
  264. tool_call_name=tool_call_name,
  265. tool_response=tool_response['tool_response'],
  266. prompt_messages=prompt_messages,
  267. )
  268. if len(tool_responses) > 0:
  269. # save agent thought
  270. self.save_agent_thought(
  271. agent_thought=agent_thought,
  272. tool_name=None,
  273. tool_input=None,
  274. thought=None,
  275. observation=tool_response['tool_response'],
  276. answer=None,
  277. messages_ids=message_file_ids
  278. )
  279. self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
  280. # update prompt tool
  281. for prompt_tool in prompt_messages_tools:
  282. self.update_prompt_message_tool(tool_instances[prompt_tool.name], prompt_tool)
  283. iteration_step += 1
  284. self.update_db_variables(self.variables_pool, self.db_variables_pool)
  285. # publish end event
  286. self.queue_manager.publish_message_end(LLMResult(
  287. model=model_instance.model,
  288. prompt_messages=prompt_messages,
  289. message=AssistantPromptMessage(
  290. content=final_answer,
  291. ),
  292. usage=llm_usage['usage'] if llm_usage['usage'] else LLMUsage.empty_usage(),
  293. system_fingerprint=''
  294. ), PublishFrom.APPLICATION_MANAGER)
  295. def check_tool_calls(self, llm_result_chunk: LLMResultChunk) -> bool:
  296. """
  297. Check if there is any tool call in llm result chunk
  298. """
  299. if llm_result_chunk.delta.message.tool_calls:
  300. return True
  301. return False
  302. def check_blocking_tool_calls(self, llm_result: LLMResult) -> bool:
  303. """
  304. Check if there is any blocking tool call in llm result
  305. """
  306. if llm_result.message.tool_calls:
  307. return True
  308. return False
  309. def extract_tool_calls(self, llm_result_chunk: LLMResultChunk) -> Union[None, List[Tuple[str, str, Dict[str, Any]]]]:
  310. """
  311. Extract tool calls from llm result chunk
  312. Returns:
  313. List[Tuple[str, str, Dict[str, Any]]]: [(tool_call_id, tool_call_name, tool_call_args)]
  314. """
  315. tool_calls = []
  316. for prompt_message in llm_result_chunk.delta.message.tool_calls:
  317. tool_calls.append((
  318. prompt_message.id,
  319. prompt_message.function.name,
  320. json.loads(prompt_message.function.arguments),
  321. ))
  322. return tool_calls
  323. def extract_blocking_tool_calls(self, llm_result: LLMResult) -> Union[None, List[Tuple[str, str, Dict[str, Any]]]]:
  324. """
  325. Extract blocking tool calls from llm result
  326. Returns:
  327. List[Tuple[str, str, Dict[str, Any]]]: [(tool_call_id, tool_call_name, tool_call_args)]
  328. """
  329. tool_calls = []
  330. for prompt_message in llm_result.message.tool_calls:
  331. tool_calls.append((
  332. prompt_message.id,
  333. prompt_message.function.name,
  334. json.loads(prompt_message.function.arguments),
  335. ))
  336. return tool_calls
  337. def organize_prompt_messages(self, prompt_template: str,
  338. query: str = None,
  339. tool_call_id: str = None, tool_call_name: str = None, tool_response: str = None,
  340. prompt_messages: list[PromptMessage] = None
  341. ) -> list[PromptMessage]:
  342. """
  343. Organize prompt messages
  344. """
  345. if not prompt_messages:
  346. prompt_messages = [
  347. SystemPromptMessage(content=prompt_template),
  348. UserPromptMessage(content=query),
  349. ]
  350. else:
  351. if tool_response:
  352. prompt_messages = prompt_messages.copy()
  353. prompt_messages.append(
  354. ToolPromptMessage(
  355. content=tool_response,
  356. tool_call_id=tool_call_id,
  357. name=tool_call_name,
  358. )
  359. )
  360. return prompt_messages