assistant_fc_runner.py 18 KB

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