# Graph RAG
[EN] Source: https://mastra.ai/examples/rag/usage/graph-rag

This example demonstrates how to implement a Retrieval-Augmented Generation (RAG) system using Mastra, OpenAI embeddings, and PGVector for vector storage.

## Overview

The system implements Graph RAG using Mastra and OpenAI. Here's what it does:

1. Sets up a Mastra agent with gpt-4o-mini for response generation
2. Creates a GraphRAG tool to manage vector store interactions and knowledge graph creation/traversal
3. Chunks text documents into smaller segments
4. Creates embeddings for these chunks
5. Stores them in a PostgreSQL vector database
6. Creates a knowledge graph of relevant chunks based on queries using GraphRAG tool
   - Tool returns results from vector store and creates knowledge graph
   - Traverses knowledge graph using query
7. Generates context-aware responses using the Mastra agent

## Setup

### Environment Setup

Make sure to set up your environment variables:

```bash title=".env"
OPENAI_API_KEY=your_openai_api_key_here
POSTGRES_CONNECTION_STRING=your_connection_string_here
```

### Dependencies

Then, import the necessary dependencies:

```typescript copy showLineNumbers title="index.ts"
import { openai } from "@ai-sdk/openai";
import { Mastra } from "@mastra/core";
import { Agent } from "@mastra/core/agent";
import { PgVector } from "@mastra/pg";
import { MDocument, createGraphRAGTool } from "@mastra/rag";
import { embedMany } from "ai";
```

## GraphRAG Tool Creation

Using createGraphRAGTool imported from @mastra/rag, you can create a tool that queries the vector database and converts the results into a knowledge graph:

```typescript copy showLineNumbers{8} title="index.ts"
const graphRagTool = createGraphRAGTool({
  vectorStoreName: "pgVector",
  indexName: "embeddings",
  model: openai.embedding("text-embedding-3-small"),
  graphOptions: {
    dimension: 1536,
    threshold: 0.7,
  },
});
```

## Agent Configuration

Set up the Mastra agent that will handle the responses:

```typescript copy showLineNumbers{19} title="index.ts"
const ragAgent = new Agent({
  name: "GraphRAG Agent",
  instructions: `You are a helpful assistant that answers questions based on the provided context. Format your answers as follows:

1. DIRECT FACTS: List only the directly stated facts from the text relevant to the question (2-3 bullet points)
2. CONNECTIONS MADE: List the relationships you found between different parts of the text (2-3 bullet points)
3. CONCLUSION: One sentence summary that ties everything together

Keep each section brief and focus on the most important points.

Important: When asked to answer a question, please base your answer only on the context provided in the tool. 
If the context doesn't contain enough information to fully answer the question, please state that explicitly.`,
  model: openai("gpt-4o-mini"),
  tools: {
    graphRagTool,
  },
});
```

## Instantiate PgVector and Mastra

Instantiate PgVector and Mastra with the components:

```typescript copy showLineNumbers{36} title="index.ts"
const pgVector = new PgVector({
  connectionString: process.env.POSTGRES_CONNECTION_STRING!,
});

export const mastra = new Mastra({
  agents: { ragAgent },
  vectors: { pgVector },
});
const agent = mastra.getAgent("ragAgent");
```

## Document Processing

Create a document and process it into chunks:

```typescript copy showLineNumbers{45} title="index.ts"
const doc = MDocument.fromText(`