JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
feat(observability): 集成team观测采集
hwxiajinge803f062e3e9
diff --git a/deploy/observability/README.md b/deploy/observability/README.mdnew file mode 100644index 0000000000..b8d8aca06a--- /dev/null+++ b/deploy/observability/README.md@@ -0,0 +1,80 @@+# Jiuwenswarm Team Observability Stack++Local docker-compose deployment for OpenTelemetry observability with Langfuse backend.++## Architecture++```+Application --(OTLP gRPC)--> OTel Collector --(OTLP HTTP)--> Langfuse+ localhost:4317 localhost:3000+```++- **Application → Collector**: gRPC (port 4317) or HTTP (port 4318), no auth required+- **Collector → Langfuse**: HTTP with Basic Auth (configured in `otel-collector-config.yaml`)++## Prerequisites++- Docker & Docker Compose++## Quick Start++```bash+cd deploy/observability++# Start all services+docker-compose up -d++# Check status+docker-compose ps++# View collector logs+docker-compose logs -f otel-collector+```++Wait for all services to become healthy (~30-60s on first start).++### Access Langfuse UI++- URL: http://localhost:3000+- Default user: `jiuwensarm` / `jiuwensarm`+- Project keys: `pk-lf-jiuwen` / `sk-lf-jiuwen`++### Stop and Clean Up++```bash+# Stop services (keep data)+docker-compose down++# Stop and remove all data+docker-compose down -v+```++## Enable in Jiuwenswarm++编辑 `~/.jiuwenswarm/config/config.yaml`,将 `team_observability.enabled` 设为 `true`,重启即可。++```yaml+team_observability:+ enabled: true+ endpoint: http://localhost:4317+```++## Production Notes++1. **Security**: Change `NEXTAUTH_SECRET`, `SALT`, `ENCRYPTION_KEY`, and database passwords in `docker-compose.yml` before exposing outside localhost.++2. **Sampling**: If trace volume is too high, set `sample_rate < 1.0` in `team_observability` config (e.g., 0.1).++3. **Databases**: For production, use managed Postgres and ClickHouse instead of docker-compose volumes.++4. **Remove debug exporter**: In `otel-collector-config.yaml`, remove `debug` from exporters once stable:+ ```yaml+ exporters: [otlphttp/langfuse]+ ```++## Files++| File | Purpose |+|------|---------|+| `docker-compose.yml` | Service orchestration: OTel Collector, Langfuse, Postgres, ClickHouse, Redis, MinIO |+| `otel-collector-config.yaml` | Collector pipeline: receivers, processors, exporters |\ No newline at end of filediff --git a/deploy/observability/docker-compose.yml b/deploy/observability/docker-compose.ymlnew file mode 100644index 0000000000..a6153f406b--- /dev/null+++ b/deploy/observability/docker-compose.yml@@ -0,0 +1,178 @@+# Langfuse v3 最简配置 (基于官方 docker-compose.yml)+# 启动: docker-compose up -d+# 访问: http://localhost:3000++services:+ otel-collector:+ image: otel/opentelemetry-collector-contrib:0.154.0+ container_name: langfuse-otel-collector+ command: ["--config=/etc/otel-collector-config.yaml"]+ volumes:+ - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml:ro+ ports:+ - "4317:4317"+ - "4318:4318"+ depends_on:+ langfuse-web:+ condition: service_started++ langfuse-web:+ image: langfuse/langfuse:3+ container_name: langfuse-web+ depends_on:+ postgres:+ condition: service_healthy+ clickhouse:+ condition: service_healthy+ redis:+ condition: service_healthy+ minio:+ condition: service_healthy+ ports:+ - "3000:3000"+ environment:+ NEXTAUTH_URL: http://localhost:3000+ NEXTAUTH_SECRET: mysecret+ DATABASE_URL: postgresql://postgres:postgres@postgres:5432/postgres+ SALT: mysalt+ ENCRYPTION_KEY: d2192b67e7e22a8c46df7b96d3699dc91a710fc0d6e0bff0894a0b8308e3971e+ CLICKHOUSE_URL: http://clickhouse:8123+ CLICKHOUSE_MIGRATION_URL: clickhouse://clickhouse:9000+ CLICKHOUSE_USER: clickhouse+ CLICKHOUSE_PASSWORD: clickhouse+ CLICKHOUSE_CLUSTER_ENABLED: false+ REDIS_HOST: redis+ REDIS_PORT: 6379+ REDIS_AUTH: myredissecret+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: langfuse+ LANGFUSE_S3_EVENT_UPLOAD_REGION: auto+ LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: minio+ LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: miniosecret+ LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: http://minio:9000+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: true+ TELEMETRY_ENABLED: "false"++ LANGFUSE_INIT_ORG_ID: jiuwen-org+ LANGFUSE_INIT_ORG_NAME: Jiuwen Organization+ LANGFUSE_INIT_PROJECT_ID: jiuwen-project+ LANGFUSE_INIT_PROJECT_NAME: Jiuwen Project+ LANGFUSE_INIT_PROJECT_PUBLIC_KEY: pk-lf-jiuwen+ LANGFUSE_INIT_PROJECT_SECRET_KEY: sk-lf-jiuwen+ LANGFUSE_INIT_USER_EMAIL: [email protected]+ LANGFUSE_INIT_USER_NAME: jiuwensarm+ LANGFUSE_INIT_USER_PASSWORD: jiuwensarm++ LANGFUSE_DEFAULT_ORG_ID: jiuwen-org+ LANGFUSE_DEFAULT_ORG_ROLE: ADMIN+ LANGFUSE_DEFAULT_PROJECT_ID: jiuwen-project+ LANGFUSE_DEFAULT_PROJECT_ROLE: ADMIN++ langfuse-worker:+ image: langfuse/langfuse-worker:3+ container_name: langfuse-worker+ depends_on:+ postgres:+ condition: service_healthy+ clickhouse:+ condition: service_healthy+ redis:+ condition: service_healthy+ minio:+ condition: service_healthy+ environment:+ DATABASE_URL: postgresql://postgres:postgres@postgres:5432/postgres+ SALT: mysalt+ ENCRYPTION_KEY: d2192b67e7e22a8c46df7b96d3699dc91a710fc0d6e0bff0894a0b8308e3971e+ CLICKHOUSE_URL: http://clickhouse:8123+ CLICKHOUSE_MIGRATION_URL: clickhouse://clickhouse:9000+ CLICKHOUSE_USER: clickhouse+ CLICKHOUSE_PASSWORD: clickhouse+ CLICKHOUSE_CLUSTER_ENABLED: false+ REDIS_HOST: redis+ REDIS_PORT: 6379+ REDIS_AUTH: myredissecret+ LANGFUSE_S3_EVENT_UPLOAD_BUCKET: langfuse+ LANGFUSE_S3_EVENT_UPLOAD_REGION: auto+ LANGFUSE_S3_EVENT_UPLOAD_ACCESS_KEY_ID: minio+ LANGFUSE_S3_EVENT_UPLOAD_SECRET_ACCESS_KEY: miniosecret+ LANGFUSE_S3_EVENT_UPLOAD_ENDPOINT: http://minio:9000+ LANGFUSE_S3_EVENT_UPLOAD_FORCE_PATH_STYLE: true+ TELEMETRY_ENABLED: "false"++ LANGFUSE_INIT_ORG_ID: jiuwen-org+ LANGFUSE_INIT_ORG_NAME: Jiuwen Organization+ LANGFUSE_INIT_PROJECT_ID: jiuwen-project+ LANGFUSE_INIT_PROJECT_NAME: Jiuwen Project+ LANGFUSE_INIT_PROJECT_PUBLIC_KEY: pk-lf-jiuwen+ LANGFUSE_INIT_PROJECT_SECRET_KEY: sk-lf-jiuwen+ LANGFUSE_INIT_USER_EMAIL: [email protected]+ LANGFUSE_INIT_USER_NAME: jiuwensarm+ LANGFUSE_INIT_USER_PASSWORD: jiuwensarm++ LANGFUSE_DEFAULT_ORG_ID: jiuwen-org+ LANGFUSE_DEFAULT_ORG_ROLE: ADMIN+ LANGFUSE_DEFAULT_PROJECT_ID: jiuwen-project+ LANGFUSE_DEFAULT_PROJECT_ROLE: ADMIN++ postgres:+ image: postgres:17+ container_name: langfuse-postgres+ environment:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: postgres+ volumes:+ - langfuse_pg:/var/lib/postgresql/data+ healthcheck:+ test: ["CMD-SHELL", "pg_isready -U postgres"]+ interval: 3s+ timeout: 3s+ retries: 10++ clickhouse:+ image: clickhouse/clickhouse-server+ container_name: langfuse-clickhouse+ user: "101:101"+ environment:+ CLICKHOUSE_DB: default+ CLICKHOUSE_USER: clickhouse+ CLICKHOUSE_PASSWORD: clickhouse+ volumes:+ - langfuse_ch:/var/lib/clickhouse+ healthcheck:+ test: wget --no-verbose --tries=1 --spider http://localhost:8123/ping || exit 1+ interval: 5s+ timeout: 5s+ retries: 10++ redis:+ image: redis:7+ container_name: langfuse-redis+ command: --requirepass myredissecret --maxmemory-policy noeviction+ healthcheck:+ test: ["CMD", "redis-cli", "-a", "myredissecret", "ping"]+ interval: 3s+ timeout: 10s+ retries: 10++ minio:+ image: minio/minio:latest+ container_name: langfuse-minio+ entrypoint: sh+ # create the 'langfuse' bucket before starting the service+ command: -c 'mkdir -p /data/langfuse && minio server --address ":9000" --console-address ":9001" /data'+ environment:+ MINIO_ROOT_USER: minio+ MINIO_ROOT_PASSWORD: miniosecret+ volumes:+ - langfuse_minio:/data+ healthcheck:+ test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"]+ interval: 5s+ timeout: 5s+ retries: 5++volumes:+ langfuse_pg:+ langfuse_ch:+ langfuse_minio:\ No newline at end of filediff --git a/deploy/observability/otel-collector-config.yaml b/deploy/observability/otel-collector-config.yamlnew file mode 100644index 0000000000..f523811645--- /dev/null+++ b/deploy/observability/otel-collector-config.yaml@@ -0,0 +1,53 @@+# OpenTelemetry Collector configuration for jiuwenswarm / agent_teams observability.+#+# Pipeline: application(otlp/grpc) -> memory_limiter -> batch+# -> transform/limit_strings+# -> langfuse / debug+#+# - The transform processor caps any string attribute at 16 KiB so that+# accidentally enormous prompts cannot OOM the backend.+# - "debug" exporter prints a one-line span summary; remove from the+# pipeline once production traffic stabilises.++receivers:+ otlp:+ protocols:+ grpc:+ endpoint: 0.0.0.0:4317+ http:+ endpoint: 0.0.0.0:4318++processors:+ memory_limiter:+ check_interval: 2s+ limit_mib: 1024+ spike_limit_mib: 256++ batch:+ timeout: 5s+ send_batch_size: 1024+ send_batch_max_size: 2048++ transform/limit_strings:+ trace_statements:+ - context: span+ statements:+ - truncate_all(attributes, 16384)++exporters:+ otlphttp/langfuse:+ endpoint: http://langfuse-web:3000/api/public/otel+ tls:+ insecure: true+ headers:+ Authorization: "Basic cGstbGYtaml1d2VuOnNrLWxmLWppdXdlbg=="++ debug:+ verbosity: basic++service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [memory_limiter, batch, transform/limit_strings]+ exporters: [otlphttp/langfuse, debug]\ No newline at end of filediff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.pyindex b3daf52f2d..369ccfbb2c 100644--- a/jiuwenswarm/agents/harness/team/team_manager.py+++ b/jiuwenswarm/agents/harness/team/team_manager.py@@ -72,6 +72,76 @@ _PG_POST_START_READY_MAX_SLEEP = 2.0_PG_POST_START_READY_BACKOFF = 1.45_PG_POST_START_LOG_EVERY_SEC = 5.0+# ── Team Observability ──────────────────────────────────────+# Tracks whether observability is currently active so we can+# detect config toggles (enabled → disabled or vice-versa)+# and init / shutdown accordingly on each team request.+_observability_active: bool = False+++def sync_team_observability() -> None:+ """Synchronize observability state with current config.++ Called before each ``Runner.run_agent_team_streaming`` so that+ hot-reloading the ``team_observability.enabled`` flag takes+ effect immediately:++ * disabled → enabled : ``init_observability()``+ * enabled → disabled : ``shutdown_observability()``+ * unchanged : no-op+ """+ global _observability_active+ cfg = get_config().get("team_observability", {}) or {}+ want_enabled = bool(cfg.get("enabled", False))++ if want_enabled and not _observability_active:+ try:+ from openjiuwen.agent_teams.observability import (+ ObservabilityConfig,+ init_observability,+ is_initialized,+ )+ if is_initialized():+ _observability_active = True+ return+ obs_cfg = ObservabilityConfig(+ enabled=True,+ service_name=cfg.get("service_name", "jiuwenswarm"),+ exporter=cfg.get("exporter", "otlp_grpc"),+ endpoint=cfg.get("endpoint", "http://localhost:4317"),+ sample_rate=cfg.get("sample_rate", 1.0),+ attribute_value_max_length=cfg.get("attribute_value_max_length", 10240),+ redact_prompts=cfg.get("redact_prompts", False),+ redact_completions=cfg.get("redact_completions", False),+ langfuse_public_key=cfg.get("langfuse_public_key", ""),+ langfuse_secret_key=cfg.get("langfuse_secret_key", ""),+ )+ init_observability(obs_cfg)+ _observability_active = True+ logger.info(+ "[TeamObservability] enabled: exporter=%s endpoint=%s",+ obs_cfg.exporter, obs_cfg.endpoint,+ )+ except Exception as exc:+ logger.warning("[TeamObservability] init failed: %s", exc)++ elif not want_enabled and _observability_active:+ shutdown_team_observability()+++def shutdown_team_observability() -> None:+ """Shutdown team observability (called on disable or process exit)."""+ global _observability_active+ if not _observability_active:+ return+ try:+ from openjiuwen.agent_teams.observability import shutdown_observability+ shutdown_observability()+ _observability_active = False+ logger.info("[TeamObservability] disabled")+ except Exception as exc:+ logger.warning("[TeamObservability] shutdown failed: %s", exc)+@dataclassclass TeamRailMountContext:diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yamlindex 41b3757241..86c12ace72 100644--- a/jiuwenswarm/resources/config.yaml+++ b/jiuwenswarm/resources/config.yaml@@ -309,6 +309,30 @@ telemetry:protocol: # metrics protocol,默认回退到 telemetry.protocolheaders: {} # metrics headers,默认回退到 telemetry.headers+# ============================================================+# Team 可观测性配置(OTel + Langfuse)+# ============================================================+# 与 telemetry 不同,team_observability 专门用于 TeamAgent 的+# 可观测性追踪,包括 team/member/task/message 级别的 span。+# 启用后会自动将 OtelTeamMonitorHandler 注册到 TeamAgent,+# 将事件转为 OTel span 导出到 Langfuse / OTLP Collector。+#+# 前置条件:+# 1. 启动 OTel Collector + Langfuse+# 2. 在用户配置中设置 team_observability.enabled: true+# ============================================================+team_observability:+ enabled: false # Team observability 总开关+ exporter: otlp_grpc # otlp_grpc / otlp_http / console+ endpoint: http://localhost:4317 # OTLP gRPC endpoint+ service_name: jiuwenswarm # 服务名称(OTel resource service.name)+ sample_rate: 1.0 # 采样率 (0.0-1.0)+ redact_prompts: false # 是否脱敏 prompt 内容+ redact_completions: false # 是否脱敏 completion 内容+ attribute_value_max_length: 10240 # OTel attribute value 最大长度+ langfuse_public_key: "" # Langfuse OTLP 认证 public key(可选)+ langfuse_secret_key: "" # Langfuse OTLP 认证 secret key(可选)+react:agent_name: main_agentenable_task_loop: falsediff --git a/jiuwenswarm/server/app_agentserver.py b/jiuwenswarm/server/app_agentserver.pyindex 5478571446..ee32c40aae 100644--- a/jiuwenswarm/server/app_agentserver.py+++ b/jiuwenswarm/server/app_agentserver.py@@ -190,6 +190,12 @@ async def _run(host: str, port: int) -> None:except Exception as exc:logger.warning("[AgentServer] teammate bootstrap daemon stop failed: %s", exc)await server.stop()+ # Shutdown team observability (flush & close spans)+ try:+ from jiuwenswarm.agents.harness.team.team_manager import shutdown_team_observability+ shutdown_team_observability()+ except Exception as exc:+ logger.warning("[AgentServer] team observability shutdown failed: %s", exc)logger.info("[AgentServer] stopped")diff --git a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.pyindex e4a903ea6b..cde58279db 100644--- a/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py+++ b/jiuwenswarm/server/runtime/agent_adapter/team_helpers.py@@ -926,6 +926,12 @@ async def process_team_message_stream(try:if is_first_request:+ # Sync team observability with current config before streaming.+ # Runner.run_agent_team_streaming auto-attaches handlers when+ # is_initialized() is True; this call ensures init/shutdown+ # matches the latest config toggle.+ from jiuwenswarm.agents.harness.team.team_manager import sync_team_observability+ sync_team_observability()team_manager.ensure_team_shared_skills_ready_for_session(session_id, team_spec)await team_manager.prepare_runtime_activation(session_id, team_name)request_queue = asyncio.Queue()