Skip to main content

Python SDK: Graph & Relationships

Create relationships, traverse the knowledge graph, and extract context with the Python SDK.

Overview

Trix organizes memories in a knowledge graph, allowing you to create meaningful connections between related information. The graph and relationships resources enable you to create relationships, traverse connections, and extract contextual subgraphs.

Relationships are automatically created when memories reference each other. Use the explicit API when you need fine-grained control over the graph structure.

Relationships

Relationships connect memories to form a knowledge graph. Each relationship has a type and weight.

Create Relationship

create_relationship.py
from trix import RelationshipType

relationship = client.relationships.create(
    source_id="mem_source",
    target_id="mem_target",
    relationship_type=RelationshipType.SUPPORTS,
    weight=1.5,
    description="Both discuss Python patterns",
    bidirectional=False
)

Relationship Types

Trix supports these built-in relationship types:

TypeDescription
RELATED_TOGeneral relationship
SUPPORTSSource supports/reinforces target
CONTRADICTSSource contradicts target
DERIVED_FROMSource is derived from target
SIMILAR_TOSource is similar to target
PRECEDESSource comes before target
FOLLOWSSource follows target

Get Relationships

get_relationships.py
incoming = client.relationships.get_incoming("mem_xyz")
outgoing = client.relationships.get_outgoing("mem_xyz")

for rel in outgoing:
    print(f"{rel.relationship_type} -> {rel.target_id} (weight: {rel.weight})")

Update and Reinforce

update_relationship.py
client.relationships.update(
    "rel_abc",
    weight=2.0,
    description="Updated description"
)

client.relationships.reinforce(
    "rel_abc",
    boost=0.5,
    context="User found this helpful"
)

Delete Relationship

delete_relationship.py
client.relationships.delete("rel_abc")

Graph Traversal

The graph resource provides advanced knowledge graph traversal and context retrieval operations.

Traverse Graph

traverse_graph.py
from trix import Direction, RelationshipType

result = client.graph.traverse(
    start_ids=["mem_xyz"],
    depth=3,
    direction=Direction.BOTH,
    relationship_types=[
        RelationshipType.RELATED_TO,
        RelationshipType.SUPPORTS
    ]
)

for node in result.nodes:
    print(f"Depth {node.depth}: {node.memory.id}")
    for rel in node.relationships:
        print(f"  -> {rel.target_id}")

Traversal Options

ParameterTypeDescription
start_idsList[str]Starting memory IDs
depthintMaximum traversal depth (1-5)
directionDirectionOUTGOING, INCOMING, or BOTH
relationship_typesList[RelationshipType]Filter by relationship types

Get Context

Retrieve contextual information around a query:

get_context.py
context = client.graph.get_context(
    query="Python memory management",
    depth=2,
    semantic_limit=10
)

print(f"Query: {context.query}")
print(f"Found {len(context.memories)} related memories")

for memory, score in zip(context.memories, context.relevance_scores):
    print(f"  {score:.2f}: {memory.content[:50]}...")

Context Options

ParameterTypeDescription
querystrNatural language query
depthintGraph traversal depth
semantic_limitintMax memories from semantic search

Find Shortest Path

shortest_path.py
path = client.graph.shortest_path(
    source_id="mem_source",
    target_id="mem_target",
    max_hops=5
)

if path.distance > 0:
    print(f"Path found with distance: {path.distance}")
    for i, memory_id in enumerate(path.path):
        print(f"  {i + 1}. {memory_id}")
        if i < len(path.relationships):
            print(f"     via {path.relationships[i].relationship_type}")
else:
    print("No path found between memories")

Path Algorithms

AlgorithmDescription
shortestFewest hops between nodes
weighted_shortestHighest total edge weight
allAll paths up to max_length

Agent Sessions

The agent resource manages sessions for AI agent interactions, providing context management and memory consolidation.

Session Management

session_management.py
session = client.agent.create_session(
    session_id="chat_123",
    space_id="space_support",
    metadata={
        "user_id": "user_456",
        "channel": "web"
    }
)

result = client.agent.get_session(
    session_id="chat_123",
    limit=50,
    offset=0
)
print(f"Session has {result.total} memories")

sessions = client.agent.list_sessions(
    limit=20,
    space_id="space_support"
)

for session in sessions.data:
    print(f"{session.session_id}: {session.created_at}")

Add Session Memory

session_memory.py
memory = client.agent.add_session_memory(
    session_id="chat_123",
    content="User asked about pricing plans",
    role="user",
    importance=0.8
)

client.agent.add_session_memory(
    session_id="chat_123",
    content="Our pricing starts at $10/month...",
    role="assistant",
    importance=0.7
)

Get Agent Context

agent_context.py
context = client.agent.get_context(
    query="What are the pricing tiers?",
    session_id="chat_123",
    limit=5
)

for memory, score in zip(context.memories, context.relevance_scores):
    print(f"Relevant ({score:.2f}): {memory.content}")

End Session

end_session.py
result = client.agent.end_session(
    session_id="chat_123",
    summary="User inquired about pricing and signed up for Pro plan",
    key_insights=["User is price-sensitive", "Interested in team features"]
)

Complete Example

Here's an example showing how to build a knowledge graph:

graph_example.py
from trix import Trix, MemoryType, RelationshipType

with Trix.from_env() as client:
    mem1 = client.memories.create(
        content="Python is a high-level programming language",
        type=MemoryType.TEXT,
        tags=["python", "programming"]
    )
    mem2 = client.memories.create(
        content="Python is excellent for data science and ML",
        type=MemoryType.TEXT,
        tags=["python", "data-science"]
    )
    mem3 = client.memories.create(
        content="Pandas is a Python library for data manipulation",
        type=MemoryType.TEXT,
        tags=["python", "pandas"]
    )

    client.relationships.create(
        source_id=mem1.id, target_id=mem2.id,
        relationship_type=RelationshipType.RELATED_TO, weight=0.9
    )
    client.relationships.create(
        source_id=mem2.id, target_id=mem3.id,
        relationship_type=RelationshipType.SUPPORTS, weight=0.85
    )

    result = client.graph.traverse(start_ids=[mem1.id], depth=2)
    print(f"Found {len(result.nodes)} connected memories")

    context = client.graph.get_context(query="Python data analysis", depth=2)
    print(f"Context includes {len(context.memories)} memories")