cot_agent_runner.py 29 KB

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