Skip to content

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

fix(observability): 默认输出到文件,提供手动上传脚本

hwxiajingcad7b35dcdf1
diff --git a/deploy/observability/README.md b/deploy/observability/README.md
index 499ee26047..8fab77bfca 100644
--- a/deploy/observability/README.md
+++ b/deploy/observability/README.md
@@ -36,10 +36,102 @@ Wait for all services to become healthy (~30-60s on first start).
### Access Langfuse UI
- URL: http://localhost:3000
-- Login email: `[email protected]`
+- Login email: `[email protected]`
- Password: `jiuwenswarm`
- Project keys: `pk-lf-jiuwen` / `sk-lf-jiuwen`
+## File Exporter (offline / two-phase)
+
+The `file` exporter writes traces as standard OTLP JSON files on disk
+instead of streaming to the collector in real time. Files can be uploaded
+later with `upload_traces_to_langfuse.py`.
+
+### Phase 1 — configure the exporter
+
+编辑 `~/.jiuwenswarm/config/config.yaml`:
+
+```yaml
+team_observability:
+ enabled: true
+ exporter: "file"
+ # traces_dir 留空则默认写入 ~/.jiuwenswarm/.trace
+ traces_dir: ""
+ file_retention_days: 7 # optional, default 7
+ sample_rate: 1.0
+```
+
+- Flat layout — all trace files are written directly under `traces_dir`,
+ no per-session sub-folders.
+- One append-only file per calendar day, named `traces-<YYYY-MM-DD>.jsonl`.
+ Spans from all traces are interleaved in it; each line is a standalone
+ single-span OTLP JSON (`resourceSpans` → `scopeSpans` → `spans`),
+ directly ingestible by the collector at `/v1/traces` — replaying is
+ just POSTing each line in turn. The collector splits traces by the
+ `traceId` carried on every span, so interleaving is irrelevant for
+ ingestion.
+- `export()` appends straight to disk with no in-memory buffer; paired
+ with `BatchSpanProcessor` (the default for the `file` exporter) so
+ span-end does not block the business thread — spans land on disk when
+ the processor flushes (default every 5s / 512 spans) and on shutdown.
+- `session.id` (if present) is read by Langfuse from span attributes,
+ not the filename — the filename carries only the date.
+
+### Phase 2 — upload to Langfuse
+
+The upload script accepts either a single trace file or a directory.
+With no arguments it defaults to `~/.jiuwenswarm/.trace`
+(overridable via `JIUWENSWARM_DATA_DIR`), matching the file exporter's
+output path. When given a directory, it uploads every `*.jsonl` directly
+under it (flat — no sub-folder walking). It POSTs each line of each file
+as a standalone OTLP request to the collector. After the run it prints
+the unique trace IDs that were ingested, parsed from each uploaded line's
+`resourceSpans[].scopeSpans[].spans[].traceId`.
+
+```bash
+# Start the collector stack
+docker-compose up -d
+
+# Upload the default traces directory (~/.jiuwenswarm/.trace):
+python upload_traces_to_langfuse.py
+
+# Upload a whole directory of trace files:
+python upload_traces_to_langfuse.py ./traces_run_001
+# or, equivalently:
+python upload_traces_to_langfuse.py --dir ./traces_run_001
+
+# Upload a single trace file:
+python upload_traces_to_langfuse.py --file ./traces_run_001/traces-2026-06-29.jsonl
+
+# Use a non-default collector endpoint:
+python upload_traces_to_langfuse.py ./traces_run_001 --endpoint http://localhost:4318/v1/traces
+```
+
+The script POSTs each `.jsonl` line to the collector's OTLP HTTP
+endpoint (`localhost:4318/v1/traces` by default, no auth), which forwards
+to Langfuse. Exit code is `0` on full success, `1` if any line failed,
+`2` if the input path was not found or contained no `.jsonl` files.
+
+Sample output:
+
+```
+[upload] source=./traces_run_001 files=3 endpoint=http://localhost:4318/v1/traces
+[upload] total_lines=128 ok=128 fail=0 elapsed=0.6s
+[upload] trace_ids (3):
+ 4f3c1a8b9d2e4f6081a3c5b7d9e1f2a3
+ 8e1c0b2d4f6a8c9e1d3b5a7c9e1f0a2b
+ 1a2b3c4d5e6f70819203a4b5c6d7e8f9
+```
+
+**认证说明**:上传脚本连接本地 Collector(`localhost:4318`,无鉴权),
+Langfuse 的 `pk/sk` 认证由 Collector 侧 `otel-collector-config.yaml` 处理,
+脚本本身不需要配置密钥。
+
+### Cleanup
+
+Trace files (`*.jsonl`) whose mtime predates `file_retention_days` are
+lazily deleted by the exporter itself (a sweep runs at most every 64
+exports). No manual cleanup is required.
+
### Stop and Clean Up
```bash
@@ -60,11 +152,90 @@ team_observability:
endpoint: http://localhost:4317
```
+## Application Configuration
+
+### Method 1: OTLP gRPC → Collector → Langfuse (Recommended)
+
+Application sends traces to local Collector. Auth is handled by Collector.
+
+```yaml
+team_observability:
+ enabled: true
+ exporter: "otlp_grpc"
+ endpoint: "http://localhost:4317"
+ sample_rate: 1.0
+```
+
+### Method 2: OTLP HTTP → Langfuse Direct
+
+Application sends traces directly to Langfuse Cloud (bypasses local Collector).
+
+```yaml
+team_observability:
+ enabled: true
+ exporter: "otlp_http"
+ endpoint: "https://cloud.langfuse.com/api/public/otel/v1/traces"
+ langfuse_public_key: "pk-lf-xxx"
+ langfuse_secret_key: "sk-lf-xxx"
+```
+
+### Method 3: Console Output (Debug)
+
+```yaml
+team_observability:
+ enabled: true
+ exporter: "console"
+```
+
+Traces printed as JSON to console.
+
+## Configuration Reference
+
+| Field | Type | Default | Description |
+|-------|------|---------|-------------|
+| `enabled` | bool | True | Enable/disable observability |
+| `service_name` | str | "openjiuwen-agent-teams" | OTel resource service name |
+| `exporter` | str | "otlp_grpc" | Exporter type: `otlp_grpc`, `otlp_http`, `console`, `file` |
+| `endpoint` | str | "http://localhost:4317" | OTLP endpoint URL |
+| `traces_dir` | str | "~/.jiuwenswarm/.trace" | Output dir for the `file` exporter (empty → default) |
+| `file_retention_days` | int | 7 | Trace files older than this are lazily pruned (`file` exporter) |
+| `sample_rate` | float | 1.0 | Sampling rate (0.0-1.0) |
+| `langfuse_public_key` | str | "" | Required for direct Langfuse connection |
+| `langfuse_secret_key` | str | "" | Required for direct Langfuse connection |
+
+## Customizing Langfuse Keys
+
+The default keys (`pk-lf-jiuwen` / `sk-lf-jiuwen`) are configured in:
+
+1. **docker-compose.yml** - Langfuse initialization:
+ ```yaml
+ LANGFUSE_INIT_PROJECT_PUBLIC_KEY: pk-lf-jiuwen
+ LANGFUSE_INIT_PROJECT_SECRET_KEY: sk-lf-jiuwen
+ ```
+
+2. **otel-collector-config.yaml** - Collector authentication:
+ ```yaml
+ exporters:
+ otlphttp/langfuse:
+ headers:
+ Authorization: "Basic <base64(pk:sk)>"
+ ```
+
+To generate a new Base64 auth header:
+```bash
+echo -n "pk-lf-xxx:sk-lf-xxx" | base64
+```
+
+Or in PowerShell:
+```powershell
+[Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes("pk-lf-xxx:sk-lf-xxx"))
+```
+
## 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).
+2. **Sampling**: Set `sample_rate < 1.0` in production (e.g., 0.1) to reduce trace volume.
3. **Databases**: For production, use managed Postgres and ClickHouse instead of docker-compose volumes.
@@ -78,4 +249,5 @@ team_observability:
| 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 file
+| `otel-collector-config.yaml` | Collector pipeline: receivers, processors, exporters |
+| `upload_traces_to_langfuse.py` | Upload per-day `.jsonl` trace files to the collector (offline two-phase) |
diff --git a/deploy/observability/upload_traces_to_langfuse.py b/deploy/observability/upload_traces_to_langfuse.py
new file mode 100644
index 0000000000..6bfff61ab2
--- /dev/null
+++ b/deploy/observability/upload_traces_to_langfuse.py
@@ -0,0 +1,220 @@
+# coding: utf-8
+"""Upload ``.jsonl`` trace files to Langfuse via the local OTel collector.
+
+Accepts either a single file or a directory:
+
+ python upload_traces_to_langfuse.py <path>
+ python upload_traces_to_langfuse.py --file traces-2026-06-29.jsonl
+ python upload_traces_to_langfuse.py --dir <traces_dir>
+
+Where ``<path>`` is:
+ - a ``.jsonl`` file → upload every line in it
+ - a directory → upload every ``*.jsonl`` directly under it (flat,
+ no sub-folder walking)
+
+With no arguments, the default traces directory is used —
+``~/.jiuwenswarm/.trace`` (overridable via ``JIUWENSWARM_DATA_DIR``),
+matching the file exporter's output path configured in team_manager.
+
+The file exporter writes one per-day ``traces-<YYYY-MM-DD>.jsonl`` whose
+lines are spans from potentially many traces, interleaved. Every line
+is a standalone OTLP JSON ``ExportTraceServiceRequest`` carrying a
+single span — just POST each line to the collector. No reconstruction,
+no merging. The collector splits traces by the ``traceId`` carried on
+each span, so interleaving is irrelevant for ingestion.
+``session.id`` (if present) is read by Langfuse from span attributes,
+not the filename.
+
+After upload, the script prints the unique trace IDs ingested, parsed
+from each uploaded line's ``resourceSpans[].scopeSpans[].spans[].traceId``.
+
+Prerequisites:
+ docker-compose up -d # from deploy/observability/
+
+The collector listens on :4318 (OTLP HTTP, no auth).
+"""
+
+from __future__ import annotations
+
+import argparse
+import glob
+import json
+import logging
+import os
+import sys
+import time
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+_logger = logging.getLogger(__name__)
+
+_COLLECTOR = "http://localhost:4318/v1/traces"
+
+
+def _default_traces_dir() -> str:
+ """Return the default traces directory, matching the file exporter output path.
+
+ Priority (mirrors ``team_manager`` → ``get_user_workspace_dir()``):
+ 1. ``JIUWENSWARM_DATA_DIR`` env / ``.trace``
+ 2. ``~/.jiuwenswarm/.trace``
+ """
+ data_dir = os.getenv("JIUWENSWARM_DATA_DIR")
+ if data_dir:
+ return str(Path(data_dir) / ".trace")
+ return str(Path.home() / ".jiuwenswarm" / ".trace")
+
+
+def _iter_lines(path: str):
+ """Yield non-empty stripped lines from a .jsonl file."""
+ with open(path, "r", encoding="utf-8") as f:
+ for line in f:
+ line = line.strip()
+ if line:
+ yield line
+
+
+def _extract_trace_id(line_body: bytes) -> str | None:
+ """Parse one OTLP JSON line and return its traceId, or None."""
+ try:
+ data = json.loads(line_body)
+ except json.JSONDecodeError:
+ return None
+ for rs in data.get("resourceSpans", []):
+ for ss in rs.get("scopeSpans", []):
+ for sp in ss.get("spans", []):
+ tid = sp.get("traceId")
+ if isinstance(tid, str):
+ return tid
+ return None
+
+
+def _post_line(body: bytes, endpoint: str) -> bool:
+ """POST one OTLP JSON line to the collector. Returns True on success."""
+ req = urllib.request.Request(endpoint, data=body, method="POST")
+ req.add_header("Content-Type", "application/json")
+ try:
+ urllib.request.urlopen(req, timeout=15)
+ return True
+ except urllib.error.HTTPError as e:
+ snippet = e.read()[:200]
+ _logger.warning("HTTP %d: %s", e.code, snippet)
+ except urllib.error.URLError as e:
+ _logger.warning("url error: %s", e)
+ except OSError as e:
+ _logger.warning("net error: %s", e)
+ return False
+
+
+def _upload_one(path: str, endpoint: str) -> tuple[int, int, list[str]]:
+ """Upload every line of one ``.jsonl`` file.
+
+ Returns (lines_ok, lines_fail, trace_ids) where trace_ids are the
+ unique traceIds seen in successfully uploaded lines.
+ """
+ ok = 0
+ fail = 0
+ seen: set[str] = set()
+ trace_ids: list[str] = []
+ for line in _iter_lines(path):
+ body = line.encode("utf-8")
+ tid = _extract_trace_id(body)
+ if _post_line(body, endpoint):
+ ok += 1
+ if tid and tid not in seen:
+ seen.add(tid)
+ trace_ids.append(tid)
+ else:
+ fail += 1
+ return ok, fail, trace_ids
+
+
+def _collect_files(path: str) -> list[str] | None:
+ """Return list of .jsonl files to upload from a file/dir path.
+
+ Returns None if path doesn't exist; empty list if dir has no .jsonl.
+ Only top-level ``*.jsonl`` under a directory are picked up (flat
+ layout — matches the file exporter's per-day output).
+ """
+ if os.path.isfile(path):
+ return [path]
+ if os.path.isdir(path):
+ return sorted(glob.glob(os.path.join(path, "*.jsonl")))
+ return None
+
+
+def _resolve_input_path(args: argparse.Namespace) -> str | None:
+ """Pick the input path from positional / --dir / --file (in that order)."""
+ if args.path:
+ return args.path
+ if args.dir:
+ return args.dir
+ if args.file:
+ return args.file
+ return None
+
+
+def main() -> int:
+ logging.basicConfig(level=logging.INFO, format="%(message)s")
+ parser = argparse.ArgumentParser(description="Upload per-day .jsonl trace files to collector")
+ parser.add_argument(
+ "path",
+ nargs="?",
+ help="trace .jsonl file or directory containing .jsonl files "
+ "(default: ~/.jiuwenswarm/.trace)",
+ )
+ parser.add_argument(
+ "--dir",
+ help="directory containing .jsonl trace files (alternative to positional path)",
+ )
+ parser.add_argument(
+ "--file",
+ help="single .jsonl trace file (alternative to positional path)",
+ )
+ parser.add_argument("--endpoint", default=_COLLECTOR)
+ args = parser.parse_args()
+
+ path = _resolve_input_path(args) or _default_traces_dir()
+
+ files = _collect_files(path)
+ if files is None:
+ _logger.error("path not found: %s", path)
+ return 2
+ if not files:
+ _logger.error("no *.jsonl found under %s", path)
+ return 2
+
+ _logger.info("source=%s files=%d endpoint=%s", path, len(files), args.endpoint)
+
+ total_ok = 0
+ total_fail = 0
+ uploaded_trace_ids: list[str] = []
+ t0 = time.time()
+ for fpath in files:
+ ok, fail, trace_ids = _upload_one(fpath, args.endpoint)
+ total_ok += ok
+ total_fail += fail
+ uploaded_trace_ids.extend(trace_ids)
+
+ elapsed = time.time() - t0
+ _logger.info(
+ "total_lines=%d ok=%d fail=%d elapsed=%.1fs",
+ total_ok + total_fail,
+ total_ok,
+ total_fail,
+ elapsed,
+ )
+
+ unique_ids = list(dict.fromkeys(uploaded_trace_ids))
+ if unique_ids:
+ _logger.info("trace_ids (%d):", len(unique_ids))
+ for tid in unique_ids:
+ _logger.info(" %s", tid)
+ else:
+ _logger.warning("no trace ids parsed from uploaded files")
+
+ return 0 if total_fail == 0 and total_ok > 0 else 1
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/jiuwenswarm/agents/harness/team/team_manager.py b/jiuwenswarm/agents/harness/team/team_manager.py
index c9442356d0..83a9b3b1f8 100644
--- a/jiuwenswarm/agents/harness/team/team_manager.py
+++ b/jiuwenswarm/agents/harness/team/team_manager.py
@@ -27,6 +27,7 @@ from openjiuwen.harness.rails import (
TeamSkillEvolutionRail,
)
from jiuwenswarm.agents.harness.team.bootstrap import configure_agent_teams_home
+from jiuwenswarm.common.utils import get_user_workspace_dir
configure_agent_teams_home()
@@ -120,13 +121,21 @@ def sync_team_observability() -> None:
redact_completions=cfg.get("redact_completions", False),
langfuse_public_key=cfg.get("langfuse_public_key", ""),
langfuse_secret_key=cfg.get("langfuse_secret_key", ""),
+ traces_dir=cfg.get("traces_dir") or str(get_user_workspace_dir() / ".trace"),
+ file_retention_days=cfg.get("file_retention_days", 7),
)
init_observability(obs_cfg)
_observability_active = True
- logger.info(
- "[TeamObservability] enabled: exporter=%s endpoint=%s",
- obs_cfg.exporter, obs_cfg.endpoint,
- )
+ if obs_cfg.exporter == "file":
+ logger.info(
+ "[TeamObservability] enabled: exporter=%s traces_dir=%s",
+ obs_cfg.exporter, obs_cfg.traces_dir,
+ )
+ else:
+ 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)
diff --git a/jiuwenswarm/resources/config.yaml b/jiuwenswarm/resources/config.yaml
index 7130bb3c1b..fc09eff70a 100644
--- a/jiuwenswarm/resources/config.yaml
+++ b/jiuwenswarm/resources/config.yaml
@@ -333,9 +333,9 @@ telemetry:
# 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
+ enabled: false # Team observability 总开关
+ exporter: file # otlp_grpc / otlp_http / file
+ endpoint: http://localhost:4317 # OTLP gRPC endpoint(file 模式不需要)
service_name: jiuwenswarm # 服务名称(OTel resource service.name)
sample_rate: 1.0 # 采样率 (0.0-1.0)
redact_prompts: false # 是否脱敏 prompt 内容
@@ -343,6 +343,8 @@ team_observability:
attribute_value_max_length: 10240 # OTel attribute value 最大长度
langfuse_public_key: "" # Langfuse OTLP 认证 public key(可选)
langfuse_secret_key: "" # Langfuse OTLP 认证 secret key(可选)
+ traces_dir: "" # file exporter 输出目录,默认 ~/.jiuwenswarm/.trace
+ file_retention_days: 7 # file exporter 文件保留天数
react:
agent_name: main_agent