""" Test Langfuse v4 connectivity and trace ingestion. Usage: python scripts/test_langfuse.py Reads LANGFUSE_PUBLIC_KEY, LANGFUSE_SECRET_KEY, LANGFUSE_HOST from .env and sends a synthetic trace so you can verify it appears in the Langfuse UI. """ from __future__ import annotations import sys import time import os # ── Load .env before anything else ─────────────────────────────────────────── from dotenv import load_dotenv load_dotenv() def _require(key: str) -> str: val = os.getenv(key, "").strip() if not val: print(f"[FAIL] {key} is not set in .env") sys.exit(1) return val def main() -> None: public_key = _require("LANGFUSE_PUBLIC_KEY") secret_key = _require("LANGFUSE_SECRET_KEY") host = os.getenv("LANGFUSE_HOST", "https://cloud.langfuse.com") print(f"Langfuse host : {host}") print(f"Public key : {public_key[:8]}…") print() # ── 1. Init client ──────────────────────────────────────────────────────── print("[1/6] Initialising Langfuse client …") try: from langfuse import Langfuse lf = Langfuse( public_key=public_key, secret_key=secret_key, host=host, ) print(" OK") except Exception as e: print(f"[FAIL] Could not create Langfuse client: {e}") sys.exit(1) # ── 2. Auth check ───────────────────────────────────────────────────────── print("[2/6] Running auth check …") try: lf.auth_check() print(" OK — credentials are valid") except Exception as e: print(f"[FAIL] Auth check failed: {e}") print(" Make sure LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY are correct.") sys.exit(1) # ── 3. Create a root trace span ─────────────────────────────────────────── print("[3/6] Creating root trace span (simulating a query) …") try: root = lf.start_observation( name="acpc-test-query", as_type="span", input="What is the cutoff for LDCE computer engineering?", metadata={ "session_id": "test-session-001", "language": "en-IN", "test": True, }, ) trace_id = getattr(root, "trace_id", None) print(f" OK — trace_id = {trace_id}") except Exception as e: print(f"[FAIL] start_observation failed: {e}") sys.exit(1) # ── 4. Add child spans (routing / retrieval / generation) ───────────────── print("[4/6] Adding child spans …") try: # Guardrail event root.create_event( name="guardrail_in", metadata={"passed": True, "category": "ok"}, ) # Routing span routing = root.start_observation( name="routing", as_type="span", input="What is the cutoff for LDCE computer engineering?", output={"path": "sql", "confidence": 0.95, "reason": "cutoff query"}, metadata={"latency_ms": 120}, ) routing.end() # Retrieval span retrieval = root.start_observation( name="retrieval", as_type="retriever", input={"path": "sql"}, output={"sql_rows": 12, "rag_chunks": 0}, metadata={"latency_ms": 230}, ) retrieval.end() # Generation span generation = root.start_observation( name="generation", as_type="generation", model="openai/gpt-4o-mini", input={"context_tokens_est": 800}, output="Here are the cutoffs for LDCE Computer Engineering…", metadata={"latency_ms": 1400}, usage_details={"input": 820, "output": 190, "total": 1010}, ) generation.end() print(" OK — routing + retrieval + generation spans created") except Exception as e: print(f"[FAIL] Child span creation failed: {e}") sys.exit(1) # ── 5. End root trace ───────────────────────────────────────────────────── print("[5/6] Closing root trace …") try: root.update( output="The cutoff for LDCE Computer Engineering (Open HS) is 289.", metadata={ "path_taken": "sql", "total_latency_ms": 1750, "sql_rows_count": 12, "rag_chunks_count": 0, }, ) root.end() print(" OK") except Exception as e: print(f"[FAIL] root.end() failed: {e}") sys.exit(1) # ── 6. Score + flush ────────────────────────────────────────────────────── print("[6/6] Adding a test score and flushing …") try: if trace_id: lf.create_score( trace_id=trace_id, name="user_feedback", value=1.0, comment="thumbs_up | test score from test_langfuse.py", ) lf.flush() print(" OK") except Exception as e: print(f"[FAIL] Score / flush failed: {e}") sys.exit(1) print() print("=" * 60) print("All checks passed!") print(f"Trace ID : {trace_id}") if trace_id: # Langfuse cloud trace URL pattern clean_host = host.rstrip("/") print(f"View at : {clean_host}/trace/{trace_id}") print("=" * 60) if __name__ == "__main__": main()