Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand Down
4 changes: 4 additions & 0 deletions docs-agent-mcp/charts/gateway-guardrails/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
62 changes: 35 additions & 27 deletions docs-agent-mcp/manifests/kagent/setup.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
86 changes: 85 additions & 1 deletion docs-agent-mcp/mcp-server/server.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import os
import re
import threading
Expand All @@ -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():
Expand Down Expand Up @@ -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."""
Expand All @@ -76,14 +155,19 @@ 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}"

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"]
Expand Down
14 changes: 12 additions & 2 deletions docs-agent-mcp/pipelines/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,15 +77,25 @@ python kubeflow-pipeline.py
</tr>
<tr>
<td><code>chunk_size</code></td>
<td>1000</td>
<td>600</td>
<td>Text chunk size for embeddings</td>
</tr>
<tr>
<td><code>chunk_overlap</code></td>
<td>100</td>
<td>60</td>
<td>Overlap between chunks</td>
</tr>
<tr>
<td><code>max_tei_chars</code></td>
<td>600</td>
<td>Per-input truncation before TEI embedding (model-dependent)</td>
</tr>
<tr>
<td><code>embedding_dim</code></td>
<td>768</td>
<td>Milvus vector dimension (must match the embeddings model)</td>
</tr>
<tr>
<td><code>milvus_host</code></td>
<td>"milvus-standalone-final.docs-agent.svc.cluster.local"</td>
<td>Milvus server host</td>
Expand Down
17 changes: 10 additions & 7 deletions docs-agent-mcp/pipelines/code-pipeline.py
Original file line number Diff line number Diff line change
@@ -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(
Expand Down Expand Up @@ -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}")
Expand Down Expand Up @@ -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)

Expand Down
6 changes: 1 addition & 5 deletions docs-agent-mcp/pipelines/issues-pipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading