text-to-cypher 0.1.9

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
# Text-to-Cypher Library API Documentation

This document provides detailed information about using text-to-cypher as a library in your Rust applications.

**For other languages:**
- [TypeScript/JavaScript Usage Guide]TYPESCRIPT_USAGE.md
- [Python Usage Guide]PYTHON_USAGE.md

## Testing

The library includes comprehensive unit tests covering all public APIs. See:
- [Library tests]../src/lib.rs#L409 - Tests for `TextToCypherClient` and core types
- [Processor tests]../src/processor.rs#L273 - Tests for `TextToCypherRequest` and `TextToCypherResponse`
- [Validator tests]../src/validator.rs - Tests for Cypher query validation
- [Formatter tests]../src/formatter.rs - Tests for result formatting
- [Schema tests]../src/schema/discovery.rs - Tests for schema discovery

Run tests with:
```bash
cargo test --lib
```

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
# For library usage only (minimal dependencies)
text-to-cypher = { version = "0.1", default-features = false }

# For full server capabilities (includes REST API)
text-to-cypher = "0.1"
```

## Quick Start

```rust
use text_to_cypher::{TextToCypherClient, ChatRequest, ChatMessage, ChatRole};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = TextToCypherClient::new(
        "gpt-4o-mini",           // AI model
        "your-api-key",          // API key
        "falkor://localhost:6379" // FalkorDB connection
    );

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

    let response = client.text_to_cypher("my_graph", request).await?;
    println!("Result: {:?}", response);
    Ok(())
}
```

## API Reference

### `TextToCypherClient`

The high-level client for text-to-cypher operations.

#### Constructor

```rust
pub fn new(
    model: impl Into<String>,
    api_key: impl Into<String>,
    falkordb_connection: impl Into<String>
) -> Self
```

Creates a new client instance.

**Parameters:**
- `model`: AI model identifier (e.g., "gpt-4o-mini", "anthropic:claude-3", "gemini:gemini-2.0-flash-exp")
- `api_key`: API key for the AI service
- `falkordb_connection`: FalkorDB connection string (e.g., "falkor://localhost:6379")

**Example:**
```rust
let client = TextToCypherClient::new(
    "gpt-4o-mini",
    "sk-...",
    "falkor://localhost:6379"
);
```

#### Methods

##### `text_to_cypher`

```rust
pub async fn text_to_cypher(
    &self,
    graph_name: impl Into<String>,
    request: ChatRequest,
) -> Result<TextToCypherResponse, Box<dyn std::error::Error + Send + Sync>>
```

Converts natural language to Cypher, executes the query, and generates a natural language answer.

**Process:**
1. Discovers the graph schema
2. Generates a Cypher query using AI
3. Executes the query against FalkorDB
4. Generates a natural language answer from the results

**Parameters:**
- `graph_name`: Name of the graph to query
- `request`: Chat request containing the user's question

**Returns:**
- `TextToCypherResponse` with schema, query, result, and answer
- Or an error if any step fails

**Example:**
```rust
let request = ChatRequest {
    messages: vec![
        ChatMessage {
            role: ChatRole::User,
            content: "Show me all actors".to_string(),
        }
    ]
};

let response = client.text_to_cypher("movies", request).await?;
println!("Query: {}", response.cypher_query.unwrap());
println!("Answer: {}", response.answer.unwrap());
```

##### `cypher_only`

```rust
pub async fn cypher_only(
    &self,
    graph_name: impl Into<String>,
    request: ChatRequest,
) -> Result<TextToCypherResponse, Box<dyn std::error::Error + Send + Sync>>
```

Generates a Cypher query without executing it.

Use this when you want to:
- Preview the generated query
- Execute the query manually
- Modify the query before execution

**Parameters:**
- `graph_name`: Name of the graph
- `request`: Chat request containing the user's question

**Returns:**
- `TextToCypherResponse` with only the schema and cypher_query fields populated

**Example:**
```rust
let request = ChatRequest {
    messages: vec![
        ChatMessage {
            role: ChatRole::User,
            content: "Find people with more than 5 friends".to_string(),
        }
    ]
};

let response = client.cypher_only("social", request).await?;
println!("Generated query: {}", response.cypher_query.unwrap());
// Now you can review, modify, or execute the query yourself
```

##### `discover_schema`

```rust
pub async fn discover_schema(
    &self,
    graph_name: impl Into<String>,
) -> Result<String, Box<dyn std::error::Error + Send + Sync>>
```

Discovers and returns the schema of a graph as JSON.

**Parameters:**
- `graph_name`: Name of the graph

**Returns:**
- JSON string representing the graph schema

**Example:**
```rust
let schema = client.discover_schema("movies").await?;
println!("Schema: {}", schema);
```

## Model Discovery

List all available AI models: 

```rust
use text_to_cypher::{core, AdapterKind};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let client = core::create_genai_client(None);
    
    // List models for a specific provider
    let openai_models = core::list_adapter_models(AdapterKind::OpenAI, &client).await?;
    println!("OpenAI models: {:?}", openai_models);
    
    // List all models
    let all_models = core::list_all_models(&client).await?;
    for (kind, models) in all_models {
        println!("{kind}: {} models available", models.len());
    }
    
    Ok(())
}
```

Or using the high-level client:

```rust
let client = TextToCypherClient::new("gpt-4o-mini", "api-key", "falkor://localhost:6379");
let models = client.list_models(AdapterKind::OpenAI).await?;
```

### Core Functions

For more control, you can use the core functions directly:

```rust
use text_to_cypher::{core, ChatRequest, ChatMessage, ChatRole};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 1. Discover schema
    let schema = core::discover_graph_schema(
        "falkor://localhost:6379",
        "movies"
    ).await?;
    
    // 2. Create GenAI client
    let genai_client = core::create_genai_client(Some("your-api-key"));
    
    // 3. 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,
        &genai_client,
        "gpt-4o-mini"
    ).await?;
    
    // 4. Execute query
    let result = core::execute_cypher_query(
        &query,
        "movies",
        "falkor://localhost:6379",
        true  // read_only
    ).await?;
    
    // 5. Generate natural language answer
    let answer = core::generate_final_answer(
        &chat_req,
        &query,
        &result,
        &genai_client,
        "gpt-4o-mini"
    ).await?;
    
    println!("Answer: {}", answer);
    Ok(())
}
```

## Data Structures

### `ChatRequest`

```rust
pub struct ChatRequest {
    pub messages: Vec<ChatMessage>,
}
```

### `ChatMessage`

```rust
pub struct ChatMessage {
    pub role: ChatRole,
    pub content: String,
}
```

### `ChatRole`

```rust
pub enum ChatRole {
    User,
    Assistant,
    System,
}
```

### `TextToCypherResponse`

```rust
pub struct TextToCypherResponse {
    pub status: String,
    pub schema: Option<String>,
    pub cypher_query: Option<String>,
    pub cypher_result: Option<String>,
    pub answer: Option<String>,
    pub error: Option<String>,
}
```

## Supported AI Models

The library uses the [genai](https://crates.io/crates/genai) crate, which supports:

- **OpenAI**: `gpt-4o-mini`, `gpt-4o`, `gpt-4-turbo`, etc.
- **Anthropic**: `anthropic:claude-3-5-sonnet-20241022`, `anthropic:claude-3-opus-20240229`
- **Google Gemini**: `gemini:gemini-2.0-flash-exp`, `gemini:gemini-1.5-pro`
- **And more**: Check [genai documentation]https://docs.rs/genai/latest/genai/ for full list

## Error Handling

All async methods return `Result<T, Box<dyn std::error::Error + Send + Sync>>`.

Common errors:
- Connection failures to FalkorDB
- AI service errors (invalid API key, rate limits, etc.)
- Schema discovery failures
- Query generation or execution failures

Example error handling:

```rust
match client.text_to_cypher("my_graph", request).await {
    Ok(response) => {
        if response.status == "success" {
            println!("Success: {:?}", response.answer);
        }
    }
    Err(e) => {
        eprintln!("Error: {}", e);
        // Handle specific error cases
    }
}
```

## Complete Example

See [examples/library_usage.rs](../examples/library_usage.rs) for a comprehensive example demonstrating:
- Using the high-level client
- Using core functions directly
- Generating queries without execution
- Error handling

Run it with:
```bash
cargo run --example library_usage --no-default-features
```

## Features

The library has two feature sets:

1. **Default (with `server` feature)**: Includes REST API server, Swagger UI, MCP server
   ```toml
   text-to-cypher = "0.1"
   ```

2. **Library-only (without `server` feature)**: Core functionality only
   ```toml
   text-to-cypher = { version = "0.1", default-features = false }
   ```

The library-only mode excludes:
- actix-web and HTTP server dependencies
- Swagger/OpenAPI dependencies
- MCP server dependencies
- Other server-specific dependencies

This results in a smaller binary and faster compile times.

## Best Practices

1. **Reuse the client**: Create one `TextToCypherClient` instance and reuse it for multiple requests
2. **Handle schemas efficiently**: The schema is discovered once per request; consider caching it if needed
3. **Use cypher_only for validation**: Generate queries first to validate them before execution
4. **Error handling**: Always handle errors appropriately in production code
5. **Connection pooling**: The underlying FalkorDB client handles connections efficiently

## License

MIT License - see [LICENSE](../LICENSE) file for details.