text2cypher 1.2.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 (47) hide show
  1. {text2cypher-1.2.0 → text2cypher-2.0.0}/PKG-INFO +16 -6
  2. {text2cypher-1.2.0 → text2cypher-2.0.0}/README.md +14 -5
  3. text2cypher-2.0.0/THIRD_PARTY_NOTICES +31 -0
  4. {text2cypher-1.2.0 → text2cypher-2.0.0}/pyproject.toml +6 -3
  5. {text2cypher-1.2.0 → text2cypher-2.0.0}/pyproject.toml.orig +3 -3
  6. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/__init__.py +8 -0
  7. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_config.py +8 -0
  8. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/__init__.py +12 -0
  9. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/conversation.py +3 -1
  10. text2cypher-2.0.0/src/text2cypher/_generation/generate.py +107 -0
  11. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/prompts.py +60 -2
  12. text2cypher-2.0.0/src/text2cypher/_generation/read_skill.py +93 -0
  13. text2cypher-2.0.0/src/text2cypher/_generation/schema_filter.py +225 -0
  14. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_pipeline.py +21 -7
  15. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_results.py +49 -12
  16. text2cypher-2.0.0/src/text2cypher/_skills/__init__.py +69 -0
  17. text2cypher-2.0.0/src/text2cypher/_skills/functions/skill.md +67 -0
  18. text2cypher-2.0.0/src/text2cypher/_skills/graph-algorithms/skill.md +57 -0
  19. text2cypher-2.0.0/src/text2cypher/_skills/path-finding/skill.md +61 -0
  20. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_workflow.py +127 -21
  21. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/llm/__init__.py +4 -0
  22. text2cypher-2.0.0/src/text2cypher/llm/_adapt.py +38 -0
  23. text2cypher-2.0.0/src/text2cypher/llm/_base.py +158 -0
  24. text2cypher-2.0.0/src/text2cypher/llm/_fake.py +81 -0
  25. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/llm/_openai.py +98 -5
  26. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/schema/__init__.py +2 -1
  27. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/schema/_filter.py +13 -3
  28. text2cypher-1.2.0/src/text2cypher/_generation/generate.py +0 -51
  29. text2cypher-1.2.0/src/text2cypher/llm/_base.py +0 -76
  30. text2cypher-1.2.0/src/text2cypher/llm/_fake.py +0 -57
  31. {text2cypher-1.2.0 → text2cypher-2.0.0}/LICENSE +0 -0
  32. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_errors.py +0 -0
  33. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_examples.py +0 -0
  34. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_execution.py +0 -0
  35. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/extract.py +0 -0
  36. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/header.py +0 -0
  37. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/problems.py +0 -0
  38. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_generation/typos.py +0 -0
  39. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_schema_source.py +0 -0
  40. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_validation/__init__.py +0 -0
  41. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_validation/issues.py +0 -0
  42. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/_validation/validator.py +0 -0
  43. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/py.typed +0 -0
  44. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/schema/_from_snapshot.py +0 -0
  45. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/schema/_model.py +0 -0
  46. {text2cypher-1.2.0 → text2cypher-2.0.0}/src/text2cypher/schema/_render.py +0 -0
  47. {text2cypher-1.2.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.2.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,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,7 +91,7 @@ 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
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.
92
97
 
@@ -94,7 +99,12 @@ There is also [a quickstart that needs no model and no server](https://github.co
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,7 +58,7 @@ 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
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.
60
64
 
@@ -62,7 +66,12 @@ There is also [a quickstart that needs no model and no server](https://github.co
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,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.2.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"
@@ -119,7 +122,7 @@ layers = [
119
122
  "text2cypher._examples",
120
123
  "text2cypher._results",
121
124
  "text2cypher._validation",
122
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
125
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
123
126
  ]
124
127
 
125
128
  [[tool.importlinter.contracts]]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.2.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"]
@@ -97,7 +97,7 @@ layers = [
97
97
  "text2cypher._examples",
98
98
  "text2cypher._results",
99
99
  "text2cypher._validation",
100
- "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
100
+ "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
101
101
  ]
102
102
 
103
103
  [[tool.importlinter.contracts]]
@@ -9,6 +9,7 @@ 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,
@@ -25,6 +26,8 @@ from text2cypher.llm import (
25
26
  FakeLLM,
26
27
  Message,
27
28
  OpenAIClient,
29
+ Tool,
30
+ ToolCall,
28
31
  Usage,
29
32
  )
30
33
  from text2cypher.schema import GraphSchema, SchemaFilter, filter_schema
@@ -37,15 +40,18 @@ except PackageNotFoundError: # running from a source tree that is not installed
37
40
  __all__ = [
38
41
  "AsyncChatClient",
39
42
  "AsyncLLMClient",
43
+ "AsyncSchemaFilter",
40
44
  "Attempt",
41
45
  "Completion",
42
46
  "Config",
43
47
  "DatabaseError",
44
48
  "FakeLLM",
49
+ "FilterResult",
45
50
  "GraphNotFoundError",
46
51
  "GraphSchema",
47
52
  "Issue",
48
53
  "LLMError",
54
+ "LLMSchemaFilter",
49
55
  "Message",
50
56
  "OpenAIClient",
51
57
  "Records",
@@ -53,6 +59,8 @@ __all__ = [
53
59
  "SchemaFilter",
54
60
  "Text2Cypher",
55
61
  "Text2CypherError",
62
+ "Tool",
63
+ "ToolCall",
56
64
  "Usage",
57
65
  "ValidationResult",
58
66
  "__version__",
@@ -41,6 +41,12 @@ 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.
49
+
44
50
  The schema shows up to ``example_values`` values of each property (``title: STRING (e.g.
45
51
  'Alien', 'Heat')``), so the LLM writes a value the way the graph does: spelling, case,
46
52
  format. They are read from the graph, one small query per property, and are **data from
@@ -66,6 +72,7 @@ class Config:
66
72
  check_performance: Report queries that may be expensive, which is off by default.
67
73
  example_values: How many example values of each property to show the LLM; ``0``
68
74
  sends none.
75
+ use_skills: Offer the LLM the skills, to read when a question needs them.
69
76
  autofix_typos: Fix a misspelled name in a query without the LLM when exactly one
70
77
  name of the graph is a likely typo of it.
71
78
  schema_refresh_seconds: Keep the schema of a graph and check it for changes at
@@ -82,6 +89,7 @@ class Config:
82
89
  check_performance: bool = False
83
90
  example_values: int = 3
84
91
  autofix_typos: bool = False
92
+ use_skills: bool = False
85
93
 
86
94
  def __post_init__(self) -> None:
87
95
  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,107 @@
1
+ """Ask an LLM for a Cypher query, or to correct one."""
2
+
3
+ from collections.abc import 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.llm import AsyncChatClient, AsyncLLMClient, Completion, Message, Usage
16
+ from text2cypher.llm._base import supports_tools
17
+ from text2cypher.schema import GraphSchema
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class Generation:
22
+ """A query an LLM wrote, empty if it declined, and the tokens that cost.
23
+
24
+ ``empty`` is a reply with no text at all, which is not the same as a decline (an empty
25
+ fenced block): it is a call that returned nothing. A refusal is not empty: it is the
26
+ model declining, in the one way it could. ``finish_reason`` is why the reply ended, when
27
+ the client says.
28
+ """
29
+
30
+ query: str
31
+ usage: Usage | None
32
+ skills: tuple[str, ...] = ()
33
+ empty: bool = False
34
+ finish_reason: str | None = None
35
+
36
+
37
+ async def generate_cypher(
38
+ llm: AsyncChatClient | AsyncLLMClient,
39
+ schema: GraphSchema,
40
+ question: str,
41
+ rounds: Sequence[Round] = (),
42
+ *,
43
+ parameterize: bool = False,
44
+ skills: bool = False,
45
+ ) -> Generation:
46
+ """A query for ``question`` over ``schema``; empty if the LLM says it has none.
47
+
48
+ ``rounds`` are the queries it wrote before that had to be corrected, oldest first.
49
+ Each correction uses the same system prompt as the first query. A client that has
50
+ ``chat`` is given the conversation as turns; one with only ``complete`` is given it
51
+ as one message.
52
+
53
+ With ``skills``, a client that can be offered tools lists the skills and may read the
54
+ ones it needs (``Generation.skills`` says which, and the skills it read before are in
55
+ the prompt already); any other client has every skill in the prompt.
56
+
57
+ Raises:
58
+ SkillLoopFailed: If a call fails after others of the same request succeeded.
59
+ """
60
+ offer = None
61
+ if skills:
62
+ read = tuple(dict.fromkeys(i for round_ in rounds for i in round_.skills_read))
63
+ offer = SkillsOffer(supports_tools(llm), read)
64
+ system = generator_system(schema, parameterize=parameterize, skills=offer)
65
+ messages = chat_messages(question, rounds, schema, parameterize=parameterize)
66
+ if offer is not None and offer.tools:
67
+ completion, read_now, usage = await chat_reading_skills(
68
+ cast("AsyncChatClient", llm), system, messages
69
+ )
70
+ return Generation(
71
+ extract_cypher(completion.text),
72
+ usage,
73
+ read_now,
74
+ empty=_no_text(completion),
75
+ finish_reason=completion.finish_reason,
76
+ )
77
+ completion = await ask(
78
+ llm,
79
+ system,
80
+ messages,
81
+ folded_message(question, rounds, schema, parameterize=parameterize),
82
+ )
83
+ return Generation(
84
+ extract_cypher(completion.text),
85
+ completion.usage,
86
+ empty=_no_text(completion),
87
+ finish_reason=completion.finish_reason,
88
+ )
89
+
90
+
91
+ def _no_text(completion: Completion) -> bool:
92
+ """A reply with nothing in it, that is not a refusal (which is a decline)."""
93
+ return not completion.text.strip() and completion.finish_reason != "refusal"
94
+
95
+
96
+ async def ask(
97
+ llm: AsyncChatClient | AsyncLLMClient,
98
+ system: str,
99
+ messages: Sequence[Message],
100
+ folded: str,
101
+ ) -> Completion:
102
+ """The model's reply to a conversation: as turns when the client has ``chat``, else
103
+ as the one message ``folded``, which says the same."""
104
+ chat = getattr(llm, "chat", None)
105
+ if callable(chat):
106
+ return await chat(system, messages)
107
+ return await cast("AsyncLLMClient", llm).complete(system, folded)
@@ -1,5 +1,8 @@
1
1
  """The prompts: what the LLM is told to write a query."""
2
2
 
3
+ from dataclasses import dataclass
4
+
5
+ from text2cypher._skills import skills as shipped_skills
3
6
  from text2cypher.schema import GraphSchema, render_schema
4
7
 
5
8
  # The queries the rules and the examples show. tests/generation/test_prompt_rules.py runs each
@@ -100,6 +103,44 @@ _EXAMPLES_RULE = (
100
103
  "written (spelling and case)."
101
104
  )
102
105
 
106
+ _SKILLS_RULE = (
107
+ "- Skills are short guides to parts of FalkorDB that are easy to get wrong. Read a skill, "
108
+ "with read_skill, only when the question needs what it covers, before you write the query."
109
+ )
110
+
111
+
112
+ @dataclass(frozen=True, slots=True)
113
+ class SkillsOffer:
114
+ """How the skills are given to the model in a request.
115
+
116
+ Attributes:
117
+ tools: ``True`` to list them and let the model read the ones it needs with
118
+ ``read_skill``; ``False`` to put every one in the prompt, for a client that
119
+ cannot be offered tools.
120
+ read: The ids of the skills the model has already read, which are in the prompt.
121
+ """
122
+
123
+ tools: bool
124
+ read: tuple[str, ...] = ()
125
+
126
+
127
+ def _skills_section(offer: SkillsOffer) -> str:
128
+ """What the prompt says about the skills: a list to read from, those already read, or all."""
129
+ guides = shipped_skills()
130
+ if not offer.tools:
131
+ everything = "\n\n".join(skill.text for skill in guides.values())
132
+ return f"Skills (guides to parts of FalkorDB that are easy to get wrong):\n\n{everything}"
133
+ unread = [skill for skill in guides.values() if skill.id not in offer.read]
134
+ parts = []
135
+ if unread:
136
+ lines = "\n".join(f"- {skill.id}: {skill.description}" for skill in unread)
137
+ parts.append(f"Skills (read one with read_skill, by its id):\n{lines}")
138
+ if offer.read:
139
+ read = "\n\n".join(guides[i].text for i in offer.read if i in guides)
140
+ parts.append(f"Skills you have already read:\n\n{read}")
141
+ return "\n\n".join(parts)
142
+
143
+
103
144
  _FUNCTION_RULE = (
104
145
  "- The graph's FalkorDB has user-defined functions, listed under User-defined "
105
146
  "functions in the schema and called by that name, as in library.function(x). Call "
@@ -156,16 +197,32 @@ def _has_examples(schema: GraphSchema) -> bool:
156
197
  )
157
198
 
158
199
 
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``."""
200
+ def generator_system(
201
+ schema: GraphSchema,
202
+ *,
203
+ parameterize: bool = False,
204
+ skills: SkillsOffer | None = None,
205
+ ) -> str:
206
+ """The system prompt that tells the LLM how to write a query for ``schema``.
207
+
208
+ With ``skills``, a section after the rules gives the model the skills, as ``skills``
209
+ says; without, the prompt has none.
210
+ """
161
211
  kinds = {index.type for index in schema.indexes}
212
+ unread = (
213
+ skills is not None
214
+ and skills.tools
215
+ and any(skill_id not in skills.read for skill_id in shipped_skills())
216
+ )
162
217
  rules = [
163
218
  *_RULES,
164
219
  _PARAMETER_RULE if parameterize else _INLINE_VALUES_RULE,
165
220
  *(rule for kind, rule in _INDEX_RULES.items() if kind in kinds),
166
221
  *([_FUNCTION_RULE] if schema.functions else []),
167
222
  *([_EXAMPLES_RULE] if _has_examples(schema) else []),
223
+ *([_SKILLS_RULE] if unread else []),
168
224
  ]
225
+ section = f"\n\n{_skills_section(skills)}" if skills is not None else ""
169
226
  text = (
170
227
  render_schema(schema)
171
228
  or "The graph has no data yet, so there is nothing to query."
@@ -173,6 +230,7 @@ def generator_system(schema: GraphSchema, *, parameterize: bool = False) -> str:
173
230
  return (
174
231
  f"{_INTRO}\n\nRules:\n"
175
232
  + "\n".join(rules)
233
+ + section
176
234
  + f"\n\n{_checks(parameterize)}\n\n{_format_and_examples(parameterize)}"
177
235
  f"\nSchema:\n{text}\n"
178
236
  )
@@ -0,0 +1,93 @@
1
+ """Let the model read skills, by calling a tool, while it writes a query."""
2
+
3
+ from collections.abc import Sequence
4
+
5
+ from text2cypher._results import NO_TOKENS
6
+ from text2cypher._skills import skills
7
+ from text2cypher.llm import AsyncChatClient, Completion, Message, Tool, ToolCall, Usage
8
+
9
+ READ_SKILL = Tool(
10
+ "read_skill",
11
+ "Read one skill: what it is for, the syntax, and an example that runs on FalkorDB.",
12
+ {
13
+ "type": "object",
14
+ "properties": {
15
+ "id": {"type": "string", "description": "The id of a skill from the list."}
16
+ },
17
+ "required": ["id"],
18
+ },
19
+ )
20
+
21
+ # Rounds of tool calls before the model must answer, and the calls answered in one round
22
+ _ROUNDS = 3
23
+ _CALLS_PER_ROUND = 4
24
+
25
+
26
+ class SkillLoopFailed(Exception):
27
+ """A call failed in the middle of reading skills; ``__cause__`` is why.
28
+
29
+ Attributes:
30
+ usage: The tokens of the calls that had succeeded, or ``None`` if unknown.
31
+ calls: How many calls had succeeded.
32
+ """
33
+
34
+ def __init__(self, usage: Usage | None, calls: int) -> None:
35
+ super().__init__("a call failed while reading skills")
36
+ self.usage = usage
37
+ self.calls = calls
38
+
39
+
40
+ async def chat_reading_skills(
41
+ llm: AsyncChatClient, system: str, messages: Sequence[Message]
42
+ ) -> tuple[Completion, tuple[str, ...], Usage | None]:
43
+ """The model's reply, the ids of the skills it read, and the tokens of every call.
44
+
45
+ The model is offered ``read_skill`` for up to three rounds; each call is answered with
46
+ the skill (or what went wrong), and it is asked again. Then it must answer: the tool is
47
+ still offered but a call is forbidden.
48
+
49
+ Raises:
50
+ SkillLoopFailed: If a call fails, with what the earlier calls cost.
51
+ """
52
+ turns = list(messages)
53
+ read: list[str] = []
54
+ usage: Usage | None = NO_TOKENS
55
+ calls = 0
56
+ try:
57
+ for _ in range(_ROUNDS):
58
+ completion = await llm.chat(system, turns, [READ_SKILL])
59
+ usage, calls = _plus(usage, completion.usage), calls + 1
60
+ if not completion.tool_calls:
61
+ return completion, tuple(read), usage
62
+ turns.append(Message("assistant", completion.text, completion.tool_calls))
63
+ for number, call in enumerate(completion.tool_calls):
64
+ content = (
65
+ _too_many if number >= _CALLS_PER_ROUND else _answer(call, read)
66
+ )
67
+ turns.append(Message("tool", content, tool_call_id=call.id))
68
+ completion = await llm.chat(system, turns, [READ_SKILL], tool_choice="none")
69
+ usage = _plus(usage, completion.usage)
70
+ return completion, tuple(read), usage
71
+ except Exception as error:
72
+ raise SkillLoopFailed(usage, calls) from error
73
+
74
+
75
+ _too_many = "Too many skills at once: ask for fewer."
76
+
77
+
78
+ def _answer(call: ToolCall, read: list[str]) -> str:
79
+ """What the model is told about one call to ``read_skill``; the id is added to ``read``."""
80
+ available = skills()
81
+ wanted = call.arguments.get("id")
82
+ ids = ", ".join(available)
83
+ if not isinstance(wanted, str) or not wanted:
84
+ return f"Give the id of a skill. The ids are: {ids}."
85
+ if wanted not in available:
86
+ return f"There is no skill with the id `{wanted}`. The ids are: {ids}."
87
+ if wanted not in read:
88
+ read.append(wanted)
89
+ return available[wanted].text
90
+
91
+
92
+ def _plus(total: Usage | None, used: Usage | None) -> Usage | None:
93
+ return None if total is None or used is None else total + used