0
0
LangChainframework~5 mins

Graph nodes and edges in LangChain

Choose your learning style9 modes available
Introduction

Graphs help us show connections between things. Nodes are the things, and edges are the links between them.

To model social networks where people (nodes) are friends (edges).
To represent maps where places (nodes) are connected by roads (edges).
To organize tasks where some tasks depend on others.
To analyze relationships in data like web pages linking to each other.
To build recommendation systems showing related items.
Syntax
LangChain
class Node:
    def __init__(self, value):
        self.value = value
        self.edges = []  # list of connected nodes

    def add_edge(self, node):
        self.edges.append(node)

# Example of creating nodes and connecting them
node1 = Node('A')
node2 = Node('B')
node1.add_edge(node2)

Each Node holds a value and a list of edges to other nodes.

The add_edge method connects one node to another.

Examples
Example of a node with no connections (edges).
LangChain
node_empty = Node('Empty')
# This node has no edges yet
Node connected to exactly one other node.
LangChain
node_single = Node('Single')
node_other = Node('Other')
node_single.add_edge(node_other)
# Node with one edge
Shows edges going both directions between two nodes.
LangChain
node_start = Node('Start')
node_end = Node('End')
node_start.add_edge(node_end)
node_end.add_edge(node_start)
# Nodes connected both ways (bidirectional edge)
Sample Program

This program creates three nodes A, B, and C. It connects them in a circle. Then it adds an extra edge from A to C. It prints the connections before and after to show the changes.

LangChain
class Node:
    def __init__(self, value):
        self.value = value
        self.edges = []

    def add_edge(self, node):
        self.edges.append(node)

    def __str__(self):
        connected_values = [node.value for node in self.edges]
        return f"Node {self.value} connected to: {connected_values}"

# Create nodes
node_a = Node('A')
node_b = Node('B')
node_c = Node('C')

# Connect nodes
node_a.add_edge(node_b)
node_b.add_edge(node_c)
node_c.add_edge(node_a)

# Print connections before adding new edge
print(node_a)
print(node_b)
print(node_c)

# Add new edge from A to C
node_a.add_edge(node_c)

# Print connections after adding new edge
print('\nAfter adding edge from A to C:')
print(node_a)
print(node_b)
print(node_c)
OutputSuccess
Important Notes

Adding an edge takes constant time O(1) because it just appends to a list.

Each node stores its edges, so space grows with number of connections.

Common mistake: forgetting to connect both nodes if you want a two-way link.

Use edges to represent relationships; use nodes to represent entities.

Summary

Graphs use nodes and edges to show connections.

Nodes hold data and a list of edges to other nodes.

Edges connect nodes and can be one-way or two-way.