From 3a391bd004d41ea18d09f44be4574aecb0f85287 Mon Sep 17 00:00:00 2001 From: Arinjay Wyawhare <72088094+jaywyawhare@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:09:19 +0530 Subject: [PATCH] Render retrieval context in named formats --- docs/retrieval.md | 38 ++++++++- src/selfgraph/__init__.py | 9 ++ src/selfgraph/_context.py | 83 ++++++++++++++++++ src/selfgraph/cli.py | 3 + src/selfgraph/client.py | 6 ++ src/selfgraph/mcp/server.py | 3 + src/selfgraph/models.py | 23 ++++- src/selfgraph/retrieval.py | 103 +++++++++++----------- tests/test_context_formats.py | 74 ++++++++++++++++ tests/test_retrieve.py | 4 +- typescript/src/cli.ts | 3 + typescript/src/client.ts | 2 +- typescript/src/context.ts | 56 ++++++++++++ typescript/src/index.ts | 4 + typescript/src/mcp.ts | 4 + typescript/src/models.ts | 16 ++++ typescript/src/retrieval.ts | 114 +++++++++++++++---------- typescript/test/conformance/py_side.py | 8 ++ typescript/test/conformance/ts_side.ts | 9 ++ typescript/test/contextFormats.test.ts | 82 ++++++++++++++++++ 20 files changed, 543 insertions(+), 101 deletions(-) create mode 100644 src/selfgraph/_context.py create mode 100644 tests/test_context_formats.py create mode 100644 typescript/src/context.ts create mode 100644 typescript/test/contextFormats.test.ts diff --git a/docs/retrieval.md b/docs/retrieval.md index e53155b1..c77e433d 100644 --- a/docs/retrieval.md +++ b/docs/retrieval.md @@ -13,7 +13,8 @@ print(result.context) | `query`, `strategy` | The query and strategy used. | | `seeds` | The seed entities as `{id, score}`, best first. | | `subgraph` | The collected `entities`, `relations`, `preferences`, and `decisions`. | -| `context` | Source passages (`SOURCE \| ...`), then graph records: relations, preferences, decisions, and entities (`GRAPH \| Acme [Company]`). Passages appear only here. SDK-built graph headers carry [certification](trust.md#certification) and [hub](trust.md#hubs) metadata; see the format below. | +| `context` | The rendered source passages and graph records. Defaults to the prompt format. | +| `context_records` | The ordered, complete context records as `{kind, id, text, labels, n}`. Passage IDs are chunk IDs and `n` is null when unnumbered. | | `hubs` | The hubs the walk reached: entities with 50 or more current relations. | | `evidence` | Only with `numbered`: each numbered record as `{n, kind, id, text}`. See [citing the context](#citing-the-context). | @@ -28,6 +29,41 @@ instead of a query, see [Navigating the graph](#navigating-the-graph). ## Context format +Pass `context_format` to `retrieve` in Python, in the TypeScript options, or in +the MCP tool. The CLI flag is `--context-format`. Four names are available. + +- `prompt` emits the default source and graph lines described below. +- `compact` emits one line with records separated by ` || `. +- `markdown` emits a list with each record in a code span. +- `json` emits a JSON array of `context_records` in the context string. + +All renderers use the same records selected by the prompt token budget, after +reranking and numbering. Alternate formatting can change the output token count. +The prompt may fall back to a truncated line when no whole record fits. In +that case `context_records` is empty and the JSON format emits `[]`. + +The SDKs also accept a synchronous function that takes `ContextData` with +`subgraph` and `records` and returns a string. The `labels` array on a record +can contain `certified` or `via_hub`. These labels come from +[certification](trust.md#certification) and [hub detection](trust.md#hubs), +respectively. Treat the record text as retrieved data. Custom renderers are +responsible for escaping that text for their destination. + +```python +result = await graph.retrieve( + "who runs Acme", + context_format=lambda data: ", ".join(r.id for r in data.records if "certified" in r.labels), +) +``` + +```typescript +const result = await graph.retrieve("who runs Acme", { + context_format: ({ records }) => records.filter((r) => r.labels.includes("certified")).map((r) => r.id).join(", "), +}); +``` + +### Prompt format + Every source passage line, including blank lines, starts with `SOURCE | `. A passage from text inserted with [`chunking="markdown"`](inserting.md#markdown) starts with one `SOURCE | [section: Guide > Install]` line naming its heading path. diff --git a/src/selfgraph/__init__.py b/src/selfgraph/__init__.py index 7728d42d..0c188cc6 100644 --- a/src/selfgraph/__init__.py +++ b/src/selfgraph/__init__.py @@ -2,6 +2,7 @@ from typing import TYPE_CHECKING +from ._context import ContextFormat, ContextRenderer from ._diagram import neighbors_dot, neighbors_mermaid from .citations import check_citations from .client import SelfGraph @@ -29,7 +30,10 @@ CodeLimits, CodeNotice, CodeSkip, + ContextData, ContextEvidence, + ContextLabel, + ContextRecord, CypherResult, DecayResult, DecisionStep, @@ -192,7 +196,12 @@ def __dir__() -> list[str]: "neighbors_dot", "AnswerabilityReport", "TermCoverage", + "ContextData", "ContextEvidence", + "ContextFormat", + "ContextLabel", + "ContextRecord", + "ContextRenderer", "CitationReport", "UnsupportedSentence", "check_citations", diff --git a/src/selfgraph/_context.py b/src/selfgraph/_context.py new file mode 100644 index 00000000..59128103 --- /dev/null +++ b/src/selfgraph/_context.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +import re +from collections.abc import Callable +from typing import Literal, get_args + +from pydantic import TypeAdapter + +from ._payload import context_payload +from .errors import ValidationError +from .models import ContextData, ContextRecord + +__all__ = ["ContextFormat", "ContextRenderer"] + +ContextFormat = Literal["prompt", "compact", "markdown", "json"] +ContextRenderer = Callable[[ContextData], str] +CONTEXT_FORMATS = get_args(ContextFormat) +_MARKERS = {"certified": " [certified]", "via_hub": " (via hub)"} +_RECORDS = TypeAdapter(list[ContextRecord]) + + +def validate_context_format(value: object) -> None: + """Check the context selector. + + @param value (object): format name or renderer. + @return (None): raises on invalid input. + """ + if not callable(value) and (not isinstance(value, str) or value not in CONTEXT_FORMATS): + raise ValidationError( + f"context_format must be one of {', '.join(CONTEXT_FORMATS)} or a renderer", field="context_format" + ) + + +def prompt_line(record: ContextRecord, n: int | None, *, multiline: bool = True) -> str: + """Render a prompt record. + + @param record (ContextRecord): source or graph record. + @param n (int | None): citation number. + @param multiline (bool): retain source line boundaries. + @return (str): framed text. + """ + header = "SOURCE" if record.kind == "passage" else "GRAPH" + header += "".join(_MARKERS[label] for label in record.labels) + if n is not None: + header += f" #{n}" + if record.kind == "passage" and multiline: + return context_payload(record.text, header=header) + return f"{header} | {context_payload(record.text)}" + + +def _markdown_line(record: ContextRecord) -> str: + """Render a source or graph record as a list item. + + @param record (ContextRecord): admitted record. + @return (str): Markdown list item. + """ + text = prompt_line(record, record.n, multiline=False) + fence = "`" * (1 + max(map(len, re.findall(r"`+", text)), default=0)) + return f"- {fence} {text} {fence}" + + +def render_context(renderer: ContextFormat | ContextRenderer, data: ContextData, prompt: str) -> str: + """Render admitted context. + + @param renderer (ContextFormat | ContextRenderer): chosen renderer. + @param data (ContextData): subgraph and admitted records. + @param prompt (str): cached budgeted prompt text. + @return (str): rendered context. + """ + if renderer == "prompt": + return prompt + if renderer == "compact": + return " || ".join( + prompt_line(record, record.n, multiline=False).replace("||", r"\|\|") for record in data.records + ) + if renderer == "markdown": + return "\n".join(map(_markdown_line, data.records)) + if renderer == "json": + return _RECORDS.dump_json(data.records).decode() + rendered = renderer(data) + if not isinstance(rendered, str): + raise ValidationError("context renderer must return a string", field="context_format") + return rendered diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index 6f99b56f..70f3f5f3 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -14,6 +14,7 @@ from typing import Any, NoReturn, get_args from . import _ops +from ._context import CONTEXT_FORMATS from ._diagram import DIAGRAM_FORMATS, neighbors_dot, neighbors_mermaid from ._diff import timeline_view from ._install import AGENTS, apply_changes, apply_hooks, plan_hooks, plan_install, server_command @@ -262,6 +263,7 @@ async def _retrieve(graph, args): skip_hubs=args.skip_hubs, numbered=args.numbered, rerank=args.rerank, + context_format=args.context_format, ) return _Text(result.context) if args.context_only else result @@ -940,6 +942,7 @@ def build_parser() -> argparse.ArgumentParser: rt.add_argument("--as-of", type=_time("as_of"), help=f"read the graph as of this time ({_ISO})") rt.add_argument("--known-at", type=_time("known_at"), help=f"read only what the graph held at this time ({_ISO})") rt.add_argument("--skip-hubs", action="store_true", help="do not walk through entities with 50 or more relations") + rt.add_argument("--context-format", default="prompt", help=f"context format: {', '.join(CONTEXT_FORMATS)}") rt.add_argument("--context-only", action="store_true", help="print only the context text, not the JSON result") rt.add_argument("--numbered", action="store_true", help="number each context record and list them in evidence") rt.set_defaults(func=_retrieve) diff --git a/src/selfgraph/client.py b/src/selfgraph/client.py index c4535390..f2920b93 100644 --- a/src/selfgraph/client.py +++ b/src/selfgraph/client.py @@ -9,6 +9,7 @@ from typing import Any from . import _ops, tiers +from ._context import ContextFormat, ContextRenderer, validate_context_format from ._cypher_guard import check_cypher_limits from ._diff import about_entity, decode_diff_cursor, graph_diff, page from ._execution import _store_call @@ -419,6 +420,7 @@ async def retrieve( skip_hubs: bool = False, numbered: bool | int = False, rerank: tiers.RerankTier | None = None, + context_format: ContextFormat | ContextRenderer = "prompt", **options: Any, ) -> RetrievalResult: """Retrieve graph context for a query via keyword seeds, or from given entities, and bounded traversal. @@ -444,6 +446,7 @@ async def retrieve( evidence, or a whole number to start the numbering from. @param rerank (RerankTier | None): reorder the context records before the budget: "off", "lexical" for BM25, "embeddings" for embedder similarity, or None for the graph's tier. + @param context_format (ContextFormat | ContextRenderer): a named or caller-supplied renderer. @return (RetrievalResult): the seeds, the collected subgraph, the assembled context, and the hubs reached. """ check_options( @@ -462,6 +465,7 @@ async def retrieve( "skip_hubs", "numbered", "rerank", + "context_format", ], ) if query is None and entity_ids is None: @@ -492,6 +496,7 @@ async def retrieve( _ops._require_bool("skip_hubs", skip_hubs) first = first_number(numbered) as_of = _ops.parse_as_of(as_of, known_at) + validate_context_format(context_format) await self._ensure_ready() return await _retrieve( self, @@ -507,6 +512,7 @@ async def retrieve( skip_hubs=skip_hubs, numbered=first, rerank=rerank_tier, + context_format=context_format, ) async def check_citations(self, answer: str, evidence: Any) -> CitationReport: diff --git a/src/selfgraph/mcp/server.py b/src/selfgraph/mcp/server.py index 928ea3fe..6f85837d 100644 --- a/src/selfgraph/mcp/server.py +++ b/src/selfgraph/mcp/server.py @@ -1006,6 +1006,7 @@ async def retrieve( skip_hubs: StrictBool = False, numbered: StrictBool = False, rerank: str | None = None, + context_format: str = "prompt", ) -> dict[str, Any]: """Retrieve graph context for a query by keyword seeds and bounded BFS, DFS, or PageRank ("ppr") ranking. as_of (ISO 8601, no offset means UTC, or relative such as 7d) reads the graph as it stood at that time. known_at @@ -1014,6 +1015,7 @@ async def retrieve( and graph records by relevance before the budget, default to the server's level. hubs lists entities with 50 or more relations the walk reached; context lines through one are marked (via hub), as weak links. skip_hubs stops the walk at hubs. Pass entity_ids (from find_entities) instead of query to start from those entities as the seeds. + context_format can be prompt (default), compact, markdown, or json. numbered numbers each context record in its header (GRAPH #3 | ...) and lists it in evidence as {n, kind, id, text}, continuing from the last number of this session, so cite records as [n] and check with check_citations.""" g = await _graph_handle() @@ -1031,6 +1033,7 @@ async def retrieve( skip_hubs=skip_hubs, numbered=len(_session_evidence.get(_evidence)) + 1 if numbered else False, rerank=rerank, + context_format=context_format, ) _session_evidence.get(_evidence).extend(result.evidence or ()) return to_jsonable(result) diff --git a/src/selfgraph/models.py b/src/selfgraph/models.py index c469d4d7..bcf0b253 100644 --- a/src/selfgraph/models.py +++ b/src/selfgraph/models.py @@ -68,7 +68,10 @@ "RetrievalSeed", "Subgraph", "RetrievalResult", + "ContextData", "ContextEvidence", + "ContextLabel", + "ContextRecord", "CitationReport", "UnsupportedSentence", "SearchPassage", @@ -1115,11 +1118,28 @@ class Subgraph(BaseModel): decisions: list[DecisionTrace] = Field(default_factory=list) +ContextKind = Literal["passage", "relation", "preference", "decision", "entity"] +ContextLabel = Literal["certified", "via_hub"] + + class ContextEvidence(BaseModel): n: int - kind: Literal["passage", "relation", "preference", "decision", "entity"] + kind: ContextKind + id: str + text: str + + +class ContextRecord(BaseModel): + kind: ContextKind id: str text: str + labels: list[ContextLabel] = Field(default_factory=list) + n: int | None = None + + +class ContextData(BaseModel): + subgraph: Subgraph + records: list[ContextRecord] class RetrievalResult(BaseModel): @@ -1131,6 +1151,7 @@ class RetrievalResult(BaseModel): tiers: dict[str, str] = Field(default_factory=dict) hubs: list[str] = Field(default_factory=list) evidence: list[ContextEvidence] | None = None + context_records: list[ContextRecord] = Field(default_factory=list) @model_serializer(mode="wrap") def _omit_unnumbered(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: diff --git a/src/selfgraph/retrieval.py b/src/selfgraph/retrieval.py index 18358a6b..c86245ae 100644 --- a/src/selfgraph/retrieval.py +++ b/src/selfgraph/retrieval.py @@ -11,9 +11,9 @@ from typing import TYPE_CHECKING from . import _ops +from ._context import ContextFormat, ContextRenderer, prompt_line, render_context from ._maintenance import scan_entities, scan_relations from ._ops import AsOf, _paged -from ._payload import context_payload from ._serde import ( L_CHUNK, L_ENTITY, @@ -32,7 +32,10 @@ from .ids import _word_runs, content_hash, normalize_rel_type, normalize_text, profile_id from .models import ( AnswerabilityReport, + ContextData, ContextEvidence, + ContextLabel, + ContextRecord, DecisionTrace, Entity, ImpactedEntity, @@ -1139,22 +1142,22 @@ async def _rerank_scores(graph: SelfGraph, tier: str, query: str, texts: list[st return scores -async def _rerank(graph: SelfGraph, tier: str, query: str, records: list[tuple[str, ...]]) -> list[tuple[str, ...]]: +async def _rerank(graph: SelfGraph, tier: str, query: str, records: list[ContextRecord]) -> list[ContextRecord]: """Reorder the passages among themselves and the graph records among themselves by relevance to the query. @param graph (SelfGraph): the open graph, with its embedder or reranker. @param tier (str): "lexical", "embeddings", or "custom". @param query (str): the query, or the seed entities' names and aliases. - @param records (list[tuple[str, ...]]): each record's kind, id, header, and text, passages first. - @return (list[tuple[str, ...]]): the records, passages still first, best first, ties in their given order. + @param records (list[ContextRecord]): the candidate context records, passages first. + @return (list[ContextRecord]): the records, passages still first, best first, ties in their given order. """ - scores = await _rerank_scores(graph, tier, query, [record[-1] for record in records]) - order = sorted(range(len(records)), key=lambda i: (records[i][0] != "passage", -scores[i])) + scores = await _rerank_scores(graph, tier, query, [record.text for record in records]) + order = sorted(range(len(records)), key=lambda i: (records[i].kind != "passage", -scores[i])) return [records[i] for i in order] async def _assemble( - passages, + passages: dict[str, str], entities, relations, preferences, @@ -1163,13 +1166,12 @@ async def _assemble( dist: dict[str, int], budget_tokens: int, hubs: Collection[str] = (), - evidence: list[ContextEvidence] | None = None, - start: int = 1, - rerank: Callable[[list[tuple[str, ...]]], Awaitable[list[tuple[str, ...]]]] | None = None, -) -> str: - """Serialise passages and the subgraph into text for an LLM, under a token budget, nearest first. + start: int = 0, + rerank: Callable[[list[ContextRecord]], Awaitable[list[ContextRecord]]] | None = None, +) -> tuple[str, list[ContextRecord]]: + """Select ordered context records under the prompt token budget. - @param passages (Iterable[str]): source passages to ground the answer, most relevant first. + @param passages (dict[str, str]): source passage texts and their chunk ids, most relevant first. @param entities (list[Entity]): the collected entities. @param relations (list[Relation]): the collected relations. @param preferences (list[Preference]): the collected preferences. @@ -1178,30 +1180,23 @@ async def _assemble( @param dist (dict[str, int]): each entity's closeness rank to the query, lower first (hops, or PageRank rank). @param budget_tokens (int): the maximum estimated tokens to emit; the first line that does not fit ends the context, and a first line that does not fit is cut to the budget. - @param hubs (Collection[str]): hub entity ids; a relation line through one is marked "(via hub)". - @param evidence (list[ContextEvidence] | None): when given, number each record that fits in its header ("#n") - and append it here; a passage's id is left empty for the caller to fill. - @param start (int): the number of the first record. - @param rerank (Callable | None): reorders the records, as (kind, id, header, text), before the budget and the - numbering; None keeps them. - @return (str): the assembled context text. Certified relations come first among equally close ones and are - marked "[certified]". A placeholder gets no line of its own. + @param hubs (Collection[str]): non-seed hub entity ids to mark on relations. + @param start (int): the first citation number, or 0 to leave the records unnumbered. + @param rerank (Callable | None): reorders the records before the budget and numbering. + @return (tuple[str, list[ContextRecord]]): the budgeted prompt and its complete records. """ lines: list[str] = [] + selected: list[ContextRecord] = [] first: list[str] = [] used = 0 rounding = 0 boundary = 0 full = False - def add(payload: str, cap: int, kind: str, rid: str = "", header: str = "GRAPH") -> bool: + def add(record: ContextRecord, cap: int) -> bool: nonlocal used, full, rounding, boundary - n = start + len(evidence) if evidence is not None else None - if n is not None: - header += f" #{n}" - line = ( - context_payload(payload, header=header) if kind == "passage" else f"{header} | {context_payload(payload)}" - ) + n = start + len(selected) if start else None + line = prompt_line(record, n) if not first: first.append(line) rounding = count_tokens("") @@ -1213,15 +1208,15 @@ def add(payload: str, cap: int, kind: str, rid: str = "", header: str = "GRAPH") full = cap >= budget_tokens return False lines.append(line) - if evidence is not None and n is not None: - evidence.append(ContextEvidence(n=n, kind=kind, id=rid, text=payload)) + record.n = n + selected.append(record) used += cost delta = count_tokens(line + "\n") - plain boundary = max(rounding, delta) if rounding else delta return True passage_cap = budget_tokens * _PASSAGE_BUDGET_PERCENT // 100 - records = [("passage", "", "SOURCE", p) for p in passages] + records = [ContextRecord(kind="passage", id=cid, text=text) for text, cid in passages.items()] far = len(dist) + 1 @@ -1235,12 +1230,12 @@ def rel_rank(r: Relation) -> tuple[int, int, bool, float]: props = _format_props(r.properties) if props: line += f" {props}" - header = "GRAPH" + labels: list[ContextLabel] = [] if r.certified_at is not None: - header += " [certified]" + labels.append("certified") if r.from_entity in hubs or r.to_entity in hubs: - header += " (via hub)" - records.append(("relation", r.id, header, line)) + labels.append("via_hub") + records.append(ContextRecord(kind="relation", id=r.id, text=line, labels=labels)) for p in sorted(preferences, key=lambda p: dist.get(p.subject_entity, far)): verb = preference_edge_type(p.stance).lower() @@ -1249,7 +1244,7 @@ def rel_rank(r: Relation) -> tuple[int, int, bool, float]: line = f"{subject} {verb} {value} ({p.key})" if p.strength is not None: line += f" [strength {p.strength}]" - records.append(("preference", p.id, "GRAPH", line)) + records.append(ContextRecord(kind="preference", id=p.id, text=line)) for d in decisions: parts = [f"Decision: {d.title}"] @@ -1259,20 +1254,23 @@ def rel_rank(r: Relation) -> tuple[int, int, bool, float]: parts.append("alternatives " + ", ".join(names.get(a, a) for a in d.alternative_entities)) if d.rationale: parts.append(f"rationale {d.rationale}") - records.append(("decision", d.id, "GRAPH", "; ".join(parts))) + records.append(ContextRecord(kind="decision", id=d.id, text="; ".join(parts))) entities = sorted(entities, key=lambda e: dist.get(e.id, far)) - records.extend(("entity", e.id, "GRAPH", f"{e.name} [{e.type}]") for e in entities if not e.placeholder) + records.extend( + ContextRecord(kind="entity", id=e.id, text=f"{e.name} [{e.type}]") for e in entities if not e.placeholder + ) if rerank is not None and records: records = await rerank(records) cut = False - for kind, rid, header, payload in records: - if kind == "passage": - cut = cut or not add(payload, passage_cap, kind, header=header) - elif not add(payload, budget_tokens, kind, rid, header): + for record in records: + if record.kind == "passage": + cut = cut or not add(record, passage_cap) + elif not add(record, budget_tokens): break - return "\n".join(lines) if lines or not first else _truncate(first[0], budget_tokens) + prompt = "\n".join(lines) if lines or not first else _truncate(first[0], budget_tokens) + return prompt, selected def _truncate(text: str, budget: int) -> str: @@ -1338,6 +1336,7 @@ async def retrieve( skip_hubs: bool = False, numbered: int = 0, rerank: str = "off", + context_format: ContextFormat | ContextRenderer = "prompt", ) -> RetrievalResult: """Retrieve graph context for a query via keyword seeds, or from given entities, and bounded traversal. @@ -1370,6 +1369,7 @@ async def retrieve( @param numbered (int): the number of the first context record, numbering each one and listing it in evidence, or 0 to leave the context unnumbered. @param rerank (str): the reranking tier: "off", "lexical", "embeddings", or "custom" for the graph's reranker. + @param context_format (ContextFormat | ContextRenderer): a named or caller-supplied renderer. @return (RetrievalResult): the seeds, the collected subgraph, the assembled context, and the hubs reached. """ strategy = strategy.lower() @@ -1441,9 +1441,8 @@ def refs_of(d: DecisionTrace) -> list[str]: preferences = [p for p in preferences if p.subject_entity in names and p.value_entity in names] hubs = {h for h in hubs if h in dist} marked = hubs - set(seed_ids) - evidence: list[ContextEvidence] | None = [] if numbered else None order = None if rerank == "off" else partial(_rerank, graph, rerank, topic) - context = await _assemble( + prompt, records = await _assemble( passages, entities, relations, @@ -1453,13 +1452,16 @@ def refs_of(d: DecisionTrace) -> list[str]: dist, budget_tokens, marked, - evidence, numbered, order, ) - for record in evidence or (): - if record.kind == "passage": - record.id = passages[record.text] + evidence = ( + [ContextEvidence(n=r.n, kind=r.kind, id=r.id, text=r.text) for r in records if r.n is not None] + if numbered + else None + ) + subgraph = Subgraph(entities=entities, relations=relations, preferences=preferences, decisions=decisions) + context = render_context(context_format, ContextData(subgraph=subgraph, records=records), prompt) _log.debug( "retrieve %r: %d seeds, %d entities, %d relations, %d passages", @@ -1473,11 +1475,12 @@ def refs_of(d: DecisionTrace) -> list[str]: query=query or "", strategy=strategy, seeds=[RetrievalSeed(id=e.id, score=s) for e, s in seeds_scored], - subgraph=Subgraph(entities=entities, relations=relations, preferences=preferences, decisions=decisions), + subgraph=subgraph, context=context, tiers={"seeds": seed_tier, "traversal": strategy, "rerank": rerank}, hubs=sorted(hubs), evidence=evidence, + context_records=records, ) diff --git a/tests/test_context_formats.py b/tests/test_context_formats.py new file mode 100644 index 00000000..da45c667 --- /dev/null +++ b/tests/test_context_formats.py @@ -0,0 +1,74 @@ +import json + +import pytest +from helpers import fresh_graph, kuzu_main, mcp_session, run + +from selfgraph import ValidationError + + +def test_context_formats_share_records_and_trust_labels(): + graph = fresh_graph("context-formats") + names = ["Ada", *(f"Leaf {i}" for i in range(49))] + run( + graph.insert.facts( + { + "entities": [{"type": "Thing", "name": n} for n in ["Hub", *names]], + "relations": [ + { + "id": f"relation:has-{i}", + "from_entity": "thing:hub", + "type": "HAS", + "to_entity": f"thing:{n.lower()}", + } + for i, n in enumerate(names) + ], + } + ) + ) + relation_id = "relation:has-0" + run(graph.relations.certify(relation_id, by="reviewer")) + + def retrieve(**options): + return run(graph.retrieve(entity_ids=["thing:ada"], depth=1, skip_hubs=True, numbered=3, **options)) + + prompt = retrieve() + assert ( + prompt.context + == "GRAPH [certified] (via hub) #3 | Hub -[HAS]-> Ada\nGRAPH #4 | Ada [Thing]\nGRAPH #5 | Hub [Thing]" + ) + assert retrieve(context_format="prompt").context == prompt.context + assert retrieve(context_format="compact").context == " || ".join(prompt.context.splitlines()) + assert retrieve(context_format="markdown").context == "\n".join( + f"- ` {line} `" for line in prompt.context.splitlines() + ) + + structured = retrieve(context_format="json") + records = json.loads(structured.context) + assert records == [r.model_dump() for r in structured.context_records] + assert structured.context_records == prompt.context_records + assert structured.evidence == prompt.evidence + assert records[0] == { + "kind": "relation", + "id": relation_id, + "text": "Hub -[HAS]-> Ada", + "labels": ["certified", "via_hub"], + "n": 3, + } + assert retrieve( + context_format=lambda data: f"{data.subgraph.relations[0].id}:{','.join(data.records[0].labels)}" + ).context == (f"{relation_id}:certified,via_hub") + assert json.loads(retrieve(context_format="json", budget_tokens=1).context) == [] + + +def test_context_format_cli_mcp_and_validation(tmp_path, capsys): + assert kuzu_main(tmp_path, "retrieve", "unknown", "--context-format", "json", "--context-only") == 0 + assert capsys.readouterr().out.strip() == "[]" + assert kuzu_main(tmp_path, "retrieve", "unknown", "--context-format", "xml") == 2 + assert "context_format must be one of prompt, compact, markdown, json or a renderer" in capsys.readouterr().err + with mcp_session("context-formats") as srv: + assert run(srv.retrieve(query="unknown", context_format="json"))["context"] == "[]" + graph = fresh_graph("context-format-validation") + for format in ("xml", lambda _: 42): + with pytest.raises(ValidationError) as exc: + run(graph.retrieve("unknown", context_format=format)) + assert exc.value.field == "context_format" diff --git a/tests/test_retrieve.py b/tests/test_retrieve.py index f59727af..66838771 100644 --- a/tests/test_retrieve.py +++ b/tests/test_retrieve.py @@ -559,7 +559,9 @@ def _budget_entity(name, index=0): def _budget_context(*, passages=(), entities=(), relations=(), names=None, budget=200000): - return run(_assemble(list(passages), list(entities), list(relations), [], [], names or {}, {}, budget)) + return run( + _assemble(dict.fromkeys(passages, ""), list(entities), list(relations), [], [], names or {}, {}, budget) + )[0] @pytest.mark.parametrize("names", [("A", "B", "C"), ("😀", "🚀", "🦉")]) diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index f581b595..bb297811 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -14,6 +14,7 @@ import { checkCitations } from "./citations.js"; import { SelfGraph } from "./client.js"; import { SKIPPED_NAMES } from "./code/files.js"; import { remoteName } from "./code/remote.js"; +import { CONTEXT_FORMATS, type ContextFormat } from "./context.js"; import { DIAGRAM_FORMATS, type DiagramFormat, neighborsDot, neighborsMermaid } from "./diagram.js"; import { diffTimeline, diffTimelineView } from "./diff.js"; import { internalError, NotFoundError, SelfGraphError, surfaceHint, ValidationError, WARNING_HINTS } from "./errors.js"; @@ -1506,6 +1507,7 @@ export function buildParser(): Command<[], GlobalOptions> { .option("--as-of ", `read the graph as of this time (${ISO})`, timeArg("as_of")) .option("--known-at ", `read only what the graph held at this time (${ISO})`, timeArg("known_at")) .option("--skip-hubs", "do not walk through entities with 50 or more relations") + .option("--context-format ", `context format: ${CONTEXT_FORMATS.join(", ")}`, "prompt") .option("--context-only", "print only the context text, not the JSON result") .option("--numbered", "number each context record and list them in evidence") .action((words, o, cmd) => @@ -1523,6 +1525,7 @@ export function buildParser(): Command<[], GlobalOptions> { skip_hubs: o.skipHubs === true, numbered: o.numbered === true, rerank: o.rerank, + context_format: o.contextFormat as ContextFormat, }); return o.contextOnly ? new Text(result.context) : result; }), diff --git a/typescript/src/client.ts b/typescript/src/client.ts index 47302c13..58601cfb 100644 --- a/typescript/src/client.ts +++ b/typescript/src/client.ts @@ -366,7 +366,7 @@ export class SelfGraph { * See also search for ranked hits without context, and neighbors for a filtered walk from one entity. * * @param query (string | null): the natural-language query to seed from; null to start from options.entity_ids. - * @param options (RetrieveOptions): entity_ids (the entities to start from instead of a query, each a seed at score 1 kept in seeds whatever k is; canonicalized as neighbors does, and a missing one throws NotFoundError), strategy ("bfs", "dfs", or "ppr"; the level's by default), seeds ("bm25", "synonyms" to also expand schema synonyms, or "embeddings" to fuse embedder similarity with BM25; the graph's tier by default), depth, k, max_nodes, budget_tokens, and as_of (read on the valid-time axis: relations and preferences valid then, with their entities), known_at (read only what the graph held at that time; alone, it also sets as_of), skip_hubs (do not walk through hubs, entities with at least 50 relations, other than seeds), numbered (true to number each context record in its header ("#n") and list it in evidence, or a whole number to start the numbering from), and rerank ("off", "lexical" for BM25, or "embeddings" for embedder similarity, reordering the context records before the budget and the numbering; the graph's tier by default). + * @param options (RetrieveOptions): entity_ids (the entities to start from instead of a query, each a seed at score 1 kept in seeds whatever k is; canonicalized as neighbors does, and a missing one throws NotFoundError), strategy ("bfs", "dfs", or "ppr"; the level's by default), seeds ("bm25", "synonyms" to also expand schema synonyms, or "embeddings" to fuse embedder similarity with BM25; the graph's tier by default), depth, k, max_nodes, budget_tokens, and as_of (read on the valid-time axis: relations and preferences valid then, with their entities), known_at (read only what the graph held at that time; alone, it also sets as_of), skip_hubs (do not walk through hubs, entities with at least 50 relations, other than seeds), numbered (true to number each context record in its header ("#n") and list it in evidence, or a whole number to start the numbering from), and rerank ("off", "lexical" for BM25, or "embeddings" for embedder similarity, reordering the context records before the budget and the numbering; the graph's tier by default). The context_format option selects a named or caller-supplied renderer. * @return (RetrievalResult): the seeds, the collected subgraph, the assembled context, and the hubs reached. */ async retrieve(query: string | null = null, options: RetrieveOptions = {}): Promise { diff --git a/typescript/src/context.ts b/typescript/src/context.ts new file mode 100644 index 00000000..379e71c9 --- /dev/null +++ b/typescript/src/context.ts @@ -0,0 +1,56 @@ +import { ValidationError } from "./errors.js"; +import { contextPayload } from "./internal/payload.js"; +import type { ContextData, ContextLabel, ContextRecord } from "./models.js"; + +export const CONTEXT_FORMATS = ["prompt", "compact", "markdown", "json"] as const; +export type ContextFormat = (typeof CONTEXT_FORMATS)[number]; +export type ContextRenderer = (data: ContextData) => string; + +const MARKERS: Record = { certified: " [certified]", via_hub: " (via hub)" }; + +/** Check the context selector. @param value (unknown): format name or renderer. @return (void): throws on invalid input. */ +export function validateContextFormat(value: unknown): void { + if (typeof value !== "function" && !CONTEXT_FORMATS.some((name) => name === value)) { + throw new ValidationError(`context_format must be one of ${CONTEXT_FORMATS.join(", ")} or a renderer`, { + field: "context_format", + }); + } +} + +/** Render a prompt record. @param record (ContextRecord): source or graph record. @param n (number | null): citation number. @param multiline (boolean): retain source line boundaries. @return (string): framed text. */ +export function promptLine(record: ContextRecord, n: number | null, multiline = true): string { + let header = record.kind === "passage" ? "SOURCE" : "GRAPH"; + header += record.labels.map((label) => MARKERS[label]).join(""); + if (n !== null) header += ` #${n}`; + if (record.kind === "passage" && multiline) return contextPayload(record.text, header); + return `${header} | ${contextPayload(record.text)}`; +} + +function markdownLine(record: ContextRecord): string { + const text = promptLine(record, record.n, false); + let width = 1; + for (const [run] of text.matchAll(/`+/g)) width = Math.max(width, run.length + 1); + const fence = "`".repeat(width); + return `- ${fence} ${text} ${fence}`; +} + +/** Render admitted context. @param format (ContextFormat | ContextRenderer): chosen renderer. @param data (ContextData): subgraph and admitted records. @param prompt (string): cached budgeted prompt text. @return (string): rendered context. */ +export function renderContext(format: ContextFormat | ContextRenderer, data: ContextData, prompt: string): string { + switch (format) { + case "prompt": + return prompt; + case "compact": + return data.records.map((record) => promptLine(record, record.n, false).replaceAll("||", "\\|\\|")).join(" || "); + case "markdown": + return data.records.map(markdownLine).join("\n"); + case "json": + return JSON.stringify(data.records); + default: { + const rendered = format(data); + if (typeof rendered !== "string") { + throw new ValidationError("context renderer must return a string", { field: "context_format" }); + } + return rendered; + } + } +} diff --git a/typescript/src/index.ts b/typescript/src/index.ts index d155e325..03db7ea1 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -19,6 +19,7 @@ export { type SuggestSchemaOptions, } from "./client.js"; export type { Code, CodeIndexOptions } from "./code/index.js"; +export type { ContextFormat, ContextRenderer } from "./context.js"; export { neighborsDot, neighborsMermaid } from "./diagram.js"; export { diffTimeline } from "./diff.js"; export { @@ -52,7 +53,10 @@ export { type CodeLimits, type CodeNotice, type CodeSkip, + type ContextData, type ContextEvidence, + type ContextLabel, + type ContextRecord, type CypherResult, type CypherRow, DateTimeInput, diff --git a/typescript/src/mcp.ts b/typescript/src/mcp.ts index 42739da3..dd2d0477 100644 --- a/typescript/src/mcp.ts +++ b/typescript/src/mcp.ts @@ -7,6 +7,7 @@ import { z } from "zod"; import { CHUNKINGS } from "./chunking.js"; import { checkCitations } from "./citations.js"; import { buildGraph, SelfGraph } from "./client.js"; +import type { ContextFormat } from "./context.js"; import { diffTimelineView } from "./diff.js"; import { internalError, SelfGraphError, surfaceHint, ValidationError, WARNING_HINTS } from "./errors.js"; import { toOssie } from "./export.js"; @@ -913,6 +914,7 @@ export const TOOLS: Tool[] = [ "records by relevance before the budget, default to the server's level. hubs lists entities with 50 or more " + "relations the walk reached; context lines through one are marked (via hub), as weak links. skip_hubs stops the " + "walk at hubs. Pass entity_ids (from find_entities) instead of query to start from those entities as the seeds. " + + "context_format can be prompt (default), compact, markdown, or json. " + "numbered numbers each context record in its header (GRAPH #3 | ...) and lists it in evidence as {n, kind, id, " + "text}, continuing from the last number of this session, so cite records as [n] and check with check_citations.", input: { @@ -929,6 +931,7 @@ export const TOOLS: Tool[] = [ skip_hubs: z.boolean().default(false), numbered: z.boolean().default(false), rerank: optStr, + context_format: z.string().default("prompt"), }, run: async (g, a) => { const result = await g.retrieve(a.query ?? null, { @@ -944,6 +947,7 @@ export const TOOLS: Tool[] = [ seeds: a.seeds as SeedTier | null | undefined, numbered: a.numbered ? heldEvidence().length + 1 : false, rerank: a.rerank as RerankTier | null | undefined, + context_format: a.context_format as ContextFormat, }); heldEvidence().push(...(result.evidence ?? [])); return result; diff --git a/typescript/src/models.ts b/typescript/src/models.ts index 9c68abcb..caea21e8 100644 --- a/typescript/src/models.ts +++ b/typescript/src/models.ts @@ -710,6 +710,21 @@ export interface ContextEvidence { text: string; } +export type ContextLabel = "certified" | "via_hub"; + +export interface ContextRecord { + kind: ContextEvidence["kind"]; + id: string; + text: string; + labels: ContextLabel[]; + n: number | null; +} + +export interface ContextData { + subgraph: Subgraph; + records: ContextRecord[]; +} + export interface RetrievalResult { query: string; strategy: string; @@ -719,6 +734,7 @@ export interface RetrievalResult { tiers: Record; hubs: string[]; evidence?: ContextEvidence[]; + context_records: ContextRecord[]; } export interface UnsupportedSentence { diff --git a/typescript/src/retrieval.ts b/typescript/src/retrieval.ts index 679b20af..01cd7447 100644 --- a/typescript/src/retrieval.ts +++ b/typescript/src/retrieval.ts @@ -1,10 +1,16 @@ import { type GraphAccess, rerankTier, seedTier } from "./access.js"; import { loadTokenizer } from "./chunking.js"; +import { + type ContextFormat, + type ContextRenderer, + promptLine, + renderContext, + validateContextFormat, +} from "./context.js"; import { NotFoundError, ValidationError } from "./errors.js"; import { canonicalEntityId, contentHash, normalizeRelType, normalizeText, profileId, wordRuns } from "./ids.js"; import { casefold } from "./internal/casefold.js"; import { loads } from "./internal/json.js"; -import { contextPayload } from "./internal/payload.js"; import { comparePy, cpLen, NON_ASCII, pyFloatRepr, pyRepr, pyStrip } from "./internal/py.js"; import { epochMicros, fromIso } from "./internal/time.js"; import { WORD_CLASS } from "./internal/unicode.js"; @@ -20,7 +26,8 @@ import { import { scanEntities, scanRelations } from "./maintenance.js"; import type { AnswerabilityReport, - ContextEvidence, + ContextLabel, + ContextRecord, DateTimeInput, DecisionTrace, Entity, @@ -1173,8 +1180,6 @@ function displayName(e: Entity): string { return e.placeholder ? e.id : e.name; } -type ContextLine = [kind: ContextEvidence["kind"], id: string, header: string, text: string]; - /** * Score texts by relevance to the query with a reranking tier. * @@ -1219,24 +1224,24 @@ async function rerankScores(graph: GraphAccess, tier: string, query: string, tex * @param graph (GraphAccess): the graph, with its embedder or reranker. * @param tier (string): "lexical", "embeddings", or "custom". * @param query (string): the query, or the seed entities' names and aliases. - * @param records (ContextLine[]): each record's kind, id, header, and text, passages first. - * @return (ContextLine[]): the records, passages still first, best first, ties in their given order. + * @param records (ContextRecord[]): the candidate context records, passages first. + * @return (ContextRecord[]): the records, passages still first, best first, ties in their given order. */ async function rerankRecords( graph: GraphAccess, tier: string, query: string, - records: ContextLine[], -): Promise { - const texts = records.map(([, , , text]) => text); + records: ContextRecord[], +): Promise { + const texts = records.map((record) => record.text); const scores = await rerankScores(graph, tier, query, texts); - const section = (i: number): number => (records[i]![0] === "passage" ? 0 : 1); + const section = (i: number): number => (records[i]!.kind === "passage" ? 0 : 1); const order = records.map((_, i) => i).sort((a, b) => section(a) - section(b) || scores[b]! - scores[a]!); return order.map((i) => records[i]!); } /** - * Fill the token budget with passages, then relations, preferences, decisions, and entities, nearest first. + * Select ordered context records under the prompt token budget. * * @param passages (Iterable): the ranked source passages. * @param subgraph (Subgraph): the collected entities, relations, preferences, and decisions. @@ -1244,36 +1249,34 @@ async function rerankRecords( * @param dist (Map): entity id to hop distance from the seeds. * @param budgetTokens (number): the token budget; the first line that does not fit ends the context, and a first line that does not fit is cut to the budget. * @param countTokens ((text: string) => number): the token counter. - * @param hubs (ReadonlySet): hub entity ids; a relation line through one is marked "(via hub)". - * @param evidence (ContextEvidence[] | null): when given, number each record that fits in its header ("#n") and append it here; a passage's id is left empty for the caller to fill. - * @param start (number): the number of the first record. - * @param rerank (((records: ContextLine[]) => Promise) | null): reorders the records, as [kind, id, header, text], before the budget and the numbering; null keeps them. - * @return (string): the context text. Certified relations come first among equally close ones and are marked "[certified]". A placeholder gets no line of its own. + * @param hubs (ReadonlySet): non-seed hub entity ids to mark on relations. + * @param start (number): the first citation number, or 0 to leave the records unnumbered. + * @param rerank (((records: ContextRecord[]) => Promise) | null): reorders the records before the budget and numbering. + * @return ([string, ContextRecord[]]): the budgeted prompt and its complete records. */ async function assemble( - passages: Iterable, + passages: ReadonlyMap, subgraph: Subgraph, names: Map, dist: Map, budgetTokens: number, countTokens: (text: string) => number, - hubs: ReadonlySet = new Set(), - evidence: ContextEvidence[] | null = null, - start = 1, - rerank: ((records: ContextLine[]) => Promise) | null = null, -): Promise { + hubs: ReadonlySet, + start: number, + rerank: ((records: ContextRecord[]) => Promise) | null, +): Promise<[string, ContextRecord[]]> { const { entities, relations, preferences, decisions } = subgraph; const nameOf = (id: string): string => names.get(id) ?? id; const lines: string[] = []; + const selected: ContextRecord[] = []; let first: string | null = null; let used = 0; let rounding = 0; let boundary = 0; let full = false; - const add = (payload: string, cap: number, kind: ContextEvidence["kind"], id = "", header = "GRAPH"): boolean => { - const n = evidence === null ? null : start + evidence.length; - if (n !== null) header += ` #${n}`; - const line = kind === "passage" ? contextPayload(payload, header) : `${header} | ${contextPayload(payload)}`; + const add = (record: ContextRecord, cap: number): boolean => { + const n = start ? start + selected.length : null; + const line = promptLine(record, n); if (first === null) { first = line; rounding = countTokens(""); @@ -1286,7 +1289,8 @@ async function assemble( return false; } lines.push(line); - if (evidence !== null && n !== null) evidence.push({ n, kind, id, text: payload }); + record.n = n; + selected.push(record); used += cost; const delta = countTokens(`${line}\n`) - plain; boundary = rounding ? Math.max(rounding, delta) : delta; @@ -1294,7 +1298,13 @@ async function assemble( }; const passageCap = Math.floor((budgetTokens * PASSAGE_BUDGET_PERCENT) / 100); - let records: ContextLine[] = [...passages].map((p) => ["passage", "", "SOURCE", p]); + const record = ( + kind: ContextRecord["kind"], + id: string, + text: string, + labels: ContextLabel[] = [], + ): ContextRecord => ({ kind, id, text, labels, n: null }); + let records = Array.from(passages, ([text, id]) => record("passage", id, text)); const distOf = distanceIn(dist); const relRank = (r: Relation): [number, number, number, number] => { @@ -1311,17 +1321,17 @@ async function assemble( let line = `${nameOf(r.from_entity)} -[${r.type}]-> ${nameOf(r.to_entity)}`; const props = formatProps(r.properties); if (props) line += ` ${props}`; - let header = "GRAPH"; - if (r.certified_at !== null) header += " [certified]"; - if (hubs.has(r.from_entity) || hubs.has(r.to_entity)) header += " (via hub)"; - records.push(["relation", r.id, header, line]); + const labels: ContextLabel[] = []; + if (r.certified_at !== null) labels.push("certified"); + if (hubs.has(r.from_entity) || hubs.has(r.to_entity)) labels.push("via_hub"); + records.push(record("relation", r.id, line, labels)); } for (const p of [...preferences].sort((a, b) => distOf(a.subject_entity) - distOf(b.subject_entity))) { const verb = preferenceEdgeType(p.stance).toLowerCase(); let line = `${nameOf(p.subject_entity)} ${verb} ${nameOf(p.value_entity)} (${p.key})`; if (p.strength !== null) line += ` [strength ${pyFloatRepr(p.strength)}]`; - records.push(["preference", p.id, "GRAPH", line]); + records.push(record("preference", p.id, line)); } for (const d of decisions) { @@ -1329,20 +1339,21 @@ async function assemble( if (d.outcome_entity) parts.push(`outcome ${nameOf(d.outcome_entity)}`); if (d.alternative_entities.length) parts.push(`alternatives ${d.alternative_entities.map(nameOf).join(", ")}`); if (d.rationale) parts.push(`rationale ${d.rationale}`); - records.push(["decision", d.id, "GRAPH", parts.join("; ")]); + records.push(record("decision", d.id, parts.join("; "))); } for (const e of [...entities].sort((a, b) => distOf(a.id) - distOf(b.id))) { - if (!e.placeholder) records.push(["entity", e.id, "GRAPH", `${e.name} [${e.type}]`]); + if (!e.placeholder) records.push(record("entity", e.id, `${e.name} [${e.type}]`)); } if (rerank !== null && records.length) records = await rerank(records); let cut = false; - for (const [kind, rid, header, payload] of records) { - if (kind === "passage") cut = cut || !add(payload, passageCap, kind, rid, header); - else if (!add(payload, budgetTokens, kind, rid, header)) break; + for (const item of records) { + if (item.kind === "passage") cut = cut || !add(item, passageCap); + else if (!add(item, budgetTokens)) break; } - return lines.length || first === null ? lines.join("\n") : truncate(first, budgetTokens, countTokens); + const prompt = lines.length || first === null ? lines.join("\n") : truncate(first, budgetTokens, countTokens); + return [prompt, selected]; } /** @@ -1380,6 +1391,7 @@ export interface RetrieveOptions { skip_hubs?: boolean; numbered?: boolean | number; rerank?: RerankTier | null; + context_format?: ContextFormat | ContextRenderer; } const RETRIEVE_KEYS = keysOf({ @@ -1395,6 +1407,7 @@ const RETRIEVE_KEYS = keysOf({ skip_hubs: true, numbered: true, rerank: true, + context_format: true, }); /** @@ -1462,7 +1475,15 @@ export async function retrieve( if (value < least) throw new ValidationError(`${name} must be >= ${least}, got ${value}`, { field: name }); } const opts = { entityIds, strategy, depth, k, maxNodes, budgetTokens, asOf, seeds, skipHubs, numbered, rerank }; - return graph.read((store, ns) => run(graph, store, ns, query, opts)); + const { context_format: format = "prompt" } = options; + validateContextFormat(format); + const result = await graph.read((store, ns) => run(graph, store, ns, query, opts)); + result.context = renderContext( + format, + { subgraph: result.subgraph, records: result.context_records }, + result.context, + ); + return result; } interface RunOptions { @@ -1606,21 +1627,19 @@ async function run( hubs = new Set([...hubs].filter((h) => dist.has(h))); const seedSet = new Set(seedIds); const marked = new Set([...hubs].filter((h) => !seedSet.has(h))); - const cited: ContextEvidence[] | null = numbered ? [] : null; - const order = rerank === "off" ? null : (records: ContextLine[]) => rerankRecords(graph, rerank, topic, records); - const context = await assemble( - passages.keys(), + const order = rerank === "off" ? null : (records: ContextRecord[]) => rerankRecords(graph, rerank, topic, records); + const [context, records] = await assemble( + passages, subgraph, names, dist, budgetTokens, countTokens, marked, - cited, numbered, order, ); - for (const record of cited ?? []) if (record.kind === "passage") record.id = passages.get(record.text)!; + const evidence = records.flatMap(({ n, kind, id, text }) => (n === null ? [] : [{ n, kind, id, text }])); return { query: query ?? "", @@ -1630,7 +1649,8 @@ async function run( context, tiers: { seeds: seeded, traversal: strategy, rerank }, hubs: [...hubs].sort(comparePy), - ...(cited === null ? {} : { evidence: cited }), + context_records: records, + ...(numbered ? { evidence } : {}), }; } diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 8507b764..bc4ac3fa 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -3741,8 +3741,16 @@ async def extract(self, document): assert sum(line.startswith("GRAPH [certified] | ") for line in result.context.splitlines()) == 1 assert stored.properties == props assert result.subgraph.relations[0].properties == props + rendered = {} + for format in ("prompt", "compact", "markdown", "json"): + alternate = await g.retrieve("Ann Acme", budget_tokens=4000, numbered=4, context_format=format) + rendered[format] = to_jsonable([alternate.context, alternate.context_records, alternate.evidence]) + custom = await g.retrieve("Ann Acme", context_format=lambda data: ",".join(data.records[1].labels)) return { "context": result.context, + "rendered": rendered, + "custom": custom.context, + "invalid_format": await error_of(g.retrieve("Ann Acme", context_format="xml")), "budgets": [(await g.retrieve("Ann Acme", budget_tokens=b)).context for b in (1, 7, 12, 21, 50, 100)], "stored": stored.properties, "structured": result.subgraph.relations[0].properties, diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 156079be..419cd1c3 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -3767,8 +3767,17 @@ async function contextBoundary(graph: SelfGraph): Promise { for (const budget of [1, 7, 12, 21, 50, 100]) { budgets.push((await g.retrieve("Ann Acme", { budget_tokens: budget })).context); } + const rendered: Record = {}; + for (const format of ["prompt", "compact", "markdown", "json"] as const) { + const alternate = await g.retrieve("Ann Acme", { budget_tokens: 4000, numbered: 4, context_format: format }); + rendered[format] = [alternate.context, alternate.context_records, alternate.evidence]; + } + const custom = await g.retrieve("Ann Acme", { context_format: ({ records }) => records[1]!.labels.join(",") }); return { context: result.context, + rendered, + custom: custom.context, + invalid_format: await errorOf(() => g.retrieve("Ann Acme", { context_format: "xml" as never })), budgets, stored: stored!.properties, structured: result.subgraph.relations[0]!.properties, diff --git a/typescript/test/contextFormats.test.ts b/typescript/test/contextFormats.test.ts new file mode 100644 index 00000000..c6e8411d --- /dev/null +++ b/typescript/test/contextFormats.test.ts @@ -0,0 +1,82 @@ +import { join } from "node:path"; +import { afterAll, beforeAll, expect, it } from "vitest"; +import { DEFAULT_SETTINGS, type RetrieveOptions } from "../src/index.js"; +import { callTool, close, configure } from "../src/mcp.js"; +import { buildCli, forEachStore, freshGraphs, runCli, tempDir, tempKuzu } from "./helpers.js"; + +await forEachStore("context formats", (spec) => { + const open = freshGraphs(spec, "context_formats"); + it("renders the same records and trust labels in every format", async () => { + const graph = open(); + const names = ["Ada", ...Array.from({ length: 49 }, (_, i) => `Leaf ${i}`)]; + await graph.insert.facts({ + entities: ["Hub", ...names].map((name) => ({ type: "Thing", name })), + relations: names.map((name, i) => ({ + id: `relation:has-${i}`, + from_entity: "thing:hub", + type: "HAS", + to_entity: `thing:${name.toLowerCase()}`, + })), + }); + const relationId = "relation:has-0"; + await graph.relations.certify(relationId, { by: "reviewer" }); + const retrieve = (options: RetrieveOptions = {}) => + graph.retrieve(null, { entity_ids: ["thing:ada"], depth: 1, skip_hubs: true, numbered: 3, ...options }); + + const prompt = await retrieve(); + expect(prompt.context).toBe( + "GRAPH [certified] (via hub) #3 | Hub -[HAS]-> Ada\nGRAPH #4 | Ada [Thing]\nGRAPH #5 | Hub [Thing]", + ); + expect((await retrieve({ context_format: "prompt" })).context).toBe(prompt.context); + expect((await retrieve({ context_format: "compact" })).context).toBe(prompt.context.split("\n").join(" || ")); + expect((await retrieve({ context_format: "markdown" })).context).toBe( + prompt.context + .split("\n") + .map((line) => `- \` ${line} \``) + .join("\n"), + ); + + const structured = await retrieve({ context_format: "json" }); + const records = JSON.parse(structured.context); + expect(records).toEqual(structured.context_records); + expect(structured.context_records).toEqual(prompt.context_records); + expect(structured.evidence).toEqual(prompt.evidence); + expect(records[0]).toEqual({ + kind: "relation", + id: relationId, + text: "Hub -[HAS]-> Ada", + labels: ["certified", "via_hub"], + n: 3, + }); + expect( + ( + await retrieve({ + context_format: ({ subgraph, records }) => `${subgraph.relations[0]!.id}:${records[0]!.labels.join(",")}`, + }) + ).context, + ).toBe(`${relationId}:certified,via_hub`); + expect(JSON.parse((await retrieve({ context_format: "json", budget_tokens: 1 })).context)).toEqual([]); + for (const format of ["xml", () => 42]) { + await expect(retrieve({ context_format: format as never })).rejects.toMatchObject({ field: "context_format" }); + } + }); +}); + +beforeAll(buildCli); +afterAll(close); + +it("selects the context format through the CLI and MCP", async () => { + const file = join(tempDir("sg-context-cli-"), "graph.kuzu"); + const cli = (args: string[]) => + runCli(["--store", "kuzu", "--uri", file, "retrieve", "unknown", ...args], { + env: { SELFGRAPH_STORE: "", SELFGRAPH_URI: undefined }, + }); + expect(cli(["--context-format", "json", "--context-only"])).toMatchObject({ code: 0, out: [] }); + expect(cli(["--context-format", "xml"])).toMatchObject({ + code: 2, + err: expect.stringContaining("context_format must be one of prompt, compact, markdown, json or a renderer"), + }); + await configure({ ...DEFAULT_SETTINGS, store: "kuzu", uri: tempKuzu("sg-context-mcp-"), namespace: "context_mcp" }); + const found = await callTool("retrieve", { query: "unknown", context_format: "json" }); + expect(found).toMatchObject({ isError: false, result: { context: "[]" } }); +});