@falkordb/text-to-cypher 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,294 @@
1
+ # @falkordb/text-to-cypher-node
2
+
3
+ Node.js bindings for the [FalkorDB text-to-cypher](https://github.com/FalkorDB/text-to-cypher) library - Convert natural language to Cypher queries using AI.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@falkordb/text-to-cypher-node.svg)](https://www.npmjs.com/package/@falkordb/text-to-cypher-node)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+
8
+ ## Features
9
+
10
+ - 🤖 **AI-Powered**: Convert natural language questions to Cypher queries using GPT-4, Claude, Gemini, and other AI models
11
+ - 🔍 **Schema Discovery**: Automatically discovers and analyzes graph database schemas
12
+ - ✅ **Query Validation**: Built-in validation to catch syntax errors before execution
13
+ - 🚀 **High Performance**: Native Rust implementation with Node.js bindings via NAPI-RS
14
+ - 🌍 **Cross-Platform**: Pre-built binaries for Linux, macOS, and Windows
15
+ - 📦 **Zero Dependencies**: No runtime dependencies required
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @falkordb/text-to-cypher-node
21
+ ```
22
+
23
+ **📚 New to this library? Check out the [Quick Start Guide](QUICKSTART.md) for a 5-minute introduction!**
24
+
25
+ ## Quick Start
26
+
27
+ ```javascript
28
+ const { TextToCypher } = require('@falkordb/text-to-cypher-node');
29
+
30
+ // Create a client
31
+ const client = new TextToCypher({
32
+ model: 'gpt-4o-mini',
33
+ apiKey: process.env.OPENAI_API_KEY,
34
+ falkordbConnection: 'falkor://localhost:6379'
35
+ });
36
+
37
+ // Convert text to Cypher and execute
38
+ async function main() {
39
+ const response = await client.textToCypher(
40
+ 'movies',
41
+ 'Find all actors who appeared in movies released after 2020'
42
+ );
43
+
44
+ console.log('Generated Query:', response.cypherQuery);
45
+ console.log('Result:', response.cypherResult);
46
+ console.log('Answer:', response.answer);
47
+ }
48
+
49
+ main().catch(console.error);
50
+ ```
51
+
52
+ ## API Reference
53
+
54
+ ### `new TextToCypher(options)`
55
+
56
+ Creates a new text-to-cypher client.
57
+
58
+ **Parameters:**
59
+ - `options.model` (string): AI model to use (e.g., `'gpt-4o-mini'`, `'anthropic:claude-3'`, `'gemini:gemini-2.0-flash-exp'`)
60
+ - `options.apiKey` (string): API key for the AI service
61
+ - `options.falkordbConnection` (string): FalkorDB connection string (e.g., `'falkor://localhost:6379'`)
62
+
63
+ **Example:**
64
+ ```javascript
65
+ const client = new TextToCypher({
66
+ model: 'gpt-4o-mini',
67
+ apiKey: 'sk-...',
68
+ falkordbConnection: 'falkor://localhost:6379'
69
+ });
70
+ ```
71
+
72
+ ### `textToCypher(graphName, question)`
73
+
74
+ Converts natural language to Cypher, executes the query, and generates a natural language answer.
75
+
76
+ **Parameters:**
77
+ - `graphName` (string): Name of the graph to query
78
+ - `question` (string): Natural language question
79
+
80
+ **Returns:** `Promise<TextToCypherResponse>`
81
+
82
+ **Example:**
83
+ ```javascript
84
+ const response = await client.textToCypher('movies', 'Who directed The Matrix?');
85
+ console.log(response.answer); // "The Matrix was directed by..."
86
+ ```
87
+
88
+ ### `textToCypherWithMessages(graphName, messages)`
89
+
90
+ Same as `textToCypher` but accepts multiple messages for conversation context.
91
+
92
+ **Parameters:**
93
+ - `graphName` (string): Name of the graph to query
94
+ - `messages` (Array<Message>): Array of conversation messages
95
+
96
+ **Example:**
97
+ ```javascript
98
+ const response = await client.textToCypherWithMessages('movies', [
99
+ { role: 'user', content: 'Show me actors' },
100
+ { role: 'assistant', content: 'Here are some actors...' },
101
+ { role: 'user', content: 'Filter those who acted after 2020' }
102
+ ]);
103
+ ```
104
+
105
+ ### `cypherOnly(graphName, question)`
106
+
107
+ Generates a Cypher query without executing it.
108
+
109
+ **Parameters:**
110
+ - `graphName` (string): Name of the graph
111
+ - `question` (string): Natural language question
112
+
113
+ **Returns:** `Promise<TextToCypherResponse>` (with only `schema` and `cypherQuery` populated)
114
+
115
+ **Example:**
116
+ ```javascript
117
+ const response = await client.cypherOnly('movies', 'Find all actors');
118
+ console.log('Generated query:', response.cypherQuery);
119
+ // Use the query however you want
120
+ ```
121
+
122
+ ### `discoverSchema(graphName)`
123
+
124
+ Discovers and returns the schema of a graph as JSON.
125
+
126
+ **Parameters:**
127
+ - `graphName` (string): Name of the graph
128
+
129
+ **Returns:** `Promise<string>` (JSON string)
130
+
131
+ **Example:**
132
+ ```javascript
133
+ const schema = await client.discoverSchema('movies');
134
+ const schemaObj = JSON.parse(schema);
135
+ console.log('Nodes:', schemaObj.nodes);
136
+ console.log('Relationships:', schemaObj.relationships);
137
+ ```
138
+
139
+ ## Types
140
+
141
+ ### TextToCypherResponse
142
+
143
+ ```typescript
144
+ interface TextToCypherResponse {
145
+ status: string; // "success" or "error"
146
+ schema?: string; // JSON schema of the graph
147
+ cypherQuery?: string; // Generated Cypher query
148
+ cypherResult?: string; // Query execution result
149
+ answer?: string; // Natural language answer
150
+ error?: string; // Error message if status is "error"
151
+ }
152
+ ```
153
+
154
+ ### Message
155
+
156
+ ```typescript
157
+ interface Message {
158
+ role: string; // "user", "assistant", or "system"
159
+ content: string; // Message content
160
+ }
161
+ ```
162
+
163
+ ## Supported AI Models
164
+
165
+ This library uses the [genai](https://crates.io/crates/genai) crate and supports:
166
+
167
+ - **OpenAI**: `gpt-4o-mini`, `gpt-4o`, `gpt-4-turbo`, etc.
168
+ - **Anthropic**: `anthropic:claude-3-5-sonnet-20241022`, `anthropic:claude-3-opus-20240229`
169
+ - **Google Gemini**: `gemini:gemini-2.0-flash-exp`, `gemini:gemini-1.5-pro`
170
+
171
+ See [genai documentation](https://docs.rs/genai/latest/genai/) for a complete list.
172
+
173
+ ## Examples
174
+
175
+ ### Using with FalkorDB Browser
176
+
177
+ ```javascript
178
+ const { TextToCypher } = require('@falkordb/text-to-cypher-node');
179
+
180
+ // In your Express.js or other Node.js server
181
+ app.post('/api/text-to-cypher', async (req, res) => {
182
+ const { graphName, question } = req.body;
183
+
184
+ try {
185
+ const client = new TextToCypher({
186
+ model: 'gpt-4o-mini',
187
+ apiKey: process.env.OPENAI_API_KEY,
188
+ falkordbConnection: process.env.FALKORDB_CONNECTION
189
+ });
190
+
191
+ const response = await client.textToCypher(graphName, question);
192
+ res.json(response);
193
+ } catch (error) {
194
+ res.status(500).json({ error: error.message });
195
+ }
196
+ });
197
+ ```
198
+
199
+ ### TypeScript Usage
200
+
201
+ ```typescript
202
+ import { TextToCypher, ClientOptions, TextToCypherResponse } from '@falkordb/text-to-cypher-node';
203
+
204
+ const options: ClientOptions = {
205
+ model: 'gpt-4o-mini',
206
+ apiKey: process.env.OPENAI_API_KEY!,
207
+ falkordbConnection: 'falkor://localhost:6379'
208
+ };
209
+
210
+ const client = new TextToCypher(options);
211
+
212
+ const response: TextToCypherResponse = await client.textToCypher(
213
+ 'movies',
214
+ 'Find top 10 highest rated movies'
215
+ );
216
+
217
+ console.log(response.answer);
218
+ ```
219
+
220
+ ### Error Handling
221
+
222
+ ```javascript
223
+ try {
224
+ const response = await client.textToCypher('movies', 'Find all actors');
225
+
226
+ if (response.status === 'error') {
227
+ console.error('Error:', response.error);
228
+ } else {
229
+ console.log('Success:', response.answer);
230
+ }
231
+ } catch (error) {
232
+ console.error('Exception:', error.message);
233
+ }
234
+ ```
235
+
236
+ ## Requirements
237
+
238
+ - Node.js >= 10
239
+ - FalkorDB instance running and accessible
240
+ - API key for your chosen AI provider (OpenAI, Anthropic, etc.)
241
+
242
+ ## Development
243
+
244
+ ### Building from Source
245
+
246
+ ```bash
247
+ # Install dependencies
248
+ npm install
249
+
250
+ # Build the native module
251
+ npm run build
252
+
253
+ # Run tests
254
+ npm test
255
+ ```
256
+
257
+ ### Prerequisites for Building
258
+
259
+ - Rust toolchain (install from [rustup.rs](https://rustup.rs/))
260
+ - Node.js >= 10
261
+ - C++ compiler (platform-specific)
262
+
263
+ ## Platform Support
264
+
265
+ Pre-built binaries are available for:
266
+
267
+ - Linux x64 (glibc and musl)
268
+ - Linux ARM64 (glibc and musl)
269
+ - macOS x64 (Intel)
270
+ - macOS ARM64 (Apple Silicon)
271
+ - Windows x64
272
+
273
+ ## Contributing
274
+
275
+ Contributions are welcome! Please feel free to submit a Pull Request.
276
+
277
+ ## License
278
+
279
+ MIT License - see [LICENSE](LICENSE) file for details.
280
+
281
+ ## Related Projects
282
+
283
+ - [text-to-cypher](https://github.com/FalkorDB/text-to-cypher) - The underlying Rust library
284
+ - [falkordb-browser](https://github.com/FalkorDB/falkordb-browser) - FalkorDB web interface
285
+ - [FalkorDB](https://github.com/FalkorDB/FalkorDB) - Graph database
286
+
287
+ ## Support
288
+
289
+ - [GitHub Issues](https://github.com/FalkorDB/text-to-cypher-node/issues)
290
+ - [FalkorDB Discord](https://discord.gg/falkordb)
291
+
292
+ ## Acknowledgments
293
+
294
+ Built with [NAPI-RS](https://napi.rs/) - A framework for building compiled Node.js add-ons in Rust.
@@ -0,0 +1,50 @@
1
+ # Examples
2
+
3
+ This directory contains example code demonstrating how to use `@falkordb/text-to-cypher-node`.
4
+
5
+ ## Running Examples
6
+
7
+ ### JavaScript Example
8
+
9
+ ```bash
10
+ # Set environment variables
11
+ export OPENAI_API_KEY="your-api-key"
12
+ export FALKORDB_CONNECTION="falkor://localhost:6379"
13
+
14
+ # Run the example
15
+ node examples/basic-usage.js
16
+ ```
17
+
18
+ ### TypeScript Example
19
+
20
+ ```bash
21
+ # Install TypeScript if needed
22
+ npm install -g typescript ts-node
23
+
24
+ # Run the TypeScript example
25
+ ts-node examples/typescript-usage.ts
26
+ ```
27
+
28
+ ## Examples Included
29
+
30
+ 1. **basic-usage.js** - Comprehensive JavaScript example showing all major features
31
+ 2. **typescript-usage.ts** - TypeScript example with type safety
32
+
33
+ ## Prerequisites
34
+
35
+ - FalkorDB instance running on `localhost:6379` (or set `FALKORDB_CONNECTION`)
36
+ - Valid OpenAI API key (or API key for your chosen AI provider)
37
+ - Sample graph data loaded in FalkorDB
38
+
39
+ ## Creating Sample Data
40
+
41
+ If you need sample data for testing, you can use FalkorDB's movie graph:
42
+
43
+ ```bash
44
+ # Connect to FalkorDB
45
+ redis-cli
46
+
47
+ # Create sample movie graph
48
+ GRAPH.QUERY movies "CREATE (:Actor {name: 'Tom Hanks'})-[:ACTED_IN]->(:Movie {title: 'Forrest Gump', year: 1994})"
49
+ GRAPH.QUERY movies "CREATE (:Actor {name: 'Robin Williams'})-[:ACTED_IN]->(:Movie {title: 'Good Will Hunting', year: 1997})"
50
+ ```
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Basic usage example for text-to-cypher-node
3
+ *
4
+ * This example demonstrates how to:
5
+ * 1. Create a TextToCypher client
6
+ * 2. Convert natural language to Cypher and execute queries
7
+ * 3. Generate queries without execution
8
+ * 4. Discover graph schema
9
+ */
10
+
11
+ const { TextToCypher } = require('../index');
12
+
13
+ async function main() {
14
+ // Create a client with your configuration
15
+ const client = new TextToCypher({
16
+ model: 'gpt-4o-mini',
17
+ apiKey: process.env.OPENAI_API_KEY || 'your-api-key-here',
18
+ falkordbConnection: process.env.FALKORDB_CONNECTION || 'falkor://localhost:6379'
19
+ });
20
+
21
+ const graphName = 'movies';
22
+
23
+ console.log('=== Text-to-Cypher Node.js Example ===\n');
24
+
25
+ // Example 1: Discover Schema
26
+ console.log('1. Discovering graph schema...');
27
+ try {
28
+ const schema = await client.discoverSchema(graphName);
29
+ const schemaObj = JSON.parse(schema);
30
+ console.log('Schema discovered:');
31
+ console.log(JSON.stringify(schemaObj, null, 2));
32
+ } catch (error) {
33
+ console.error('Error discovering schema:', error.message);
34
+ }
35
+
36
+ console.log('\n---\n');
37
+
38
+ // Example 2: Generate Cypher Query Only
39
+ console.log('2. Generating Cypher query (without execution)...');
40
+ try {
41
+ const response = await client.cypherOnly(
42
+ graphName,
43
+ 'Find all actors who appeared in movies released after 2020'
44
+ );
45
+ console.log('Generated query:', response.cypherQuery);
46
+ } catch (error) {
47
+ console.error('Error generating query:', error.message);
48
+ }
49
+
50
+ console.log('\n---\n');
51
+
52
+ // Example 3: Full Text-to-Cypher with Execution
53
+ console.log('3. Converting text to Cypher and executing...');
54
+ try {
55
+ const response = await client.textToCypher(
56
+ graphName,
57
+ 'Show me the top 5 highest rated movies'
58
+ );
59
+
60
+ if (response.status === 'success') {
61
+ console.log('Query:', response.cypherQuery);
62
+ console.log('Result:', response.cypherResult);
63
+ console.log('Answer:', response.answer);
64
+ } else {
65
+ console.error('Error:', response.error);
66
+ }
67
+ } catch (error) {
68
+ console.error('Error:', error.message);
69
+ }
70
+
71
+ console.log('\n---\n');
72
+
73
+ // Example 4: Using Conversation History
74
+ console.log('4. Using conversation with multiple messages...');
75
+ try {
76
+ const response = await client.textToCypherWithMessages(graphName, [
77
+ { role: 'user', content: 'Show me actors' },
78
+ { role: 'assistant', content: 'Here are some actors from the graph' },
79
+ { role: 'user', content: 'Now show me only those who acted in movies after 2020' }
80
+ ]);
81
+
82
+ if (response.status === 'success') {
83
+ console.log('Query:', response.cypherQuery);
84
+ console.log('Answer:', response.answer);
85
+ } else {
86
+ console.error('Error:', response.error);
87
+ }
88
+ } catch (error) {
89
+ console.error('Error:', error.message);
90
+ }
91
+ }
92
+
93
+ // Run the examples
94
+ main().catch(console.error);
@@ -0,0 +1,52 @@
1
+ /**
2
+ * TypeScript example for text-to-cypher-node
3
+ */
4
+
5
+ import { TextToCypher, ClientOptions, TextToCypherResponse } from '../index';
6
+
7
+ async function main(): Promise<void> {
8
+ // Create client with type safety
9
+ const options: ClientOptions = {
10
+ model: 'gpt-4o-mini',
11
+ apiKey: process.env.OPENAI_API_KEY || 'your-api-key-here',
12
+ falkordbConnection: process.env.FALKORDB_CONNECTION || 'falkor://localhost:6379'
13
+ };
14
+
15
+ const client = new TextToCypher(options);
16
+ const graphName = 'movies';
17
+
18
+ console.log('=== TypeScript Text-to-Cypher Example ===\n');
19
+
20
+ // Type-safe query execution
21
+ try {
22
+ const response: TextToCypherResponse = await client.textToCypher(
23
+ graphName,
24
+ 'Find actors who worked with Tom Hanks'
25
+ );
26
+
27
+ if (response.status === 'success') {
28
+ console.log('Generated Query:', response.cypherQuery);
29
+ console.log('Result:', response.cypherResult);
30
+ console.log('Answer:', response.answer);
31
+ } else {
32
+ console.error('Error:', response.error);
33
+ }
34
+ } catch (error) {
35
+ if (error instanceof Error) {
36
+ console.error('Exception:', error.message);
37
+ }
38
+ }
39
+
40
+ // Schema discovery with type safety
41
+ try {
42
+ const schemaJson: string = await client.discoverSchema(graphName);
43
+ const schema = JSON.parse(schemaJson);
44
+ console.log('\nSchema:', schema);
45
+ } catch (error) {
46
+ if (error instanceof Error) {
47
+ console.error('Schema discovery failed:', error.message);
48
+ }
49
+ }
50
+ }
51
+
52
+ main().catch(console.error);
package/index.d.ts ADDED
@@ -0,0 +1,174 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+
4
+ /* auto-generated by NAPI-RS */
5
+
6
+ /** Options for creating a TextToCypher client */
7
+ export interface ClientOptions {
8
+ /** The AI model to use (e.g., "gpt-4o-mini", "anthropic:claude-3") */
9
+ model: string
10
+ /** API key for the AI service */
11
+ apiKey: string
12
+ /** FalkorDB connection string (e.g., "falkor://localhost:6379") */
13
+ falkordbConnection: string
14
+ }
15
+ /** A chat message in the conversation */
16
+ export interface Message {
17
+ /** Role of the message sender: "user", "assistant", or "system" */
18
+ role: string
19
+ /** Content of the message */
20
+ content: string
21
+ }
22
+ /** Response from text-to-cypher operations */
23
+ export interface TextToCypherResponse {
24
+ /** Status of the operation: "success" or "error" */
25
+ status: string
26
+ /** The discovered graph schema (JSON string) */
27
+ schema?: string
28
+ /** The generated Cypher query */
29
+ cypherQuery?: string
30
+ /** The result from executing the Cypher query */
31
+ cypherResult?: string
32
+ /** Natural language answer generated from the results */
33
+ answer?: string
34
+ /** Error message if status is "error" */
35
+ error?: string
36
+ }
37
+ /**
38
+ * Node.js wrapper for the text-to-cypher Rust library
39
+ *
40
+ * This class provides methods to convert natural language text to Cypher queries
41
+ * and execute them against a FalkorDB instance.
42
+ *
43
+ * # Example
44
+ *
45
+ * ```javascript
46
+ * const { TextToCypher } = require('@falkordb/text-to-cypher-node');
47
+ *
48
+ * const client = new TextToCypher({
49
+ * model: 'gpt-4o-mini',
50
+ * apiKey: 'your-api-key',
51
+ * falkordbConnection: 'falkor://localhost:6379'
52
+ * });
53
+ *
54
+ * const response = await client.textToCypher('movies', 'Find all actors');
55
+ * console.log(response.answer);
56
+ * ```
57
+ */
58
+ export declare class TextToCypher {
59
+ /**
60
+ * Creates a new TextToCypher client
61
+ *
62
+ * # Arguments
63
+ *
64
+ * * `options` - Client configuration including model, API key, and FalkorDB connection
65
+ *
66
+ * # Example
67
+ *
68
+ * ```javascript
69
+ * const client = new TextToCypher({
70
+ * model: 'gpt-4o-mini',
71
+ * apiKey: 'your-api-key',
72
+ * falkordbConnection: 'falkor://localhost:6379'
73
+ * });
74
+ * ```
75
+ */
76
+ constructor(options: ClientOptions)
77
+ /**
78
+ * Converts natural language text to Cypher and executes the query
79
+ *
80
+ * This method:
81
+ * 1. Discovers the graph schema
82
+ * 2. Generates a Cypher query using AI
83
+ * 3. Executes the query
84
+ * 4. Generates a natural language answer
85
+ *
86
+ * # Arguments
87
+ *
88
+ * * `graph_name` - Name of the graph to query
89
+ * * `question` - Natural language question or request
90
+ *
91
+ * # Returns
92
+ *
93
+ * A promise that resolves to a TextToCypherResponse containing the query, result, and answer
94
+ *
95
+ * # Example
96
+ *
97
+ * ```javascript
98
+ * const response = await client.textToCypher(
99
+ * 'movies',
100
+ * 'Find all actors who appeared in movies released after 2020'
101
+ * );
102
+ * console.log('Query:', response.cypherQuery);
103
+ * console.log('Answer:', response.answer);
104
+ * ```
105
+ */
106
+ textToCypher(graphName: string, question: string): Promise<TextToCypherResponse>
107
+ /**
108
+ * Converts natural language text to Cypher and executes the query with multiple messages
109
+ *
110
+ * This method allows for conversation history by accepting multiple messages.
111
+ *
112
+ * # Arguments
113
+ *
114
+ * * `graph_name` - Name of the graph to query
115
+ * * `messages` - Array of conversation messages
116
+ *
117
+ * # Returns
118
+ *
119
+ * A promise that resolves to a TextToCypherResponse
120
+ *
121
+ * # Example
122
+ *
123
+ * ```javascript
124
+ * const response = await client.textToCypherWithMessages('movies', [
125
+ * { role: 'user', content: 'Show me actors' },
126
+ * { role: 'assistant', content: 'Here are the actors...' },
127
+ * { role: 'user', content: 'Filter those who acted after 2020' }
128
+ * ]);
129
+ * ```
130
+ */
131
+ textToCypherWithMessages(graphName: string, messages: Array<Message>): Promise<TextToCypherResponse>
132
+ /**
133
+ * Generates a Cypher query without executing it
134
+ *
135
+ * Use this when you only want to generate the query for inspection or manual execution.
136
+ *
137
+ * # Arguments
138
+ *
139
+ * * `graph_name` - Name of the graph to generate query for
140
+ * * `question` - Natural language question or request
141
+ *
142
+ * # Returns
143
+ *
144
+ * A promise that resolves to a TextToCypherResponse with only the schema and query
145
+ *
146
+ * # Example
147
+ *
148
+ * ```javascript
149
+ * const response = await client.cypherOnly('movies', 'Find all actors');
150
+ * console.log('Generated query:', response.cypherQuery);
151
+ * // You can now review, modify, or execute the query yourself
152
+ * ```
153
+ */
154
+ cypherOnly(graphName: string, question: string): Promise<TextToCypherResponse>
155
+ /**
156
+ * Discovers and returns the schema of a graph
157
+ *
158
+ * # Arguments
159
+ *
160
+ * * `graph_name` - Name of the graph to discover schema for
161
+ *
162
+ * # Returns
163
+ *
164
+ * A promise that resolves to a JSON string representing the graph schema
165
+ *
166
+ * # Example
167
+ *
168
+ * ```javascript
169
+ * const schema = await client.discoverSchema('movies');
170
+ * console.log('Schema:', JSON.parse(schema));
171
+ * ```
172
+ */
173
+ discoverSchema(graphName: string): Promise<string>
174
+ }