cot_completion_agent_runner.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import json
  2. from typing import Optional
  3. from core.agent.cot_agent_runner import CotAgentRunner
  4. from core.model_runtime.entities.message_entities import AssistantPromptMessage, PromptMessage, UserPromptMessage
  5. from core.model_runtime.utils.encoders import jsonable_encoder
  6. class CotCompletionAgentRunner(CotAgentRunner):
  7. def _organize_instruction_prompt(self) -> str:
  8. """
  9. Organize instruction prompt
  10. """
  11. prompt_entity = self.app_config.agent.prompt
  12. first_prompt = prompt_entity.first_prompt
  13. system_prompt = (
  14. first_prompt.replace("{{instruction}}", self._instruction)
  15. .replace("{{tools}}", json.dumps(jsonable_encoder(self._prompt_messages_tools)))
  16. .replace("{{tool_names}}", ", ".join([tool.name for tool in self._prompt_messages_tools]))
  17. )
  18. return system_prompt
  19. def _organize_historic_prompt(self, current_session_messages: Optional[list[PromptMessage]] = None) -> str:
  20. """
  21. Organize historic prompt
  22. """
  23. historic_prompt_messages = self._organize_historic_prompt_messages(current_session_messages)
  24. historic_prompt = ""
  25. for message in historic_prompt_messages:
  26. if isinstance(message, UserPromptMessage):
  27. historic_prompt += f"Question: {message.content}\n\n"
  28. elif isinstance(message, AssistantPromptMessage):
  29. historic_prompt += message.content + "\n\n"
  30. return historic_prompt
  31. def _organize_prompt_messages(self) -> list[PromptMessage]:
  32. """
  33. Organize prompt messages
  34. """
  35. # organize system prompt
  36. system_prompt = self._organize_instruction_prompt()
  37. # organize historic prompt messages
  38. historic_prompt = self._organize_historic_prompt()
  39. # organize current assistant messages
  40. agent_scratchpad = self._agent_scratchpad
  41. assistant_prompt = ""
  42. for unit in agent_scratchpad:
  43. if unit.is_final():
  44. assistant_prompt += f"Final Answer: {unit.agent_response}"
  45. else:
  46. assistant_prompt += f"Thought: {unit.thought}\n\n"
  47. if unit.action_str:
  48. assistant_prompt += f"Action: {unit.action_str}\n\n"
  49. if unit.observation:
  50. assistant_prompt += f"Observation: {unit.observation}\n\n"
  51. # query messages
  52. query_prompt = f"Question: {self._query}"
  53. # join all messages
  54. prompt = (
  55. system_prompt.replace("{{historic_messages}}", historic_prompt)
  56. .replace("{{agent_scratchpad}}", assistant_prompt)
  57. .replace("{{query}}", query_prompt)
  58. )
  59. return [UserPromptMessage(content=prompt)]