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
2 changes: 1 addition & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ settings from the environment are ignored silently.
| `check-citations ANSWER_FILE --evidence FILE` | Checks the `[n]` citations in an answer file, or `-` for stdin, against the JSON `retrieve --numbered` printed, and prints the report ([citing the context](retrieval.md#citing-the-context)). It opens no store. |
| `search` | Prints the ranked entities and passages for a query as JSON. See [`search`](#search). |
| `neighbors`, `path` | List the entities near an entity, or find how two connect. See [`neighbors` and `path`](#neighbors-and-path). |
| `insert text` | Extracts from text, or `-` for stdin, with the configured LLM, else spaCy or the regex fallback ([inserting](inserting.md#from-text)). `--metadata` takes a JSON object or `KEY=VALUE` pairs, repeatable and merged in order. `--replace-source` makes the text [replace](inserting.md#replacing-a-source) the earlier versions of `--source-id`. `--chunking markdown` splits it on [headings](inserting.md#markdown). |
| `insert text` | Extracts from text, or `-` for stdin, with the configured LLM, else spaCy or the regex fallback ([inserting](inserting.md#from-text)). `--metadata` takes a JSON object or `KEY=VALUE` pairs, repeatable and merged in order. `--replace-source` makes the text [replace](inserting.md#replacing-a-source) the earlier versions of `--source-id`. `--chunking markdown` splits it on [headings](inserting.md#markdown). `--facts FILE` stores the facts in that JSON file with the text instead of extracting ([facts with their text](inserting.md#facts-with-their-text)). |
| `insert facts` | Inserts facts from a JSON file, or `-` for stdin. `--placeholders` stores a [placeholder](inserting.md#references-to-entities-not-yet-inserted) for an entity reference not yet in the graph instead of failing. |
| `sync DIR` | Syncs the text files under `DIR`, extracting only those that changed, once or with `--watch` until interrupted. See [`sync`](#sync). |
| `code index DIR...` | Indexes source code into the graph, writing only the files that changed, once or with `--watch` until interrupted. See [`code index`](#code-index). |
Expand Down
25 changes: 23 additions & 2 deletions docs/inserting.md
Original file line number Diff line number Diff line change
Expand Up @@ -377,8 +377,9 @@ pass. `result.warnings` says which ran (`ner_extraction` or `basic_extraction`).
- The regex pass types every entity `Thing` and links neighbouring names in a
sentence with `RELATED_TO`.

Both can link the wrong pair. Use an LLM when the graph matters. `instructions`
and `prompts` are ignored here, with a `prompts_ignored` warning.
Both can link the wrong pair. Use an LLM when the graph matters, or extract the
facts yourself and pass them with the text, as [facts with their text](#facts-with-their-text)
shows. `instructions` and `prompts` are ignored here, with a `prompts_ignored` warning.

## From facts

Expand Down Expand Up @@ -423,6 +424,26 @@ CLI `insert facts`, and the MCP `insert_facts` tool give the same errors.
A [schema](schema.md), passed to the graph or to one insert, guides extraction
and checks what you write.

### Facts with their text

An agent with no `llm` configured can extract the facts itself. Pass them with
the text in one call:

```python
result = await graph.insert.text(text, source_id="note", facts=facts)
```

Nothing is extracted, so `result.tiers` has no `extraction` entry. The text is
stored as the source, so [retrieval](retrieval.md) returns its passages with
citations, and `replace_source` retires what only older versions stated. The facts are checked as `insert.facts` checks them: in `strict`
schema mode a fact outside the schema is rejected rather than dropped.
`instructions` and `prompts` guide extraction, so passing them with `facts`
raises `invalid_argument` on the `facts` field. The CLI takes `insert text TEXT
--facts FILE`, and the MCP `insert_text` tool takes `facts`.

Relation evidence that names no `source_id` cites the call's `source_id`, in
`insert.text` and `insert.facts`, so `{"quote": "..."}` is enough.

### References to entities not yet inserted

Every entity a relation, preference, or decision names must be in the facts or
Expand Down
2 changes: 1 addition & 1 deletion docs/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ default 50) and `[cursor]`.
| `suggest_schema` | `[extend]`, `[min_count]` (default 1), `[format]` (`selfgraph` or `neo4j`) ([suggesting a schema](schema.md#suggesting-a-schema-from-the-graph)) |
| `list_namespaces` | none ([several graphs](#several-graphs)) |
| `use_namespace` | `namespace` ([several graphs](#several-graphs)) |
| `insert_text` | `text`, `[source_id]`, `[event_time]`, `[metadata]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[instructions]`, `[prompts]`, `[replace_source]`, `[chunking]` (`tokens` or `markdown`, see [markdown chunking](inserting.md#markdown)) |
| `insert_text` | `text`, `[source_id]`, `[event_time]`, `[metadata]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[instructions]`, `[prompts]`, `[replace_source]`, `[chunking]` (`tokens` or `markdown`, see [markdown chunking](inserting.md#markdown)), `[facts]` (stored with the text instead of extracting, see [facts with their text](inserting.md#facts-with-their-text)) |
| `insert_facts` | `facts` (an object with `entities`, `relations`, `preferences`, `decisions`), `[source_id]`, `[event_time]`, `[resolver]`, `[contradiction]`, `[schema]`, `[schema_mode]`, `[placeholders]` ([placeholders](inserting.md#references-to-entities-not-yet-inserted)) |
| `index_code` | `[paths]` (local directories inside the working directory or remote git URLs, default the directory itself), `[ref]` (remote branch, tag or commit), `[languages]`, `[remove_missing]` (default true) ([indexing code](#indexing-code)) |
| `sync_folder` | `directory` (inside the working directory), `[globs]` (default `**/*.md` and `**/*.txt`), `[remove_missing]` (default false), `[resolver]`, `[contradiction]`, `[chunking]` (`tokens` or `markdown`) ([syncing a folder](#syncing-a-folder)) |
Expand Down
14 changes: 14 additions & 0 deletions skill/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,20 @@ asyncio.run(main())
The heuristic extractor is coarse. Ready facts avoid extraction; LLM extraction is opt-in.
Run `examples/retrieval.py` for the same workflow against a path you choose.

## Without an LLM key

With no LLM configured, extract the facts yourself instead of relying on the heuristic
extractor: give entities real types, name the relations, and pass them with the text.

```python
await graph.insert.text(text, source_id="note", facts={"entities": [...], "relations": [...]})
```

Nothing is extracted. The text is still stored as the source, so passages, citations, and
`replace_source` keep working. Evidence that names no `source_id` cites the call's, so
`{"quote": "..."}` is enough. CLI `selfgraph insert text TEXT --facts FILE`; MCP `upsert_text`
with `facts`. The facts shape is in `references/writing.md`.

## Load details when needed

- Writes, schema, CRUD, resolution: `references/writing.md`.
Expand Down
4 changes: 4 additions & 0 deletions skill/references/writing.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ await graph.insert.facts(
)
```

To keep the text as the source too, pass the same facts to `insert.text(text, source_id=..., facts=...)`:
nothing is extracted, and passages, citations, and `replace_source` work as they do for extracted text.
Relation evidence that names no `source_id` cites the call's `source_id`, in `insert.text` and `insert.facts`.

`await graph.export_facts()` (CLI `selfgraph export facts [FILE]`) returns the namespace's current entities,
relations (with evidence and `certifications`), preferences, and decisions in this shape, each list ordered by
id. Inserting it into an empty namespace, with `placeholders=True` when it names placeholders, and exporting
Expand Down
2 changes: 2 additions & 0 deletions src/selfgraph/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,7 @@ def build_parser() -> argparse.ArgumentParser:
action="store_true",
help="the text replaces --source-id's earlier versions: retire relations only they stated",
)
it.add_argument("--facts", help="a facts JSON file to store with the text instead of extracting, or '-' for stdin")
_add_chunking(it)
_add_call_overrides(it)

Expand All @@ -1137,6 +1138,7 @@ async def insert_text(g, a):
contradiction=a.call_contradiction,
replace_source=a.replace_source,
chunking=a.chunking,
facts=None if a.facts is None else read_json(a.facts, "facts"),
)
)

Expand Down
52 changes: 50 additions & 2 deletions src/selfgraph/insert.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ async def text(
contradiction: ContradictionMode | None = None,
replace_source: bool = False,
chunking: Chunking = "tokens",
facts: Extraction | Mapping[str, Any] | None = None,
**options: Unpack[_NoOptions],
) -> InsertResult:
"""Extract and upsert text facts; content.upsert_text is the noun path and insert.text its compatibility alias.
Expand All @@ -88,6 +89,8 @@ async def text(
contradiction: Conflict handling policy, defaulting to the graph's policy.
replace_source: treat the text as a replacement of source_id's earlier versions.
chunking: "tokens", or "markdown" to split on headings and keep each chunk's section.
facts: entities, relations, preferences, and decisions to store with the text instead of extracting
them; the text is still recorded as the source, and evidence without a source_id cites it.

Returns:
what was inserted, with source_diff when replace_source is set.
Expand All @@ -107,6 +110,7 @@ async def text(
"contradiction",
"replace_source",
"chunking",
"facts",
],
)
if resolver is not None:
Expand All @@ -131,6 +135,26 @@ async def text(
)
instructions = as_input(ExtractionInstructions, instructions, "instructions")
prompts = as_input(ExtractionPrompts, prompts, "prompts")
if facts is not None:
if instructions is not None or prompts is not None:
raise ValidationError(
"instructions and prompts guide extraction, which facts skip; pass one or the other",
field="facts",
)
return await self._c._apply_facts(
as_input(Extraction, _inherit_source(facts, source_id), "facts"),
source_id=source_id,
parsed_text=text,
media_type="text/plain",
metadata=metadata,
default_event_time=event_time,
schema=active_schema,
schema_mode=schema_mode,
resolver=resolver,
contradiction=contradiction,
replace_source=replace_source,
chunking=chunking,
)
extractor = self._c._build_extractor(
instructions, prompts, schema=active_schema, source_id=source_id, chunking=chunking
)
Expand Down Expand Up @@ -303,7 +327,7 @@ async def facts(

Args:
facts: the facts to merge.
source_id: optional source id to attach as provenance.
source_id: optional source id to attach as provenance; evidence without a source_id cites it.
event_time: the default event time (a datetime or ISO 8601 text) for
relations, preferences, and decisions that carry none of their own.
schema: The schema for this call, defaulting to the graph's schema.
Expand All @@ -326,7 +350,7 @@ async def facts(
if facts is None:
raise ValidationError("invalid facts: expected object")
return await self._c._apply_facts(
as_input(Extraction, facts, "facts"),
as_input(Extraction, _inherit_source(facts, source_id), "facts"),
source_id=source_id,
parsed_text=None,
media_type=None,
Expand All @@ -341,3 +365,27 @@ async def facts(

upsert_text = text
upsert_facts = facts


def _inherit_source(facts: Any, source_id: str | None) -> Any:
"""Give relation evidence that names no source the call's source_id.

@param facts (Any): the facts as given.
@param source_id (str | None): the call's source id.
@return (Any): the facts, with each evidence item lacking a source_id citing the call's source.
"""
if source_id is None or not isinstance(facts, Mapping) or not isinstance(facts.get("relations"), list | tuple):
return facts
relations = [
{
**rel,
"evidence": [
{**ev, "source_id": source_id} if isinstance(ev, Mapping) and "source_id" not in ev else ev
for ev in rel["evidence"]
],
}
if isinstance(rel, Mapping) and isinstance(rel.get("evidence"), list | tuple)
else rel
for rel in facts["relations"]
]
return {**facts, "relations": relations}
11 changes: 8 additions & 3 deletions src/selfgraph/mcp/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,10 +400,13 @@ async def insert_text(
prompts: dict | None = None,
replace_source: StrictBool = False,
chunking: Chunking = "tokens",
facts: dict | None = None,
) -> dict[str, Any]:
"""Extract and upsert facts from text; insert_text is a compatibility alias of upsert_text. Uses the
configured LLM, or with none
configured falls back to a built-in LLM-free extractor (coarser). event_time (ISO 8601 or relative such as 7d) is
configured LLM; with none configured, extract the entities and relations yourself and pass them as facts,
because the built-in LLM-free extractor is coarse. With facts, nothing is extracted, the text is still stored
as the source for passages, citations, and replace_source, and evidence without a source_id cites this one,
and instructions and prompts must be left out. event_time (ISO 8601 or relative such as 7d) is
the default valid time for what is extracted; metadata is stored on the source.

Idempotent: ids are derived deterministically from content, so re-inserting the
Expand Down Expand Up @@ -432,6 +435,7 @@ async def insert_text(
prompts=prompts,
replace_source=replace_source,
chunking=chunking,
facts=facts,
)
)
)
Expand Down Expand Up @@ -462,7 +466,8 @@ async def insert_facts(
is handled: warn keeps both and reports it, supersede retires the older relation. schema (a SelfGraph schema object)
and schema_mode (off, warn, strict) override the server's for this call. placeholders stores a placeholder entity
for a reference that is neither in the facts nor in the graph, instead of failing, and reports each one as a
placeholder_created warning; inserting an entity with that id later fills it in.
placeholder_created warning; inserting an entity with that id later fills it in. Evidence without a source_id
cites source_id. To keep the source text for passages and citations, pass it with these facts to insert_text.
"""
at = parse_time(event_time, "event_time")
g = await _graph_handle()
Expand Down
82 changes: 82 additions & 0 deletions tests/test_insert_with_facts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import json

import pytest
from helpers import fresh_graph, json_file, kuzu_main, mcp_session, run

from selfgraph import ValidationError

TEXT = "Ann Lee leads the Payments team at Acme. In March, Bob Diaz joined Payments."
QUOTE = "Ann Lee leads the Payments team"
FACTS = {
"entities": [{"type": "Person", "name": "Ann Lee"}, {"type": "Team", "name": "Payments"}],
"relations": [
{"from_entity": "person:ann-lee", "type": "LEADS", "to_entity": "team:payments", "evidence": [{"quote": QUOTE}]}
],
}


def evidence_of(graph, relation_id):
return [(ev.source_id, ev.source_version, ev.quote) for ev in run(graph.relations.evidence(relation_id)).items]


def test_text_with_facts_stores_the_source_without_extracting():
g = fresh_graph("withfacts")
result = run(g.insert.text(TEXT, source_id="doc1", facts=FACTS))
assert sorted(entity.type for entity in result.entities) == ["Person", "Team"]
assert [relation.type for relation in result.relations] == ["LEADS"]
assert "extraction" not in result.tiers
assert evidence_of(g, result.relations[0].id) == [("doc1", result.source_version, QUOTE)]
retrieved = run(g.retrieve("who leads payments", numbered=True))
assert retrieved.context.splitlines()[0] == f"SOURCE #1 | {TEXT}"
assert [record.kind for record in retrieved.evidence][0] == "passage"


def test_facts_evidence_takes_the_call_source_id_unless_it_names_one():
g = fresh_graph("inherit")
evidence = ({"quote": QUOTE}, {"source_id": "other", "quote": QUOTE})
facts = {**FACTS, "relations": ({**FACTS["relations"][0], "evidence": evidence},)}
result = run(g.insert.facts(facts, source_id="doc2"))
assert sorted(evidence_of(g, result.relations[0].id)) == [
("doc2", result.source_version, QUOTE),
("other", "other:manual", QUOTE),
]


def test_replace_source_with_facts_retires_what_only_older_versions_stated():
g = fresh_graph("replace")
first = run(g.insert.text(TEXT, source_id="doc1", facts=FACTS))
joined = {
"entities": [{"type": "Person", "name": "Bob Diaz"}, {"type": "Team", "name": "Payments"}],
"relations": [{"from_entity": "person:bob-diaz", "type": "JOINED", "to_entity": "team:payments"}],
}
second = run(g.insert.text("Bob Diaz joined Payments.", source_id="doc1", replace_source=True, facts=joined))
assert second.source_diff.retired == [first.relations[0].id]
assert [relation.type for relation in second.relations] == ["JOINED"]


def test_strict_mode_rejects_caller_facts_outside_the_schema():
g = fresh_graph("strict", schema={"entities": [{"name": "Person"}]}, schema_mode="strict")
with pytest.raises(ValidationError) as caught:
run(g.insert.text(TEXT, source_id="doc1", facts=FACTS))
assert caught.value.code == "schema_violation"
assert run(g.entities.list()).items == []


@pytest.mark.parametrize("extra", [{"instructions": {"entities": "people"}}, {"prompts": {}}])
def test_facts_with_extraction_settings_is_rejected(extra):
g = fresh_graph("guard")
with pytest.raises(ValidationError) as caught:
run(g.insert.text(TEXT, source_id="doc1", facts=FACTS, **extra))
assert (caught.value.code, caught.value.field) == ("invalid_argument", "facts")
assert str(caught.value) == "instructions and prompts guide extraction, which facts skip; pass one or the other"
assert run(g.entities.list()).items == []


def test_cli_and_mcp_take_facts_with_the_text(tmp_path, capsys):
path = json_file(tmp_path, "facts.json", FACTS)
assert kuzu_main(tmp_path, "insert", "text", TEXT, "--source-id", "doc1", "--facts", path) == 0
inserted = json.loads(capsys.readouterr().out)
assert sorted(entity["type"] for entity in inserted["entities"]) == ["Person", "Team"]
with mcp_session() as server:
result = run(server.insert_text(TEXT, source_id="doc1", facts=FACTS))
assert [relation["type"] for relation in result["relations"]] == ["LEADS"]
6 changes: 4 additions & 2 deletions typescript/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ import {
DEFAULT_STANCE,
DEFAULT_STATUS,
type EvidenceInput,
type Extraction,
type FactsInput,
type InsertResult,
type JsonObject,
type NeighborsResult,
Expand Down Expand Up @@ -1700,6 +1700,7 @@ export function buildParser(): Command<[], GlobalOptions> {
[],
)
.option("--replace-source", "the text replaces --source-id's earlier versions: retire relations only they stated")
.option("--facts <path>", "a facts JSON file to store with the text instead of extracting, or '-' for stdin")
.addOption(chunkingOption())
.addOption(callResolver())
.addOption(contradictionOption())
Expand All @@ -1714,6 +1715,7 @@ export function buildParser(): Command<[], GlobalOptions> {
contradiction: o.contradiction as ContradictionMode | undefined,
replace_source: o.replaceSource === true,
chunking: o.chunking,
facts: o.facts === undefined ? undefined : (readJson(o.facts, "facts") as FactsInput),
})
.then(inserted),
),
Expand All @@ -1734,7 +1736,7 @@ export function buildParser(): Command<[], GlobalOptions> {
.action((path, o, cmd) =>
emit(cmd, (g) =>
g.insert
.facts(readJson(path) as Extraction, {
.facts(readJson(path) as FactsInput, {
source_id: o.sourceId,
event_time: o.eventTime,
resolver: (o.resolver as ResolverMode | undefined) ?? null,
Expand Down
Loading
Loading