agent_service.py 6.4 KB

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