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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
2 changes: 1 addition & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)) |
Expand Down
30 changes: 29 additions & 1 deletion docs/retrieval.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions src/selfgraph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@
CodeNotice,
CodeSkip,
ContextEvidence,
ContextFormat,
ContextRecord,
ContextRenderer,
CypherResult,
DecayResult,
DecisionStep,
Expand Down Expand Up @@ -193,6 +196,9 @@ def __dir__() -> list[str]:
"AnswerabilityReport",
"TermCoverage",
"ContextEvidence",
"ContextFormat",
"ContextRecord",
"ContextRenderer",
"CitationReport",
"UnsupportedSentence",
"check_citations",
Expand Down
4 changes: 3 additions & 1 deletion src/selfgraph/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down
9 changes: 8 additions & 1 deletion src/selfgraph/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@
from .models import (
AnswerabilityReport,
CitationReport,
ContextFormat,
ContextRenderer,
CypherResult,
DecisionTrace,
DecisionTraceInput,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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:
Expand All @@ -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.
Expand All @@ -460,6 +464,7 @@ async def retrieve(
"seeds",
"skip_hubs",
"numbered",
"context_format",
"rerank",
],
)
Expand Down Expand Up @@ -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(
Expand All @@ -505,6 +511,7 @@ async def retrieve(
seeds=seed_tier,
skip_hubs=skip_hubs,
numbered=first,
context_format=context_format,
rerank=rerank_tier,
)

Expand Down
3 changes: 3 additions & 0 deletions src/selfgraph/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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()
Expand All @@ -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,
)
Expand Down
25 changes: 23 additions & 2 deletions src/selfgraph/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,9 @@
"Subgraph",
"RetrievalResult",
"ContextEvidence",
"ContextFormat",
"ContextRecord",
"ContextRenderer",
"CitationReport",
"UnsupportedSentence",
"SearchPassage",
Expand Down Expand Up @@ -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

Expand All @@ -1131,20 +1146,26 @@ 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.
"""
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]
Expand Down
Loading
Loading