Natural-language queries on any backend (Text2Query)
Optional module
Install: as Natural-language queries (Text2Cypher) (
[graphrag]only onNeo4jGraph).Import:
from cvcdocdb import Text2Query
Text2Query picks the translator from the
backend, so the same script works on every backend:
Backend |
Translator |
|
|---|---|---|
|
|
|
|
|
from cvcdocdb import Text2Query, Text2QueryError
t2q = Text2Query(graph, llm=my_llm)
try:
result = t2q.query("Quantes pàgines té el document D1?")
print(result.language, result.query, result.records)
except Text2QueryError as exc: # base of Text2CypherError / Text2SPARQLError
print("Could not answer:", exc)
API
One natural-language query API for every backend.
Text2Query picks the right translator from the backend:
Text2SPARQL on a SPARQL backend
(JenaGraph) and
Text2Cypher on every other one
(NetworkXGraph, Neo4jGraph, MemgraphGraph):
from cvcdocdb import Text2Query
t2q = Text2Query(graph, llm=my_llm)
result = t2q.query("Quantes pàgines té el document D1?")
result.language # "sparql" or "cypher"
result.query # the generated query (already executed)
result.records # [{'c': 2}]
Errors are Text2QueryError (the base of Text2CypherError and
Text2SPARQLError).
- class cvcdocdb.text2query.Text2Query(graph, llm, *, schema=None, examples=None, custom_prompt=None, database=None)[source]
Ask natural-language questions to any cvcdocdb graph.
- Parameters:
graph (Any) – Any cvcdocdb backend.
llm (Any) – The LLM handle (see
Text2Cypher).schema (Optional[str]) – Schema text for the prompt; introspected when omitted.
examples (Optional[List[str]]) – Optional example question/query pairs for the prompt.
custom_prompt (Optional[str]) – Optional prompt template with
{schema},{examples}and{query_text}placeholders.database (Optional[str]) – Neo4j only — database to query; defaults to the graph’s.
- language
"sparql"or"cypher".
- translator
The underlying
Text2SPARQLorText2Cypher.
- schema
The schema text shown to the LLM.
- Raises:
TypeError – As the translators, or if database is given for a SPARQL backend.
- Parameters:
- query(question)[source]
Translate question with the LLM, run it, return the rows.
- Raises:
Text2QueryError – If the generated query is invalid or not read-only (nothing is executed in that case).
- Parameters:
question (str)
- Return type: