agent_service.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. import threading
  2. import pytz
  3. from flask_login import current_user
  4. import contexts
  5. from core.app.app_config.easy_ui_based_app.agent.manager import AgentConfigManager
  6. from core.tools.tool_manager import ToolManager
  7. from extensions.ext_database import db
  8. from models.account import Account
  9. from models.model import App, Conversation, EndUser, Message, MessageAgentThought
  10. class AgentService:
  11. @classmethod
  12. def get_agent_logs(cls, app_model: App, conversation_id: str, message_id: str) -> dict:
  13. """
  14. Service to get agent logs
  15. """
  16. contexts.plugin_tool_providers.set({})
  17. contexts.plugin_tool_providers_lock.set(threading.Lock())
  18. conversation: Conversation = (
  19. db.session.query(Conversation)
  20. .filter(
  21. Conversation.id == conversation_id,
  22. Conversation.app_id == app_model.id,
  23. )
  24. .first()
  25. )
  26. if not conversation:
  27. raise ValueError(f"Conversation not found: {conversation_id}")
  28. message: Message = (
  29. db.session.query(Message)
  30. .filter(
  31. Message.id == message_id,
  32. Message.conversation_id == conversation_id,
  33. )
  34. .first()
  35. )
  36. if not message:
  37. raise ValueError(f"Message not found: {message_id}")
  38. agent_thoughts: list[MessageAgentThought] = message.agent_thoughts
  39. if conversation.from_end_user_id:
  40. # only select name field
  41. executor = (
  42. db.session.query(EndUser, EndUser.name).filter(EndUser.id == conversation.from_end_user_id).first()
  43. )
  44. else:
  45. executor = (
  46. db.session.query(Account, Account.name).filter(Account.id == conversation.from_account_id).first()
  47. )
  48. if executor:
  49. executor = executor.name
  50. else:
  51. executor = "Unknown"
  52. timezone = pytz.timezone(current_user.timezone)
  53. result = {
  54. "meta": {
  55. "status": "success",
  56. "executor": executor,
  57. "start_time": message.created_at.astimezone(timezone).isoformat(),
  58. "elapsed_time": message.provider_response_latency,
  59. "total_tokens": message.answer_tokens + message.message_tokens,
  60. "agent_mode": app_model.app_model_config.agent_mode_dict.get("strategy", "react"),
  61. "iterations": len(agent_thoughts),
  62. },
  63. "iterations": [],
  64. "files": message.message_files,
  65. }
  66. agent_config = AgentConfigManager.convert(app_model.app_model_config.to_dict())
  67. agent_tools = agent_config.tools
  68. def find_agent_tool(tool_name: str):
  69. for agent_tool in agent_tools:
  70. if agent_tool.tool_name == tool_name:
  71. return agent_tool
  72. for agent_thought in agent_thoughts:
  73. tools = agent_thought.tools
  74. tool_labels = agent_thought.tool_labels
  75. tool_meta = agent_thought.tool_meta
  76. tool_inputs = agent_thought.tool_inputs_dict
  77. tool_outputs = agent_thought.tool_outputs_dict
  78. tool_calls = []
  79. for tool in tools:
  80. tool_name = tool
  81. tool_label = tool_labels.get(tool_name, tool_name)
  82. tool_input = tool_inputs.get(tool_name, {})
  83. tool_output = tool_outputs.get(tool_name, {})
  84. tool_meta_data = tool_meta.get(tool_name, {})
  85. tool_config = tool_meta_data.get("tool_config", {})
  86. if tool_config.get("tool_provider_type", "") != "dataset-retrieval":
  87. tool_icon = ToolManager.get_tool_icon(
  88. tenant_id=app_model.tenant_id,
  89. provider_type=tool_config.get("tool_provider_type", ""),
  90. provider_id=tool_config.get("tool_provider", ""),
  91. )
  92. if not tool_icon:
  93. tool_entity = find_agent_tool(tool_name)
  94. if tool_entity:
  95. tool_icon = ToolManager.get_tool_icon(
  96. tenant_id=app_model.tenant_id,
  97. provider_type=tool_entity.provider_type,
  98. provider_id=tool_entity.provider_id,
  99. )
  100. else:
  101. tool_icon = ""
  102. tool_calls.append(
  103. {
  104. "status": "success" if not tool_meta_data.get("error") else "error",
  105. "error": tool_meta_data.get("error"),
  106. "time_cost": tool_meta_data.get("time_cost", 0),
  107. "tool_name": tool_name,
  108. "tool_label": tool_label,
  109. "tool_input": tool_input,
  110. "tool_output": tool_output,
  111. "tool_parameters": tool_meta_data.get("tool_parameters", {}),
  112. "tool_icon": tool_icon,
  113. }
  114. )
  115. result["iterations"].append(
  116. {
  117. "tokens": agent_thought.tokens,
  118. "tool_calls": tool_calls,
  119. "tool_raw": {
  120. "inputs": agent_thought.tool_input,
  121. "outputs": agent_thought.observation,
  122. },
  123. "thought": agent_thought.thought,
  124. "created_at": agent_thought.created_at.isoformat(),
  125. "files": agent_thought.files,
  126. }
  127. )
  128. return result