From dfaa11ca69d76451cdf41dee74e20b4d195a1d81 Mon Sep 17 00:00:00 2001 From: shipitdev Date: Wed, 11 Nov 2026 13:04:59 +0530 Subject: [PATCH 1/2] Group question chains and expose complete evaluation verdicts and costs --- .env.example | 3 + README.md | 9 +++ rag_app/api.py | 5 +- rag_app/generation.py | 28 ++++---- rag_app/tracing.py | 36 +++++++++- scripts/eval_layers.py | 16 ++++- scripts/eval_ragas.py | 118 +++++++++++++++++++++++---------- scripts/publish_langsmith.py | 72 +++++++++++++++++--- tests/test_app_generation.py | 15 +++++ tests/test_langsmith_export.py | 20 ++++++ tests/test_ragas_eval.py | 21 ++++++ tests/test_tracing.py | 18 ++++- 12 files changed, 297 insertions(+), 64 deletions(-) diff --git a/.env.example b/.env.example index 601cd00..e229628 100644 --- a/.env.example +++ b/.env.example @@ -23,3 +23,6 @@ RAG_LLM_PROVIDER=groq TOKENHARBOR_BASE_URL=https://tokenharbor.ai/v1 TOKENHARBOR_MODEL=deepseek-v4.1-flash:free TOKENHARBOR_API_KEY= + +# TokenHarbor reasoning mode. Change only for a separately labeled comparison. +RAG_THINKING=disabled diff --git a/README.md b/README.md index 8d7641f..c3a91bd 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,15 @@ Set `EVAL_BUDGET_FILE` to a shared ledger path to enforce the $0.50 token-value Style rubrics and broad toxicity/PII/jailbreak evaluation are also planned. Existing origin/session, withholding and generated-component checks cover specific application contracts; they are not a comprehensive safety benchmark. Optional semantic metrics compare against available references, which may omit valid alternative answers. +### Reading evaluation traces + +- Each question opens as one chain. Expand the saved pipeline stages, then each RAGAS metric and its judge steps. Conversation turns share a thread ID. Imported child timestamps have zero duration; their outputs retain the original measured duration. +- Each metric reports its score and status. The categorical `ragas_status_*` fields show success, skipped, not run, error, budget exhausted, undefined or needs review. A missing score stays empty. A zero score records a completed judgment with a zero result. +- Context precision judges each passage, so seven passages can require seven judge calls. Faithfulness uses statement extraction and checking. Relevancy uses three generated questions. Reference F1 uses claim extraction and checking in both directions. Cached judgments report zero HTTP calls. +- The TokenHarbor free route reports explicit `$0.00` billed cost. The shared budget ledger separately tracks standard-route token value. Unknown prices stay unknown. Cache and available reasoning-token counts are recorded. +- Completed traces rejected further updates in the current backend. Earlier flat imports remain archived. Replacement imports preserve saved answers and scores, with complete verdicts and parent/child links created together. +- Set `RAG_THINKING=disabled` for the current serving configuration. Use `enabled` only in a separately labeled fixed-evidence comparison. Generation mode is part of the answer-cache identity. The judge stays fixed while generation reasoning changes. + ### Bounded generation comparison with prompt version 6 The [saved comparison](evaluations/results/generation_v6.json) keeps the same 30 questions, references and source passages. The updated flow uses one writer, code-only display of valid writer-selected citation IDs and one verifier. A failed factual check withholds the answer. Code formatted citations in **21/30** cases, so prompt changes alone did not solve citation output. diff --git a/rag_app/api.py b/rag_app/api.py index 3bb20fa..63e5f3c 100644 --- a/rag_app/api.py +++ b/rag_app/api.py @@ -227,7 +227,8 @@ def run_worker(): 'index': retrieve.index_identity() if hasattr(retrieve, 'index_identity') else 'injected_test_index', 'model': provider.model if provider else MODEL, 'prompt': PROMPT_VERSION, 'generation': {'provider': provider.provider if provider else 'injected', - 'max_output_tokens': provider.max_tokens if provider else 1500}} + 'max_output_tokens': provider.max_tokens if provider else 1500, + 'thinking': getattr(provider, 'thinking', None)}} cached = None if regen or result else answers.get(session.id, identity, session_expires_at=session.expires_at) if cached: result = dict(cached) @@ -356,7 +357,7 @@ def run_worker(): emit('done', {}) def worker(): - with trace_span('Pipeline / Question', inputs={'question': body.question, 'regenerate': body.regenerate}, run_id=uuid.UUID(rid), metadata={'model': os.getenv('TOKENHARBOR_MODEL', MODEL) if os.getenv('RAG_LLM_PROVIDER') == 'tokenharbor' else MODEL, 'prompt_version': PROMPT_VERSION, 'pipeline_sha256': pipeline_version()}) as run: + with trace_span('Pipeline / Question', inputs={'question': body.question, 'regenerate': body.regenerate}, run_id=uuid.UUID(rid), metadata={'model': os.getenv('TOKENHARBOR_MODEL', MODEL) if os.getenv('RAG_LLM_PROVIDER') == 'tokenharbor' else MODEL, 'prompt_version': PROMPT_VERSION, 'pipeline_sha256': pipeline_version(), 'thread_id': 'TechQA / session / ' + hashlib.sha256(session.id.encode()).hexdigest()[:24]}) as run: run_worker() if run and not run.outputs: run.end(outputs={'status': 'cancelled_or_timed_out'}) diff --git a/rag_app/generation.py b/rag_app/generation.py index bab679f..c3ee8ee 100644 --- a/rag_app/generation.py +++ b/rag_app/generation.py @@ -1,7 +1,7 @@ """Private draft generation and evidence verification using Groq.""" from __future__ import annotations -from rag_app.tracing import trace_span +from rag_app.tracing import trace_span, model_usage import json import math @@ -57,10 +57,13 @@ class GroqREST: def __init__(self, api_key: str | None = None, *, model: str = MODEL, timeout: float = 75, post: Callable[..., Any] = httpx.post, provider: str = "groq", base_url: str = "https://api.groq.com/openai/v1", - max_tokens: int = 1500): + max_tokens: int = 1500, thinking: str = "disabled"): self.api_key = api_key if api_key is not None else os.getenv("GROQ_API_KEY") or os.getenv("GROK_API_KEY") if not self.api_key: raise GenerationError("Model provider API key is not configured") + if thinking not in {"enabled", "disabled"}: + raise ValueError("thinking must be enabled or disabled") + self.thinking = thinking self.provider, self.base_url, self.max_tokens = provider, base_url.rstrip("/"), max_tokens self.model, self.timeout, self.post = model, min(timeout, 120 if provider == "tokenharbor" else 75), post self.usage: list[dict[str, Any]] = [] @@ -83,19 +86,16 @@ def json_call(self, prompt: ChatPrompt, schema: dict[str, Any]) -> dict[str, Any messages = ([{"role": "system", "content": SYSTEM_RULES}, {"role": "user", "content": prompt}] if isinstance(prompt, str) else prompt) with trace_span(f"Pipeline / LLM / {self.provider}", inputs={"messages": messages}, run_type="llm", - metadata={"ls_provider": self.provider, "ls_model_name": self.model}) as span: + metadata={"ls_provider": self.provider, "ls_model_name": self.model, "thinking": self.thinking}) as span: before = len(self.usage) try: result = self._json_call(messages, schema) finally: if span and len(self.usage) > before: - usage = self.usage[-1] - recorded = {"input_tokens": usage.get("prompt_tokens"), - "output_tokens": usage.get("output_tokens"), - "total_tokens": usage.get("total_tokens")} - span.end(outputs={"usage_metadata": recorded}, metadata={"usage_metadata": recorded}) - if span: - span.end(outputs=result) + recorded = model_usage(self.usage[before:], provider=self.provider, model=self.model) + span.set(usage_metadata=recorded) + span.end(outputs={"result": result if 'result' in locals() else None, + "usage_metadata": recorded}) return result def _json_call(self, messages: list[dict[str, str]], schema: dict[str, Any]) -> dict[str, Any]: @@ -107,7 +107,7 @@ def _json_call(self, messages: list[dict[str, str]], schema: dict[str, Any]) -> if self.provider == "groq": body.update(reasoning_effort="low", max_completion_tokens=self.max_tokens) else: - body.update(max_tokens=self.max_tokens, thinking={"type": "disabled"}) + body.update(max_tokens=self.max_tokens, thinking={"type": self.thinking}) headers = {"Authorization": f"Bearer {self.api_key}"} prompt_chars = sum(len(message["content"]) for message in messages) started = time.monotonic() @@ -161,7 +161,8 @@ def _json_call(self, messages: list[dict[str, str]], schema: dict[str, Any]) -> "prompt_tokens": metadata.get("prompt_tokens"), "output_tokens": metadata.get("completion_tokens"), "reasoning_tokens": details.get("reasoning_tokens"), - "cached_tokens": prompt_details.get("cached_tokens"), + "cached_tokens": metadata.get("prompt_cache_hit_tokens") or prompt_details.get("cached_tokens"), + "thinking": self.thinking, "total_tokens": metadata.get("total_tokens")}) try: choice = payload["choices"][0] @@ -212,7 +213,8 @@ def transport(url, **kwargs): return GroqREST(api_key=os.getenv("TOKENHARBOR_API_KEY", ""), model=os.getenv("TOKENHARBOR_MODEL", "deepseek-v4.1-flash:free"), provider=provider, base_url=os.getenv("TOKENHARBOR_BASE_URL", "https://tokenharbor.ai/v1"), - max_tokens=6000, timeout=90, post=transport) + max_tokens=6000, timeout=90, post=transport, + thinking=os.getenv("RAG_THINKING", "disabled")) ANSWER_SCHEMA = {"type": "OBJECT", "properties": {"answer": {"type": "STRING"}, diff --git a/rag_app/tracing.py b/rag_app/tracing.py index 147aee2..846db59 100644 --- a/rag_app/tracing.py +++ b/rag_app/tracing.py @@ -3,9 +3,11 @@ from contextlib import contextmanager from functools import lru_cache import logging +import hashlib +import json import os -from langsmith import Client, trace, tracing_context +from langsmith import Client, trace, tracing_context, get_current_run_tree @lru_cache(maxsize=1) @@ -13,6 +15,32 @@ def get_client(): return Client(timeout_ms=1500) +def evaluation_thread(case): + """Keep generation, scoring and imports for the same saved answer together.""" + identity = case.get('langsmith_run_id') or hashlib.sha256(json.dumps( + [case['question_id'], case.get('response'), case.get('retrieved_contexts')], + sort_keys=True).encode()).hexdigest()[:24] + return case.get('thread_id') or f"TechQA / {case.get('evaluation_layer', 'pipeline')} / {case['question_id']} / {identity}" + + +def model_usage(calls, *, provider, model): + """Normalize reported usage, including explicit zero billing for the free route.""" + inputs = sum(c.get('prompt_tokens') or 0 for c in calls) + outputs = sum(c.get('completion_tokens', c.get('output_tokens')) or 0 for c in calls) + cached = sum(c.get('prompt_cache_hit_tokens') or c.get('cached_tokens') or + (c.get('prompt_tokens_details') or {}).get('cached_tokens') or 0 for c in calls) + reasoning = sum(c.get('reasoning_tokens') or + (c.get('completion_tokens_details') or {}).get('reasoning_tokens') or 0 for c in calls) + usage = {'input_tokens': inputs, 'output_tokens': outputs, 'total_tokens': inputs + outputs, + 'input_token_details': {'cache_read': min(inputs, cached)}, + 'output_token_details': {'reasoning': reasoning}} + if not any(c.get('reasoning_tokens') is not None or (c.get('completion_tokens_details') or {}).get('reasoning_tokens') is not None for c in calls): + usage.pop('output_token_details') + if calls and provider == 'tokenharbor' and model.endswith(':free'): + usage.update(input_cost=0.0, output_cost=0.0, total_cost=0.0) + return usage + + @contextmanager def trace_span(name, *, inputs=None, run_type="chain", **kwargs): enabled = ( @@ -25,12 +53,16 @@ def trace_span(name, *, inputs=None, run_type="chain", **kwargs): try: context = tracing_context(enabled=True) context.__enter__() + parent = get_current_run_tree() + inherited = (parent.extra or {}).get('metadata', {}) if parent else {} + kwargs['metadata'] = {**{k: inherited[k] for k in ('thread_id', 'question_id', 'layer') if k in inherited}, + **kwargs.get('metadata', {})} span = trace( name, run_type, inputs=inputs or {}, client=get_client(), - project_name=os.getenv("LANGSMITH_PROJECT") or "techqa-rag", + project_name=kwargs.pop("project_name", None) or (parent.session_name if parent else None) or os.getenv("LANGSMITH_PROJECT") or "techqa-rag", **kwargs, ) run = span.__enter__() diff --git a/scripts/eval_layers.py b/scripts/eval_layers.py index ea33651..e3b71fe 100644 --- a/scripts/eval_layers.py +++ b/scripts/eval_layers.py @@ -1,5 +1,6 @@ """Collect supplied-evidence component cases and real API workflow cases for RAGAS.""" import argparse +import hashlib import json import os from pathlib import Path @@ -11,7 +12,7 @@ from rag_app.api import create_app from rag_app.generation import AnswerGenerator, ConversationResolver, GenerationError, configured_provider from rag_app.retriever import Retriever -from rag_app.tracing import trace_span +from rag_app.tracing import trace_span, evaluation_thread from scripts.audit_techqa import RAW, ROOT from scripts.eval_ragas import save from scripts.eval_suite import load_cases @@ -37,6 +38,7 @@ def collect_components(pipeline, output, question_ids): provider = configured_provider() for qid in question_ids: case = dict(cases[qid]) + case.pop('thread_id', None) doc = case['reference_provenance']['document_id'] evidence = [{'id': 'S1', 'document_id': doc, 'text': documents[doc]['text']}] provider.usage.clear() @@ -44,7 +46,9 @@ def collect_components(pipeline, output, question_ids): generator = AnswerGenerator(provider.json_call) started = time.perf_counter() with trace_span('Component / Generator / ' + qid, inputs={'question': case['user_input']}, - metadata={'evidence_mode': 'annotated_original_article'}) as run: + metadata={'evidence_mode': 'annotated_original_article', 'question_id': qid}) as run: + if run: + run.add_metadata({'thread_id': f'TechQA / component / {qid} / {run.id}'}) try: answer = generator.generate(case['user_input'], evidence) except GenerationError as exc: @@ -57,6 +61,7 @@ def collect_components(pipeline, output, question_ids): 'error_type': answer.get('error_type')}) if run: run.end(outputs={'status': case['status'], 'response': case['response']}) + case['thread_id'] = evaluation_thread(case) save(output / (qid + '.json'), case) save(output / 'manifest.json', {**manifest, 'question_ids': question_ids, 'evaluation_layer': 'component', 'scope': 'generator with supplied original annotated article'}) @@ -80,13 +85,18 @@ def collect_workflow(pipeline, output, root_id, followup): started = time.perf_counter() with trace_span('Workflow / ' + qid, inputs={'question': question}) as run: result = stream_result(client.post('/ask', json={'question': question})) + session_id = client.cookies.get('techqa_session') + thread_id = ('TechQA / session / ' + hashlib.sha256(session_id.encode()).hexdigest()[:24] + if session_id else f'TechQA / workflow / {root_id}') + if run: + run.add_metadata({'thread_id': thread_id}) if root_status is None: root_status = result['status'] sources = result.get('sources', []) case = {**base, 'question_id': qid, 'user_input': question, 'status': result['status'], 'response': result['answer'], 'citations': result['citations'], 'sources': sources, 'retrieved_contexts': [json.dumps(s, ensure_ascii=False) for s in sources], - 'evaluation_layer': 'workflow', 'langsmith_run_id': str(run.id) if run else None, + 'evaluation_layer': 'workflow', 'langsmith_run_id': str(run.id) if run else None, 'thread_id': thread_id, 'generation': {'seconds': time.perf_counter() - started, 'trace': list(generator.trace), 'provider_calls': result['metrics'].get('provider_calls', []), 'http_attempts': result['metrics'].get('http_attempts', []), diff --git a/scripts/eval_ragas.py b/scripts/eval_ragas.py index 6ec6492..8e5c66c 100644 --- a/scripts/eval_ragas.py +++ b/scripts/eval_ragas.py @@ -97,22 +97,30 @@ async def cached_judgment(generate, settings, prompt, response_model, directory, path = directory / (key + '.json') started = time.perf_counter() offset = len(http_calls) + from rag_app.tracing import trace_span, model_usage if path.exists(): stored = json.loads(path.read_text()) result = response_model.model_validate(stored['output']) + with trace_span('RAGAS / Cached / ' + response_model.__name__, inputs={'cache_key': key}) as span: + if span: + span.end(outputs={'decision': stored['output'], 'cache_hit': True, 'http_attempts': 0}) journal.append({'cache_hit': True, 'key': key, 'decision': stored['output'], 'seconds': time.perf_counter() - started, 'http_calls': []}) return result try: - from rag_app.tracing import trace_span - with trace_span('RAGAS / Judge', inputs={'prompt': prompt}, run_type='llm', - metadata={'ls_provider': settings.get('provider'), 'ls_model_name': settings.get('judge')} ) as span: - result = await generate(prompt, response_model) - if span: - calls = http_calls[offset:] - span.end(outputs={**result.model_dump(mode='json'), 'usage_metadata': { - 'input_tokens': sum((c.get('usage') or {}).get('prompt_tokens') or 0 for c in calls), - 'output_tokens': sum((c.get('usage') or {}).get('completion_tokens') or 0 for c in calls)}}) + with trace_span('RAGAS / Judge / ' + response_model.__name__, inputs={'prompt': prompt}, run_type='llm', + metadata={'ls_provider': settings.get('provider'), 'ls_model_name': settings.get('judge'), + 'thinking': settings.get('thinking')}) as span: + try: + result = await generate(prompt, response_model) + finally: + if span: + calls = http_calls[offset:] + usage = model_usage([c.get('usage') or {} for c in calls], + provider=settings.get('provider'), model=settings.get('judge', '')) + span.set(usage_metadata=usage) + span.end(outputs={'decision': result.model_dump(mode='json') if 'result' in locals() else None, + 'usage_metadata': usage, 'cache_hit': False, 'http_attempts': len(calls)}) save(path, {'output': result.model_dump(mode='json')}) return result finally: @@ -121,35 +129,68 @@ async def cached_judgment(generate, settings, prompt, response_model, directory, 'seconds': time.perf_counter() - started, 'http_calls': http_calls[offset:]}) +def metric_verdict(metric): + """A score is a measurement. Release thresholds are reviewed separately.""" + calls = metric.get('judge_calls', []) + return {k: v for k, v in metric.items() if k != 'judge_calls'} | { + 'judge_steps': len(calls), 'cache_hits': sum(c.get('cache_hit', False) for c in calls), + 'http_attempts': sum(len(c.get('http_calls', [])) for c in calls)} + + async def evaluate_case(case, scorers, *, timeout=300, journal=None, budget=None): + from rag_app.tracing import trace_span, evaluation_thread results = {} - for name, scorer in scorers.items(): - started = time.perf_counter() - offset = len(journal) if journal is not None else 0 - if (('retrieved_contexts' in FIELDS[name] and not case['retrieved_contexts']) or - ('response' in FIELDS[name] and case['status'] != 'answered')): - results[name] = {'state': 'skipped', 'score': None, 'reason': 'no_context_or_no_released_answer'} - continue - try: - from rag_app.tracing import trace_span + metadata = {'thread_id': evaluation_thread(case), 'question_id': case['question_id'], + 'layer': case.get('evaluation_layer', 'pipeline'), + 'source_trace_id': case.get('langsmith_run_id'), + 'evaluation_run_id': case.get('evaluation_run_id'), 'variant': case.get('evaluation_variant')} + with trace_span('RAGAS / ' + case.get('evaluation_variant', 'Case') + ' / ' + case['question_id'], + inputs={'question_id': case['question_id'], 'question': case['user_input'], 'response': case.get('response', '')}, + metadata=metadata, project_name=case.get('evaluation_project_name') or os.getenv('LANGSMITH_EVAL_PROJECT', 'techqa-evaluations'), + reference_example_id=case.get('trace_reference_example_id')) as case_run: + if case.get('generation'): + with trace_span('Pipeline / Saved generation', inputs={'source_trace_id': case.get('langsmith_run_id'), + 'evaluation_run_id': case.get('evaluation_run_id'), 'variant': case.get('evaluation_variant')}, + metadata={'replay': True}) as saved_run: + for event in case['generation'].get('trace', []): + with trace_span('Pipeline / ' + event['stage'].title(), inputs={'stage': event['stage']}, + metadata={'replay': True}) as stage_run: + if stage_run: + stage_run.end(outputs={'decision': event.get('result'), 'error_type': event.get('error_type'), + 'recorded_milliseconds': event.get('milliseconds')}) + if saved_run: + saved_run.end(outputs={'status': case['status'], 'response': case.get('response', ''), + 'recorded_generation_seconds': case['generation'].get('seconds'), + 'new_generation_calls': 0}) + for name, scorer in scorers.items(): + started = time.perf_counter() + offset = len(journal) if journal is not None else 0 with trace_span('RAGAS / ' + name, inputs={'question_id': case['question_id']}, - metadata={'layer': case.get('evaluation_layer', 'pipeline')}) as metric_run: - async with asyncio.timeout(timeout): - result = await scorer.ascore(**metric_inputs(name, case)) - value = float(result.value) + metadata=metadata) as metric_run: + if (('retrieved_contexts' in FIELDS[name] and not case['retrieved_contexts']) or + ('response' in FIELDS[name] and case['status'] != 'answered')): + results[name] = {'state': 'skipped', 'score': None, 'reason': 'no_context_or_no_released_answer'} + else: + try: + async with asyncio.timeout(timeout): + result = await scorer.ascore(**metric_inputs(name, case)) + value = float(result.value) + results[name] = {'state': 'success' if math.isfinite(value) else 'undefined', + 'score': value if math.isfinite(value) else None} + except Exception as exc: + results[name] = {'state': 'budget_exhausted' if budget and budget.exhausted else 'error', + 'score': None, 'error_type': type(exc).__name__} + results[name]['seconds'] = round(time.perf_counter() - started, 3) + if journal is not None: + results[name]['judge_calls'] = journal[offset:] if metric_run: - metric_run.end(outputs={'score': value if math.isfinite(value) else None}) - results[name] = {'state': 'success' if math.isfinite(value) else 'undefined', - 'score': value if math.isfinite(value) else None} - except Exception as exc: - # Provider messages can contain inputs/headers; retain a safe category only. - results[name] = {'state': 'budget_exhausted' if budget and budget.exhausted else 'error', - 'score': None, 'error_type': type(exc).__name__} - results[name]['seconds'] = round(time.perf_counter() - started, 3) - if journal is not None: - results[name]['judge_calls'] = journal[offset:] - print(f" {name}: {results[name]['state']} {results[name]['score']}", flush=True) - return {'question_id': case['question_id'], 'status': case['status'], 'metrics': results} + metric_run.end(outputs=metric_verdict(results[name])) + print(f" {name}: {results[name]['state']} {results[name]['score']}", flush=True) + if case_run: + case_run.end(outputs={'response_status': case['status'], 'response': case.get('response', ''), + 'metrics': {k: metric_verdict(v) for k, v in results.items()}}) + return {'question_id': case['question_id'], 'status': case['status'], 'metrics': results, + 'langsmith_evaluation_run_id': str(case_run.id) if case_run else None} def summarize(rows): @@ -194,6 +235,7 @@ def bounded_post(*args, **kwargs): generator = AnswerGenerator(provider.json_call) identity = {'split_sha256': sha256(split_path), 'source_hashes': split['source_hashes'], 'index': retriever.index_identity(), 'model': provider.model, + 'thinking': getattr(provider, 'thinking', None), 'max_tokens': getattr(provider, 'max_tokens', None), 'code': {str(p.relative_to(ROOT)): sha256(p) for p in sorted((ROOT / 'rag_app').glob('*.py'))}, 'scope': 'standalone canonical answer; no memory, answer cache, UI or reference labels in inference'} args.output.mkdir(parents=True, exist_ok=True) @@ -221,6 +263,8 @@ def bounded_post(*args, **kwargs): question = q['QUESTION_TITLE'] + '\n' + q['QUESTION_TEXT'] print(q['QUESTION_ID'] + ': retrieval → writer → verifier', flush=True) with trace_span('Pipeline / Evaluation / ' + q['QUESTION_ID'], inputs={'question': question}, metadata={'question_id': q['QUESTION_ID'], 'evaluation': True, 'split': 'training_tuning', 'model': provider.model, 'index': identity['index']}) as run: + if run: + run.add_metadata({'thread_id': f"TechQA / pipeline / {q['QUESTION_ID']} / {run.id}"}) started = time.perf_counter() with trace_span('Retrieve and select evidence', inputs={'question': question}) as retrieval_run: retrieved = retriever.retrieve(question) @@ -243,6 +287,10 @@ def bounded_post(*args, **kwargs): 'provider_calls': list(provider.usage), 'error_type': answer.get('error_type'), 'http_attempts': list(provider.attempts), 'trace': list(generator.trace)} case['langsmith_run_id'] = str(run.id) if run else None + from rag_app.tracing import evaluation_thread + case['thread_id'] = evaluation_thread(case) + if run: + run.add_metadata({'thread_id': case['thread_id']}) if run: run.end(error=answer.get('error_type'), outputs={'status': case['status'], 'response': case['response'], 'sources': case['sources'], 'generation': {key: value for key, value in case['generation'].items() if key != 'trace'}}) save(path, case) @@ -386,7 +434,7 @@ async def aembed_text(self, text, **kwargs): 'manifest': manifest, 'selected_question_ids': ids, 'selected_metrics': list(scorers), 'cases_sha256': {c['question_id']: sha256(args.cases / (c['question_id'] + '.json')) for c in cases}, 'limitations': [('Synthetic judge calibration canaries' if canary_cohort else 'Reviewed feedback regression cohort; selected by users and reviewers' if feedback_cohort else 'training tuning pilot, not final development'), 'same model family writer/judge; manual review needed', - 'answer metrics conditional on released answers; no global refusal accuracy', 'cost not calculated; actual token usage recorded']} + 'answer metrics conditional on released answers; no global refusal accuracy', 'free-route zero billing reported separately from standard-route budget value; other billing unknown unless configured']} started = time.perf_counter() try: for case in cases: diff --git a/scripts/publish_langsmith.py b/scripts/publish_langsmith.py index cf29421..f15d95a 100644 --- a/scripts/publish_langsmith.py +++ b/scripts/publish_langsmith.py @@ -12,8 +12,58 @@ from langsmith.run_trees import RunTree from langsmith.utils import LangSmithNotFoundError -from rag_app.tracing import get_client +from rag_app.tracing import get_client, evaluation_thread, model_usage from scripts.eval_suite import build_report, load_cases +from scripts.eval_ragas import metric_verdict, FIELDS + + +METRIC_STATES = ['success', 'skipped', 'not_run', 'error', 'budget_exhausted', 'undefined', 'needs_review'] + + +def status_feedback(metric, state, reason): + return {'key': 'ragas_status_' + metric, 'score': METRIC_STATES.index(state) + 1, + 'comment': reason, 'feedback_config': {'type': 'categorical', 'categories': [ + {'value': i + 1, 'label': label.replace('_', ' ')} for i, label in enumerate(METRIC_STATES)]}} + + +def publish_generation_children(run, case, timestamp): + for event in case.get('generation', {}).get('trace', []): + child = run.create_child('Pipeline / ' + event['stage'].title(), run_type='chain', + inputs={'stage': event['stage']}, + outputs={'state': 'error' if event.get('error_type') else 'completed', + 'decision': event.get('result'), 'error_type': event.get('error_type'), + 'recorded_milliseconds': event.get('milliseconds')}, + start_time=timestamp, end_time=timestamp, error=event.get('error_type'), + extra={'metadata': {'thread_id': evaluation_thread(case), 'question_id': case['question_id'], + 'timestamp_basis': 'zero_duration_import', 'duration_source': 'outputs.recorded_milliseconds'}}) + child.post() + + +def publish_ragas_children(run, case, metrics, settings, timestamp): + """Import complete saved verdicts without issuing judgments or inventing call times.""" + thread = evaluation_thread(case) + for name, metric in metrics.items(): + metadata = {'thread_id': thread, 'question_id': case['question_id'], + 'timestamp_basis': 'zero_duration_import', 'duration_source': 'outputs.seconds', + 'thinking': settings.get('thinking')} + child = run.create_child('RAGAS / ' + name, run_type='chain', + inputs={'question_id': case['question_id']}, outputs=metric_verdict(metric), + start_time=timestamp, end_time=timestamp, extra={'metadata': metadata}) + child.post() + for index, call in enumerate(metric.get('judge_calls', []), 1): + cached = call.get('cache_hit', False) + usage = model_usage([c.get('usage') or {} for c in call.get('http_calls', [])], + provider=settings.get('provider'), model=settings.get('judge', '')) + decision = child.create_child(f"RAGAS / {'Cached' if cached else 'Judge'} / {index}", + run_type='chain' if cached else 'llm', inputs={'cache_key': call.get('key')}, + outputs={'decision': call.get('decision'), 'cache_hit': cached, + 'http_attempts': len(call.get('http_calls', [])), 'seconds': call.get('seconds'), + **({'usage_metadata': usage} if not cached else {})}, + start_time=timestamp, end_time=timestamp, + extra={'metadata': {**metadata, 'ls_provider': settings.get('provider'), + 'ls_model_name': settings.get('judge'), + **({'usage_metadata': usage} if not cached else {})}}) + decision.post() def publish(directory, client, ragas=None, *, dataset_name=None, experiment_prefix='techqa-saved-pipeline'): @@ -49,9 +99,12 @@ def publish(directory, client, ragas=None, *, dataset_name=None, experiment_pref num_examples=len(cases), num_repetitions=1, metadata=metadata, description='Saved measurements imported with original duration, usage and failure status.') rows = {r['question_id']: r for r in report['cases']} + judgments = {r['question_id']: r['metrics'] for r in (ragas or {}).get('results', [])} for case in cases: qid = case['question_id'] row = rows[qid] + metric_rows = {n: row['ragas'].get(n, {'state': 'not_run', 'score': None, + 'needs_review': False, 'reason': 'Metric was not attempted for this case'}) for n in FIELDS} gen = case.get('generation', {}) end = datetime.now(timezone.utc) seconds = gen.get('seconds') @@ -60,24 +113,26 @@ def publish(directory, client, ragas=None, *, dataset_name=None, experiment_pref outputs = {'question_id': qid, 'response': case['response'], 'status': case['status'], 'sources': case['sources'], 'original_trace_id': case.get('langsmith_run_id'), 'evaluation_layer': case.get('evaluation_layer', 'pipeline'), - 'model_calls': [{k: call.get(k) for k in ('provider', 'model')} for call in calls]} + 'model_calls': [{k: call.get(k) for k in ('provider', 'model')} for call in calls], + 'evaluation': {k: {x: y for x, y in v.items() if x != 'judge_calls'} for k, v in metric_rows.items()}} run = RunTree(name=case.get('evaluation_layer', 'pipeline').title() + ' / ' + qid, run_type='chain', client=client, project_name=experiment_name, reference_example_id=existing[qid].id, inputs={'question_id': qid, 'question': case['user_input']}, outputs=outputs, start_time=end - timedelta(seconds=seconds) if measured else end, end_time=end, error=(gen.get('error_type') or 'generation_error') if case['status'] == 'generation_error' else None, extra={'metadata': {**metadata, 'timestamp_basis': 'import_time', - 'duration_source': 'saved_generation_seconds' if measured else 'unavailable'}}) + 'thread_id': evaluation_thread(case), 'duration_source': 'saved_generation_seconds' if measured else 'unavailable'}}) run.post() + publish_generation_children(run, case, end) if calls: - usage = {'input_tokens': sum(c.get('prompt_tokens') or 0 for c in calls), - 'output_tokens': sum(c.get('output_tokens', c.get('completion_tokens')) or 0 for c in calls), - 'total_tokens': sum(c.get('total_tokens') or 0 for c in calls)} + usage = model_usage(calls, provider=calls[0].get('provider'), model=calls[0].get('model', '')) child = run.create_child('Pipeline / Recorded model usage', run_type='llm', inputs={'messages': []}, outputs={'usage_metadata': usage}, start_time=end, end_time=end, extra={'metadata': {'ls_provider': calls[0].get('provider'), - 'ls_model_name': calls[0].get('model'), 'aggregate_usage': True}}) + 'ls_model_name': calls[0].get('model'), 'aggregate_usage': True, + 'thread_id': evaluation_thread(case), 'usage_metadata': usage}}) child.post() + publish_ragas_children(run, case, judgments.get(qid, {}), (ragas or {}).get('settings', {}), end) feedback = [ {'key': 'response_status', 'value': case['status']}, {'key': 'selected_gold_document_hit', 'score': row['selected_gold_document_hit']}, @@ -91,9 +146,10 @@ def publish(directory, client, ragas=None, *, dataset_name=None, experiment_pref 'comment': 'Custom reference-claim coverage from cached reverse NLI judgments, version 1.'}, {'key': 'cost_status', 'value': 'free_route' if calls and all(str(c.get('model', '')).endswith(':free') for c in calls) else 'not_recorded'}, ] - for metric, value in row['ragas'].items(): + for metric, value in metric_rows.items(): scored = value['state'] == 'success' and not value['needs_review'] reason = 'Judge review required' if value['needs_review'] else value.get('reason') or value['state'] + feedback.append(status_feedback(metric, 'needs_review' if value['needs_review'] else value['state'], reason)) feedback.extend([ {'key': 'ragas_' + metric, 'score': value['score'] if scored else None, 'comment': reason}, {'key': 'ragas_state_' + metric, 'value': 'needs_review' if value['needs_review'] else value['state'], 'comment': reason}, diff --git a/tests/test_app_generation.py b/tests/test_app_generation.py index 1d5f666..9a9143a 100644 --- a/tests/test_app_generation.py +++ b/tests/test_app_generation.py @@ -408,3 +408,18 @@ def post(url, **kwargs): with unittest.TestCase().assertRaises(GenerationError) as error: provider.json_call("test", {}) assert error.exception.category == "invalid_response" + + +def test_reasoning_switch_is_explicit_and_validated(): + from unittest.mock import Mock + from rag_app.generation import GroqREST + import pytest + response = Mock(status_code=200, headers={}) + response.json.return_value = {'choices': [{'finish_reason': 'stop', 'message': {'content': '{}'}}], 'usage': {}} + post = Mock(return_value=response) + p = GroqREST(api_key='test', provider='tokenharbor', post=post, thinking='enabled') + p.json_call('test', {'type': 'OBJECT', 'properties': {}}) + assert post.call_args.kwargs['json']['thinking'] == {'type': 'enabled'} + assert p.usage[0]['thinking'] == 'enabled' + with pytest.raises(ValueError): + GroqREST(api_key='test', thinking='invalid') diff --git a/tests/test_langsmith_export.py b/tests/test_langsmith_export.py index 3db5e72..d227f11 100644 --- a/tests/test_langsmith_export.py +++ b/tests/test_langsmith_export.py @@ -34,6 +34,7 @@ def test_saved_experiment_imports_measurements_before_run_creation(tmp_path): assert root['outputs']['model_calls'] == [{'provider': 'tokenharbor', 'model': 'deepseek-v4.1-flash:free'}] assert client.evaluate.call_count == 0 assert client.update_run.call_count == 0 + assert len([c for c in client.create_feedback.call_args_list if c.kwargs.get('key', '').startswith('ragas_status_')]) == len(payload['cases']) * 6 assert any(c.kwargs.get('key') == 'pipeline_error' and c.kwargs.get('score') == 1 for c in client.create_feedback.call_args_list) @@ -76,3 +77,22 @@ def test_custom_dataset_rejects_changed_reference(): client.list_examples.return_value[0].outputs['reference'] = 'Different reference' with pytest.raises(ValueError, match='question/reference differs'): publish(Path('evaluations/fixtures/offline_demo.json'), client, dataset_name='existing') + + +def test_imported_metric_children_include_verdict_cost_and_thread(): + from datetime import datetime, timezone + from scripts.publish_langsmith import publish_ragas_children + root = Mock() + case = {'question_id': 'Q1', 'langsmith_run_id': 'source'} + metrics = {'factual_correctness': {'state': 'success', 'score': 0.0, 'seconds': 1, + 'judge_calls': [{'cache_hit': False, 'key': 'k', 'decision': {'verdict': 0}, + 'http_calls': [{'usage': {'prompt_tokens': 10, 'completion_tokens': 2}}]}]}} + publish_ragas_children(root, case, metrics, + {'provider': 'tokenharbor', 'judge': 'deepseek-v4.1-flash:free'}, + datetime.now(timezone.utc)) + metric = root.create_child.call_args.kwargs + assert metric['outputs']['score'] == 0.0 + assert metric['outputs']['http_attempts'] == 1 + judge = root.create_child.return_value.create_child.call_args.kwargs + assert judge['outputs']['usage_metadata']['total_cost'] == 0.0 + assert judge['extra']['metadata']['thread_id'] == metric['extra']['metadata']['thread_id'] diff --git a/tests/test_ragas_eval.py b/tests/test_ragas_eval.py index 6cf0890..4aceef7 100644 --- a/tests/test_ragas_eval.py +++ b/tests/test_ragas_eval.py @@ -299,3 +299,24 @@ def generate(self, question, sources): layers.collect_components(pipeline, output, [c['question_id']]) assert seen[0][0]['text'] == 'GOLD_ARTICLE' assert json.loads((output / (c['question_id'] + '.json')).read_text())['evaluation_layer'] == 'component' + + +def test_metric_trace_always_contains_verdict_including_skips(monkeypatch): + from contextlib import contextmanager + from unittest.mock import Mock + import rag_app.tracing as tracing + spans = [] + @contextmanager + def capture(name, **kwargs): + run = Mock() + spans.append((name, kwargs, run)) + yield run + monkeypatch.setattr(tracing, 'trace_span', capture) + c = case() + c['status'] = 'insufficient_evidence' + asyncio.run(evaluate_case(c, {'faithfulness': Mock()})) + metric = spans[1][2].end.call_args.kwargs['outputs'] + assert metric['state'] == 'skipped' + assert metric['reason'] == 'no_context_or_no_released_answer' + assert metric['http_attempts'] == 0 + assert spans[0][2].end.call_args.kwargs['outputs']['metrics']['faithfulness']['state'] == 'skipped' diff --git a/tests/test_tracing.py b/tests/test_tracing.py index df13bd4..803f6f6 100644 --- a/tests/test_tracing.py +++ b/tests/test_tracing.py @@ -23,9 +23,11 @@ def test_nested_spans_keep_parent_and_outputs(monkeypatch): monkeypatch.setenv("LANGSMITH_API_KEY", "test") monkeypatch.setenv("LANGSMITH_TRACING", "true") monkeypatch.setattr(tracing, "get_client", lambda: client) - with tracing.trace_span("question", inputs={"question": "Example?"}) as root: + with tracing.trace_span("question", inputs={"question": "Example?"}, metadata={"thread_id": "session-test"}, project_name="techqa-evaluations") as root: with tracing.trace_span("retrieval", inputs={"question": "Example?"}) as child: + assert root.session_name == child.session_name == "techqa-evaluations" assert child.parent_run_id == root.id + assert child.extra["metadata"]["thread_id"] == "session-test" child.end(outputs={"candidate_count": 100}) root.end(outputs={"status": "answered"}) assert create_run.call_count == 2 @@ -74,4 +76,18 @@ def test_provider_trace_records_actual_token_usage(monkeypatch): "input_tokens": 10, "output_tokens": 2, "total_tokens": 12, + "input_token_details": {"cache_read": 0}, } + + +def test_free_route_usage_has_explicit_cost_and_cache_details(): + from rag_app.tracing import model_usage, evaluation_thread + usage = model_usage([{'prompt_tokens': 10, 'completion_tokens': 5, + 'prompt_tokens_details': {'cached_tokens': 4}, + 'completion_tokens_details': {'reasoning_tokens': 2}}], + provider='tokenharbor', model='deepseek-v4.1-flash:free') + assert usage['total_cost'] == 0 + assert usage['input_token_details']['cache_read'] == 4 + assert usage['output_token_details']['reasoning'] == 2 + assert 'total_cost' not in model_usage([{}], provider='other', model='unknown') + assert evaluation_thread({'question_id': 'Q1', 'langsmith_run_id': 'id'}) == 'TechQA / pipeline / Q1 / id' From 29f67c86477ac2c45693c91e7b1cb20a061ccce3 Mon Sep 17 00:00:00 2001 From: shipitdev Date: Fri, 13 Nov 2026 15:59:45 +0530 Subject: [PATCH 2/2] Publish structured evaluation and reasoning comparison results --- .env.example | 2 +- README.md | 17 ++ evaluations/results/layered_audit_10.json | 315 ++++++++++++++++++++++ 3 files changed, 333 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index e229628..cd5f443 100644 --- a/.env.example +++ b/.env.example @@ -15,7 +15,7 @@ ENABLE_GENUI=1 # Optional LangSmith dashboard. Traces include questions, evidence and model outputs. LANGSMITH_API_KEY= -LANGSMITH_PROJECT=techqa-rag +LANGSMITH_PROJECT="TechQA / Pipeline / Live" LANGSMITH_TRACING=true # Select groq or tokenharbor for generation. diff --git a/README.md b/README.md index c3a91bd..f88e324 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,23 @@ Set `EVAL_BUDGET_FILE` to a shared ledger path to enforce the $0.50 token-value Style rubrics and broad toxicity/PII/jailbreak evaluation are also planned. Existing origin/session, withholding and generated-component checks cover specific application contracts; they are not a comprehensive safety benchmark. Optional semantic metrics compare against available references, which may omit valid alternative answers. +### Reasoning comparison after trace verification + +The [structured recheck](evaluations/results/layered_audit_10.json) evaluates saved generations from the same ten training questions. Evidence, prompts and the 6,000-token output cap were held fixed. Both arms use the same reasoning-disabled judge. The clean pass reused **422 judgments** and made **19 new judge requests**, with zero judge errors. + +| Measure | Reasoning off | Reasoning on | +|---|---:|---:| +| Released answers / 10 | 7 | 6 | +| Generation errors / 10 | 0 | 3 | +| Median recorded generation time | 8.73 s | 19.13 s | +| Reported generation tokens | 107,269 | 143,141 | +| Reference F1, five shared released answers | 33.6% | 50.2% | +| Faithfulness, same five answers | 100.0% | 97.1% | + +Reasoning stays disabled under the current output cap. All three reasoning-on errors were truncations. The five-case reference improvement requires a larger independent sample before a broader quality claim. Generation timings come from the saved executions. Replay spans report evaluation time and retain original generation durations in their outputs. The provider did not report reasoning-token counts. + +The recheck has **24 question chains, 23 threads and 136 metric verdicts**, with zero missing verdict outputs, thread IDs or reported LLM costs. The two workflow turns share a thread. All **144 metric status cells** are present, including eight metrics outside the component/workflow scoring scope. Reference-score review continues around answer scope, version conditions and bundled claims. The combined audit/comparison ledger reached **$0.392/$0.50** of standard-route token value, with one unresolved reservation. The selected free route records zero billed cost. + ### Reading evaluation traces - Each question opens as one chain. Expand the saved pipeline stages, then each RAGAS metric and its judge steps. Conversation turns share a thread ID. Imported child timestamps have zero duration; their outputs retain the original measured duration. diff --git a/evaluations/results/layered_audit_10.json b/evaluations/results/layered_audit_10.json index f7039a0..768e62b 100644 --- a/evaluations/results/layered_audit_10.json +++ b/evaluations/results/layered_audit_10.json @@ -612,5 +612,320 @@ "provenance": { "scorer_sha256": "4024b7d7422acb2e166f5cf366476e29df778d6a0845425510fe4cc18f9ae00d", "pipeline_manifest_sha256": "4c69828bb542728f0915e4ead1a88319bc8b445ce9b5e05199c8782a7ba63883" + }, + "structured_recheck": { + "run_date": "2026-11-11", + "scope": "Fixed ten training-tuning questions, identical saved evidence and 6000-token generation output cap. Reasoning-on uses provider default effort. The clean evaluation reused saved generations and valid cached judgments after tracing verification.", + "judge": "deepseek-v4.1-flash:free, thinking disabled in both arms", + "limitations": [ + "Small training sample", + "Same model family writes and judges", + "Reasoning token breakdown unavailable from provider", + "Latency is observational and includes failures", + "Three reasoning-on truncations limit the comparison; conclusions apply to the current output cap", + "Saved-generation replay spans retain recorded durations separately from evaluation latency" + ], + "layers": { + "off": { + "attempted": 10, + "outcomes": { + "answered": 7, + "insufficient_evidence": 2, + "needs_clarification": 1 + }, + "metrics": { + "context_precision": { + "success": 10, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.8385714285112444 + }, + "context_recall": { + "success": 10, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + }, + "faithfulness": { + "success": 7, + "error": 0, + "undefined": 0, + "skipped": 3, + "budget_exhausted": 0, + "mean": 0.9659863945578231 + }, + "answer_relevancy": { + "success": 7, + "error": 0, + "undefined": 0, + "skipped": 3, + "budget_exhausted": 0, + "mean": 0.8849442137920638 + }, + "factual_correctness": { + "success": 7, + "error": 0, + "undefined": 0, + "skipped": 3, + "budget_exhausted": 0, + "mean": 0.40857142857142853 + }, + "answer_completeness": { + "success": 7, + "error": 0, + "undefined": 0, + "skipped": 3, + "budget_exhausted": 0, + "mean": 0.7857142857142857 + } + } + }, + "on": { + "attempted": 10, + "outcomes": { + "generation_error": 3, + "answered": 6, + "insufficient_evidence": 1 + }, + "metrics": { + "context_precision": { + "success": 10, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.8385714285112444 + }, + "context_recall": { + "success": 10, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + }, + "faithfulness": { + "success": 6, + "error": 0, + "undefined": 0, + "skipped": 4, + "budget_exhausted": 0, + "mean": 0.9761904761904762 + }, + "answer_relevancy": { + "success": 6, + "error": 0, + "undefined": 0, + "skipped": 4, + "budget_exhausted": 0, + "mean": 0.9125643521285411 + }, + "factual_correctness": { + "success": 6, + "error": 0, + "undefined": 0, + "skipped": 4, + "budget_exhausted": 0, + "mean": 0.4183333333333334 + }, + "answer_completeness": { + "success": 6, + "error": 0, + "undefined": 0, + "skipped": 4, + "budget_exhausted": 0, + "mean": 0.75 + } + } + }, + "component": { + "attempted": 2, + "outcomes": { + "answered": 2 + }, + "metrics": { + "faithfulness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + }, + "answer_relevancy": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.8169765529503135 + }, + "factual_correctness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.25 + }, + "answer_completeness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + } + } + }, + "workflow": { + "attempted": 2, + "outcomes": { + "answered": 2 + }, + "metrics": { + "faithfulness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + }, + "answer_relevancy": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.9418714459143624 + }, + "factual_correctness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 0.7350000000000001 + }, + "answer_completeness": { + "success": 2, + "error": 0, + "undefined": 0, + "skipped": 0, + "budget_exhausted": 0, + "mean": 1.0 + } + } + } + }, + "generation_operations": { + "off": { + "cases": 10, + "median_generation_seconds": 8.726474104500312, + "reported_generation_tokens": 107269, + "generation_errors": {} + }, + "on": { + "cases": 10, + "median_generation_seconds": 19.133343312500074, + "reported_generation_tokens": 143141, + "generation_errors": { + "output_truncated": 3 + } + } + }, + "paired_released_cases": { + "count": 5, + "question_ids": [ + "TRAIN_Q425", + "TRAIN_Q376", + "TRAIN_Q013", + "TRAIN_Q361", + "TRAIN_Q310" + ], + "metrics": { + "faithfulness": { + "off": 1.0, + "on": 0.9714285714285714 + }, + "answer_relevancy": { + "off": 0.9069352095509547, + "on": 0.9002108346996028 + }, + "factual_correctness": { + "off": 0.33599999999999997, + "on": 0.502 + }, + "answer_completeness": { + "off": 0.7, + "on": 0.9 + } + } + }, + "observability": { + "off": { + "roots": 10, + "threads": 10, + "metric_verdicts": 60, + "missing_outputs": 0, + "missing_threads": 0, + "llm_spans": 0, + "missing_costs": 0, + "status_cells": 60, + "billed_cost": 0 + }, + "on": { + "roots": 10, + "threads": 10, + "metric_verdicts": 60, + "missing_outputs": 0, + "missing_threads": 0, + "llm_spans": 19, + "missing_costs": 0, + "status_cells": 60, + "billed_cost": 0.0 + }, + "component": { + "roots": 2, + "threads": 2, + "metric_verdicts": 8, + "missing_outputs": 0, + "missing_threads": 0, + "llm_spans": 0, + "missing_costs": 0, + "status_cells": 12, + "billed_cost": 0 + }, + "workflow": { + "roots": 2, + "threads": 1, + "metric_verdicts": 8, + "missing_outputs": 0, + "missing_threads": 0, + "llm_spans": 0, + "missing_costs": 0, + "status_cells": 12, + "billed_cost": 0 + } + }, + "execution": { + "judge_cache_hits": 422, + "judge_cache_misses": 19, + "http_attempts": 19, + "embedding_cache": { + "query_cache_hits": 61, + "query_cache_misses": 7 + }, + "standard_route_value_usd_including_prior_audit": 0.39192151199999997, + "budget_usd": 0.5, + "unresolved_reservations": 1, + "free_route_billed_cost_usd": 0 + }, + "decision": "Keep reasoning disabled under the current output cap. Review answer scope and reference/judge alignment before another generation change." } }