text2cypher 1.1.0__tar.gz → 2.0.0__tar.gz

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.
Files changed (55) hide show
  1. {text2cypher-1.1.0 → text2cypher-2.0.0}/PKG-INFO +21 -8
  2. {text2cypher-1.1.0 → text2cypher-2.0.0}/README.md +19 -7
  3. text2cypher-2.0.0/THIRD_PARTY_NOTICES +31 -0
  4. {text2cypher-1.1.0 → text2cypher-2.0.0}/pyproject.toml +7 -3
  5. {text2cypher-1.1.0 → text2cypher-2.0.0}/pyproject.toml.orig +4 -3
  6. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/__init__.py +23 -2
  7. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_config.py +43 -7
  8. text2cypher-2.0.0/src/text2cypher/_errors.py +9 -0
  9. text2cypher-2.0.0/src/text2cypher/_examples.py +90 -0
  10. text2cypher-2.0.0/src/text2cypher/_execution.py +59 -0
  11. text2cypher-2.0.0/src/text2cypher/_generation/__init__.py +26 -0
  12. text2cypher-2.0.0/src/text2cypher/_generation/conversation.py +102 -0
  13. text2cypher-2.0.0/src/text2cypher/_generation/generate.py +107 -0
  14. text2cypher-2.0.0/src/text2cypher/_generation/header.py +69 -0
  15. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_generation/problems.py +13 -6
  16. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_generation/prompts.py +108 -35
  17. text2cypher-2.0.0/src/text2cypher/_generation/read_skill.py +93 -0
  18. text2cypher-2.0.0/src/text2cypher/_generation/schema_filter.py +225 -0
  19. text2cypher-2.0.0/src/text2cypher/_generation/typos.py +81 -0
  20. text2cypher-2.0.0/src/text2cypher/_pipeline.py +115 -0
  21. text2cypher-2.0.0/src/text2cypher/_results.py +210 -0
  22. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_schema_source.py +44 -5
  23. text2cypher-2.0.0/src/text2cypher/_skills/__init__.py +69 -0
  24. text2cypher-2.0.0/src/text2cypher/_skills/functions/skill.md +67 -0
  25. text2cypher-2.0.0/src/text2cypher/_skills/graph-algorithms/skill.md +57 -0
  26. text2cypher-2.0.0/src/text2cypher/_skills/path-finding/skill.md +61 -0
  27. text2cypher-2.0.0/src/text2cypher/_workflow.py +301 -0
  28. text2cypher-2.0.0/src/text2cypher/llm/__init__.py +24 -0
  29. text2cypher-2.0.0/src/text2cypher/llm/_adapt.py +38 -0
  30. text2cypher-2.0.0/src/text2cypher/llm/_base.py +158 -0
  31. text2cypher-2.0.0/src/text2cypher/llm/_fake.py +81 -0
  32. text2cypher-2.0.0/src/text2cypher/llm/_openai.py +179 -0
  33. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/__init__.py +2 -1
  34. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/_filter.py +15 -3
  35. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/_model.py +10 -1
  36. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/_render.py +17 -4
  37. text2cypher-1.1.0/src/text2cypher/_errors.py +0 -5
  38. text2cypher-1.1.0/src/text2cypher/_execution.py +0 -25
  39. text2cypher-1.1.0/src/text2cypher/_generation/__init__.py +0 -8
  40. text2cypher-1.1.0/src/text2cypher/_generation/generate.py +0 -63
  41. text2cypher-1.1.0/src/text2cypher/_pipeline.py +0 -91
  42. text2cypher-1.1.0/src/text2cypher/_results.py +0 -91
  43. text2cypher-1.1.0/src/text2cypher/_workflow.py +0 -108
  44. text2cypher-1.1.0/src/text2cypher/llm/__init__.py +0 -5
  45. text2cypher-1.1.0/src/text2cypher/llm/_base.py +0 -43
  46. text2cypher-1.1.0/src/text2cypher/llm/_fake.py +0 -47
  47. text2cypher-1.1.0/src/text2cypher/llm/_openai.py +0 -59
  48. {text2cypher-1.1.0 → text2cypher-2.0.0}/LICENSE +0 -0
  49. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_generation/extract.py +0 -0
  50. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_validation/__init__.py +0 -0
  51. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_validation/issues.py +0 -0
  52. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/_validation/validator.py +0 -0
  53. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/py.typed +0 -0
  54. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/_from_snapshot.py +0 -0
  55. {text2cypher-1.1.0 → text2cypher-2.0.0}/src/text2cypher/schema/_stopwords.py +0 -0
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: text2cypher
3
- Version: 1.1.0
3
+ Version: 2.0.0
4
4
  Summary: text2cypher: Generate validated Cypher queries from natural language text with LLMs
5
5
  Keywords: cypher,text2cypher,falkordb,llm,knowledge-graph,openCypher,graphdb
6
6
  Author: Kwaku Yeboah-Antwi
7
7
  License-Expression: Apache-2.0
8
8
  License-File: LICENSE
9
+ License-File: THIRD_PARTY_NOTICES
9
10
  Classifier: Development Status :: 5 - Production/Stable
10
11
  Classifier: Framework :: AsyncIO
11
12
  Classifier: Intended Audience :: Developers
@@ -33,6 +34,7 @@ Description-Content-Type: text/markdown
33
34
  # text2cypher
34
35
 
35
36
  **Generate validated Cypher queries from natural language text with LLMs**
37
+
36
38
  *Ask a question in plain language and get back a read-only Cypher query that has been checked against your [FalkorDB](https://www.falkordb.com/) graph.*
37
39
 
38
40
  [![CI](https://github.com/Killeroid/text2cypher/actions/workflows/ci.yml/badge.svg)](https://github.com/Killeroid/text2cypher/actions/workflows/ci.yml)
@@ -45,9 +47,13 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
45
47
  * **Grounded in your graph**: the prompt carries the schema read from the graph itself (labels, relationship types, properties with their value types, the paths that exist, and the indexes), cut down to what the question is about.
46
48
  * **Validated before it is returned**: syntax, schema (labels, relationship types, paths and their direction) and property checks. A query that could write to the graph is never valid.
47
49
  * **Self-correcting**: the problems found are written back to the LLM. If the cut-down schema does not get there, the loop moves to the full one.
48
- * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out), with every attempt, its issues, the schema it used and its token usage.
49
- * **Optional execution**: run the final query read-only, with a timeout, and get the rows.
50
- * **Bring your own LLM**: a one-method protocol, with an OpenAI client included. Async throughout.
50
+ * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out, or the LLM sent nothing twice), with every attempt, its issues, the schema it used and its token usage.
51
+ * **LLM schema filter** (optional): on a large graph, a model chooses which labels and relationships a question needs, in place of the word matching; it can be a cheaper model than the main one. Measured on a large schema: it picks the right part more often than the word matching.
52
+ * **Example values**: the schema shows up to three values of each property, so the LLM writes values the way your graph does. They are real data sent to the LLM provider: `Config(example_values=0)` sends none.
53
+ * **Skills** (optional): short guides to graph algorithms, path finding and the functions FalkorDB has, which the LLM reads with a tool only when a question needs them. Measured: they help a smaller model, and a stronger one gains little.
54
+ * **Typos fixed without the LLM** (optional): a misspelled label, relationship type or property that is a likely typo of exactly one name in your graph is replaced and the query validated again, at no cost in LLM calls.
55
+ * **Optional execution**: run the query read-only, with a timeout, and get the rows; a query that FalkorDB fails at run time is sent back to the LLM like any other problem.
56
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
51
57
 
52
58
  ## Installation
53
59
 
@@ -65,12 +71,13 @@ You need a FalkorDB graph that has data, reachable with the async client (`falko
65
71
  import asyncio
66
72
 
67
73
  from falkordb.asyncio import FalkorDB
68
- from text2cypher import OpenAIClient, Text2Cypher
74
+ from openai import AsyncOpenAI
75
+ from text2cypher import Text2Cypher
69
76
 
70
77
 
71
78
  async def main() -> None:
72
79
  client = FalkorDB(host="localhost", port=6379) # one client per event loop
73
- agent = Text2Cypher(client, OpenAIClient("your-model"))
80
+ agent = Text2Cypher(client, AsyncOpenAI(), model="your-model")
74
81
 
75
82
  result = await agent.run("Which actors appeared in The Matrix?", graph="movies")
76
83
  print(result.status) # "valid", "unanswerable" or "failed"
@@ -84,7 +91,7 @@ async def main() -> None:
84
91
  asyncio.run(main())
85
92
  ```
86
93
 
87
- Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant (see below).
94
+ Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
88
95
 
89
96
  There is also [a quickstart that needs no model and no server](https://github.com/Killeroid/text2cypher/blob/main/examples/quickstart.py): it starts an embedded FalkorDB and answers with a scripted LLM, including one correction.
90
97
 
@@ -92,7 +99,12 @@ There is also [a quickstart that needs no model and no server](https://github.co
92
99
 
93
100
  * **Checked**: the query is valid Cypher for FalkorDB, it cannot write, its parameters are provided (the prompt asks for values written in the query, so a `$name` is a problem), the labels, relationship types and paths exist in the direction used, and every property read exists on the label or relationship type it is read from.
94
101
  * **Not checked**: that the query means what the question meant. A query can be valid and still answer another question, for example by using a property with a similar name. Look at the query, or at the rows, before you rely on them.
95
- * **Known limits**: the prompts, the loop and the schema filter have been tried with Claude Haiku on two small test graphs (6 and 36 labels); the filter was measured offline on the larger one. How well they do on your data, on a large schema or with other models is not measured yet, so check the queries and the rows on your own questions (the [`evals/`](https://github.com/Killeroid/text2cypher/blob/main/evals/README.md) harness is there for that). Prompts and the filter's matching can change in a minor version; the public names (`text2cypher.__all__`, `text2cypher.llm` and `text2cypher.schema`) follow [semantic versioning](https://semver.org/).
102
+
103
+ ## Configuration
104
+
105
+ * See [the configuration table in Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
106
+ * Choose LLM models based on your requirements. Different models provide different balances of speed and accuracy and cost. See [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html) for more details.
107
+
96
108
 
97
109
  ## Documentation
98
110
 
@@ -101,6 +113,7 @@ The full documentation is at **[text2cypher.readthedocs.io](https://text2cypher.
101
113
  * [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html): the result, the configuration, running the query, errors
102
114
  * [How it works](https://text2cypher.readthedocs.io/en/latest/how-it-works.html): the loop, the escalation and what it costs
103
115
  * [The schema and its filter](https://text2cypher.readthedocs.io/en/latest/schema.html): what the LLM is shown, your own filter, keeping the schema between runs
116
+ * [When a question fails](https://text2cypher.readthedocs.io/en/latest/troubleshooting.html): what to look at, and what to try, for each outcome
104
117
  * [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html): your own client, other OpenAI-compatible models, `FakeLLM` for tests
105
118
  * [What is and is not checked](https://text2cypher.readthedocs.io/en/latest/checks.html) and the [API reference](https://text2cypher.readthedocs.io/en/latest/reference.html)
106
119
 
@@ -1,6 +1,7 @@
1
1
  # text2cypher
2
2
 
3
3
  **Generate validated Cypher queries from natural language text with LLMs**
4
+
4
5
  *Ask a question in plain language and get back a read-only Cypher query that has been checked against your [FalkorDB](https://www.falkordb.com/) graph.*
5
6
 
6
7
  [![CI](https://github.com/Killeroid/text2cypher/actions/workflows/ci.yml/badge.svg)](https://github.com/Killeroid/text2cypher/actions/workflows/ci.yml)
@@ -13,9 +14,13 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
13
14
  * **Grounded in your graph**: the prompt carries the schema read from the graph itself (labels, relationship types, properties with their value types, the paths that exist, and the indexes), cut down to what the question is about.
14
15
  * **Validated before it is returned**: syntax, schema (labels, relationship types, paths and their direction) and property checks. A query that could write to the graph is never valid.
15
16
  * **Self-correcting**: the problems found are written back to the LLM. If the cut-down schema does not get there, the loop moves to the full one.
16
- * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out), with every attempt, its issues, the schema it used and its token usage.
17
- * **Optional execution**: run the final query read-only, with a timeout, and get the rows.
18
- * **Bring your own LLM**: a one-method protocol, with an OpenAI client included. Async throughout.
17
+ * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out, or the LLM sent nothing twice), with every attempt, its issues, the schema it used and its token usage.
18
+ * **LLM schema filter** (optional): on a large graph, a model chooses which labels and relationships a question needs, in place of the word matching; it can be a cheaper model than the main one. Measured on a large schema: it picks the right part more often than the word matching.
19
+ * **Example values**: the schema shows up to three values of each property, so the LLM writes values the way your graph does. They are real data sent to the LLM provider: `Config(example_values=0)` sends none.
20
+ * **Skills** (optional): short guides to graph algorithms, path finding and the functions FalkorDB has, which the LLM reads with a tool only when a question needs them. Measured: they help a smaller model, and a stronger one gains little.
21
+ * **Typos fixed without the LLM** (optional): a misspelled label, relationship type or property that is a likely typo of exactly one name in your graph is replaced and the query validated again, at no cost in LLM calls.
22
+ * **Optional execution**: run the query read-only, with a timeout, and get the rows; a query that FalkorDB fails at run time is sent back to the LLM like any other problem.
23
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
19
24
 
20
25
  ## Installation
21
26
 
@@ -33,12 +38,13 @@ You need a FalkorDB graph that has data, reachable with the async client (`falko
33
38
  import asyncio
34
39
 
35
40
  from falkordb.asyncio import FalkorDB
36
- from text2cypher import OpenAIClient, Text2Cypher
41
+ from openai import AsyncOpenAI
42
+ from text2cypher import Text2Cypher
37
43
 
38
44
 
39
45
  async def main() -> None:
40
46
  client = FalkorDB(host="localhost", port=6379) # one client per event loop
41
- agent = Text2Cypher(client, OpenAIClient("your-model"))
47
+ agent = Text2Cypher(client, AsyncOpenAI(), model="your-model")
42
48
 
43
49
  result = await agent.run("Which actors appeared in The Matrix?", graph="movies")
44
50
  print(result.status) # "valid", "unanswerable" or "failed"
@@ -52,7 +58,7 @@ async def main() -> None:
52
58
  asyncio.run(main())
53
59
  ```
54
60
 
55
- Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant (see below).
61
+ Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
56
62
 
57
63
  There is also [a quickstart that needs no model and no server](https://github.com/Killeroid/text2cypher/blob/main/examples/quickstart.py): it starts an embedded FalkorDB and answers with a scripted LLM, including one correction.
58
64
 
@@ -60,7 +66,12 @@ There is also [a quickstart that needs no model and no server](https://github.co
60
66
 
61
67
  * **Checked**: the query is valid Cypher for FalkorDB, it cannot write, its parameters are provided (the prompt asks for values written in the query, so a `$name` is a problem), the labels, relationship types and paths exist in the direction used, and every property read exists on the label or relationship type it is read from.
62
68
  * **Not checked**: that the query means what the question meant. A query can be valid and still answer another question, for example by using a property with a similar name. Look at the query, or at the rows, before you rely on them.
63
- * **Known limits**: the prompts, the loop and the schema filter have been tried with Claude Haiku on two small test graphs (6 and 36 labels); the filter was measured offline on the larger one. How well they do on your data, on a large schema or with other models is not measured yet, so check the queries and the rows on your own questions (the [`evals/`](https://github.com/Killeroid/text2cypher/blob/main/evals/README.md) harness is there for that). Prompts and the filter's matching can change in a minor version; the public names (`text2cypher.__all__`, `text2cypher.llm` and `text2cypher.schema`) follow [semantic versioning](https://semver.org/).
69
+
70
+ ## Configuration
71
+
72
+ * See [the configuration table in Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
73
+ * Choose LLM models based on your requirements. Different models provide different balances of speed and accuracy and cost. See [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html) for more details.
74
+
64
75
 
65
76
  ## Documentation
66
77
 
@@ -69,6 +80,7 @@ The full documentation is at **[text2cypher.readthedocs.io](https://text2cypher.
69
80
  * [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html): the result, the configuration, running the query, errors
70
81
  * [How it works](https://text2cypher.readthedocs.io/en/latest/how-it-works.html): the loop, the escalation and what it costs
71
82
  * [The schema and its filter](https://text2cypher.readthedocs.io/en/latest/schema.html): what the LLM is shown, your own filter, keeping the schema between runs
83
+ * [When a question fails](https://text2cypher.readthedocs.io/en/latest/troubleshooting.html): what to look at, and what to try, for each outcome
72
84
  * [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html): your own client, other OpenAI-compatible models, `FakeLLM` for tests
73
85
  * [What is and is not checked](https://text2cypher.readthedocs.io/en/latest/checks.html) and the [API reference](https://text2cypher.readthedocs.io/en/latest/reference.html)
74
86
 
@@ -0,0 +1,31 @@
1
+ Third-party notices
2
+ ===================
3
+
4
+ The "path-finding" skill (src/text2cypher/_skills/path-finding/skill.md) is adapted from
5
+ the skill of the same subject in the text-to-cypher project of FalkorDB
6
+ (https://github.com/FalkorDB/text-to-cypher, assets/cypher-skills), which is itself derived
7
+ from FalkorDB's skills repository (https://github.com/FalkorDB/skills). Its examples and
8
+ its description of the options were rewritten and checked against a running FalkorDB.
9
+ Those projects are licensed as follows.
10
+
11
+ MIT License
12
+
13
+ Copyright (c) 2025 FalkorDB
14
+
15
+ Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ of this software and associated documentation files (the "Software"), to deal
17
+ in the Software without restriction, including without limitation the rights
18
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ copies of the Software, and to permit persons to whom the Software is
20
+ furnished to do so, subject to the following conditions:
21
+
22
+ The above copyright notice and this permission notice shall be included in all
23
+ copies or substantial portions of the Software.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
31
+ SOFTWARE.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.1.0"
3
+ version = "2.0.0"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -34,7 +34,10 @@ classifiers = [
34
34
  "Typing :: Typed",
35
35
  ]
36
36
  license = "Apache-2.0"
37
- license-files = ["LICENSE"]
37
+ license-files = [
38
+ "LICENSE",
39
+ "THIRD_PARTY_NOTICES",
40
+ ]
38
41
 
39
42
  [[project.authors]]
40
43
  name = "Kwaku Yeboah-Antwi"
@@ -116,9 +119,10 @@ layers = [
116
119
  "text2cypher._pipeline",
117
120
  "text2cypher._workflow",
118
121
  "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
122
+ "text2cypher._examples",
119
123
  "text2cypher._results",
120
124
  "text2cypher._validation",
121
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
125
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
122
126
  ]
123
127
 
124
128
  [[tool.importlinter.contracts]]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.1.0"
3
+ version = "2.0.0"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -29,7 +29,7 @@ classifiers = [
29
29
  "Typing :: Typed",
30
30
  ]
31
31
  license = "Apache-2.0"
32
- license-files = ["LICENSE"]
32
+ license-files = ["LICENSE", "THIRD_PARTY_NOTICES"]
33
33
 
34
34
  [build-system]
35
35
  requires = ["uv_build>=0.13.1,<0.14.0"]
@@ -94,9 +94,10 @@ layers = [
94
94
  "text2cypher._pipeline",
95
95
  "text2cypher._workflow",
96
96
  "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
97
+ "text2cypher._examples",
97
98
  "text2cypher._results",
98
99
  "text2cypher._validation",
99
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
100
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
100
101
  ]
101
102
 
102
103
  [[tool.importlinter.contracts]]
@@ -8,15 +8,26 @@ change without notice.
8
8
  from importlib.metadata import PackageNotFoundError, version
9
9
 
10
10
  from text2cypher._config import Config
11
- from text2cypher._errors import GraphNotFoundError
11
+ from text2cypher._errors import GraphNotFoundError, Text2CypherError
12
+ from text2cypher._generation import AsyncSchemaFilter, FilterResult, LLMSchemaFilter
12
13
  from text2cypher._pipeline import Text2Cypher
13
- from text2cypher._results import Attempt, Records, Result
14
+ from text2cypher._results import (
15
+ Attempt,
16
+ DatabaseError,
17
+ LLMError,
18
+ Records,
19
+ Result,
20
+ )
14
21
  from text2cypher._validation import Issue, ValidationResult
15
22
  from text2cypher.llm import (
23
+ AsyncChatClient,
16
24
  AsyncLLMClient,
17
25
  Completion,
18
26
  FakeLLM,
27
+ Message,
19
28
  OpenAIClient,
29
+ Tool,
30
+ ToolCall,
20
31
  Usage,
21
32
  )
22
33
  from text2cypher.schema import GraphSchema, SchemaFilter, filter_schema
@@ -27,19 +38,29 @@ except PackageNotFoundError: # running from a source tree that is not installed
27
38
  __version__ = "0+unknown"
28
39
 
29
40
  __all__ = [
41
+ "AsyncChatClient",
30
42
  "AsyncLLMClient",
43
+ "AsyncSchemaFilter",
31
44
  "Attempt",
32
45
  "Completion",
33
46
  "Config",
47
+ "DatabaseError",
34
48
  "FakeLLM",
49
+ "FilterResult",
35
50
  "GraphNotFoundError",
36
51
  "GraphSchema",
37
52
  "Issue",
53
+ "LLMError",
54
+ "LLMSchemaFilter",
55
+ "Message",
38
56
  "OpenAIClient",
39
57
  "Records",
40
58
  "Result",
41
59
  "SchemaFilter",
42
60
  "Text2Cypher",
61
+ "Text2CypherError",
62
+ "Tool",
63
+ "ToolCall",
43
64
  "Usage",
44
65
  "ValidationResult",
45
66
  "__version__",
@@ -11,8 +11,12 @@ class Config:
11
11
  with the filtered schema; the rest, up to ``total_attempts``, with the full one.
12
12
 
13
13
  With ``execute``, a query that passed validation is run (read-only) and its rows
14
- are on the result. Generated queries can be expensive, so a run is stopped after
15
- ``execute_timeout_ms`` milliseconds; ``None`` lets it run without limit.
14
+ are on the result. If FalkorDB rejects or fails it (a type error on a value, a
15
+ division by zero), that error is sent back for a correction, which counts like any
16
+ other, and the result is ``failed`` when the corrections run out. Generated queries
17
+ can be expensive, so a run is stopped after ``execute_timeout_ms`` milliseconds;
18
+ ``None`` lets it run without limit. A timeout or a lost connection ends the run with
19
+ the valid query and the error, because it says nothing about the query.
16
20
 
17
21
  Two optional checks report more than the validators do by default. ``check_types``
18
22
  (on) reports a property compared with a value of another type, and ``sum``, ``avg`` and
@@ -25,7 +29,29 @@ class Config:
25
29
  By default the LLM writes the values of a query inside it. With ``use_parameters`` it
26
30
  puts them in a ``CYPHER`` header before the query (``CYPHER name='Ann' MATCH (p
27
31
  {name: $name}) ...``) and uses them as parameters, which FalkorDB can plan once and
28
- reuse. The query stays one string: ``Result.query`` runs as it is.
32
+ reuse. The query stays one string: ``Result.query`` runs as it is. FalkorDB wants the
33
+ pairs separated by spaces and a ``CYPHER`` in front, so a header with commas, or
34
+ without it, is written that way without asking the LLM again (that changes nothing about
35
+ what the query means) and the query is validated again.
36
+
37
+ With ``autofix_typos``, a label, relationship type or property that the validators
38
+ report as unknown is first replaced, without the LLM, by the one name of the graph it
39
+ is a likely typo of (``Persn`` for ``Person``), and the query is validated again. If it
40
+ passes, that is the result and no LLM call and no correction was spent. If it does
41
+ not, the LLM gets the query it wrote, as usual. Off by default: a fix can make a query
42
+ valid and still not what the question meant.
43
+
44
+ With ``use_skills`` the LLM is offered short guides to parts of FalkorDB's Cypher that
45
+ are easy to get wrong (graph algorithms, path finding, functions). It sees what each is
46
+ for, and reads a skill, by calling a tool, only when the question needs it; each read
47
+ is another call to the model, and a later correction already has what was read. A client
48
+ that cannot be offered tools is given every skill in the prompt instead.
49
+
50
+ The schema shows up to ``example_values`` values of each property (``title: STRING (e.g.
51
+ 'Alien', 'Heat')``), so the LLM writes a value the way the graph does: spelling, case,
52
+ format. They are read from the graph, one small query per property, and are **data from
53
+ your graph that goes to the LLM provider**: pass ``0`` to send none. They are kept while the
54
+ structure of the graph is the same, so a graph pays for the queries once, not on every run.
29
55
 
30
56
  The schema is read from the graph on every run by default. With
31
57
  ``schema_refresh_seconds`` it is kept: a run that comes after that many seconds first
@@ -37,25 +63,33 @@ class Config:
37
63
  attempts_w_filtered: Corrections made with the filtered schema.
38
64
  total_attempts: Corrections in all, with the filtered and the full schema. The
39
65
  first query is not a correction.
40
- execute: Run the final query when it is valid, read-only, and put the rows on
41
- the result.
66
+ execute: Run a query that is valid, read-only, correct it if FalkorDB fails it, and
67
+ put the rows on the result.
42
68
  execute_timeout_ms: Stop an execution after this many milliseconds, or never
43
69
  if ``None``.
44
70
  use_parameters: Ask the LLM for the values in a ``CYPHER`` header and parameters.
45
71
  check_types: Report type mismatches of properties.
46
72
  check_performance: Report queries that may be expensive, which is off by default.
73
+ example_values: How many example values of each property to show the LLM; ``0``
74
+ sends none.
75
+ use_skills: Offer the LLM the skills, to read when a question needs them.
76
+ autofix_typos: Fix a misspelled name in a query without the LLM when exactly one
77
+ name of the graph is a likely typo of it.
47
78
  schema_refresh_seconds: Keep the schema of a graph and check it for changes at
48
79
  most this often, or read it on every run if ``None``.
49
80
  """
50
81
 
51
- attempts_w_filtered: int = 3
52
- total_attempts: int = 5
82
+ attempts_w_filtered: int = 5
83
+ total_attempts: int = 10
53
84
  execute: bool = False
54
85
  execute_timeout_ms: int | None = 10_000
55
86
  schema_refresh_seconds: float | None = None
56
87
  use_parameters: bool = False
57
88
  check_types: bool = True
58
89
  check_performance: bool = False
90
+ example_values: int = 3
91
+ autofix_typos: bool = False
92
+ use_skills: bool = False
59
93
 
60
94
  def __post_init__(self) -> None:
61
95
  if self.attempts_w_filtered < 0:
@@ -66,5 +100,7 @@ class Config:
66
100
  raise ValueError("total_attempts must be at least attempts_w_filtered")
67
101
  if self.execute_timeout_ms is not None and self.execute_timeout_ms <= 0:
68
102
  raise ValueError("execute_timeout_ms must be positive")
103
+ if self.example_values < 0:
104
+ raise ValueError("example_values must be 0 or more")
69
105
  if self.schema_refresh_seconds is not None and self.schema_refresh_seconds < 0:
70
106
  raise ValueError("schema_refresh_seconds must be 0 or more")
@@ -0,0 +1,9 @@
1
+ """The errors the library raises itself."""
2
+
3
+
4
+ class Text2CypherError(Exception):
5
+ """The base of the errors text2cypher raises itself, so one ``except`` catches them all."""
6
+
7
+
8
+ class GraphNotFoundError(Text2CypherError, ValueError):
9
+ """The graph does not exist, or has no labelled nodes or relationships to query."""
@@ -0,0 +1,90 @@
1
+ """A few example values of each property, to show the LLM how values are written."""
2
+
3
+ import asyncio
4
+ from collections.abc import Mapping
5
+
6
+ from falkordb.asyncio import FalkorDB
7
+ from falkordb.asyncio.graph import AsyncGraph
8
+ from redis.exceptions import RedisError
9
+
10
+ from text2cypher.schema import GraphSchema
11
+ from text2cypher.schema._model import quote_identifier
12
+
13
+ type Examples = dict[str, dict[str, tuple[str, ...]]]
14
+
15
+ # Only values that read as plain text in a prompt; lists, maps, points and vectors do not
16
+ _SCALARS = {"String", "Integer", "Float", "Boolean"}
17
+ # The first non-null values read per property, of which the distinct ones are the
18
+ # examples: a read that stops after a few rows, where DISTINCT would read every one
19
+ _ROWS = 20
20
+ _LONGEST = 40
21
+ # A property that is slow to sample has no examples: they are a help, not a need
22
+ _TIMEOUT_MS = 2_000
23
+ _MAX_CONCURRENCY = 8
24
+
25
+
26
+ async def sample_examples(
27
+ client: FalkorDB, graph: str, schema: GraphSchema, count: int
28
+ ) -> tuple[Examples, Examples]:
29
+ """Up to ``count`` example values of each scalar property of ``schema``: of the
30
+ labels, then of the relationship types. A query that fails gives no examples.
31
+
32
+ Each is one read-only query that stops after a few rows, with a timeout.
33
+ """
34
+ handle = client.select_graph(graph)
35
+ gate = asyncio.Semaphore(_MAX_CONCURRENCY)
36
+
37
+ async def sample(query: str) -> tuple[str, ...]:
38
+ async with gate:
39
+ return await _first_values(handle, query, count)
40
+
41
+ jobs = {
42
+ (kind, entity, prop): sample(_query(kind, entity, prop))
43
+ for kind, entities in (
44
+ ("node", schema.node_properties),
45
+ ("relationship", schema.relationship_properties),
46
+ )
47
+ for entity, properties in entities.items()
48
+ for prop, types in properties.items()
49
+ if set(types) <= _SCALARS
50
+ }
51
+ found = dict(zip(jobs, await asyncio.gather(*jobs.values()), strict=True))
52
+ return (
53
+ _group(found, "node"),
54
+ _group(found, "relationship"),
55
+ )
56
+
57
+
58
+ def _query(kind: str, entity: str, prop: str) -> str:
59
+ name, key = quote_identifier(entity), quote_identifier(prop)
60
+ pattern = f"(e:{name})" if kind == "node" else f"()-[e:{name}]->()"
61
+ return f"MATCH {pattern} WHERE e.{key} IS NOT NULL RETURN e.{key} LIMIT {_ROWS}"
62
+
63
+
64
+ async def _first_values(graph: AsyncGraph, query: str, count: int) -> tuple[str, ...]:
65
+ try:
66
+ result = await graph.ro_query(query, timeout=_TIMEOUT_MS)
67
+ except RedisError:
68
+ return ()
69
+ distinct = dict.fromkeys(_literal(row[0]) for row in result.result_set)
70
+ return tuple(distinct)[:count]
71
+
72
+
73
+ def _group(
74
+ found: Mapping[tuple[str, str, str], tuple[str, ...]], kind: str
75
+ ) -> Examples:
76
+ grouped: Examples = {}
77
+ for (found_kind, entity, prop), values in found.items():
78
+ if found_kind == kind and values:
79
+ grouped.setdefault(entity, {})[prop] = values
80
+ return grouped
81
+
82
+
83
+ def _literal(value: object) -> str:
84
+ """``value`` as it is written in a query; a long string is cut short."""
85
+ if isinstance(value, bool):
86
+ return "true" if value else "false"
87
+ if not isinstance(value, str):
88
+ return str(value)
89
+ text = value.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
90
+ return f"'{text[:_LONGEST]}…'" if len(text) > _LONGEST else f"'{text}'"
@@ -0,0 +1,59 @@
1
+ """Run a query that passed validation, read-only."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from falkordb.asyncio.graph import AsyncGraph
6
+ from redis.exceptions import RedisError, ResponseError
7
+
8
+ from text2cypher._results import Records
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Execution:
13
+ """How running a query went: the rows it returned, or the error FalkorDB gave.
14
+
15
+ ``correctable`` says whether another query might not fail: FalkorDB rejected or
16
+ failed this one. A timeout, or a connection that is lost, says nothing about the query.
17
+ """
18
+
19
+ records: Records | None = None
20
+ error: str | None = None
21
+ correctable: bool = False
22
+
23
+
24
+ async def execute_cypher(
25
+ graph: AsyncGraph, query: str, *, timeout_ms: int | None = None
26
+ ) -> Records:
27
+ """The rows ``query`` returns from ``graph``.
28
+
29
+ It runs as a read-only query, which FalkorDB rejects if it could write. Values
30
+ are the client's: nodes, relationships and paths stay ``falkordb`` objects.
31
+
32
+ Raises:
33
+ redis.exceptions.RedisError: If FalkorDB rejects or fails the query (a
34
+ ``ResponseError``, also when it runs longer than ``timeout_ms``) or cannot be
35
+ reached.
36
+ """
37
+ result = await graph.ro_query(query, timeout=timeout_ms)
38
+ return Records(
39
+ columns=tuple(name for _, name in result.header),
40
+ rows=tuple(tuple(row) for row in result.result_set),
41
+ )
42
+
43
+
44
+ async def run_query(
45
+ graph: AsyncGraph, query: str, *, timeout_ms: int | None = None
46
+ ) -> Execution:
47
+ """``execute_cypher``, with an error from FalkorDB or the connection as a value.
48
+
49
+ Any other error is a bug and propagates.
50
+ """
51
+ try:
52
+ records = await execute_cypher(graph, query, timeout_ms=timeout_ms)
53
+ except RedisError as error:
54
+ return Execution(error=str(error), correctable=_is_the_querys_fault(error))
55
+ return Execution(records=records)
56
+
57
+
58
+ def _is_the_querys_fault(error: RedisError) -> bool:
59
+ return isinstance(error, ResponseError) and "timed out" not in str(error).lower()
@@ -0,0 +1,26 @@
1
+ from text2cypher._generation.conversation import Round
2
+ from text2cypher._generation.extract import extract_cypher
3
+ from text2cypher._generation.generate import Generation, generate_cypher
4
+ from text2cypher._generation.header import repair_header
5
+ from text2cypher._generation.read_skill import SkillLoopFailed
6
+ from text2cypher._generation.schema_filter import (
7
+ AsyncSchemaFilter,
8
+ FilterResult,
9
+ LLMSchemaFilter,
10
+ apply_filter,
11
+ )
12
+ from text2cypher._generation.typos import fix_typos
13
+
14
+ __all__ = [
15
+ "AsyncSchemaFilter",
16
+ "FilterResult",
17
+ "Generation",
18
+ "LLMSchemaFilter",
19
+ "Round",
20
+ "SkillLoopFailed",
21
+ "apply_filter",
22
+ "extract_cypher",
23
+ "fix_typos",
24
+ "generate_cypher",
25
+ "repair_header",
26
+ ]