text2cypher 1.0.0__tar.gz → 1.2.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 (46) hide show
  1. {text2cypher-1.0.0 → text2cypher-1.2.0}/PKG-INFO +6 -3
  2. {text2cypher-1.0.0 → text2cypher-1.2.0}/README.md +5 -2
  3. {text2cypher-1.0.0 → text2cypher-1.2.0}/pyproject.toml +2 -1
  4. {text2cypher-1.0.0 → text2cypher-1.2.0}/pyproject.toml.orig +2 -1
  5. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/__init__.py +15 -2
  6. text2cypher-1.2.0/src/text2cypher/_config.py +98 -0
  7. text2cypher-1.2.0/src/text2cypher/_errors.py +9 -0
  8. text2cypher-1.2.0/src/text2cypher/_examples.py +90 -0
  9. text2cypher-1.2.0/src/text2cypher/_execution.py +59 -0
  10. text2cypher-1.2.0/src/text2cypher/_generation/__init__.py +14 -0
  11. text2cypher-1.2.0/src/text2cypher/_generation/conversation.py +100 -0
  12. text2cypher-1.2.0/src/text2cypher/_generation/generate.py +51 -0
  13. text2cypher-1.2.0/src/text2cypher/_generation/header.py +69 -0
  14. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_generation/problems.py +34 -14
  15. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_generation/prompts.py +72 -31
  16. text2cypher-1.2.0/src/text2cypher/_generation/typos.py +81 -0
  17. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_pipeline.py +40 -30
  18. text2cypher-1.2.0/src/text2cypher/_results.py +173 -0
  19. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_schema_source.py +44 -5
  20. text2cypher-1.2.0/src/text2cypher/_workflow.py +195 -0
  21. text2cypher-1.2.0/src/text2cypher/llm/__init__.py +20 -0
  22. text2cypher-1.2.0/src/text2cypher/llm/_base.py +76 -0
  23. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/llm/_fake.py +16 -6
  24. text2cypher-1.2.0/src/text2cypher/llm/_openai.py +86 -0
  25. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/_filter.py +3 -0
  26. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/_from_snapshot.py +15 -1
  27. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/_model.py +12 -1
  28. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/_render.py +20 -5
  29. text2cypher-1.0.0/src/text2cypher/_config.py +0 -62
  30. text2cypher-1.0.0/src/text2cypher/_errors.py +0 -5
  31. text2cypher-1.0.0/src/text2cypher/_execution.py +0 -25
  32. text2cypher-1.0.0/src/text2cypher/_generation/__init__.py +0 -8
  33. text2cypher-1.0.0/src/text2cypher/_generation/generate.py +0 -51
  34. text2cypher-1.0.0/src/text2cypher/_results.py +0 -91
  35. text2cypher-1.0.0/src/text2cypher/_workflow.py +0 -99
  36. text2cypher-1.0.0/src/text2cypher/llm/__init__.py +0 -5
  37. text2cypher-1.0.0/src/text2cypher/llm/_base.py +0 -43
  38. text2cypher-1.0.0/src/text2cypher/llm/_openai.py +0 -59
  39. {text2cypher-1.0.0 → text2cypher-1.2.0}/LICENSE +0 -0
  40. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_generation/extract.py +0 -0
  41. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_validation/__init__.py +0 -0
  42. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_validation/issues.py +0 -0
  43. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/_validation/validator.py +0 -0
  44. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/py.typed +0 -0
  45. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/__init__.py +0 -0
  46. {text2cypher-1.0.0 → text2cypher-1.2.0}/src/text2cypher/schema/_stopwords.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: text2cypher
3
- Version: 1.0.0
3
+ Version: 1.2.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
@@ -46,8 +46,10 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
46
46
  * **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
47
  * **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
48
  * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out), with every attempt, its issues, the schema it used and its token usage.
49
- * **Optional execution**: run the final query read-only, with a timeout, and get the rows.
50
- * **Bring your own LLM**: a one-method protocol, with an OpenAI client included. Async throughout.
49
+ * **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.
50
+ * **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
+ * **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
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
51
53
 
52
54
  ## Installation
53
55
 
@@ -101,6 +103,7 @@ The full documentation is at **[text2cypher.readthedocs.io](https://text2cypher.
101
103
  * [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html): the result, the configuration, running the query, errors
102
104
  * [How it works](https://text2cypher.readthedocs.io/en/latest/how-it-works.html): the loop, the escalation and what it costs
103
105
  * [The schema and its filter](https://text2cypher.readthedocs.io/en/latest/schema.html): what the LLM is shown, your own filter, keeping the schema between runs
106
+ * [When a question fails](https://text2cypher.readthedocs.io/en/latest/troubleshooting.html): what to look at, and what to try, for each outcome
104
107
  * [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html): your own client, other OpenAI-compatible models, `FakeLLM` for tests
105
108
  * [What is and is not checked](https://text2cypher.readthedocs.io/en/latest/checks.html) and the [API reference](https://text2cypher.readthedocs.io/en/latest/reference.html)
106
109
 
@@ -14,8 +14,10 @@ text2cypher asks an LLM to write the query, checks it against the real graph wit
14
14
  * **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
15
  * **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
16
  * **Honest outcomes**: `valid`, `unanswerable` (the LLM declined) or `failed` (the corrections ran out), with every attempt, its issues, the schema it used and its token usage.
17
- * **Optional execution**: run the final query read-only, with a timeout, and get the rows.
18
- * **Bring your own LLM**: a one-method protocol, with an OpenAI client included. Async throughout.
17
+ * **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.
18
+ * **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
+ * **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
+ * **Bring your own LLM**: a small protocol, `chat` (the conversation as turns) or just `complete`, with an OpenAI client included. Async throughout.
19
21
 
20
22
  ## Installation
21
23
 
@@ -69,6 +71,7 @@ The full documentation is at **[text2cypher.readthedocs.io](https://text2cypher.
69
71
  * [Using text2cypher](https://text2cypher.readthedocs.io/en/latest/usage.html): the result, the configuration, running the query, errors
70
72
  * [How it works](https://text2cypher.readthedocs.io/en/latest/how-it-works.html): the loop, the escalation and what it costs
71
73
  * [The schema and its filter](https://text2cypher.readthedocs.io/en/latest/schema.html): what the LLM is shown, your own filter, keeping the schema between runs
74
+ * [When a question fails](https://text2cypher.readthedocs.io/en/latest/troubleshooting.html): what to look at, and what to try, for each outcome
72
75
  * [LLM clients](https://text2cypher.readthedocs.io/en/latest/llm.html): your own client, other OpenAI-compatible models, `FakeLLM` for tests
73
76
  * [What is and is not checked](https://text2cypher.readthedocs.io/en/latest/checks.html) and the [API reference](https://text2cypher.readthedocs.io/en/latest/reference.html)
74
77
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.0.0"
3
+ version = "1.2.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"
@@ -116,6 +116,7 @@ layers = [
116
116
  "text2cypher._pipeline",
117
117
  "text2cypher._workflow",
118
118
  "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
119
+ "text2cypher._examples",
119
120
  "text2cypher._results",
120
121
  "text2cypher._validation",
121
122
  "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "text2cypher"
3
- version = "1.0.0"
3
+ version = "1.2.0"
4
4
  description = "text2cypher: Generate validated Cypher queries from natural language text with LLMs"
5
5
  readme = "README.md"
6
6
  authors = [
@@ -94,6 +94,7 @@ layers = [
94
94
  "text2cypher._pipeline",
95
95
  "text2cypher._workflow",
96
96
  "text2cypher._generation | text2cypher._execution | text2cypher._schema_source",
97
+ "text2cypher._examples",
97
98
  "text2cypher._results",
98
99
  "text2cypher._validation",
99
100
  "text2cypher.llm | text2cypher.schema | text2cypher._config | text2cypher._errors",
@@ -8,14 +8,22 @@ change without notice.
8
8
  from importlib.metadata import PackageNotFoundError, version
9
9
 
10
10
  from text2cypher._config import Config
11
- from text2cypher._errors import GraphNotFoundError
11
+ from text2cypher._errors import GraphNotFoundError, Text2CypherError
12
12
  from text2cypher._pipeline import Text2Cypher
13
- from text2cypher._results import Attempt, Records, Result
13
+ from text2cypher._results import (
14
+ Attempt,
15
+ DatabaseError,
16
+ LLMError,
17
+ Records,
18
+ Result,
19
+ )
14
20
  from text2cypher._validation import Issue, ValidationResult
15
21
  from text2cypher.llm import (
22
+ AsyncChatClient,
16
23
  AsyncLLMClient,
17
24
  Completion,
18
25
  FakeLLM,
26
+ Message,
19
27
  OpenAIClient,
20
28
  Usage,
21
29
  )
@@ -27,19 +35,24 @@ except PackageNotFoundError: # running from a source tree that is not installed
27
35
  __version__ = "0+unknown"
28
36
 
29
37
  __all__ = [
38
+ "AsyncChatClient",
30
39
  "AsyncLLMClient",
31
40
  "Attempt",
32
41
  "Completion",
33
42
  "Config",
43
+ "DatabaseError",
34
44
  "FakeLLM",
35
45
  "GraphNotFoundError",
36
46
  "GraphSchema",
37
47
  "Issue",
48
+ "LLMError",
49
+ "Message",
38
50
  "OpenAIClient",
39
51
  "Records",
40
52
  "Result",
41
53
  "SchemaFilter",
42
54
  "Text2Cypher",
55
+ "Text2CypherError",
43
56
  "Usage",
44
57
  "ValidationResult",
45
58
  "__version__",
@@ -0,0 +1,98 @@
1
+ """The limits of the correction loop."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(frozen=True, slots=True)
7
+ class Config:
8
+ """How many times a query may be corrected, and whether the result is executed.
9
+
10
+ The first query is not a correction. ``attempts_w_filtered`` corrections are made
11
+ with the filtered schema; the rest, up to ``total_attempts``, with the full one.
12
+
13
+ With ``execute``, a query that passed validation is run (read-only) and its rows
14
+ are on the result. If FalkorDB rejects or fails it (a type error on a value, a
15
+ division by zero), that error is sent back for a correction, which counts like any
16
+ other, and the result is ``failed`` when the corrections run out. Generated queries
17
+ can be expensive, so a run is stopped after ``execute_timeout_ms`` milliseconds;
18
+ ``None`` lets it run without limit. A timeout or a lost connection ends the run with
19
+ the valid query and the error, because it says nothing about the query.
20
+
21
+ Two optional checks report more than the validators do by default. ``check_types``
22
+ (on) reports a property compared with a value of another type, and ``sum``, ``avg`` and
23
+ the like of a property that holds no numbers: such a query fails or returns nothing.
24
+ ``check_performance`` (off) reports a cartesian product, a scan of every node and a path
25
+ with no upper bound; each can be what the question needs (a shortest path between two
26
+ nodes is a cartesian product by design). Every issue a check reports is corrected like
27
+ any other.
28
+
29
+ By default the LLM writes the values of a query inside it. With ``use_parameters`` it
30
+ puts them in a ``CYPHER`` header before the query (``CYPHER name='Ann' MATCH (p
31
+ {name: $name}) ...``) and uses them as parameters, which FalkorDB can plan once and
32
+ reuse. The query stays one string: ``Result.query`` runs as it is. FalkorDB wants the
33
+ pairs separated by spaces and a ``CYPHER`` in front, so a header with commas, or
34
+ without it, is written that way without asking the LLM again (that changes nothing about
35
+ what the query means) and the query is validated again.
36
+
37
+ With ``autofix_typos``, a label, relationship type or property that the validators
38
+ report as unknown is first replaced, without the LLM, by the one name of the graph it
39
+ is a likely typo of (``Persn`` for ``Person``), and the query is validated again. If it
40
+ passes, that is the result and no LLM call and no correction was spent. If it does
41
+ not, the LLM gets the query it wrote, as usual. Off by default: a fix can make a query
42
+ valid and still not what the question meant.
43
+
44
+ The schema shows up to ``example_values`` values of each property (``title: STRING (e.g.
45
+ 'Alien', 'Heat')``), so the LLM writes a value the way the graph does: spelling, case,
46
+ format. They are read from the graph, one small query per property, and are **data from
47
+ your graph that goes to the LLM provider**: pass ``0`` to send none. They are kept while the
48
+ structure of the graph is the same, so a graph pays for the queries once, not on every run.
49
+
50
+ The schema is read from the graph on every run by default. With
51
+ ``schema_refresh_seconds`` it is kept: a run that comes after that many seconds first
52
+ checks whether the graph changed (a few cheap queries) and reads the schema again only
53
+ if it did. ``0`` checks on every run. Between checks a graph that changed is not seen
54
+ in the prompt, but a query that uses a new name is still validated against the graph.
55
+
56
+ Attributes:
57
+ attempts_w_filtered: Corrections made with the filtered schema.
58
+ total_attempts: Corrections in all, with the filtered and the full schema. The
59
+ first query is not a correction.
60
+ execute: Run a query that is valid, read-only, correct it if FalkorDB fails it, and
61
+ put the rows on the result.
62
+ execute_timeout_ms: Stop an execution after this many milliseconds, or never
63
+ if ``None``.
64
+ use_parameters: Ask the LLM for the values in a ``CYPHER`` header and parameters.
65
+ check_types: Report type mismatches of properties.
66
+ check_performance: Report queries that may be expensive, which is off by default.
67
+ example_values: How many example values of each property to show the LLM; ``0``
68
+ sends none.
69
+ autofix_typos: Fix a misspelled name in a query without the LLM when exactly one
70
+ name of the graph is a likely typo of it.
71
+ schema_refresh_seconds: Keep the schema of a graph and check it for changes at
72
+ most this often, or read it on every run if ``None``.
73
+ """
74
+
75
+ attempts_w_filtered: int = 5
76
+ total_attempts: int = 10
77
+ execute: bool = False
78
+ execute_timeout_ms: int | None = 10_000
79
+ schema_refresh_seconds: float | None = None
80
+ use_parameters: bool = False
81
+ check_types: bool = True
82
+ check_performance: bool = False
83
+ example_values: int = 3
84
+ autofix_typos: bool = False
85
+
86
+ def __post_init__(self) -> None:
87
+ if self.attempts_w_filtered < 0:
88
+ raise ValueError("attempts_w_filtered must be 0 or more")
89
+ if self.total_attempts < 0:
90
+ raise ValueError("total_attempts must be 0 or more")
91
+ if self.total_attempts < self.attempts_w_filtered:
92
+ raise ValueError("total_attempts must be at least attempts_w_filtered")
93
+ if self.execute_timeout_ms is not None and self.execute_timeout_ms <= 0:
94
+ raise ValueError("execute_timeout_ms must be positive")
95
+ if self.example_values < 0:
96
+ raise ValueError("example_values must be 0 or more")
97
+ if self.schema_refresh_seconds is not None and self.schema_refresh_seconds < 0:
98
+ raise ValueError("schema_refresh_seconds must be 0 or more")
@@ -0,0 +1,9 @@
1
+ """The errors the library raises itself."""
2
+
3
+
4
+ class Text2CypherError(Exception):
5
+ """The base of the errors text2cypher raises itself, so one ``except`` catches them all."""
6
+
7
+
8
+ class GraphNotFoundError(Text2CypherError, ValueError):
9
+ """The graph does not exist, or has no labelled nodes or relationships to query."""
@@ -0,0 +1,90 @@
1
+ """A few example values of each property, to show the LLM how values are written."""
2
+
3
+ import asyncio
4
+ from collections.abc import Mapping
5
+
6
+ from falkordb.asyncio import FalkorDB
7
+ from falkordb.asyncio.graph import AsyncGraph
8
+ from redis.exceptions import RedisError
9
+
10
+ from text2cypher.schema import GraphSchema
11
+ from text2cypher.schema._model import quote_identifier
12
+
13
+ type Examples = dict[str, dict[str, tuple[str, ...]]]
14
+
15
+ # Only values that read as plain text in a prompt; lists, maps, points and vectors do not
16
+ _SCALARS = {"String", "Integer", "Float", "Boolean"}
17
+ # The first non-null values read per property, of which the distinct ones are the
18
+ # examples: a read that stops after a few rows, where DISTINCT would read every one
19
+ _ROWS = 20
20
+ _LONGEST = 40
21
+ # A property that is slow to sample has no examples: they are a help, not a need
22
+ _TIMEOUT_MS = 2_000
23
+ _MAX_CONCURRENCY = 8
24
+
25
+
26
+ async def sample_examples(
27
+ client: FalkorDB, graph: str, schema: GraphSchema, count: int
28
+ ) -> tuple[Examples, Examples]:
29
+ """Up to ``count`` example values of each scalar property of ``schema``: of the
30
+ labels, then of the relationship types. A query that fails gives no examples.
31
+
32
+ Each is one read-only query that stops after a few rows, with a timeout.
33
+ """
34
+ handle = client.select_graph(graph)
35
+ gate = asyncio.Semaphore(_MAX_CONCURRENCY)
36
+
37
+ async def sample(query: str) -> tuple[str, ...]:
38
+ async with gate:
39
+ return await _first_values(handle, query, count)
40
+
41
+ jobs = {
42
+ (kind, entity, prop): sample(_query(kind, entity, prop))
43
+ for kind, entities in (
44
+ ("node", schema.node_properties),
45
+ ("relationship", schema.relationship_properties),
46
+ )
47
+ for entity, properties in entities.items()
48
+ for prop, types in properties.items()
49
+ if set(types) <= _SCALARS
50
+ }
51
+ found = dict(zip(jobs, await asyncio.gather(*jobs.values()), strict=True))
52
+ return (
53
+ _group(found, "node"),
54
+ _group(found, "relationship"),
55
+ )
56
+
57
+
58
+ def _query(kind: str, entity: str, prop: str) -> str:
59
+ name, key = quote_identifier(entity), quote_identifier(prop)
60
+ pattern = f"(e:{name})" if kind == "node" else f"()-[e:{name}]->()"
61
+ return f"MATCH {pattern} WHERE e.{key} IS NOT NULL RETURN e.{key} LIMIT {_ROWS}"
62
+
63
+
64
+ async def _first_values(graph: AsyncGraph, query: str, count: int) -> tuple[str, ...]:
65
+ try:
66
+ result = await graph.ro_query(query, timeout=_TIMEOUT_MS)
67
+ except RedisError:
68
+ return ()
69
+ distinct = dict.fromkeys(_literal(row[0]) for row in result.result_set)
70
+ return tuple(distinct)[:count]
71
+
72
+
73
+ def _group(
74
+ found: Mapping[tuple[str, str, str], tuple[str, ...]], kind: str
75
+ ) -> Examples:
76
+ grouped: Examples = {}
77
+ for (found_kind, entity, prop), values in found.items():
78
+ if found_kind == kind and values:
79
+ grouped.setdefault(entity, {})[prop] = values
80
+ return grouped
81
+
82
+
83
+ def _literal(value: object) -> str:
84
+ """``value`` as it is written in a query; a long string is cut short."""
85
+ if isinstance(value, bool):
86
+ return "true" if value else "false"
87
+ if not isinstance(value, str):
88
+ return str(value)
89
+ text = value.replace("\\", "\\\\").replace("'", "\\'").replace("\n", "\\n")
90
+ return f"'{text[:_LONGEST]}…'" if len(text) > _LONGEST else f"'{text}'"
@@ -0,0 +1,59 @@
1
+ """Run a query that passed validation, read-only."""
2
+
3
+ from dataclasses import dataclass
4
+
5
+ from falkordb.asyncio.graph import AsyncGraph
6
+ from redis.exceptions import RedisError, ResponseError
7
+
8
+ from text2cypher._results import Records
9
+
10
+
11
+ @dataclass(frozen=True, slots=True)
12
+ class Execution:
13
+ """How running a query went: the rows it returned, or the error FalkorDB gave.
14
+
15
+ ``correctable`` says whether another query might not fail: FalkorDB rejected or
16
+ failed this one. A timeout, or a connection that is lost, says nothing about the query.
17
+ """
18
+
19
+ records: Records | None = None
20
+ error: str | None = None
21
+ correctable: bool = False
22
+
23
+
24
+ async def execute_cypher(
25
+ graph: AsyncGraph, query: str, *, timeout_ms: int | None = None
26
+ ) -> Records:
27
+ """The rows ``query`` returns from ``graph``.
28
+
29
+ It runs as a read-only query, which FalkorDB rejects if it could write. Values
30
+ are the client's: nodes, relationships and paths stay ``falkordb`` objects.
31
+
32
+ Raises:
33
+ redis.exceptions.RedisError: If FalkorDB rejects or fails the query (a
34
+ ``ResponseError``, also when it runs longer than ``timeout_ms``) or cannot be
35
+ reached.
36
+ """
37
+ result = await graph.ro_query(query, timeout=timeout_ms)
38
+ return Records(
39
+ columns=tuple(name for _, name in result.header),
40
+ rows=tuple(tuple(row) for row in result.result_set),
41
+ )
42
+
43
+
44
+ async def run_query(
45
+ graph: AsyncGraph, query: str, *, timeout_ms: int | None = None
46
+ ) -> Execution:
47
+ """``execute_cypher``, with an error from FalkorDB or the connection as a value.
48
+
49
+ Any other error is a bug and propagates.
50
+ """
51
+ try:
52
+ records = await execute_cypher(graph, query, timeout_ms=timeout_ms)
53
+ except RedisError as error:
54
+ return Execution(error=str(error), correctable=_is_the_querys_fault(error))
55
+ return Execution(records=records)
56
+
57
+
58
+ def _is_the_querys_fault(error: RedisError) -> bool:
59
+ return isinstance(error, ResponseError) and "timed out" not in str(error).lower()
@@ -0,0 +1,14 @@
1
+ from text2cypher._generation.conversation import Round
2
+ from text2cypher._generation.extract import extract_cypher
3
+ from text2cypher._generation.generate import Generation, generate_cypher
4
+ from text2cypher._generation.header import repair_header
5
+ from text2cypher._generation.typos import fix_typos
6
+
7
+ __all__ = [
8
+ "Generation",
9
+ "Round",
10
+ "extract_cypher",
11
+ "fix_typos",
12
+ "generate_cypher",
13
+ "repair_header",
14
+ ]
@@ -0,0 +1,100 @@
1
+ """The conversation with the LLM: the question, then each query it wrote and what was wrong."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+
6
+ from text2cypher._generation.problems import problems
7
+ from text2cypher._generation.prompts import generator_user
8
+ from text2cypher._validation import Issue
9
+ from text2cypher.llm import Message
10
+ from text2cypher.schema import GraphSchema
11
+
12
+ _REPLY = (
13
+ "Reply with the query in one ```cypher code block and nothing else. "
14
+ "If the question cannot be answered with this schema, reply with an empty code block."
15
+ )
16
+ CLOSING = f"Write a corrected query that fixes the problems and keeps what already works. {_REPLY}"
17
+ _CLOSING_AFTER_ERROR = (
18
+ f"Write a corrected query that fixes this and keeps what already works. {_REPLY}"
19
+ )
20
+ SCHEMA_NOTE = (
21
+ "The schema in the system message now lists the whole graph; before, it showed "
22
+ "only part of it."
23
+ )
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Round:
28
+ """A query the LLM wrote that has to be corrected, and what was wrong with it.
29
+
30
+ That is its ``issues``, or the ``execution_error`` FalkorDB gave when it ran a query
31
+ that had passed validation.
32
+
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.
35
+ """
36
+
37
+ query: str
38
+ issues: tuple[Issue, ...]
39
+ execution_error: str | None = None
40
+ schema_note: bool = False
41
+
42
+
43
+ def chat_messages(
44
+ question: str,
45
+ rounds: Sequence[Round],
46
+ schema: GraphSchema,
47
+ *,
48
+ parameterize: bool = False,
49
+ ) -> list[Message]:
50
+ """The conversation as turns: the question, then for each round the query the LLM
51
+ wrote and a user turn with its problems. The problems are worded with ``schema``,
52
+ the one the next query is written for."""
53
+ messages = [Message("user", generator_user(question))]
54
+ for round_ in rounds:
55
+ note = f"{SCHEMA_NOTE}\n\n" if round_.schema_note else ""
56
+ messages.append(Message("assistant", _fenced(round_.query)))
57
+ closing = CLOSING if round_.execution_error is None else _CLOSING_AFTER_ERROR
58
+ messages.append(
59
+ Message(
60
+ "user",
61
+ f"{note}{_feedback(round_, schema, parameterize)}\n\n{closing}",
62
+ )
63
+ )
64
+ return messages
65
+
66
+
67
+ def folded_message(
68
+ question: str,
69
+ rounds: Sequence[Round],
70
+ schema: GraphSchema,
71
+ *,
72
+ parameterize: bool = False,
73
+ ) -> str:
74
+ """The same conversation as one user message, for a client that cannot be given turns."""
75
+ if not rounds:
76
+ return generator_user(question)
77
+ note = f"{SCHEMA_NOTE}\n\n" if any(r.schema_note for r in rounds) else ""
78
+ attempts = "\n\n".join(
79
+ f"Attempt {number}\n{_fenced(r.query)}\n{_feedback(r, schema, parameterize)}"
80
+ for number, r in enumerate(rounds, start=1)
81
+ )
82
+ return (
83
+ f"{generator_user(question)}\n\n{note}Earlier attempts, oldest first:\n\n"
84
+ f"{attempts}\n\n{CLOSING}"
85
+ )
86
+
87
+
88
+ def _fenced(query: str) -> str:
89
+ return f"```cypher\n{query}\n```"
90
+
91
+
92
+ def _feedback(round_: Round, schema: GraphSchema, parameterize: bool) -> str:
93
+ if round_.execution_error is not None:
94
+ return (
95
+ "FalkorDB accepted this query but it failed when it ran:\n\n"
96
+ f"{round_.execution_error}"
97
+ )
98
+ return "This query has problems:\n\n" + problems(
99
+ round_.issues, schema, parameterized=parameterize
100
+ )
@@ -0,0 +1,51 @@
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 generator_system
14
+ from text2cypher.llm import AsyncChatClient, AsyncLLMClient, Completion, Usage
15
+ from text2cypher.schema import GraphSchema
16
+
17
+
18
+ @dataclass(frozen=True, slots=True)
19
+ class Generation:
20
+ """A query an LLM wrote, empty if it declined, and the tokens that cost."""
21
+
22
+ query: str
23
+ usage: Usage | None
24
+
25
+
26
+ async def generate_cypher(
27
+ llm: AsyncChatClient | AsyncLLMClient,
28
+ schema: GraphSchema,
29
+ question: str,
30
+ rounds: Sequence[Round] = (),
31
+ *,
32
+ parameterize: bool = False,
33
+ ) -> Generation:
34
+ """A query for ``question`` over ``schema``; empty if the LLM says it has none.
35
+
36
+ ``rounds`` are the queries it wrote before that had to be corrected, oldest first.
37
+ Each correction uses the same system prompt as the first query. A client that has
38
+ ``chat`` is given the conversation as turns; one with only ``complete`` is given it
39
+ as one message.
40
+ """
41
+ system = generator_system(schema, parameterize=parameterize)
42
+ chat = getattr(llm, "chat", None)
43
+ if callable(chat):
44
+ completion: Completion = await chat(
45
+ system, chat_messages(question, rounds, schema, parameterize=parameterize)
46
+ )
47
+ else:
48
+ completion = await cast("AsyncLLMClient", llm).complete(
49
+ system, folded_message(question, rounds, schema, parameterize=parameterize)
50
+ )
51
+ return Generation(extract_cypher(completion.text), completion.usage)
@@ -0,0 +1,69 @@
1
+ """Repair the ``CYPHER`` header of a query that uses parameters."""
2
+
3
+ import re
4
+
5
+ _KEYWORD = re.compile(r"cypher(?!\w)", re.IGNORECASE)
6
+ _PAIR = re.compile(r"\s*([A-Za-z_]\w*)\s*=\s*")
7
+ _WORD = re.compile(r"[^\s,]+")
8
+
9
+
10
+ def repair_header(query: str) -> str | None:
11
+ """``query`` with its parameter header in the form FalkorDB accepts, or ``None``.
12
+
13
+ FalkorDB wants ``CYPHER`` and then the pairs separated by spaces, not commas, so
14
+ ``name='Ann', year=1990 MATCH ...`` is a syntax error, and so is a header without
15
+ ``CYPHER``. This adds a missing ``CYPHER`` and writes the pairs with one space between.
16
+ A query with no header, or one whose values cannot be read to their end, gives ``None``,
17
+ and so does one that is already written like that.
18
+ """
19
+ text = query.strip()
20
+ keyword = _KEYWORD.match(text)
21
+ rest = text[keyword.end() :] if keyword else text
22
+ pairs: list[str] = []
23
+ position = 0
24
+ while found := _PAIR.match(rest, position):
25
+ end = _value_end(rest, found.end())
26
+ if end is None:
27
+ return None
28
+ pairs.append(f"{found[1]}={rest[found.end() : end]}")
29
+ position = end
30
+ while position < len(rest) and (
31
+ rest[position].isspace() or rest[position] == ","
32
+ ):
33
+ position += 1
34
+ if not pairs:
35
+ return None
36
+ repaired = f"CYPHER {' '.join(pairs)} {rest[position:]}".rstrip()
37
+ return None if repaired == text else repaired
38
+
39
+
40
+ def _value_end(text: str, start: int) -> int | None:
41
+ """Where the value that begins at ``start`` ends: a string, a list, a map or a word."""
42
+ if start >= len(text):
43
+ return None
44
+ if text[start] in "'\"[{(":
45
+ return _closing(text, start)
46
+ word = _WORD.match(text, start)
47
+ return word.end() if word else None
48
+
49
+
50
+ def _closing(text: str, start: int) -> int | None:
51
+ """The end of the string or bracketed value that begins at ``start``, or ``None``."""
52
+ depth, quote, i = 0, None, start
53
+ while i < len(text):
54
+ char = text[i]
55
+ if quote and char == "\\":
56
+ i += 2
57
+ continue
58
+ if quote:
59
+ quote = None if char == quote else quote
60
+ elif char in "'\"":
61
+ quote = char
62
+ elif char in "[{(":
63
+ depth += 1
64
+ elif char in "]})":
65
+ depth -= 1
66
+ i += 1
67
+ if quote is None and depth == 0:
68
+ return i
69
+ return None