text2cypher 1.2.0__tar.gz → 2.1.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 (51) hide show
  1. {text2cypher-1.2.0 → text2cypher-2.1.0}/PKG-INFO +18 -8
  2. {text2cypher-1.2.0 → text2cypher-2.1.0}/README.md +15 -6
  3. text2cypher-2.1.0/THIRD_PARTY_NOTICES +31 -0
  4. {text2cypher-1.2.0 → text2cypher-2.1.0}/pyproject.toml +9 -7
  5. {text2cypher-1.2.0 → text2cypher-2.1.0}/pyproject.toml.orig +6 -7
  6. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/__init__.py +18 -0
  7. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_config.py +9 -0
  8. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/__init__.py +12 -0
  9. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/conversation.py +3 -1
  10. text2cypher-2.1.0/src/text2cypher/_generation/generate.py +114 -0
  11. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/prompts.py +64 -2
  12. text2cypher-2.1.0/src/text2cypher/_generation/read_skill.py +99 -0
  13. text2cypher-2.1.0/src/text2cypher/_generation/schema_filter.py +225 -0
  14. text2cypher-2.1.0/src/text2cypher/_graph/__init__.py +14 -0
  15. text2cypher-1.2.0/src/text2cypher/_schema_source.py → text2cypher-2.1.0/src/text2cypher/_graph/schema_source.py +1 -1
  16. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_pipeline.py +50 -10
  17. text2cypher-2.1.0/src/text2cypher/_results/__init__.py +37 -0
  18. text2cypher-1.2.0/src/text2cypher/_results.py → text2cypher-2.1.0/src/text2cypher/_results/results.py +60 -13
  19. text2cypher-2.1.0/src/text2cypher/_results/values.py +150 -0
  20. text2cypher-2.1.0/src/text2cypher/_skills/__init__.py +178 -0
  21. text2cypher-2.1.0/src/text2cypher/_skills/functions/SKILL.md +67 -0
  22. text2cypher-2.1.0/src/text2cypher/_skills/graph-algorithms/SKILL.md +57 -0
  23. text2cypher-2.1.0/src/text2cypher/_skills/path-finding/SKILL.md +61 -0
  24. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_workflow.py +136 -23
  25. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/llm/__init__.py +4 -0
  26. text2cypher-2.1.0/src/text2cypher/llm/_adapt.py +38 -0
  27. text2cypher-2.1.0/src/text2cypher/llm/_base.py +158 -0
  28. text2cypher-2.1.0/src/text2cypher/llm/_fake.py +81 -0
  29. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/llm/_openai.py +98 -5
  30. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/schema/__init__.py +2 -1
  31. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/schema/_filter.py +13 -3
  32. text2cypher-2.1.0/src/text2cypher/skills.py +5 -0
  33. text2cypher-1.2.0/src/text2cypher/_generation/generate.py +0 -51
  34. text2cypher-1.2.0/src/text2cypher/llm/_base.py +0 -76
  35. text2cypher-1.2.0/src/text2cypher/llm/_fake.py +0 -57
  36. {text2cypher-1.2.0 → text2cypher-2.1.0}/LICENSE +0 -0
  37. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_errors.py +0 -0
  38. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/extract.py +0 -0
  39. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/header.py +0 -0
  40. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/problems.py +0 -0
  41. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_generation/typos.py +0 -0
  42. /text2cypher-1.2.0/src/text2cypher/_examples.py → /text2cypher-2.1.0/src/text2cypher/_graph/examples.py +0 -0
  43. /text2cypher-1.2.0/src/text2cypher/_execution.py → /text2cypher-2.1.0/src/text2cypher/_graph/execution.py +0 -0
  44. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_validation/__init__.py +0 -0
  45. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_validation/issues.py +0 -0
  46. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/_validation/validator.py +0 -0
  47. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/py.typed +0 -0
  48. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/schema/_from_snapshot.py +0 -0
  49. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/schema/_model.py +0 -0
  50. {text2cypher-1.2.0 → text2cypher-2.1.0}/src/text2cypher/schema/_render.py +0 -0
  51. {text2cypher-1.2.0 → text2cypher-2.1.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.2.0
3
+ Version: 2.1.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
@@ -17,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.13
17
18
  Classifier: Programming Language :: Python :: 3.14
18
19
  Classifier: Topic :: Database
19
20
  Classifier: Typing :: Typed
20
- Requires-Dist: cypher-guardrail>=1.4.0
21
+ Requires-Dist: cypher-guardrail>=1.5.1
21
22
  Requires-Dist: falkordb>=1.8.0
22
23
  Requires-Dist: openai>=3.31.0
23
24
  Requires-Dist: redis>=8.1.0
@@ -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,8 +47,10 @@ 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.
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.
49
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.
50
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.
51
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.
52
56
  * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
@@ -67,12 +71,13 @@ You need a FalkorDB graph that has data, reachable with the async client (`falko
67
71
  import asyncio
68
72
 
69
73
  from falkordb.asyncio import FalkorDB
70
- from text2cypher import OpenAIClient, Text2Cypher
74
+ from openai import AsyncOpenAI
75
+ from text2cypher import Text2Cypher
71
76
 
72
77
 
73
78
  async def main() -> None:
74
79
  client = FalkorDB(host="localhost", port=6379) # one client per event loop
75
- agent = Text2Cypher(client, OpenAIClient("your-model"))
80
+ agent = Text2Cypher(client, AsyncOpenAI(), model="your-model")
76
81
 
77
82
  result = await agent.run("Which actors appeared in The Matrix?", graph="movies")
78
83
  print(result.status) # "valid", "unanswerable" or "failed"
@@ -86,15 +91,20 @@ async def main() -> None:
86
91
  asyncio.run(main())
87
92
  ```
88
93
 
89
- 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.
90
95
 
91
- 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.
96
+ There is also [a quickstart](https://github.com/Killeroid/text2cypher/blob/main/examples/quickstart.py) that needs no model and no server: it starts an embedded FalkorDB and answers with a scripted LLM, including one correction.
92
97
 
93
98
  ## What is and is not checked
94
99
 
95
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.
96
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.
97
- * **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
+
98
108
 
99
109
  ## Documentation
100
110
 
@@ -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,8 +14,10 @@ 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
+ * **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.
17
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.
18
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.
19
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.
20
23
  * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
@@ -35,12 +38,13 @@ You need a FalkorDB graph that has data, reachable with the async client (`falko
35
38
  import asyncio
36
39
 
37
40
  from falkordb.asyncio import FalkorDB
38
- from text2cypher import OpenAIClient, Text2Cypher
41
+ from openai import AsyncOpenAI
42
+ from text2cypher import Text2Cypher
39
43
 
40
44
 
41
45
  async def main() -> None:
42
46
  client = FalkorDB(host="localhost", port=6379) # one client per event loop
43
- agent = Text2Cypher(client, OpenAIClient("your-model"))
47
+ agent = Text2Cypher(client, AsyncOpenAI(), model="your-model")
44
48
 
45
49
  result = await agent.run("Which actors appeared in The Matrix?", graph="movies")
46
50
  print(result.status) # "valid", "unanswerable" or "failed"
@@ -54,15 +58,20 @@ async def main() -> None:
54
58
  asyncio.run(main())
55
59
  ```
56
60
 
57
- 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.
58
62
 
59
- 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.
63
+ There is also [a quickstart](https://github.com/Killeroid/text2cypher/blob/main/examples/quickstart.py) that needs no model and no server: it starts an embedded FalkorDB and answers with a scripted LLM, including one correction.
60
64
 
61
65
  ## What is and is not checked
62
66
 
63
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.
64
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.
65
- * **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
+
66
75
 
67
76
  ## Documentation
68
77
 
@@ -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,11 +1,11 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.2.0"
3
+ version = "2.1.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"
7
7
  dependencies = [
8
- "cypher-guardrail>=1.4.0",
8
+ "cypher-guardrail>=1.5.1",
9
9
  "falkordb>=1.8.0",
10
10
  "openai>=3.31.0",
11
11
  "redis>=8.1.0",
@@ -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"
@@ -113,13 +116,12 @@ root_packages = [
113
116
  name = "The layers of the package"
114
117
  type = "layers"
115
118
  layers = [
116
- "text2cypher._pipeline",
119
+ "text2cypher._pipeline | text2cypher.skills",
117
120
  "text2cypher._workflow",
118
- "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
119
- "text2cypher._examples",
121
+ "text2cypher._generation | text2cypher._graph",
120
122
  "text2cypher._results",
121
123
  "text2cypher._validation",
122
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
124
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
123
125
  ]
124
126
 
125
127
  [[tool.importlinter.contracts]]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.2.0"
3
+ version = "2.1.0"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -8,7 +8,7 @@ authors = [
8
8
  ]
9
9
  requires-python = ">=3.12"
10
10
  dependencies = [
11
- "cypher-guardrail>=1.4.0",
11
+ "cypher-guardrail>=1.5.1",
12
12
  "falkordb>=1.8.0",
13
13
  "openai>=3.31.0",
14
14
  "redis>=8.1.0",
@@ -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"]
@@ -91,13 +91,12 @@ root_packages = ["text2cypher", "evals"]
91
91
  name = "The layers of the package"
92
92
  type = "layers"
93
93
  layers = [
94
- "text2cypher._pipeline",
94
+ "text2cypher._pipeline | text2cypher.skills",
95
95
  "text2cypher._workflow",
96
- "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
97
- "text2cypher._examples",
96
+ "text2cypher._generation | text2cypher._graph",
98
97
  "text2cypher._results",
99
98
  "text2cypher._validation",
100
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
99
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
101
100
  ]
102
101
 
103
102
  [[tool.importlinter.contracts]]
@@ -9,14 +9,20 @@ from importlib.metadata import PackageNotFoundError, version
9
9
 
10
10
  from text2cypher._config import Config
11
11
  from text2cypher._errors import GraphNotFoundError, Text2CypherError
12
+ from text2cypher._generation import AsyncSchemaFilter, FilterResult, LLMSchemaFilter
12
13
  from text2cypher._pipeline import Text2Cypher
13
14
  from text2cypher._results import (
14
15
  Attempt,
15
16
  DatabaseError,
17
+ GraphNode,
18
+ GraphPath,
19
+ GraphRelationship,
16
20
  LLMError,
17
21
  Records,
18
22
  Result,
23
+ to_python,
19
24
  )
25
+ from text2cypher._skills import Skill
20
26
  from text2cypher._validation import Issue, ValidationResult
21
27
  from text2cypher.llm import (
22
28
  AsyncChatClient,
@@ -25,6 +31,8 @@ from text2cypher.llm import (
25
31
  FakeLLM,
26
32
  Message,
27
33
  OpenAIClient,
34
+ Tool,
35
+ ToolCall,
28
36
  Usage,
29
37
  )
30
38
  from text2cypher.schema import GraphSchema, SchemaFilter, filter_schema
@@ -37,24 +45,34 @@ except PackageNotFoundError: # running from a source tree that is not installed
37
45
  __all__ = [
38
46
  "AsyncChatClient",
39
47
  "AsyncLLMClient",
48
+ "AsyncSchemaFilter",
40
49
  "Attempt",
41
50
  "Completion",
42
51
  "Config",
43
52
  "DatabaseError",
44
53
  "FakeLLM",
54
+ "FilterResult",
55
+ "GraphNode",
45
56
  "GraphNotFoundError",
57
+ "GraphPath",
58
+ "GraphRelationship",
46
59
  "GraphSchema",
47
60
  "Issue",
48
61
  "LLMError",
62
+ "LLMSchemaFilter",
49
63
  "Message",
50
64
  "OpenAIClient",
51
65
  "Records",
52
66
  "Result",
53
67
  "SchemaFilter",
68
+ "Skill",
54
69
  "Text2Cypher",
55
70
  "Text2CypherError",
71
+ "Tool",
72
+ "ToolCall",
56
73
  "Usage",
57
74
  "ValidationResult",
58
75
  "__version__",
59
76
  "filter_schema",
77
+ "to_python",
60
78
  ]
@@ -41,6 +41,13 @@ class Config:
41
41
  not, the LLM gets the query it wrote, as usual. Off by default: a fix can make a query
42
42
  valid and still not what the question meant.
43
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. Which skills,
49
+ the ones that ship or your own, is the ``skills`` argument of ``Text2Cypher``.
50
+
44
51
  The schema shows up to ``example_values`` values of each property (``title: STRING (e.g.
45
52
  'Alien', 'Heat')``), so the LLM writes a value the way the graph does: spelling, case,
46
53
  format. They are read from the graph, one small query per property, and are **data from
@@ -66,6 +73,7 @@ class Config:
66
73
  check_performance: Report queries that may be expensive, which is off by default.
67
74
  example_values: How many example values of each property to show the LLM; ``0``
68
75
  sends none.
76
+ use_skills: Offer the LLM the skills, to read when a question needs them.
69
77
  autofix_typos: Fix a misspelled name in a query without the LLM when exactly one
70
78
  name of the graph is a likely typo of it.
71
79
  schema_refresh_seconds: Keep the schema of a graph and check it for changes at
@@ -82,6 +90,7 @@ class Config:
82
90
  check_performance: bool = False
83
91
  example_values: int = 3
84
92
  autofix_typos: bool = False
93
+ use_skills: bool = False
85
94
 
86
95
  def __post_init__(self) -> None:
87
96
  if self.attempts_w_filtered < 0:
@@ -2,11 +2,23 @@ from text2cypher._generation.conversation import Round
2
2
  from text2cypher._generation.extract import extract_cypher
3
3
  from text2cypher._generation.generate import Generation, generate_cypher
4
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
+ )
5
12
  from text2cypher._generation.typos import fix_typos
6
13
 
7
14
  __all__ = [
15
+ "AsyncSchemaFilter",
16
+ "FilterResult",
8
17
  "Generation",
18
+ "LLMSchemaFilter",
9
19
  "Round",
20
+ "SkillLoopFailed",
21
+ "apply_filter",
10
22
  "extract_cypher",
11
23
  "fix_typos",
12
24
  "generate_cypher",
@@ -31,13 +31,15 @@ class Round:
31
31
  that had passed validation.
32
32
 
33
33
  ``schema_note`` marks the round whose turn tells the LLM that the schema is now the
34
- whole graph, after queries written with a part of it.
34
+ whole graph, after queries written with a part of it. ``skills_read`` are the ids of the
35
+ skills the LLM read to write the query; the next request already has them in its prompt.
35
36
  """
36
37
 
37
38
  query: str
38
39
  issues: tuple[Issue, ...]
39
40
  execution_error: str | None = None
40
41
  schema_note: bool = False
42
+ skills_read: tuple[str, ...] = ()
41
43
 
42
44
 
43
45
  def chat_messages(
@@ -0,0 +1,114 @@
1
+ """Ask an LLM for a Cypher query, or to correct one."""
2
+
3
+ from collections.abc import Mapping, Sequence
4
+ from dataclasses import dataclass
5
+ from typing import cast
6
+
7
+ from text2cypher._generation.conversation import (
8
+ Round,
9
+ chat_messages,
10
+ folded_message,
11
+ )
12
+ from text2cypher._generation.extract import extract_cypher
13
+ from text2cypher._generation.prompts import SkillsOffer, generator_system
14
+ from text2cypher._generation.read_skill import chat_reading_skills
15
+ from text2cypher._skills import Skill
16
+ from text2cypher.llm import AsyncChatClient, AsyncLLMClient, Completion, Message, Usage
17
+ from text2cypher.llm._base import supports_tools
18
+ from text2cypher.schema import GraphSchema
19
+
20
+
21
+ @dataclass(frozen=True, slots=True)
22
+ class Generation:
23
+ """A query an LLM wrote, empty if it declined, and the tokens that cost.
24
+
25
+ ``empty`` is a reply with no text at all, which is not the same as a decline (an empty
26
+ fenced block): it is a call that returned nothing. A refusal is not empty: it is the
27
+ model declining, in the one way it could. ``finish_reason`` is why the reply ended, when
28
+ the client says.
29
+ """
30
+
31
+ query: str
32
+ usage: Usage | None
33
+ skills: tuple[str, ...] = ()
34
+ empty: bool = False
35
+ finish_reason: str | None = None
36
+
37
+
38
+ async def generate_cypher(
39
+ llm: AsyncChatClient | AsyncLLMClient,
40
+ schema: GraphSchema,
41
+ question: str,
42
+ rounds: Sequence[Round] = (),
43
+ *,
44
+ parameterize: bool = False,
45
+ skills: bool = False,
46
+ catalog: Mapping[str, Skill] | None = None,
47
+ ) -> Generation:
48
+ """A query for ``question`` over ``schema``; empty if the LLM says it has none.
49
+
50
+ ``rounds`` are the queries it wrote before that had to be corrected, oldest first.
51
+ Each correction uses the same system prompt as the first query. A client that has
52
+ ``chat`` is given the conversation as turns; one with only ``complete`` is given it
53
+ as one message.
54
+
55
+ With ``skills``, a client that can be offered tools lists the skills and may read the
56
+ ones it needs (``Generation.skills`` says which, and the skills it read before are in
57
+ the prompt already); any other client has every skill in the prompt. ``catalog`` is the
58
+ skills on offer, by id; the ones that ship unless given.
59
+
60
+ Raises:
61
+ SkillLoopFailed: If a call fails after others of the same request succeeded.
62
+ """
63
+ offer = None
64
+ if skills:
65
+ read = tuple(dict.fromkeys(i for round_ in rounds for i in round_.skills_read))
66
+ offer = (
67
+ SkillsOffer(supports_tools(llm), read)
68
+ if catalog is None
69
+ else SkillsOffer(supports_tools(llm), read, catalog)
70
+ )
71
+ system = generator_system(schema, parameterize=parameterize, skills=offer)
72
+ messages = chat_messages(question, rounds, schema, parameterize=parameterize)
73
+ if offer is not None and offer.tools:
74
+ completion, read_now, usage = await chat_reading_skills(
75
+ cast("AsyncChatClient", llm), system, messages, offer.catalog
76
+ )
77
+ return Generation(
78
+ extract_cypher(completion.text),
79
+ usage,
80
+ read_now,
81
+ empty=_no_text(completion),
82
+ finish_reason=completion.finish_reason,
83
+ )
84
+ completion = await ask(
85
+ llm,
86
+ system,
87
+ messages,
88
+ folded_message(question, rounds, schema, parameterize=parameterize),
89
+ )
90
+ return Generation(
91
+ extract_cypher(completion.text),
92
+ completion.usage,
93
+ empty=_no_text(completion),
94
+ finish_reason=completion.finish_reason,
95
+ )
96
+
97
+
98
+ def _no_text(completion: Completion) -> bool:
99
+ """A reply with nothing in it, that is not a refusal (which is a decline)."""
100
+ return not completion.text.strip() and completion.finish_reason != "refusal"
101
+
102
+
103
+ async def ask(
104
+ llm: AsyncChatClient | AsyncLLMClient,
105
+ system: str,
106
+ messages: Sequence[Message],
107
+ folded: str,
108
+ ) -> Completion:
109
+ """The model's reply to a conversation: as turns when the client has ``chat``, else
110
+ as the one message ``folded``, which says the same."""
111
+ chat = getattr(llm, "chat", None)
112
+ if callable(chat):
113
+ return await chat(system, messages)
114
+ return await cast("AsyncLLMClient", llm).complete(system, folded)
@@ -1,5 +1,10 @@
1
1
  """The prompts: what the LLM is told to write a query."""
2
2
 
3
+ from collections.abc import Mapping
4
+ from dataclasses import dataclass, field
5
+
6
+ from text2cypher._skills import Skill
7
+ from text2cypher._skills import skills as shipped_skills
3
8
  from text2cypher.schema import GraphSchema, render_schema
4
9
 
5
10
  # The queries the rules and the examples show. tests/generation/test_prompt_rules.py runs each
@@ -100,6 +105,46 @@ _EXAMPLES_RULE = (
100
105
  "written (spelling and case)."
101
106
  )
102
107
 
108
+ _SKILLS_RULE = (
109
+ "- Skills are short guides to parts of FalkorDB that are easy to get wrong. Read a skill, "
110
+ "with read_skill, only when the question needs what it covers, before you write the query."
111
+ )
112
+
113
+
114
+ @dataclass(frozen=True, slots=True)
115
+ class SkillsOffer:
116
+ """How the skills are given to the model in a request.
117
+
118
+ Attributes:
119
+ tools: ``True`` to list them and let the model read the ones it needs with
120
+ ``read_skill``; ``False`` to put every one in the prompt, for a client that
121
+ cannot be offered tools.
122
+ read: The ids of the skills the model has already read, which are in the prompt.
123
+ catalog: The skills on offer, by id; the ones that ship unless given.
124
+ """
125
+
126
+ tools: bool
127
+ read: tuple[str, ...] = ()
128
+ catalog: Mapping[str, Skill] = field(default_factory=shipped_skills)
129
+
130
+
131
+ def _skills_section(offer: SkillsOffer) -> str:
132
+ """What the prompt says about the skills: a list to read from, those already read, or all."""
133
+ guides = offer.catalog
134
+ if not offer.tools:
135
+ everything = "\n\n".join(skill.text for skill in guides.values())
136
+ return f"Skills (guides to parts of FalkorDB that are easy to get wrong):\n\n{everything}"
137
+ unread = [skill for skill in guides.values() if skill.id not in offer.read]
138
+ parts = []
139
+ if unread:
140
+ lines = "\n".join(f"- {skill.id}: {skill.description}" for skill in unread)
141
+ parts.append(f"Skills (read one with read_skill, by its id):\n{lines}")
142
+ if offer.read:
143
+ read = "\n\n".join(guides[i].text for i in offer.read if i in guides)
144
+ parts.append(f"Skills you have already read:\n\n{read}")
145
+ return "\n\n".join(parts)
146
+
147
+
103
148
  _FUNCTION_RULE = (
104
149
  "- The graph's FalkorDB has user-defined functions, listed under User-defined "
105
150
  "functions in the schema and called by that name, as in library.function(x). Call "
@@ -156,16 +201,32 @@ def _has_examples(schema: GraphSchema) -> bool:
156
201
  )
157
202
 
158
203
 
159
- def generator_system(schema: GraphSchema, *, parameterize: bool = False) -> str:
160
- """The system prompt that tells the LLM how to write a query for ``schema``."""
204
+ def generator_system(
205
+ schema: GraphSchema,
206
+ *,
207
+ parameterize: bool = False,
208
+ skills: SkillsOffer | None = None,
209
+ ) -> str:
210
+ """The system prompt that tells the LLM how to write a query for ``schema``.
211
+
212
+ With ``skills``, a section after the rules gives the model the skills, as ``skills``
213
+ says; without, the prompt has none.
214
+ """
161
215
  kinds = {index.type for index in schema.indexes}
216
+ unread = (
217
+ skills is not None
218
+ and skills.tools
219
+ and any(skill_id not in skills.read for skill_id in skills.catalog)
220
+ )
162
221
  rules = [
163
222
  *_RULES,
164
223
  _PARAMETER_RULE if parameterize else _INLINE_VALUES_RULE,
165
224
  *(rule for kind, rule in _INDEX_RULES.items() if kind in kinds),
166
225
  *([_FUNCTION_RULE] if schema.functions else []),
167
226
  *([_EXAMPLES_RULE] if _has_examples(schema) else []),
227
+ *([_SKILLS_RULE] if unread else []),
168
228
  ]
229
+ section = f"\n\n{_skills_section(skills)}" if skills is not None else ""
169
230
  text = (
170
231
  render_schema(schema)
171
232
  or "The graph has no data yet, so there is nothing to query."
@@ -173,6 +234,7 @@ def generator_system(schema: GraphSchema, *, parameterize: bool = False) -> str:
173
234
  return (
174
235
  f"{_INTRO}\n\nRules:\n"
175
236
  + "\n".join(rules)
237
+ + section
176
238
  + f"\n\n{_checks(parameterize)}\n\n{_format_and_examples(parameterize)}"
177
239
  f"\nSchema:\n{text}\n"
178
240
  )