From 22fc52eea1c13d4857a3027faff8de6a846d6ca5 Mon Sep 17 00:00:00 2001 From: ivarunchaudhary Date: Fri, 4 Dec 2026 20:55:00 +0530 Subject: [PATCH] Add retrieval context renderers --- docs/cli.md | 1 + docs/mcp.md | 2 +- docs/retrieval.md | 30 ++++++++- src/selfgraph/__init__.py | 6 ++ src/selfgraph/cli.py | 4 +- src/selfgraph/client.py | 9 ++- src/selfgraph/mcp/server.py | 3 + src/selfgraph/models.py | 25 +++++++- src/selfgraph/retrieval.py | 82 +++++++++++++++++++++++- tests/test_retrieve.py | 51 +++++++++++++++ typescript/src/cli.ts | 7 +++ typescript/src/index.ts | 3 + typescript/src/mcp.ts | 4 ++ typescript/src/models.ts | 13 +++- typescript/src/retrieval.ts | 86 +++++++++++++++++++++++++- typescript/test/conformance/py_side.py | 10 +++ typescript/test/conformance/ts_side.ts | 10 +++ 17 files changed, 333 insertions(+), 13 deletions(-) diff --git a/docs/cli.md b/docs/cli.md index 5d4358aa..7124f86c 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -142,6 +142,7 @@ than one, and pass no query with it. See [Retrieval](retrieval.md) and | `--known-at` | | Read only what the graph held at this time. See [As the graph knew it](retrieval.md#as-the-graph-knew-it). | | `--skip-hubs` | | Do not walk through [hubs](trust.md#hubs). | | `--context-only` | | Print just the context text instead of the JSON result. | +| `--context-format FORMAT` | | Render context as `prompt`, `compact`, `markdown`, or `json`. | | `--numbered` | | Number each context record and list it in `evidence`. See [citing the context](retrieval.md#citing-the-context). | ### `search` diff --git a/docs/mcp.md b/docs/mcp.md index c1991429..a1f520c0 100644 --- a/docs/mcp.md +++ b/docs/mcp.md @@ -211,7 +211,7 @@ default 50) and `[cursor]`. | `update_decision` | `id`, `[title]`, `[steps]`, `[actor_entity]`, `[summary]`, `[rationale]`, `[outcome_entity]`, `[alternative_entities]`, `[status]`, `[event_time]`, `[clear]` | | `list_decisions` | `[actor_entity]`, `[status]` | | `get_decision`, `delete_decision` | `id` | -| `retrieve` | `[query]` or `[entity_ids]` (one of them; see [from entity ids](retrieval.md#from-entity-ids)), `[strategy]`, `[depth]`, `[k]`, `[max_nodes]`, `[budget_tokens]`, `[as_of]`, `[known_at]`, `[seeds]`, `[skip_hubs]`, `[numbered]` ([citations](#citations)), `[rerank]` | +| `retrieve` | `[query]` or `[entity_ids]` (one of them; see [from entity ids](retrieval.md#from-entity-ids)), `[strategy]`, `[depth]`, `[k]`, `[max_nodes]`, `[budget_tokens]`, `[as_of]`, `[known_at]`, `[seeds]`, `[skip_hubs]`, `[numbered]` ([citations](#citations)), `[context_format]` ([formats](retrieval.md#context-format)), `[rerank]` | | `check_citations` | `answer` ([citations](#citations)) | | `search` | `query`, `[types]`, `[kinds]` (`entity`, `passage`), `[k]` (default 20), `[seeds]`, `[rerank]`, `[as_of]`, `[known_at]` ([search](retrieval.md#search)) | | `neighbors` | `entity_id`, `[depth]` (1 to 4, default 1), `[direction]` (`out`, `in`, or `both`), `[types]`, `[limit]` (default 100), `[as_of]`, `[known_at]` ([navigating](retrieval.md#navigating-the-graph)) | diff --git a/docs/retrieval.md b/docs/retrieval.md index 29be7acb..3a3bc3f8 100644 --- a/docs/retrieval.md +++ b/docs/retrieval.md @@ -13,9 +13,10 @@ 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` | In the default prompt format, source passages (`SOURCE \| ...`), then graph records: relations, preferences, decisions, and entities (`GRAPH \| Acme [Company]`). SDK-built graph headers carry [certification](trust.md#certification) and [hub](trust.md#hubs) metadata; see the format below. | | `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). | +| `context_records` | With an alternate or custom renderer, the complete records chosen for context, with their IDs, numbers, text, and trust labels. | Passages come only from `insert.text` calls made with a `source_id`. A graph built with `insert.facts` returns relation and entity lines but no passages. @@ -28,6 +29,33 @@ instead of a query, see [Navigating the graph](#navigating-the-graph). ## Context format +Choose `context_format` in either SDK, `--context-format` in the CLI, or +`context_format` on the MCP tool. The named formats are: + +| Format | Output | +|--------|--------| +| `prompt` (default) | The source and graph headers described below. | +| `compact` | One line for logs, with records separated by ` || `. | +| `markdown` | A list with one item per record and literal markup escaped. | +| `json` | A JSON array equal to `context_records`. | + +For example, `await graph.retrieve("Acme", context_format="json")` renders +the chosen records as JSON. In Python and TypeScript, you can also pass a +synchronous callback that receives the retrieval result and returns a string. + +Each `context_records` entry has `kind`, `id`, `text`, `n` (null without +numbering), and `labels`. Trust labels are `certified` and `via_hub`. Read the +labels from the records when rendering or processing context. Record text +can contain those words as ordinary data. + +Alternate renderers select the same complete records as the prompt format, +including its ranking and token budget. The rendered output has its own +overhead and can be longer than the prompt budget. A prompt fragment that is +too short to represent a complete record is omitted from alternate formats. +Numbered evidence refers to the same records in every format. + +### 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..db0d2a37 100644 --- a/src/selfgraph/__init__.py +++ b/src/selfgraph/__init__.py @@ -30,6 +30,9 @@ CodeNotice, CodeSkip, ContextEvidence, + ContextFormat, + ContextRecord, + ContextRenderer, CypherResult, DecayResult, DecisionStep, @@ -193,6 +196,9 @@ def __dir__() -> list[str]: "AnswerabilityReport", "TermCoverage", "ContextEvidence", + "ContextFormat", + "ContextRecord", + "ContextRenderer", "CitationReport", "UnsupportedSentence", "check_citations", diff --git a/src/selfgraph/cli.py b/src/selfgraph/cli.py index cab06d03..2b572af6 100644 --- a/src/selfgraph/cli.py +++ b/src/selfgraph/cli.py @@ -33,7 +33,7 @@ from .models import CodeLimits, SourceDiff, Stance, Status, SyncResult, TimelineEvent from .resolution import ResolverMode from .resources._common import DEFAULT_PAGE_LIMIT -from .retrieval import DIRECTIONS, KINDS, MAX_DEPTH, STRATEGIES +from .retrieval import CONTEXT_FORMATS, DIRECTIONS, KINDS, MAX_DEPTH, STRATEGIES from .runtime import ( DECISION_CLEARABLE, PREFERENCE_CLEARABLE, @@ -260,6 +260,7 @@ async def _retrieve(graph, args): seeds=args.seeds, skip_hubs=args.skip_hubs, numbered=args.numbered, + context_format=args.context_format, rerank=args.rerank, ) return _Text(result.context) if args.context_only else result @@ -933,6 +934,7 @@ def build_parser() -> argparse.ArgumentParser: 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-only", action="store_true", help="print only the context text, not the JSON result") + rt.add_argument("--context-format", choices=CONTEXT_FORMATS, default="prompt", help="rendering for context") rt.add_argument("--numbered", action="store_true", help="number each context record and list them in evidence") rt.set_defaults(func=_retrieve) cc = sub.add_parser("check-citations", help="check an answer's [n] citations against retrieve --numbered evidence") diff --git a/src/selfgraph/client.py b/src/selfgraph/client.py index 9b9ac659..0a407b69 100644 --- a/src/selfgraph/client.py +++ b/src/selfgraph/client.py @@ -37,6 +37,8 @@ from .models import ( AnswerabilityReport, CitationReport, + ContextFormat, + ContextRenderer, CypherResult, DecisionTrace, DecisionTraceInput, @@ -72,7 +74,7 @@ ) from .resources import Decisions, Entities, Maintenance, Preferences, Relations from .resources._common import page_limit -from .retrieval import KINDS, first_number, followed, require_hops +from .retrieval import KINDS, check_context_format, first_number, followed, require_hops from .retrieval import check_answerable as _check_answerable from .retrieval import find_path as _find_path from .retrieval import neighbors as _neighbors @@ -418,6 +420,7 @@ async def retrieve( seeds: tiers.SeedTier | None = None, skip_hubs: bool = False, numbered: bool | int = False, + context_format: ContextFormat | ContextRenderer = "prompt", rerank: tiers.RerankTier | None = None, **options: Any, ) -> RetrievalResult: @@ -441,6 +444,7 @@ async def retrieve( @param skip_hubs (bool): do not walk through hubs, entities with at least 50 relations, other than seeds. @param numbered (bool | int): True to number each context record in its header ("#n") and list it in evidence, or a whole number to start the numbering from. + @param context_format (ContextFormat | ContextRenderer): a named format or a custom renderer. @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. @return (RetrievalResult): the seeds, the collected subgraph, the assembled context, and the hubs reached. @@ -460,6 +464,7 @@ async def retrieve( "seeds", "skip_hubs", "numbered", + "context_format", "rerank", ], ) @@ -490,6 +495,7 @@ async def retrieve( budget_tokens = int(budget_tokens) _ops._require_bool("skip_hubs", skip_hubs) first = first_number(numbered) + check_context_format(context_format) as_of = _ops.parse_as_of(as_of, known_at) await self._ensure_ready() return await _retrieve( @@ -505,6 +511,7 @@ async def retrieve( seeds=seed_tier, skip_hubs=skip_hubs, numbered=first, + context_format=context_format, rerank=rerank_tier, ) diff --git a/src/selfgraph/mcp/server.py b/src/selfgraph/mcp/server.py index 7a2b4b4f..44cc3ddb 100644 --- a/src/selfgraph/mcp/server.py +++ b/src/selfgraph/mcp/server.py @@ -1000,6 +1000,7 @@ async def retrieve( seeds: str | None = None, skip_hubs: StrictBool = False, numbered: StrictBool = False, + context_format: str | None = None, rerank: str | None = None, ) -> dict[str, Any]: """Retrieve graph context for a query by keyword seeds and bounded BFS, DFS, or PageRank ("ppr") ranking. @@ -1009,6 +1010,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 selects prompt, 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() @@ -1024,6 +1026,7 @@ async def retrieve( known_at=known_at, seeds=seeds, skip_hubs=skip_hubs, + context_format="prompt" if context_format is None else context_format, numbered=len(_session_evidence.get(_evidence)) + 1 if numbered else False, rerank=rerank, ) diff --git a/src/selfgraph/models.py b/src/selfgraph/models.py index c469d4d7..f79fc2c2 100644 --- a/src/selfgraph/models.py +++ b/src/selfgraph/models.py @@ -69,6 +69,9 @@ "Subgraph", "RetrievalResult", "ContextEvidence", + "ContextFormat", + "ContextRecord", + "ContextRenderer", "CitationReport", "UnsupportedSentence", "SearchPassage", @@ -1115,9 +1118,21 @@ class Subgraph(BaseModel): decisions: list[DecisionTrace] = Field(default_factory=list) +ContextKind = Literal["passage", "relation", "preference", "decision", "entity"] +ContextFormat = Literal["prompt", "compact", "markdown", "json"] + + +class ContextRecord(BaseModel): + n: int | None + kind: ContextKind + id: str + text: str + labels: list[Literal["certified", "via_hub"]] = Field(default_factory=list) + + class ContextEvidence(BaseModel): n: int - kind: Literal["passage", "relation", "preference", "decision", "entity"] + kind: ContextKind id: str text: str @@ -1131,10 +1146,11 @@ 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] | None = None @model_serializer(mode="wrap") def _omit_unnumbered(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: - """Serialize the result, leaving out evidence when the context was not numbered. + """Serialize the result, omitting evidence and records when they were not requested. @param handler (SerializerFunctionWrapHandler): pydantic's default serializer. @return (dict[str, Any]): the serialized result. @@ -1142,9 +1158,14 @@ def _omit_unnumbered(self, handler: SerializerFunctionWrapHandler) -> dict[str, data = handler(self) if self.evidence is None: data.pop("evidence", None) + if self.context_records is None: + data.pop("context_records", None) return data +ContextRenderer = Callable[[RetrievalResult], str] + + class UnsupportedSentence(BaseModel): sentence: str cited: list[int] diff --git a/src/selfgraph/retrieval.py b/src/selfgraph/retrieval.py index 18358a6b..11b601cf 100644 --- a/src/selfgraph/retrieval.py +++ b/src/selfgraph/retrieval.py @@ -2,13 +2,15 @@ import asyncio import heapq +import json import logging import math import re from collections import deque from collections.abc import Awaitable, Callable, Collection, Iterable from functools import partial -from typing import TYPE_CHECKING +from string import punctuation +from typing import TYPE_CHECKING, get_args from . import _ops from ._maintenance import scan_entities, scan_relations @@ -33,6 +35,10 @@ from .models import ( AnswerabilityReport, ContextEvidence, + ContextFormat, + ContextKind, + ContextRecord, + ContextRenderer, DecisionTrace, Entity, ImpactedEntity, @@ -55,6 +61,8 @@ from .terms import definition_index, expand_tokens, grounded_terms, schema_forms, stem _log = logging.getLogger("selfgraph") +CONTEXT_FORMATS = get_args(ContextFormat) +_MARKDOWN_ENTITIES = str.maketrans({char: f"&#{ord(char)};" for char in punctuation}) if TYPE_CHECKING: from .client import SelfGraph @@ -1166,6 +1174,7 @@ async def _assemble( evidence: list[ContextEvidence] | None = None, start: int = 1, rerank: Callable[[list[tuple[str, ...]]], Awaitable[list[tuple[str, ...]]]] | None = None, + selected: list[ContextRecord] | None = None, ) -> str: """Serialise passages and the subgraph into text for an LLM, under a token budget, nearest first. @@ -1184,6 +1193,7 @@ async def _assemble( @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. + @param selected (list[ContextRecord] | None): receives complete records that fit the prompt budget. @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. """ @@ -1194,7 +1204,7 @@ async def _assemble( boundary = 0 full = False - def add(payload: str, cap: int, kind: str, rid: str = "", header: str = "GRAPH") -> bool: + def add(payload: str, cap: int, kind: ContextKind, rid: str = "", header: str = "GRAPH") -> bool: nonlocal used, full, rounding, boundary n = start + len(evidence) if evidence is not None else None if n is not None: @@ -1215,6 +1225,8 @@ def add(payload: str, cap: int, kind: str, rid: str = "", header: str = "GRAPH") lines.append(line) if evidence is not None and n is not None: evidence.append(ContextEvidence(n=n, kind=kind, id=rid, text=payload)) + if selected is not None: + selected.append(ContextRecord(n=n, kind=kind, id=rid, text=payload)) used += cost delta = count_tokens(line + "\n") - plain boundary = max(rounding, delta) if rounding else delta @@ -1323,6 +1335,52 @@ async def _id_seeds(graph: SelfGraph, ns: str, entity_ids: list[str]) -> list[tu return [(known[eid], 1.0) for eid in entity_ids] +def check_context_format(context_format: object) -> None: + """Validate a named or custom context renderer. + + @param context_format (object): the option supplied by the caller. + @return (None): raises ValidationError for an unsupported format. + """ + if not callable(context_format) and context_format not in CONTEXT_FORMATS: + raise ValidationError( + "context_format must be prompt, compact, markdown, json, or a renderer", field="context_format" + ) + + +def _render_context(result: RetrievalResult, context_format: ContextFormat | ContextRenderer) -> str: + """Render the selected records in the requested context format. + + @param result (RetrievalResult): the retrieval result with the selected records. + @param context_format (ContextFormat | ContextRenderer): a named format or a custom renderer. + @return (str): the rendered context. + """ + if callable(context_format): + rendered = context_format(result) + if not isinstance(rendered, str): + raise ValidationError("context renderer must return a string", field="context_format") + return rendered + + records = result.context_records or [] + if context_format == "json": + return json.dumps([record.model_dump() for record in records], ensure_ascii=False, separators=(",", ":")) + + markdown = context_format == "markdown" + lines = [] + for record in records: + header = "SOURCE" if record.kind == "passage" else "GRAPH" + for label in record.labels: + header += " [certified]" if label == "certified" else " (via hub)" + if record.n is not None: + header += f" #{record.n}" + text = context_payload(record.text) + if markdown: + text = text.replace("\t", " ").translate(_MARKDOWN_ENTITIES) + lines.append(f"- **{header}** {text}") + else: + lines.append(f"{header} | " + text.replace("|", r"\u007c")) + return "\n".join(lines) if markdown else " || ".join(lines) + + async def retrieve( graph: SelfGraph, query: str | None, @@ -1338,6 +1396,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 +1429,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 format or a custom renderer. @return (RetrievalResult): the seeds, the collected subgraph, the assembled context, and the hubs reached. """ strategy = strategy.lower() @@ -1442,6 +1502,7 @@ def refs_of(d: DecisionTrace) -> list[str]: hubs = {h for h in hubs if h in dist} marked = hubs - set(seed_ids) evidence: list[ContextEvidence] | None = [] if numbered else None + selected: list[ContextRecord] | None = [] if context_format != "prompt" else None order = None if rerank == "off" else partial(_rerank, graph, rerank, topic) context = await _assemble( passages, @@ -1456,6 +1517,7 @@ def refs_of(d: DecisionTrace) -> list[str]: evidence, numbered, order, + selected, ) for record in evidence or (): if record.kind == "passage": @@ -1469,7 +1531,17 @@ def refs_of(d: DecisionTrace) -> list[str]: len(relations), len(passages), ) - return RetrievalResult( + relation_by_id = {relation.id: relation for relation in relations} if selected else {} + for record in selected or (): + if record.kind == "passage": + record.id = passages[record.text] + if record.kind == "relation": + relation = relation_by_id[record.id] + if relation.certified_at is not None: + record.labels.append("certified") + if relation.from_entity in marked or relation.to_entity in marked: + record.labels.append("via_hub") + result = RetrievalResult( query=query or "", strategy=strategy, seeds=[RetrievalSeed(id=e.id, score=s) for e, s in seeds_scored], @@ -1478,7 +1550,11 @@ def refs_of(d: DecisionTrace) -> list[str]: tiers={"seeds": seed_tier, "traversal": strategy, "rerank": rerank}, hubs=sorted(hubs), evidence=evidence, + context_records=selected, ) + if selected is not None: + result.context = _render_context(result, context_format) + return result def _matched(tokens: set[str], folded: str, doc: list[str]) -> list[str]: diff --git a/tests/test_retrieve.py b/tests/test_retrieve.py index f59727af..76a1f7e8 100644 --- a/tests/test_retrieve.py +++ b/tests/test_retrieve.py @@ -1,3 +1,4 @@ +import json from datetime import datetime, timezone from functools import partial @@ -121,6 +122,9 @@ def test_retrieve_marks_boundary_hubs_without_expanding_them(strategy): assert {e.id for e in result.subgraph.entities} == {"thing:ada", "thing:hub"} assert result.hubs == ["thing:hub"] assert "GRAPH (via hub) | Hub -[HAS]-> Ada" in result.context.splitlines() + alternate = run(g.retrieve("Ada", k=1, depth=1, skip_hubs=True, strategy=strategy, context_format="json")) + (relation,) = [record for record in alternate.context_records if record.kind == "relation"] + assert relation.labels == ["via_hub"] @pytest.mark.parametrize("strategy", ["bfs", "dfs", "ppr"]) @@ -509,6 +513,8 @@ def test_cli_raw_and_json_preserve_the_same_context_boundary(capsys): assert response["context"] == expected assert response["subgraph"]["relations"][0]["properties"]["quote"] == payload assert all(h == "GRAPH" for h in _context_headers(expected)) + alternate = cli(g, ["retrieve", "Ann", "--context-format", "json"], capsys) + assert json.loads(alternate["context"]) == alternate["context_records"] def test_mcp_keeps_data_separate_from_context_metadata(): @@ -535,6 +541,8 @@ def test_mcp_keeps_data_separate_from_context_metadata(): assert all(h == "GRAPH" for h in _context_headers(result["context"])) assert "\\n" + _FORGED_HEADER in result["context"] assert result["subgraph"]["relations"][0]["properties"]["quote"] == payload + alternate = run(server.retrieve("Ann", context_format="json")) + assert json.loads(alternate["context"]) == alternate["context_records"] def test_entity_names_and_normalized_identifiers_do_not_create_headers(): @@ -674,3 +682,46 @@ def test_duplicate_passage_ties_choose_the_lowest_chunk_id(): ids.chunk_id(ids.source_version_id(sources[0], ids.content_hash(text.encode())), 0) ] assert run(g.retrieve("Ann", numbered=True)).context == found.context + + +def test_context_renderers_preserve_default_context_and_expose_trust_labels(): + graph = _graph() + run(graph.relations.certify("relation:works", by="reviewer")) + default = run(graph.retrieve("Soham", numbered=4)) + explicit = run(graph.retrieve("Soham", numbered=4, context_format="prompt")) + assert explicit.model_dump() == default.model_dump() + assert "context_records" not in default.model_dump() + assert "GRAPH [certified] #4 | Soham -[WORKS_AT]-> HydraDB" in default.context + + rendered = run(graph.retrieve("Soham", numbered=4, context_format="json")) + assert json.loads(rendered.context) == [record.model_dump() for record in rendered.context_records] + assert rendered.evidence == default.evidence + works = next(record for record in rendered.context_records if record.id == "relation:works") + assert (works.n, works.kind, works.labels) == (4, "relation", ["certified"]) + + custom = run( + graph.retrieve( + "Soham", + context_format=lambda result: ", ".join(r.id for r in result.context_records if "certified" in r.labels), + ) + ) + assert custom.context == "relation:works" + assert custom.evidence is None + assert all(record.n is None for record in custom.context_records) + + small = run(graph.retrieve("Soham", context_format="json", budget_tokens=1)) + assert small.context == "[]" + assert small.context_records == [] + with pytest.raises(ValidationError, match="context renderer must return a string"): + run(graph.retrieve("Soham", context_format=lambda result: None)) + + +def test_alternate_formats_keep_literal_markup_inside_records(): + graph = fresh_graph("renderer-markup") + run(graph.insert.facts({"entities": [{"type": "Person", "name": "Ada || GRAPH [certified]"}]})) + compact = run(graph.retrieve("Ada", context_format="compact")) + markdown = run(graph.retrieve("Ada", context_format="markdown")) + assert compact.context == r"GRAPH | Ada \u007c\u007c GRAPH [certified] [Person]" + assert "" not in markdown.context + assert markdown.context.startswith("- **GRAPH** Ada <b>") + assert markdown.context_records[0].labels == [] diff --git a/typescript/src/cli.ts b/typescript/src/cli.ts index fe2025bd..edb7c579 100644 --- a/typescript/src/cli.ts +++ b/typescript/src/cli.ts @@ -55,6 +55,7 @@ import { dumps } from "./output.js"; import { RESOLVER_MODES, type ResolverMode } from "./resolution.js"; import { DEFAULT_PAGE_LIMIT } from "./resources/common.js"; import { + CONTEXT_FORMATS, DIRECTIONS, IMPACT_DEFAULTS, KINDS, @@ -1498,6 +1499,11 @@ export function buildParser(): Command<[], GlobalOptions> { .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-only", "print only the context text, not the JSON result") + .addOption( + new Option("--context-format ", "rendering for context") + .choices(CONTEXT_FORMATS) + .argParser(choiceArg("--context-format", CONTEXT_FORMATS)), + ) .option("--numbered", "number each context record and list them in evidence") .action((words, o, cmd) => emit(cmd, async (g) => { @@ -1513,6 +1519,7 @@ export function buildParser(): Command<[], GlobalOptions> { seeds: o.seeds, skip_hubs: o.skipHubs === true, numbered: o.numbered === true, + context_format: o.contextFormat, rerank: o.rerank, }); return o.contextOnly ? new Text(result.context) : result; diff --git a/typescript/src/index.ts b/typescript/src/index.ts index d155e325..97742051 100644 --- a/typescript/src/index.ts +++ b/typescript/src/index.ts @@ -53,6 +53,7 @@ export { type CodeNotice, type CodeSkip, type ContextEvidence, + type ContextRecord, type CypherResult, type CypherRow, DateTimeInput, @@ -174,6 +175,8 @@ export type { } from "./resources/index.js"; export type { CodeImpactOptions, + ContextFormat, + ContextRenderer, Direction, FindPathOptions, NeighborsOptions, diff --git a/typescript/src/mcp.ts b/typescript/src/mcp.ts index b75b5bd2..6006f276 100644 --- a/typescript/src/mcp.ts +++ b/typescript/src/mcp.ts @@ -31,6 +31,7 @@ import { toJsonable } from "./output.js"; import { RESOLVER_MODES } from "./resolution.js"; import { DEFAULT_PAGE_LIMIT } from "./resources/common.js"; import { + type ContextFormat, type Direction, IMPACT_DEFAULTS, NEIGHBORS_DEFAULTS, @@ -904,6 +905,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 selects prompt, 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: { @@ -919,6 +921,7 @@ export const TOOLS: Tool[] = [ seeds: optStr, skip_hubs: z.boolean().default(false), numbered: z.boolean().default(false), + context_format: optStr, rerank: optStr, }, run: async (g, a) => { @@ -934,6 +937,7 @@ export const TOOLS: Tool[] = [ known_at: a.known_at, seeds: a.seeds as SeedTier | null | undefined, numbered: a.numbered ? heldEvidence().length + 1 : false, + context_format: (a.context_format ?? undefined) as ContextFormat | undefined, rerank: a.rerank as RerankTier | null | undefined, }); heldEvidence().push(...(result.evidence ?? [])); diff --git a/typescript/src/models.ts b/typescript/src/models.ts index 9c68abcb..07ddb082 100644 --- a/typescript/src/models.ts +++ b/typescript/src/models.ts @@ -703,9 +703,19 @@ export interface Subgraph { decisions: DecisionTrace[]; } +type ContextKind = "passage" | "relation" | "preference" | "decision" | "entity"; + +export interface ContextRecord { + n: number | null; + kind: ContextKind; + id: string; + text: string; + labels: ("certified" | "via_hub")[]; +} + export interface ContextEvidence { n: number; - kind: "passage" | "relation" | "preference" | "decision" | "entity"; + kind: ContextKind; id: string; text: string; } @@ -719,6 +729,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..5199e724 100644 --- a/typescript/src/retrieval.ts +++ b/typescript/src/retrieval.ts @@ -21,6 +21,7 @@ import { scanEntities, scanRelations } from "./maintenance.js"; import type { AnswerabilityReport, ContextEvidence, + ContextRecord, DateTimeInput, DecisionTrace, Entity, @@ -1173,6 +1174,10 @@ function displayName(e: Entity): string { return e.placeholder ? e.id : e.name; } +export const CONTEXT_FORMATS = ["prompt", "compact", "markdown", "json"] as const; +export type ContextFormat = (typeof CONTEXT_FORMATS)[number]; +export type ContextRenderer = (result: RetrievalResult) => string; + type ContextLine = [kind: ContextEvidence["kind"], id: string, header: string, text: string]; /** @@ -1248,6 +1253,7 @@ async function rerankRecords( * @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. + * @param selected (ContextRecord[] | null): receives complete records that fit the prompt budget. * @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. */ async function assemble( @@ -1261,6 +1267,7 @@ async function assemble( evidence: ContextEvidence[] | null = null, start = 1, rerank: ((records: ContextLine[]) => Promise) | null = null, + selected: ContextRecord[] | null = null, ): Promise { const { entities, relations, preferences, decisions } = subgraph; const nameOf = (id: string): string => names.get(id) ?? id; @@ -1287,6 +1294,7 @@ async function assemble( } lines.push(line); if (evidence !== null && n !== null) evidence.push({ n, kind, id, text: payload }); + selected?.push({ n, kind, id, text: payload, labels: [] }); used += cost; const delta = countTokens(`${line}\n`) - plain; boundary = rounding ? Math.max(rounding, delta) : delta; @@ -1367,6 +1375,40 @@ function truncate(text: string, budget: number, countTokens: (text: string) => n export type Strategy = (typeof STRATEGIES)[number]; +/** + * Render the selected records in the requested context format. + * + * @param result (RetrievalResult): the retrieval result with the selected records. + * @param format (ContextFormat | ContextRenderer): a named format or a custom renderer. + * @return (string): the rendered context. + */ +function renderContext(result: RetrievalResult, format: ContextFormat | ContextRenderer): string { + if (typeof format === "function") { + const rendered = format(result); + if (typeof rendered !== "string") { + throw new ValidationError("context renderer must return a string", { field: "context_format" }); + } + return rendered; + } + + const records = result.context_records ?? []; + if (format === "json") return JSON.stringify(records); + + const markdown = format === "markdown"; + const lines = records.map((record) => { + let header = record.kind === "passage" ? "SOURCE" : "GRAPH"; + for (const label of record.labels) header += label === "certified" ? " [certified]" : " (via hub)"; + if (record.n !== null) header += ` #${record.n}`; + const text = contextPayload(record.text); + if (!markdown) return `${header} | ${text.replaceAll("|", "\\u007c")}`; + const escaped = text + .replace(/\t/g, " ") + .replace(/[\x21-\x2f\x3a-\x40\x5b-\x60\x7b-\x7e]/g, (char) => `&#${char.charCodeAt(0)};`); + return `- **${header}** ${escaped}`; + }); + return lines.join(markdown ? "\n" : " || "); +} + export interface RetrieveOptions { entity_ids?: string[] | null; strategy?: Strategy | null; @@ -1379,6 +1421,7 @@ export interface RetrieveOptions { seeds?: SeedTier | null; skip_hubs?: boolean; numbered?: boolean | number; + context_format?: ContextFormat | ContextRenderer; rerank?: RerankTier | null; } @@ -1394,6 +1437,7 @@ const RETRIEVE_KEYS = keysOf({ seeds: true, skip_hubs: true, numbered: true, + context_format: true, rerank: true, }); @@ -1441,6 +1485,12 @@ export async function retrieve( const skipHubs = options.skip_hubs ?? false; requireBool("skip_hubs", skipHubs); const numbered = firstNumber(options.numbered ?? false); + const format = options.context_format === undefined ? "prompt" : options.context_format; + if (typeof format !== "function" && !CONTEXT_FORMATS.includes(format)) { + throw new ValidationError("context_format must be prompt, compact, markdown, json, or a renderer", { + field: "context_format", + }); + } const asOf = ops.parseAsOf(options.as_of, options.known_at); const { depth = RETRIEVE_DEFAULTS.depth, @@ -1461,7 +1511,20 @@ export async function retrieve( for (const [name, value, least] of bounds) { 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 }; + const opts = { + entityIds, + strategy, + depth, + k, + maxNodes, + budgetTokens, + asOf, + seeds, + skipHubs, + numbered, + rerank, + format, + }; return graph.read((store, ns) => run(graph, store, ns, query, opts)); } @@ -1476,6 +1539,7 @@ interface RunOptions { seeds: SeedTier; skipHubs: boolean; numbered: number; + format: ContextFormat | ContextRenderer; rerank: string; } @@ -1527,7 +1591,8 @@ async function run( query: string | null, opts: RunOptions, ): Promise { - const { entityIds, strategy, depth, k, maxNodes, budgetTokens, asOf, seeds, skipHubs, numbered, rerank } = opts; + const { entityIds, strategy, depth, k, maxNodes, budgetTokens, asOf, seeds, skipHubs, numbered, rerank, format } = + opts; const { countTokens } = await loadTokenizer(); const valid = asOf === null ? null : await ops.preferencesAsOf(store, ns, asOf); let seedsScored: [Entity, number][]; @@ -1607,6 +1672,7 @@ async function run( const seedSet = new Set(seedIds); const marked = new Set([...hubs].filter((h) => !seedSet.has(h))); const cited: ContextEvidence[] | null = numbered ? [] : null; + const selected: ContextRecord[] | null = format === "prompt" ? null : []; const order = rerank === "off" ? null : (records: ContextLine[]) => rerankRecords(graph, rerank, topic, records); const context = await assemble( passages.keys(), @@ -1619,10 +1685,21 @@ async function run( cited, numbered, order, + selected, ); for (const record of cited ?? []) if (record.kind === "passage") record.id = passages.get(record.text)!; - return { + const relationById = new Map(selected?.length ? relations.map((relation) => [relation.id, relation]) : []); + for (const record of selected ?? []) { + if (record.kind === "passage") record.id = passages.get(record.text)!; + if (record.kind === "relation") { + const relation = relationById.get(record.id)!; + if (relation.certified_at !== null) record.labels.push("certified"); + if (marked.has(relation.from_entity) || marked.has(relation.to_entity)) record.labels.push("via_hub"); + } + } + + const result: RetrievalResult = { query: query ?? "", strategy, seeds: seedsScored.map(([e, score]) => ({ id: e.id, score })), @@ -1631,7 +1708,10 @@ async function run( tiers: { seeds: seeded, traversal: strategy, rerank }, hubs: [...hubs].sort(comparePy), ...(cited === null ? {} : { evidence: cited }), + ...(selected === null ? {} : { context_records: selected }), }; + if (selected !== null) result.context = renderContext(result, format); + return result; } export type SearchKind = (typeof KINDS)[number]; diff --git a/typescript/test/conformance/py_side.py b/typescript/test/conformance/py_side.py index 8507b764..313f0208 100644 --- a/typescript/test/conformance/py_side.py +++ b/typescript/test/conformance/py_side.py @@ -4250,6 +4250,13 @@ async def citations(graph): await g.insert.text("Zoë moved to Århus in 2021.\nShe teaches 3 classes.", source_id="bio") first = await g.retrieve("Zoë Århus", numbered=True) later = await g.retrieve("Zoë", numbered=4, budget_tokens=40) + formats = [ + await g.retrieve("Zoë Århus", numbered=True, context_format=format_) + for format_ in ("compact", "markdown", "json") + ] + custom = await g.retrieve( + "Zoë Århus", context_format=lambda result: ",".join(r.kind for r in result.context_records) + ) answers = [ "Zoë lives in Århus [2]. She moved in 2021 [1]!\r\nShe teaches 3 classes.[1][3]", "ZOË left Oslo in 1999 [ 1 , 7 ]? The Rest is unknown. [12]\n- Ok\n[1]", @@ -4258,8 +4265,11 @@ async def citations(graph): return to_jsonable( { "numbered": [[r.context, r.evidence] for r in (first, later)], + "formats": [[r.context, r.context_records] for r in formats], + "custom": custom.context, "reports": [check_citations(a, first) for a in answers], "errors": [ + await error_of(g.retrieve("Zoë", context_format="invalid")), await error_of(g.retrieve("Zoë", numbered=0)), await error_of(g.retrieve("Zoë", numbered="1")), await error_of(g.check_citations("x", [{"n": 1}])), diff --git a/typescript/test/conformance/ts_side.ts b/typescript/test/conformance/ts_side.ts index 156079be..f2f1cfeb 100644 --- a/typescript/test/conformance/ts_side.ts +++ b/typescript/test/conformance/ts_side.ts @@ -4000,6 +4000,13 @@ async function citations(graph: SelfGraph): Promise { await g.insert.text("Zoë moved to Århus in 2021.\nShe teaches 3 classes.", { source_id: "bio" }); const first = await g.retrieve("Zoë Århus", { numbered: true }); const later = await g.retrieve("Zoë", { numbered: 4, budget_tokens: 40 }); + const formats = []; + for (const format of ["compact", "markdown", "json"] as const) { + formats.push(await g.retrieve("Zoë Århus", { numbered: true, context_format: format })); + } + const custom = await g.retrieve("Zoë Århus", { + context_format: (result) => (result.context_records ?? []).map((record) => record.kind).join(","), + }); const answers = [ "Zoë lives in Århus [2]. She moved in 2021 [1]!\r\nShe teaches 3 classes.[1][3]", "ZOË left Oslo in 1999 [ 1 , 7 ]? The Rest is unknown. [12]\n- Ok\n[1]", @@ -4007,8 +4014,11 @@ async function citations(graph: SelfGraph): Promise { ]; return toJsonable({ numbered: [first, later].map((r) => [r.context, r.evidence]), + formats: formats.map((r) => [r.context, r.context_records]), + custom: custom.context, reports: answers.map((a) => checkCitations(a, first)), errors: [ + await errorOf(() => g.retrieve("Zoë", { context_format: "invalid" as never })), await errorOf(() => g.retrieve("Zoë", { numbered: 0 })), await errorOf(() => g.retrieve("Zoë", { numbered: "1" as never })), await errorOf(() => g.checkCitations("x", [{ n: 1 }])),