> ## Documentation Index
> Fetch the complete documentation index at: https://docs.praison.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Graph RAG

> Give Agents relationship-aware knowledge with Graph RAG

# Graph RAG for Agents

Graph RAG enables Agents to understand relationships between concepts, not just find similar documents. Your Agent can traverse connections like "TypeScript extends JavaScript" or "Function A calls Function B".

## Agent with Graph Knowledge

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, createGraphRAG } from 'praisonai';

const graphRag = createGraphRAG();

// Build knowledge graph
await graphRag.addDocument({ id: 'ts', content: 'TypeScript is a typed superset of JavaScript', type: 'language' });
await graphRag.addDocument({ id: 'js', content: 'JavaScript is a programming language for the web', type: 'language' });
graphRag.addRelationship('ts', 'js', 'extends');

// Agent with graph-aware knowledge
const agent = new Agent({
  name: 'Tech Expert',
  instructions: 'Answer questions using the knowledge graph. Follow relationships to provide complete answers.',
  knowledge: { graphRag }
});

// Agent understands relationships
const response = await agent.chat('How is TypeScript related to JavaScript?');
// Agent can traverse: TypeScript -> extends -> JavaScript
```

## Agent with Graph Search Tool

Give your Agent the ability to explore the knowledge graph:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, createTool, createGraphRAG } from 'praisonai';

const graphRag = createGraphRAG();

// Tool for Agent to search the graph
const searchGraph = createTool({
  name: 'search_knowledge_graph',
  description: 'Search the knowledge graph and find related concepts',
  parameters: {
    type: 'object',
    properties: {
      query: { type: 'string', description: 'What to search for' },
      depth: { type: 'number', description: 'How many relationship hops to follow (1-3)' }
    },
    required: ['query']
  },
  execute: async ({ query, depth = 2 }) => {
    const results = await graphRag.query(query, { maxDepth: depth, maxNodes: 10 });
    return graphRag.getContext(results);
  }
});

const agent = new Agent({
  name: 'Research Agent',
  instructions: 'Use the knowledge graph to find information and understand relationships between concepts.',
  tools: [searchGraph]
});

const response = await agent.chat('What technologies are related to React?');
```

## Agent that Builds Knowledge Graphs

An Agent can extract entities and relationships from text:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, createGraphRAG, createTool } from 'praisonai';

const graphRag = createGraphRAG();

// Entity extraction Agent
const extractorAgent = new Agent({
  name: 'Entity Extractor',
  instructions: `Extract entities and relationships from text.
Return JSON: { "entities": [{"id": "...", "type": "...", "name": "..."}], "relationships": [{"source": "...", "target": "...", "type": "..."}] }`
});

// Tool to add extracted knowledge
const learnFromText = createTool({
  name: 'learn_from_text',
  description: 'Extract entities and relationships from text and add to knowledge graph',
  parameters: {
    type: 'object',
    properties: {
      text: { type: 'string', description: 'Text to learn from' }
    },
    required: ['text']
  },
  execute: async ({ text }) => {
    const extraction = await extractorAgent.chat(text);
    const { entities, relationships } = JSON.parse(extraction);
    
    for (const entity of entities) {
      await graphRag.addDocument({
        id: entity.id,
        content: entity.name,
        type: entity.type
      });
    }
    
    for (const rel of relationships) {
      graphRag.addRelationship(rel.source, rel.target, rel.type);
    }
    
    return `Learned ${entities.length} entities and ${relationships.length} relationships`;
  }
});

// Learning Agent
const learningAgent = new Agent({
  name: 'Learning Agent',
  instructions: 'Read documents and build a knowledge graph from them.',
  tools: [learnFromText]
});

await learningAgent.chat('Learn from this: "React is a JavaScript library created by Facebook. It uses JSX syntax and virtual DOM."');
```

## Multi-Agent Knowledge Graph System

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, Agents, createGraphRAG } from 'praisonai';

const graphRag = createGraphRAG();

// Agent 1: Extracts entities
const extractor = new Agent({
  name: 'Extractor',
  instructions: 'Extract key entities and their relationships from the given text.',
  outputFormat: 'json'
});

// Agent 2: Queries the graph
const researcher = new Agent({
  name: 'Researcher', 
  instructions: 'Search the knowledge graph to answer questions.',
  knowledge: { graphRag }
});

// Agent 3: Synthesizes answers
const synthesizer = new Agent({
  name: 'Synthesizer',
  instructions: 'Create comprehensive answers from the research findings.'
});

const agents = new AgentTeam({
  agents: [extractor, researcher, synthesizer],
  tasks: [
    { agent: extractor, description: 'Extract entities from: {document}' },
    { agent: researcher, description: 'Find related information for: {query}' },
    { agent: synthesizer, description: 'Write a complete answer based on the research' }
  ]
});

await agents.start({ 
  document: 'Technical documentation...',
  query: 'How do these components interact?'
});
```

## Code Analysis Agent

An Agent that understands code structure:

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
import { Agent, createGraphRAG, createTool } from 'praisonai';

const codeGraph = createGraphRAG();

// Tool to analyze code dependencies
const analyzeCode = createTool({
  name: 'analyze_code',
  description: 'Analyze code and build a dependency graph',
  parameters: {
    type: 'object',
    properties: {
      code: { type: 'string', description: 'Code to analyze' },
      filename: { type: 'string', description: 'File name' }
    },
    required: ['code', 'filename']
  },
  execute: async ({ code, filename }) => {
    // Add file as node
    await codeGraph.addDocument({
      id: filename,
      content: code,
      type: 'file'
    });
    
    // Extract imports and add relationships
    const imports = code.match(/import .+ from ['"](.+)['"]/g) || [];
    for (const imp of imports) {
      const match = imp.match(/from ['"](.+)['"]/);
      if (match) {
        codeGraph.addRelationship(filename, match[1], 'imports');
      }
    }
    
    return `Analyzed ${filename} with ${imports.length} imports`;
  }
});

const codeAgent = new Agent({
  name: 'Code Analyst',
  instructions: 'Analyze code structure and answer questions about dependencies.',
  tools: [analyzeCode],
  knowledge: { graphRag: codeGraph }
});

await codeAgent.chat('Analyze this code and tell me what it depends on');
```

## Configuration

```typescript theme={"theme":{"light":"vitesse-light","dark":"vitesse-dark"}}
const graphRag = createGraphRAG({
  embedFn: async (text) => await getEmbedding(text),  // Optional: for similarity search
  maxDepth: 2,      // How many hops to traverse
  maxNodes: 10,     // Max nodes to return
  minScore: 0.3     // Min similarity threshold
});
```

## Use Cases for Agents

| Use Case          | Agent Capability                             |
| ----------------- | -------------------------------------------- |
| **Document Q\&A** | Navigate related documents via relationships |
| **Code Analysis** | Understand function/class dependencies       |
| **Research**      | Follow citation networks and references      |
| **Support Bots**  | Connect symptoms → causes → solutions        |

## Related

* [Vector Stores](/docs/js/vector-stores) - Similarity-based Agent knowledge
* [Reranking](/docs/js/reranking) - Improve Agent retrieval accuracy
* [Knowledge Base](/docs/js/knowledge-base) - Combined RAG for Agents
