text2cypher 2.0.0__tar.gz → 3.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.
- {text2cypher-2.0.0 → text2cypher-3.0.0}/PKG-INFO +8 -5
- {text2cypher-2.0.0 → text2cypher-3.0.0}/README.md +6 -3
- {text2cypher-2.0.0 → text2cypher-3.0.0}/THIRD_PARTY_NOTICES +1 -1
- {text2cypher-2.0.0 → text2cypher-3.0.0}/pyproject.toml +4 -5
- {text2cypher-2.0.0 → text2cypher-3.0.0}/pyproject.toml.orig +4 -5
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/__init__.py +14 -3
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_config.py +2 -1
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/conversation.py +3 -3
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/generate.py +11 -4
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/prompts.py +92 -38
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/read_skill.py +13 -7
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/schema_filter.py +86 -10
- text2cypher-3.0.0/src/text2cypher/_graph/__init__.py +14 -0
- text2cypher-2.0.0/src/text2cypher/_schema_source.py → text2cypher-3.0.0/src/text2cypher/_graph/schema_source.py +1 -1
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_pipeline.py +52 -10
- text2cypher-3.0.0/src/text2cypher/_results/__init__.py +37 -0
- text2cypher-2.0.0/src/text2cypher/_results.py → text2cypher-3.0.0/src/text2cypher/_results/results.py +11 -1
- text2cypher-3.0.0/src/text2cypher/_results/values.py +150 -0
- text2cypher-3.0.0/src/text2cypher/_skills/__init__.py +178 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_workflow.py +10 -3
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/llm/__init__.py +2 -2
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/llm/_adapt.py +16 -7
- text2cypher-2.0.0/src/text2cypher/llm/_openai.py → text2cypher-3.0.0/src/text2cypher/llm/_chat_completions.py +42 -34
- text2cypher-3.0.0/src/text2cypher/llm/_options.py +95 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/schema/__init__.py +2 -0
- text2cypher-3.0.0/src/text2cypher/schema/_dictionary.py +182 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/schema/_filter.py +9 -4
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/schema/_model.py +6 -0
- text2cypher-3.0.0/src/text2cypher/schema/_render.py +204 -0
- text2cypher-3.0.0/src/text2cypher/skills.py +5 -0
- text2cypher-2.0.0/src/text2cypher/_skills/__init__.py +0 -69
- text2cypher-2.0.0/src/text2cypher/schema/_render.py +0 -70
- {text2cypher-2.0.0 → text2cypher-3.0.0}/LICENSE +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_errors.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/extract.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/header.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/problems.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_generation/typos.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_examples.py → /text2cypher-3.0.0/src/text2cypher/_graph/examples.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_execution.py → /text2cypher-3.0.0/src/text2cypher/_graph/execution.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/functions/skill.md → /text2cypher-3.0.0/src/text2cypher/_skills/functions/SKILL.md +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/graph-algorithms/skill.md → /text2cypher-3.0.0/src/text2cypher/_skills/graph-algorithms/SKILL.md +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/path-finding/skill.md → /text2cypher-3.0.0/src/text2cypher/_skills/path-finding/SKILL.md +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_validation/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_validation/issues.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/_validation/validator.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/llm/_base.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/llm/_fake.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/py.typed +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/schema/_from_snapshot.py +0 -0
- {text2cypher-2.0.0 → text2cypher-3.0.0}/src/text2cypher/schema/_stopwords.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: text2cypher
|
|
3
|
-
Version:
|
|
3
|
+
Version: 3.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
|
|
@@ -18,7 +18,7 @@ Classifier: Programming Language :: Python :: 3.13
|
|
|
18
18
|
Classifier: Programming Language :: Python :: 3.14
|
|
19
19
|
Classifier: Topic :: Database
|
|
20
20
|
Classifier: Typing :: Typed
|
|
21
|
-
Requires-Dist: cypher-guardrail>=1.
|
|
21
|
+
Requires-Dist: cypher-guardrail>=1.5.1
|
|
22
22
|
Requires-Dist: falkordb>=1.8.0
|
|
23
23
|
Requires-Dist: openai>=3.31.0
|
|
24
24
|
Requires-Dist: redis>=8.1.0
|
|
@@ -49,11 +49,12 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
|
|
|
49
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.
|
|
50
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
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
|
+
* **Described by you** (optional): a data dictionary says in your words what each label, relationship type and property means, so the LLM reads `Customer` and `client` as one thing. It goes next to the schema in the prompt, and the LLM schema filter reads it too. It is text you write, sent to the LLM provider.
|
|
52
53
|
* **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
54
|
* **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
55
|
* **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
56
|
* **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`,
|
|
57
|
+
* **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
|
|
57
58
|
|
|
58
59
|
## Installation
|
|
59
60
|
|
|
@@ -93,7 +94,9 @@ asyncio.run(main())
|
|
|
93
94
|
|
|
94
95
|
Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
|
|
95
96
|
|
|
96
|
-
There is also [a quickstart
|
|
97
|
+
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.
|
|
98
|
+
|
|
99
|
+
For the breadth of the library, [a tour with the OpenAI SDK](https://github.com/Killeroid/text2cypher/blob/main/examples/full_tour.py) (it needs a FalkorDB server and an API key) asks questions that return values, single nodes, lists of nodes, relationships, paths and nodes inside lists, with a data dictionary, the model options, the LLM schema filter, skills of your own, execution and the other options on, and shows nodes as plain objects and as your own classes.
|
|
97
100
|
|
|
98
101
|
## What is and is not checked
|
|
99
102
|
|
|
@@ -102,7 +105,7 @@ There is also [a quickstart that needs no model and no server](https://github.co
|
|
|
102
105
|
|
|
103
106
|
## Configuration
|
|
104
107
|
|
|
105
|
-
* See
|
|
108
|
+
* See the configuration table in [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
|
|
106
109
|
* 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
110
|
|
|
108
111
|
|
|
@@ -16,11 +16,12 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
|
|
|
16
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.
|
|
17
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
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
|
+
* **Described by you** (optional): a data dictionary says in your words what each label, relationship type and property means, so the LLM reads `Customer` and `client` as one thing. It goes next to the schema in the prompt, and the LLM schema filter reads it too. It is text you write, sent to the LLM provider.
|
|
19
20
|
* **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
21
|
* **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
22
|
* **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
23
|
* **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`,
|
|
24
|
+
* **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, and the OpenAI SDK's own client accepted as it is, with the settings of how a model is asked (temperature, reasoning effort and others) as one dictionary. Async throughout.
|
|
24
25
|
|
|
25
26
|
## Installation
|
|
26
27
|
|
|
@@ -60,7 +61,9 @@ asyncio.run(main())
|
|
|
60
61
|
|
|
61
62
|
Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
|
|
62
63
|
|
|
63
|
-
There is also [a quickstart
|
|
64
|
+
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.
|
|
65
|
+
|
|
66
|
+
For the breadth of the library, [a tour with the OpenAI SDK](https://github.com/Killeroid/text2cypher/blob/main/examples/full_tour.py) (it needs a FalkorDB server and an API key) asks questions that return values, single nodes, lists of nodes, relationships, paths and nodes inside lists, with a data dictionary, the model options, the LLM schema filter, skills of your own, execution and the other options on, and shows nodes as plain objects and as your own classes.
|
|
64
67
|
|
|
65
68
|
## What is and is not checked
|
|
66
69
|
|
|
@@ -69,7 +72,7 @@ There is also [a quickstart that needs no model and no server](https://github.co
|
|
|
69
72
|
|
|
70
73
|
## Configuration
|
|
71
74
|
|
|
72
|
-
* See
|
|
75
|
+
* See the configuration table in [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
|
|
73
76
|
* 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
77
|
|
|
75
78
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Third-party notices
|
|
2
2
|
===================
|
|
3
3
|
|
|
4
|
-
The "path-finding" skill (src/text2cypher/_skills/path-finding/
|
|
4
|
+
The "path-finding" skill (src/text2cypher/_skills/path-finding/SKILL.md) is adapted from
|
|
5
5
|
the skill of the same subject in the text-to-cypher project of FalkorDB
|
|
6
6
|
(https://github.com/FalkorDB/text-to-cypher, assets/cypher-skills), which is itself derived
|
|
7
7
|
from FalkorDB's skills repository (https://github.com/FalkorDB/skills). Its examples and
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "text2cypher"
|
|
3
|
-
version = "
|
|
3
|
+
version = "3.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"
|
|
7
7
|
dependencies = [
|
|
8
|
-
"cypher-guardrail>=1.
|
|
8
|
+
"cypher-guardrail>=1.5.1",
|
|
9
9
|
"falkordb>=1.8.0",
|
|
10
10
|
"openai>=3.31.0",
|
|
11
11
|
"redis>=8.1.0",
|
|
@@ -116,10 +116,9 @@ root_packages = [
|
|
|
116
116
|
name = "The layers of the package"
|
|
117
117
|
type = "layers"
|
|
118
118
|
layers = [
|
|
119
|
-
"text2cypher._pipeline",
|
|
119
|
+
"text2cypher._pipeline | text2cypher.skills",
|
|
120
120
|
"text2cypher._workflow",
|
|
121
|
-
"text2cypher._generation | text2cypher.
|
|
122
|
-
"text2cypher._examples",
|
|
121
|
+
"text2cypher._generation | text2cypher._graph",
|
|
123
122
|
"text2cypher._results",
|
|
124
123
|
"text2cypher._validation",
|
|
125
124
|
"text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "text2cypher"
|
|
3
|
-
version = "
|
|
3
|
+
version = "3.0.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.
|
|
11
|
+
"cypher-guardrail>=1.5.1",
|
|
12
12
|
"falkordb>=1.8.0",
|
|
13
13
|
"openai>=3.31.0",
|
|
14
14
|
"redis>=8.1.0",
|
|
@@ -91,10 +91,9 @@ 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.
|
|
97
|
-
"text2cypher._examples",
|
|
96
|
+
"text2cypher._generation | text2cypher._graph",
|
|
98
97
|
"text2cypher._results",
|
|
99
98
|
"text2cypher._validation",
|
|
100
99
|
"text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors | text2cypher._skills",
|
|
@@ -14,10 +14,15 @@ from text2cypher._pipeline import Text2Cypher
|
|
|
14
14
|
from text2cypher._results import (
|
|
15
15
|
Attempt,
|
|
16
16
|
DatabaseError,
|
|
17
|
+
GraphNode,
|
|
18
|
+
GraphPath,
|
|
19
|
+
GraphRelationship,
|
|
17
20
|
LLMError,
|
|
18
21
|
Records,
|
|
19
22
|
Result,
|
|
23
|
+
to_python,
|
|
20
24
|
)
|
|
25
|
+
from text2cypher._skills import Skill
|
|
21
26
|
from text2cypher._validation import Issue, ValidationResult
|
|
22
27
|
from text2cypher.llm import (
|
|
23
28
|
AsyncChatClient,
|
|
@@ -25,12 +30,12 @@ from text2cypher.llm import (
|
|
|
25
30
|
Completion,
|
|
26
31
|
FakeLLM,
|
|
27
32
|
Message,
|
|
28
|
-
|
|
33
|
+
ModelOptions,
|
|
29
34
|
Tool,
|
|
30
35
|
ToolCall,
|
|
31
36
|
Usage,
|
|
32
37
|
)
|
|
33
|
-
from text2cypher.schema import GraphSchema, SchemaFilter, filter_schema
|
|
38
|
+
from text2cypher.schema import DataDictionary, GraphSchema, SchemaFilter, filter_schema
|
|
34
39
|
|
|
35
40
|
try:
|
|
36
41
|
__version__ = version("text2cypher")
|
|
@@ -44,19 +49,24 @@ __all__ = [
|
|
|
44
49
|
"Attempt",
|
|
45
50
|
"Completion",
|
|
46
51
|
"Config",
|
|
52
|
+
"DataDictionary",
|
|
47
53
|
"DatabaseError",
|
|
48
54
|
"FakeLLM",
|
|
49
55
|
"FilterResult",
|
|
56
|
+
"GraphNode",
|
|
50
57
|
"GraphNotFoundError",
|
|
58
|
+
"GraphPath",
|
|
59
|
+
"GraphRelationship",
|
|
51
60
|
"GraphSchema",
|
|
52
61
|
"Issue",
|
|
53
62
|
"LLMError",
|
|
54
63
|
"LLMSchemaFilter",
|
|
55
64
|
"Message",
|
|
56
|
-
"
|
|
65
|
+
"ModelOptions",
|
|
57
66
|
"Records",
|
|
58
67
|
"Result",
|
|
59
68
|
"SchemaFilter",
|
|
69
|
+
"Skill",
|
|
60
70
|
"Text2Cypher",
|
|
61
71
|
"Text2CypherError",
|
|
62
72
|
"Tool",
|
|
@@ -65,4 +75,5 @@ __all__ = [
|
|
|
65
75
|
"ValidationResult",
|
|
66
76
|
"__version__",
|
|
67
77
|
"filter_schema",
|
|
78
|
+
"to_python",
|
|
68
79
|
]
|
|
@@ -45,7 +45,8 @@ class Config:
|
|
|
45
45
|
are easy to get wrong (graph algorithms, path finding, functions). It sees what each is
|
|
46
46
|
for, and reads a skill, by calling a tool, only when the question needs it; each read
|
|
47
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.
|
|
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``.
|
|
49
50
|
|
|
50
51
|
The schema shows up to ``example_values`` values of each property (``title: STRING (e.g.
|
|
51
52
|
'Alien', 'Heat')``), so the LLM writes a value the way the graph does: spelling, case,
|
|
@@ -78,12 +78,12 @@ def folded_message(
|
|
|
78
78
|
return generator_user(question)
|
|
79
79
|
note = f"{SCHEMA_NOTE}\n\n" if any(r.schema_note for r in rounds) else ""
|
|
80
80
|
attempts = "\n\n".join(
|
|
81
|
-
f"Attempt {number}\n{_fenced(r.query)}\n{_feedback(r, schema, parameterize)}"
|
|
81
|
+
f"## Attempt {number}\n{_fenced(r.query)}\n{_feedback(r, schema, parameterize)}"
|
|
82
82
|
for number, r in enumerate(rounds, start=1)
|
|
83
83
|
)
|
|
84
84
|
return (
|
|
85
|
-
f"{generator_user(question)}\n\n
|
|
86
|
-
f"{attempts}\n\n{CLOSING}"
|
|
85
|
+
f"{generator_user(question)}\n\n# Earlier attempts, oldest first\n\n"
|
|
86
|
+
f"{note}{attempts}\n\n{CLOSING}"
|
|
87
87
|
)
|
|
88
88
|
|
|
89
89
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"""Ask an LLM for a Cypher query, or to correct one."""
|
|
2
2
|
|
|
3
|
-
from collections.abc import Sequence
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
4
|
from dataclasses import dataclass
|
|
5
5
|
from typing import cast
|
|
6
6
|
|
|
@@ -12,6 +12,7 @@ from text2cypher._generation.conversation import (
|
|
|
12
12
|
from text2cypher._generation.extract import extract_cypher
|
|
13
13
|
from text2cypher._generation.prompts import SkillsOffer, generator_system
|
|
14
14
|
from text2cypher._generation.read_skill import chat_reading_skills
|
|
15
|
+
from text2cypher._skills import Skill
|
|
15
16
|
from text2cypher.llm import AsyncChatClient, AsyncLLMClient, Completion, Message, Usage
|
|
16
17
|
from text2cypher.llm._base import supports_tools
|
|
17
18
|
from text2cypher.schema import GraphSchema
|
|
@@ -42,6 +43,7 @@ async def generate_cypher(
|
|
|
42
43
|
*,
|
|
43
44
|
parameterize: bool = False,
|
|
44
45
|
skills: bool = False,
|
|
46
|
+
catalog: Mapping[str, Skill] | None = None,
|
|
45
47
|
) -> Generation:
|
|
46
48
|
"""A query for ``question`` over ``schema``; empty if the LLM says it has none.
|
|
47
49
|
|
|
@@ -52,7 +54,8 @@ async def generate_cypher(
|
|
|
52
54
|
|
|
53
55
|
With ``skills``, a client that can be offered tools lists the skills and may read the
|
|
54
56
|
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.
|
|
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.
|
|
56
59
|
|
|
57
60
|
Raises:
|
|
58
61
|
SkillLoopFailed: If a call fails after others of the same request succeeded.
|
|
@@ -60,12 +63,16 @@ async def generate_cypher(
|
|
|
60
63
|
offer = None
|
|
61
64
|
if skills:
|
|
62
65
|
read = tuple(dict.fromkeys(i for round_ in rounds for i in round_.skills_read))
|
|
63
|
-
offer =
|
|
66
|
+
offer = (
|
|
67
|
+
SkillsOffer(supports_tools(llm), read)
|
|
68
|
+
if catalog is None
|
|
69
|
+
else SkillsOffer(supports_tools(llm), read, catalog)
|
|
70
|
+
)
|
|
64
71
|
system = generator_system(schema, parameterize=parameterize, skills=offer)
|
|
65
72
|
messages = chat_messages(question, rounds, schema, parameterize=parameterize)
|
|
66
73
|
if offer is not None and offer.tools:
|
|
67
74
|
completion, read_now, usage = await chat_reading_skills(
|
|
68
|
-
cast("AsyncChatClient", llm), system, messages
|
|
75
|
+
cast("AsyncChatClient", llm), system, messages, offer.catalog
|
|
69
76
|
)
|
|
70
77
|
return Generation(
|
|
71
78
|
extract_cypher(completion.text),
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
"""The prompts: what the LLM is told to write a query."""
|
|
2
2
|
|
|
3
|
-
from
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass, field
|
|
4
5
|
|
|
6
|
+
from text2cypher._skills import Skill
|
|
5
7
|
from text2cypher._skills import skills as shipped_skills
|
|
6
|
-
from text2cypher.schema import GraphSchema
|
|
8
|
+
from text2cypher.schema import GraphSchema
|
|
9
|
+
from text2cypher.schema._render import (
|
|
10
|
+
as_markdown,
|
|
11
|
+
data_dictionary_section,
|
|
12
|
+
schema_sections,
|
|
13
|
+
)
|
|
7
14
|
|
|
8
15
|
# The queries the rules and the examples show. tests/generation/test_prompt_rules.py runs each
|
|
9
16
|
# of them on FalkorDB, so a rule or an example cannot silently stop being true.
|
|
@@ -103,6 +110,12 @@ _EXAMPLES_RULE = (
|
|
|
103
110
|
"written (spelling and case)."
|
|
104
111
|
)
|
|
105
112
|
|
|
113
|
+
_DICTIONARY_RULE = (
|
|
114
|
+
"- Use the data dictionary to decide which label, relationship type or property the "
|
|
115
|
+
"question means; "
|
|
116
|
+
"write names in the query as the schema spells them."
|
|
117
|
+
)
|
|
118
|
+
|
|
106
119
|
_SKILLS_RULE = (
|
|
107
120
|
"- Skills are short guides to parts of FalkorDB that are easy to get wrong. Read a skill, "
|
|
108
121
|
"with read_skill, only when the question needs what it covers, before you write the query."
|
|
@@ -118,26 +131,42 @@ class SkillsOffer:
|
|
|
118
131
|
``read_skill``; ``False`` to put every one in the prompt, for a client that
|
|
119
132
|
cannot be offered tools.
|
|
120
133
|
read: The ids of the skills the model has already read, which are in the prompt.
|
|
134
|
+
catalog: The skills on offer, by id; the ones that ship unless given.
|
|
121
135
|
"""
|
|
122
136
|
|
|
123
137
|
tools: bool
|
|
124
138
|
read: tuple[str, ...] = ()
|
|
139
|
+
catalog: Mapping[str, Skill] = field(default_factory=shipped_skills)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _demoted(text: str) -> str:
|
|
143
|
+
"""``text`` with each Markdown heading one level down, so that a skill put under a heading
|
|
144
|
+
of the prompt does not look like a part of the prompt. A line in a code block is not one."""
|
|
145
|
+
lines, fenced = [], False
|
|
146
|
+
for line in text.split("\n"):
|
|
147
|
+
if line.startswith("```"):
|
|
148
|
+
fenced = not fenced
|
|
149
|
+
lines.append(f"#{line}" if line.startswith("#") and not fenced else line)
|
|
150
|
+
return "\n".join(lines)
|
|
125
151
|
|
|
126
152
|
|
|
127
153
|
def _skills_section(offer: SkillsOffer) -> str:
|
|
128
154
|
"""What the prompt says about the skills: a list to read from, those already read, or all."""
|
|
129
|
-
guides =
|
|
155
|
+
guides = offer.catalog
|
|
130
156
|
if not offer.tools:
|
|
131
|
-
everything = "\n\n".join(skill.text for skill in guides.values())
|
|
132
|
-
return
|
|
157
|
+
everything = "\n\n".join(_demoted(skill.text) for skill in guides.values())
|
|
158
|
+
return (
|
|
159
|
+
"# Skills\nGuides to parts of FalkorDB that are easy to get wrong:\n\n"
|
|
160
|
+
f"{everything}"
|
|
161
|
+
)
|
|
133
162
|
unread = [skill for skill in guides.values() if skill.id not in offer.read]
|
|
134
163
|
parts = []
|
|
135
164
|
if unread:
|
|
136
165
|
lines = "\n".join(f"- {skill.id}: {skill.description}" for skill in unread)
|
|
137
|
-
parts.append(f"Skills
|
|
166
|
+
parts.append(f"# Skills\nRead one with read_skill, by its id:\n{lines}")
|
|
138
167
|
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
|
|
168
|
+
read = "\n\n".join(_demoted(guides[i].text) for i in offer.read if i in guides)
|
|
169
|
+
parts.append(f"# Skills you have already read\n\n{read}")
|
|
141
170
|
return "\n\n".join(parts)
|
|
142
171
|
|
|
143
172
|
|
|
@@ -162,33 +191,46 @@ _PARAMETER_CHECK = (
|
|
|
162
191
|
)
|
|
163
192
|
|
|
164
193
|
|
|
165
|
-
|
|
194
|
+
CHECKS_LEAD = "Before you answer, check the query:"
|
|
195
|
+
CHECKS_CLOSING = (
|
|
196
|
+
"If a check fails, fix the query first. Do not write the checks in your reply."
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def check_bullets(parameterize: bool) -> list[str]:
|
|
201
|
+
"""The checks the LLM is asked to make, one line each."""
|
|
166
202
|
syntax, *others = _CHECKS
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
)
|
|
203
|
+
return [syntax, *([_PARAMETER_CHECK] if parameterize else []), *others]
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _checks(parameterize: bool) -> str:
|
|
207
|
+
bullets = check_bullets(parameterize)
|
|
208
|
+
return f"# Checks\n{CHECKS_LEAD}\n" + "\n".join(bullets) + f"\n{CHECKS_CLOSING}"
|
|
173
209
|
|
|
174
210
|
|
|
175
211
|
def _format_and_examples(parameterize: bool) -> str:
|
|
176
212
|
example = EXAMPLE_PARAMETER_QUERY if parameterize else EXAMPLE_QUERY
|
|
177
213
|
return f"""\
|
|
214
|
+
# Output format
|
|
178
215
|
Reply with the query in one ```cypher code block and nothing else.
|
|
179
216
|
|
|
180
|
-
|
|
181
|
-
|
|
217
|
+
# Examples
|
|
218
|
+
These examples use another schema; they show the format only.
|
|
182
219
|
|
|
220
|
+
## Example 1
|
|
221
|
+
Schema: (:Employee {{name}})-[:WORKS_IN]->(:Department {{name}})
|
|
183
222
|
Question: Who works in Sales?
|
|
223
|
+
Answer:
|
|
184
224
|
```cypher
|
|
185
225
|
{example}
|
|
186
226
|
```
|
|
187
227
|
|
|
228
|
+
## Example 2
|
|
229
|
+
Schema: (:Employee {{name}})-[:WORKS_IN]->(:Department {{name}})
|
|
188
230
|
Question: Remove all employees.
|
|
231
|
+
Answer:
|
|
189
232
|
```cypher
|
|
190
|
-
```
|
|
191
|
-
"""
|
|
233
|
+
```"""
|
|
192
234
|
|
|
193
235
|
|
|
194
236
|
def _has_examples(schema: GraphSchema) -> bool:
|
|
@@ -197,6 +239,29 @@ def _has_examples(schema: GraphSchema) -> bool:
|
|
|
197
239
|
)
|
|
198
240
|
|
|
199
241
|
|
|
242
|
+
def rules_for(
|
|
243
|
+
schema: GraphSchema, *, parameterize: bool = False, skills_unread: bool = False
|
|
244
|
+
) -> list[str]:
|
|
245
|
+
"""The rules of the system prompt for ``schema``, one line (or one example) each."""
|
|
246
|
+
kinds = {index.type for index in schema.indexes}
|
|
247
|
+
return [
|
|
248
|
+
*_RULES,
|
|
249
|
+
_PARAMETER_RULE if parameterize else _INLINE_VALUES_RULE,
|
|
250
|
+
*(rule for kind, rule in _INDEX_RULES.items() if kind in kinds),
|
|
251
|
+
*([_FUNCTION_RULE] if schema.functions else []),
|
|
252
|
+
*([_EXAMPLES_RULE] if _has_examples(schema) else []),
|
|
253
|
+
*([_DICTIONARY_RULE] if data_dictionary_section(schema) else []),
|
|
254
|
+
*([_SKILLS_RULE] if skills_unread else []),
|
|
255
|
+
]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def _schema_block(schema: GraphSchema) -> str:
|
|
259
|
+
sections = schema_sections(schema)
|
|
260
|
+
if not sections:
|
|
261
|
+
return "# Schema\nThe graph has no data yet, so there is nothing to query."
|
|
262
|
+
return "# Schema\n" + "\n\n".join(as_markdown(section, 2) for section in sections)
|
|
263
|
+
|
|
264
|
+
|
|
200
265
|
def generator_system(
|
|
201
266
|
schema: GraphSchema,
|
|
202
267
|
*,
|
|
@@ -205,36 +270,25 @@ def generator_system(
|
|
|
205
270
|
) -> str:
|
|
206
271
|
"""The system prompt that tells the LLM how to write a query for ``schema``.
|
|
207
272
|
|
|
208
|
-
|
|
209
|
-
|
|
273
|
+
It is Markdown: a heading for the role, the rules, the checks, the format of the
|
|
274
|
+
reply, the examples and the schema. With ``skills``, a section after the rules gives
|
|
275
|
+
the model the skills, as ``skills`` says; without, the prompt has none.
|
|
210
276
|
"""
|
|
211
|
-
kinds = {index.type for index in schema.indexes}
|
|
212
277
|
unread = (
|
|
213
278
|
skills is not None
|
|
214
279
|
and skills.tools
|
|
215
|
-
and any(skill_id not in skills.read for skill_id in
|
|
280
|
+
and any(skill_id not in skills.read for skill_id in skills.catalog)
|
|
216
281
|
)
|
|
217
|
-
rules =
|
|
218
|
-
*_RULES,
|
|
219
|
-
_PARAMETER_RULE if parameterize else _INLINE_VALUES_RULE,
|
|
220
|
-
*(rule for kind, rule in _INDEX_RULES.items() if kind in kinds),
|
|
221
|
-
*([_FUNCTION_RULE] if schema.functions else []),
|
|
222
|
-
*([_EXAMPLES_RULE] if _has_examples(schema) else []),
|
|
223
|
-
*([_SKILLS_RULE] if unread else []),
|
|
224
|
-
]
|
|
282
|
+
rules = rules_for(schema, parameterize=parameterize, skills_unread=unread)
|
|
225
283
|
section = f"\n\n{_skills_section(skills)}" if skills is not None else ""
|
|
226
|
-
text = (
|
|
227
|
-
render_schema(schema)
|
|
228
|
-
or "The graph has no data yet, so there is nothing to query."
|
|
229
|
-
)
|
|
230
284
|
return (
|
|
231
|
-
f"{_INTRO}\n\
|
|
285
|
+
f"# Role\n{_INTRO}\n\n# Rules\n"
|
|
232
286
|
+ "\n".join(rules)
|
|
233
287
|
+ section
|
|
234
288
|
+ f"\n\n{_checks(parameterize)}\n\n{_format_and_examples(parameterize)}"
|
|
235
|
-
f"\
|
|
289
|
+
f"\n\n{_schema_block(schema)}\n"
|
|
236
290
|
)
|
|
237
291
|
|
|
238
292
|
|
|
239
293
|
def generator_user(question: str) -> str:
|
|
240
|
-
return f"Question
|
|
294
|
+
return f"# Question\n{question}"
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
"""Let the model read skills, by calling a tool, while it writes a query."""
|
|
2
2
|
|
|
3
|
-
from collections.abc import Sequence
|
|
3
|
+
from collections.abc import Mapping, Sequence
|
|
4
4
|
|
|
5
5
|
from text2cypher._results import NO_TOKENS
|
|
6
|
-
from text2cypher._skills import skills
|
|
6
|
+
from text2cypher._skills import Skill, skills
|
|
7
7
|
from text2cypher.llm import AsyncChatClient, Completion, Message, Tool, ToolCall, Usage
|
|
8
8
|
|
|
9
9
|
READ_SKILL = Tool(
|
|
@@ -38,17 +38,22 @@ class SkillLoopFailed(Exception):
|
|
|
38
38
|
|
|
39
39
|
|
|
40
40
|
async def chat_reading_skills(
|
|
41
|
-
llm: AsyncChatClient,
|
|
41
|
+
llm: AsyncChatClient,
|
|
42
|
+
system: str,
|
|
43
|
+
messages: Sequence[Message],
|
|
44
|
+
catalog: Mapping[str, Skill] | None = None,
|
|
42
45
|
) -> tuple[Completion, tuple[str, ...], Usage | None]:
|
|
43
46
|
"""The model's reply, the ids of the skills it read, and the tokens of every call.
|
|
44
47
|
|
|
45
48
|
The model is offered ``read_skill`` for up to three rounds; each call is answered with
|
|
46
49
|
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.
|
|
50
|
+
still offered but a call is forbidden. ``catalog`` is what can be read, by id; the
|
|
51
|
+
skills that ship unless given.
|
|
48
52
|
|
|
49
53
|
Raises:
|
|
50
54
|
SkillLoopFailed: If a call fails, with what the earlier calls cost.
|
|
51
55
|
"""
|
|
56
|
+
available = skills() if catalog is None else catalog
|
|
52
57
|
turns = list(messages)
|
|
53
58
|
read: list[str] = []
|
|
54
59
|
usage: Usage | None = NO_TOKENS
|
|
@@ -62,7 +67,9 @@ async def chat_reading_skills(
|
|
|
62
67
|
turns.append(Message("assistant", completion.text, completion.tool_calls))
|
|
63
68
|
for number, call in enumerate(completion.tool_calls):
|
|
64
69
|
content = (
|
|
65
|
-
_too_many
|
|
70
|
+
_too_many
|
|
71
|
+
if number >= _CALLS_PER_ROUND
|
|
72
|
+
else _answer(call, read, available)
|
|
66
73
|
)
|
|
67
74
|
turns.append(Message("tool", content, tool_call_id=call.id))
|
|
68
75
|
completion = await llm.chat(system, turns, [READ_SKILL], tool_choice="none")
|
|
@@ -75,9 +82,8 @@ async def chat_reading_skills(
|
|
|
75
82
|
_too_many = "Too many skills at once: ask for fewer."
|
|
76
83
|
|
|
77
84
|
|
|
78
|
-
def _answer(call: ToolCall, read: list[str]) -> str:
|
|
85
|
+
def _answer(call: ToolCall, read: list[str], available: Mapping[str, Skill]) -> str:
|
|
79
86
|
"""What the model is told about one call to ``read_skill``; the id is added to ``read``."""
|
|
80
|
-
available = skills()
|
|
81
87
|
wanted = call.arguments.get("id")
|
|
82
88
|
ids = ", ".join(available)
|
|
83
89
|
if not isinstance(wanted, str) or not wanted:
|