You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ops_trace_manager.py 33KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. import json
  2. import logging
  3. import os
  4. import queue
  5. import threading
  6. import time
  7. from datetime import timedelta
  8. from typing import Any, Optional, Union
  9. from uuid import UUID, uuid4
  10. from cachetools import LRUCache
  11. from flask import current_app
  12. from sqlalchemy import select
  13. from sqlalchemy.orm import Session
  14. from core.helper.encrypter import decrypt_token, encrypt_token, obfuscated_token
  15. from core.ops.entities.config_entity import (
  16. OPS_FILE_PATH,
  17. TracingProviderEnum,
  18. )
  19. from core.ops.entities.trace_entity import (
  20. DatasetRetrievalTraceInfo,
  21. GenerateNameTraceInfo,
  22. MessageTraceInfo,
  23. ModerationTraceInfo,
  24. SuggestedQuestionTraceInfo,
  25. TaskData,
  26. ToolTraceInfo,
  27. TraceTaskName,
  28. WorkflowTraceInfo,
  29. )
  30. from core.ops.utils import get_message_data
  31. from core.workflow.entities.workflow_execution import WorkflowExecution
  32. from extensions.ext_database import db
  33. from extensions.ext_storage import storage
  34. from models.model import App, AppModelConfig, Conversation, Message, MessageFile, TraceAppConfig
  35. from models.workflow import WorkflowAppLog, WorkflowRun
  36. from tasks.ops_trace_task import process_trace_tasks
  37. class OpsTraceProviderConfigMap(dict[str, dict[str, Any]]):
  38. def __getitem__(self, provider: str) -> dict[str, Any]:
  39. match provider:
  40. case TracingProviderEnum.LANGFUSE:
  41. from core.ops.entities.config_entity import LangfuseConfig
  42. from core.ops.langfuse_trace.langfuse_trace import LangFuseDataTrace
  43. return {
  44. "config_class": LangfuseConfig,
  45. "secret_keys": ["public_key", "secret_key"],
  46. "other_keys": ["host", "project_key"],
  47. "trace_instance": LangFuseDataTrace,
  48. }
  49. case TracingProviderEnum.LANGSMITH:
  50. from core.ops.entities.config_entity import LangSmithConfig
  51. from core.ops.langsmith_trace.langsmith_trace import LangSmithDataTrace
  52. return {
  53. "config_class": LangSmithConfig,
  54. "secret_keys": ["api_key"],
  55. "other_keys": ["project", "endpoint"],
  56. "trace_instance": LangSmithDataTrace,
  57. }
  58. case TracingProviderEnum.OPIK:
  59. from core.ops.entities.config_entity import OpikConfig
  60. from core.ops.opik_trace.opik_trace import OpikDataTrace
  61. return {
  62. "config_class": OpikConfig,
  63. "secret_keys": ["api_key"],
  64. "other_keys": ["project", "url", "workspace"],
  65. "trace_instance": OpikDataTrace,
  66. }
  67. case TracingProviderEnum.WEAVE:
  68. from core.ops.entities.config_entity import WeaveConfig
  69. from core.ops.weave_trace.weave_trace import WeaveDataTrace
  70. return {
  71. "config_class": WeaveConfig,
  72. "secret_keys": ["api_key"],
  73. "other_keys": ["project", "entity", "endpoint"],
  74. "trace_instance": WeaveDataTrace,
  75. }
  76. case _:
  77. raise KeyError(f"Unsupported tracing provider: {provider}")
  78. provider_config_map: dict[str, dict[str, Any]] = OpsTraceProviderConfigMap()
  79. class OpsTraceManager:
  80. ops_trace_instances_cache: LRUCache = LRUCache(maxsize=128)
  81. @classmethod
  82. def encrypt_tracing_config(
  83. cls, tenant_id: str, tracing_provider: str, tracing_config: dict, current_trace_config=None
  84. ):
  85. """
  86. Encrypt tracing config.
  87. :param tenant_id: tenant id
  88. :param tracing_provider: tracing provider
  89. :param tracing_config: tracing config dictionary to be encrypted
  90. :param current_trace_config: current tracing configuration for keeping existing values
  91. :return: encrypted tracing configuration
  92. """
  93. # Get the configuration class and the keys that require encryption
  94. config_class, secret_keys, other_keys = (
  95. provider_config_map[tracing_provider]["config_class"],
  96. provider_config_map[tracing_provider]["secret_keys"],
  97. provider_config_map[tracing_provider]["other_keys"],
  98. )
  99. new_config = {}
  100. # Encrypt necessary keys
  101. for key in secret_keys:
  102. if key in tracing_config:
  103. if "*" in tracing_config[key]:
  104. # If the key contains '*', retain the original value from the current config
  105. new_config[key] = current_trace_config.get(key, tracing_config[key])
  106. else:
  107. # Otherwise, encrypt the key
  108. new_config[key] = encrypt_token(tenant_id, tracing_config[key])
  109. for key in other_keys:
  110. new_config[key] = tracing_config.get(key, "")
  111. # Create a new instance of the config class with the new configuration
  112. encrypted_config = config_class(**new_config)
  113. return encrypted_config.model_dump()
  114. @classmethod
  115. def decrypt_tracing_config(cls, tenant_id: str, tracing_provider: str, tracing_config: dict):
  116. """
  117. Decrypt tracing config
  118. :param tenant_id: tenant id
  119. :param tracing_provider: tracing provider
  120. :param tracing_config: tracing config
  121. :return:
  122. """
  123. config_class, secret_keys, other_keys = (
  124. provider_config_map[tracing_provider]["config_class"],
  125. provider_config_map[tracing_provider]["secret_keys"],
  126. provider_config_map[tracing_provider]["other_keys"],
  127. )
  128. new_config = {}
  129. for key in secret_keys:
  130. if key in tracing_config:
  131. new_config[key] = decrypt_token(tenant_id, tracing_config[key])
  132. for key in other_keys:
  133. new_config[key] = tracing_config.get(key, "")
  134. return config_class(**new_config).model_dump()
  135. @classmethod
  136. def obfuscated_decrypt_token(cls, tracing_provider: str, decrypt_tracing_config: dict):
  137. """
  138. Decrypt tracing config
  139. :param tracing_provider: tracing provider
  140. :param decrypt_tracing_config: tracing config
  141. :return:
  142. """
  143. config_class, secret_keys, other_keys = (
  144. provider_config_map[tracing_provider]["config_class"],
  145. provider_config_map[tracing_provider]["secret_keys"],
  146. provider_config_map[tracing_provider]["other_keys"],
  147. )
  148. new_config = {}
  149. for key in secret_keys:
  150. if key in decrypt_tracing_config:
  151. new_config[key] = obfuscated_token(decrypt_tracing_config[key])
  152. for key in other_keys:
  153. new_config[key] = decrypt_tracing_config.get(key, "")
  154. return config_class(**new_config).model_dump()
  155. @classmethod
  156. def get_decrypted_tracing_config(cls, app_id: str, tracing_provider: str):
  157. """
  158. Get decrypted tracing config
  159. :param app_id: app id
  160. :param tracing_provider: tracing provider
  161. :return:
  162. """
  163. trace_config_data: Optional[TraceAppConfig] = (
  164. db.session.query(TraceAppConfig)
  165. .filter(TraceAppConfig.app_id == app_id, TraceAppConfig.tracing_provider == tracing_provider)
  166. .first()
  167. )
  168. if not trace_config_data:
  169. return None
  170. # decrypt_token
  171. app = db.session.query(App).filter(App.id == app_id).first()
  172. if not app:
  173. raise ValueError("App not found")
  174. tenant_id = app.tenant_id
  175. decrypt_tracing_config = cls.decrypt_tracing_config(
  176. tenant_id, tracing_provider, trace_config_data.tracing_config
  177. )
  178. return decrypt_tracing_config
  179. @classmethod
  180. def get_ops_trace_instance(
  181. cls,
  182. app_id: Optional[Union[UUID, str]] = None,
  183. ):
  184. """
  185. Get ops trace through model config
  186. :param app_id: app_id
  187. :return:
  188. """
  189. if isinstance(app_id, UUID):
  190. app_id = str(app_id)
  191. if app_id is None:
  192. return None
  193. app: Optional[App] = db.session.query(App).filter(App.id == app_id).first()
  194. if app is None:
  195. return None
  196. app_ops_trace_config = json.loads(app.tracing) if app.tracing else None
  197. if app_ops_trace_config is None:
  198. return None
  199. if not app_ops_trace_config.get("enabled"):
  200. return None
  201. tracing_provider = app_ops_trace_config.get("tracing_provider")
  202. if tracing_provider is None:
  203. return None
  204. try:
  205. provider_config_map[tracing_provider]
  206. except KeyError:
  207. return None
  208. # decrypt_token
  209. decrypt_trace_config = cls.get_decrypted_tracing_config(app_id, tracing_provider)
  210. if not decrypt_trace_config:
  211. return None
  212. trace_instance, config_class = (
  213. provider_config_map[tracing_provider]["trace_instance"],
  214. provider_config_map[tracing_provider]["config_class"],
  215. )
  216. decrypt_trace_config_key = str(decrypt_trace_config)
  217. tracing_instance = cls.ops_trace_instances_cache.get(decrypt_trace_config_key)
  218. if tracing_instance is None:
  219. # create new tracing_instance and update the cache if it absent
  220. tracing_instance = trace_instance(config_class(**decrypt_trace_config))
  221. cls.ops_trace_instances_cache[decrypt_trace_config_key] = tracing_instance
  222. logging.info(f"new tracing_instance for app_id: {app_id}")
  223. return tracing_instance
  224. @classmethod
  225. def get_app_config_through_message_id(cls, message_id: str):
  226. app_model_config = None
  227. message_data = db.session.query(Message).filter(Message.id == message_id).first()
  228. if not message_data:
  229. return None
  230. conversation_id = message_data.conversation_id
  231. conversation_data = db.session.query(Conversation).filter(Conversation.id == conversation_id).first()
  232. if not conversation_data:
  233. return None
  234. if conversation_data.app_model_config_id:
  235. app_model_config = (
  236. db.session.query(AppModelConfig)
  237. .filter(AppModelConfig.id == conversation_data.app_model_config_id)
  238. .first()
  239. )
  240. elif conversation_data.app_model_config_id is None and conversation_data.override_model_configs:
  241. app_model_config = conversation_data.override_model_configs
  242. return app_model_config
  243. @classmethod
  244. def update_app_tracing_config(cls, app_id: str, enabled: bool, tracing_provider: str):
  245. """
  246. Update app tracing config
  247. :param app_id: app id
  248. :param enabled: enabled
  249. :param tracing_provider: tracing provider
  250. :return:
  251. """
  252. # auth check
  253. if enabled == True:
  254. try:
  255. provider_config_map[tracing_provider]
  256. except KeyError:
  257. raise ValueError(f"Invalid tracing provider: {tracing_provider}")
  258. else:
  259. if tracing_provider is not None:
  260. raise ValueError(f"Invalid tracing provider: {tracing_provider}")
  261. app_config: Optional[App] = db.session.query(App).filter(App.id == app_id).first()
  262. if not app_config:
  263. raise ValueError("App not found")
  264. app_config.tracing = json.dumps(
  265. {
  266. "enabled": enabled,
  267. "tracing_provider": tracing_provider,
  268. }
  269. )
  270. db.session.commit()
  271. @classmethod
  272. def get_app_tracing_config(cls, app_id: str):
  273. """
  274. Get app tracing config
  275. :param app_id: app id
  276. :return:
  277. """
  278. app: Optional[App] = db.session.query(App).filter(App.id == app_id).first()
  279. if not app:
  280. raise ValueError("App not found")
  281. if not app.tracing:
  282. return {"enabled": False, "tracing_provider": None}
  283. app_trace_config = json.loads(app.tracing)
  284. return app_trace_config
  285. @staticmethod
  286. def check_trace_config_is_effective(tracing_config: dict, tracing_provider: str):
  287. """
  288. Check trace config is effective
  289. :param tracing_config: tracing config
  290. :param tracing_provider: tracing provider
  291. :return:
  292. """
  293. config_type, trace_instance = (
  294. provider_config_map[tracing_provider]["config_class"],
  295. provider_config_map[tracing_provider]["trace_instance"],
  296. )
  297. tracing_config = config_type(**tracing_config)
  298. return trace_instance(tracing_config).api_check()
  299. @staticmethod
  300. def get_trace_config_project_key(tracing_config: dict, tracing_provider: str):
  301. """
  302. get trace config is project key
  303. :param tracing_config: tracing config
  304. :param tracing_provider: tracing provider
  305. :return:
  306. """
  307. config_type, trace_instance = (
  308. provider_config_map[tracing_provider]["config_class"],
  309. provider_config_map[tracing_provider]["trace_instance"],
  310. )
  311. tracing_config = config_type(**tracing_config)
  312. return trace_instance(tracing_config).get_project_key()
  313. @staticmethod
  314. def get_trace_config_project_url(tracing_config: dict, tracing_provider: str):
  315. """
  316. get trace config is project key
  317. :param tracing_config: tracing config
  318. :param tracing_provider: tracing provider
  319. :return:
  320. """
  321. config_type, trace_instance = (
  322. provider_config_map[tracing_provider]["config_class"],
  323. provider_config_map[tracing_provider]["trace_instance"],
  324. )
  325. tracing_config = config_type(**tracing_config)
  326. return trace_instance(tracing_config).get_project_url()
  327. class TraceTask:
  328. def __init__(
  329. self,
  330. trace_type: Any,
  331. message_id: Optional[str] = None,
  332. workflow_execution: Optional[WorkflowExecution] = None,
  333. conversation_id: Optional[str] = None,
  334. user_id: Optional[str] = None,
  335. timer: Optional[Any] = None,
  336. **kwargs,
  337. ):
  338. self.trace_type = trace_type
  339. self.message_id = message_id
  340. self.workflow_run_id = workflow_execution.id_ if workflow_execution else None
  341. self.conversation_id = conversation_id
  342. self.user_id = user_id
  343. self.timer = timer
  344. self.file_base_url = os.getenv("FILES_URL", "http://127.0.0.1:5001")
  345. self.app_id = None
  346. self.kwargs = kwargs
  347. def execute(self):
  348. return self.preprocess()
  349. def preprocess(self):
  350. preprocess_map = {
  351. TraceTaskName.CONVERSATION_TRACE: lambda: self.conversation_trace(**self.kwargs),
  352. TraceTaskName.WORKFLOW_TRACE: lambda: self.workflow_trace(
  353. workflow_run_id=self.workflow_run_id, conversation_id=self.conversation_id, user_id=self.user_id
  354. ),
  355. TraceTaskName.MESSAGE_TRACE: lambda: self.message_trace(message_id=self.message_id),
  356. TraceTaskName.MODERATION_TRACE: lambda: self.moderation_trace(
  357. message_id=self.message_id, timer=self.timer, **self.kwargs
  358. ),
  359. TraceTaskName.SUGGESTED_QUESTION_TRACE: lambda: self.suggested_question_trace(
  360. message_id=self.message_id, timer=self.timer, **self.kwargs
  361. ),
  362. TraceTaskName.DATASET_RETRIEVAL_TRACE: lambda: self.dataset_retrieval_trace(
  363. message_id=self.message_id, timer=self.timer, **self.kwargs
  364. ),
  365. TraceTaskName.TOOL_TRACE: lambda: self.tool_trace(
  366. message_id=self.message_id, timer=self.timer, **self.kwargs
  367. ),
  368. TraceTaskName.GENERATE_NAME_TRACE: lambda: self.generate_name_trace(
  369. conversation_id=self.conversation_id, timer=self.timer, **self.kwargs
  370. ),
  371. }
  372. return preprocess_map.get(self.trace_type, lambda: None)()
  373. # process methods for different trace types
  374. def conversation_trace(self, **kwargs):
  375. return kwargs
  376. def workflow_trace(
  377. self,
  378. *,
  379. workflow_run_id: str | None,
  380. conversation_id: str | None,
  381. user_id: str | None,
  382. ):
  383. if not workflow_run_id:
  384. return {}
  385. with Session(db.engine) as session:
  386. workflow_run_stmt = select(WorkflowRun).where(WorkflowRun.id == workflow_run_id)
  387. workflow_run = session.scalars(workflow_run_stmt).first()
  388. if not workflow_run:
  389. raise ValueError("Workflow run not found")
  390. workflow_id = workflow_run.workflow_id
  391. tenant_id = workflow_run.tenant_id
  392. workflow_run_id = workflow_run.id
  393. workflow_run_elapsed_time = workflow_run.elapsed_time
  394. workflow_run_status = workflow_run.status
  395. workflow_run_inputs = workflow_run.inputs_dict
  396. workflow_run_outputs = workflow_run.outputs_dict
  397. workflow_run_version = workflow_run.version
  398. error = workflow_run.error or ""
  399. total_tokens = workflow_run.total_tokens
  400. file_list = workflow_run_inputs.get("sys.file") or []
  401. query = workflow_run_inputs.get("query") or workflow_run_inputs.get("sys.query") or ""
  402. # get workflow_app_log_id
  403. workflow_app_log_data_stmt = select(WorkflowAppLog.id).where(
  404. WorkflowAppLog.tenant_id == tenant_id,
  405. WorkflowAppLog.app_id == workflow_run.app_id,
  406. WorkflowAppLog.workflow_run_id == workflow_run.id,
  407. )
  408. workflow_app_log_id = session.scalar(workflow_app_log_data_stmt)
  409. # get message_id
  410. message_id = None
  411. if conversation_id:
  412. message_data_stmt = select(Message.id).where(
  413. Message.conversation_id == conversation_id,
  414. Message.workflow_run_id == workflow_run_id,
  415. )
  416. message_id = session.scalar(message_data_stmt)
  417. metadata = {
  418. "workflow_id": workflow_id,
  419. "conversation_id": conversation_id,
  420. "workflow_run_id": workflow_run_id,
  421. "tenant_id": tenant_id,
  422. "elapsed_time": workflow_run_elapsed_time,
  423. "status": workflow_run_status,
  424. "version": workflow_run_version,
  425. "total_tokens": total_tokens,
  426. "file_list": file_list,
  427. "triggered_from": workflow_run.triggered_from,
  428. "user_id": user_id,
  429. }
  430. workflow_trace_info = WorkflowTraceInfo(
  431. workflow_data=workflow_run.to_dict(),
  432. conversation_id=conversation_id,
  433. workflow_id=workflow_id,
  434. tenant_id=tenant_id,
  435. workflow_run_id=workflow_run_id,
  436. workflow_run_elapsed_time=workflow_run_elapsed_time,
  437. workflow_run_status=workflow_run_status,
  438. workflow_run_inputs=workflow_run_inputs,
  439. workflow_run_outputs=workflow_run_outputs,
  440. workflow_run_version=workflow_run_version,
  441. error=error,
  442. total_tokens=total_tokens,
  443. file_list=file_list,
  444. query=query,
  445. metadata=metadata,
  446. workflow_app_log_id=workflow_app_log_id,
  447. message_id=message_id,
  448. start_time=workflow_run.created_at,
  449. end_time=workflow_run.finished_at,
  450. )
  451. return workflow_trace_info
  452. def message_trace(self, message_id: str | None):
  453. if not message_id:
  454. return {}
  455. message_data = get_message_data(message_id)
  456. if not message_data:
  457. return {}
  458. conversation_mode_stmt = select(Conversation.mode).where(Conversation.id == message_data.conversation_id)
  459. conversation_mode = db.session.scalars(conversation_mode_stmt).all()
  460. if not conversation_mode or len(conversation_mode) == 0:
  461. return {}
  462. conversation_mode = conversation_mode[0]
  463. created_at = message_data.created_at
  464. inputs = message_data.message
  465. # get message file data
  466. message_file_data = db.session.query(MessageFile).filter_by(message_id=message_id).first()
  467. file_list = []
  468. if message_file_data and message_file_data.url is not None:
  469. file_url = f"{self.file_base_url}/{message_file_data.url}" if message_file_data else ""
  470. file_list.append(file_url)
  471. metadata = {
  472. "conversation_id": message_data.conversation_id,
  473. "ls_provider": message_data.model_provider,
  474. "ls_model_name": message_data.model_id,
  475. "status": message_data.status,
  476. "from_end_user_id": message_data.from_end_user_id,
  477. "from_account_id": message_data.from_account_id,
  478. "agent_based": message_data.agent_based,
  479. "workflow_run_id": message_data.workflow_run_id,
  480. "from_source": message_data.from_source,
  481. "message_id": message_id,
  482. }
  483. message_tokens = message_data.message_tokens
  484. message_trace_info = MessageTraceInfo(
  485. message_id=message_id,
  486. message_data=message_data.to_dict(),
  487. conversation_model=conversation_mode,
  488. message_tokens=message_tokens,
  489. answer_tokens=message_data.answer_tokens,
  490. total_tokens=message_tokens + message_data.answer_tokens,
  491. error=message_data.error or "",
  492. inputs=inputs,
  493. outputs=message_data.answer,
  494. file_list=file_list,
  495. start_time=created_at,
  496. end_time=created_at + timedelta(seconds=message_data.provider_response_latency),
  497. metadata=metadata,
  498. message_file_data=message_file_data,
  499. conversation_mode=conversation_mode,
  500. )
  501. return message_trace_info
  502. def moderation_trace(self, message_id, timer, **kwargs):
  503. moderation_result = kwargs.get("moderation_result")
  504. if not moderation_result:
  505. return {}
  506. inputs = kwargs.get("inputs")
  507. message_data = get_message_data(message_id)
  508. if not message_data:
  509. return {}
  510. metadata = {
  511. "message_id": message_id,
  512. "action": moderation_result.action,
  513. "preset_response": moderation_result.preset_response,
  514. "query": moderation_result.query,
  515. }
  516. # get workflow_app_log_id
  517. workflow_app_log_id = None
  518. if message_data.workflow_run_id:
  519. workflow_app_log_data = (
  520. db.session.query(WorkflowAppLog).filter_by(workflow_run_id=message_data.workflow_run_id).first()
  521. )
  522. workflow_app_log_id = str(workflow_app_log_data.id) if workflow_app_log_data else None
  523. moderation_trace_info = ModerationTraceInfo(
  524. message_id=workflow_app_log_id or message_id,
  525. inputs=inputs,
  526. message_data=message_data.to_dict(),
  527. flagged=moderation_result.flagged,
  528. action=moderation_result.action,
  529. preset_response=moderation_result.preset_response,
  530. query=moderation_result.query,
  531. start_time=timer.get("start"),
  532. end_time=timer.get("end"),
  533. metadata=metadata,
  534. )
  535. return moderation_trace_info
  536. def suggested_question_trace(self, message_id, timer, **kwargs):
  537. suggested_question = kwargs.get("suggested_question", [])
  538. message_data = get_message_data(message_id)
  539. if not message_data:
  540. return {}
  541. metadata = {
  542. "message_id": message_id,
  543. "ls_provider": message_data.model_provider,
  544. "ls_model_name": message_data.model_id,
  545. "status": message_data.status,
  546. "from_end_user_id": message_data.from_end_user_id,
  547. "from_account_id": message_data.from_account_id,
  548. "agent_based": message_data.agent_based,
  549. "workflow_run_id": message_data.workflow_run_id,
  550. "from_source": message_data.from_source,
  551. }
  552. # get workflow_app_log_id
  553. workflow_app_log_id = None
  554. if message_data.workflow_run_id:
  555. workflow_app_log_data = (
  556. db.session.query(WorkflowAppLog).filter_by(workflow_run_id=message_data.workflow_run_id).first()
  557. )
  558. workflow_app_log_id = str(workflow_app_log_data.id) if workflow_app_log_data else None
  559. suggested_question_trace_info = SuggestedQuestionTraceInfo(
  560. message_id=workflow_app_log_id or message_id,
  561. message_data=message_data.to_dict(),
  562. inputs=message_data.message,
  563. outputs=message_data.answer,
  564. start_time=timer.get("start"),
  565. end_time=timer.get("end"),
  566. metadata=metadata,
  567. total_tokens=message_data.message_tokens + message_data.answer_tokens,
  568. status=message_data.status,
  569. error=message_data.error,
  570. from_account_id=message_data.from_account_id,
  571. agent_based=message_data.agent_based,
  572. from_source=message_data.from_source,
  573. model_provider=message_data.model_provider,
  574. model_id=message_data.model_id,
  575. suggested_question=suggested_question,
  576. level=message_data.status,
  577. status_message=message_data.error,
  578. )
  579. return suggested_question_trace_info
  580. def dataset_retrieval_trace(self, message_id, timer, **kwargs):
  581. documents = kwargs.get("documents")
  582. message_data = get_message_data(message_id)
  583. if not message_data:
  584. return {}
  585. metadata = {
  586. "message_id": message_id,
  587. "ls_provider": message_data.model_provider,
  588. "ls_model_name": message_data.model_id,
  589. "status": message_data.status,
  590. "from_end_user_id": message_data.from_end_user_id,
  591. "from_account_id": message_data.from_account_id,
  592. "agent_based": message_data.agent_based,
  593. "workflow_run_id": message_data.workflow_run_id,
  594. "from_source": message_data.from_source,
  595. }
  596. dataset_retrieval_trace_info = DatasetRetrievalTraceInfo(
  597. message_id=message_id,
  598. inputs=message_data.query or message_data.inputs,
  599. documents=[doc.model_dump() for doc in documents] if documents else [],
  600. start_time=timer.get("start"),
  601. end_time=timer.get("end"),
  602. metadata=metadata,
  603. message_data=message_data.to_dict(),
  604. )
  605. return dataset_retrieval_trace_info
  606. def tool_trace(self, message_id, timer, **kwargs):
  607. tool_name = kwargs.get("tool_name", "")
  608. tool_inputs = kwargs.get("tool_inputs", {})
  609. tool_outputs = kwargs.get("tool_outputs", {})
  610. message_data = get_message_data(message_id)
  611. if not message_data:
  612. return {}
  613. tool_config = {}
  614. time_cost = 0
  615. error = None
  616. tool_parameters = {}
  617. created_time = message_data.created_at
  618. end_time = message_data.updated_at
  619. agent_thoughts = message_data.agent_thoughts
  620. for agent_thought in agent_thoughts:
  621. if tool_name in agent_thought.tools:
  622. created_time = agent_thought.created_at
  623. tool_meta_data = agent_thought.tool_meta.get(tool_name, {})
  624. tool_config = tool_meta_data.get("tool_config", {})
  625. time_cost = tool_meta_data.get("time_cost", 0)
  626. end_time = created_time + timedelta(seconds=time_cost)
  627. error = tool_meta_data.get("error", "")
  628. tool_parameters = tool_meta_data.get("tool_parameters", {})
  629. metadata = {
  630. "message_id": message_id,
  631. "tool_name": tool_name,
  632. "tool_inputs": tool_inputs,
  633. "tool_outputs": tool_outputs,
  634. "tool_config": tool_config,
  635. "time_cost": time_cost,
  636. "error": error,
  637. "tool_parameters": tool_parameters,
  638. }
  639. file_url = ""
  640. message_file_data = db.session.query(MessageFile).filter_by(message_id=message_id).first()
  641. if message_file_data:
  642. message_file_id = message_file_data.id if message_file_data else None
  643. type = message_file_data.type
  644. created_by_role = message_file_data.created_by_role
  645. created_user_id = message_file_data.created_by
  646. file_url = f"{self.file_base_url}/{message_file_data.url}"
  647. metadata.update(
  648. {
  649. "message_file_id": message_file_id,
  650. "created_by_role": created_by_role,
  651. "created_user_id": created_user_id,
  652. "type": type,
  653. }
  654. )
  655. tool_trace_info = ToolTraceInfo(
  656. message_id=message_id,
  657. message_data=message_data.to_dict(),
  658. tool_name=tool_name,
  659. start_time=timer.get("start") if timer else created_time,
  660. end_time=timer.get("end") if timer else end_time,
  661. tool_inputs=tool_inputs,
  662. tool_outputs=tool_outputs,
  663. metadata=metadata,
  664. message_file_data=message_file_data,
  665. error=error,
  666. inputs=message_data.message,
  667. outputs=message_data.answer,
  668. tool_config=tool_config,
  669. time_cost=time_cost,
  670. tool_parameters=tool_parameters,
  671. file_url=file_url,
  672. )
  673. return tool_trace_info
  674. def generate_name_trace(self, conversation_id, timer, **kwargs):
  675. generate_conversation_name = kwargs.get("generate_conversation_name")
  676. inputs = kwargs.get("inputs")
  677. tenant_id = kwargs.get("tenant_id")
  678. if not tenant_id:
  679. return {}
  680. start_time = timer.get("start")
  681. end_time = timer.get("end")
  682. metadata = {
  683. "conversation_id": conversation_id,
  684. "tenant_id": tenant_id,
  685. }
  686. generate_name_trace_info = GenerateNameTraceInfo(
  687. conversation_id=conversation_id,
  688. inputs=inputs,
  689. outputs=generate_conversation_name,
  690. start_time=start_time,
  691. end_time=end_time,
  692. metadata=metadata,
  693. tenant_id=tenant_id,
  694. )
  695. return generate_name_trace_info
  696. trace_manager_timer: Optional[threading.Timer] = None
  697. trace_manager_queue: queue.Queue = queue.Queue()
  698. trace_manager_interval = int(os.getenv("TRACE_QUEUE_MANAGER_INTERVAL", 5))
  699. trace_manager_batch_size = int(os.getenv("TRACE_QUEUE_MANAGER_BATCH_SIZE", 100))
  700. class TraceQueueManager:
  701. def __init__(self, app_id=None, user_id=None):
  702. global trace_manager_timer
  703. self.app_id = app_id
  704. self.user_id = user_id
  705. self.trace_instance = OpsTraceManager.get_ops_trace_instance(app_id)
  706. self.flask_app = current_app._get_current_object() # type: ignore
  707. if trace_manager_timer is None:
  708. self.start_timer()
  709. def add_trace_task(self, trace_task: TraceTask):
  710. global trace_manager_timer, trace_manager_queue
  711. try:
  712. if self.trace_instance:
  713. trace_task.app_id = self.app_id
  714. trace_manager_queue.put(trace_task)
  715. except Exception as e:
  716. logging.exception(f"Error adding trace task, trace_type {trace_task.trace_type}")
  717. finally:
  718. self.start_timer()
  719. def collect_tasks(self):
  720. global trace_manager_queue
  721. tasks: list[TraceTask] = []
  722. while len(tasks) < trace_manager_batch_size and not trace_manager_queue.empty():
  723. task = trace_manager_queue.get_nowait()
  724. tasks.append(task)
  725. trace_manager_queue.task_done()
  726. return tasks
  727. def run(self):
  728. try:
  729. tasks = self.collect_tasks()
  730. if tasks:
  731. self.send_to_celery(tasks)
  732. except Exception as e:
  733. logging.exception("Error processing trace tasks")
  734. def start_timer(self):
  735. global trace_manager_timer
  736. if trace_manager_timer is None or not trace_manager_timer.is_alive():
  737. trace_manager_timer = threading.Timer(trace_manager_interval, self.run)
  738. trace_manager_timer.name = f"trace_manager_timer_{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}"
  739. trace_manager_timer.daemon = False
  740. trace_manager_timer.start()
  741. def send_to_celery(self, tasks: list[TraceTask]):
  742. with self.flask_app.app_context():
  743. for task in tasks:
  744. if task.app_id is None:
  745. continue
  746. file_id = uuid4().hex
  747. trace_info = task.execute()
  748. task_data = TaskData(
  749. app_id=task.app_id,
  750. trace_info_type=type(trace_info).__name__,
  751. trace_info=trace_info.model_dump() if trace_info else None,
  752. )
  753. file_path = f"{OPS_FILE_PATH}{task.app_id}/{file_id}.json"
  754. storage.save(file_path, task_data.model_dump_json().encode("utf-8"))
  755. file_info = {
  756. "file_id": file_id,
  757. "app_id": task.app_id,
  758. }
  759. process_trace_tasks.delay(file_info)