Skip to content

API Reference parrot_tools.graphindex.toolkit

github-actions[bot] edited this page Dec 2, 2026 · 4 revisions

parrot_tools.graphindex.toolkit

View source

GraphIndex Toolkit — Agent-Facing Tools.

Exposes the knowledge graph to AI agents as a set of 19 callable tools via GraphIndexToolkit(AbstractToolkit). All public async methods are auto-discovered and registered as tools by the AbstractToolkit base class.

Hot read queries operate over the in-memory rustworkx.PyDiGraph and FAISS index. Write tools mutate the same in-memory state through the GraphAssembler reference (when supplied) so the graph stays consistent; agents can build the wiki from inside a tool call.

Optional integrations:

  • GraphIndexEmbedder — when injected, replaces the placeholder query encoder with a real model.encode call and embeds freshly created nodes so find_node and search_hybrid see them.
  • SignalRelevanceConfig (FEAT-190) — drives relevance() and neighborhood_by_relevance(). Lazy-imported.
  • FEAT-191 communities — list_communities / find_community cache the partition until a write tool runs. Lazy-imported.

Tool surface:

READ

find_node, find_references, get_neighborhood, traverse, search_hybrid, find_central_nodes, shortest_path, explain, relevance, neighborhood_by_relevance, list_communities, find_community, export_graph_html

WRITE

create_concept, create_node, link_nodes, unlink_nodes, attach_summary, tag_node, merge_nodes

DURABLE MEMORY (requires publisher=GraphPublisher)

graph_history, revert_write

TEMPORAL + HYBRID (FEAT-520 — Postgres-backed durable plane ONLY;

excluded from tool generation, not just error-returning, when the

bound persistence lacks the surface — capability-checked with

runtime-checkable protocols)

graph_as_of, graph_concept_history, graph_diff, graph_hybrid_retrieve

When a GraphPublisher is injected, every write tool ALSO persists its mutation as an audited, revertible commit stamped with the agent's identity and run — the graph becomes durable cross-session memory ("the agent forgets, the graph does not"). Persistence failures never fail the tool call; they surface as persist_warning in the result.

FEAT-520: when the injected publisher's bound persistence implements the temporal capability, four additional mono-purpose tools are registered: graph_as_of/graph_concept_history/graph_diff (temporal reads) and graph_hybrid_retrieve (one-pass graph+KNN+FTS retrieval). They are deliberately excluded from tool generation — not merely error-returning — on SQLite/ArangoDB-backed toolkits, via exclude_tools computed in __init__. Fusion weights and result limits are fixed operator configuration (_HYBRID_RETRIEVE_WEIGHTS/ _HYBRID_RETRIEVE_LIMIT below), never LLM-controlled parameters — "el agente elige tools, nunca pesos ni modos" (brainstorm D6). NOTE: graph_concept_history is named to avoid colliding with the EXISTING graph_history tool above (commit/write history, unrelated to a concept's bitemporal VERSION history — spec D5's history(concept_id)).

Attribute DEFAULT_ANALYTICS_TOP_K

Class GraphIndexToolkit

Agent-facing tools for querying AND mutating the GraphIndex graph.

Read-only queries work with the original three-positional-arg constructor (graph, faiss_index, node_map, node_id_list). Write capabilities and signal/community wrappers require the assembler, embedder, and nodes kwargs.

Parameter Type Default Description
graph rustworkx.PyDiGraph The assembled rustworkx.PyDiGraph. Node payloads must be dicts with at least node_id, kind, title.
faiss_index faiss.Index FAISS index populated with node embeddings.
node_map dict[str, int] Mapping node_id (str) → rustworkx integer index.
node_id_list list[str] Ordered list mapping FAISS position → node_id. Mutations may set entries to None to orphan a FAISS row (FAISS does not support row deletion for IndexFlatL2).
client None Optional AbstractClient for explain().
assembler Optional['GraphAssembler'] None Optional GraphAssembler — required for the write tools. Without it, write methods return a structured {"error": ...} response instead of raising.
embedder Optional['GraphIndexEmbedder'] None Optional GraphIndexEmbedder — used to embed new nodes (create_concept / create_node) and to encode queries for find_node / search_hybrid. Falls back to the placeholder hash encoder when missing.
nodes Optional[list['UniversalNode']] None Optional list of UniversalNode instances kept in sync with the graph; required by signal/community tools and by attach_summary (so the model object stays authoritative).
signal_config Optional['SignalRelevanceConfig'] None Optional :class:SignalRelevanceConfig (FEAT-190). Defaults to the library's default config when not supplied.
publisher Optional[Any] None Optional GraphPublisher — when supplied, every write tool ALSO persists its mutation durably as an audited commit (write-through). Without it, writes stay in-memory only (legacy behavior). Persistence failures never fail the tool call; they surface as a persist_warning key.
agent_id str 'agent' Stable identifier stamped onto persisted writes.
run_id Optional[str] None Optional run/session identifier linking persisted writes to the execution that produced them. Mutable — set per ask.

Attributes:

Attribute Type Description
confirming_tools frozenset

Method GraphIndexToolkit.find_node

Find the most semantically similar node to the query.

Uses the FAISS index to find the closest embedding. Requires the query to be a non-empty string.

find_node(query: str) -> dict

Parameter Type Default Description
query str Natural language search query.

Returns: dict — Dict with node_id, title, kind, and similarity_score, or an error dict if no nodes are indexed.

Method GraphIndexToolkit.find_references

Return all edges where node_id is source or target.

find_references(node_id: str) -> list[dict]

Parameter Type Default Description
node_id str The node to find references for.

Returns: list[dict] — List of edge dicts with source_id, target_id, kind, and confidence.

Method GraphIndexToolkit.get_neighborhood

BFS subgraph around a node up to a given depth.

get_neighborhood(node_id: str, depth: int = 2) -> dict

Parameter Type Default Description
node_id str Center node identifier.
depth int 2 Maximum traversal depth (default 2).

Returns: dict — Dict with center, nodes (list of node dicts), and edges (list of edge dicts) within the neighborhood.

Method GraphIndexToolkit.traverse

Walk edges of a specific relation type from a node.

traverse(from_id: str, relation: str, to_kind: Optional[str] = None) -> list[dict]

Parameter Type Default Description
from_id str Starting node identifier.
relation str Edge kind to follow (e.g., "contains", "references").
to_kind Optional[str] None Optional filter for target node kind (e.g., "document").

Returns: list[dict] — List of reached node payload dicts.

Method GraphIndexToolkit.search_hybrid

Combine FAISS similarity with graph proximity for hybrid search.

Retrieves FAISS nearest neighbours and boosts their scores by the number of graph connections (degree), combining both signals.

search_hybrid(query: str, top_k: int = 10) -> list[dict]

Parameter Type Default Description
query str Natural language search query.
top_k int 10 Number of results to return.

Returns: list[dict] — List of node dicts ranked by combined score (descending).

Method GraphIndexToolkit.find_central_nodes

Return top-K most central nodes by the specified centrality metric.

find_central_nodes(top_k: int = 10, metric: str = 'betweenness') -> list[dict]

Parameter Type Default Description
top_k int 10 Number of top nodes to return.
metric str 'betweenness' Centrality metric to use: "betweenness" (default) or "eigenvector".

Returns: list[dict] — List of node dicts with node_id, title, kind, and centrality_score, sorted by score descending.

Method GraphIndexToolkit.export_graph_html

Export an interactive graph.html map plus graph.json.

Renders the current in-memory graph as a self-contained, clickable force-directed page: nodes are concepts, colour is the detected community, node size scales with centrality (god nodes are highlighted), and clicking a node opens a detail panel. The page inlines the ECharts runtime so it works fully offline. A sibling graph.json carries the serialized graph for programmatic reuse.

export_graph_html(output_dir: str, top_k_god_nodes: int = 15) -> dict

Parameter Type Default Description
output_dir str Directory where graph.html and graph.json are written (created if missing).
top_k_god_nodes int 15 Number of most-central "god" nodes to highlight.

Returns: dict — Dict with graph_html, graph_json, node_count, edge_count and community_count — or an error dict when the export module is unavailable.

Method GraphIndexToolkit.shortest_path

Find the shortest path between two nodes.

shortest_path(from_id: str, to_id: str) -> list[dict]

Parameter Type Default Description
from_id str Source node identifier.
to_id str Target node identifier.

Returns: list[dict] — Ordered list of node payload dicts forming the path, or an empty list if no path exists.

Method GraphIndexToolkit.explain

LLM-generated summary of a node's role in the knowledge graph.

Requires an AbstractClient to be provided at construction time. If no client is available, returns a fallback description built from the node's metadata.

explain(node_id: str) -> str

Parameter Type Default Description
node_id str The node to explain.

Returns: str — Natural language explanation of the node's significance.

Method GraphIndexToolkit.create_concept

Create a CONCEPT node and embed it.

The deterministic node_id is a SHA-1 prefix of "concept::title::summary" so re-creating an identical concept is idempotent at the id level. Categories are stored in domain_tags['categories'].

Returns {node_id, kind, title, status} or {"error": ...}.

create_concept(title: str, summary: str, source_uri: Optional[str] = None, categories: Optional[list[str]] = None) -> dict

Parameter Type Default Description
title str
summary str
source_uri Optional[str] None
categories Optional[list[str]] None

Returns: dict

Method GraphIndexToolkit.create_node

Generic node creation for any NodeKind.

create_node(kind: str, title: str, summary: Optional[str] = None, source_uri: Optional[str] = None, parent_id: Optional[str] = None, domain_tags: Optional[dict] = None) -> dict

Parameter Type Default Description
kind str
title str
summary Optional[str] None
source_uri Optional[str] None
parent_id Optional[str] None
domain_tags Optional[dict] None

Returns: dict

Method GraphIndexToolkit.link_nodes

Add a directed edge.

confidence is allowed iff kind is treated as INFERRED provenance — the underlying UniversalEdge validator enforces confidence ⇔ provenance=INFERRED.

link_nodes(source_id: str, target_id: str, kind: str, confidence: Optional[float] = None) -> dict

Parameter Type Default Description
source_id str
target_id str
kind str
confidence Optional[float] None

Returns: dict

Method GraphIndexToolkit.unlink_nodes

Remove edge(s) between two nodes.

kind=None removes every edge between them (in either direction); a specific kind removes only matching edges.

unlink_nodes(source_id: str, target_id: str, kind: Optional[str] = None) -> dict

Parameter Type Default Description
source_id str
target_id str
kind Optional[str] None

Returns: dict

Method GraphIndexToolkit.attach_summary

Set / overwrite the summary on an existing node and re-embed.

attach_summary(node_id: str, summary: str) -> dict

Parameter Type Default Description
node_id str
summary str

Returns: dict

Method GraphIndexToolkit.tag_node

Shallow-merge a single key/value into the node's domain_tags.

tag_node(node_id: str, key: str, value: Any) -> dict

Parameter Type Default Description
node_id str
key str
value Any

Returns: dict

Method GraphIndexToolkit.merge_nodes

Re-point every edge of duplicate_id to canonical_id and remove the duplicate node.

FAISS does not support row deletion for IndexFlatL2, so the duplicate's FAISS position is orphaned: node_id_list[pos] is set to None and read tools skip the position. Edges that would duplicate an existing canonical edge (same source, target, kind) are dropped, not double-added. Self-loops created by the merge are dropped.

merge_nodes(canonical_id: str, duplicate_id: str) -> dict

Parameter Type Default Description
canonical_id str
duplicate_id str

Returns: dict

Method GraphIndexToolkit.graph_history

List durable graph write commits, newest first.

Every persisted write (create_node, link_nodes, merge_nodes, ...) is recorded as an audited commit carrying the agent, run, and rationale that produced it.

graph_history(run_id: Optional[str] = None, limit: int = 20) -> list[dict]

Parameter Type Default Description
run_id Optional[str] None Only show commits from this run/session.
limit int 20 Maximum commits returned.

Returns: list[dict] — Commit summaries, or a single-element list with an error key when no durable plane is configured.

Method GraphIndexToolkit.revert_write

Revert a durable graph write commit (restore its pre-images).

The revert is refused when later commits touched the same nodes or edges. NOTE: the revert applies to the durable plane; the in-memory view refreshes on the next toolkit load.

revert_write(commit_id: str) -> dict

Parameter Type Default Description
commit_id str The commit to revert (see graph_history).

Returns: dict — {"status": "reverted", ...} or {"error": ...}.

Method GraphIndexToolkit.graph_as_of

Snapshot the durable graph as it existed at a point in time.

Only available when the durable graph plane is Postgres-backed (bitemporal storage — FEAT-520). Repealed/superseded nodes and edges are excluded exactly as they were at timestamp.

graph_as_of(timestamp: str) -> dict

Parameter Type Default Description
timestamp str ISO-8601, timezone-aware timestamp (e.g. "2026-06-01T00:00:00+00:00").

Returns: dict — {"nodes": [...], "edges": [...]} at that snapshot, or {"error": ...} when unavailable or the timestamp is malformed/naive.

Method GraphIndexToolkit.graph_concept_history

List every version of a concept over time (bitemporal version history).

Distinct from graph_history above (which lists durable WRITE commits) — this lists a single CONCEPT's content versions, including repealed ones. Only available on a Postgres-backed durable plane (FEAT-520).

graph_concept_history(concept_id: str) -> dict

Parameter Type Default Description
concept_id str The concept to list version history for.

Returns: dict — {"versions": [...]} ordered oldest-first, or {"error": ...} when unavailable.

Method GraphIndexToolkit.graph_diff

Structured diff of a concept between two points in time.

Reports version changes plus incident edges added/removed between t1 and t2 — structured data for the LLM to reason over, never a raw-text comparison. Only available on a Postgres-backed durable plane (FEAT-520).

graph_diff(concept_id: str, t1: str, t2: str) -> dict

Parameter Type Default Description
concept_id str The concept to diff.
t1 str Start ISO-8601, timezone-aware timestamp.
t2 str End ISO-8601, timezone-aware timestamp.

Returns: dict — The structured diff as a dict, or {"error": ...}.

Method GraphIndexToolkit.graph_hybrid_retrieve

Retrieve relevant concepts via combined graph + lexical search.

Fuses temporal graph expansion (from seeds) with full-text search (over query) in one ranked result set. Fusion weights and the result limit are FIXED operator configuration — never exposed as parameters here, so the agent picks WHAT to search for, never HOW (brainstorm D6). Only available on a Postgres -backed durable plane (FEAT-520); the semantic/KNN leg is not wired from this tool (query embedding generation is a separate concern outside this toolkit's scope) — this wraps the graph and FTS legs only.

graph_hybrid_retrieve(query: Optional[str] = None, seeds: Optional[list[str]] = None) -> dict

Parameter Type Default Description
query Optional[str] None Free-form natural-language query for the lexical leg.
seeds Optional[list[str]] None Optional concept_ids to seed graph expansion from.

Returns: dict — {"candidates": [...]} ranked results, or {"error": ...} when unavailable or neither query nor seeds is given.

Method GraphIndexToolkit.ground_claim

Check whether the graph evidences a claim (grounding layer).

Resolves the claim's entities, looks for supporting edge paths, and returns either cited evidence (stable edge ids) or a structured revise instruction listing the missing evidence. Contradicting relations touching the entities are surfaced.

ground_claim(claim: str) -> dict

Parameter Type Default Description
claim str Natural-language claim to check.

Returns: dict — A grounding result dict (decision: grounded | revise) or {"error": ...}.

Method GraphIndexToolkit.extract_knowledge

Extract typed entities/relations from text into the graph.

Runs a schema-constrained LLM extraction, deduplicates entities against the existing graph (additive alias merges — nothing is destroyed), publishes ONE audited commit, and mirrors the new nodes/edges into the in-memory graph so they are immediately searchable.

Requires both a client (LLM) and a publisher (durable plane) on the toolkit.

extract_knowledge(text: str, source_uri: str = '') -> dict

Parameter Type Default Description
text str Free text to extract knowledge from.
source_uri str '' Citation URI recorded on the extracted items.

Returns: dict — {entities, relations, commit_id, node_ids} or {"error": ...}.

Method GraphIndexToolkit.relevance

Decomposed five-signal relevance between two nodes (FEAT-190).

Returns {direct, source_overlap, adamic_adar, type_affinity, embedding, combined, direct_edges, shared_sources, aa_neighbours, embedding_available} or {"error": "FEAT-190 not available"}.

relevance(node_a: str, node_b: str) -> dict

Parameter Type Default Description
node_a str
node_b str

Returns: dict

Method GraphIndexToolkit.neighborhood_by_relevance

Top-K nodes most relevant to node_id by combined signal score.

neighborhood_by_relevance(node_id: str, top_k: int = 10) -> list[dict]

Parameter Type Default Description
node_id str
top_k int 10

Returns: list[dict]

Method GraphIndexToolkit.list_communities

FEAT-191 Louvain communities, filtered by minimum size.

The result is cached until any write tool runs. Repeated calls do not re-run Louvain.

list_communities(min_size: int = 2) -> list[dict]

Parameter Type Default Description
min_size int 2

Returns: list[dict]

Method GraphIndexToolkit.find_community

Return the Community containing node_id (FEAT-191).

find_community(node_id: str) -> dict

Parameter Type Default Description
node_id str

Returns: dict

Method GraphIndexToolkit.search_with_expansion

Search with graph-expanded retrieval: seeds → graph expansion → result assembly.

Runs the full 4-phase GraphExpandedRetriever pipeline using the toolkit's stored graph, embedder, and signal configuration.

Phase 1 uses the GraphIndexEmbedder (FAISS) for seed search. Phase 2 expands N hops with exponential score decay. Phase 3 community annotation is skipped — pass a CommunitiesResult to GraphExpandedRetriever directly if community context is needed. Phase 4 applies a token budget and sorts results by combined score.

search_with_expansion(query: str, seed_top_k: int = 10, max_hops: int = 2, decay_base: float = 0.7, max_tokens: int = 8000) -> dict

Parameter Type Default Description
query str Natural language search query.
seed_top_k int 10 Number of seed nodes from the initial FAISS search.
max_hops int 2 Maximum graph traversal depth (1–4).
decay_base float 0.7 Score decay per hop (0–1, default 0.7).
max_tokens int 8000 Token budget for the returned result set.

Returns: dict — Dictionary representation of a GraphRetrievalResult with keys: query, nodes, total_candidates, nodes_expanded, communities_touched, budget_used, budget_limit, truncated.

Method GraphIndexToolkit.find_isolated_nodes

Find nodes with few connections — potential knowledge gaps.

Returns nodes with total degree (in + out) <= max_degree. DOCUMENT root nodes are excluded by default as they are structural anchors.

find_isolated_nodes(max_degree: int = 1) -> list[dict]

Parameter Type Default Description
max_degree int 1 Maximum total degree for a node to be considered isolated. Defaults to 1.

Returns: list[dict] — List of dicts with node_id, title, kind, degree.

Method GraphIndexToolkit.find_sparse_communities

Find Louvain communities with low internal cohesion.

Communities that are large enough to be meaningful but poorly connected internally represent areas where knowledge is fragmented.

find_sparse_communities(min_size: int = 3, max_cohesion: float = 0.15) -> list[dict]

Parameter Type Default Description
min_size int 3 Minimum number of community members. Defaults to 3.
max_cohesion float 0.15 Maximum cohesion threshold (exclusive). Defaults to 0.15.

Returns: list[dict] — List of dicts with community_id, size, cohesion, top_titles. Returns [{"error": ...}] if communities are not available.

Method GraphIndexToolkit.find_bridge_nodes

Find nodes that bridge multiple distinct communities.

Bridge nodes are critical connectors spanning at least min_communities distinct Louvain communities. They represent important cross-domain knowledge links.

find_bridge_nodes(min_communities: int = 3) -> list[dict]

Parameter Type Default Description
min_communities int 3 Minimum number of neighbor communities for a node to be classified as a bridge. Defaults to 3.

Returns: list[dict] — List of dicts with node_id, title, kind, community_count, neighbor_community_ids. Returns [{"error": ...}] if communities are not available.

Method GraphIndexToolkit.dismiss_insight

Mark an insight as dismissed so it won't appear in future reports.

The dismissal is persisted in a cached AnalyticsResult for the lifetime of this toolkit instance (session-scoped).

dismiss_insight(insight_id: str) -> dict

Parameter Type Default Description
insight_id str The stable insight ID to dismiss. Conventions: "surprise:<src>:<tgt>", "isolated:<node_id>", "sparse:<community_id>", "bridge:<node_id>".

Returns: dict — Dict with dismissed (the ID) and total_dismissed (count).

Method GraphIndexToolkit.list_unreviewed_insights

List all insights not yet dismissed.

Aggregates surprising connections and knowledge gap entries (isolated nodes, sparse communities, bridge nodes) and filters out any that have been dismissed via dismiss_insight.

list_unreviewed_insights() -> list[dict]

Returns: list[dict] — List of insight dicts, each with an id field and the original insight data. Empty list when no insights remain or analytics is unavailable.

Attribute logger

Architecture

Clients

Bots & Agents

Memory

Knowledge

Tools & Toolkits

Flows

Experts

Skills

Stores & Loaders

MCP & A2A

Server & APIs

Integrations

Outputs & A2UI

Prompts

Security

Operations

Migration

SDD Tooling

LLM Wiki

Deployment

Decisions

API Reference

Clone this wiki locally