Skip to main content

TypeScript SDK: Graph & Relationships

Build knowledge graphs with relationships, traversal, and context extraction.

Overview

Relationships connect memories to form a knowledge graph. Each relationship has a type and strength. The graph resource provides advanced knowledge graph traversal and context retrieval operations.

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

Create Relationship

create-relationship.ts
const relationship = await trix.relationships.create(
  'mem_source',
  'mem_target',
  {
    relationshipType: 'related_to',
    strength: 0.8,
    metadata: {
      reason: 'Both discuss TypeScript patterns'
    }
  }
);

Relationship Types

Trix supports 12 built-in relationship types:

TypeDescription
related_toGeneral relationship
supportsSource supports/reinforces target
contradictsSource contradicts target
causesSource causes target
precedesSource comes before target
followsSource follows target
containsSource contains target
part_ofSource is part of target
referencesSource references target
derived_fromSource is derived from target
similar_toSource is similar to target
opposite_ofSource is opposite of target

Get Relationships

get-relationships.ts
const incoming = await trix.relationships.getIncoming('mem_xyz');
const outgoing = await trix.relationships.getOutgoing('mem_xyz');

for (const rel of outgoing) {
  console.log(`${rel.relationshipType} -> ${rel.targetId} (strength: ${rel.strength})`);
}

Update and Reinforce

update-relationship.ts
await trix.relationships.update('rel_abc', {
  strength: 0.9,
  metadata: { reviewed: true }
});

await trix.relationships.reinforce('rel_abc', {
  amount: 0.1
});

Delete Relationship

delete-relationship.ts
await trix.relationships.delete('rel_abc');

Graph Traversal

Traverse the knowledge graph to discover connected memories across multiple hops:

traverse-graph.ts
const result = await trix.graph.traverse({
  startNodeId: 'mem_xyz',
  maxDepth: 3,
  direction: 'both',
  relationshipTypes: ['related_to', 'supports'],
  limit: 50
});

for (const node of result.nodes) {
  console.log(`Depth ${node.depth}: ${node.id}`);
}

for (const edge of result.edges) {
  console.log(`${edge.source} -> ${edge.target}`);
}

Traversal Options

OptionTypeDefaultDescription
startNodeIdstringrequiredStarting memory ID
maxDepthnumber2Maximum traversal depth (1-5)
directionstring'both''incoming', 'outgoing', 'both'
relationshipTypesstring[]allFilter by relationship types
limitnumber100Maximum nodes to return

Get Context

Retrieve a memory with its full context:

get-context.ts
const context = await trix.graph.getContext({
  memoryId: 'mem_xyz',
  depth: 2,
  relationshipTypes: ['related_to', 'supports'],
  includeMetadata: true
});

console.log('Central memory:', context.central.content);
console.log('Related memories:', context.related.length);
console.log('Relationships:', context.relationships.length);
console.log('Clusters:', context.clusters?.length);

Context extraction is perfect for providing relevant background information to LLMs when generating responses.

Find Shortest Path

Find the shortest path between two memories:

shortest-path.ts
const path = await trix.graph.shortestPath(
  'mem_source',
  'mem_target',
  {
    relationshipTypes: ['related_to'],
    maxDepth: 5
  }
);

if (path.found) {
  console.log(`Path found with distance: ${path.distance}`);
  for (const step of path.path) {
    console.log(`  ${step.node.id}`);
    if (step.relationship) {
      console.log(`    via ${step.relationship.relationshipType}`);
    }
  }
} else {
  console.log('No path found between memories');
}

Agent Sessions

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

Session Management

session-management.ts
const session = await trix.agent.createSession({
  name: 'Customer Support Chat',
  spaceId: 'space_support',
  metadata: {
    userId: 'user_123',
    channel: 'web'
  }
});

console.log('Session ID:', session.id);

const { session: sess, memories } = await trix.agent.getSession(session.id, {
  includeMemories: true,
  limit: 50
});

const { data } = await trix.agent.listSessions({
  active: true,
  spaceId: 'space_support'
});

for await (const s of trix.agent.listSessionsAll({ active: true })) {
  console.log(s.name, s.memoryCount);
}

Add Session Memory

session-memory.ts
await trix.agent.addSessionMemory(session.id, {
  memoryId: 'mem_existing'
});

const sessionMemory = await trix.agent.addSessionMemory(session.id, {
  content: 'User asked about pricing plans',
  type: 'text',
  tags: ['question', 'pricing'],
  metadata: {
    role: 'user'
  }
});

Get Agent Context

agent-context.ts
const context = await trix.agent.getContext({
  sessionId: session.id,
  query: 'What are the pricing tiers?',
  limit: 5,
  includeRelated: true
});

for (const memory of context.memories) {
  console.log('Relevant:', memory.content);
}

End Session

end-session.ts
const result = await trix.agent.endSession(session.id, {
  consolidate: true,
  metadata: {
    outcome: 'resolved',
    satisfaction: 5
  }
});

if (result.consolidationJobId) {
  console.log('Consolidation job:', result.consolidationJobId);
}

Webhooks

Webhooks notify your application when events occur in Trix.

Create Webhook

create-webhook.ts
const webhook = await trix.webhooks.create({
  url: 'https://api.yourapp.com/trix-webhook',
  events: [
    'memory.created',
    'memory.updated',
    'memory.deleted',
    'relationship.created',
    'cluster.created',
    'session.ended'
  ],
  secret: 'your_32_byte_secret',
  active: true,
  metadata: {
    environment: 'production'
  }
});

Available Events

  • memory.created, memory.updated, memory.deleted
  • relationship.created, relationship.updated, relationship.deleted
  • cluster.created, cluster.updated, cluster.deleted
  • session.created, session.ended

Test and Monitor

test-webhook.ts
const test = await trix.webhooks.test('whk_abc', 'memory.created');
console.log('Test result:', test.success, test.statusCode);

const { data: deliveries } = await trix.webhooks.getDeliveries('whk_abc', {
  status: 'failed',
  limit: 10
});

await trix.webhooks.retryDelivery('whk_abc', 'del_xyz');

Manage Webhooks

manage-webhooks.ts
for await (const webhook of trix.webhooks.listAll()) {
  console.log(webhook.url, webhook.events);
}

await trix.webhooks.update('whk_abc', {
  events: ['memory.created'],
  active: false
});

await trix.webhooks.delete('whk_abc');