File size: 21,918 Bytes
fb52d98 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 | #!/usr/bin/env uv run
"""
Claude Code -> Langfuse hook
Sends Claude Code conversation turns to Langfuse as traces with spans,
generations, and tool observations. Runs on the "Stop" hook (after each
assistant turn) and reads the JSONL transcript incrementally.
Setup
=====
1. Register the hook in .claude/settings.json (committed to repo):
{
"hooks": {
"Stop": [
{
"hooks": [
{
"type": "command",
"command": "uv run --project /path/to/project .claude/hooks/langfuse_hook.py"
}
]
}
]
}
}
2. Add credentials and config in .claude/settings.local.json (gitignored):
{
"env": {
"TRACE_TO_LANGFUSE": "true",
"LANGFUSE_PUBLIC_KEY": "pk-lf-...",
"LANGFUSE_SECRET_KEY": "sk-lf-...",
"LANGFUSE_BASE_URL": "https://cloud.langfuse.com",
"CC_LANGFUSE_USER_ID": "user@example.com",
"CC_LANGFUSE_ENVIRONMENT": "my-project"
}
}
Environment variables
=====================
Required (in settings.local.json env):
TRACE_TO_LANGFUSE Set to "true" to enable tracing.
LANGFUSE_PUBLIC_KEY Langfuse project public key.
LANGFUSE_SECRET_KEY Langfuse project secret key.
Optional:
LANGFUSE_BASE_URL Langfuse host (default: https://cloud.langfuse.com).
CC_LANGFUSE_USER_ID User ID attached to all traces (e.g. email).
CC_LANGFUSE_ENVIRONMENT Environment name for Langfuse (e.g. project name).
Must match: ^(?!langfuse)[a-z0-9-_]+$ (max 40 chars).
CC_LANGFUSE_DEBUG Set to "true" for verbose logging.
CC_LANGFUSE_MAX_CHARS Max characters before truncation (default: 20000).
Trace metadata
==============
Each trace/span includes the following metadata keys:
source Always "claude-code".
session_id Claude Code session UUID.
turn_number Sequential turn number within the session.
transcript_path Local path to the JSONL transcript file.
user_text Truncation info for the user message.
host_ip Public IP of the machine (via api.ipify.org).
host_name OS hostname of the machine.
host_cwd Working directory where Claude Code was invoked.
Notes
=====
- settings.json is committed and shared; settings.local.json holds secrets
and per-user config and should be gitignored.
- The hook fails open: if Langfuse is unreachable or misconfigured, Claude
Code continues normally.
"""
import json
import os
import socket
import sys
import time
import hashlib
from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
# --- Langfuse import (fail-open) ---
try:
from langfuse import Langfuse, propagate_attributes
except Exception:
sys.exit(0)
# --- Paths ---
STATE_DIR = Path.home() / ".claude" / "state"
LOG_FILE = STATE_DIR / "langfuse_hook.log"
STATE_FILE = STATE_DIR / "langfuse_state.json"
LOCK_FILE = STATE_DIR / "langfuse_state.lock"
DEBUG = os.environ.get("CC_LANGFUSE_DEBUG", "").lower() == "true"
MAX_CHARS = int(os.environ.get("CC_LANGFUSE_MAX_CHARS", "20000"))
# ----------------- Logging -----------------
def _log(level: str, message: str) -> None:
try:
STATE_DIR.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(LOG_FILE, "a", encoding="utf-8") as f:
f.write(f"{ts} [{level}] {message}\n")
except Exception:
# Never block
pass
def debug(msg: str) -> None:
if DEBUG:
_log("DEBUG", msg)
def info(msg: str) -> None:
_log("INFO", msg)
def warn(msg: str) -> None:
_log("WARN", msg)
def error(msg: str) -> None:
_log("ERROR", msg)
# ----------------- State locking (best-effort) -----------------
class FileLock:
def __init__(self, path: Path, timeout_s: float = 2.0):
self.path = path
self.timeout_s = timeout_s
self._fh = None
def __enter__(self):
STATE_DIR.mkdir(parents=True, exist_ok=True)
self._fh = open(self.path, "a+", encoding="utf-8")
try:
import fcntl # Unix only
deadline = time.time() + self.timeout_s
while True:
try:
fcntl.flock(self._fh.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
break
except BlockingIOError:
if time.time() > deadline:
break
time.sleep(0.05)
except Exception:
# If locking isn't available, proceed without it.
pass
return self
def __exit__(self, exc_type, exc, tb):
try:
import fcntl
fcntl.flock(self._fh.fileno(), fcntl.LOCK_UN)
except Exception:
pass
try:
self._fh.close()
except Exception:
pass
def load_state() -> Dict[str, Any]:
try:
if not STATE_FILE.exists():
return {}
return json.loads(STATE_FILE.read_text(encoding="utf-8"))
except Exception:
return {}
def save_state(state: Dict[str, Any]) -> None:
try:
STATE_DIR.mkdir(parents=True, exist_ok=True)
tmp = STATE_FILE.with_suffix(".tmp")
tmp.write_text(json.dumps(state, indent=2, sort_keys=True), encoding="utf-8")
os.replace(tmp, STATE_FILE)
except Exception as e:
debug(f"save_state failed: {e}")
def state_key(session_id: str, transcript_path: str) -> str:
# stable key even if session_id collides
raw = f"{session_id}::{transcript_path}"
return hashlib.sha256(raw.encode("utf-8")).hexdigest()
# ----------------- Hook payload -----------------
def read_hook_payload() -> Dict[str, Any]:
"""
Claude Code hooks pass a JSON payload on stdin.
This script tolerates missing/empty stdin by returning {}.
"""
try:
data = sys.stdin.read()
if not data.strip():
return {}
return json.loads(data)
except Exception:
return {}
def extract_session_and_transcript(
payload: Dict[str, Any],
) -> Tuple[Optional[str], Optional[Path]]:
"""
Tries a few plausible field names; exact keys can vary across hook types/versions.
Prefer structured values from stdin over heuristics.
"""
session_id = (
payload.get("sessionId")
or payload.get("session_id")
or payload.get("session", {}).get("id")
)
transcript = (
payload.get("transcriptPath")
or payload.get("transcript_path")
or payload.get("transcript", {}).get("path")
)
if transcript:
try:
transcript_path = Path(transcript).expanduser().resolve()
except Exception:
transcript_path = None
else:
transcript_path = None
return session_id, transcript_path
# ----------------- Transcript parsing helpers -----------------
def get_content(msg: Dict[str, Any]) -> Any:
if not isinstance(msg, dict):
return None
if "message" in msg and isinstance(msg.get("message"), dict):
return msg["message"].get("content")
return msg.get("content")
def get_role(msg: Dict[str, Any]) -> Optional[str]:
# Claude Code transcript lines commonly have type=user/assistant OR message.role
t = msg.get("type")
if t in ("user", "assistant"):
return t
m = msg.get("message")
if isinstance(m, dict):
r = m.get("role")
if r in ("user", "assistant"):
return r
return None
def is_tool_result(msg: Dict[str, Any]) -> bool:
role = get_role(msg)
if role != "user":
return False
content = get_content(msg)
if isinstance(content, list):
return any(
isinstance(x, dict) and x.get("type") == "tool_result" for x in content
)
return False
def iter_tool_results(content: Any) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
if isinstance(content, list):
for x in content:
if isinstance(x, dict) and x.get("type") == "tool_result":
out.append(x)
return out
def iter_tool_uses(content: Any) -> List[Dict[str, Any]]:
out: List[Dict[str, Any]] = []
if isinstance(content, list):
for x in content:
if isinstance(x, dict) and x.get("type") == "tool_use":
out.append(x)
return out
def extract_text(content: Any) -> str:
if isinstance(content, str):
return content
if isinstance(content, list):
parts: List[str] = []
for x in content:
if isinstance(x, dict) and x.get("type") == "text":
parts.append(x.get("text", ""))
elif isinstance(x, str):
parts.append(x)
return "\n".join([p for p in parts if p])
return ""
def truncate_text(s: str, max_chars: int = MAX_CHARS) -> Tuple[str, Dict[str, Any]]:
if s is None:
return "", {"truncated": False, "orig_len": 0}
orig_len = len(s)
if orig_len <= max_chars:
return s, {"truncated": False, "orig_len": orig_len}
head = s[:max_chars]
return head, {
"truncated": True,
"orig_len": orig_len,
"kept_len": len(head),
"sha256": hashlib.sha256(s.encode("utf-8")).hexdigest(),
}
def get_model(msg: Dict[str, Any]) -> str:
m = msg.get("message")
if isinstance(m, dict):
return m.get("model") or "claude"
return "claude"
def get_message_id(msg: Dict[str, Any]) -> Optional[str]:
m = msg.get("message")
if isinstance(m, dict):
mid = m.get("id")
if isinstance(mid, str) and mid:
return mid
return None
# ----------------- Incremental reader -----------------
@dataclass
class SessionState:
offset: int = 0
buffer: str = ""
turn_count: int = 0
def load_session_state(global_state: Dict[str, Any], key: str) -> SessionState:
s = global_state.get(key, {})
return SessionState(
offset=int(s.get("offset", 0)),
buffer=str(s.get("buffer", "")),
turn_count=int(s.get("turn_count", 0)),
)
def write_session_state(
global_state: Dict[str, Any], key: str, ss: SessionState
) -> None:
global_state[key] = {
"offset": ss.offset,
"buffer": ss.buffer,
"turn_count": ss.turn_count,
"updated": datetime.now(timezone.utc).isoformat(),
}
def read_new_jsonl(
transcript_path: Path, ss: SessionState
) -> Tuple[List[Dict[str, Any]], SessionState]:
"""
Reads only new bytes since ss.offset. Keeps ss.buffer for partial last line.
Returns parsed JSON lines (best-effort) and updated state.
"""
if not transcript_path.exists():
return [], ss
try:
with open(transcript_path, "rb") as f:
f.seek(ss.offset)
chunk = f.read()
new_offset = f.tell()
except Exception as e:
debug(f"read_new_jsonl failed: {e}")
return [], ss
if not chunk:
return [], ss
try:
text = chunk.decode("utf-8", errors="replace")
except Exception:
text = chunk.decode(errors="replace")
combined = ss.buffer + text
lines = combined.split("\n")
# last element may be incomplete
ss.buffer = lines[-1]
ss.offset = new_offset
msgs: List[Dict[str, Any]] = []
for line in lines[:-1]:
line = line.strip()
if not line:
continue
try:
msgs.append(json.loads(line))
except Exception:
continue
return msgs, ss
# ----------------- Turn assembly -----------------
@dataclass
class Turn:
user_msg: Dict[str, Any]
assistant_msgs: List[Dict[str, Any]]
tool_results_by_id: Dict[str, Any]
def build_turns(messages: List[Dict[str, Any]]) -> List[Turn]:
"""
Groups incremental transcript rows into turns:
user (non-tool-result) -> assistant messages -> (tool_result rows, possibly interleaved)
Uses:
- assistant message dedupe by message.id (latest row wins)
- tool results dedupe by tool_use_id (latest wins)
"""
turns: List[Turn] = []
current_user: Optional[Dict[str, Any]] = None
# assistant messages for current turn:
assistant_order: List[
str
] = [] # message ids in order of first appearance (or synthetic)
assistant_latest: Dict[str, Dict[str, Any]] = {} # id -> latest msg
tool_results_by_id: Dict[str, Any] = {} # tool_use_id -> content
def flush_turn():
nonlocal \
current_user, \
assistant_order, \
assistant_latest, \
tool_results_by_id, \
turns
if current_user is None:
return
if not assistant_latest:
return
assistants = [
assistant_latest[mid] for mid in assistant_order if mid in assistant_latest
]
turns.append(
Turn(
user_msg=current_user,
assistant_msgs=assistants,
tool_results_by_id=dict(tool_results_by_id),
)
)
for msg in messages:
role = get_role(msg)
# tool_result rows show up as role=user with content blocks of type tool_result
if is_tool_result(msg):
for tr in iter_tool_results(get_content(msg)):
tid = tr.get("tool_use_id")
if tid:
tool_results_by_id[str(tid)] = tr.get("content")
continue
if role == "user":
# new user message -> finalize previous turn
flush_turn()
# start a new turn
current_user = msg
assistant_order = []
assistant_latest = {}
tool_results_by_id = {}
continue
if role == "assistant":
if current_user is None:
# ignore assistant rows until we see a user message
continue
mid = get_message_id(msg) or f"noid:{len(assistant_order)}"
if mid not in assistant_latest:
assistant_order.append(mid)
assistant_latest[mid] = msg
continue
# ignore unknown rows
# flush last
flush_turn()
return turns
# ----------------- Langfuse emit -----------------
def _tool_calls_from_assistants(
assistant_msgs: List[Dict[str, Any]],
) -> List[Dict[str, Any]]:
calls: List[Dict[str, Any]] = []
for am in assistant_msgs:
for tu in iter_tool_uses(get_content(am)):
tid = tu.get("id") or ""
calls.append(
{
"id": str(tid),
"name": tu.get("name") or "unknown",
"input": tu.get("input")
if isinstance(tu.get("input"), (dict, list, str, int, float, bool))
else {},
}
)
return calls
def emit_turn(
langfuse: Langfuse,
session_id: str,
turn_num: int,
turn: Turn,
transcript_path: Path,
host_meta: Optional[Dict[str, str]] = None,
) -> None:
user_text_raw = extract_text(get_content(turn.user_msg))
user_text, user_text_meta = truncate_text(user_text_raw)
last_assistant = turn.assistant_msgs[-1]
assistant_text_raw = extract_text(get_content(last_assistant))
assistant_text, assistant_text_meta = truncate_text(assistant_text_raw)
model = get_model(turn.assistant_msgs[0])
tool_calls = _tool_calls_from_assistants(turn.assistant_msgs)
# attach tool outputs
for c in tool_calls:
if c["id"] and c["id"] in turn.tool_results_by_id:
out_raw = turn.tool_results_by_id[c["id"]]
out_str = (
out_raw
if isinstance(out_raw, str)
else json.dumps(out_raw, ensure_ascii=False)
)
out_trunc, out_meta = truncate_text(out_str)
c["output"] = out_trunc
c["output_meta"] = out_meta
else:
c["output"] = None
user_id = os.environ.get("CC_LANGFUSE_USER_ID")
with propagate_attributes(
session_id=session_id,
user_id=user_id,
trace_name=f"Claude Code - Turn {turn_num}",
tags=["claude-code"],
metadata=host_meta or None,
):
with langfuse.start_as_current_span(
name=f"Claude Code - Turn {turn_num}",
input={"role": "user", "content": user_text},
metadata={
"source": "claude-code",
"session_id": session_id,
"turn_number": turn_num,
"transcript_path": str(transcript_path),
"user_text": user_text_meta,
**(host_meta or {}),
},
) as trace_span:
# LLM generation
with langfuse.start_as_current_observation(
name="Claude Response",
as_type="generation",
model=model,
input={"role": "user", "content": user_text},
output={"role": "assistant", "content": assistant_text},
metadata={
"assistant_text": assistant_text_meta,
"tool_count": len(tool_calls),
},
):
pass
# Tool observations
for tc in tool_calls:
in_obj = tc["input"]
# truncate tool input if it's a large string payload
if isinstance(in_obj, str):
in_obj, in_meta = truncate_text(in_obj)
else:
in_meta = None
with langfuse.start_as_current_observation(
name=f"Tool: {tc['name']}",
as_type="tool",
input=in_obj,
metadata={
"tool_name": tc["name"],
"tool_id": tc["id"],
"input_meta": in_meta,
"output_meta": tc.get("output_meta"),
},
) as tool_obs:
tool_obs.update(output=tc.get("output"))
trace_span.update(output={"role": "assistant", "content": assistant_text})
# ----------------- Main -----------------
def main() -> int:
start = time.time()
debug("Hook started")
if os.environ.get("TRACE_TO_LANGFUSE", "").lower() != "true":
return 0
public_key = os.environ.get("CC_LANGFUSE_PUBLIC_KEY") or os.environ.get(
"LANGFUSE_PUBLIC_KEY"
)
secret_key = os.environ.get("CC_LANGFUSE_SECRET_KEY") or os.environ.get(
"LANGFUSE_SECRET_KEY"
)
host = (
os.environ.get("CC_LANGFUSE_BASE_URL")
or os.environ.get("LANGFUSE_BASE_URL")
or "https://cloud.langfuse.com"
)
if not public_key or not secret_key:
return 0
# Set environment for Langfuse tracing (must be set before client init)
environment = os.environ.get("CC_LANGFUSE_ENVIRONMENT")
if environment:
os.environ.setdefault("LANGFUSE_TRACING_ENVIRONMENT", environment)
# Build host identifier for metadata
try:
import urllib.request
public_ip = (
urllib.request.urlopen("https://api.ipify.org", timeout=2)
.read()
.decode()
.strip()
)
except Exception:
public_ip = "unknown"
host_meta = {
"host_ip": public_ip,
"host_name": socket.gethostname(),
"host_cwd": os.getcwd(),
}
payload = read_hook_payload()
session_id, transcript_path = extract_session_and_transcript(payload)
if not session_id or not transcript_path:
# No structured payload; fail open (do not guess)
debug("Missing session_id or transcript_path from hook payload; exiting.")
return 0
if not transcript_path.exists():
debug(f"Transcript path does not exist: {transcript_path}")
return 0
try:
langfuse = Langfuse(
public_key=public_key,
secret_key=secret_key,
host=host,
environment=environment,
)
except Exception:
return 0
try:
with FileLock(LOCK_FILE):
state = load_state()
key = state_key(session_id, str(transcript_path))
ss = load_session_state(state, key)
msgs, ss = read_new_jsonl(transcript_path, ss)
if not msgs:
write_session_state(state, key, ss)
save_state(state)
return 0
turns = build_turns(msgs)
if not turns:
write_session_state(state, key, ss)
save_state(state)
return 0
# emit turns
emitted = 0
for t in turns:
emitted += 1
turn_num = ss.turn_count + emitted
try:
emit_turn(
langfuse, session_id, turn_num, t, transcript_path, host_meta
)
except Exception as e:
debug(f"emit_turn failed: {e}")
# continue emitting other turns
ss.turn_count += emitted
write_session_state(state, key, ss)
save_state(state)
try:
langfuse.flush()
except Exception:
pass
dur = time.time() - start
info(f"Processed {emitted} turns in {dur:.2f}s (session={session_id})")
return 0
except Exception as e:
debug(f"Unexpected failure: {e}")
return 0
finally:
try:
langfuse.shutdown()
except Exception:
pass
if __name__ == "__main__":
sys.exit(main())
|