Spaces:
Running
Running
Deploy ac9bb358
Browse filesFiles changed (5)
- app.py+60-5
- main.py+67-5
- nodes/retrieval.py+94-23
- observability.py+218-14
- scripts/alert.py+5-1
30 unmodified lines31323334353654 unmodified lines91929394959697989910017 unmodified lines118119120121122123165 unmodified lines28929029129229329429526 unmodified lines32232332432532632732832933033130 unmodified linesestimate_groq_cost,format_cost,log_error_to_backends,HealthStatus,TokenCostCallback,check_groq_connectivity,54 unmodified lines"""Build the graph, stream up to the interrupt, and return state + config."""graph = build_graph(DB_PATH)thread_id = str(uuid.uuid4())handler = get_langfuse_handler()cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="gradio_ui", repo=repo, pr_number=pr_number, session_id=thread_id,)config: dict = {"configurable": {"thread_id": f"web-{thread_id}"},17 unmodified linesraisestate = graph.get_state(config)return state, config, cost_tracker.summary()165 unmodified linesconfig = json.loads(config_json)graph = build_graph(DB_PATH)handler = get_langfuse_handler()cost_tracker = TokenCostCallback()callbacks = [cost_tracker]if handler:26 unmodified linesprogress(0.1, desc="Building graphβ¦")graph = build_graph(DB_PATH)thread_id = str(uuid.uuid4())handler = get_langfuse_handler()cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="gradio_ui", repo="demo-org/demo-repo", pr_number=1, session_id=thread_id,)config: dict = {"configurable": {"thread_id": f"smoke-web-{thread_id}"},30 unmodified lines3132333435363754 unmodified lines929394959697989910010110210310410510610710810911011111211311411511611711811912012117 unmodified lines139140141142143144145146147148149150151152153154155156157158159160161162165 unmodified lines32832933033133233333433533633726 unmodified lines36436536636736836937037137237337437537637737837938038138238338438538630 unmodified linesestimate_groq_cost,format_cost,log_error_to_backends,log_langfuse_score,HealthStatus,TokenCostCallback,check_groq_connectivity,54 unmodified lines"""Build the graph, stream up to the interrupt, and return state + config."""graph = build_graph(DB_PATH)thread_id = str(uuid.uuid4())trace_name = f"opencodereview/review/{repo}#{pr_number}"tags = ["gradio_ui", repo]prompt_versions = {"correctness": "v1","security": "v1","test_coverage": "v1","aggregator": "v1",}handler = get_langfuse_handler(trace_name=trace_name,tags=tags,session_id=thread_id,metadata={"source": "gradio_ui","repo": repo,"pr_number": pr_number,"prompt_versions": prompt_versions,},)cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="gradio_ui", repo=repo, pr_number=pr_number,session_id=thread_id,prompt_versions=prompt_versions,)config: dict = {"configurable": {"thread_id": f"web-{thread_id}"},17 unmodified linesraisestate = graph.get_state(config)# Log verdict and findings scores to Langfuse (linked to trace via handler)verdict = state.values.get("verdict")findings = state.values.get("final_findings", [])if verdict:log_langfuse_score(name="verdict_score",value=verdict.overall_score,comment=f"{repo}#{pr_number} β {verdict.recommendation}: {verdict.summary[:100]}",handler=handler,)log_langfuse_score(name="findings_count",value=len(findings),comment=f"{repo}#{pr_number}",handler=handler,)return state, config, cost_tracker.summary()165 unmodified linesconfig = json.loads(config_json)graph = build_graph(DB_PATH)handler = get_langfuse_handler(trace_name="opencodereview/resume",tags=["gradio_ui", "resume"],)cost_tracker = TokenCostCallback()callbacks = [cost_tracker]if handler:26 unmodified linesprogress(0.1, desc="Building graphβ¦")graph = build_graph(DB_PATH)thread_id = str(uuid.uuid4())prompt_versions = {"correctness": "v1","security": "v1","test_coverage": "v1","aggregator": "v1",}handler = get_langfuse_handler(trace_name="opencodereview/smoke-test",tags=["gradio_ui", "smoke", "demo-org/demo-repo"],session_id=thread_id,metadata={"prompt_versions": prompt_versions},)cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="gradio_ui", repo="demo-org/demo-repo", pr_number=1,session_id=thread_id,prompt_versions=prompt_versions,)config: dict = {"configurable": {"thread_id": f"smoke-web-{thread_id}"},
31 unmodified lines323334353637156 unmodified lines19419519619719819920020120220355 unmodified lines25926026126226326426526626741 unmodified lines30931031131231331431531631731831 unmodified linesestimate_groq_cost,format_cost,log_error_to_backends,TokenCostCallback,)from state import ChangedFile, ContextChunk, Finding, Severity, Verdict156 unmodified lines"""Run the graph on a real PR β fetches data from GitHub, pauses forhuman approval, then posts findings back as PR comments."""thread_id = str(uuid.uuid4())handler = get_langfuse_handler()cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo=repo, pr_number=pr_number, session_id=thread_id,)config: dict = {"configurable": {"thread_id": f"hitl-{thread_id}"},55 unmodified lines)logger.info(" %s", f.comment[:120])# Show costlogger.info(" %s", cost_tracker.summary())logger.info("=" * 60)click.echo()41 unmodified linesdef _test_offline(graph) -> None:"""Non-interactive test that the graph compiles and runs up to interrupt."""thread_id = str(uuid.uuid4())handler = get_langfuse_handler()cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo="demo-org/demo-repo", pr_number=1, session_id=thread_id,)config: dict = {"configurable": {"thread_id": f"smoke-{thread_id}"},31 unmodified lines3233343536373839156 unmodified lines19619719819920020120220320420520620720820921021121221321421521621721821922022122222322422555 unmodified lines28128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531641 unmodified lines35835936036136236336436536636736836937037137237337437537637737837938031 unmodified linesestimate_groq_cost,format_cost,log_error_to_backends,log_langfuse_score,update_langfuse_trace,TokenCostCallback,)from state import ChangedFile, ContextChunk, Finding, Severity, Verdict156 unmodified lines"""Run the graph on a real PR β fetches data from GitHub, pauses forhuman approval, then posts findings back as PR comments."""thread_id = str(uuid.uuid4())trace_name = f"opencodereview/review/{repo}#{pr_number}"tags = ["cli", repo]prompt_versions = {"correctness": "v1","security": "v1","test_coverage": "v1","aggregator": "v1",}handler = get_langfuse_handler(trace_name=trace_name,tags=tags,session_id=thread_id,metadata={"source": "cli","repo": repo,"pr_number": pr_number,"prompt_versions": prompt_versions,},)cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo=repo, pr_number=pr_number,session_id=thread_id,prompt_versions=prompt_versions,)config: dict = {"configurable": {"thread_id": f"hitl-{thread_id}"},55 unmodified lines)logger.info(" %s", f.comment[:120])# Show cost & TTFTlogger.info(" %s", cost_tracker.summary())# Log verdict score to Langfuse and update trace metadataif state.values.get("verdict"):v = state.values["verdict"]log_langfuse_score(name="verdict_score",value=v.overall_score,comment=f"{repo}#{pr_number} β {v.recommendation}: {v.summary[:100]}",handler=handler,)log_langfuse_score(name="findings_count",value=len(final_findings),comment=f"{repo}#{pr_number}",handler=handler,)if handler:update_langfuse_trace(tags=tags + [f"verdict:{v.recommendation}"],metadata={"verdict_score": v.overall_score,"findings_count": len(final_findings),"recommendation": v.recommendation,},trace_name=trace_name,handler=handler,)logger.info("=" * 60)click.echo()41 unmodified linesdef _test_offline(graph) -> None:"""Non-interactive test that the graph compiles and runs up to interrupt."""thread_id = str(uuid.uuid4())prompt_versions = {"correctness": "v1","security": "v1","test_coverage": "v1","aggregator": "v1",}handler = get_langfuse_handler(trace_name="opencodereview/smoke-test",tags=["cli", "smoke", "demo-org/demo-repo"],session_id=thread_id,metadata={"prompt_versions": prompt_versions},)cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo="demo-org/demo-repo", pr_number=1,session_id=thread_id,prompt_versions=prompt_versions,)config: dict = {"configurable": {"thread_id": f"smoke-{thread_id}"},
4 unmodified lines5678910156 unmodified lines16716816917017117229 unmodified lines20220320420520620720820921013 unmodified lines22422522622722822923023123223323423523641 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073084 unmodified linesimport reimport tempfileimport uuidfrom typing import Optionalimport requests156 unmodified lines# βββ Helpers: building the vector store βββββββββββββββββββββββββββββββββββββ_VECTOR_DIR: str | None = None29 unmodified linesif chromadb is None:raise RuntimeError("chromadb is not installed β cannot build vector store")ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")client = chromadb.PersistentClient(path=_ensure_vector_dir())coll_name = _repo_collection_name(f"{owner}/{repo_name}")13 unmodified lines)client.delete_collection(coll_name)except Exception:pass # First build or error β create freshreturn _build_vector_store(owner, repo_name, head_sha, exclude_paths, client, coll_name, ef,)def _build_vector_store(owner: str, repo_name: str,head_sha: str,41 unmodified linesand _should_include(item["path"])and item["path"] not in exclude_paths]logger.info("Source files to embed (excl. changed): %d", len(source_paths))code_docs: list[str] = []code_metadatas: list[dict] = []code_ids: list[str] = []for fp in source_paths:raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{fp}"try:resp = requests.get(raw_url, timeout=30)if resp.status_code != 200:continuecontent = resp.textexcept requests.RequestException:continuefile_chunks = _chunk_source(fp, content)for chunk in file_chunks:code_docs.append(chunk["text"])code_metadatas.append({"source": "codebase","file_path": fp,"chunk_type": chunk["type"],})code_ids.append(str(uuid.uuid4()))if code_docs:collection.add(4 unmodified lines567891011156 unmodified lines16816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120229 unmodified lines23223323423523623723813 unmodified lines25225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130241 unmodified lines3443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783794 unmodified linesimport reimport tempfileimport uuidfrom concurrent.futures import ThreadPoolExecutor, as_completedfrom typing import Optionalimport requests156 unmodified lines# βββ Helpers: building the vector store βββββββββββββββββββββββββββββββββββββ# βββ Global embedding-function cache ββββββββββββββββββββββββββββββββββββββββ# The ChromaDB SentenceTransformer embedding function loads a ~90 MB PyTorch# model from disk every time it is instantiated, which takes ~20 s. Cache it# at module level and prefer the ONNX variant (loads in <1 s)._EMBEDDING_FN = Nonedef _get_embedding_fn():"""Return a cached embedding function (ONNX MiniLM, loaded once per process)."""global _EMBEDDING_FNif _EMBEDDING_FN is not None:return _EMBEDDING_FN# Prefer the ONNX-optimised variant (loads <1 s vs ~20 s for PyTorch)if hasattr(embedding_functions, "ONNXMiniLM_L6_V2"):logger.info("Using ONNX MiniLM embedding function (faster load)")_EMBEDDING_FN = embedding_functions.ONNXMiniLM_L6_V2()elif hasattr(embedding_functions, "SentenceTransformerEmbeddingFunction"):logger.info("Using SentenceTransformer embedding function")_EMBEDDING_FN = embedding_functions.SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")else:raise RuntimeError("No usable ChromaDB embedding function found. Install with: ""pip install chromadb (includes ONNX MiniLM support)")return _EMBEDDING_FN_VECTOR_DIR: str | None = None29 unmodified linesif chromadb is None:raise RuntimeError("chromadb is not installed β cannot build vector store")ef = _get_embedding_fn()client = chromadb.PersistentClient(path=_ensure_vector_dir())coll_name = _repo_collection_name(f"{owner}/{repo_name}")13 unmodified lines)client.delete_collection(coll_name)except Exception:# Collection doesn't exist or is incompatible (e.g. different# embedding function class) β delete any remnants and create fresh.try:client.delete_collection(coll_name)except Exception:passreturn _build_vector_store(owner, repo_name, head_sha, exclude_paths, client, coll_name, ef,)def _fetch_and_chunk_file(fp: str, owner: str, repo_name: str, head_sha: str,) -> list[dict]:"""Fetch a single source file from GitHub and return its chunks.Called by :class:`ThreadPoolExecutor` workers to parallelise theI/O-bound file-fetching phase of vector-store construction.Returns an empty list on any error (404, timeout, etc.)"""raw_url = f"{RAW_CONTENT_BASE}/{owner}/{repo_name}/{head_sha}/{fp}"try:resp = requests.get(raw_url, timeout=30)if resp.status_code != 200:return []content = resp.textexcept requests.RequestException:return []chunks = _chunk_source(fp, content)result: list[dict] = []for chunk in chunks:result.append({"text": chunk["text"],"meta": {"source": "codebase","file_path": fp,"chunk_type": chunk["type"],},"id": str(uuid.uuid4()),})return resultdef _build_vector_store(owner: str, repo_name: str,head_sha: str,41 unmodified linesand _should_include(item["path"])and item["path"] not in exclude_paths]logger.info("Source files to embed (excl. changed): %d β fetching in parallel β¦",len(source_paths),)code_docs: list[str] = []code_metadatas: list[dict] = []code_ids: list[str] = []# Fetch files concurrently β I/O-bound network requests benefit# greatly from thread-level parallelism.with ThreadPoolExecutor(max_workers=10) as pool:futures = {pool.submit(_fetch_and_chunk_file, fp, owner, repo_name, head_sha): fpfor fp in source_paths}for future in as_completed(futures):fp = futures[future]try:file_result = future.result()except Exception as exc:logger.debug("Failed to fetch %s: %s", fp, exc)continuefor chunk in file_result:code_docs.append(chunk["text"])code_metadatas.append(chunk["meta"])code_ids.append(chunk["id"])if code_docs:collection.add(
27 unmodified lines28293031323359 unmodified lines9394959697989910010122 unmodified lines124125126127128129130210 unmodified lines34134234334434534634720 unmodified lines3683693703713723737 unmodified lines3813823833843853861 unmodified line3883893903913923933943953963973983994007 unmodified lines4084094104114124134144154164173 unmodified lines42142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245327 unmodified linesimport loggingimport osimport platformimport uuidfrom datetime import datetime, timezonefrom typing import Any, Optional59 unmodified lines# βββ Langfuse (explicit callback) ββββββββββββββββββββββββββββββββββββββββββdef get_langfuse_handler():"""Return a Langfuse ``CallbackHandler`` if keys are configured, else None.Reads ``LANGFUSE_PUBLIC_KEY``, ``LANGFUSE_SECRET_KEY``, and optionally``LANGFUSE_HOST`` from environment variables. In langfuse v4+ the``CallbackHandler`` only needs ``public_key``; the SDK reads22 unmodified linesLangfuse(additional_headers={"x-langfuse-ingestion-version": "4"},)return CallbackHandler()except ImportError:logger.warning("langfuse not available β skipping tracing",210 unmodified linesclass TokenCostCallback:"""Accumulates per-model token usage from LangChain LLM calls.Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` canbe imported even when ``langchain-core`` has version incompatibilities20 unmodified linesdef __init__(self) -> None:self.usage: list[dict[str, Any]] = []@propertydef total_input_tokens(self) -> int:7 unmodified linesdef total_cost(self) -> float:return sum(u.get("cost", 0.0) for u in self.usage)def on_chain_start(self, *args, **kwargs) -> None:pass1 unmodified linepassdef on_chat_model_start(self, *args, **kwargs) -> None:passdef on_llm_start(self, *args, **kwargs) -> None:passdef on_llm_error(self, error, **kwargs) -> None:passdef on_chain_error(self, error, **kwargs) -> None:pass7 unmodified linesdef on_llm_end(self, response, **kwargs) -> None:"""LangChain callback β called after each LLM invocation.``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and othermetadata that LangChain passes to callback handlers."""try:usage = response.llm_output or {}token_usage = usage.get("token_usage", {}) or {}model = usage.get("model_name", "") or ""3 unmodified linesif input_tokens > 0 or output_tokens > 0:cost = estimate_groq_cost(model, input_tokens, output_tokens)self.usage.append({"model": model,"input_tokens": input_tokens,"output_tokens": output_tokens,"cost": cost,})except Exception:pass # Best-effort β don't let cost tracking crash the rundef summary(self) -> str:"""Return a human-readable cost summary."""calls = len(self.usage)if calls == 0:return "Cost: N/A (no LLM calls captured)"return (f"Cost: {format_cost(self.total_cost)}"f" Β· {calls} LLM call(s)"f" Β· {self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens")def reset(self) -> None:self.usage.clear()# βββ Error event logging βββββββββββββββββββββββββββββββββββββββββββββββββ--def log_error_to_backends(error: Exception,context: Optional[dict[str, Any]] = None,27 unmodified lines2829303132333459 unmodified lines94959697989910010110210310410510610710810911011111211311411511611711811912012122 unmodified lines144145146147148149150151152153154155156210 unmodified lines36736836937037137237337437537637737820 unmodified lines3994004014024034044057 unmodified lines4134144154164174184194204214224234244254264274284294304314321 unmodified line4344354364374384394404414424434444454464474484494504514524534544557 unmodified lines4634644654664674684694704714724734744754764774784794803 unmodified lines48448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665727 unmodified linesimport loggingimport osimport platformimport timeimport uuidfrom datetime import datetime, timezonefrom typing import Any, Optional59 unmodified lines# βββ Langfuse (explicit callback) ββββββββββββββββββββββββββββββββββββββββββdef get_langfuse_handler(trace_name: str = "opencodereview",tags: Optional[list[str]] = None,user_id: Optional[str] = None,session_id: Optional[str] = None,metadata: Optional[dict[str, Any]] = None,):"""Return a Langfuse ``CallbackHandler`` if keys are configured, else None.Parameters----------trace_name : strName for the trace in Langfuse (e.g. ``"opencodereview/review/psf/requests#42"``).tags : list[str] or NoneTags attached to the trace for filtering in the Langfuse UI.user_id : str or NoneUser identifier associated with the trace.session_id : str or NoneSession identifier for grouping related traces.metadata : dict or NoneAdditional metadata to attach to the trace.Reads ``LANGFUSE_PUBLIC_KEY``, ``LANGFUSE_SECRET_KEY``, and optionally``LANGFUSE_HOST`` from environment variables. In langfuse v4+ the``CallbackHandler`` only needs ``public_key``; the SDK reads22 unmodified linesLangfuse(additional_headers={"x-langfuse-ingestion-version": "4"},)return CallbackHandler(trace_name=trace_name,tags=tags or [],user_id=user_id,session_id=session_id,metadata=metadata,)except ImportError:logger.warning("langfuse not available β skipping tracing",210 unmodified linesclass TokenCostCallback:"""Accumulates per-model token usage & TTFT from LangChain LLM calls.Also tracks **TTFT** (Time to First Token) by recording a timestampat ``on_chat_model_start`` and computing elapsed time at ``on_llm_end``.For non-streaming LLM calls this is effectively the full request duration;for streaming it would be the time to the first chunk.Lazily imports ``BaseCallbackHandler`` so that ``observability.py`` canbe imported even when ``langchain-core`` has version incompatibilities20 unmodified linesdef __init__(self) -> None:self.usage: list[dict[str, Any]] = []self._start_times: dict[str, float] = {} # run_id -> timestamp@propertydef total_input_tokens(self) -> int:7 unmodified linesdef total_cost(self) -> float:return sum(u.get("cost", 0.0) for u in self.usage)@propertydef total_ttft(self) -> float:"""Total TTFT across all LLM calls, in seconds."""ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]return sum(ttfts)@propertydef avg_ttft(self) -> Optional[float]:"""Average TTFT across all LLM calls, in seconds (None if no calls)."""ttfts = [u.get("ttft_seconds", 0.0) for u in self.usage if u.get("ttft_seconds") is not None]if not ttfts:return Nonereturn sum(ttfts) / len(ttfts)def on_chain_start(self, *args, **kwargs) -> None:pass1 unmodified linepassdef on_chat_model_start(self, *args, **kwargs) -> None:"""Record start timestamp for TTFT measurement.``**kwargs`` contains ``run_id`` which we use as the key."""run_id = kwargs.get("run_id")if run_id:self._start_times[str(run_id)] = time.time()def on_llm_start(self, *args, **kwargs) -> None:"""Fallback: record start timestamp if ``on_chat_model_start`` wasn't called."""run_id = kwargs.get("run_id")if run_id and str(run_id) not in self._start_times:self._start_times[str(run_id)] = time.time()def on_llm_error(self, error, **kwargs) -> None:self._cleanup_run(kwargs.get("run_id"))def on_chain_error(self, error, **kwargs) -> None:pass7 unmodified linesdef on_llm_end(self, response, **kwargs) -> None:"""LangChain callback β called after each LLM invocation.Computes TTFT from the recorded start time and captures token usage.``**kwargs`` absorbs ``run_id``, ``parent_run_id``, and othermetadata that LangChain passes to callback handlers."""try:run_key = str(kwargs.get("run_id", ""))# Compute TTFT (time from start to first token / completion)ttft: Optional[float] = Noneif run_key in self._start_times:ttft = round(time.time() - self._start_times.pop(run_key), 3)usage = response.llm_output or {}token_usage = usage.get("token_usage", {}) or {}model = usage.get("model_name", "") or ""3 unmodified linesif input_tokens > 0 or output_tokens > 0:cost = estimate_groq_cost(model, input_tokens, output_tokens)entry: dict[str, Any] = {"model": model,"input_tokens": input_tokens,"output_tokens": output_tokens,"cost": cost,}if ttft is not None:entry["ttft_seconds"] = ttftself.usage.append(entry)else:self._cleanup_run(run_key)except Exception:self._cleanup_run(run_key)pass # Best-effort β don't let cost tracking crash the rundef _cleanup_run(self, run_id: Any) -> None:"""Remove a run_id from the start times map (cleanup on error)."""if run_id:self._start_times.pop(str(run_id), None)def summary(self) -> str:"""Return a human-readable cost & TTFT summary."""calls = len(self.usage)if calls == 0:return "Cost: N/A (no LLM calls captured)"parts = [f"Cost: {format_cost(self.total_cost)}",f"{calls} LLM call(s)",f"{self.total_input_tokens:,} in / {self.total_output_tokens:,} out tokens",]avg = self.avg_ttftif avg is not None:parts.append(f"TTFT: {self.total_ttft:.1f}s total / {avg:.2f}s avg")return " Β· ".join(parts)def reset(self) -> None:self.usage.clear()self._start_times.clear()# βββ Error event logging βββββββββββββββββββββββββββββββββββββββββββββββββ--# βββ Score logging ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββdef log_langfuse_score(name: str,value: float,comment: Optional[str] = None,trace_id: Optional[str] = None,handler: Optional[Any] = None,) -> None:"""Log a numeric score to Langfuse, linked to a specific trace.Requires Langfuse to be enabled (keys in environment). The score isassociated with a trace by ``trace_id``. If ``handler`` is provided(a Langfuse ``CallbackHandler``) and ``trace_id`` is not explicitlyset, the function will extract the trace ID from the handler's``.trace_id`` attribute β this ensures the score appears directlyon the trace in the Langfuse UI rather than as a standalone score.Parameters----------name : strScore name (e.g. ``"verdict_score"``, ``"findings_count"``).value : floatNumeric score value.comment : str or NoneOptional human-readable comment.trace_id : str or NoneExplicit trace ID. If ``None`` but ``handler`` is provided,the handler's ``.trace_id`` is used.handler : Langfuse CallbackHandler or NoneLangfuse ``CallbackHandler`` from which to extract the trace IDafter the graph run completes."""if not is_langfuse_enabled():return# Auto-extract trace_id from handler if not explicitly providedresolved_trace_id = trace_idif resolved_trace_id is None and handler is not None:try:resolved_trace_id = getattr(handler, "trace_id", None)except Exception:passtry:from langfuse import Langfuself = Langfuse()kwargs: dict[str, Any] = {"name": name,"value": value,}if resolved_trace_id:kwargs["trace_id"] = resolved_trace_idif comment:kwargs["comment"] = commentlf.score(**kwargs)lf.flush()except Exception as exc:logger.debug("Failed to log Langfuse score: %s", exc)def update_langfuse_trace(trace_name: Optional[str] = None,tags: Optional[list[str]] = None,metadata: Optional[dict[str, Any]] = None,trace_id: Optional[str] = None,handler: Optional[Any] = None,) -> None:"""Update an existing Langfuse trace with name, tags, or metadata.This is useful for enriching a trace after the fact (e.g., afterthe graph completes and we know the final verdict).Parameters----------trace_name : str or NoneNew name for the trace.tags : list[str] or NoneTags to add to the trace (replaces existing tags).metadata : dict or NoneMetadata to merge into the trace.trace_id : str or NoneExplicit trace ID. If ``None`` but ``handler`` is provided,the handler's ``.trace_id`` is used.handler : Langfuse CallbackHandler or NoneLangfuse ``CallbackHandler`` from which to extract the trace ID."""if not is_langfuse_enabled():return# Auto-extract trace_id from handler if not explicitly providedresolved_trace_id = trace_idif resolved_trace_id is None and handler is not None:try:resolved_trace_id = getattr(handler, "trace_id", None)except Exception:passtry:from langfuse import Langfuself = Langfuse()kwargs: dict[str, Any] = {}if trace_name is not None:kwargs["name"] = trace_nameif tags is not None:kwargs["tags"] = tagsif metadata is not None:kwargs["metadata"] = metadataif resolved_trace_id:kwargs["trace_id"] = resolved_trace_idif kwargs:lf.update_trace(**kwargs)lf.flush()except Exception as exc:logger.debug("Failed to update Langfuse trace: %s", exc)def log_error_to_backends(error: Exception,context: Optional[dict[str, Any]] = None,
88 unmodified lines8990919293949588 unmodified linesdb_path = str(_project_root / "alert_checkpoints.db")graph = build_graph(db_path)thread_id = str(uuid.uuid4())handler = get_langfuse_handler()cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo="demo-org/demo-repo",88 unmodified lines899091929394959697989988 unmodified linesdb_path = str(_project_root / "alert_checkpoints.db")graph = build_graph(db_path)thread_id = str(uuid.uuid4())handler = get_langfuse_handler(trace_name="opencodereview/alert-check",tags=["cli", "alert", "demo-org/demo-repo"],session_id=thread_id,)cost_tracker = TokenCostCallback()metadata = build_run_metadata(source="cli", repo="demo-org/demo-repo",
app.py+60-5
main.py+67-5
nodes/retrieval.py+94-23
observability.py+218-14
scripts/alert.py+5-1