observability.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import logging
  2. from langsmith import Client
  3. from langsmith.integrations.otel import configure
  4. from zbt.core.config import Settings
  5. logger = logging.getLogger(__name__)
  6. _otel_configured = False
  7. def configure_langsmith_otel(settings: Settings) -> bool:
  8. """将项目自定义工作流 Span 发送到当前 LangSmith 项目。"""
  9. global _otel_configured
  10. if _otel_configured:
  11. return True
  12. if (
  13. not settings.langsmith_tracing
  14. or not settings.langsmith_otel_enabled
  15. or not settings.langsmith_api_key
  16. ):
  17. return False
  18. try:
  19. client = Client(
  20. api_url=settings.langsmith_endpoint,
  21. api_key=settings.langsmith_api_key,
  22. )
  23. try:
  24. project = client.read_project(
  25. project_name=settings.langsmith_project,
  26. )
  27. except Exception:
  28. project = client.create_project(
  29. settings.langsmith_project,
  30. description="智保通第三阶段Agent与LangGraph运行轨迹",
  31. upsert=True,
  32. )
  33. # OTLP请求头必须是ASCII;官方接口也接受项目UUID作为目标标识。
  34. _otel_configured = configure(
  35. api_key=settings.langsmith_api_key,
  36. project_name=str(project.id),
  37. )
  38. except Exception:
  39. logger.exception("LangSmith OpenTelemetry项目解析失败")
  40. return False
  41. if not _otel_configured:
  42. logger.warning("LangSmith OpenTelemetry 初始化未生效")
  43. return _otel_configured