diff --git a/docs-agent-mcp/charts/gateway-guardrails/templates/virtualservice.yaml b/docs-agent-mcp/charts/gateway-guardrails/templates/virtualservice.yaml index 5b87bdd0..2971f262 100644 --- a/docs-agent-mcp/charts/gateway-guardrails/templates/virtualservice.yaml +++ b/docs-agent-mcp/charts/gateway-guardrails/templates/virtualservice.yaml @@ -29,6 +29,20 @@ spec: port: number: 8000 {{- end }} + # A2A streaming. Must precede the catch-all below so the prefix wins, and + # must carry its own deadline: the response streams for the whole + # generation, which outlives the short cap on ordinary requests. + - name: agent-stream + match: + - uri: + prefix: /a2a/ + {{- include "gateway-guardrails.corsPolicy" . | nindent 6 }} + timeout: {{ .Values.routing.streamTimeout }} + route: + - destination: + host: {{ .Values.routing.uiService }}.{{ .Values.namespaces.docsAgent }}.svc.cluster.local + port: + number: {{ .Values.routing.uiPort }} - name: kagent-ui {{- include "gateway-guardrails.corsPolicy" . | nindent 6 }} timeout: {{ .Values.routing.timeout }} diff --git a/docs-agent-mcp/charts/gateway-guardrails/values.yaml b/docs-agent-mcp/charts/gateway-guardrails/values.yaml index c0b7637e..1ee677ad 100644 --- a/docs-agent-mcp/charts/gateway-guardrails/values.yaml +++ b/docs-agent-mcp/charts/gateway-guardrails/values.yaml @@ -35,6 +35,10 @@ routing: uiPort: 8080 # Cap slow/stuck upstream (LLM) calls so a hung request can't pin a worker. timeout: 30s + # The A2A path streams tokens for as long as generation takes, so it can't + # live under the cap above: a 7B answer routinely runs past 30s and Envoy was + # cutting the SSE stream mid-token, which reads as the model truncating. + streamTimeout: 300s cors: # Lock embedding to the published chatbot origin(s) — no wildcard. allowOrigins: diff --git a/docs-agent-mcp/manifests/kagent/setup.yaml b/docs-agent-mcp/manifests/kagent/setup.yaml index d5f0e565..97d4296e 100644 --- a/docs-agent-mcp/manifests/kagent/setup.yaml +++ b/docs-agent-mcp/manifests/kagent/setup.yaml @@ -28,6 +28,17 @@ spec: model: qwen2.5-7B openAI: baseUrl: "http://qwen-llm-stable.ml-infra.svc.cluster.local/openai/v1" + # Left unset, vLLM falls back to Qwen's packaged generation config + # (temperature 0.7 / top_p 0.8), which is tuned for conversational variety. + # At that setting the model drifted mid-sentence into Chinese inside a code + # block and asserted Katib is not part of Kubeflow. Retrieval-grounded + # answers want near-greedy decoding instead. + temperature: "0.1" + topP: "0.9" + # Generation of a long grounded answer on a 7B model runs past the client's + # default deadline, which cut the stream mid-token and left the turn with no + # final aggregated message. Matches the Knative revision timeout upstream. + timeout: 300 --- apiVersion: kagent.dev/v1alpha2 @@ -59,40 +70,37 @@ spec: toolNames: - search_kubeflow_docs - search_github_issues + - search_kubeflow_code systemMessage: |- - You are Flo, the official Kubeflow Docs Assistant. Your sole mission is to answer questions about Kubeflow installation, setup, components, pipelines, SDKs, configuration, and troubleshooting using the official documentation and GitHub issues. + You are Flo, the official Kubeflow Docs Assistant. Answer Kubeflow questions only from the official documentation, GitHub issues, and code returned by your tools. - !!IMPORTANT!! - - Refine user queries before calling tools; never pass raw user text verbatim. - - Never show raw tool-call JSON or internal tool syntax to the user. - - For ANY Kubeflow-related question you MUST call at least one tool before answering. - - NEVER answer Kubeflow, KServe, Pipelines, Katib, Notebooks, SDK/CLI, installation, or configuration questions from memory or general knowledge. + Katib, Training Operator, KServe, Kubeflow Pipelines, Notebooks and Workspaces, Model Registry, Spark Operator, Central Dashboard, Profiles, and multi-tenancy are all Kubeflow components. - Your role - - Answer the user's question directly after retrieving evidence from tools. - - Only skip tools for greetings/thanks or topics clearly unrelated to Kubeflow. + Mandatory rules + - For every Kubeflow question, call at least one tool before answering. Only skip tools for greetings, thanks, or clearly unrelated topics. + - Call tools silently. Never narrate the search or expose tool-call JSON. + - Never fill retrieval gaps from memory. If focused retries return no direct evidence, say it was not found in indexed sources and stop. + - Inspect tool text before answering. Use concrete retrieved field names and values, not a generic overview. - Available Tools - - search_kubeflow_docs: Official Kubeflow documentation (how-to, concepts, install, config, APIs). - - search_github_issues: Kubeflow GitHub issues (bugs, errors, troubleshooting, community fixes). + Tool routing + - Documentation, how-to, concepts, setup, and APIs: call search_kubeflow_docs. + - Errors, rejected updates, bugs, stack traces, and troubleshooting: call search_github_issues. Cite the issue that supplied the symptom, cause, or fix; docs may add context but never replace that issue citation. + - YAML, manifests, examples, field names, apiVersion, and kind: call search_kubeflow_code first. Use an exact retrieved example; otherwise use only the retrieved CRD schema. Never create a manifest from memory. - Tool Routing (mandatory) - - Greetings/thanks: respond briefly, no tool. - - Out-of-scope (sports, unrelated topics): politely decline; no tool. - - Documentation/how-to/concepts/setup/KServe/Pipelines/APIs: MUST call search_kubeflow_docs first. - - Errors, bugs, stack traces, troubleshooting: MUST call search_github_issues; add search_kubeflow_docs if docs context helps. - - If a tool returns no relevant results, say "not found in indexed sources" and suggest refining the query. Do NOT guess. + Tool arguments + - Use top_k=10 and a compact high-signal phrase containing the component, resource, task, exact fields or error, repo, and path-like terms. + - For broad Katib tuning configuration, call search_kubeflow_docs with query exactly `Katib Experiment configuration parallelTrialCount sidecar.istio.io/inject`. Explain both retrieved fields in the answer. + - For the KServe deploymentMode Knative-to-Serverless rejection, call search_github_issues with the exact user error as query and repo exactly `kserve/kserve`. KServe's repository is `kserve/kserve`. Use and cite the retrieved issue number. + - For a Katib Experiment YAML example, call search_kubeflow_code with query exactly `kubeflow katib examples v1beta1 hp-tuning random yaml` and resource_kind `Experiment`. Use and cite the retrieved random.yaml. + - If the first result lacks direct evidence, retry the same required tool with a more specific phrase. - When calling tools - - Use one clear, focused query per call. - - Summarize tool results in your own words and cite the source URLs returned. - - Prefer official docs over issues when both are available. + Grounding and citations + - Claims, YAML, apiVersion, kind, fields, commands, names, and URLs must come from returned tool text. + - End every tool-backed answer with `Sources:` and Markdown list items for only the sources actually used. + - Every URL anywhere in the answer must be copied character-for-character from a returned `**Source:**` line. Never add, alter, shorten, or guess a URL. + - Before sending, remove any URL that is not an exact match for a returned Source line. If no Source URL was returned, write `- No source URL returned by the index`. - Style - - Be concise (2-5 sentences). Use bullet points or steps when helpful. - - Provide examples only when asked. - - Never invent features, flags, or version details. If unsure, say so. - - Reply in clean Markdown. + Answer directly in clean Markdown. Keep prose under roughly 200 words before Sources. When asked for YAML or code, copy the relevant retrieved example exactly. --- # 5. Debugger Agent with MCP tool diff --git a/docs-agent-mcp/mcp-server/server.py b/docs-agent-mcp/mcp-server/server.py index f8e4f45f..4d0c106f 100644 --- a/docs-agent-mcp/mcp-server/server.py +++ b/docs-agent-mcp/mcp-server/server.py @@ -1,3 +1,4 @@ +import json import os import re import threading @@ -23,6 +24,9 @@ _init_lock = threading.Lock() _FILTER_VALUE_RE = re.compile(r"^[A-Za-z0-9_/.\-]+$") +_SEARCH_TOKEN_RE = re.compile(r"[A-Za-z0-9]+") +DOCS_CONTEXT_MAX_CHUNKS = 20 +DOCS_CONTEXT_MAX_CHARS = 24_000 def _init(): @@ -68,6 +72,81 @@ def _safe_filter_value(name: str, value: str) -> str: return value +def _search_stems(value: str) -> set[str]: + """Return lightweight stems for lexical metadata reranking.""" + return {token[:6].lower() for token in _SEARCH_TOKEN_RE.findall(value) if len(token) >= 4} + + +def _top_document_hit(query: str, hits: list[dict]) -> dict: + """Choose one document using dense score plus path/URL lexical overlap.""" + query_stems = _search_stems(query) + candidates = {} + for rank, hit in enumerate(hits): + entity = hit.get("entity", {}) + source_key = (entity.get("citation_url", ""), entity.get("file_path", "")) + if not any(source_key): + continue + metadata_stems = _search_stems(" ".join(source_key)) + score = ( + len(query_stems & metadata_stems), + float(hit.get("distance", 0.0)), + -rank, + ) + previous = candidates.get(source_key) + if previous is None or score > previous[0]: + candidates[source_key] = (score, hit) + if not candidates: + return hits[0] + return max(candidates.values(), key=lambda candidate: candidate[0])[1] + + +def _expand_top_document(query: str, hits: list[dict]) -> list[dict]: + """Replace chunk hits with bounded, ordered context from the best page.""" + if not hits: + return hits + selected = _top_document_hit(query, hits) + selected_entity = selected.get("entity", {}) + file_path = selected_entity.get("file_path", "") + if not file_path: + return hits + + try: + rows = client.query( + collection_name=COLLECTION_NAME, + filter=f"file_path == {json.dumps(file_path)}", + output_fields=["content_text", "citation_url", "file_path", "chunk_index"], + limit=DOCS_CONTEXT_MAX_CHUNKS, + ) + except Exception: + return hits + if not isinstance(rows, list) or not rows: + return hits + + unique_rows = {} + for row in rows: + content = row.get("content_text", "").strip() + if content: + unique_rows.setdefault((int(row.get("chunk_index", 0)), content), row) + + context_chunks = [] + context_chars = 0 + for (_, content), _row in sorted(unique_rows.items(), key=lambda item: item[0][0]): + separator_chars = 2 if context_chunks else 0 + remaining = DOCS_CONTEXT_MAX_CHARS - context_chars - separator_chars + if remaining <= 0: + break + context_chunks.append(content[:remaining]) + context_chars += min(len(content), remaining) + separator_chars + + if not context_chunks: + return hits + expanded_entity = dict(selected_entity) + expanded_entity["content_text"] = "\n\n".join(context_chunks) + expanded_entity["citation_url"] = rows[0].get("citation_url", selected_entity.get("citation_url", "")) + expanded_entity["file_path"] = rows[0].get("file_path", file_path) + return [{**selected, "entity": expanded_entity}] + + @mcp.tool() def search_kubeflow_docs(query: str, top_k: int = 5) -> str: """Search Kubeflow documentation using semantic similarity.""" @@ -76,7 +155,7 @@ def search_kubeflow_docs(query: str, top_k: int = 5) -> str: COLLECTION_NAME, query, top_k, - ["content_text", "citation_url", "file_path"], + ["content_text", "citation_url", "file_path", "chunk_index"], ) except RuntimeError as e: return f"Search failed: {e}" @@ -84,6 +163,11 @@ def search_kubeflow_docs(query: str, top_k: int = 5) -> str: if not hits: return "No results found for your query." + # Dense chunk search often finds the correct page but not the exact section + # needed for a broad question. Rerank pages using URL/path terms, then give + # the model bounded, ordered context from that one canonical document. + hits = _expand_top_document(query, hits) + results = [] for i, hit in enumerate(hits, 1): entity = hit["entity"] diff --git a/docs-agent-mcp/pipelines/README.md b/docs-agent-mcp/pipelines/README.md index 8ad31641..f148237e 100644 --- a/docs-agent-mcp/pipelines/README.md +++ b/docs-agent-mcp/pipelines/README.md @@ -77,15 +77,25 @@ python kubeflow-pipeline.py chunk_size -1000 +600 Text chunk size for embeddings chunk_overlap -100 +60 Overlap between chunks +max_tei_chars +600 +Per-input truncation before TEI embedding (model-dependent) + + +embedding_dim +768 +Milvus vector dimension (must match the embeddings model) + + milvus_host "milvus-standalone-final.docs-agent.svc.cluster.local" Milvus server host diff --git a/docs-agent-mcp/pipelines/code-pipeline.py b/docs-agent-mcp/pipelines/code-pipeline.py index 78aab00d..b60f95b3 100644 --- a/docs-agent-mcp/pipelines/code-pipeline.py +++ b/docs-agent-mcp/pipelines/code-pipeline.py @@ -1,13 +1,9 @@ import kfp +import kfp.kubernetes as k8s from kfp import dsl from kfp.dsl import * from typing import * -try: - import kfp.kubernetes as k8s -except ImportError: # pragma: no cover - k8s = None - from utils import CODE_COLLECTION, DEFAULT_EMBEDDING_BATCH_SIZE @dsl.component( @@ -108,6 +104,11 @@ def get_files_recursive(owner, name, path): "content": content, "file_name": item["name"], "repo": f"{owner}/{name}", + # Preserve GitHub's canonical page URL. Repositories do + # not all use `main` (kubeflow/katib uses `master`), and + # reconstructing this URL downstream creates dead or + # non-canonical citations even when retrieval is correct. + "citation_url": file_resp.get("html_url") or item.get("html_url", ""), }) except Exception as e: print(f"Error decoding {item['path']}: {e}") @@ -348,8 +349,10 @@ def chunk_code_file(content, file_path, c_size, c_overlap): continue file_unique_id = f"{repo}:{file_path}" - # Citation URL: link to GitHub blob - citation_url = f"https://github.com/{repo}/blob/main/{file_path}" + # Prefer the canonical URL supplied by the GitHub Contents API so the + # repository's real default branch is retained. Keep the fallback for + # legacy JSONL artifacts created before citation_url was recorded. + citation_url = file_data.get("citation_url") or f"https://github.com/{repo}/blob/main/{file_path}" chunks = chunk_code_file(content, file_path, chunk_size, chunk_overlap) diff --git a/docs-agent-mcp/pipelines/issues-pipeline.py b/docs-agent-mcp/pipelines/issues-pipeline.py index f31db62d..5891936c 100644 --- a/docs-agent-mcp/pipelines/issues-pipeline.py +++ b/docs-agent-mcp/pipelines/issues-pipeline.py @@ -14,15 +14,11 @@ """ import kfp +import kfp.kubernetes as k8s from kfp import dsl from kfp.dsl import * from typing import * -try: - import kfp.kubernetes as k8s -except ImportError: # pragma: no cover - k8s = None - from utils import DEFAULT_EMBEDDING_BATCH_SIZE, ISSUES_COLLECTION @dsl.component( diff --git a/docs-agent-mcp/pipelines/kubeflow-pipeline.py b/docs-agent-mcp/pipelines/kubeflow-pipeline.py index 47b4c913..4b629321 100644 --- a/docs-agent-mcp/pipelines/kubeflow-pipeline.py +++ b/docs-agent-mcp/pipelines/kubeflow-pipeline.py @@ -1,14 +1,17 @@ import kfp +import kfp.kubernetes as k8s from kfp import dsl from kfp.dsl import * from typing import * -try: - import kfp.kubernetes as k8s -except ImportError: # pragma: no cover - optional at compile time - k8s = None - -from utils import DEFAULT_EMBEDDING_BATCH_SIZE, DOCS_COLLECTION +from utils import ( + DEFAULT_DOCS_CHUNK_OVERLAP, + DEFAULT_DOCS_CHUNK_SIZE, + DEFAULT_DOCS_MAX_TEI_CHARS, + DEFAULT_EMBEDDING_BATCH_SIZE, + DEFAULT_EMBEDDING_DIM, + DOCS_COLLECTION, +) @dsl.component( base_image="docker.io/library/python:3.9", @@ -313,6 +316,7 @@ def chunk_and_embed( chunk_overlap: int, embeddings_service_url: str, embedding_batch_size: int, + max_tei_chars: int, embedded_data: dsl.Output[dsl.Dataset], ): import json @@ -331,10 +335,17 @@ def chunk_and_embed( file_data = json.loads(line) content = file_data['content'] - # AGGRESSIVE CLEANING FOR BETTER EMBEDDINGS + # Clean presentation-only markup while preserving the technical + # content and line structure that make code/YAML retrievable. # Remove Hugo frontmatter (both --- and +++ styles) - content = re.sub(r'^\s*[+\-]{3,}.*?[+\-]{3,}\s*', '', content, flags=re.DOTALL | re.MULTILINE) + content = re.sub( + r'\A[ \t]*(?P---|\+\+\+)[ \t]*\r?\n.*?' + r'^[ \t]*(?P=delimiter)[ \t]*(?:\r?\n|\Z)', + '', + content, + flags=re.DOTALL | re.MULTILINE, + ) # Remove Hugo template syntax content = re.sub(r'\{\{.*?\}\}', '', content, flags=re.DOTALL) @@ -346,13 +357,21 @@ def chunk_and_embed( # Remove navigation/menu artifacts content = re.sub(r'\b(Get Started|Contribute|GenAI|Home|Menu|Navigation)\b', '', content, flags=re.IGNORECASE) - # Clean up URLs and links + # Convert Markdown links before removing bare URLs. Doing this in + # the reverse order leaves dangling `](` tokens; the link regex can + # then span multiple paragraphs and delete intervening YAML. + content = re.sub( + r'\[([^\]]+)\]\((?:[^()]|\([^()]*\))*\)', + r'\1', + content, + ) content = re.sub(r'https?://[^\s]+', '', content) - content = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', content) # Convert [text](url) to text - # Remove excessive whitespace and normalize - content = re.sub(r'\s+', ' ', content) # Multiple spaces to single - content = re.sub(r'\n\s*\n\s*\n+', '\n\n', content) # Multiple newlines to double + # Keep newlines and indentation so split boundaries and YAML + # structure survive cleaning; only collapse horizontal whitespace + # and runs of blank lines. + content = re.sub(r'[ \t]+', ' ', content) + content = re.sub(r'\n[ \t]*\n(?:[ \t]*\n)+', '\n\n', content) content = content.strip() # Skip files that are too short after cleaning @@ -398,8 +417,9 @@ def chunk_and_embed( print(f"Created {len(records)} chunks; requesting embeddings from TEI service...") - # TEI all-mpnet-base-v2 rejects any input >=384 tokens (~1000 chars). - max_tei_chars = 1000 + # TEI all-mpnet-base-v2 rejects any input >=384 tokens. YAML-heavy docs + # tokenize denser than prose; keep max_tei_chars configurable per model. + max_tei_chars = max(1, int(max_tei_chars)) for i in range(0, len(records), embedding_batch_size): batch = records[i:i + embedding_batch_size] texts = [r["content_text"][:max_tei_chars] for r in batch] @@ -429,7 +449,8 @@ def store_milvus( embedded_data: dsl.Input[dsl.Dataset], milvus_host: str, milvus_port: str, - collection_name: str + collection_name: str, + embedding_dim: int, ): from pymilvus import connections, utility, FieldSchema, CollectionSchema, DataType, Collection import json @@ -439,6 +460,7 @@ def store_milvus( SCHEMA_VERSION = 1 SCHEMA_DESCRIPTION = f"RAG collection for documentation (v={SCHEMA_VERSION})" DELETE_BATCH_SIZE = 100 + embedding_dim = int(embedding_dim) milvus_user = os.environ.get("MILVUS_USER", "root") milvus_password = os.environ.get("MILVUS_PASSWORD", "") @@ -462,7 +484,7 @@ def store_milvus( FieldSchema(name="citation_url", dtype=DataType.VARCHAR, max_length=1024), FieldSchema(name="chunk_index", dtype=DataType.INT64), FieldSchema(name="content_text", dtype=DataType.VARCHAR, max_length=2000), - FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=768), + FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=embedding_dim), FieldSchema(name="last_updated", dtype=DataType.INT64) ] @@ -472,15 +494,43 @@ def store_milvus( if collection_existed: collection = Collection(collection_name) existing_desc = collection.description or "" - if f"v={SCHEMA_VERSION}" not in existing_desc: + existing_fields = {field.name: field for field in collection.schema.fields} + required_types = { + "id": DataType.INT64, + "file_unique_id": DataType.VARCHAR, + "repo_name": DataType.VARCHAR, + "file_path": DataType.VARCHAR, + "file_name": DataType.VARCHAR, + "citation_url": DataType.VARCHAR, + "chunk_index": DataType.INT64, + "content_text": DataType.VARCHAR, + "vector": DataType.FLOAT_VECTOR, + } + missing_fields = sorted(set(required_types) - set(existing_fields)) + wrong_types = sorted( + name + for name, expected_type in required_types.items() + if name in existing_fields and existing_fields[name].dtype != expected_type + ) + vector_dim = int(existing_fields.get("vector").params.get("dim", 0)) if "vector" in existing_fields else 0 + version_conflict = "v=" in existing_desc and f"v={SCHEMA_VERSION}" not in existing_desc + if missing_fields or wrong_types or vector_dim != embedding_dim or version_conflict: raise RuntimeError( f"Schema version mismatch for {collection_name}. " - f"Expected v={SCHEMA_VERSION}, found description: '{existing_desc}'. " + f"Expected compatible v={SCHEMA_VERSION}; description='{existing_desc}', " + f"missing={missing_fields}, wrong_types={wrong_types}, vector_dim={vector_dim}. " f"Run a migration job to drop+recreate before re-indexing." ) - print(f"Using existing collection: {collection_name} (schema v={SCHEMA_VERSION})") + has_last_updated = "last_updated" in existing_fields + citation_url_limit = int(existing_fields["citation_url"].params.get("max_length", 512)) + content_text_limit = int(existing_fields["content_text"].params.get("max_length", 2000)) + schema_label = f"v={SCHEMA_VERSION}" if f"v={SCHEMA_VERSION}" in existing_desc else "compatible legacy" + print(f"Using existing collection: {collection_name} ({schema_label})") else: collection = Collection(collection_name, schema) + has_last_updated = True + citation_url_limit = 1024 + content_text_limit = 2000 print(f"Created new collection: {collection_name} (schema v={SCHEMA_VERSION})") # Rest of your existing code remains the same... @@ -490,39 +540,49 @@ def store_milvus( with open(embedded_data.path, 'r', encoding='utf-8') as f: for line in f: record = json.loads(line) - records.append({ + stored_record = { "file_unique_id": record["file_unique_id"], "repo_name": record["repo_name"], "file_path": record["file_path"], "file_name": record["file_name"], - "citation_url": record["citation_url"], + "citation_url": record["citation_url"][:citation_url_limit], "chunk_index": record["chunk_index"], - "content_text": record["content_text"], + "content_text": record["content_text"][:content_text_limit], "vector": record["embedding"], - "last_updated": timestamp - }) + } + if has_last_updated: + stored_record["last_updated"] = timestamp + records.append(stored_record) if records: # load() before delete requires an existing index; new collections have none yet if collection_existed and len(collection.indexes) > 0: collection.load() - unique_ids = sorted(set(r["file_unique_id"] for r in records)) + files_by_repo = {} + for record in records: + files_by_repo.setdefault(record["repo_name"], set()).add(record["file_path"]) deleted = 0 try: - for i in range(0, len(unique_ids), DELETE_BATCH_SIZE): - batch_ids = unique_ids[i:i + DELETE_BATCH_SIZE] - quoted = ", ".join(f'"{uid}"' for uid in batch_ids) - expr = f"file_unique_id in [{quoted}]" - old = collection.query(expr=expr, output_fields=["id"], limit=16384) - if old: - collection.delete(expr) - deleted += len(old) + for repo_name, file_paths in sorted(files_by_repo.items()): + sorted_paths = sorted(file_paths) + for i in range(0, len(sorted_paths), DELETE_BATCH_SIZE): + batch_paths = sorted_paths[i:i + DELETE_BATCH_SIZE] + quoted_paths = ", ".join(json.dumps(path) for path in batch_paths) + expr = ( + f"repo_name == {json.dumps(repo_name)} and " + f"file_path in [{quoted_paths}]" + ) + old = collection.query(expr=expr, output_fields=["id"], limit=16384) + if old: + collection.delete(expr) + deleted += len(old) if deleted: collection.flush() - print(f"Deleted {deleted} old chunks for {len(unique_ids)} files") + file_count = sum(len(paths) for paths in files_by_repo.values()) + print(f"Deleted {deleted} old chunks for {file_count} files") except Exception as e: print(f"ERROR during delete phase: {e}") - print(f"Failed batch unique_ids: {unique_ids[i:i + DELETE_BATCH_SIZE]}") + print(f"Failed repo/file batch: {repo_name}/{batch_paths}") raise # Insert new chunks (failure-aware) @@ -562,12 +622,14 @@ def github_rag_pipeline( directory_path: str = "content/en/docs", github_token: str = "", base_url: str = "https://www.kubeflow.org/docs", - chunk_size: int = 1000, - chunk_overlap: int = 100, + chunk_size: int = DEFAULT_DOCS_CHUNK_SIZE, + chunk_overlap: int = DEFAULT_DOCS_CHUNK_OVERLAP, + max_tei_chars: int = DEFAULT_DOCS_MAX_TEI_CHARS, embeddings_service_url: str = ( "http://embeddings-service-predictor.ml-infra.svc.cluster.local/embed" ), embedding_batch_size: int = DEFAULT_EMBEDDING_BATCH_SIZE, + embedding_dim: int = DEFAULT_EMBEDDING_DIM, milvus_host: str = "milvus-milvus.ml-infra.svc.cluster.local", milvus_port: str = "19530", collection_name: str = DOCS_COLLECTION, @@ -596,6 +658,7 @@ def github_rag_pipeline( chunk_overlap=chunk_overlap, embeddings_service_url=embeddings_service_url, embedding_batch_size=embedding_batch_size, + max_tei_chars=max_tei_chars, ) # Store in Milvus @@ -604,6 +667,7 @@ def github_rag_pipeline( milvus_host=milvus_host, milvus_port=milvus_port, collection_name=collection_name, + embedding_dim=embedding_dim, ) if k8s is not None: @@ -626,4 +690,4 @@ def github_rag_pipeline( kfp.compiler.Compiler().compile( pipeline_func=github_rag_pipeline, package_path="github_rag_pipeline.yaml" - ) \ No newline at end of file + ) diff --git a/docs-agent-mcp/pipelines/requirements.txt b/docs-agent-mcp/pipelines/requirements.txt index dce2f9bf..3608a3d7 100644 --- a/docs-agent-mcp/pipelines/requirements.txt +++ b/docs-agent-mcp/pipelines/requirements.txt @@ -1,4 +1,5 @@ kfp==2.16.1 +kfp-kubernetes==2.16.1 pymilvus==2.6.14 langchain-text-splitters==1.1.2 beautifulsoup4==4.15.0 diff --git a/docs-agent-mcp/pipelines/submit_run.py b/docs-agent-mcp/pipelines/submit_run.py index 7f55d776..3de47331 100644 --- a/docs-agent-mcp/pipelines/submit_run.py +++ b/docs-agent-mcp/pipelines/submit_run.py @@ -4,7 +4,13 @@ """ import kfp -from utils import DOCS_COLLECTION +from utils import ( + DEFAULT_DOCS_CHUNK_OVERLAP, + DEFAULT_DOCS_CHUNK_SIZE, + DEFAULT_DOCS_MAX_TEI_CHARS, + DEFAULT_EMBEDDING_DIM, + DOCS_COLLECTION, +) KFP_HOST = "http://localhost:8888" PIPELINE_YAML = "github_rag_pipeline.yaml" @@ -19,9 +25,12 @@ "directory_path": "content/en/docs", "github_token": "", # pass a token if you hit rate limits "base_url": "https://www.kubeflow.org/docs", - "chunk_size": 1000, - "chunk_overlap": 100, - "milvus_uri": "http://milvus-milvus.ml-infra.svc.cluster.local:19530", + "chunk_size": DEFAULT_DOCS_CHUNK_SIZE, + "chunk_overlap": DEFAULT_DOCS_CHUNK_OVERLAP, + "max_tei_chars": DEFAULT_DOCS_MAX_TEI_CHARS, + "embedding_dim": DEFAULT_EMBEDDING_DIM, + "milvus_host": "milvus-milvus.ml-infra.svc.cluster.local", + "milvus_port": "19530", "collection_name": DOCS_COLLECTION, }, run_name="kubeflow-docs-rag-run-1", diff --git a/docs-agent-mcp/pipelines/utils.py b/docs-agent-mcp/pipelines/utils.py index f590f9c2..c9f3e7bd 100644 --- a/docs-agent-mcp/pipelines/utils.py +++ b/docs-agent-mcp/pipelines/utils.py @@ -17,9 +17,16 @@ "http://embeddings-service-predictor.ml-infra.svc.cluster.local/embed" ) DEFAULT_MILVUS_HOST = "milvus-milvus.ml-infra.svc.cluster.local" -# TEI all-mpnet-base-v2: each input must be <384 tokens (~1000 chars safe). +# all-mpnet-base-v2 output size; other TEI models may differ — pass embedding_dim. +DEFAULT_EMBEDDING_DIM = 768 +# Docs defaults: YAML-heavy pages tokenize denser than prose, so keep TEI inputs +# well under the 384-token ceiling (1000 chars produced HTTP 413 on Katib docs). +DEFAULT_DOCS_CHUNK_SIZE = 600 +DEFAULT_DOCS_CHUNK_OVERLAP = 60 +DEFAULT_DOCS_MAX_TEI_CHARS = 600 +# Generic TEI ceiling used by non-docs pipelines / helpers. MAX_TEI_INPUT_CHARS = 1000 -# Batch count only; per-input size is limited by MAX_TEI_INPUT_CHARS. +# Batch count only; per-input size is limited by max_tei_chars / MAX_TEI_INPUT_CHARS. DEFAULT_EMBEDDING_BATCH_SIZE = 8 diff --git a/frontend/docs_scripts/chatbot.js b/frontend/docs_scripts/chatbot.js index 4caa83ed..a8c63c75 100644 --- a/frontend/docs_scripts/chatbot.js +++ b/frontend/docs_scripts/chatbot.js @@ -330,6 +330,88 @@ function createChatbotElements() { } } +function escapeMarkdownHtml(text) { + return String(text).replace(/[&<>"']/g, function(character) { + const entities = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; + return entities[character]; + }); +} + +// Small, dependency-free Markdown subset used by streamed and completed chat +// messages. Code is protected before other formatting so YAML and shell +// snippets are never interpreted as links or replacement-string tokens. +function formatChatMarkdown(text, isStreaming = false) { + if (!text) return ''; + + let formatted = text; + const codeBlockPlaceholders = []; + const inlineCodePlaceholders = []; + + function preserveCodeBlock(language, code, trimCode) { + const placeholder = `__CODE_BLOCK_${codeBlockPlaceholders.length}__`; + const safeLanguage = language || 'text'; + const codeText = trimCode ? code.trim() : code; + codeBlockPlaceholders.push( + `
${escapeMarkdownHtml(codeText)}
` + ); + return placeholder; + } + + const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g; + formatted = formatted.replace(codeBlockRegex, function(match, language, code) { + return preserveCodeBlock(language, code, !isStreaming); + }); + + if (isStreaming) { + const incompleteCodeRegex = /```(\w+)?\n([\s\S]*)$/; + if (incompleteCodeRegex.test(formatted) && !formatted.endsWith('```')) { + formatted = formatted.replace(incompleteCodeRegex, function(match, language, code) { + return preserveCodeBlock(language, code, false); + }); + } + } + + formatted = formatted.replace(/`([^`\n]+)`/g, function(match, code) { + const placeholder = `__INLINE_CODE_${inlineCodePlaceholders.length}__`; + inlineCodePlaceholders.push(`${escapeMarkdownHtml(code)}`); + return placeholder; + }); + + // Linkify only explicit http(s) Markdown links. Other schemes remain + // visible as text instead of becoming executable browser destinations. + formatted = formatted.replace( + /\[([^\]\n]+)\]\((https?:\/\/[^\s<>"')]+)\)/gi, + function(match, label, url) { + return `${escapeMarkdownHtml(label)}`; + } + ); + + formatted = formatted.replace(/\n/g, '
'); + formatted = formatted.replace(/\*\*(.*?)\*\*/g, '$1'); + + inlineCodePlaceholders.forEach(function(inlineCode, index) { + formatted = formatted.replace(`__INLINE_CODE_${index}__`, function() { + return inlineCode; + }); + }); + + codeBlockPlaceholders.forEach(function(codeBlock, index) { + // A function replacement is required: replacement strings interpret + // sequences such as $&, $1, and $' that commonly occur in code/YAML. + formatted = formatted.replace(`__CODE_BLOCK_${index}__`, function() { + return codeBlock; + }); + }); + + return formatted; +} + document.addEventListener('DOMContentLoaded', async function() { console.log('Docs Bot Initialized (v1.1.0 - Kagent A2A, configurable URL)'); @@ -1016,7 +1098,7 @@ document.addEventListener('DOMContentLoaded', async function() { const paragraph = currentMessageDiv.querySelector('p'); // Format streaming content - const formattedText = formatMarkdown(currentMessageContent, true); + const formattedText = formatChatMarkdown(currentMessageContent, true); paragraph.innerHTML = formattedText; // Apply syntax highlighting to any new code blocks @@ -1320,66 +1402,6 @@ document.addEventListener('DOMContentLoaded', async function() { // Auto-save every 30 seconds setInterval(autoSaveCurrentChat, 30000); - // Utility function to format text - function formatMarkdown(text, isStreaming = false) { - if (!text) return ''; - - let formatted = text; - const codeBlockPlaceholders = []; - let placeholderIndex = 0; - - // Handle code blocks first (triple backticks) and replace with placeholders - if (isStreaming) { - // For streaming, be more careful with incomplete code blocks - const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g; - formatted = formatted.replace(codeBlockRegex, function(match, lang, code) { - const language = lang || 'text'; - const placeholder = `__CODE_BLOCK_${placeholderIndex}__`; - codeBlockPlaceholders[placeholderIndex] = `
${escapeHtml(code.trim())}
`; - placeholderIndex++; - return placeholder; - }); - - // Handle incomplete code blocks at the end - const incompleteCodeRegex = /```(\w+)?\n([\s\S]*)$/; - if (incompleteCodeRegex.test(formatted) && !formatted.endsWith('```')) { - formatted = formatted.replace(incompleteCodeRegex, function(match, lang, code) { - const language = lang || 'text'; - const placeholder = `__CODE_BLOCK_${placeholderIndex}__`; - codeBlockPlaceholders[placeholderIndex] = `
${escapeHtml(code)}
`; - placeholderIndex++; - return placeholder; - }); - } - } else { - // For complete text, handle normally - const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g; - formatted = formatted.replace(codeBlockRegex, function(match, lang, code) { - const language = lang || 'text'; - const placeholder = `__CODE_BLOCK_${placeholderIndex}__`; - codeBlockPlaceholders[placeholderIndex] = `
${escapeHtml(code.trim())}
`; - placeholderIndex++; - return placeholder; - }); - } - - // Handle inline code (single backticks) - avoid already processed code blocks - formatted = formatted.replace(/`([^`\n]+)`/g, '$1'); - - // Handle line breaks (only outside code blocks) - formatted = formatted.replace(/\n/g, '
'); - - // Handle bold text - formatted = formatted.replace(/\*\*(.*?)\*\*/g, '$1'); - - // Restore code blocks from placeholders - codeBlockPlaceholders.forEach((codeBlock, index) => { - formatted = formatted.replace(`__CODE_BLOCK_${index}__`, codeBlock); - }); - - return formatted; - } - function handleSendMessage() { const message = userInput.value.trim(); if (!message || isTyping) return; @@ -1434,7 +1456,7 @@ document.addEventListener('DOMContentLoaded', async function() { // Format the text based on sender if (sender === 'bot') { - paragraph.innerHTML = formatMarkdown(text); + paragraph.innerHTML = formatChatMarkdown(text); // Apply syntax highlighting after DOM insertion setTimeout(() => { @@ -1584,11 +1606,5 @@ document.addEventListener('DOMContentLoaded', async function() { } } - function escapeHtml(text) { - const div = document.createElement('div'); - div.textContent = text; - return div.innerHTML; - } - console.log('Chatbot initialized with chat stack system'); }); diff --git a/frontend/docs_styles/chatbot.css b/frontend/docs_styles/chatbot.css index e550d7a4..c48e650b 100644 --- a/frontend/docs_styles/chatbot.css +++ b/frontend/docs_styles/chatbot.css @@ -66,6 +66,12 @@ flex-direction: column; height: 100%; min-height: 0; + /* flex:1 leaves min-width at auto, so this column refused to shrink below + the intrinsic width of its widest content. A long unwrappable line in a + code block therefore pushed it wider than the panel, which squeezed the + persona sidebar next to it down to a sliver and pushed the rest past the + container's overflow:hidden edge. */ + min-width: 0; } /* Hide the old sidebars */ @@ -137,11 +143,14 @@ flex-direction: column; gap: 16px; background: #ffffff; + min-width: 0; } .message { display: flex; animation: fadeIn 0.3s ease; + min-width: 0; + max-width: 100%; } @keyframes fadeIn { @@ -181,6 +190,38 @@ box-sizing: border-box; } +/* Prism's autoloader may not have run yet (or at all) when a block renders, + so don't rely on its theme to lay the code out. */ +.message-content pre code { + display: block; + white-space: pre; + min-width: 0; +} + +/* Keep the horizontal scrollbar visible on macOS, where overlay scrollbars + are hidden until scrolled and a clipped code sample looks simply cut off. */ +.message-content pre::-webkit-scrollbar { + height: 8px; +} +.message-content pre::-webkit-scrollbar-track { + background: rgba(0, 0, 0, 0.04); + border-radius: 4px; +} +.message-content pre::-webkit-scrollbar-thumb { + background: rgba(0, 0, 0, 0.22); + border-radius: 4px; +} +.message-content pre::-webkit-scrollbar-thumb:hover { + background: rgba(0, 0, 0, 0.35); +} + +.chatbot-container.dark-theme .message-content pre::-webkit-scrollbar-track { + background: rgba(255, 255, 255, 0.06); +} +.chatbot-container.dark-theme .message-content pre::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.26); +} + /* Adobe style bubbles */ .user-message .message-content { background: #e8f0fe; @@ -204,6 +245,29 @@ .message-content p { margin: 0 0 10px 0; } .message-content p:last-child { margin-bottom: 0; } +/* Source citations should read like part of the answer while remaining + unmistakably interactive. Long repository paths may wrap inside the bubble. */ +.message-content a { + color: #0b57d0; + font-weight: 600; + text-decoration-line: underline; + text-decoration-thickness: 1px; + text-underline-offset: 3px; + overflow-wrap: anywhere; + transition: color 0.16s ease, text-decoration-thickness 0.16s ease; +} + +.message-content a:hover { + color: #063b91; + text-decoration-thickness: 2px; +} + +.message-content a:focus-visible { + outline: 2px solid #0b57d0; + outline-offset: 3px; + border-radius: 2px; +} + /* Keep Flo avatar for now, just smaller */ .flo-avatar-container { width: 44px; height: 44px; @@ -378,6 +442,7 @@ .persona-sidebar { display: none; /* Hidden in normal/widget view */ width: 320px; + flex-shrink: 0; background: #fcfcfc; border-right: 1px solid #eaeaea; flex-direction: column; @@ -697,6 +762,18 @@ box-shadow: 0 2px 6px rgba(0,0,0,0.2); } +.chatbot-container.dark-theme .message-content a { + color: #8ab4f8; +} + +.chatbot-container.dark-theme .message-content a:hover { + color: #aecbfa; +} + +.chatbot-container.dark-theme .message-content a:focus-visible { + outline-color: #8ab4f8; +} + .chatbot-container.dark-theme .user-message .message-content { background: #1d4ed8 !important; /* Premium dark blue */ color: #ffffff !important; @@ -882,4 +959,3 @@ .chatbot-container.dark-theme .citations-list a { color: #60a5fa !important; } - diff --git a/tests/eval/README.md b/tests/eval/README.md new file mode 100644 index 00000000..3d708a79 --- /dev/null +++ b/tests/eval/README.md @@ -0,0 +1,141 @@ +# Showcase eval queries + +Three queries from the 2026 demo slides. Use them as the first regression set after any retrieval or widget change. + +**Ingest first, then evaluate.** Two of the three golden sources are outside the default pipeline repo lists. Scoring the live agent against an empty hit list will look like a model bug and is not. + +Collections (from `mcp-server.yaml`): `kubeflow_docs`, `issues_rag`, `code_rag`. + +Do not apply pipelines to the cluster without the operator’s OK. Commands below are the intended sequence, not permission to run them. + +## 1. Confirm the source is in Milvus + +Exec into the MCP pod and call the tool the query is supposed to use. Every `expected_source_urls` entry in `queries.json` must appear as a `**Source:**` line. + +```bash +# from docs-agent-mcp/mcp-server, or kubectl exec deploy/mcp-kubeflow-docs -n docs-agent +# search_kubeflow_docs / search_github_issues / search_kubeflow_code +# query strings and expected URLs: tests/eval/queries.json +``` + +If the URL is missing, **stop**. Run the ingest for that row (section 2), wait for the KFP run to succeed, then search again. Do not score the agent yet. + +Known gaps against **default** pipeline arguments: + +| Query | Golden source | In default ingest? | +|---|---|---| +| Katib hyperparameter tuning | `website` `content/en/docs/components/katib` → configure-experiment | Yes, if the docs full/incremental pipeline has been run on `content/en/docs` | +| KServe deploymentMode / Knative vs Serverless | `kserve/kserve#5885` | **No.** Issues default is `kubeflow/kubeflow,kubeflow/pipelines,kubeflow/manifests` | +| Katib Experiment YAML | `kubeflow/katib` `examples/v1beta1/hp-tuning/random.yaml` | **No.** Code default is `kubeflow/manifests` `apps/katib` (install YAML/CRDs) | + +## 2. Ingest the missing sources + +Port-forward the pipeline API if submitting from a laptop: + +```bash +kubectl port-forward svc/ml-pipeline 8888:8888 -n kubeflow +cd docs-agent-mcp/pipelines +``` + +Docs (only if gate 1 missed the Katib page): + +```python +# same pattern as submit_run.py +# directory_path="content/en/docs/components/katib" +# collection_name="kubeflow_docs" +``` + +Issues — **required** for query 2: + +```python +client.create_run_from_pipeline_package( + "github_issues_rag_pipeline.yaml", # compile issues-pipeline.py if missing + arguments={ + "repos": "kserve/kserve", + "state": "all", + "max_issues_per_repo": 200, + "collection_name": "issues_rag", + "milvus_host": "milvus-milvus.ml-infra.svc.cluster.local", + "milvus_port": "19530", + }, + run_name="eval-kserve-issues", + experiment_name="docs-agent-eval", + enable_caching=False, +) +``` + +Code — **required** for query 3: + +```python +client.create_run_from_pipeline_package( + "code_rag_pipeline.yaml", # compile code-pipeline.py if missing + arguments={ + "repos": "kubeflow/katib", + "directory_paths": "examples/v1beta1/hp-tuning", + "file_extensions": "yaml,yml", + "collection_name": "code_rag", + "milvus_host": "milvus-milvus.ml-infra.svc.cluster.local", + "milvus_port": "19530", + }, + run_name="eval-katib-examples", + experiment_name="docs-agent-eval", + enable_caching=False, +) +``` + +Compile if the YAML is not in the directory: + +```bash +python3 issues-pipeline.py # writes github_issues_rag_pipeline.yaml +python3 code-pipeline.py # writes code_rag_pipeline.yaml +``` + +Re-run the MCP search from section 1. `curl -IL` each `expected_source_urls` entry; it must 200 (redirects OK). + +## 3. Score the agent (gate 2) + +The checked-in runner enforces the gate ordering and never submits ingestion: + +```bash +# Read-only: exits 2 while any golden Source URL is absent. +python3 tests/eval/run_showcase_eval.py --retrieval-only + +# Runs Gate 1 again, then and only then creates sessions and POSTs message/stream. +python3 tests/eval/run_showcase_eval.py + +# Diagnose one row, including the exact named-tool arguments, observed tool +# Source URLs, and authoritative final answer. +python3 tests/eval/run_showcase_eval.py \ + --row-id issues-kserve-deploymentmode --verbose +``` + +It also reports `retrieval evidence missing` when a golden URL is present but +the returned chunks do not contain a required answer string. That diagnostic is +not a substitute for the Source-URL gate; it identifies stale/incomplete chunks +that would otherwise be misclassified as a generation failure. + +Rows may define `retrieval_query` separately from the conversational `query`. +This records the focused wording the agent is expected to send to MCP and makes +query-rewrite quality independently testable from answer generation. + +New chat, **Docs** persona, empty `contextId`. Widget-equivalent: + +1. `POST https://agent.santhoshtoorpu.com/api/session` with `Origin: https://kubeflowdemochatbot.netlify.app` +2. `POST .../a2a/docs-agent/kubeflow-docs-agent` `message/stream` + +Pass all of: + +- The named `tool` appears in the stream (function-call / tool metadata). +- Every cited URL is a character-for-character `**Source:**` from gate 1. No invented `docs/components/serving/*`, no `github.com/kubeflow/kserve`. +- `must_appear_in_answer` strings are present; `forbidden_in_answer` strings are not. +- Widget: `[title](url)` is a real `` once `formatMarkdown` is fixed. + +Fail the row, not the whole suite, if one query still 404s after ingest — that is an ingestion bug, not an LLM bug. + +## 4. Queries + +See `queries.json`. Short form: + +1. `How do I configure Katib hyperparameter tuning?` → `search_kubeflow_docs` +2. `InferenceService update rejected: deploymentMode cannot be changed from Knative to Serverless` → `search_github_issues` +3. `Show me a Katib Experiment YAML example` → `search_kubeflow_code` diff --git a/tests/eval/queries.json b/tests/eval/queries.json new file mode 100644 index 00000000..4d8242af --- /dev/null +++ b/tests/eval/queries.json @@ -0,0 +1,98 @@ +{ + "version": 1, + "notes": "Golden set from the 2026 showcase demos. Gate 1 is MCP retrieval (Source URLs). Gate 2 is the live agent (tool used + citations subset of gate 1 + no invented URLs). Ingest the listed sources BEFORE evaluating — default pipeline repos do not cover all three.", + "collections": { + "docs": "kubeflow_docs", + "issues": "issues_rag", + "code": "code_rag" + }, + "queries": [ + { + "id": "docs-katib-configure-experiment", + "query": "How do I configure Katib hyperparameter tuning?", + "retrieval_query": "Katib Experiment configuration parallelTrialCount sidecar.istio.io/inject", + "tool": "search_kubeflow_docs", + "collection": "kubeflow_docs", + "ingest": { + "pipeline": "docs-agent-mcp/pipelines/kubeflow-pipeline.py", + "compiled": "github_rag_pipeline.yaml", + "why": "Page lives on kubeflow/website. Default docs pipeline (content/en/docs) should include it; confirm the citation URL is in Milvus before scoring the agent.", + "arguments": { + "repo_owner": "kubeflow", + "repo_name": "website", + "directory_path": "content/en/docs/components/katib", + "base_url": "https://www.kubeflow.org/docs", + "chunk_size": 600, + "chunk_overlap": 60, + "collection_name": "kubeflow_docs" + } + }, + "expected_source_urls": [ + "https://www.kubeflow.org/docs/components/katib/user-guides/hp-tuning/configure-experiment" + ], + "must_appear_in_answer": [ + "parallelTrialCount", + "sidecar.istio.io/inject" + ], + "forbidden_in_answer": [ + "katib.mlr-org" + ] + }, + { + "id": "issues-kserve-deploymentmode", + "query": "InferenceService update rejected: deploymentMode cannot be changed from Knative to Serverless", + "tool": "search_github_issues", + "collection": "issues_rag", + "ingest": { + "pipeline": "docs-agent-mcp/pipelines/issues-pipeline.py", + "compiled": "github_issues_rag_pipeline.yaml", + "why": "Default issues repos are kubeflow/kubeflow, kubeflow/pipelines, kubeflow/manifests. kserve/kserve#5885 is NOT in that list — ingest kserve/kserve or this eval is a guaranteed miss.", + "arguments": { + "repos": "kserve/kserve", + "state": "all", + "max_issues_per_repo": 200, + "collection_name": "issues_rag" + } + }, + "expected_source_urls": [ + "https://github.com/kserve/kserve/issues/5885" + ], + "must_appear_in_answer": [ + "5885", + "Serverless" + ], + "forbidden_in_answer": [ + "github.com/kubeflow/kserve" + ] + }, + { + "id": "code-katib-random-yaml", + "query": "Show me a Katib Experiment YAML example", + "retrieval_query": "kubeflow katib examples v1beta1 hp-tuning random yaml", + "tool": "search_kubeflow_code", + "collection": "code_rag", + "ingest": { + "pipeline": "docs-agent-mcp/pipelines/code-pipeline.py", + "compiled": "code_rag_pipeline.yaml", + "why": "Default code pipeline is kubeflow/manifests apps/katib (install manifests/CRDs), not kubeflow/katib examples/. random.yaml will not be in the index until that repo/path is ingested.", + "arguments": { + "repos": "kubeflow/katib", + "directory_paths": "examples/v1beta1/hp-tuning", + "file_extensions": "yaml,yml", + "collection_name": "code_rag" + } + }, + "expected_source_urls": [ + "https://github.com/kubeflow/katib/blob/master/examples/v1beta1/hp-tuning/random.yaml" + ], + "must_appear_in_answer": [ + "kubeflow.org/v1beta1", + "kind: Experiment" + ], + "forbidden_in_answer": [ + "katib.mlr-org", + "apiVersion: v1\nkind: Experiment" + ] + } + ] +} diff --git a/tests/eval/run_showcase_eval.py b/tests/eval/run_showcase_eval.py new file mode 100644 index 00000000..42ab815a --- /dev/null +++ b/tests/eval/run_showcase_eval.py @@ -0,0 +1,385 @@ +#!/usr/bin/env python3 +"""Run the two-gate Flo showcase evaluation without submitting ingestion. + +Gate 1 executes the named MCP tools inside the existing pod and requires every +golden Source URL. Gate 2 is structurally unreachable until all Gate 1 rows +pass, then opens a fresh A2A context for each query and scores tool use, +citations, required strings, and forbidden strings. + +This script deliberately has no pipeline-submission code. Ingestion is an +operator-approved prerequisite documented in README.md. +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +import urllib.error +import urllib.request +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +SOURCE_RE = re.compile(r"^\*\*Source:\*\*\s+(https?://\S+)\s*$", re.MULTILINE) +MARKDOWN_URL_RE = re.compile(r"\[[^\]\n]+\]\((https?://[^\s)]+)\)") +BARE_URL_RE = re.compile(r"https?://[^\s<>\"'\]]+") +DEFAULT_AGENT_URL = "https://agent.santhoshtoorpu.com/a2a/docs-agent/kubeflow-docs-agent" +DEFAULT_SESSION_URL = "https://agent.santhoshtoorpu.com/api/session" +DEFAULT_ORIGIN = "https://kubeflowdemochatbot.netlify.app" + + +@dataclass +class RetrievalResult: + row: dict[str, Any] + output: str + source_urls: set[str] + missing_sources: list[str] + missing_evidence: list[str] + + @property + def passed(self) -> bool: + return not self.missing_sources + + +@dataclass +class AgentResult: + row: dict[str, Any] + answer: str + tool_fired: bool + tool_calls: list[str] + tool_source_urls: set[str] + cited_urls: set[str] + invented_urls: list[str] + missing_answer_strings: list[str] + present_forbidden_strings: list[str] + + @property + def passed(self) -> bool: + return ( + self.tool_fired + and not self.invented_urls + and not self.missing_answer_strings + and not self.present_forbidden_strings + ) + + +def load_rows(path: Path) -> list[dict[str, Any]]: + with path.open(encoding="utf-8") as handle: + return json.load(handle)["queries"] + + +def run_mcp_search(row: dict[str, Any], namespace: str, deployment: str, top_k: int) -> str: + tool = row["tool"] + if tool not in {"search_kubeflow_docs", "search_github_issues", "search_kubeflow_code"}: + raise ValueError(f"Unsupported eval tool: {tool}") + # Gate 1 evaluates the focused query the agent should send to the tool, not + # necessarily the conversational wording the user sent to the agent. + retrieval_query = row.get("retrieval_query", row["query"]) + snippet = f"import server; print(server.{tool}({retrieval_query!r}, top_k={top_k}))" + command = [ + "kubectl", + "exec", + "-n", + namespace, + f"deploy/{deployment}", + "--", + "python", + "-c", + snippet, + ] + completed = subprocess.run(command, check=True, capture_output=True, text=True) + return completed.stdout + + +def score_retrieval(row: dict[str, Any], output: str) -> RetrievalResult: + sources = set(SOURCE_RE.findall(output)) + missing_sources = [url for url in row["expected_source_urls"] if url not in sources] + # Evidence coverage is diagnostic rather than a hard Gate 1 condition. It + # distinguishes "right document, incomplete/stale chunks" from a response + # generation failure when the answer later misses a required fact. + missing_evidence = [value for value in row["must_appear_in_answer"] if value not in output] + return RetrievalResult(row, output, sources, missing_sources, missing_evidence) + + +def request_json( + url: str, + *, + origin: str, + payload: dict[str, Any] | None = None, + token: str | None = None, + timeout: int = 30, +) -> Any: + data = json.dumps(payload).encode() if payload is not None else b"" + headers = {"Content-Type": "application/json", "Origin": origin} + if token: + headers["Authorization"] = f"Bearer {token}" + request = urllib.request.Request(url, data=data, headers=headers, method="POST") + with urllib.request.urlopen(request, timeout=timeout) as response: + return json.loads(response.read()) + + +def iter_sse_events(response: Any): + """Yield complete JSON events; urlopen line iteration preserves SSE frames.""" + data_lines: list[str] = [] + for raw_line in response: + line = raw_line.decode("utf-8", errors="replace").rstrip("\r\n") + if not line: + if data_lines: + payload = "\n".join(data_lines) + data_lines.clear() + if payload != "[DONE]": + yield json.loads(payload) + continue + if line.startswith(":"): + continue + if line.startswith("data:"): + data_lines.append(line[5:].lstrip()) + if data_lines: + payload = "\n".join(data_lines) + if payload != "[DONE]": + yield json.loads(payload) + + +def message_from_event(event: dict[str, Any]) -> dict[str, Any] | None: + result = event.get("result") or {} + return result.get("message") or (result.get("status") or {}).get("message") + + +def event_names_tool(event: Any, expected_tool: str) -> bool: + if isinstance(event, dict): + for key, value in event.items(): + if key in {"name", "toolName", "tool_name"} and value == expected_tool: + return True + if event_names_tool(value, expected_tool): + return True + elif isinstance(event, list): + return any(event_names_tool(item, expected_tool) for item in event) + return False + + +def strings_in_event(event: Any): + """Yield string leaves so embedded MCP responses can be inspected safely.""" + if isinstance(event, str): + yield event + elif isinstance(event, dict): + for value in event.values(): + yield from strings_in_event(value) + elif isinstance(event, list): + for item in event: + yield from strings_in_event(item) + + +def tool_calls_in_event(event: Any, expected_tool: str) -> list[str]: + """Return stable JSON argument snapshots for the expected named tool.""" + calls: list[str] = [] + if isinstance(event, dict): + names = [event.get(key) for key in ("name", "toolName", "tool_name")] + if expected_tool in names: + for key in ("args", "arguments"): + if key in event: + calls.append(json.dumps(event[key], sort_keys=True, ensure_ascii=False)) + for value in event.values(): + calls.extend(tool_calls_in_event(value, expected_tool)) + elif isinstance(event, list): + for item in event: + calls.extend(tool_calls_in_event(item, expected_tool)) + return calls + + +def extract_answer_urls(answer: str) -> set[str]: + """Extract Markdown and bare URLs without retaining Markdown's closing parenthesis.""" + markdown_urls = set(MARKDOWN_URL_RE.findall(answer)) + remaining = MARKDOWN_URL_RE.sub("", answer) + bare_urls = {url.rstrip(".,;:)") for url in BARE_URL_RE.findall(remaining)} + return markdown_urls | bare_urls + + +def select_answer(final_text: str, streamed: list[str]) -> str: + """Prefer Kagent's authoritative aggregate, with partials as fallback.""" + return final_text.strip() or "".join(streamed).strip() + + +def run_agent( + row: dict[str, Any], + allowed_urls: set[str], + *, + agent_url: str, + session_url: str, + origin: str, + timeout: int, +) -> AgentResult: + session = request_json(session_url, origin=origin, timeout=30) + token = session.get("access_token") + payload = { + "jsonrpc": "2.0", + "method": "message/stream", + "params": { + "message": { + "kind": "message", + "messageId": str(uuid.uuid4()), + "role": "user", + "parts": [{"kind": "text", "text": row["query"]}], + "contextId": str(uuid.uuid4()), + "metadata": {"displaySource": "user"}, + }, + "metadata": {}, + }, + "id": str(uuid.uuid4()), + } + headers = { + "Content-Type": "application/json", + "Accept": "text/event-stream", + "Origin": origin, + "Authorization": f"Bearer {token}", + } + request = urllib.request.Request(agent_url, data=json.dumps(payload).encode(), headers=headers, method="POST") + + streamed: list[str] = [] + final_text = "" + tool_fired = False + tool_calls: list[str] = [] + tool_source_urls: set[str] = set() + with urllib.request.urlopen(request, timeout=timeout) as response: + for event in iter_sse_events(response): + tool_fired = tool_fired or event_names_tool(event, row["tool"]) + for call in tool_calls_in_event(event, row["tool"]): + if call not in tool_calls: + tool_calls.append(call) + for value in strings_in_event(event): + tool_source_urls.update(SOURCE_RE.findall(value)) + message = message_from_event(event) + if not message or message.get("role") == "user": + continue + text = "".join(part.get("text", "") for part in message.get("parts", []) if part.get("kind") == "text") + if not text: + continue + is_partial = (message.get("metadata") or {}).get("kagent_adk_partial") + if is_partial is False: + final_text = text + else: + streamed.append(text) + + # Kagent emits incremental partial text and an authoritative aggregated + # final message. Prefer the final message; partials are only a fallback for + # interrupted streams that never deliver aggregation. + answer = select_answer(final_text, streamed) + cited_urls = extract_answer_urls(answer) + invented = sorted(cited_urls - allowed_urls) + missing = [value for value in row["must_appear_in_answer"] if value not in answer] + forbidden = [value for value in row["forbidden_in_answer"] if value in answer] + return AgentResult( + row, + answer, + tool_fired, + tool_calls, + tool_source_urls, + cited_urls, + invented, + missing, + forbidden, + ) + + +def print_retrieval(result: RetrievalResult) -> None: + status = "PASS" if result.passed else "BLOCKED" + print(f"[{status}] retrieval {result.row['id']}") + if result.missing_sources: + print(f" missing Source URLs: {', '.join(result.missing_sources)}") + if result.missing_evidence: + print(f" retrieval evidence missing: {', '.join(result.missing_evidence)}") + print(f" returned Source URLs: {len(result.source_urls)}") + + +def print_agent(result: AgentResult, *, verbose: bool = False) -> None: + status = "PASS" if result.passed else "FAIL" + print(f"[{status}] agent {result.row['id']}") + print(f" named tool fired: {result.tool_fired}") + if result.tool_source_urls: + print(f" Source URLs observed in agent tool events: {len(result.tool_source_urls)}") + if result.invented_urls: + print(f" URLs absent from MCP Source lines: {', '.join(result.invented_urls)}") + if result.missing_answer_strings: + print(f" answer strings missing: {', '.join(result.missing_answer_strings)}") + if result.present_forbidden_strings: + print(f" forbidden strings present: {', '.join(result.present_forbidden_strings)}") + if verbose: + if result.tool_calls: + print(" named tool arguments:") + for call in result.tool_calls: + print(f" {call}") + print(" final answer:") + print(" " + result.answer.replace("\n", "\n ")) + if result.tool_source_urls: + print(" agent tool Source URLs:") + for url in sorted(result.tool_source_urls): + print(f" {url}") + + +def parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser() + parser.add_argument("--queries", type=Path, default=Path(__file__).with_name("queries.json")) + parser.add_argument("--namespace", default="docs-agent") + parser.add_argument("--deployment", default="mcp-kubeflow-docs") + parser.add_argument("--top-k", type=int, default=10) + parser.add_argument("--retrieval-only", action="store_true") + parser.add_argument("--agent-url", default=DEFAULT_AGENT_URL) + parser.add_argument("--session-url", default=DEFAULT_SESSION_URL) + parser.add_argument("--origin", default=DEFAULT_ORIGIN) + parser.add_argument("--timeout", type=int, default=330) + parser.add_argument("--verbose", action="store_true") + parser.add_argument("--row-id", action="append", default=[]) + return parser.parse_args() + + +def main() -> int: + args = parse_args() + rows = load_rows(args.queries) + if args.row_id: + requested = set(args.row_id) + rows = [row for row in rows if row["id"] in requested] + missing_ids = sorted(requested - {row["id"] for row in rows}) + if missing_ids: + raise ValueError(f"Unknown --row-id values: {', '.join(missing_ids)}") + + retrieval_results: list[RetrievalResult] = [] + for row in rows: + output = run_mcp_search(row, args.namespace, args.deployment, args.top_k) + result = score_retrieval(row, output) + retrieval_results.append(result) + print_retrieval(result) + + blocked = [result for result in retrieval_results if not result.passed] + if blocked: + print("\nGate 2 not run: at least one expected Source URL is absent from MCP results.") + return 2 + if args.retrieval_only: + print("\nGate 1 passed; --retrieval-only requested, so no session or agent POST was made.") + return 0 + + agent_results = [] + for retrieval in retrieval_results: + result = run_agent( + retrieval.row, + retrieval.source_urls, + agent_url=args.agent_url, + session_url=args.session_url, + origin=args.origin, + timeout=args.timeout, + ) + agent_results.append(result) + print_agent(result, verbose=args.verbose) + + return 0 if all(result.passed for result in agent_results) else 1 + + +if __name__ == "__main__": + try: + raise SystemExit(main()) + except (subprocess.CalledProcessError, urllib.error.URLError, json.JSONDecodeError) as error: + print(f"eval infrastructure error: {error}", file=sys.stderr) + raise SystemExit(3) from error diff --git a/tests/test_code_utils.py b/tests/test_code_utils.py index 981bd02c..5c51e05a 100644 --- a/tests/test_code_utils.py +++ b/tests/test_code_utils.py @@ -1,7 +1,13 @@ """Tests for code and manifest chunking utilities.""" +import base64 +import importlib.util +import json import sys from pathlib import Path +from types import SimpleNamespace + +import pytest PIPELINES_DIR = Path(__file__).parent.parent / "docs-agent-mcp" / "pipelines" @@ -10,6 +16,103 @@ from code_utils import chunk_code_file, parse_json_file, parse_python_ast, parse_yaml_documents +def load_code_pipeline_module(): + """Load the hyphenated pipeline module so component python funcs are testable.""" + pytest.importorskip("kfp", reason="pipeline component tests require the KFP SDK") + pipeline_path = PIPELINES_DIR / "code-pipeline.py" + spec = importlib.util.spec_from_file_location("code_pipeline", pipeline_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class FakeResponse: + def __init__(self, payload): + self.payload = payload + self.status_code = 200 + self.headers = {} + + def json(self): + return self.payload + + def raise_for_status(self): + return None + + +def test_code_pipeline_preserves_github_canonical_citation_url(monkeypatch, tmp_path): + """Katib's master branch URL must survive download and chunking unchanged.""" + module = load_code_pipeline_module() + source_url = "https://github.com/kubeflow/katib/blob/master/examples/v1beta1/hp-tuning/random.yaml" + contents_url = "https://api.github.com/repos/kubeflow/katib/contents/examples/v1beta1/hp-tuning" + file_api_url = "https://api.github.com/repos/kubeflow/katib/contents/random.yaml" + yaml_text = "apiVersion: kubeflow.org/v1beta1\nkind: Experiment\nmetadata:\n name: random\n" + + def fake_get(url, params=None, headers=None): + if url == contents_url: + return FakeResponse( + [ + { + "type": "file", + "name": "random.yaml", + "path": "examples/v1beta1/hp-tuning/random.yaml", + "url": file_api_url, + "html_url": source_url, + } + ] + ) + if url == file_api_url: + return FakeResponse( + { + "content": base64.b64encode(yaml_text.encode()).decode(), + "html_url": source_url, + } + ) + raise AssertionError(f"Unexpected GitHub URL: {url}") + + monkeypatch.setattr("requests.get", fake_get) + downloaded_path = tmp_path / "downloaded.jsonl" + module.download_github_code.python_func( + repos="kubeflow/katib", + directory_paths="examples/v1beta1/hp-tuning", + file_extensions="yaml,yml", + github_token="test-token", + code_data=SimpleNamespace(path=str(downloaded_path)), + ) + + downloaded = json.loads(downloaded_path.read_text()) + assert downloaded["citation_url"] == source_url + + monkeypatch.setattr("requests.post", lambda *args, **kwargs: FakeResponse([[0.1, 0.2]])) + embedded_path = tmp_path / "embedded.jsonl" + module.chunk_and_embed_code.python_func( + code_data=SimpleNamespace(path=str(downloaded_path)), + chunk_size=1000, + chunk_overlap=100, + embeddings_service_url="http://embeddings.test/embed", + embedding_batch_size=8, + embedded_data=SimpleNamespace(path=str(embedded_path)), + ) + + embedded = json.loads(embedded_path.read_text()) + assert embedded["citation_url"] == source_url + + +def test_compiled_code_pipeline_injects_required_secrets(tmp_path): + """Compilation must fail closed rather than silently omit Milvus auth.""" + module = load_code_pipeline_module() + compiled_path = tmp_path / "code_rag_pipeline.yaml" + + module.kfp.compiler.Compiler().compile( + pipeline_func=module.code_rag_pipeline, + package_path=str(compiled_path), + ) + + compiled = compiled_path.read_text() + assert "milvus-auth" in compiled + assert "MILVUS_PASSWORD" in compiled + assert "github-pat" in compiled + + class TestParseYamlDocuments: """Tests for Kubernetes YAML-aware chunking.""" diff --git a/tests/test_docs_pipeline.py b/tests/test_docs_pipeline.py new file mode 100644 index 00000000..9349d4a0 --- /dev/null +++ b/tests/test_docs_pipeline.py @@ -0,0 +1,283 @@ +"""Tests for the full documentation ingestion pipeline.""" + +import importlib.util +import json +import sys +from pathlib import Path +from types import ModuleType, SimpleNamespace + +import pytest + + +PIPELINES_DIR = Path(__file__).parent.parent / "docs-agent-mcp" / "pipelines" +sys.path.insert(0, str(PIPELINES_DIR)) + + +class DataType: + INT64 = "INT64" + VARCHAR = "VARCHAR" + FLOAT_VECTOR = "FLOAT_VECTOR" + + +class FieldSchema: + def __init__(self, name, dtype, **params): + self.name = name + self.dtype = dtype + self.params = params + + +class CollectionSchema: + def __init__(self, fields, description=""): + self.fields = fields + self.description = description + + +def fake_pymilvus_module(): + module = ModuleType("pymilvus") + module.CollectionSchema = CollectionSchema + module.DataType = DataType + module.FieldSchema = FieldSchema + module.Collection = lambda *args, **kwargs: None + module.connections = SimpleNamespace(connect=lambda *args, **kwargs: None) + module.utility = SimpleNamespace(has_collection=lambda *args, **kwargs: False) + return module + + +def load_docs_pipeline_module(): + pytest.importorskip("kfp", reason="pipeline component tests require the KFP SDK") + pipeline_path = PIPELINES_DIR / "kubeflow-pipeline.py" + spec = importlib.util.spec_from_file_location("kubeflow_pipeline", pipeline_path) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +def legacy_docs_schema(): + """Match the compatible pre-versioned schema currently used in Milvus.""" + return CollectionSchema( + [ + FieldSchema(name="id", dtype=DataType.INT64, is_primary=True, auto_id=True), + FieldSchema(name="file_unique_id", dtype=DataType.VARCHAR, max_length=512), + FieldSchema(name="repo_name", dtype=DataType.VARCHAR, max_length=256), + FieldSchema(name="file_path", dtype=DataType.VARCHAR, max_length=512), + FieldSchema(name="file_name", dtype=DataType.VARCHAR, max_length=256), + FieldSchema(name="citation_url", dtype=DataType.VARCHAR, max_length=512), + FieldSchema(name="chunk_index", dtype=DataType.INT64), + FieldSchema(name="content_text", dtype=DataType.VARCHAR, max_length=4096), + FieldSchema(name="vector", dtype=DataType.FLOAT_VECTOR, dim=768), + ], + description="", + ) + + +def test_store_accepts_compatible_legacy_schema_without_last_updated(monkeypatch, tmp_path): + module = load_docs_pipeline_module() + inserted = [] + pymilvus = fake_pymilvus_module() + + class FakeCollection: + description = "" + schema = legacy_docs_schema() + indexes = [object()] + num_entities = 1 + + def load(self): + return None + + def query(self, **kwargs): + return [] + + def delete(self, expr): + raise AssertionError("No old records were returned, so delete must not run") + + def insert(self, batch): + inserted.extend(batch) + + def flush(self): + return None + + def has_index(self): + return True + + monkeypatch.setitem(sys.modules, "pymilvus", pymilvus) + monkeypatch.setattr(pymilvus.connections, "connect", lambda *args, **kwargs: None) + monkeypatch.setattr(pymilvus.utility, "has_collection", lambda name: True) + monkeypatch.setattr(pymilvus, "Collection", lambda name: FakeCollection()) + monkeypatch.setenv("MILVUS_PASSWORD", "test-password") + + input_path = tmp_path / "embedded.jsonl" + record = { + "file_unique_id": "website:content/en/docs/components/katib/example.md", + "repo_name": "website", + "file_path": "content/en/docs/components/katib/example.md", + "file_name": "example.md", + "citation_url": "https://www.kubeflow.org/docs/components/katib/example", + "chunk_index": 0, + "content_text": "Katib Experiment evidence", + "embedding": [0.0] * 768, + } + input_path.write_text(json.dumps(record) + "\n") + + module.store_milvus.python_func( + embedded_data=SimpleNamespace(path=str(input_path)), + milvus_host="milvus.test", + milvus_port="19530", + collection_name="kubeflow_docs", + embedding_dim=768, + ) + + assert len(inserted) == 1 + assert "last_updated" not in inserted[0] + assert inserted[0]["citation_url"] == record["citation_url"] + + +def test_docs_cleaner_preserves_markdown_link_adjacent_yaml(monkeypatch, tmp_path): + module = load_docs_pipeline_module() + + class FakeEmbeddingResponse: + def raise_for_status(self): + return None + + def json(self): + return [[0.0] * 768] + + monkeypatch.setattr("requests.post", lambda *args, **kwargs: FakeEmbeddingResponse()) + source_path = tmp_path / "docs.jsonl" + source_path.write_text( + json.dumps( + { + "path": "content/en/docs/components/katib/configure-experiment.md", + "file_name": "configure-experiment.md", + "content": """--- +title: Configure an Experiment +--- +### Running Katib Experiment with Istio + +Katib Experiment from [this directory](https://github.com/kubeflow/katib/tree/main/examples) +doesn't work with [Istio sidecar injection](https://istio.io/latest/docs/setup/additional-setup/sidecar-injection/#automatic-sidecar-injection). +Specify this annotation: + +```yaml +metadata: + annotations: + \"sidecar.istio.io/inject\": \"false\" +``` +""", + } + ) + + "\n" + ) + output_path = tmp_path / "embedded.jsonl" + + module.chunk_and_embed.python_func( + github_data=SimpleNamespace(path=str(source_path)), + repo_name="website", + base_url="https://www.kubeflow.org/docs", + chunk_size=2000, + chunk_overlap=60, + embeddings_service_url="http://embeddings.test/embed", + embedding_batch_size=8, + max_tei_chars=600, + embedded_data=SimpleNamespace(path=str(output_path)), + ) + + record = json.loads(output_path.read_text()) + assert "title: Configure an Experiment" not in record["content_text"] + assert "this directory" in record["content_text"] + assert '"sidecar.istio.io/inject": "false"' in record["content_text"] + assert "metadata:\n annotations:" in record["content_text"] + + +def test_store_replaces_legacy_chunk_ids_by_repo_and_file_path(monkeypatch, tmp_path): + module = load_docs_pipeline_module() + queried = [] + deleted = [] + pymilvus = fake_pymilvus_module() + + class FakeCollection: + description = "" + schema = legacy_docs_schema() + indexes = [object()] + num_entities = 3 + + def load(self): + return None + + def query(self, **kwargs): + queried.append(kwargs["expr"]) + return [{"id": 1}, {"id": 2}] + + def delete(self, expr): + deleted.append(expr) + + def insert(self, batch): + return None + + def flush(self): + return None + + def has_index(self): + return True + + monkeypatch.setitem(sys.modules, "pymilvus", pymilvus) + monkeypatch.setattr(pymilvus.connections, "connect", lambda *args, **kwargs: None) + monkeypatch.setattr(pymilvus.utility, "has_collection", lambda name: True) + monkeypatch.setattr(pymilvus, "Collection", lambda name: FakeCollection()) + monkeypatch.setenv("MILVUS_PASSWORD", "test-password") + + input_path = tmp_path / "embedded.jsonl" + record = { + "file_unique_id": "website:content/en/docs/components/katib/example.md", + "repo_name": "website", + "file_path": "content/en/docs/components/katib/example.md", + "file_name": "example.md", + "citation_url": "https://www.kubeflow.org/docs/components/katib/example", + "chunk_index": 0, + "content_text": "Katib Experiment evidence", + "embedding": [0.0] * 768, + } + input_path.write_text(json.dumps(record) + "\n") + + module.store_milvus.python_func( + embedded_data=SimpleNamespace(path=str(input_path)), + milvus_host="milvus.test", + milvus_port="19530", + collection_name="kubeflow_docs", + embedding_dim=768, + ) + + assert queried == ['repo_name == "website" and file_path in ["content/en/docs/components/katib/example.md"]'] + assert deleted == queried + + +def test_store_rejects_embedding_dim_mismatch(monkeypatch, tmp_path): + module = load_docs_pipeline_module() + pymilvus = fake_pymilvus_module() + + class FakeCollection: + description = "" + schema = legacy_docs_schema() + indexes = [object()] + num_entities = 0 + + def load(self): + raise AssertionError("must fail before load on dim mismatch") + + monkeypatch.setitem(sys.modules, "pymilvus", pymilvus) + monkeypatch.setattr(pymilvus.connections, "connect", lambda *args, **kwargs: None) + monkeypatch.setattr(pymilvus.utility, "has_collection", lambda name: True) + monkeypatch.setattr(pymilvus, "Collection", lambda name: FakeCollection()) + monkeypatch.setenv("MILVUS_PASSWORD", "test-password") + + input_path = tmp_path / "embedded.jsonl" + input_path.write_text("{}" + "\n") + + with pytest.raises(RuntimeError, match="vector_dim=768"): + module.store_milvus.python_func( + embedded_data=SimpleNamespace(path=str(input_path)), + milvus_host="milvus.test", + milvus_port="19530", + collection_name="kubeflow_docs", + embedding_dim=1024, + ) + diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 8fa2af12..4e6b69d1 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -150,6 +150,60 @@ def test_requests_correct_output_fields(self, inject_mocks): assert "content_text" in output_fields assert "citation_url" in output_fields assert "file_path" in output_fields + assert "chunk_index" in output_fields + + def test_reranks_and_expands_the_best_document(self, inject_mocks): + mock_client, _ = inject_mocks + mock_client.search.return_value = [ + [ + { + "distance": 0.90, + "entity": { + "content_text": "Katib introduction", + "citation_url": "https://www.kubeflow.org/docs/components/katib/getting-started", + "file_path": "content/en/docs/components/katib/getting-started.md", + "chunk_index": 0, + }, + }, + { + "distance": 0.82, + "entity": { + "content_text": "Experiment overview", + "citation_url": ( + "https://www.kubeflow.org/docs/components/katib/user-guides/hp-tuning/configure-experiment" + ), + "file_path": ("content/en/docs/components/katib/user-guides/hp-tuning/configure-experiment.md"), + "chunk_index": 0, + }, + }, + ] + ] + mock_client.query.return_value = [ + { + "chunk_index": 11, + "content_text": '"sidecar.istio.io/inject": "false"', + "citation_url": ( + "https://www.kubeflow.org/docs/components/katib/user-guides/hp-tuning/configure-experiment" + ), + "file_path": ("content/en/docs/components/katib/user-guides/hp-tuning/configure-experiment.md"), + }, + { + "chunk_index": 6, + "content_text": "parallelTrialCount controls concurrent Trials.", + "citation_url": ( + "https://www.kubeflow.org/docs/components/katib/user-guides/hp-tuning/configure-experiment" + ), + "file_path": ("content/en/docs/components/katib/user-guides/hp-tuning/configure-experiment.md"), + }, + ] + + result = server.search_kubeflow_docs("Katib hyperparameter tuning configuration", top_k=10) + + assert "parallelTrialCount controls" in result + assert '"sidecar.istio.io/inject": "false"' in result + assert "getting-started" not in result + assert result.count("**Source:**") == 1 + assert "configure-experiment" in mock_client.query.call_args.kwargs["filter"] def test_searches_correct_collection(self, inject_mocks): """Should search the configured COLLECTION_NAME.""" diff --git a/tests/test_showcase_eval.py b/tests/test_showcase_eval.py new file mode 100644 index 00000000..07ae9f54 --- /dev/null +++ b/tests/test_showcase_eval.py @@ -0,0 +1,112 @@ +"""Deterministic tests for the two-gate showcase evaluator.""" + +import importlib.util +import io +import sys +from pathlib import Path + + +EVAL_PATH = Path(__file__).parent / "eval" / "run_showcase_eval.py" +SPEC = importlib.util.spec_from_file_location("run_showcase_eval", EVAL_PATH) +EVAL = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = EVAL +SPEC.loader.exec_module(EVAL) + + +def golden_row(): + return { + "id": "golden", + "tool": "search_kubeflow_code", + "query": "Show me an example", + "retrieval_query": "katib random yaml", + "expected_source_urls": ["https://github.com/kubeflow/katib/blob/master/random.yaml"], + "must_appear_in_answer": ["kubeflow.org/v1beta1", "kind: Experiment"], + "forbidden_in_answer": ["katib.mlr-org"], + } + + +def test_retrieval_gate_and_evidence_are_scored_separately(): + output = """**Source:** https://github.com/kubeflow/katib/blob/master/random.yaml + +apiVersion: kubeflow.org/v1beta1 +""" + result = EVAL.score_retrieval(golden_row(), output) + + assert result.passed + assert result.missing_sources == [] + assert result.missing_evidence == ["kind: Experiment"] + + +def test_retrieval_gate_blocks_absent_source_even_when_answer_terms_exist(): + output = "apiVersion: kubeflow.org/v1beta1\nkind: Experiment" + result = EVAL.score_retrieval(golden_row(), output) + + assert not result.passed + assert result.missing_sources == golden_row()["expected_source_urls"] + assert result.missing_evidence == [] + + +def test_extract_answer_urls_removes_markdown_delimiter(): + answer = ( + "Sources:\n- [Random](https://github.com/kubeflow/katib/blob/master/random.yaml)\n" + "See https://www.kubeflow.org/docs." + ) + assert EVAL.extract_answer_urls(answer) == { + "https://github.com/kubeflow/katib/blob/master/random.yaml", + "https://www.kubeflow.org/docs", + } + + +def test_tool_detection_requires_a_tool_name_field(): + event = {"result": {"message": {"parts": [{"kind": "function_call", "name": "search_kubeflow_code"}]}}} + assert EVAL.event_names_tool(event, "search_kubeflow_code") + assert not EVAL.event_names_tool( + {"result": {"message": {"parts": [{"kind": "text", "text": "search_kubeflow_code"}]}}}, + "search_kubeflow_code", + ) + + +def test_strings_in_event_finds_embedded_tool_sources(): + event = { + "result": { + "parts": [ + { + "kind": "function_response", + "response": "**Source:** https://example.test/source\n\nEvidence", + } + ] + } + } + values = list(EVAL.strings_in_event(event)) + + assert EVAL.SOURCE_RE.findall("\n".join(values)) == ["https://example.test/source"] + + +def test_tool_calls_in_event_extracts_named_tool_args_once_per_event_shape(): + event = { + "result": { + "message": { + "parts": [ + { + "kind": "function_call", + "name": "search_github_issues", + "args": {"query": "deploymentMode Serverless", "repo": "kserve/kserve"}, + } + ] + } + } + } + + assert EVAL.tool_calls_in_event(event, "search_github_issues") == [ + '{"query": "deploymentMode Serverless", "repo": "kserve/kserve"}' + ] + + +def test_final_message_wins_over_partial_stream_fragments(): + assert EVAL.select_answer("authoritative final", ["partial ", "draft"]) == ("authoritative final") + assert EVAL.select_answer("", ["partial ", "fallback"]) == "partial fallback" + + +def test_sse_parser_joins_multiline_data_and_skips_comments(): + stream = io.BytesIO(b': keepalive\n\ndata: {"result":\ndata: {"final": true}}\n\ndata: [DONE]\n\n') + assert list(EVAL.iter_sse_events(stream)) == [{"result": {"final": True}}] diff --git a/tests/test_widget_markdown.py b/tests/test_widget_markdown.py new file mode 100644 index 00000000..76422584 --- /dev/null +++ b/tests/test_widget_markdown.py @@ -0,0 +1,83 @@ +"""Behavioral tests for the widget's dependency-free Markdown formatter.""" + +import json +import shutil +import subprocess +from pathlib import Path + +import pytest + + +CHATBOT_JS = Path(__file__).parent.parent / "frontend" / "docs_scripts" / "chatbot.js" + + +def run_formatter(text: str, *, streaming: bool = False) -> str: + node = shutil.which("node") + if not node: + pytest.skip("Node.js is required for widget formatter tests") + + script = f""" +const fs = require('fs'); +const vm = require('vm'); +const source = fs.readFileSync({json.dumps(str(CHATBOT_JS))}, 'utf8'); +const prelude = source.split("document.addEventListener('DOMContentLoaded'")[0]; +const context = {{}}; +vm.createContext(context); +vm.runInContext(prelude, context); +process.stdout.write(context.formatChatMarkdown( + {json.dumps(text)}, + {json.dumps(streaming)} +)); +""" + completed = subprocess.run( + [node, "-e", script], + check=True, + capture_output=True, + text=True, + ) + return completed.stdout + + +def test_linkifies_only_http_sources_with_safe_anchor_attributes(): + rendered = run_formatter("[Katib Experiment](https://www.kubeflow.org/docs/components/katib/)") + + assert rendered == ( + 'Katib Experiment' + ) + assert run_formatter("[unsafe](javascript:alert(1))") == ("[unsafe](javascript:alert(1))") + + +def test_escapes_markdown_link_label_and_query_delimiter(): + rendered = run_formatter("[](https://example.test/docs?a=1&b=2)") + + assert "<img src=x>" in rendered + assert 'href="https://example.test/docs?a=1&b=2"' in rendered + assert "' in rendered + + +def test_does_not_linkify_markdown_inside_inline_code(): + rendered = run_formatter("Use `[title](https://example.test/literal)` then [open docs](https://example.test/docs).") + + assert "[title](https://example.test/literal)" in rendered + assert rendered.count("