graph

package
v0.100.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 19, 2026 License: MIT Imports: 9 Imported by: 0

README

AI Knowledge Graph (ai/graph)

The graph package is responsible for building a Personal Knowledge Graph (PKG), connecting fragmented Memos into a structured network.

Architecture

The graph consists of Nodes and Edges, supporting multiple types of relationships.

classDiagram
    class KnowledgeGraph {
        +Nodes []GraphNode
        +Edges []GraphEdge
        +Stats GraphStats
    }
    class GraphBuilder {
        -store Store
        -embedding EmbeddingService
        +Build(ctx, userID)
    }
    class GraphNode {
        +ID string
        +Label string
        +Type string
        +Tags []string
        +Cluster int
        +Importance float64
    }
    class GraphEdge {
        +Source string
        +Target string
        +Type string
        +Weight float64
    }

    GraphBuilder ..> KnowledgeGraph : builds
    KnowledgeGraph *-- GraphNode
    KnowledgeGraph *-- GraphEdge
Data Structures
  • Nodes: Represent Memo or Tag. Include Importance and Cluster properties.
  • Edges:
    • Link: Explicit reference (bidirectional [[WikiLink]]).
    • Tag Co-occurrence: Tag co-occurrence relationship.
    • Semantic: Vector semantic similarity relationship.

Algorithm

1. Building Process (Build)
flowchart TD
    Start[Build Start] --> FetchMemos[Fetch All User Memos]
    FetchMemos --> Nodes[Generate Node List]

    Nodes --> LinkEdges[Build Link Edges (DB Relations)]
    Nodes --> TagEdges[Build Tag Edges (Jaccard)]
    Nodes --> SemEdges[Build Semantic Edges (Vector Search)]

    LinkEdges & TagEdges & SemEdges --> Merge[Merge Edge Sets]

    Merge --> Pagerank[Calculate PageRank Importance]
    Merge --> Community[Calculate Community Clustering]

    Pagerank & Community --> Final[Output KnowledgeGraph]
  1. Node Generation: Load all user Memos.
  2. Edge Generation:
    • Link Edges: Parse MemoRelation table from database.
    • Tag Edges: Calculate Jaccard similarity between tag sets of any two notes, connect if exceeds threshold.
    • Semantic Edges: For each node, perform Vector Search to find Top-K similar nodes, connect if exceeds threshold.
2. Graph Analysis Algorithms

After graph construction, run graph algorithms to extract insights:

  • PageRank: Calculate node importance score. Notes that are referenced more and connected to important nodes get higher scores. Used to control node size in visualization.
  • Community Detection: Use simplified Label Propagation algorithm to divide nodes into different clusters. Used to color nodes in visualization, showing knowledge topic distribution.

Filtering

The GraphFilter supports filtering the graph for visualization:

Filter Description
StartDate Filter by start date
EndDate Filter by end date
Tags Filter by tags
Clusters Filter by cluster IDs
MinImportance Filter by minimum importance

Configuration

Config Default Description
EnablePageRank true Enable PageRank calculation
EnableCommunityDetection true Enable community detection
MinTagSimilarity 0.3 Minimum tag similarity threshold
MinSemanticSimilarity 0.7 Minimum semantic similarity threshold
MaxSemanticEdgesPerNode 5 Maximum semantic edges per node

Business Flow

  1. Frontend requests "Knowledge Graph" view.
  2. Backend builds graph in real-time or from cache.
  3. Apply filter (ApplyFilter): Filter subgraph by time range, tags, importance threshold.
  4. Frontend uses D3.js or other libraries to render Force-Directed Graph.

Documentation

Overview

Package graph - builder implementation for P3-C001.

Package graph provides knowledge graph construction for P3-C001.

Index

Constants

View Source
const (
	EdgeTypeLink     = "link"     // explicit user-created link
	EdgeTypeTagCo    = "tag_co"   // tag co-occurrence
	EdgeTypeSemantic = "semantic" // semantic similarity
)

EdgeType constants.

View Source
const (
	NodeTypeMemo = "memo"
	NodeTypeTag  = "tag"
)

NodeType constants.

Variables

This section is empty.

Functions

This section is empty.

Types

type GraphBuilder

type GraphBuilder struct {
	// contains filtered or unexported fields
}

GraphBuilder builds knowledge graphs from memos.

func NewGraphBuilder

func NewGraphBuilder(s *store.Store, embedding ai.EmbeddingService, model string) *GraphBuilder

NewGraphBuilder creates a new GraphBuilder.

func NewGraphBuilderWithConfig

func NewGraphBuilderWithConfig(s *store.Store, embedding ai.EmbeddingService, model string, config GraphConfig) *GraphBuilder

NewGraphBuilderWithConfig creates a builder with custom config.

func (*GraphBuilder) Build

func (b *GraphBuilder) Build(ctx context.Context, userID int32) (*KnowledgeGraph, error)

Build constructs the knowledge graph for a user.

func (*GraphBuilder) GetFilteredGraph

func (b *GraphBuilder) GetFilteredGraph(ctx context.Context, userID int32, filter GraphFilter) (*KnowledgeGraph, error)

GetFilteredGraph returns a filtered view of the graph.

func (*GraphBuilder) GetGraph

func (b *GraphBuilder) GetGraph(ctx context.Context, userID int32) (*KnowledgeGraph, error)

GetGraph retrieves a cached graph or builds a new one.

type GraphConfig

type GraphConfig struct {
	// MinTagSimilarity is the minimum Jaccard similarity between tag sets to create an edge.
	MinTagSimilarity float64
	// MinSemanticSimilarity is the minimum similarity score for semantic edges.
	MinSemanticSimilarity float64
	// MaxSemanticEdgesPerNode limits semantic edges per node.
	MaxSemanticEdgesPerNode int
	// EnableCommunityDetection enables Louvain community detection.
	EnableCommunityDetection bool
	// EnablePageRank enables PageRank importance calculation.
	EnablePageRank bool
}

GraphConfig contains configuration for graph building.

func DefaultConfig

func DefaultConfig() GraphConfig

DefaultConfig returns default graph configuration.

type GraphEdge

type GraphEdge struct {
	Source string  `json:"source"`
	Target string  `json:"target"`
	Type   string  `json:"type"`   // "link", "tag_co", "semantic"
	Weight float64 `json:"weight"` // 0-1, higher = stronger connection
}

GraphEdge represents an edge in the knowledge graph.

type GraphFilter

type GraphFilter struct {
	StartDate     *time.Time
	EndDate       *time.Time
	Tags          []string
	Clusters      []int
	MinImportance float64
}

GraphFilter contains filter criteria for graph visualization.

type GraphNode

type GraphNode struct {
	CreatedAt  time.Time `json:"created_at"`
	ID         string    `json:"id"`
	Label      string    `json:"label"`
	Type       string    `json:"type"`
	Tags       []string  `json:"tags,omitempty"`
	Importance float64   `json:"importance"`
	Cluster    int       `json:"cluster"`
	X          float64   `json:"x,omitempty"`
	Y          float64   `json:"y,omitempty"`
}

GraphNode represents a node in the knowledge graph.

type GraphStats

type GraphStats struct {
	NodeCount     int `json:"node_count"`
	EdgeCount     int `json:"edge_count"`
	ClusterCount  int `json:"cluster_count"`
	LinkEdges     int `json:"link_edges"`
	TagEdges      int `json:"tag_edges"`
	SemanticEdges int `json:"semantic_edges"`
}

GraphStats contains graph statistics.

type KnowledgeGraph

type KnowledgeGraph struct {
	Nodes   []GraphNode `json:"nodes"`
	Edges   []GraphEdge `json:"edges"`
	Stats   GraphStats  `json:"stats"`
	BuildMs int64       `json:"build_ms"` // build latency
}

KnowledgeGraph represents the complete graph structure.

func ApplyFilter

func ApplyFilter(graph *KnowledgeGraph, filter GraphFilter) *KnowledgeGraph

ApplyFilter filters the graph based on criteria.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL