prograph 1.3.3__py3-none-any.whl

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 (237) hide show
  1. prograph/__init__.py +36 -0
  2. prograph/__main__.py +5 -0
  3. prograph/_version.py +375 -0
  4. prograph/cli/__init__.py +1 -0
  5. prograph/cli/_iri_utils.py +124 -0
  6. prograph/cli/emit_genie_space.py +107 -0
  7. prograph/cli/generate_views.py +140 -0
  8. prograph/cli/main.py +420 -0
  9. prograph/cli/schema_inferrer.py +746 -0
  10. prograph/cli/ttl_loader.py +289 -0
  11. prograph/cli/upload_genie_space.py +84 -0
  12. prograph/config/__init__.py +27 -0
  13. prograph/config/yaml_config.py +848 -0
  14. prograph/demos/__init__.py +14 -0
  15. prograph/demos/turbofan/README.md +74 -0
  16. prograph/demos/turbofan/SCENARIO.md +209 -0
  17. prograph/demos/turbofan/__init__.py +75 -0
  18. prograph/demos/turbofan/create_tables.sql +206 -0
  19. prograph/demos/turbofan/data/engine-instances.ttl +1123 -0
  20. prograph/demos/turbofan/data/sensor-timeseries.csv +90 -0
  21. prograph/demos/turbofan/demo.py +162 -0
  22. prograph/demos/turbofan/genie_qa_notebook.py +434 -0
  23. prograph/demos/turbofan/graph.yaml +1098 -0
  24. prograph/demos/turbofan/instance_graph_demo.py +32 -0
  25. prograph/demos/turbofan/load.py +223 -0
  26. prograph/demos/turbofan/mapping.r2rml.ttl +991 -0
  27. prograph/demos/turbofan/ontology/engine-maintenance.ttl +606 -0
  28. prograph/demos/turbofan/payload-shapes.ttl +33 -0
  29. prograph/demos/turbofan/queries/example-queries.sparql +215 -0
  30. prograph/demos/turbofan/shapes.ttl +75 -0
  31. prograph/demos/turbofan/tables.py +106 -0
  32. prograph/demos/turbofan/turbofan_schema.py +393 -0
  33. prograph/demos/turbofan/validation_demo.py +153 -0
  34. prograph/describe.py +231 -0
  35. prograph/endpoint/__init__.py +12 -0
  36. prograph/endpoint/app.py +722 -0
  37. prograph/endpoint/cli.py +280 -0
  38. prograph/endpoint/credentials.py +240 -0
  39. prograph/endpoint/engines.py +418 -0
  40. prograph/endpoint/negotiate.py +101 -0
  41. prograph/endpoint/results.py +181 -0
  42. prograph/endpoint/service.py +31 -0
  43. prograph/engine.py +2718 -0
  44. prograph/execution.py +455 -0
  45. prograph/executors/__init__.py +6 -0
  46. prograph/executors/base.py +11 -0
  47. prograph/executors/databricks_sql_executor.py +51 -0
  48. prograph/executors/duckdb_executor.py +24 -0
  49. prograph/executors/mysql_executor.py +20 -0
  50. prograph/executors/oracle_executor.py +24 -0
  51. prograph/executors/pandas_executor.py +72 -0
  52. prograph/executors/postgresql_executor.py +35 -0
  53. prograph/executors/spark_executor.py +88 -0
  54. prograph/executors/sqlserver_executor.py +35 -0
  55. prograph/extras/__init__.py +1 -0
  56. prograph/extras/graphql/__init__.py +33 -0
  57. prograph/extras/graphql/execute.py +25 -0
  58. prograph/extras/graphql/schema.py +314 -0
  59. prograph/extras/instance_graph.py +559 -0
  60. prograph/genie/__init__.py +83 -0
  61. prograph/genie/databricks_uploader.py +306 -0
  62. prograph/genie/deploy.py +393 -0
  63. prograph/genie/formats.py +414 -0
  64. prograph/genie/instruction_generator.py +375 -0
  65. prograph/genie/sample_query_generator.py +256 -0
  66. prograph/genie/shacl_views.py +318 -0
  67. prograph/genie/space_emitter.py +329 -0
  68. prograph/genie/view_generator.py +628 -0
  69. prograph/genie/view_writer.py +172 -0
  70. prograph/graph/__init__.py +1 -0
  71. prograph/graph/ansi_session.py +348 -0
  72. prograph/graph/databricks_sql_graph.py +300 -0
  73. prograph/graph/drivers.py +143 -0
  74. prograph/graph/duckdb_graph.py +68 -0
  75. prograph/graph/mysql_graph.py +38 -0
  76. prograph/graph/oracle_graph.py +285 -0
  77. prograph/graph/pandas_graph.py +343 -0
  78. prograph/graph/postgresql_graph.py +644 -0
  79. prograph/graph/spark_graph.py +556 -0
  80. prograph/graph/sql_graph.py +83 -0
  81. prograph/graph/sqlserver_graph.py +72 -0
  82. prograph/hints.py +95 -0
  83. prograph/logging.py +550 -0
  84. prograph/mcp/__init__.py +29 -0
  85. prograph/mcp/__main__.py +180 -0
  86. prograph/mcp/bootstrap.py +98 -0
  87. prograph/mcp/server.py +601 -0
  88. prograph/mcp/sparql.py +397 -0
  89. prograph/mcp/tools.py +504 -0
  90. prograph/nlp/__init__.py +79 -0
  91. prograph/nlp/client.py +305 -0
  92. prograph/nlp/databricks_tools.py +369 -0
  93. prograph/nlp/graph_context.py +313 -0
  94. prograph/nlp/interface.py +652 -0
  95. prograph/nlp/prompts/__init__.py +19 -0
  96. prograph/nlp/prompts/examples.py +258 -0
  97. prograph/nlp/prompts/system.py +239 -0
  98. prograph/nlp/providers/__init__.py +14 -0
  99. prograph/nlp/providers/anthropic.py +274 -0
  100. prograph/nlp/providers/databricks.py +312 -0
  101. prograph/nlp/providers/openai.py +203 -0
  102. prograph/nlp/schema_context.py +78 -0
  103. prograph/ontology/__init__.py +53 -0
  104. prograph/ontology/alignment.py +542 -0
  105. prograph/ontology/hierarchy.py +310 -0
  106. prograph/ontology/imports.py +587 -0
  107. prograph/ontology/layer.py +991 -0
  108. prograph/ontology/skos.py +61 -0
  109. prograph/owl/__init__.py +27 -0
  110. prograph/owl/defined_classes.py +323 -0
  111. prograph/parameters.py +242 -0
  112. prograph/parser/__init__.py +1 -0
  113. prograph/parser/cypher/CypherLexer.py +836 -0
  114. prograph/parser/cypher/CypherListener.py +966 -0
  115. prograph/parser/cypher/CypherParser.py +10854 -0
  116. prograph/parser/cypher/CypherVisitor.py +543 -0
  117. prograph/parser/cypher/__init__.py +1 -0
  118. prograph/parser/sparql/SparqlLexer.py +801 -0
  119. prograph/parser/sparql/SparqlParser.py +10146 -0
  120. prograph/parser/sparql/SparqlParserListener.py +1056 -0
  121. prograph/parser/sparql/SparqlParserVisitor.py +593 -0
  122. prograph/parser/sparql/__init__.py +8 -0
  123. prograph/plan/__init__.py +3 -0
  124. prograph/plan/ir/__init__.py +1 -0
  125. prograph/plan/ir/casts.py +338 -0
  126. prograph/plan/ir/consistency.py +397 -0
  127. prograph/plan/ir/construct.py +90 -0
  128. prograph/plan/ir/cost.py +234 -0
  129. prograph/plan/ir/cypher_answer.py +1081 -0
  130. prograph/plan/ir/cypher_apoc.py +717 -0
  131. prograph/plan/ir/cypher_apoc_convert.py +505 -0
  132. prograph/plan/ir/cypher_apoc_date.py +845 -0
  133. prograph/plan/ir/cypher_apoc_map.py +496 -0
  134. prograph/plan/ir/cypher_apoc_meta.py +384 -0
  135. prograph/plan/ir/cypher_apoc_path.py +597 -0
  136. prograph/plan/ir/cypher_apoc_procedures.py +163 -0
  137. prograph/plan/ir/cypher_apoc_text.py +785 -0
  138. prograph/plan/ir/cypher_front.py +5474 -0
  139. prograph/plan/ir/cypher_functions.py +565 -0
  140. prograph/plan/ir/cypher_lists.py +935 -0
  141. prograph/plan/ir/cypher_maps.py +370 -0
  142. prograph/plan/ir/cypher_mixed.py +604 -0
  143. prograph/plan/ir/cypher_ontology.py +226 -0
  144. prograph/plan/ir/cypher_procedures.py +191 -0
  145. prograph/plan/ir/cypher_runtime_errors.py +107 -0
  146. prograph/plan/ir/cypher_temporal.py +1357 -0
  147. prograph/plan/ir/cypher_temporal_arith.py +339 -0
  148. prograph/plan/ir/cypher_values.py +546 -0
  149. prograph/plan/ir/cypher_write.py +612 -0
  150. prograph/plan/ir/dataset.py +643 -0
  151. prograph/plan/ir/dates.py +102 -0
  152. prograph/plan/ir/entry.py +992 -0
  153. prograph/plan/ir/expr.py +260 -0
  154. prograph/plan/ir/facts.py +1171 -0
  155. prograph/plan/ir/fresh.py +291 -0
  156. prograph/plan/ir/freshness.py +625 -0
  157. prograph/plan/ir/identity.py +797 -0
  158. prograph/plan/ir/java_datetime.py +265 -0
  159. prograph/plan/ir/java_regex.py +391 -0
  160. prograph/plan/ir/join_order.py +39 -0
  161. prograph/plan/ir/key_checks.py +433 -0
  162. prograph/plan/ir/keys.py +454 -0
  163. prograph/plan/ir/lower.py +5323 -0
  164. prograph/plan/ir/ops.py +619 -0
  165. prograph/plan/ir/owl_rl.py +1119 -0
  166. prograph/plan/ir/owl_rl_rules.py +725 -0
  167. prograph/plan/ir/profiles.py +694 -0
  168. prograph/plan/ir/ql.py +987 -0
  169. prograph/plan/ir/rdfs.py +342 -0
  170. prograph/plan/ir/rewrite.py +1782 -0
  171. prograph/plan/ir/saturate.py +339 -0
  172. prograph/plan/ir/semantics.py +103 -0
  173. prograph/plan/ir/slot.py +509 -0
  174. prograph/plan/ir/sparql_front.py +3418 -0
  175. prograph/plan/ir/strings.py +534 -0
  176. prograph/plan/ir/term_functions.py +274 -0
  177. prograph/plan/ir/terms.py +84 -0
  178. prograph/plan/ir/xpath_regex.py +264 -0
  179. prograph/plan/run_record.py +65 -0
  180. prograph/plan/sql/__init__.py +21 -0
  181. prograph/plan/sql/dialect.py +3726 -0
  182. prograph/plan/sql/mysql_serializer.py +103 -0
  183. prograph/plan/sql/names.py +65 -0
  184. prograph/plan/sql/oracle_serializer.py +306 -0
  185. prograph/plan/sql/pg_serializer.py +501 -0
  186. prograph/plan/sql/rel_algebra.py +781 -0
  187. prograph/plan/sql/sql_serializer.py +1419 -0
  188. prograph/plan/sql/sqlserver_serializer.py +603 -0
  189. prograph/provenance.py +222 -0
  190. prograph/r2rml/__init__.py +48 -0
  191. prograph/r2rml/catalog.py +259 -0
  192. prograph/r2rml/compile.py +372 -0
  193. prograph/r2rml/direct.py +140 -0
  194. prograph/r2rml/export.py +495 -0
  195. prograph/r2rml/model.py +180 -0
  196. prograph/r2rml/parser.py +546 -0
  197. prograph/r2rml/schema.py +120 -0
  198. prograph/read_only.py +122 -0
  199. prograph/results.py +157 -0
  200. prograph/rules/__init__.py +168 -0
  201. prograph/rules/__main__.py +32 -0
  202. prograph/schema/__init__.py +60 -0
  203. prograph/schema/change_set.py +50 -0
  204. prograph/schema/collations.py +198 -0
  205. prograph/schema/compile_schema.py +388 -0
  206. prograph/schema/context.py +845 -0
  207. prograph/schema/examples.py +234 -0
  208. prograph/schema/iri.py +817 -0
  209. prograph/schema/literals.py +94 -0
  210. prograph/schema/lpg_view.py +617 -0
  211. prograph/schema/mapping.py +1803 -0
  212. prograph/schema/maps_schema.py +40 -0
  213. prograph/schema/naming.py +77 -0
  214. prograph/schema/query_sources.py +59 -0
  215. prograph/schema/rows.py +215 -0
  216. prograph/schema/source_map.py +1103 -0
  217. prograph/schema/store_view.py +459 -0
  218. prograph/schema/types.py +569 -0
  219. prograph/schema/xsd.py +569 -0
  220. prograph/shacl/__init__.py +30 -0
  221. prograph/shacl/dqv.py +58 -0
  222. prograph/shacl/generate.py +255 -0
  223. prograph/shacl/report.py +138 -0
  224. prograph/shacl/validator.py +164 -0
  225. prograph/store.py +1737 -0
  226. prograph/utils/__init__.py +6 -0
  227. prograph/utils/exceptions.py +308 -0
  228. prograph/utils/helpers.py +126 -0
  229. prograph/warnings.py +46 -0
  230. prograph/writes.py +369 -0
  231. prograph-1.3.3.dist-info/METADATA +281 -0
  232. prograph-1.3.3.dist-info/RECORD +237 -0
  233. prograph-1.3.3.dist-info/WHEEL +5 -0
  234. prograph-1.3.3.dist-info/entry_points.txt +3 -0
  235. prograph-1.3.3.dist-info/licenses/LICENSE +201 -0
  236. prograph-1.3.3.dist-info/licenses/NOTICE +10 -0
  237. prograph-1.3.3.dist-info/top_level.txt +1 -0
@@ -0,0 +1,258 @@
1
+ """
2
+ Few-shot examples for different domains.
3
+
4
+ These examples help LLMs understand the query patterns for specific use cases.
5
+ """
6
+
7
+ from typing import Dict, List, Optional
8
+
9
+ # Generic Cypher examples
10
+ CYPHER_EXAMPLES: List[Dict[str, str]] = [
11
+ {
12
+ "question": "Find all people older than 30",
13
+ "query": "MATCH (p:Person) WHERE p.age > 30 RETURN p.name, p.age ORDER BY p.age DESC",
14
+ },
15
+ {
16
+ "question": "How many customers are there?",
17
+ "query": "MATCH (c:Customer) RETURN count(c) AS total_customers",
18
+ },
19
+ {
20
+ "question": "Find people who know each other",
21
+ "query": "MATCH (a:Person)-[:KNOWS]->(b:Person) RETURN a.name AS person1, b.name AS person2",
22
+ },
23
+ {
24
+ "question": "What are the top 5 most connected nodes?",
25
+ "query": "MATCH (n)-[r]-() RETURN n, count(r) AS connections ORDER BY connections DESC LIMIT 5",
26
+ },
27
+ {
28
+ "question": "Find all paths between Alice and Bob",
29
+ "query": "MATCH path = (a:Person {name: 'Alice'})-[*1..5]-(b:Person {name: 'Bob'}) RETURN path LIMIT 10",
30
+ },
31
+ ]
32
+
33
+ # Domain-specific examples for AML/Financial Crime
34
+ AML_EXAMPLES: List[Dict[str, str]] = [
35
+ {
36
+ "question": "Find accounts with suspicious activity",
37
+ "query": "MATCH (a:Account) WHERE a.risk_score > 0.8 RETURN a.account_id, a.risk_score ORDER BY a.risk_score DESC",
38
+ },
39
+ {
40
+ "question": "Show money transfer chains longer than 3 hops",
41
+ "query": "MATCH path = (a:Account)-[:TRANSFERRED_TO*3..5]->(b:Account) RETURN path LIMIT 20",
42
+ },
43
+ {
44
+ "question": "Find accounts connected to sanctioned entities",
45
+ "query": "MATCH (a:Account)-[:OWNED_BY]->(p:Person)-[:ASSOCIATED_WITH]->(s:SanctionedEntity) RETURN a, p, s",
46
+ },
47
+ {
48
+ "question": "Identify circular money flows",
49
+ "query": "MATCH (a:Account)-[:TRANSFERRED_TO*3..6]->(a) RETURN a.account_id, count(*) AS circular_flows ORDER BY circular_flows DESC",
50
+ },
51
+ {
52
+ "question": "Find high-value transactions to high-risk jurisdictions",
53
+ "query": "MATCH (a:Account)-[t:TRANSFERRED_TO]->(b:Account)-[:LOCATED_IN]->(c:Country) WHERE t.amount > 10000 AND c.risk_level = 'HIGH' RETURN a, t.amount, b, c.name",
54
+ },
55
+ ]
56
+
57
+ # Domain-specific examples for Social Network Analysis
58
+ SOCIAL_EXAMPLES: List[Dict[str, str]] = [
59
+ {
60
+ "question": "Find the most influential people",
61
+ "query": "MATCH (p:Person)<-[:FOLLOWS]-(f) RETURN p.name, count(f) AS followers ORDER BY followers DESC LIMIT 10",
62
+ },
63
+ {
64
+ "question": "Find communities based on mutual connections",
65
+ "query": "MATCH (a:Person)-[:KNOWS]->(b:Person)-[:KNOWS]->(c:Person)-[:KNOWS]->(a) RETURN a.name, b.name, c.name",
66
+ },
67
+ {
68
+ "question": "What content is trending?",
69
+ "query": "MATCH (p:Post)<-[:LIKED]-(u:User) RETURN p.title, count(u) AS likes ORDER BY likes DESC LIMIT 10",
70
+ },
71
+ {
72
+ "question": "Find potential connections (friends of friends)",
73
+ "query": "MATCH (me:Person {name: $name})-[:KNOWS]->(friend)-[:KNOWS]->(suggestion) WHERE NOT (me)-[:KNOWS]->(suggestion) AND me <> suggestion RETURN suggestion.name, count(friend) AS mutual_friends ORDER BY mutual_friends DESC LIMIT 5",
74
+ },
75
+ ]
76
+
77
+ # Domain-specific examples for Supply Chain
78
+ SUPPLY_CHAIN_EXAMPLES: List[Dict[str, str]] = [
79
+ {
80
+ "question": "Find all suppliers for a product",
81
+ "query": "MATCH (p:Product {name: $product})<-[:SUPPLIES]-(s:Supplier) RETURN s.name, s.location, s.reliability_score",
82
+ },
83
+ {
84
+ "question": "Trace the origin of components",
85
+ "query": "MATCH path = (p:Product)-[:CONTAINS*]->(c:Component)-[:SOURCED_FROM]->(s:Supplier) RETURN path",
86
+ },
87
+ {
88
+ "question": "Find single points of failure in the supply chain",
89
+ "query": "MATCH (s:Supplier)-[:SUPPLIES]->(p:Product) WITH s, count(p) AS products WHERE products > 5 RETURN s.name, products ORDER BY products DESC",
90
+ },
91
+ {
92
+ "question": "Calculate lead time for products",
93
+ "query": "MATCH (s:Supplier)-[r:SUPPLIES]->(p:Product) RETURN p.name, avg(r.lead_time_days) AS avg_lead_time ORDER BY avg_lead_time",
94
+ },
95
+ ]
96
+
97
+ # Domain-specific examples for LDBC Social Network Benchmark
98
+ # These showcase relationship-centric queries that go beyond SQL capabilities
99
+ LDBC_SNB_EXAMPLES: List[Dict[str, str]] = [
100
+ # === Basic Counts ===
101
+ {
102
+ "question": "How many people are there?",
103
+ "query": "MATCH (p:Person) RETURN count(p) AS totalPeople",
104
+ },
105
+ {
106
+ "question": "How many forums are there?",
107
+ "query": "MATCH (f:Forum) RETURN count(f) AS totalForums",
108
+ },
109
+ {
110
+ "question": "How many tags are there?",
111
+ "query": "MATCH (t:Tag) RETURN count(t) AS totalTags",
112
+ },
113
+ # === Finding People ===
114
+ {
115
+ "question": "Find people named John",
116
+ "query": "MATCH (p:Person) WHERE p.firstName = 'John' RETURN p.firstName, p.lastName, p.id LIMIT 20",
117
+ },
118
+ {
119
+ "question": "Find people with first name Alice",
120
+ "query": "MATCH (p:Person {firstName: 'Alice'}) RETURN p.firstName, p.lastName, p.id LIMIT 20",
121
+ },
122
+ # === Most Connected (Aggregation) ===
123
+ {
124
+ "question": "Who are the most connected people in the network?",
125
+ "query": "MATCH (p:Person)-[:KNOWS]-(friend:Person) RETURN p.firstName, p.lastName, COUNT(friend) AS connections ORDER BY connections DESC LIMIT 10",
126
+ },
127
+ {
128
+ "question": "Find the top 10 people with the most friends",
129
+ "query": "MATCH (p:Person)-[:KNOWS]-(friend:Person) RETURN p.firstName, p.lastName, COUNT(friend) AS friendCount ORDER BY friendCount DESC LIMIT 10",
130
+ },
131
+ # === Forums and Members ===
132
+ {
133
+ "question": "Which forums have the most members?",
134
+ "query": "MATCH (f:Forum)-[:HAS_MEMBER]-(m:Person) RETURN f.title, COUNT(m) AS memberCount ORDER BY memberCount DESC LIMIT 10",
135
+ },
136
+ {
137
+ "question": "Find the most active forum members",
138
+ "query": "MATCH (f:Forum)-[:HAS_MEMBER]-(m:Person) RETURN m.firstName, m.lastName, COUNT(DISTINCT f) AS forumsJoined ORDER BY forumsJoined DESC LIMIT 10",
139
+ },
140
+ {
141
+ "question": "Find people who are in the most forums and have the most friends",
142
+ "query": "MATCH (p:Person)-[:HAS_MEMBER]-(f:Forum) WITH p, COUNT(DISTINCT f) AS forumCount MATCH (p)-[:KNOWS]-(friend:Person) RETURN p.firstName, p.lastName, forumCount, COUNT(DISTINCT friend) AS friendCount ORDER BY forumCount DESC, friendCount DESC LIMIT 10",
143
+ },
144
+ # === Interests and Tags ===
145
+ {
146
+ "question": "What are the most popular interests?",
147
+ "query": "MATCH (p:Person)-[:HAS_INTEREST]->(t:Tag) RETURN t.name, COUNT(p) AS popularity ORDER BY popularity DESC LIMIT 10",
148
+ },
149
+ {
150
+ "question": "Find interests of the most connected people",
151
+ "query": "MATCH (p:Person)-[:KNOWS]-(friend:Person) WITH p, COUNT(friend) AS connections ORDER BY connections DESC LIMIT 5 MATCH (p)-[:HAS_INTEREST]->(t:Tag) RETURN p.firstName, p.lastName, connections, COLLECT(t.name) AS interests LIMIT 10",
152
+ },
153
+ {
154
+ "question": "Find people who share interests",
155
+ "query": "MATCH (p1:Person)-[:HAS_INTEREST]->(t:Tag)<-[:HAS_INTEREST]-(p2:Person) WHERE p1.id < p2.id RETURN p1.firstName, p2.firstName, t.name AS sharedInterest LIMIT 20",
156
+ },
157
+ # === Friends and Connections ===
158
+ {
159
+ "question": "Find people who know each other",
160
+ "query": "MATCH (a:Person)-[:KNOWS]-(b:Person) WHERE a.id < b.id RETURN a.firstName, a.lastName, b.firstName, b.lastName LIMIT 20",
161
+ },
162
+ {
163
+ "question": "Find friends of friends for a person",
164
+ "query": "MATCH (p:Person {id: $personId})-[:KNOWS]-(friend:Person)-[:KNOWS]-(fof:Person) WHERE fof <> p AND NOT (p)-[:KNOWS]-(fof) RETURN DISTINCT fof.firstName, fof.lastName, COUNT(friend) AS mutualFriends ORDER BY mutualFriends DESC LIMIT 10",
165
+ },
166
+ # === Location Queries ===
167
+ {
168
+ "question": "Find people and their locations",
169
+ "query": "MATCH (p:Person)-[:IS_LOCATED_IN]->(place:Place) RETURN p.firstName, p.lastName, place.name AS location LIMIT 20",
170
+ },
171
+ {
172
+ "question": "Find people located in a specific city",
173
+ "query": "MATCH (p:Person)-[:IS_LOCATED_IN]->(place:Place {name: $cityName}) RETURN p.firstName, p.lastName LIMIT 20",
174
+ },
175
+ # === Multi-MATCH with WITH (Correct Pattern) ===
176
+ {
177
+ "question": "Find what interests the most connected people have",
178
+ "query": "MATCH (p:Person)-[:KNOWS]-(friend:Person) WITH p, COUNT(friend) AS connections ORDER BY connections DESC LIMIT 3 MATCH (p)-[:HAS_INTEREST]->(t:Tag) RETURN p.firstName, connections, t.name AS interest",
179
+ },
180
+ {
181
+ "question": "Find friends of people who are in the most forums",
182
+ "query": "MATCH (p:Person)-[:HAS_MEMBER]-(f:Forum) WITH p, COUNT(f) AS forumCount ORDER BY forumCount DESC LIMIT 5 MATCH (p)-[:KNOWS]-(friend:Person) RETURN p.firstName, forumCount, friend.firstName AS friendName LIMIT 20",
183
+ },
184
+ # === Variable-length Paths ===
185
+ {
186
+ "question": "Find all people within 3 degrees of connection",
187
+ "query": "MATCH (p:Person {id: $personId})-[:KNOWS*1..3]-(friend:Person) RETURN DISTINCT friend.firstName, friend.lastName LIMIT 50",
188
+ },
189
+ {
190
+ "question": "Find all places within a country",
191
+ "query": "MATCH (country:Place {name: $countryName})<-[:IS_PART_OF*]-(place:Place) RETURN place.name LIMIT 50",
192
+ },
193
+ # === Posts and Comments ===
194
+ {
195
+ "question": "Find posts with the most likes",
196
+ "query": "MATCH (p:Post)<-[:LIKES]-(person:Person) RETURN p.id, COUNT(person) AS likeCount ORDER BY likeCount DESC LIMIT 10",
197
+ },
198
+ {
199
+ "question": "Find the most active content creators",
200
+ "query": "MATCH (p:Person)<-[:HAS_CREATOR]-(post:Post) RETURN p.firstName, p.lastName, COUNT(post) AS postCount ORDER BY postCount DESC LIMIT 10",
201
+ },
202
+ ]
203
+
204
+ # Registry of domain examples
205
+ DOMAIN_EXAMPLES: Dict[str, List[Dict[str, str]]] = {
206
+ "generic": CYPHER_EXAMPLES,
207
+ "aml": AML_EXAMPLES,
208
+ "financial": AML_EXAMPLES,
209
+ "social": SOCIAL_EXAMPLES,
210
+ "supply_chain": SUPPLY_CHAIN_EXAMPLES,
211
+ "ldbc": LDBC_SNB_EXAMPLES,
212
+ "snb": LDBC_SNB_EXAMPLES,
213
+ "network": LDBC_SNB_EXAMPLES,
214
+ }
215
+
216
+
217
+ def get_examples_for_domain(
218
+ domain: str = "generic",
219
+ language: str = "sparql",
220
+ n: Optional[int] = None,
221
+ ) -> List[Dict[str, str]]:
222
+ """
223
+ Get few-shot examples for a specific domain.
224
+
225
+ Args:
226
+ domain: Domain name (generic, aml, social, supply_chain).
227
+ language: Query language (cypher).
228
+ n: Optional limit on number of examples.
229
+
230
+ Returns:
231
+ List of {"question": str, "query": str} examples.
232
+ """
233
+ examples = DOMAIN_EXAMPLES.get(domain.lower(), CYPHER_EXAMPLES)
234
+
235
+ if n is not None:
236
+ examples = examples[:n]
237
+
238
+ return examples
239
+
240
+
241
+ def format_examples(examples: List[Dict[str, str]]) -> str:
242
+ """
243
+ Format examples as a string for inclusion in prompts.
244
+
245
+ Args:
246
+ examples: List of example dicts.
247
+
248
+ Returns:
249
+ Formatted string.
250
+ """
251
+ lines = ["## Examples", ""]
252
+ for i, ex in enumerate(examples, 1):
253
+ lines.append(f"**Q{i}:** {ex['question']}")
254
+ lines.append(f"```")
255
+ lines.append(ex["query"])
256
+ lines.append("```")
257
+ lines.append("")
258
+ return "\n".join(lines)
@@ -0,0 +1,239 @@
1
+ """
2
+ System prompt templates for LLM query generation.
3
+ """
4
+
5
+ from typing import Any, Optional
6
+ from prograph.rules import home, module_home
7
+
8
+ module_home("sparql-query-rules", "SPARQL query-writing rules (NLP and MCP)",
9
+ terms=("SPARQL_QUERY_RULES", "system prompt", "render_sparql_rules", "query rules", "get_schema"))
10
+
11
+
12
+ # The rules for writing a SPARQL query over a mapping: the one copy, read
13
+ # by the prompt `ask` gives its model (below) and by the MCP `get_schema`
14
+ # (`prograph.mcp.sparql`), so a client writing its own SPARQL follows the
15
+ # same rules (docs/architecture/rules.md, "SPARQL query-writing rules").
16
+ SPARQL_QUERY_RULES = (
17
+ "**Use only the vocabulary.** Every class and predicate must be one it lists, written with its prefixes; an IRI it does not list matches nothing.",
18
+ "**Start with the PREFIX lines the vocabulary gives**, all of them, exactly as written.\n"
19
+ " A value the question gives for a property the vocabulary lists (a serial number, a name, a code) is a literal\n"
20
+ " matched on that property: `?x :code \"A-17\"`, never an IRI. Write an individual's IRI only for its key, the\n"
21
+ " identifier the Individuals templates take (`bearing-1001-mid`), as the full IRI in angle brackets: never a\n"
22
+ " prefixed name in the vocabulary's namespace. When unsure which a value is, match the property.",
23
+ "**A class covers the classes within it.** To count or list every module, ask for the class of all modules; do not list its subclasses one by one.",
24
+ "**Follow a chain with a property path:** `?a :p+ ?b` for one or more steps, `?a :p* ?b` for zero or more, `?a :p/:q ?b` for a sequence, `^:p` for the inverse.",
25
+ "**A value that may be missing goes in OPTIONAL**, so the row is kept without it.",
26
+ "**Compare literals as their datatype:** numbers unquoted (`FILTER(?w > 0.5)`), dates as `\"2024-01-31\"^^xsd:date`, text as a quoted string; use `rdfs:label` for a name where the vocabulary has it.",
27
+ "**Aggregates need GROUP BY** of every other selected variable: `SELECT ?e (COUNT(?m) AS ?n) WHERE { ... } GROUP BY ?e`. Add ORDER BY and LIMIT when the question asks for the top or the most.",
28
+ "Do not use SERVICE, FROM, FROM NAMED or GRAPH: the dataset is the mapping.",
29
+ "**Show each entity a person would name by its name too.** Where you select or group by an entity whose class has a name (`rdfs:label`, or the class's own name property), select that name beside it, and group by both: `SELECT ?nation ?nationName (COUNT(?c) AS ?n) WHERE { ?c a :customer ; :c_has_nation ?nation . ?nation :n_name ?nationName } GROUP BY ?nation ?nationName`. A bare IRI is not an answer a reader can use.",
30
+ "**Name a variable after what it holds:** its class for an entity (`?customer`, `?nation`), its property for a value (`?acctbal`, `?orderdate`), `Name` after the entity for its name (`?nationName`).",
31
+ "**Order so equal values keep one order:** after the ordering the question asks for, order by the entity's name, else its key (`ORDER BY DESC(?acctbal) ?customerName`).",
32
+ "**A year is `YEAR(?date) = 1995`;** a span of days is `?date >= \"1995-03-01\"^^xsd:date && ?date < \"1995-04-01\"^^xsd:date`.",
33
+ )
34
+
35
+
36
+ def render_sparql_rules() -> str:
37
+ """The query-writing rules as a numbered list."""
38
+ return "\n".join(f"{n}. {rule}" for n, rule in enumerate(SPARQL_QUERY_RULES, 1))
39
+
40
+
41
+ SPARQL_SYSTEM_PROMPT = f"""You write SPARQL 1.1 queries over a mapping of relational tables to RDF.
42
+
43
+ Your task is to convert a natural language question into one valid SPARQL 1.1 query over the vocabulary below.
44
+
45
+ ## Rules
46
+
47
+ {render_sparql_rules()}
48
+
49
+ ## Output Format
50
+
51
+ Return ONLY the SPARQL query, with no explanation. If the question cannot be answered from the vocabulary, return one line:
52
+ # ERROR: [why it cannot be answered]
53
+ """
54
+
55
+ # The rules for writing a Cypher query over a mapping's property-graph view: the one copy, read by the
56
+ # prompt `ask` gives its model for Cypher (`cypher_prompt`) (docs/architecture/rules.md, "Cypher
57
+ # query-writing rules"). They state what ProGraph's Cypher builds and refuses; a test runs every function
58
+ # and form they name on the turbofan demo (`tests/nlp/test_ask_in_cypher.py`).
59
+ CYPHER_QUERY_RULES = (
60
+ "**Use only the graph schema's names**, spelled as it lists them (case matters): its labels, relationship "
61
+ "types and property keys. A label or type it does not list matches nothing, and a key no label lists is null.",
62
+ "**A node has the labels of every kind it is:** a `(:Blade)` node is a `(:Component)` too, and under an "
63
+ "ontology its superclasses' labels are its labels. To count or list every component, match `(:Component)`; "
64
+ "do not list its kinds one by one.",
65
+ "**Follow a relationship in the direction the schema gives**, `(start)-[:TYPE]->(end)`; write `-[:TYPE]-` "
66
+ "(no arrow) only for either direction.",
67
+ "**Follow a chain with a variable-length relationship:** `-[:TYPE*1..]->` for one or more steps, `*0..` for "
68
+ "zero or more, `*2` for exactly two, `-[:A]->()-[:B]->` for a sequence of two types. Return the nodes it "
69
+ "reaches with DISTINCT. Do not bind a path variable (`p = ...`) over a variable-length relationship.",
70
+ "**A node's key column is a property under its column name:** a node named by its key (`bearing-1001-mid`) "
71
+ "is found by the key property the schema lists, `(:Bearing {id: 'bearing-1001-mid'})` or `WHERE b.id = ...`; "
72
+ "else by another listed key (a name, a serial number). `id(n)` and `elementId(n)` are the node's IRI, not "
73
+ "its key: compare nodes with them, and read a key as its property (`b.id`). Where the question names a node "
74
+ "only by a value no listed key holds, return the ERROR line.",
75
+ "**A key a node lacks is null:** read it as it is (`RETURN c, c.finding`); use OPTIONAL MATCH for a "
76
+ "relationship that may be missing.",
77
+ "**Compare values as their type:** numbers unquoted (`c.wear_index > 0.5`), strings quoted, a Date as "
78
+ "`date('2024-01-31')`, a DateTime as `datetime('2024-01-31T10:00:00Z')`; a year is `d.year = 2024`.",
79
+ "**A Decimal key is an exact number:** sum(), avg(), min(), max(), arithmetic with integers and other "
80
+ "Decimal keys, abs, round, floor and ceil keep it exact; a number written with a point (`1.1`) is a float "
81
+ "and makes the result a float.",
82
+ "**Aggregate in RETURN or WITH:** every item that is not an aggregate is a grouping key "
83
+ "(`RETURN e, e.label AS engineName, count(m) AS modules`). Add ORDER BY and LIMIT when the question asks "
84
+ "for the top or the most.",
85
+ "**Return the nodes the question asks for, with their name beside them:** `RETURN c, c.label AS "
86
+ "componentName`, not the name alone. A node is answered as its id, labels and properties.",
87
+ "**Name each column after what it holds** with AS: `componentName`, `wearIndex`, `count`.",
88
+ "**Order so equal values keep one order:** after the ordering the question asks for, order by the name "
89
+ "(`ORDER BY wearIndex DESC, componentName`).",
90
+ "**Read only:** never CREATE, MERGE, SET, REMOVE, DELETE or DETACH DELETE. ask refuses a query that writes.",
91
+ "**Functions that are built:** count, sum, avg, min, max, collect; size, labels, type, keys, properties, "
92
+ "id and elementId of a node, "
93
+ "coalesce, head, last; toUpper, toLower, substring, split, reverse, toString, toInteger, toFloat; abs, "
94
+ "round, floor, ceil, sqrt; date, datetime and a temporal's parts (`d.year`). Also CASE, list "
95
+ "comprehensions, UNWIND, UNION, EXISTS { ... }, pattern predicates (`WHERE (a)-[:T]->()`) and "
96
+ "`size([(a)-[:T]->(x) | x])`.",
97
+ "**Not built, and refused by name:** regular expressions (`=~`: use CONTAINS, STARTS WITH, ENDS WITH), "
98
+ "trim(), left(), right(), replace(), duration.between() of a property, stDev and stDevP, reduce(), "
99
+ "FOREACH, a CALL { ... } subquery after a MATCH, collect() after a `WITH ... ORDER BY ... LIMIT`, and "
100
+ "procedures other than the declared ones. A query refused as needing too many CTEs reads whole nodes or "
101
+ "labels() over a chain of steps: return the end nodes of one variable-length relationship (`*2`), or "
102
+ "their keys, instead.",
103
+ )
104
+
105
+
106
+ @home("cypher-query-rules", "Cypher query-writing rules (ask)",
107
+ terms=("CYPHER_QUERY_RULES", "render_cypher_rules", "cypher_prompt", "Cypher system prompt",
108
+ "functions that are built", "named refusals"))
109
+ def render_cypher_rules() -> str:
110
+ """The Cypher query-writing rules as a numbered list."""
111
+ return "\n".join(f"{n}. {rule}" for n, rule in enumerate(CYPHER_QUERY_RULES, 1))
112
+
113
+
114
+ CYPHER_SYSTEM_PROMPT = f"""You write openCypher queries over a property-graph view of relational tables.
115
+
116
+ Your task is to convert a natural language question into one valid, read-only Cypher query over the graph schema below.
117
+
118
+ ## Rules
119
+
120
+ {render_cypher_rules()}
121
+
122
+ ## Output Format
123
+
124
+ Return ONLY the Cypher query, with no explanation. If the question cannot be answered from the graph schema, return one line:
125
+ // ERROR: [why it cannot be answered]
126
+ """
127
+
128
+ RETRY_PROMPT_TEMPLATE = """The previous query failed with the following error:
129
+
130
+ ```
131
+ {error}
132
+ ```
133
+
134
+ Please fix the query and try again. The original question was:
135
+ "{question}"
136
+
137
+ Return ONLY the corrected query.
138
+ """
139
+
140
+ EXPLANATION_PROMPT_TEMPLATE = """Based on the following graph query and its results, provide a brief natural language explanation of what the query found.
141
+
142
+ **Query:**
143
+ ```
144
+ {query}
145
+ ```
146
+
147
+ **Results:**
148
+ {results}
149
+
150
+ Provide a 1-2 sentence summary of the findings.
151
+ """
152
+
153
+
154
+ def get_system_prompt(
155
+ language: str = "sparql",
156
+ schema_context: Optional[str] = None,
157
+ examples: Optional[str] = None,
158
+ ) -> str:
159
+ """
160
+ Build a complete system prompt for the given language.
161
+
162
+ Args:
163
+ language: Query language ("cypher" or "sparql").
164
+ schema_context: Optional schema description to include.
165
+ examples: Optional few-shot examples to include.
166
+
167
+ Returns:
168
+ Complete system prompt string.
169
+ """
170
+ prompts = {"cypher": CYPHER_SYSTEM_PROMPT,
171
+ "sparql": SPARQL_SYSTEM_PROMPT}
172
+ lang = language.lower()
173
+ if lang not in prompts:
174
+ raise ValueError(f"there is no system prompt for {language!r}")
175
+ base_prompt = prompts[lang]
176
+
177
+ parts = [base_prompt]
178
+
179
+ if schema_context:
180
+ # Each language's schema has its own heading (`render_sparql`, `render_graph`).
181
+ parts.append(schema_context)
182
+
183
+ if examples:
184
+ parts.append("\n")
185
+ parts.append(examples)
186
+
187
+ return "\n".join(parts)
188
+
189
+
190
+ def sparql_prompt(schema: Any) -> str:
191
+ """The whole prompt a model writes SPARQL from over `schema`: the rules, the vocabulary
192
+ (`render_sparql`) and examples generated from the mapping (`sparql_examples`). `ask` gives it to
193
+ its model, and the SPARQL MCP server offers it as the `write-sparql` prompt, so a client that
194
+ writes its own queries gets the same guidance."""
195
+ from prograph.schema.context import describe_schema, render_sparql
196
+ from prograph.schema.examples import render_examples, sparql_examples
197
+ desc = describe_schema(schema)
198
+ return get_system_prompt(language="sparql", schema_context=render_sparql(desc),
199
+ examples=render_examples(sparql_examples(desc, n=5)))
200
+
201
+
202
+ def cypher_prompt(engine: Any) -> str:
203
+ """The whole prompt a model writes Cypher from over `engine`: the rules, the property-graph schema
204
+ (`graph_context.render_graph`: labels with their keys, relationship types with their ends, and what the
205
+ ontology adds) and the examples (`graph_context.cypher_examples`: the questions of the SPARQL examples,
206
+ answered in Cypher)."""
207
+ from prograph.nlp.graph_context import cypher_examples, describe_graph, render_graph
208
+ from prograph.schema.examples import render_examples
209
+ desc = describe_graph(engine)
210
+ return get_system_prompt(language="cypher", schema_context=render_graph(desc),
211
+ examples=render_examples(cypher_examples(desc, n=5)))
212
+
213
+
214
+ def get_retry_prompt(question: str, error: str) -> str:
215
+ """
216
+ Build a retry prompt after a query error.
217
+
218
+ Args:
219
+ question: Original user question.
220
+ error: Error message from failed query.
221
+
222
+ Returns:
223
+ Retry prompt string.
224
+ """
225
+ return RETRY_PROMPT_TEMPLATE.format(question=question, error=error)
226
+
227
+
228
+ def get_explanation_prompt(query: str, results: str) -> str:
229
+ """
230
+ Build a prompt to explain query results.
231
+
232
+ Args:
233
+ query: The executed query.
234
+ results: String representation of results.
235
+
236
+ Returns:
237
+ Explanation prompt string.
238
+ """
239
+ return EXPLANATION_PROMPT_TEMPLATE.format(query=query, results=results)
@@ -0,0 +1,14 @@
1
+ """
2
+ LLM provider implementations for ProGraph NL interface.
3
+
4
+ Available providers:
5
+ - DatabricksLLMClient: Uses Databricks Foundation Model APIs
6
+ - OpenAILLMClient: Uses OpenAI API directly
7
+ - AnthropicLLMClient: Uses Anthropic API for Claude models
8
+ """
9
+
10
+ from prograph.nlp.providers.databricks import DatabricksLLMClient
11
+ from prograph.nlp.providers.openai import OpenAILLMClient
12
+ from prograph.nlp.providers.anthropic import AnthropicLLMClient
13
+
14
+ __all__ = ["DatabricksLLMClient", "OpenAILLMClient", "AnthropicLLMClient"]