cot_agent_runner.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690
  1. import json
  2. import re
  3. from collections.abc import Generator
  4. from typing import Literal, Union
  5. from core.agent.base_agent_runner import BaseAgentRunner
  6. from core.agent.entities import AgentPromptEntity, AgentScratchpadUnit
  7. from core.app.apps.base_app_queue_manager import PublishFrom
  8. from core.app.entities.queue_entities import QueueAgentThoughtEvent, QueueMessageEndEvent, QueueMessageFileEvent
  9. from core.model_runtime.entities.llm_entities import LLMResult, LLMResultChunk, LLMResultChunkDelta, LLMUsage
  10. from core.model_runtime.entities.message_entities import (
  11. AssistantPromptMessage,
  12. PromptMessage,
  13. PromptMessageTool,
  14. SystemPromptMessage,
  15. ToolPromptMessage,
  16. UserPromptMessage,
  17. )
  18. from core.model_runtime.utils.encoders import jsonable_encoder
  19. from core.tools.entities.tool_entities import ToolInvokeMeta
  20. from core.tools.tool_engine import ToolEngine
  21. from models.model import Conversation, Message
  22. class CotAgentRunner(BaseAgentRunner):
  23. _is_first_iteration = True
  24. _ignore_observation_providers = ['wenxin']
  25. def run(self, conversation: Conversation,
  26. message: Message,
  27. query: str,
  28. inputs: dict[str, str],
  29. ) -> Union[Generator, LLMResult]:
  30. """
  31. Run Cot agent application
  32. """
  33. app_generate_entity = self.application_generate_entity
  34. self._repack_app_generate_entity(app_generate_entity)
  35. agent_scratchpad: list[AgentScratchpadUnit] = []
  36. self._init_agent_scratchpad(agent_scratchpad, self.history_prompt_messages)
  37. # check model mode
  38. if 'Observation' not in app_generate_entity.model_config.stop:
  39. if app_generate_entity.model_config.provider not in self._ignore_observation_providers:
  40. app_generate_entity.model_config.stop.append('Observation')
  41. app_config = self.app_config
  42. # override inputs
  43. inputs = inputs or {}
  44. instruction = app_config.prompt_template.simple_prompt_template
  45. instruction = self._fill_in_inputs_from_external_data_tools(instruction, inputs)
  46. iteration_step = 1
  47. max_iteration_steps = min(app_config.agent.max_iteration, 5) + 1
  48. prompt_messages = self.history_prompt_messages
  49. # convert tools into ModelRuntime Tool format
  50. prompt_messages_tools: list[PromptMessageTool] = []
  51. tool_instances = {}
  52. for tool in app_config.agent.tools if app_config.agent else []:
  53. try:
  54. prompt_tool, tool_entity = self._convert_tool_to_prompt_message_tool(tool)
  55. except Exception:
  56. # api tool may be deleted
  57. continue
  58. # save tool entity
  59. tool_instances[tool.tool_name] = tool_entity
  60. # save prompt tool
  61. prompt_messages_tools.append(prompt_tool)
  62. # convert dataset tools into ModelRuntime Tool format
  63. for dataset_tool in self.dataset_tools:
  64. prompt_tool = self._convert_dataset_retriever_tool_to_prompt_message_tool(dataset_tool)
  65. # save prompt tool
  66. prompt_messages_tools.append(prompt_tool)
  67. # save tool entity
  68. tool_instances[dataset_tool.identity.name] = dataset_tool
  69. function_call_state = True
  70. llm_usage = {
  71. 'usage': None
  72. }
  73. final_answer = ''
  74. def increase_usage(final_llm_usage_dict: dict[str, LLMUsage], usage: LLMUsage):
  75. if not final_llm_usage_dict['usage']:
  76. final_llm_usage_dict['usage'] = usage
  77. else:
  78. llm_usage = final_llm_usage_dict['usage']
  79. llm_usage.prompt_tokens += usage.prompt_tokens
  80. llm_usage.completion_tokens += usage.completion_tokens
  81. llm_usage.prompt_price += usage.prompt_price
  82. llm_usage.completion_price += usage.completion_price
  83. model_instance = self.model_instance
  84. while function_call_state and iteration_step <= max_iteration_steps:
  85. # continue to run until there is not any tool call
  86. function_call_state = False
  87. if iteration_step == max_iteration_steps:
  88. # the last iteration, remove all tools
  89. prompt_messages_tools = []
  90. message_file_ids = []
  91. agent_thought = self.create_agent_thought(
  92. message_id=message.id,
  93. message='',
  94. tool_name='',
  95. tool_input='',
  96. messages_ids=message_file_ids
  97. )
  98. if iteration_step > 1:
  99. self.queue_manager.publish(QueueAgentThoughtEvent(
  100. agent_thought_id=agent_thought.id
  101. ), PublishFrom.APPLICATION_MANAGER)
  102. # update prompt messages
  103. prompt_messages = self._organize_cot_prompt_messages(
  104. mode=app_generate_entity.model_config.mode,
  105. prompt_messages=prompt_messages,
  106. tools=prompt_messages_tools,
  107. agent_scratchpad=agent_scratchpad,
  108. agent_prompt_message=app_config.agent.prompt,
  109. instruction=instruction,
  110. input=query
  111. )
  112. # recalc llm max tokens
  113. self.recalc_llm_max_tokens(self.model_config, prompt_messages)
  114. # invoke model
  115. chunks: Generator[LLMResultChunk, None, None] = model_instance.invoke_llm(
  116. prompt_messages=prompt_messages,
  117. model_parameters=app_generate_entity.model_config.parameters,
  118. tools=[],
  119. stop=app_generate_entity.model_config.stop,
  120. stream=True,
  121. user=self.user_id,
  122. callbacks=[],
  123. )
  124. # check llm result
  125. if not chunks:
  126. raise ValueError("failed to invoke llm")
  127. usage_dict = {}
  128. react_chunks = self._handle_stream_react(chunks, usage_dict)
  129. scratchpad = AgentScratchpadUnit(
  130. agent_response='',
  131. thought='',
  132. action_str='',
  133. observation='',
  134. action=None,
  135. )
  136. # publish agent thought if it's first iteration
  137. if iteration_step == 1:
  138. self.queue_manager.publish(QueueAgentThoughtEvent(
  139. agent_thought_id=agent_thought.id
  140. ), PublishFrom.APPLICATION_MANAGER)
  141. for chunk in react_chunks:
  142. if isinstance(chunk, dict):
  143. scratchpad.agent_response += json.dumps(chunk)
  144. try:
  145. if scratchpad.action:
  146. raise Exception("")
  147. scratchpad.action_str = json.dumps(chunk)
  148. scratchpad.action = AgentScratchpadUnit.Action(
  149. action_name=chunk['action'],
  150. action_input=chunk['action_input']
  151. )
  152. except:
  153. scratchpad.thought += json.dumps(chunk)
  154. yield LLMResultChunk(
  155. model=self.model_config.model,
  156. prompt_messages=prompt_messages,
  157. system_fingerprint='',
  158. delta=LLMResultChunkDelta(
  159. index=0,
  160. message=AssistantPromptMessage(
  161. content=json.dumps(chunk, ensure_ascii=False) # if ensure_ascii=True, the text in webui maybe garbled text
  162. ),
  163. usage=None
  164. )
  165. )
  166. else:
  167. scratchpad.agent_response += chunk
  168. scratchpad.thought += chunk
  169. yield LLMResultChunk(
  170. model=self.model_config.model,
  171. prompt_messages=prompt_messages,
  172. system_fingerprint='',
  173. delta=LLMResultChunkDelta(
  174. index=0,
  175. message=AssistantPromptMessage(
  176. content=chunk
  177. ),
  178. usage=None
  179. )
  180. )
  181. scratchpad.thought = scratchpad.thought.strip() or 'I am thinking about how to help you'
  182. agent_scratchpad.append(scratchpad)
  183. # get llm usage
  184. if 'usage' in usage_dict:
  185. increase_usage(llm_usage, usage_dict['usage'])
  186. else:
  187. usage_dict['usage'] = LLMUsage.empty_usage()
  188. self.save_agent_thought(agent_thought=agent_thought,
  189. tool_name=scratchpad.action.action_name if scratchpad.action else '',
  190. tool_input={
  191. scratchpad.action.action_name: scratchpad.action.action_input
  192. } if scratchpad.action else '',
  193. tool_invoke_meta={},
  194. thought=scratchpad.thought,
  195. observation='',
  196. answer=scratchpad.agent_response,
  197. messages_ids=[],
  198. llm_usage=usage_dict['usage'])
  199. if scratchpad.action and scratchpad.action.action_name.lower() != "final answer":
  200. self.queue_manager.publish(QueueAgentThoughtEvent(
  201. agent_thought_id=agent_thought.id
  202. ), PublishFrom.APPLICATION_MANAGER)
  203. if not scratchpad.action:
  204. # failed to extract action, return final answer directly
  205. final_answer = scratchpad.agent_response or ''
  206. else:
  207. if scratchpad.action.action_name.lower() == "final answer":
  208. # action is final answer, return final answer directly
  209. try:
  210. final_answer = scratchpad.action.action_input if \
  211. isinstance(scratchpad.action.action_input, str) else \
  212. json.dumps(scratchpad.action.action_input)
  213. except json.JSONDecodeError:
  214. final_answer = f'{scratchpad.action.action_input}'
  215. else:
  216. function_call_state = True
  217. # action is tool call, invoke tool
  218. tool_call_name = scratchpad.action.action_name
  219. tool_call_args = scratchpad.action.action_input
  220. tool_instance = tool_instances.get(tool_call_name)
  221. if not tool_instance:
  222. answer = f"there is not a tool named {tool_call_name}"
  223. self.save_agent_thought(
  224. agent_thought=agent_thought,
  225. tool_name='',
  226. tool_input='',
  227. tool_invoke_meta=ToolInvokeMeta.error_instance(
  228. f"there is not a tool named {tool_call_name}"
  229. ).to_dict(),
  230. thought=None,
  231. observation={
  232. tool_call_name: answer
  233. },
  234. answer=answer,
  235. messages_ids=[]
  236. )
  237. self.queue_manager.publish(QueueAgentThoughtEvent(
  238. agent_thought_id=agent_thought.id
  239. ), PublishFrom.APPLICATION_MANAGER)
  240. else:
  241. if isinstance(tool_call_args, str):
  242. try:
  243. tool_call_args = json.loads(tool_call_args)
  244. except json.JSONDecodeError:
  245. pass
  246. # invoke tool
  247. tool_invoke_response, message_files, tool_invoke_meta = ToolEngine.agent_invoke(
  248. tool=tool_instance,
  249. tool_parameters=tool_call_args,
  250. user_id=self.user_id,
  251. tenant_id=self.tenant_id,
  252. message=self.message,
  253. invoke_from=self.application_generate_entity.invoke_from,
  254. agent_tool_callback=self.agent_callback
  255. )
  256. # publish files
  257. for message_file, save_as in message_files:
  258. if save_as:
  259. self.variables_pool.set_file(tool_name=tool_call_name, value=message_file.id, name=save_as)
  260. # publish message file
  261. self.queue_manager.publish(QueueMessageFileEvent(
  262. message_file_id=message_file.id
  263. ), PublishFrom.APPLICATION_MANAGER)
  264. # add message file ids
  265. message_file_ids.append(message_file.id)
  266. # publish files
  267. for message_file, save_as in message_files:
  268. if save_as:
  269. self.variables_pool.set_file(tool_name=tool_call_name,
  270. value=message_file.id,
  271. name=save_as)
  272. self.queue_manager.publish(QueueMessageFileEvent(
  273. message_file_id=message_file.id
  274. ), PublishFrom.APPLICATION_MANAGER)
  275. message_file_ids = [message_file.id for message_file, _ in message_files]
  276. observation = tool_invoke_response
  277. # save scratchpad
  278. scratchpad.observation = observation
  279. # save agent thought
  280. self.save_agent_thought(
  281. agent_thought=agent_thought,
  282. tool_name=tool_call_name,
  283. tool_input={
  284. tool_call_name: tool_call_args
  285. },
  286. tool_invoke_meta={
  287. tool_call_name: tool_invoke_meta.to_dict()
  288. },
  289. thought=None,
  290. observation={
  291. tool_call_name: observation
  292. },
  293. answer=scratchpad.agent_response,
  294. messages_ids=message_file_ids,
  295. )
  296. self.queue_manager.publish(QueueAgentThoughtEvent(
  297. agent_thought_id=agent_thought.id
  298. ), PublishFrom.APPLICATION_MANAGER)
  299. # update prompt tool message
  300. for prompt_tool in prompt_messages_tools:
  301. self.update_prompt_message_tool(tool_instances[prompt_tool.name], prompt_tool)
  302. iteration_step += 1
  303. yield LLMResultChunk(
  304. model=model_instance.model,
  305. prompt_messages=prompt_messages,
  306. delta=LLMResultChunkDelta(
  307. index=0,
  308. message=AssistantPromptMessage(
  309. content=final_answer
  310. ),
  311. usage=llm_usage['usage']
  312. ),
  313. system_fingerprint=''
  314. )
  315. # save agent thought
  316. self.save_agent_thought(
  317. agent_thought=agent_thought,
  318. tool_name='',
  319. tool_input={},
  320. tool_invoke_meta={},
  321. thought=final_answer,
  322. observation={},
  323. answer=final_answer,
  324. messages_ids=[]
  325. )
  326. self.update_db_variables(self.variables_pool, self.db_variables_pool)
  327. # publish end event
  328. self.queue_manager.publish(QueueMessageEndEvent(llm_result=LLMResult(
  329. model=model_instance.model,
  330. prompt_messages=prompt_messages,
  331. message=AssistantPromptMessage(
  332. content=final_answer
  333. ),
  334. usage=llm_usage['usage'] if llm_usage['usage'] else LLMUsage.empty_usage(),
  335. system_fingerprint=''
  336. )), PublishFrom.APPLICATION_MANAGER)
  337. def _handle_stream_react(self, llm_response: Generator[LLMResultChunk, None, None], usage: dict) \
  338. -> Generator[Union[str, dict], None, None]:
  339. def parse_json(json_str):
  340. try:
  341. return json.loads(json_str.strip())
  342. except:
  343. return json_str
  344. def extra_json_from_code_block(code_block) -> Generator[Union[dict, str], None, None]:
  345. code_blocks = re.findall(r'```(.*?)```', code_block, re.DOTALL)
  346. if not code_blocks:
  347. return
  348. for block in code_blocks:
  349. json_text = re.sub(r'^[a-zA-Z]+\n', '', block.strip(), flags=re.MULTILINE)
  350. yield parse_json(json_text)
  351. code_block_cache = ''
  352. code_block_delimiter_count = 0
  353. in_code_block = False
  354. json_cache = ''
  355. json_quote_count = 0
  356. in_json = False
  357. got_json = False
  358. for response in llm_response:
  359. response = response.delta.message.content
  360. if not isinstance(response, str):
  361. continue
  362. # stream
  363. index = 0
  364. while index < len(response):
  365. steps = 1
  366. delta = response[index:index+steps]
  367. if delta == '`':
  368. code_block_cache += delta
  369. code_block_delimiter_count += 1
  370. else:
  371. if not in_code_block:
  372. if code_block_delimiter_count > 0:
  373. yield code_block_cache
  374. code_block_cache = ''
  375. else:
  376. code_block_cache += delta
  377. code_block_delimiter_count = 0
  378. if code_block_delimiter_count == 3:
  379. if in_code_block:
  380. yield from extra_json_from_code_block(code_block_cache)
  381. code_block_cache = ''
  382. in_code_block = not in_code_block
  383. code_block_delimiter_count = 0
  384. if not in_code_block:
  385. # handle single json
  386. if delta == '{':
  387. json_quote_count += 1
  388. in_json = True
  389. json_cache += delta
  390. elif delta == '}':
  391. json_cache += delta
  392. if json_quote_count > 0:
  393. json_quote_count -= 1
  394. if json_quote_count == 0:
  395. in_json = False
  396. got_json = True
  397. index += steps
  398. continue
  399. else:
  400. if in_json:
  401. json_cache += delta
  402. if got_json:
  403. got_json = False
  404. yield parse_json(json_cache)
  405. json_cache = ''
  406. json_quote_count = 0
  407. in_json = False
  408. if not in_code_block and not in_json:
  409. yield delta.replace('`', '')
  410. index += steps
  411. if code_block_cache:
  412. yield code_block_cache
  413. if json_cache:
  414. yield parse_json(json_cache)
  415. def _fill_in_inputs_from_external_data_tools(self, instruction: str, inputs: dict) -> str:
  416. """
  417. fill in inputs from external data tools
  418. """
  419. for key, value in inputs.items():
  420. try:
  421. instruction = instruction.replace(f'{{{{{key}}}}}', str(value))
  422. except Exception as e:
  423. continue
  424. return instruction
  425. def _init_agent_scratchpad(self,
  426. agent_scratchpad: list[AgentScratchpadUnit],
  427. messages: list[PromptMessage]
  428. ) -> list[AgentScratchpadUnit]:
  429. """
  430. init agent scratchpad
  431. """
  432. current_scratchpad: AgentScratchpadUnit = None
  433. for message in messages:
  434. if isinstance(message, AssistantPromptMessage):
  435. current_scratchpad = AgentScratchpadUnit(
  436. agent_response=message.content,
  437. thought=message.content or 'I am thinking about how to help you',
  438. action_str='',
  439. action=None,
  440. observation=None,
  441. )
  442. if message.tool_calls:
  443. try:
  444. current_scratchpad.action = AgentScratchpadUnit.Action(
  445. action_name=message.tool_calls[0].function.name,
  446. action_input=json.loads(message.tool_calls[0].function.arguments)
  447. )
  448. except:
  449. pass
  450. agent_scratchpad.append(current_scratchpad)
  451. elif isinstance(message, ToolPromptMessage):
  452. if current_scratchpad:
  453. current_scratchpad.observation = message.content
  454. return agent_scratchpad
  455. def _check_cot_prompt_messages(self, mode: Literal["completion", "chat"],
  456. agent_prompt_message: AgentPromptEntity,
  457. ):
  458. """
  459. check chain of thought prompt messages, a standard prompt message is like:
  460. Respond to the human as helpfully and accurately as possible.
  461. {{instruction}}
  462. You have access to the following tools:
  463. {{tools}}
  464. Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
  465. Valid action values: "Final Answer" or {{tool_names}}
  466. Provide only ONE action per $JSON_BLOB, as shown:
  467. ```
  468. {
  469. "action": $TOOL_NAME,
  470. "action_input": $ACTION_INPUT
  471. }
  472. ```
  473. """
  474. # parse agent prompt message
  475. first_prompt = agent_prompt_message.first_prompt
  476. next_iteration = agent_prompt_message.next_iteration
  477. if not isinstance(first_prompt, str) or not isinstance(next_iteration, str):
  478. raise ValueError("first_prompt or next_iteration is required in CoT agent mode")
  479. # check instruction, tools, and tool_names slots
  480. if not first_prompt.find("{{instruction}}") >= 0:
  481. raise ValueError("{{instruction}} is required in first_prompt")
  482. if not first_prompt.find("{{tools}}") >= 0:
  483. raise ValueError("{{tools}} is required in first_prompt")
  484. if not first_prompt.find("{{tool_names}}") >= 0:
  485. raise ValueError("{{tool_names}} is required in first_prompt")
  486. if mode == "completion":
  487. if not first_prompt.find("{{query}}") >= 0:
  488. raise ValueError("{{query}} is required in first_prompt")
  489. if not first_prompt.find("{{agent_scratchpad}}") >= 0:
  490. raise ValueError("{{agent_scratchpad}} is required in first_prompt")
  491. if mode == "completion":
  492. if not next_iteration.find("{{observation}}") >= 0:
  493. raise ValueError("{{observation}} is required in next_iteration")
  494. def _convert_scratchpad_list_to_str(self, agent_scratchpad: list[AgentScratchpadUnit]) -> str:
  495. """
  496. convert agent scratchpad list to str
  497. """
  498. next_iteration = self.app_config.agent.prompt.next_iteration
  499. result = ''
  500. for scratchpad in agent_scratchpad:
  501. result += (scratchpad.thought or '') + (scratchpad.action_str or '') + \
  502. next_iteration.replace("{{observation}}", scratchpad.observation or 'It seems that no response is available')
  503. return result
  504. def _organize_cot_prompt_messages(self, mode: Literal["completion", "chat"],
  505. prompt_messages: list[PromptMessage],
  506. tools: list[PromptMessageTool],
  507. agent_scratchpad: list[AgentScratchpadUnit],
  508. agent_prompt_message: AgentPromptEntity,
  509. instruction: str,
  510. input: str,
  511. ) -> list[PromptMessage]:
  512. """
  513. organize chain of thought prompt messages, a standard prompt message is like:
  514. Respond to the human as helpfully and accurately as possible.
  515. {{instruction}}
  516. You have access to the following tools:
  517. {{tools}}
  518. Use a json blob to specify a tool by providing an action key (tool name) and an action_input key (tool input).
  519. Valid action values: "Final Answer" or {{tool_names}}
  520. Provide only ONE action per $JSON_BLOB, as shown:
  521. ```
  522. {{{{
  523. "action": $TOOL_NAME,
  524. "action_input": $ACTION_INPUT
  525. }}}}
  526. ```
  527. """
  528. self._check_cot_prompt_messages(mode, agent_prompt_message)
  529. # parse agent prompt message
  530. first_prompt = agent_prompt_message.first_prompt
  531. # parse tools
  532. tools_str = self._jsonify_tool_prompt_messages(tools)
  533. # parse tools name
  534. tool_names = '"' + '","'.join([tool.name for tool in tools]) + '"'
  535. # get system message
  536. system_message = first_prompt.replace("{{instruction}}", instruction) \
  537. .replace("{{tools}}", tools_str) \
  538. .replace("{{tool_names}}", tool_names)
  539. # organize prompt messages
  540. if mode == "chat":
  541. # override system message
  542. overridden = False
  543. prompt_messages = prompt_messages.copy()
  544. for prompt_message in prompt_messages:
  545. if isinstance(prompt_message, SystemPromptMessage):
  546. prompt_message.content = system_message
  547. overridden = True
  548. break
  549. # convert tool prompt messages to user prompt messages
  550. for idx, prompt_message in enumerate(prompt_messages):
  551. if isinstance(prompt_message, ToolPromptMessage):
  552. prompt_messages[idx] = UserPromptMessage(
  553. content=prompt_message.content
  554. )
  555. if not overridden:
  556. prompt_messages.insert(0, SystemPromptMessage(
  557. content=system_message,
  558. ))
  559. # add assistant message
  560. if len(agent_scratchpad) > 0 and not self._is_first_iteration:
  561. prompt_messages.append(AssistantPromptMessage(
  562. content=(agent_scratchpad[-1].thought or '') + (agent_scratchpad[-1].action_str or ''),
  563. ))
  564. # add user message
  565. if len(agent_scratchpad) > 0 and not self._is_first_iteration:
  566. prompt_messages.append(UserPromptMessage(
  567. content=(agent_scratchpad[-1].observation or 'It seems that no response is available'),
  568. ))
  569. self._is_first_iteration = False
  570. return prompt_messages
  571. elif mode == "completion":
  572. # parse agent scratchpad
  573. agent_scratchpad_str = self._convert_scratchpad_list_to_str(agent_scratchpad)
  574. self._is_first_iteration = False
  575. # parse prompt messages
  576. return [UserPromptMessage(
  577. content=first_prompt.replace("{{instruction}}", instruction)
  578. .replace("{{tools}}", tools_str)
  579. .replace("{{tool_names}}", tool_names)
  580. .replace("{{query}}", input)
  581. .replace("{{agent_scratchpad}}", agent_scratchpad_str),
  582. )]
  583. else:
  584. raise ValueError(f"mode {mode} is not supported")
  585. def _jsonify_tool_prompt_messages(self, tools: list[PromptMessageTool]) -> str:
  586. """
  587. jsonify tool prompt messages
  588. """
  589. tools = jsonable_encoder(tools)
  590. try:
  591. return json.dumps(tools, ensure_ascii=False)
  592. except json.JSONDecodeError:
  593. return json.dumps(tools)