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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 37 additions & 1 deletion docs/retrieval.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ print(result.context)
| `query`, `strategy` | The query and strategy used. |
| `seeds` | The seed entities as `{id, score, entity}`, 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). |

Expand Down Expand Up @@ -45,6 +46,41 @@ The existing seed `id` and entity-hit `id` remain back-compatible aliases for

## 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.
Expand Down
9 changes: 9 additions & 0 deletions src/selfgraph/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -42,7 +43,10 @@
CodeLimits,
CodeNotice,
CodeSkip,
ContextData,
ContextEvidence,
ContextLabel,
ContextRecord,
CypherResult,
DecayResult,
DecisionStep,
Expand Down Expand Up @@ -207,7 +211,12 @@ def __dir__() -> list[str]:
"neighbors_dot",
"AnswerabilityReport",
"TermCoverage",
"ContextData",
"ContextEvidence",
"ContextFormat",
"ContextLabel",
"ContextRecord",
"ContextRenderer",
"CitationReport",
"UnsupportedSentence",
"check_citations",
Expand Down
83 changes: 83 additions & 0 deletions src/selfgraph/_context.py
Original file line number Diff line number Diff line change
@@ -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
3 changes: 3 additions & 0 deletions src/selfgraph/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, install_llm, plan_hooks, plan_install, server_command
Expand Down Expand Up @@ -263,6 +264,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

Expand Down Expand Up @@ -950,6 +952,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)
Expand Down
6 changes: 6 additions & 0 deletions src/selfgraph/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 _WRITE_WARNINGS, _store_call
Expand Down Expand Up @@ -425,6 +426,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.
Expand All @@ -450,6 +452,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(
Expand All @@ -468,6 +471,7 @@ async def retrieve(
"skip_hubs",
"numbered",
"rerank",
"context_format",
],
)
if query is None and entity_ids is None:
Expand Down Expand Up @@ -498,6 +502,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,
Expand All @@ -513,6 +518,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:
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 @@ -1008,6 +1008,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
Expand All @@ -1016,6 +1017,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()
Expand All @@ -1033,6 +1035,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)
Expand Down
23 changes: 22 additions & 1 deletion src/selfgraph/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@
"RetrievalSeed",
"Subgraph",
"RetrievalResult",
"ContextData",
"ContextEvidence",
"ContextLabel",
"ContextRecord",
"CitationReport",
"UnsupportedSentence",
"SearchPassage",
Expand Down Expand Up @@ -1134,11 +1137,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):
Expand All @@ -1151,6 +1171,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)
truncated: bool = False

@model_serializer(mode="wrap")
Expand Down
Loading
Loading