diff --git a/genai-tools/index.md b/genai-tools/index.md index 86220065..19e0953c 100644 --- a/genai-tools/index.md +++ b/genai-tools/index.md @@ -20,7 +20,7 @@ FalkorDB provides powerful tools and integrations for building intelligent GenAI - [GraphRAG-SDK](./graphrag-sdk.md): Build intelligent GraphRAG applications with FalkorDB and LLMs. - [AG2](./ag2.md): Build multi-agent AI systems with AG2 (formerly AutoGen) and FalkorDB GraphRAG. -- [LangChain](./langchain.md): Integration with LangChain for AI agents with memory. +- [LangChain](./langchain.md): Integration with LangChain for AI agents with memory (Python and JavaScript/TypeScript). - [LangGraph](./langgraph.md): Build stateful, multi-actor agentic applications with LangGraph. - [LlamaIndex](./llamaindex.md): Simplify development of LLM-powered applications with LlamaIndex. - [GraphRAG Toolkit](./graphrag-toolkit.md): AWS GraphRAG Toolkit integration for building knowledge graph applications. diff --git a/genai-tools/langchain.md b/genai-tools/langchain.md index 14a90816..031826a8 100644 --- a/genai-tools/langchain.md +++ b/genai-tools/langchain.md @@ -9,12 +9,20 @@ parent: "GenAI Tools" FalkorDB is integrated with [LangChain](https://www.langchain.com/), bringing powerful graph database capabilities to AI-driven applications. This integration enables the creation of AI agents with memory, enhancing their ability to retain state and context across interactions. +The FalkorDB LangChain integration is available for both **Python** and **JavaScript/TypeScript** environments, making it easy to build intelligent applications in your preferred language. + ## Resources -- 🔗 [FalkorDBQAChain Documentation](https://python.langchain.com/docs/use_cases/more/graph/graph_falkordb_qa) +- 🔗 [FalkorDBQAChain Documentation (Python)](https://python.langchain.com/docs/use_cases/more/graph/graph_falkordb_qa) +- 📦 [@falkordb/langchain-ts Package (JavaScript/TypeScript)](https://www.npmjs.com/package/@falkordb/langchain-ts) +- 💻 [FalkorDB-Langchain-js Repository](https://github.com/FalkorDB/FalkorDB-Langchain-js) - 📓 [Blog: Build AI Agents with Memory – LangChain + FalkorDB](https://www.falkordb.com/blog/building-ai-agents-with-memory-langchain/) -## Installation +--- + +## Python Integration + +### Installation Install LangChain with FalkorDB support: @@ -22,9 +30,9 @@ Install LangChain with FalkorDB support: pip install langchain langchain-community falkordb ``` -## Quick Start +### Quick Start -### 1. Connect to FalkorDB +#### 1. Connect to FalkorDB ```python from langchain_community.graphs import FalkorDBGraph @@ -39,7 +47,7 @@ graph = FalkorDBGraph( ) ``` -### 2. Create a Knowledge Graph from Text +#### 2. Create a Knowledge Graph from Text ```python from langchain.chains import GraphCypherQAChain @@ -56,7 +64,7 @@ chain = GraphCypherQAChain.from_llm( ) ``` -### 3. Query the Graph +#### 3. Query the Graph ```python # Ask natural language questions @@ -68,9 +76,9 @@ response = chain.run("What other movies did they act in?") print(response) ``` -## Advanced Usage +### Advanced Usage -### Using Graph Memory for Conversational AI +#### Using Graph Memory for Conversational AI ```python from langchain.memory import ConversationGraphMemory @@ -96,7 +104,7 @@ conversation.predict(input="I work as a software engineer") conversation.predict(input="What do you know about me?") ``` -### Custom Cypher Generation +#### Custom Cypher Generation ```python from langchain.chains.graph_qa.cypher import GraphCypherQAChain @@ -131,7 +139,7 @@ chain = GraphCypherQAChain.from_llm( response = chain.run("Find all products in the electronics category") ``` -### Loading Data into the Graph +#### Loading Data into the Graph ```python from langchain_community.document_loaders import TextLoader @@ -156,7 +164,7 @@ vector_store = FalkorDBVector.from_documents( ) ``` -### Graph RAG Pattern +#### Graph RAG Pattern ```python from langchain.chains import RetrievalQA @@ -183,6 +191,162 @@ response = qa_chain.run("What are the key features of our product?") print(response) ``` +--- + +## JavaScript/TypeScript Integration + +FalkorDB also provides a JavaScript/TypeScript integration for LangChain applications through the [@falkordb/langchain-ts](https://www.npmjs.com/package/@falkordb/langchain-ts) package. + +### Installation + +```bash +npm install @falkordb/langchain-ts falkordb langchain @langchain/openai +``` + +### Quick Start (JS/TS) + +```typescript +import { FalkorDBGraph } from "@falkordb/langchain-ts"; +import { ChatOpenAI } from "@langchain/openai"; +import { GraphCypherQAChain } from "@langchain/community/chains/graph_qa/cypher"; + +// Initialize FalkorDB connection +const graph = await FalkorDBGraph.initialize({ + host: "localhost", + port: 6379, + graph: "movies" +}); + +// Set up the language model +const model = new ChatOpenAI({ temperature: 0 }); + +// Create and populate the graph +await graph.query( + "CREATE (a:Actor {name:'Bruce Willis'})" + + "-[:ACTED_IN]->(:Movie {title: 'Pulp Fiction'})" +); + +// Refresh the graph schema +await graph.refreshSchema(); + +// Create a graph QA chain +const chain = GraphCypherQAChain.fromLLM({ + llm: model, + graph: graph as any, +}); + +// Ask questions about your graph +const response = await chain.run("Who played in Pulp Fiction?"); +console.log(response); +// Output: Bruce Willis played in Pulp Fiction. + +await graph.close(); +``` + +> **Alternative Connection:** You can also connect using a URL format: +> ```typescript +> const graph = await FalkorDBGraph.initialize({ +> url: "falkor://localhost:6379", +> graph: "movies" +> }); +> ``` + +### Key Features (JS/TS) + +- **Natural Language Querying**: Convert questions to Cypher queries automatically +- **Schema Management**: Automatic schema refresh and retrieval +- **Type Safety**: Full TypeScript support with type definitions +- **Promise-based API**: Modern async/await patterns + +### API Reference (JS/TS) + +#### `FalkorDBGraph.initialize(config)` + +Create and initialize a new FalkorDB connection. + +**Config Options:** +- `host` (string): Database host (default: "localhost") +- `port` (number): Database port (default: 6379) +- `graph` (string): Graph name to use +- `url` (string): Alternative connection URL format: `falkor[s]://[[username][:password]@][host][:port][/db-number]` +- `enhancedSchema` (boolean): Enable enhanced schema details + +**Example with URL:** +```typescript +// Connect using URL format +const graph = await FalkorDBGraph.initialize({ + url: "falkor://localhost:6379", + graph: "myGraph" +}); + +// With authentication +const graph = await FalkorDBGraph.initialize({ + url: "falkor://username:password@localhost:6379", + graph: "myGraph" +}); +``` + +#### `query(query: string)` + +Execute a Cypher query on the graph. + +```typescript +const result = await graph.query( + "MATCH (n:Person) RETURN n.name LIMIT 10" +); +``` + +#### `refreshSchema()` + +Update the graph schema information. + +```typescript +await graph.refreshSchema(); +console.log(graph.getSchema()); +``` + +### Advanced Usage (JS/TS) + +#### Custom Cypher Queries + +```typescript +const graph = await FalkorDBGraph.initialize({ + host: "localhost", + port: 6379, + graph: "movies" +}); + +// Complex query +const result = await graph.query(` + MATCH (a:Actor)-[:ACTED_IN]->(m:Movie) + WHERE m.year > 2000 + RETURN a.name, m.title, m.year + ORDER BY m.year DESC + LIMIT 10 +`); + +console.log(result.data); +``` + +#### Working with Schema (JS/TS) + +```typescript +await graph.refreshSchema(); + +// Get formatted schema +const schema = graph.getSchema(); +console.log(schema); + +// Get structured schema +const structuredSchema = graph.getStructuredSchema(); +console.log(structuredSchema.nodeProps); +console.log(structuredSchema.relationships); +``` + +For more examples and source code, see the [@falkordb/langchain-ts repository](https://github.com/FalkorDB/FalkorDB-Langchain-js). + +--- + ## Use Cases - **Conversational AI with Memory**: Build chatbots that remember user context across sessions diff --git a/integration/langchain-js.md b/integration/langchain-js.md deleted file mode 100644 index 80a606ab..00000000 --- a/integration/langchain-js.md +++ /dev/null @@ -1,190 +0,0 @@ ---- -title: "LangChain JS/TS" -nav_order: 2 -description: "LangChain JavaScript/TypeScript integration for FalkorDB" -parent: "Integration" ---- - -![falkordb-langchain](https://github.com/user-attachments/assets/b5ebbef1-6943-4493-a33a-af5bcac87a60) - -# LangChain JS/TS Integration with FalkorDB - -The [@falkordb/langchain-ts](https://www.npmjs.com/package/@falkordb/langchain-ts) package enables developers to integrate FalkorDB with LangChain applications. The integration allows applications to accept natural language questions, generate Cypher queries automatically, retrieve relevant context from the graph database, and return responses in natural language. - -## Installation - -### Step 1 - -```bash -npm install @falkordb/langchain-ts falkordb -``` - -### Step 2 -> Ensure LangChain and a language model are installed - -```bash -npm install langchain @langchain/openai -``` - -## Getting Started - -### Movie data example -In this example, we'll initialize the connection to FalkorDB, define a language model (E.g, OpenAI), and both create and populate the graph with movie-related data. **We'll then query the graph in natural language to see the integration at work.** -> Note: You can change the LLM's temperature - -```typescript -import { FalkorDBGraph } from "@falkordb/langchain-ts"; -import { ChatOpenAI } from "@langchain/openai"; -import { GraphCypherQAChain } from "@langchain/community/chains/graph_qa/cypher"; - -// Initialize FalkorDB connection -const graph = await FalkorDBGraph.initialize({ - host: "localhost", - port: 6379, - graph: "movies" -}); - -// Set up the language model -const model = new ChatOpenAI({ temperature: 0 }); - -// Create and populate the graph with some data -await graph.query( - "CREATE (a:Actor {name:'Bruce Willis'})" + - "-[:ACTED_IN]->(:Movie {title: 'Pulp Fiction'})" -); - -// Refresh the graph schema -await graph.refreshSchema(); - -// Create a graph QA chain -const chain = GraphCypherQAChain.fromLLM({ - llm: model, - graph: graph as any, -}); - -// Ask questions about your graph -const response = await chain.run("Who played in Pulp Fiction?"); -console.log(response); -// Output: Bruce Willis played in Pulp Fiction. - -// Clean up -await graph.close(); -``` - -## API Reference - -### FalkorDBGraph -> The following command creates and initializes a new FalkorDB connection. - -#### `initialize(config: FalkorDBGraphConfig): Promise` - -**Config Options:** - -- `host` (string, optional): Database host. Default: `"localhost"` -- `port` (number, optional): Database port. Default: `6379` -- `graph` (string, optional): Graph name to use -- `url` (string, optional): Alternative connection URL format -- `enhancedSchema` (boolean, optional): Enable enhanced schema details. Default: `false` - -**Example:** -```typescript -const graph = await FalkorDBGraph.initialize({ - host: "localhost", - port: 6379, - graph: "myGraph", - enhancedSchema: true -}); -``` - -#### `query(query: string): Promise` - -Executes a Cypher query on the graph. - -```typescript -const result = await graph.query( - "MATCH (n:Person) RETURN n.name LIMIT 10" -); -``` - -#### `refreshSchema(): Promise` - -Updates the graph schema information. - -```typescript -await graph.refreshSchema(); -console.log(graph.getSchema()); -``` - -#### `getSchema(): string` - -Returns the current graph schema as a formatted string. - -#### `getStructuredSchema(): StructuredSchema` - -Returns the structured schema object containing node properties, relationship properties, and relationships. - -#### `close(): Promise` - -Closes the database connection. - -```typescript -await graph.close(); -``` - -## Advanced Usage - -### Custom Cypher Queries - -```typescript -const graph = await FalkorDBGraph.initialize({ - host: "localhost", - port: 6379, - graph: "movies" -}); - -// Complex query -const result = await graph.query(` - MATCH (a:Actor)-[:ACTED_IN]->(m:Movie) - WHERE m.year > 2000 - RETURN a.name, m.title, m.year - ORDER BY m.year DESC - LIMIT 10 -`); - -console.log(result.data); -``` - -### Multiple Queries - -```typescript -await graph.executeQueries([ - "CREATE (p:Person {name: 'Alice'})", - "CREATE (p:Person {name: 'Bob'})", - "MATCH (a:Person {name: 'Alice'}), (b:Person {name: 'Bob'}) CREATE (a)-[:KNOWS]->(b)" -]); -``` - -### Working with Schema - -```typescript -await graph.refreshSchema(); - -// Get formatted schema -const schema = graph.getSchema(); -console.log(schema); - -// Get structured schema -const structuredSchema = graph.getStructuredSchema(); -console.log(structuredSchema.nodeProps); -console.log(structuredSchema.relationships); -``` - -## Prerequisites - -- Node.js >= 18 -- FalkorDB server running -- LangChain >= 0.1.0 - -## Additional Examples - -For more examples and source code, see the [@falkordb/langchain-ts repository](https://github.com/FalkorDB/FalkorDB-Langchain-js) on GitHub.