text-to-cypher 0.1.14

A library and REST API for translating natural language text to Cypher queries using AI models
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
//! # text-to-cypher
//!
//! A library for translating natural language text to Cypher queries using AI models.
//!
//! This library provides both a programmatic API and a REST server for converting
//! natural language questions into Cypher queries for graph databases, with built-in
//! support for `FalkorDB`.
//!
//! ## Features
//!
//! - **Text to Cypher Translation**: Convert natural language queries to Cypher database queries using AI
//! - **Schema Discovery**: Automatically discover and analyze graph database schemas
//! - **Query Validation**: Built-in validation system to catch syntax errors before execution
//! - **Self-Healing Queries**: Automatic retry with error feedback when queries fail
//! - **Flexible AI Integration**: Support for multiple AI providers through the genai crate
//!
//! ## Library Usage
//!
//! To use text-to-cypher as a library in your Rust application:
//!
//! ```toml
//! [dependencies]
//! text-to-cypher = { version = "0.1", default-features = false }
//! ```
//!
//! ### Basic Example
//!
//! ```rust,no_run
//! use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     // Create a client
//!     let client = TextToCypherClient::new(
//!         "gpt-4o-mini",
//!         "your-api-key",
//!         "falkor://127.0.0.1:6379"
//!     );
//!
//!     // Create a chat request
//!     let request = ChatRequest {
//!         messages: vec![
//!             ChatMessage {
//!                 role: ChatRole::User,
//!                 content: "Find all actors who appeared in movies released after 2020".to_string(),
//!             }
//!         ]
//!     };
//!
//!     // Convert text to Cypher and execute
//!     let response = client.text_to_cypher("movies", request).await?;
//!     
//!     println!("Generated query: {}", response.cypher_query.unwrap());
//!     println!("Result: {}", response.cypher_result.unwrap());
//!     println!("Answer: {}", response.answer.unwrap());
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Generate Cypher Only (Without Execution)
//!
//! ```rust,no_run
//! use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     let client = TextToCypherClient::new(
//!         "gpt-4o-mini",
//!         "your-api-key",
//!         "falkor://127.0.0.1:6379"
//!     );
//!
//!     let request = ChatRequest {
//!         messages: vec![
//!             ChatMessage {
//!                 role: ChatRole::User,
//!                 content: "Find all people with more than 5 friends".to_string(),
//!             }
//!         ]
//!     };
//!
//!     // Generate query only, don't execute
//!     let response = client.cypher_only("social", request).await?;
//!     println!("Query: {}", response.cypher_query.unwrap());
//!
//!     Ok(())
//! }
//! ```
//!
//! ### Using Core Functions Directly
//!
//! For more control, you can use the core functions directly:
//!
//! ```rust,no_run
//! use text_to_cypher::{core, ChatRequest, ChatMessage, ChatRole};
//!
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
//!     // Discover schema
//!     let schema = core::discover_graph_schema(
//!         "falkor://127.0.0.1:6379",
//!         "movies"
//!     ).await?;
//!     
//!     // Create GenAI client
//!     let client = core::create_genai_client(Some("your-api-key"));
//!     
//!     // Generate query
//!     let chat_req = ChatRequest {
//!         messages: vec![
//!             ChatMessage {
//!                 role: ChatRole::User,
//!                 content: "Find all actors".to_string(),
//!             }
//!         ]
//!     };
//!     
//!     let query = core::generate_cypher_query(
//!         &chat_req,
//!         &schema,
//!         &client,
//!         "gpt-4o-mini"
//!     ).await?;
//!     
//!     // Execute query
//!     let result = core::execute_cypher_query(
//!         &query,
//!         "movies",
//!         "falkor://127.0.0.1:6379",
//!         true
//!     ).await?;
//!     
//!     println!("Result: {}", result);
//!     Ok(())
//! }
//! ```
//!
//! ## Server Mode
//!
//! To use the REST server, enable the `server` feature (enabled by default):
//!
//! ```toml
//! [dependencies]
//! text-to-cypher = "0.1"
//! ```
//!
//! Then run the binary:
//!
//! ```bash
//! cargo run
//! ```

// Core modules - always available
pub mod chat;
pub mod core;
pub mod error;
pub mod formatter;
pub mod processor;
pub mod schema;
pub mod template;
pub mod validator;

// Re-export commonly used types for easier access
pub use chat::{ChatMessage, ChatRequest, ChatRole};
pub use error::ErrorResponse;
pub use genai::adapter::AdapterKind;
pub use processor::{TextToCypherRequest, TextToCypherResponse};
// Server-specific modules - only when server feature is enabled
#[cfg(feature = "server")]
pub mod mcp;

/// A high-level client for text-to-cypher operations.
///
/// This client provides a convenient interface for converting natural language
/// to Cypher queries and executing them against a `FalkorDB` instance.
///
/// # Example
///
/// ```no_run
/// use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
///     let client = TextToCypherClient::new(
///         "gpt-4o-mini",
///         "your-api-key",
///         "falkor://127.0.0.1:6379"
///     );
///
///     let request = ChatRequest {
///         messages: vec![
///             ChatMessage {
///                 role: ChatRole::User,
///                 content: "Find all nodes".to_string(),
///             }
///         ]
///     };
///
///     let response = client.text_to_cypher("my_graph", request).await?;
///     Ok(())
/// }
/// ```
pub struct TextToCypherClient {
    model: String,
    api_key: String,
    falkordb_connection: String,
}

impl TextToCypherClient {
    /// Creates a new `TextToCypherClient`.
    ///
    /// # Arguments
    ///
    /// * `model` - The AI model to use (e.g., "gpt-4o-mini", "anthropic:claude-3")
    /// * `api_key` - API key for the AI service
    /// * `falkordb_connection` - `FalkorDB` connection string (e.g., `falkor://127.0.0.1:6379`)
    ///
    /// # Example
    ///
    /// ```no_run
    /// use text_to_cypher::TextToCypherClient;
    ///
    /// let client = TextToCypherClient::new(
    ///     "gpt-4o-mini",
    ///     "your-api-key",
    ///     "falkor://127.0.0.1:6379"
    /// );
    /// ```
    #[must_use]
    pub fn new(
        model: impl Into<String>,
        api_key: impl Into<String>,
        falkordb_connection: impl Into<String>,
    ) -> Self {
        Self {
            model: model.into(),
            api_key: api_key.into(),
            falkordb_connection: falkordb_connection.into(),
        }
    }

    /// Converts natural language text to Cypher and executes the query.
    ///
    /// This is the main method for full text-to-cypher processing:
    /// 1. Discovers the graph schema
    /// 2. Generates a Cypher query using AI
    /// 3. Executes the query
    /// 4. Generates a natural language answer
    ///
    /// # Arguments
    ///
    /// * `graph_name` - Name of the graph to query
    /// * `request` - Chat request containing the user's question
    ///
    /// # Errors
    ///
    /// Returns an error if schema discovery, query generation, execution, or answer generation fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let client = TextToCypherClient::new("gpt-4o-mini", "key", "falkor://127.0.0.1:6379");
    /// let request = ChatRequest {
    ///     messages: vec![
    ///         ChatMessage {
    ///             role: ChatRole::User,
    ///             content: "Find all actors".to_string(),
    ///         }
    ///     ]
    /// };
    ///
    /// let response = client.text_to_cypher("movies", request).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn text_to_cypher(
        &self,
        graph_name: impl Into<String>,
        request: ChatRequest,
    ) -> Result<TextToCypherResponse, Box<dyn std::error::Error + Send + Sync>> {
        let req = TextToCypherRequest {
            graph_name: graph_name.into(),
            chat_request: request,
            model: Some(self.model.clone()),
            key: Some(self.api_key.clone()),
            falkordb_connection: Some(self.falkordb_connection.clone()),
            cypher_only: false,
        };

        let response = processor::process_text_to_cypher(
            req,
            Some(self.model.clone()),
            Some(self.api_key.clone()),
            self.falkordb_connection.clone(),
        )
        .await;

        if response.is_error() {
            return Err(response.error.unwrap_or_else(|| "Unknown error".to_string()).into());
        }

        Ok(response)
    }

    /// Generates a Cypher query without executing it.
    ///
    /// Use this method when you only want to generate the query for inspection
    /// or manual execution.
    ///
    /// # Arguments
    ///
    /// * `graph_name` - Name of the graph to generate query for
    /// * `request` - Chat request containing the user's question
    ///
    /// # Errors
    ///
    /// Returns an error if schema discovery or query generation fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let client = TextToCypherClient::new("gpt-4o-mini", "key", "falkor://127.0.0.1:6379");
    /// let request = ChatRequest {
    ///     messages: vec![
    ///         ChatMessage {
    ///             role: ChatRole::User,
    ///             content: "Find all actors".to_string(),
    ///         }
    ///     ]
    /// };
    ///
    /// let response = client.cypher_only("movies", request).await?;
    /// println!("Generated query: {}", response.cypher_query.unwrap());
    /// # Ok(())
    /// # }
    /// ```
    pub async fn cypher_only(
        &self,
        graph_name: impl Into<String>,
        request: ChatRequest,
    ) -> Result<TextToCypherResponse, Box<dyn std::error::Error + Send + Sync>> {
        let req = TextToCypherRequest {
            graph_name: graph_name.into(),
            chat_request: request,
            model: Some(self.model.clone()),
            key: Some(self.api_key.clone()),
            falkordb_connection: Some(self.falkordb_connection.clone()),
            cypher_only: true,
        };

        let response = processor::process_text_to_cypher(
            req,
            Some(self.model.clone()),
            Some(self.api_key.clone()),
            self.falkordb_connection.clone(),
        )
        .await;

        if response.is_error() {
            return Err(response.error.unwrap_or_else(|| "Unknown error".to_string()).into());
        }

        Ok(response)
    }

    /// Discovers and returns the schema of a graph.
    ///
    /// # Arguments
    ///
    /// * `graph_name` - Name of the graph to discover schema for
    ///
    /// # Errors
    ///
    /// Returns an error if schema discovery fails.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use text_to_cypher::TextToCypherClient;
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// # let client = TextToCypherClient::new("gpt-4o-mini", "key", "falkor://127.0.0.1:6379");
    /// let schema = client.discover_schema("movies").await?;
    /// println!("Schema: {}", schema);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn discover_schema(
        &self,
        graph_name: impl Into<String>,
    ) -> Result<String, Box<dyn std::error::Error + Send + Sync>> {
        core::discover_graph_schema(&self.falkordb_connection, &graph_name.into()).await
    }

    /// Lists all available model names for a specific AI provider
    ///
    /// # Arguments
    ///
    /// * `adapter_kind` - The AI provider to query
    ///
    /// # Returns
    ///
    /// A vector of model names supported by the adapter
    ///
    /// # Errors
    ///
    /// Returns an error if the model listing request fails
    ///
    /// # Example
    ///
    /// ```no_run
    /// use text_to_cypher::TextToCypherClient;
    /// use genai::adapter::AdapterKind;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let client = TextToCypherClient::new(
    ///     "gpt-4o-mini",
    ///     "your-api-key",
    ///     "falkor://127.0.0.1:6379"
    /// );
    ///
    /// let models = client.list_models(AdapterKind::OpenAI).await?;
    /// println!("Available OpenAI models: {:?}", models);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_models(
        &self,
        adapter_kind: AdapterKind,
    ) -> Result<Vec<String>, Box<dyn std::error::Error + Send + Sync>> {
        let client = core::create_genai_client(Some(&self.api_key));
        core::list_adapter_models(adapter_kind, &client).await
    }

    /// Lists all available models across all supported AI providers
    ///
    /// # Returns
    ///
    /// A hashmap mapping adapter kinds to their available model names
    ///
    /// # Errors
    ///
    /// Returns an error if the model listing fails
    ///
    /// # Note
    ///
    /// This method uses the API key configured in the client. Different providers
    /// require different API keys, so only the provider matching the configured key
    /// will successfully return results. Other providers will be logged as warnings
    /// and skipped.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use text_to_cypher::TextToCypherClient;
    ///
    /// # #[tokio::main]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    /// let client = TextToCypherClient::new(
    ///     "gpt-4o-mini",
    ///     "your-api-key",
    ///     "falkor://127.0.0.1:6379"
    /// );
    ///
    /// let all_models = client.list_all_models().await?;
    /// for (kind, models) in all_models {
    ///     println!("{kind}: {} models", models.len());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn list_all_models(
        &self
    ) -> Result<std::collections::HashMap<AdapterKind, Vec<String>>, Box<dyn std::error::Error + Send + Sync>> {
        let client = core::create_genai_client(Some(&self.api_key));
        core::list_all_models(&client).await
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_client_creation() {
        let client = TextToCypherClient::new("gpt-4o-mini", "test-api-key", "falkor://127.0.0.1:6379");

        assert_eq!(client.model, "gpt-4o-mini");
        assert_eq!(client.api_key, "test-api-key");
        assert_eq!(client.falkordb_connection, "falkor://127.0.0.1:6379");
    }

    #[test]
    fn test_client_creation_with_string() {
        let client = TextToCypherClient::new(
            "anthropic:claude-3".to_string(),
            "key123".to_string(),
            "falkor://localhost:6379".to_string(),
        );

        assert_eq!(client.model, "anthropic:claude-3");
        assert_eq!(client.api_key, "key123");
        assert_eq!(client.falkordb_connection, "falkor://localhost:6379");
    }

    #[test]
    fn test_chat_request_construction() {
        let request = ChatRequest {
            messages: vec![
                ChatMessage {
                    role: ChatRole::User,
                    content: "Hello".to_string(),
                },
                ChatMessage {
                    role: ChatRole::Assistant,
                    content: "Hi there".to_string(),
                },
            ],
        };

        assert_eq!(request.messages.len(), 2);
        assert_eq!(request.messages[0].role, ChatRole::User);
        assert_eq!(request.messages[1].role, ChatRole::Assistant);
    }

    #[test]
    fn test_chat_role_serialization() {
        let role = ChatRole::User;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, r#""user""#);

        let role = ChatRole::Assistant;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, r#""assistant""#);

        let role = ChatRole::System;
        let json = serde_json::to_string(&role).unwrap();
        assert_eq!(json, r#""system""#);
    }

    #[test]
    fn test_chat_message_serialization() {
        let message = ChatMessage {
            role: ChatRole::User,
            content: "Test message".to_string(),
        };

        let json = serde_json::to_string(&message).unwrap();
        let deserialized: ChatMessage = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.role, ChatRole::User);
        assert_eq!(deserialized.content, "Test message");
    }

    #[test]
    fn test_chat_request_serialization() {
        let request = ChatRequest {
            messages: vec![ChatMessage {
                role: ChatRole::User,
                content: "Find all nodes".to_string(),
            }],
        };

        let json = serde_json::to_string(&request).unwrap();
        let deserialized: ChatRequest = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.messages.len(), 1);
        assert_eq!(deserialized.messages[0].content, "Find all nodes");
    }

    #[test]
    fn test_error_response_structure() {
        let error = ErrorResponse {
            error: "Test error".to_string(),
            message: "Detailed message".to_string(),
            status_code: 500,
        };

        assert_eq!(error.error, "Test error");
        assert_eq!(error.message, "Detailed message");
        assert_eq!(error.status_code, 500);
    }

    #[test]
    fn test_chat_role_equality() {
        assert_eq!(ChatRole::User, ChatRole::User);
        assert_eq!(ChatRole::Assistant, ChatRole::Assistant);
        assert_eq!(ChatRole::System, ChatRole::System);
        assert_ne!(ChatRole::User, ChatRole::Assistant);
    }

    #[test]
    fn test_client_with_different_models() {
        let models = vec!["gpt-4o-mini", "gpt-4o", "anthropic:claude-3", "gemini:gemini-2.0-flash-exp"];

        for model in models {
            let client = TextToCypherClient::new(model, "key", "falkor://localhost:6379");
            assert_eq!(client.model, model);
        }
    }
}