text2cypher 2.0.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.
- {text2cypher-2.0.0 → text2cypher-2.1.0}/PKG-INFO +4 -4
- {text2cypher-2.0.0 → text2cypher-2.1.0}/README.md +2 -2
- {text2cypher-2.0.0 → text2cypher-2.1.0}/THIRD_PARTY_NOTICES +1 -1
- {text2cypher-2.0.0 → text2cypher-2.1.0}/pyproject.toml +4 -5
- {text2cypher-2.0.0 → text2cypher-2.1.0}/pyproject.toml.orig +4 -5
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/__init__.py +10 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_config.py +2 -1
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/generate.py +11 -4
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/prompts.py +7 -3
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/read_skill.py +13 -7
- text2cypher-2.1.0/src/text2cypher/_graph/__init__.py +14 -0
- text2cypher-2.0.0/src/text2cypher/_schema_source.py → text2cypher-2.1.0/src/text2cypher/_graph/schema_source.py +1 -1
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_pipeline.py +29 -3
- text2cypher-2.1.0/src/text2cypher/_results/__init__.py +37 -0
- text2cypher-2.0.0/src/text2cypher/_results.py → text2cypher-2.1.0/src/text2cypher/_results/results.py +11 -1
- text2cypher-2.1.0/src/text2cypher/_results/values.py +150 -0
- text2cypher-2.1.0/src/text2cypher/_skills/__init__.py +178 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_workflow.py +10 -3
- text2cypher-2.1.0/src/text2cypher/skills.py +5 -0
- text2cypher-2.0.0/src/text2cypher/_skills/__init__.py +0 -69
- {text2cypher-2.0.0 → text2cypher-2.1.0}/LICENSE +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_errors.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/conversation.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/extract.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/header.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/problems.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/schema_filter.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_generation/typos.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_examples.py → /text2cypher-2.1.0/src/text2cypher/_graph/examples.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_execution.py → /text2cypher-2.1.0/src/text2cypher/_graph/execution.py +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/functions/skill.md → /text2cypher-2.1.0/src/text2cypher/_skills/functions/SKILL.md +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/graph-algorithms/skill.md → /text2cypher-2.1.0/src/text2cypher/_skills/graph-algorithms/SKILL.md +0 -0
- /text2cypher-2.0.0/src/text2cypher/_skills/path-finding/skill.md → /text2cypher-2.1.0/src/text2cypher/_skills/path-finding/SKILL.md +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_validation/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_validation/issues.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/_validation/validator.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/llm/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/llm/_adapt.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/llm/_base.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/llm/_fake.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/llm/_openai.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/py.typed +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/__init__.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/_filter.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/_from_snapshot.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/_model.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/_render.py +0 -0
- {text2cypher-2.0.0 → text2cypher-2.1.0}/src/text2cypher/schema/_stopwords.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: text2cypher
|
|
3
|
-
Version: 2.
|
|
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
|
|
@@ -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
|
|
@@ -93,7 +93,7 @@ asyncio.run(main())
|
|
|
93
93
|
|
|
94
94
|
Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
|
|
95
95
|
|
|
96
|
-
There is also [a quickstart
|
|
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.
|
|
97
97
|
|
|
98
98
|
## What is and is not checked
|
|
99
99
|
|
|
@@ -102,7 +102,7 @@ There is also [a quickstart that needs no model and no server](https://github.co
|
|
|
102
102
|
|
|
103
103
|
## Configuration
|
|
104
104
|
|
|
105
|
-
* See
|
|
105
|
+
* See the configuration table in [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
|
|
106
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
107
|
|
|
108
108
|
|
|
@@ -60,7 +60,7 @@ asyncio.run(main())
|
|
|
60
60
|
|
|
61
61
|
Always look at `result.status`. `valid` means the query passed the checks, not that it means what you meant.
|
|
62
62
|
|
|
63
|
-
There is also [a quickstart
|
|
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.
|
|
64
64
|
|
|
65
65
|
## What is and is not checked
|
|
66
66
|
|
|
@@ -69,7 +69,7 @@ There is also [a quickstart that needs no model and no server](https://github.co
|
|
|
69
69
|
|
|
70
70
|
## Configuration
|
|
71
71
|
|
|
72
|
-
* See
|
|
72
|
+
* See the configuration table in [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html#configuration) for every option.
|
|
73
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
74
|
|
|
75
75
|
|
|
@@ -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 = "2.
|
|
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.
|
|
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 = "2.
|
|
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.
|
|
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,
|
|
@@ -47,7 +52,10 @@ __all__ = [
|
|
|
47
52
|
"DatabaseError",
|
|
48
53
|
"FakeLLM",
|
|
49
54
|
"FilterResult",
|
|
55
|
+
"GraphNode",
|
|
50
56
|
"GraphNotFoundError",
|
|
57
|
+
"GraphPath",
|
|
58
|
+
"GraphRelationship",
|
|
51
59
|
"GraphSchema",
|
|
52
60
|
"Issue",
|
|
53
61
|
"LLMError",
|
|
@@ -57,6 +65,7 @@ __all__ = [
|
|
|
57
65
|
"Records",
|
|
58
66
|
"Result",
|
|
59
67
|
"SchemaFilter",
|
|
68
|
+
"Skill",
|
|
60
69
|
"Text2Cypher",
|
|
61
70
|
"Text2CypherError",
|
|
62
71
|
"Tool",
|
|
@@ -65,4 +74,5 @@ __all__ = [
|
|
|
65
74
|
"ValidationResult",
|
|
66
75
|
"__version__",
|
|
67
76
|
"filter_schema",
|
|
77
|
+
"to_python",
|
|
68
78
|
]
|
|
@@ -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,
|
|
@@ -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,7 +1,9 @@
|
|
|
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
8
|
from text2cypher.schema import GraphSchema, render_schema
|
|
7
9
|
|
|
@@ -118,15 +120,17 @@ class SkillsOffer:
|
|
|
118
120
|
``read_skill``; ``False`` to put every one in the prompt, for a client that
|
|
119
121
|
cannot be offered tools.
|
|
120
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.
|
|
121
124
|
"""
|
|
122
125
|
|
|
123
126
|
tools: bool
|
|
124
127
|
read: tuple[str, ...] = ()
|
|
128
|
+
catalog: Mapping[str, Skill] = field(default_factory=shipped_skills)
|
|
125
129
|
|
|
126
130
|
|
|
127
131
|
def _skills_section(offer: SkillsOffer) -> str:
|
|
128
132
|
"""What the prompt says about the skills: a list to read from, those already read, or all."""
|
|
129
|
-
guides =
|
|
133
|
+
guides = offer.catalog
|
|
130
134
|
if not offer.tools:
|
|
131
135
|
everything = "\n\n".join(skill.text for skill in guides.values())
|
|
132
136
|
return f"Skills (guides to parts of FalkorDB that are easy to get wrong):\n\n{everything}"
|
|
@@ -212,7 +216,7 @@ def generator_system(
|
|
|
212
216
|
unread = (
|
|
213
217
|
skills is not None
|
|
214
218
|
and skills.tools
|
|
215
|
-
and any(skill_id not in skills.read for skill_id in
|
|
219
|
+
and any(skill_id not in skills.read for skill_id in skills.catalog)
|
|
216
220
|
)
|
|
217
221
|
rules = [
|
|
218
222
|
*_RULES,
|
|
@@ -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:
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"""Talking to FalkorDB: reading the schema and example values, and running a query."""
|
|
2
|
+
|
|
3
|
+
from text2cypher._graph.examples import Examples, sample_examples
|
|
4
|
+
from text2cypher._graph.execution import Execution, execute_cypher, run_query
|
|
5
|
+
from text2cypher._graph.schema_source import SchemaSource
|
|
6
|
+
|
|
7
|
+
__all__ = [
|
|
8
|
+
"Examples",
|
|
9
|
+
"Execution",
|
|
10
|
+
"SchemaSource",
|
|
11
|
+
"execute_cypher",
|
|
12
|
+
"run_query",
|
|
13
|
+
"sample_examples",
|
|
14
|
+
]
|
|
@@ -8,7 +8,7 @@ from cypher_guardrail import AsyncLiveSnapshot, Snapshot, SnapshotSource
|
|
|
8
8
|
from falkordb.asyncio import FalkorDB
|
|
9
9
|
|
|
10
10
|
from text2cypher._errors import GraphNotFoundError
|
|
11
|
-
from text2cypher.
|
|
11
|
+
from text2cypher._graph.examples import Examples, sample_examples
|
|
12
12
|
from text2cypher.schema import GraphSchema, schema_from_snapshot
|
|
13
13
|
|
|
14
14
|
# A live snapshot refreshes itself in the background after this long; ours is refreshed by
|
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
"""The entry point: ask a question of a graph."""
|
|
2
2
|
|
|
3
|
-
from collections.abc import Awaitable, Callable
|
|
3
|
+
from collections.abc import Awaitable, Callable, Sequence
|
|
4
4
|
|
|
5
5
|
from falkordb.asyncio import FalkorDB
|
|
6
6
|
from openai import AsyncOpenAI
|
|
7
7
|
|
|
8
8
|
from text2cypher._config import Config
|
|
9
|
-
from text2cypher._execution import Execution, run_query
|
|
10
9
|
from text2cypher._generation import AsyncSchemaFilter, LLMSchemaFilter
|
|
10
|
+
from text2cypher._graph import Execution, SchemaSource, run_query
|
|
11
11
|
from text2cypher._results import Result
|
|
12
|
-
from text2cypher.
|
|
12
|
+
from text2cypher._skills import Skill, catalog, check_inline, skills
|
|
13
13
|
from text2cypher._validation import QueryValidator
|
|
14
14
|
from text2cypher._workflow import run_workflow
|
|
15
15
|
from text2cypher.llm import AsyncChatClient, AsyncLLMClient
|
|
16
16
|
from text2cypher.llm._adapt import as_client
|
|
17
|
+
from text2cypher.llm._base import supports_tools
|
|
17
18
|
from text2cypher.schema import SchemaFilter, filter_schema
|
|
18
19
|
|
|
19
20
|
|
|
@@ -38,6 +39,15 @@ class Text2Cypher:
|
|
|
38
39
|
``LLMSchemaFilter`` asks a model instead (it is given ``llm`` unless it has
|
|
39
40
|
its own), and runs alone. ``None`` turns filtering off: every attempt uses the
|
|
40
41
|
full schema. It may be a function or an async one; see ``AsyncSchemaFilter``.
|
|
42
|
+
skills: The skills the LLM can read, in place of the ones that ship (to add to them,
|
|
43
|
+
pass ``[*builtin_skills(), yours]``; see ``text2cypher.skills``). It needs
|
|
44
|
+
``Config(use_skills=True)``. A skill is text that steers the model and goes to the
|
|
45
|
+
LLM provider: use only text you trust. A client that cannot be offered tools is
|
|
46
|
+
given every skill in each prompt, so they may add up to 16,000 characters.
|
|
47
|
+
|
|
48
|
+
Raises:
|
|
49
|
+
ValueError: If ``skills`` is given without ``use_skills``, is empty, has two skills
|
|
50
|
+
with one id, or (for a client without tools) is too long to put in every prompt.
|
|
41
51
|
"""
|
|
42
52
|
|
|
43
53
|
def __init__(
|
|
@@ -48,10 +58,12 @@ class Text2Cypher:
|
|
|
48
58
|
model: str | None = None,
|
|
49
59
|
config: Config | None = None,
|
|
50
60
|
schema_filter: SchemaFilter | AsyncSchemaFilter | None = filter_schema,
|
|
61
|
+
skills: Sequence[Skill] | None = None,
|
|
51
62
|
) -> None:
|
|
52
63
|
self._client = client
|
|
53
64
|
self._llm = as_client(llm, model)
|
|
54
65
|
self._config = config or Config()
|
|
66
|
+
self._skills = self._skills_on_offer(skills)
|
|
55
67
|
# A filter that has no client of its own is given the main one
|
|
56
68
|
if isinstance(schema_filter, LLMSchemaFilter):
|
|
57
69
|
schema_filter = schema_filter.bound(self._llm)
|
|
@@ -60,6 +72,19 @@ class Text2Cypher:
|
|
|
60
72
|
client, self._config.schema_refresh_seconds, self._config.example_values
|
|
61
73
|
)
|
|
62
74
|
|
|
75
|
+
def _skills_on_offer(
|
|
76
|
+
self, chosen: Sequence[Skill] | None
|
|
77
|
+
) -> dict[str, Skill] | None:
|
|
78
|
+
"""What the LLM may read, checked; ``None`` when skills are off."""
|
|
79
|
+
if not self._config.use_skills:
|
|
80
|
+
if chosen is not None:
|
|
81
|
+
raise ValueError("skills needs Config(use_skills=True)")
|
|
82
|
+
return None
|
|
83
|
+
offered = dict(skills()) if chosen is None else catalog(chosen)
|
|
84
|
+
if not supports_tools(self._llm):
|
|
85
|
+
check_inline(offered)
|
|
86
|
+
return offered
|
|
87
|
+
|
|
63
88
|
def clear_schema(self, graph: str | None = None) -> None:
|
|
64
89
|
"""Forget what is kept of the schema of ``graph``, or of every graph.
|
|
65
90
|
|
|
@@ -103,6 +128,7 @@ class Text2Cypher:
|
|
|
103
128
|
config=self._config,
|
|
104
129
|
schema_filter=self._schema_filter,
|
|
105
130
|
execute=self._executor(graph),
|
|
131
|
+
skills=self._skills,
|
|
106
132
|
)
|
|
107
133
|
|
|
108
134
|
def _executor(self, graph: str) -> Callable[[str], Awaitable[Execution]] | None:
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""What comes back from a run: the result, its attempts and the errors, and the values of a query."""
|
|
2
|
+
|
|
3
|
+
from text2cypher._results.results import (
|
|
4
|
+
NO_TOKENS,
|
|
5
|
+
Attempt,
|
|
6
|
+
DatabaseError,
|
|
7
|
+
LLMError,
|
|
8
|
+
Records,
|
|
9
|
+
Result,
|
|
10
|
+
RunInterrupted,
|
|
11
|
+
SchemaScope,
|
|
12
|
+
Status,
|
|
13
|
+
total_usage,
|
|
14
|
+
)
|
|
15
|
+
from text2cypher._results.values import (
|
|
16
|
+
GraphNode,
|
|
17
|
+
GraphPath,
|
|
18
|
+
GraphRelationship,
|
|
19
|
+
to_python,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = [
|
|
23
|
+
"NO_TOKENS",
|
|
24
|
+
"Attempt",
|
|
25
|
+
"DatabaseError",
|
|
26
|
+
"GraphNode",
|
|
27
|
+
"GraphPath",
|
|
28
|
+
"GraphRelationship",
|
|
29
|
+
"LLMError",
|
|
30
|
+
"Records",
|
|
31
|
+
"Result",
|
|
32
|
+
"RunInterrupted",
|
|
33
|
+
"SchemaScope",
|
|
34
|
+
"Status",
|
|
35
|
+
"to_python",
|
|
36
|
+
"total_usage",
|
|
37
|
+
]
|
|
@@ -5,6 +5,7 @@ from dataclasses import dataclass
|
|
|
5
5
|
from typing import Any, Literal, Self
|
|
6
6
|
|
|
7
7
|
from text2cypher._errors import Text2CypherError
|
|
8
|
+
from text2cypher._results.values import to_python
|
|
8
9
|
from text2cypher._validation import ValidationResult
|
|
9
10
|
from text2cypher.llm import Usage
|
|
10
11
|
|
|
@@ -77,7 +78,7 @@ class Records:
|
|
|
77
78
|
"""What a query returned: the names of its columns, and its rows.
|
|
78
79
|
|
|
79
80
|
Values are the client's own: nodes, relationships and paths are ``falkordb``
|
|
80
|
-
objects.
|
|
81
|
+
objects. ``as_python()`` gives the same rows with them as plain objects.
|
|
81
82
|
|
|
82
83
|
Attributes:
|
|
83
84
|
columns: The names of the columns, as the query returns them.
|
|
@@ -87,6 +88,15 @@ class Records:
|
|
|
87
88
|
columns: tuple[str, ...]
|
|
88
89
|
rows: tuple[tuple[Any, ...], ...]
|
|
89
90
|
|
|
91
|
+
def as_python(self) -> Self:
|
|
92
|
+
"""The same columns and rows, with every node, relationship and path (also inside a
|
|
93
|
+
list or a map) as a ``GraphNode``, ``GraphRelationship`` or ``GraphPath``, which
|
|
94
|
+
have no client in them. This ``Records`` is not changed, and calling it on one that
|
|
95
|
+
was converted gives the same values."""
|
|
96
|
+
return type(self)(
|
|
97
|
+
self.columns, tuple(tuple(to_python(v) for v in row) for row in self.rows)
|
|
98
|
+
)
|
|
99
|
+
|
|
90
100
|
|
|
91
101
|
@dataclass(frozen=True, slots=True)
|
|
92
102
|
class Result:
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Nodes, relationships and paths as plain Python objects, with no client in them."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Mapping
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
from types import MappingProxyType
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from falkordb.edge import Edge
|
|
9
|
+
from falkordb.node import Node
|
|
10
|
+
from falkordb.path import Path
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
@dataclass(frozen=True, slots=True, eq=False, repr=False)
|
|
14
|
+
class GraphNode:
|
|
15
|
+
"""A node a query returned, as a plain object.
|
|
16
|
+
|
|
17
|
+
Two nodes are equal when they have the same ``id``, and the same hash.
|
|
18
|
+
|
|
19
|
+
Attributes:
|
|
20
|
+
id: The node's id in the graph.
|
|
21
|
+
labels: Its labels.
|
|
22
|
+
properties: Its properties, read-only. ``node["name"]`` and ``node.get("name")``
|
|
23
|
+
read one.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
id: int
|
|
27
|
+
labels: tuple[str, ...]
|
|
28
|
+
properties: Mapping[str, Any]
|
|
29
|
+
|
|
30
|
+
def __post_init__(self) -> None:
|
|
31
|
+
object.__setattr__(self, "labels", tuple(self.labels))
|
|
32
|
+
object.__setattr__(self, "properties", MappingProxyType(dict(self.properties)))
|
|
33
|
+
|
|
34
|
+
def __getitem__(self, name: str) -> Any:
|
|
35
|
+
return self.properties[name]
|
|
36
|
+
|
|
37
|
+
def get(self, name: str, default: Any = None) -> Any:
|
|
38
|
+
"""The property ``name``, or ``default`` if there is none."""
|
|
39
|
+
return self.properties.get(name, default)
|
|
40
|
+
|
|
41
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
42
|
+
return (GraphNode, (self.id, self.labels, dict(self.properties)))
|
|
43
|
+
|
|
44
|
+
def __eq__(self, other: object) -> bool:
|
|
45
|
+
return isinstance(other, GraphNode) and other.id == self.id
|
|
46
|
+
|
|
47
|
+
def __hash__(self) -> int:
|
|
48
|
+
return hash(("node", self.id))
|
|
49
|
+
|
|
50
|
+
def __repr__(self) -> str:
|
|
51
|
+
return f"GraphNode(id={self.id!r}, labels={self.labels!r}, properties={dict(self.properties)!r})"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
@dataclass(frozen=True, slots=True, eq=False, repr=False)
|
|
55
|
+
class GraphRelationship:
|
|
56
|
+
"""A relationship a query returned, as a plain object.
|
|
57
|
+
|
|
58
|
+
Two relationships are equal when they have the same ``id``, and the same hash.
|
|
59
|
+
|
|
60
|
+
Attributes:
|
|
61
|
+
id: The relationship's id in the graph.
|
|
62
|
+
type: Its type, for example ``"KNOWS"``.
|
|
63
|
+
start_id: The id of the node it starts at.
|
|
64
|
+
end_id: The id of the node it ends at.
|
|
65
|
+
properties: Its properties, read-only.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
id: int
|
|
69
|
+
type: str
|
|
70
|
+
start_id: int
|
|
71
|
+
end_id: int
|
|
72
|
+
properties: Mapping[str, Any]
|
|
73
|
+
|
|
74
|
+
def __post_init__(self) -> None:
|
|
75
|
+
object.__setattr__(self, "properties", MappingProxyType(dict(self.properties)))
|
|
76
|
+
|
|
77
|
+
def __getitem__(self, name: str) -> Any:
|
|
78
|
+
return self.properties[name]
|
|
79
|
+
|
|
80
|
+
def get(self, name: str, default: Any = None) -> Any:
|
|
81
|
+
"""The property ``name``, or ``default`` if there is none."""
|
|
82
|
+
return self.properties.get(name, default)
|
|
83
|
+
|
|
84
|
+
def __reduce__(self) -> tuple[Any, ...]:
|
|
85
|
+
return (
|
|
86
|
+
GraphRelationship,
|
|
87
|
+
(self.id, self.type, self.start_id, self.end_id, dict(self.properties)),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def __eq__(self, other: object) -> bool:
|
|
91
|
+
return isinstance(other, GraphRelationship) and other.id == self.id
|
|
92
|
+
|
|
93
|
+
def __hash__(self) -> int:
|
|
94
|
+
return hash(("relationship", self.id))
|
|
95
|
+
|
|
96
|
+
def __repr__(self) -> str:
|
|
97
|
+
return (
|
|
98
|
+
f"GraphRelationship(id={self.id!r}, type={self.type!r}, start_id={self.start_id!r}, "
|
|
99
|
+
f"end_id={self.end_id!r}, properties={dict(self.properties)!r})"
|
|
100
|
+
)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass(frozen=True, slots=True)
|
|
104
|
+
class GraphPath:
|
|
105
|
+
"""A path a query returned, as plain objects.
|
|
106
|
+
|
|
107
|
+
Attributes:
|
|
108
|
+
nodes: The nodes along the path, in order.
|
|
109
|
+
relationships: The relationships between them, in order: one fewer than the nodes.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
nodes: tuple[GraphNode, ...]
|
|
113
|
+
relationships: tuple[GraphRelationship, ...]
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def to_python(value: Any) -> Any:
|
|
117
|
+
"""``value`` with every node, relationship and path in it as a plain object.
|
|
118
|
+
|
|
119
|
+
A ``falkordb`` node, edge or path becomes a ``GraphNode``, ``GraphRelationship`` or
|
|
120
|
+
``GraphPath``; a list, tuple or map is converted inside, and a map comes back as a
|
|
121
|
+
``dict``. Anything else (text, numbers, dates, points) is the client's own value,
|
|
122
|
+
which is already plain. A value that was converted before is returned as it is.
|
|
123
|
+
"""
|
|
124
|
+
if isinstance(value, Node):
|
|
125
|
+
return GraphNode(_id(value), tuple(value.labels or ()), value.properties or {})
|
|
126
|
+
if isinstance(value, Edge):
|
|
127
|
+
return GraphRelationship(
|
|
128
|
+
_id(value),
|
|
129
|
+
value.relation,
|
|
130
|
+
_id(value.src_node),
|
|
131
|
+
_id(value.dest_node),
|
|
132
|
+
value.properties or {},
|
|
133
|
+
)
|
|
134
|
+
if isinstance(value, Path):
|
|
135
|
+
return GraphPath(
|
|
136
|
+
tuple(to_python(node) for node in value.nodes()),
|
|
137
|
+
tuple(to_python(edge) for edge in value.edges()),
|
|
138
|
+
)
|
|
139
|
+
if isinstance(value, list):
|
|
140
|
+
return [to_python(item) for item in value]
|
|
141
|
+
if isinstance(value, tuple):
|
|
142
|
+
return tuple(to_python(item) for item in value)
|
|
143
|
+
if isinstance(value, dict):
|
|
144
|
+
return {key: to_python(item) for key, item in value.items()}
|
|
145
|
+
return value
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _id(entity: Any) -> int:
|
|
149
|
+
"""The id of a node or relationship, or an id that is already one."""
|
|
150
|
+
return getattr(entity, "id", entity)
|
|
@@ -0,0 +1,178 @@
|
|
|
1
|
+
"""Short guides to the parts of FalkorDB's Cypher that a model gets wrong without them.
|
|
2
|
+
|
|
3
|
+
Each skill is a folder with a ``SKILL.md``: a front matter with a ``name`` and a one-line
|
|
4
|
+
``description``, then the guide. The folder's name is the skill's id. Adding a skill is
|
|
5
|
+
adding a folder; the tests run every example in every skill on a FalkorDB.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Iterable, Mapping
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from functools import cache
|
|
12
|
+
from importlib import resources
|
|
13
|
+
from importlib.resources.abc import Traversable
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
_FRONT_MATTER = re.compile(r"\A---\n(.*?)\n---\n(.*)\Z", re.DOTALL)
|
|
17
|
+
_ID = re.compile(r"[\w.-]+")
|
|
18
|
+
_CYPHER_BLOCK = re.compile(r"```cypher\n(.*?)```", re.DOTALL | re.IGNORECASE)
|
|
19
|
+
_STRING = re.compile(r"'(?:[^'\\]|\\.)*'|\"(?:[^\"\\]|\\.)*\"")
|
|
20
|
+
# A clause, not a function of the same name (``list.remove``)
|
|
21
|
+
_WRITE = re.compile(
|
|
22
|
+
r"(?<![\w.])(CREATE|MERGE|DELETE|DETACH|SET|REMOVE|DROP|FOREACH)\b", re.IGNORECASE
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
# What every skill may add up to in a prompt, for a client that cannot be offered tools and
|
|
26
|
+
# so is given all of them in every request
|
|
27
|
+
INLINE_LIMIT = 16_000
|
|
28
|
+
|
|
29
|
+
# The file of a skill's folder
|
|
30
|
+
GUIDE = "SKILL.md"
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass(frozen=True, slots=True)
|
|
34
|
+
class Skill:
|
|
35
|
+
"""One guide.
|
|
36
|
+
|
|
37
|
+
Attributes:
|
|
38
|
+
id: The folder's name, which a model asks for it by.
|
|
39
|
+
name: What it is called.
|
|
40
|
+
description: One line that says what it covers and when to read it.
|
|
41
|
+
body: The guide, in Markdown, with examples in ``cypher`` blocks.
|
|
42
|
+
|
|
43
|
+
Raises:
|
|
44
|
+
ValueError: If the id is empty or has anything but letters, digits, ``_``, ``-`` and
|
|
45
|
+
``.``; if the name, the description or the body is empty; if the description is
|
|
46
|
+
more than one line; or if an example in a ``cypher`` block writes to the graph
|
|
47
|
+
(``CREATE``, ``MERGE``, ``DELETE``, ``SET`` and the like), because the library
|
|
48
|
+
only ever returns read-only queries and a guide must not teach otherwise.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
id: str
|
|
52
|
+
name: str
|
|
53
|
+
description: str
|
|
54
|
+
body: str
|
|
55
|
+
|
|
56
|
+
def __post_init__(self) -> None:
|
|
57
|
+
if not _ID.fullmatch(self.id):
|
|
58
|
+
raise ValueError(
|
|
59
|
+
f"The id of a skill is letters, digits, _, - and . only, not {self.id!r}"
|
|
60
|
+
)
|
|
61
|
+
if (
|
|
62
|
+
not self.name.strip()
|
|
63
|
+
or not self.description.strip()
|
|
64
|
+
or not self.body.strip()
|
|
65
|
+
):
|
|
66
|
+
raise ValueError(
|
|
67
|
+
f"The skill {self.id!r} needs a name, a description and a body"
|
|
68
|
+
)
|
|
69
|
+
if "\n" in self.description.strip():
|
|
70
|
+
raise ValueError(
|
|
71
|
+
f"The description of the skill {self.id!r} is more than one line"
|
|
72
|
+
)
|
|
73
|
+
for block in _CYPHER_BLOCK.findall(self.body):
|
|
74
|
+
written = _WRITE.search(_STRING.sub("", block))
|
|
75
|
+
if written:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
f"The skill {self.id!r} has an example that writes ({written[1].upper()}); "
|
|
78
|
+
"an example must be read-only"
|
|
79
|
+
)
|
|
80
|
+
|
|
81
|
+
@property
|
|
82
|
+
def text(self) -> str:
|
|
83
|
+
"""What a model is given when it reads the skill."""
|
|
84
|
+
return f"# {self.name}\n\n{self.body.strip()}"
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@cache
|
|
88
|
+
def skills() -> dict[str, Skill]:
|
|
89
|
+
"""Every skill that ships with the package, by id, in id order."""
|
|
90
|
+
return load(resources.files(__package__))
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def builtin_skills() -> list[Skill]:
|
|
94
|
+
"""The skills that ship with the package, in id order."""
|
|
95
|
+
return list(skills().values())
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def load_skills(directory: str | Path) -> list[Skill]:
|
|
99
|
+
"""The skills in the folders of ``directory``, as ``load`` reads them, in id order.
|
|
100
|
+
|
|
101
|
+
Raises:
|
|
102
|
+
ValueError: If a ``SKILL.md`` is not a valid skill, or there is none.
|
|
103
|
+
FileNotFoundError: If ``directory`` does not exist.
|
|
104
|
+
"""
|
|
105
|
+
path = Path(directory)
|
|
106
|
+
if not path.is_dir():
|
|
107
|
+
raise FileNotFoundError(f"{path} is not a directory")
|
|
108
|
+
found = list(load(path).values())
|
|
109
|
+
if not found:
|
|
110
|
+
raise ValueError(f"There is no skill (a folder with a SKILL.md) in {path}")
|
|
111
|
+
return found
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def catalog(chosen: Iterable[Skill]) -> dict[str, Skill]:
|
|
115
|
+
"""``chosen`` by id, in the order given.
|
|
116
|
+
|
|
117
|
+
Raises:
|
|
118
|
+
ValueError: If there are none, or two have the same id.
|
|
119
|
+
"""
|
|
120
|
+
found: dict[str, Skill] = {}
|
|
121
|
+
for skill in chosen:
|
|
122
|
+
if skill.id in found:
|
|
123
|
+
raise ValueError(f"Two skills have the id {skill.id!r}")
|
|
124
|
+
found[skill.id] = skill
|
|
125
|
+
if not found:
|
|
126
|
+
raise ValueError("skills is empty; turn use_skills off instead")
|
|
127
|
+
return found
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def check_inline(guides: Mapping[str, Skill]) -> None:
|
|
131
|
+
"""Raise ``ValueError`` if ``guides`` are too long to put in every prompt."""
|
|
132
|
+
size = sum(len(skill.text) for skill in guides.values())
|
|
133
|
+
if size > INLINE_LIMIT:
|
|
134
|
+
raise ValueError(
|
|
135
|
+
f"The skills add up to {size} characters, more than the {INLINE_LIMIT} that fit in "
|
|
136
|
+
"every prompt of a client that cannot be offered tools; use fewer or shorter ones"
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def load(directory: Traversable) -> dict[str, Skill]:
|
|
141
|
+
"""The skills in the folders of ``directory`` that have a ``SKILL.md``, by id, sorted.
|
|
142
|
+
|
|
143
|
+
The file is found whatever the case of its name (``SKILL.md``, ``skill.md``), the same
|
|
144
|
+
on every file system, because the entries are listed and compared, not opened by name.
|
|
145
|
+
|
|
146
|
+
Raises:
|
|
147
|
+
ValueError: If a ``SKILL.md`` has no front matter, or no ``name`` or ``description``,
|
|
148
|
+
or a description of more than one line, or a folder has two files whose names
|
|
149
|
+
differ only in case.
|
|
150
|
+
"""
|
|
151
|
+
found = {}
|
|
152
|
+
for folder in sorted(directory.iterdir(), key=lambda entry: entry.name):
|
|
153
|
+
if not folder.is_dir():
|
|
154
|
+
continue
|
|
155
|
+
guides = [
|
|
156
|
+
entry
|
|
157
|
+
for entry in folder.iterdir()
|
|
158
|
+
if entry.name.lower() == GUIDE.lower() and entry.is_file()
|
|
159
|
+
]
|
|
160
|
+
if len(guides) > 1:
|
|
161
|
+
raise ValueError(f"The skill {folder.name!r} has more than one {GUIDE}")
|
|
162
|
+
if guides:
|
|
163
|
+
found[folder.name] = _parse(
|
|
164
|
+
folder.name, guides[0].read_text(encoding="utf-8")
|
|
165
|
+
)
|
|
166
|
+
return found
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _parse(skill_id: str, text: str) -> Skill:
|
|
170
|
+
parts = _FRONT_MATTER.match(text)
|
|
171
|
+
if parts is None:
|
|
172
|
+
raise ValueError(f"The skill {skill_id!r} has no front matter")
|
|
173
|
+
fields = dict(line.split(":", 1) for line in parts[1].splitlines() if ":" in line)
|
|
174
|
+
name = fields.get("name", "").strip()
|
|
175
|
+
description = fields.get("description", "").strip()
|
|
176
|
+
if not name or not description:
|
|
177
|
+
raise ValueError(f"The skill {skill_id!r} needs a name and a description")
|
|
178
|
+
return Skill(skill_id, name, description, parts[2].strip())
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
"""The loop: generate a query, validate it, correct it, and escalate the schema."""
|
|
2
2
|
|
|
3
|
-
from collections.abc import Awaitable, Callable, Sequence
|
|
3
|
+
from collections.abc import Awaitable, Callable, Mapping, Sequence
|
|
4
4
|
from dataclasses import replace
|
|
5
5
|
|
|
6
6
|
from redis.exceptions import RedisError
|
|
7
7
|
|
|
8
8
|
from text2cypher._config import Config
|
|
9
|
-
from text2cypher._execution import Execution
|
|
10
9
|
from text2cypher._generation import (
|
|
11
10
|
AsyncSchemaFilter,
|
|
12
11
|
Generation,
|
|
@@ -17,6 +16,7 @@ from text2cypher._generation import (
|
|
|
17
16
|
generate_cypher,
|
|
18
17
|
repair_header,
|
|
19
18
|
)
|
|
19
|
+
from text2cypher._graph import Execution
|
|
20
20
|
from text2cypher._results import (
|
|
21
21
|
NO_TOKENS,
|
|
22
22
|
Attempt,
|
|
@@ -26,6 +26,7 @@ from text2cypher._results import (
|
|
|
26
26
|
SchemaScope,
|
|
27
27
|
Status,
|
|
28
28
|
)
|
|
29
|
+
from text2cypher._skills import Skill
|
|
29
30
|
from text2cypher._validation import ValidationResult
|
|
30
31
|
from text2cypher.llm import AsyncChatClient, AsyncLLMClient, Usage
|
|
31
32
|
from text2cypher.schema import GraphSchema, SchemaFilter
|
|
@@ -49,6 +50,7 @@ async def run_workflow(
|
|
|
49
50
|
config: Config,
|
|
50
51
|
schema_filter: SchemaFilter | AsyncSchemaFilter | None = None,
|
|
51
52
|
execute: Callable[[str], Awaitable[Execution]] | None = None,
|
|
53
|
+
skills: Mapping[str, Skill] | None = None,
|
|
52
54
|
) -> Result:
|
|
53
55
|
"""Answer ``question`` with a query that passes ``validate``, if one can be found.
|
|
54
56
|
|
|
@@ -73,6 +75,9 @@ async def run_workflow(
|
|
|
73
75
|
other; when the corrections run out the result is ``failed``. A timeout or a lost
|
|
74
76
|
connection ends the loop with the valid query and the error, as they say nothing
|
|
75
77
|
about the query.
|
|
78
|
+
|
|
79
|
+
With ``config.use_skills``, ``skills`` is what the LLM can read, by id; the skills that
|
|
80
|
+
ship unless given.
|
|
76
81
|
"""
|
|
77
82
|
filtered, filter_usage = None, NO_TOKENS
|
|
78
83
|
if schema_filter is not None:
|
|
@@ -94,7 +99,7 @@ async def run_workflow(
|
|
|
94
99
|
)
|
|
95
100
|
rounds = _with_schema_note(rounds, attempts, scope)
|
|
96
101
|
generation = await _write(
|
|
97
|
-
llm, used, question, rounds, scope, attempts, filter_usage, config
|
|
102
|
+
llm, used, question, rounds, scope, attempts, filter_usage, config, skills
|
|
98
103
|
)
|
|
99
104
|
empties = empties + 1 if generation.empty else 0
|
|
100
105
|
if not generation.query:
|
|
@@ -261,6 +266,7 @@ async def _write(
|
|
|
261
266
|
attempts: Sequence[Attempt],
|
|
262
267
|
filter_usage: Usage | None,
|
|
263
268
|
config: Config,
|
|
269
|
+
catalog: Mapping[str, Skill] | None,
|
|
264
270
|
) -> Generation:
|
|
265
271
|
"""The next query, or an ``LLMError`` that keeps what was paid for.
|
|
266
272
|
|
|
@@ -275,6 +281,7 @@ async def _write(
|
|
|
275
281
|
rounds,
|
|
276
282
|
parameterize=config.use_parameters,
|
|
277
283
|
skills=config.use_skills,
|
|
284
|
+
catalog=catalog,
|
|
278
285
|
)
|
|
279
286
|
except SkillLoopFailed as failed:
|
|
280
287
|
partial = [Attempt("", None, scope, failed.usage)] if failed.calls else []
|
|
@@ -1,69 +0,0 @@
|
|
|
1
|
-
"""Short guides to the parts of FalkorDB's Cypher that a model gets wrong without them.
|
|
2
|
-
|
|
3
|
-
Each skill is a folder with a ``skill.md``: a front matter with a ``name`` and a one-line
|
|
4
|
-
``description``, then the guide. The folder's name is the skill's id. Adding a skill is
|
|
5
|
-
adding a folder; the tests run every example in every skill on a FalkorDB.
|
|
6
|
-
"""
|
|
7
|
-
|
|
8
|
-
import re
|
|
9
|
-
from dataclasses import dataclass
|
|
10
|
-
from functools import cache
|
|
11
|
-
from importlib import resources
|
|
12
|
-
from importlib.resources.abc import Traversable
|
|
13
|
-
|
|
14
|
-
_FRONT_MATTER = re.compile(r"\A---\n(.*?)\n---\n(.*)\Z", re.DOTALL)
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
@dataclass(frozen=True, slots=True)
|
|
18
|
-
class Skill:
|
|
19
|
-
"""One guide.
|
|
20
|
-
|
|
21
|
-
Attributes:
|
|
22
|
-
id: The folder's name, which a model asks for it by.
|
|
23
|
-
name: What it is called.
|
|
24
|
-
description: One line that says what it covers and when to read it.
|
|
25
|
-
body: The guide, in Markdown, with examples in ``cypher`` blocks.
|
|
26
|
-
"""
|
|
27
|
-
|
|
28
|
-
id: str
|
|
29
|
-
name: str
|
|
30
|
-
description: str
|
|
31
|
-
body: str
|
|
32
|
-
|
|
33
|
-
@property
|
|
34
|
-
def text(self) -> str:
|
|
35
|
-
"""What a model is given when it reads the skill."""
|
|
36
|
-
return f"# {self.name}\n\n{self.body.strip()}"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
@cache
|
|
40
|
-
def skills() -> dict[str, Skill]:
|
|
41
|
-
"""Every skill that ships with the package, by id, in id order."""
|
|
42
|
-
return load(resources.files(__package__))
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
def load(directory: Traversable) -> dict[str, Skill]:
|
|
46
|
-
"""The skills in the folders of ``directory`` that have a ``skill.md``, by id, sorted.
|
|
47
|
-
|
|
48
|
-
Raises:
|
|
49
|
-
ValueError: If a ``skill.md`` has no front matter, or no ``name`` or ``description``,
|
|
50
|
-
or a description of more than one line.
|
|
51
|
-
"""
|
|
52
|
-
found = {}
|
|
53
|
-
for folder in sorted(directory.iterdir(), key=lambda entry: entry.name):
|
|
54
|
-
guide = folder / "skill.md"
|
|
55
|
-
if folder.is_dir() and guide.is_file():
|
|
56
|
-
found[folder.name] = _parse(folder.name, guide.read_text(encoding="utf-8"))
|
|
57
|
-
return found
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
def _parse(skill_id: str, text: str) -> Skill:
|
|
61
|
-
parts = _FRONT_MATTER.match(text)
|
|
62
|
-
if parts is None:
|
|
63
|
-
raise ValueError(f"The skill {skill_id!r} has no front matter")
|
|
64
|
-
fields = dict(line.split(":", 1) for line in parts[1].splitlines() if ":" in line)
|
|
65
|
-
name = fields.get("name", "").strip()
|
|
66
|
-
description = fields.get("description", "").strip()
|
|
67
|
-
if not name or not description:
|
|
68
|
-
raise ValueError(f"The skill {skill_id!r} needs a name and a description")
|
|
69
|
-
return Skill(skill_id, name, description, parts[2].strip())
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|