graphs.py 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683
  1. import asyncio
  2. import contextlib
  3. import datetime
  4. import json
  5. import logging
  6. import os
  7. import time
  8. from enum import Enum
  9. from typing import Any, AsyncGenerator, Optional, Tuple
  10. from uuid import UUID
  11. import asyncpg
  12. import httpx
  13. from asyncpg.exceptions import UndefinedTableError, UniqueViolationError
  14. from fastapi import HTTPException
  15. from core.base.abstractions import (
  16. Community,
  17. Entity,
  18. Graph,
  19. KGCreationSettings,
  20. KGEnrichmentSettings,
  21. KGEntityDeduplicationSettings,
  22. KGExtractionStatus,
  23. R2RException,
  24. Relationship,
  25. VectorQuantizationType,
  26. )
  27. from core.base.api.models import GraphResponse
  28. from core.base.providers.database import Handler
  29. from core.base.utils import (
  30. _decorate_vector_type,
  31. _get_str_estimation_output,
  32. llm_cost_per_million_tokens,
  33. )
  34. from .base import PostgresConnectionManager
  35. from .collections import PostgresCollectionsHandler
  36. class StoreType(str, Enum):
  37. GRAPHS = "graphs"
  38. DOCUMENTS = "documents"
  39. logger = logging.getLogger()
  40. class PostgresEntitiesHandler(Handler):
  41. def __init__(self, *args: Any, **kwargs: Any) -> None:
  42. self.project_name: str = kwargs.get("project_name") # type: ignore
  43. self.connection_manager: PostgresConnectionManager = kwargs.get("connection_manager") # type: ignore
  44. self.dimension: int = kwargs.get("dimension") # type: ignore
  45. self.quantization_type: VectorQuantizationType = kwargs.get("quantization_type") # type: ignore
  46. def _get_table_name(self, table: str) -> str:
  47. """Get the fully qualified table name."""
  48. return f'"{self.project_name}"."{table}"'
  49. def _get_entity_table_for_store(self, store_type: StoreType) -> str:
  50. """Get the appropriate table name for the store type."""
  51. if isinstance(store_type, StoreType):
  52. store_type = store_type.value
  53. return f"{store_type}_entities"
  54. def _get_parent_constraint(self, store_type: StoreType) -> str:
  55. """Get the appropriate foreign key constraint for the store type."""
  56. if store_type == StoreType.GRAPHS:
  57. return f"""
  58. CONSTRAINT fk_graph
  59. FOREIGN KEY(parent_id)
  60. REFERENCES {self._get_table_name("graphs")}(id)
  61. ON DELETE CASCADE
  62. """
  63. else:
  64. return f"""
  65. CONSTRAINT fk_document
  66. FOREIGN KEY(parent_id)
  67. REFERENCES {self._get_table_name("documents")}(id)
  68. ON DELETE CASCADE
  69. """
  70. async def create_tables(self) -> None:
  71. """Create separate tables for graph and document entities."""
  72. vector_column_str = _decorate_vector_type(
  73. f"({self.dimension})", self.quantization_type
  74. )
  75. for store_type in StoreType:
  76. table_name = self._get_entity_table_for_store(store_type)
  77. parent_constraint = self._get_parent_constraint(store_type)
  78. QUERY = f"""
  79. CREATE TABLE IF NOT EXISTS {self._get_table_name(table_name)} (
  80. id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  81. name TEXT NOT NULL,
  82. category TEXT,
  83. description TEXT,
  84. parent_id UUID NOT NULL,
  85. description_embedding {vector_column_str},
  86. chunk_ids UUID[],
  87. metadata JSONB,
  88. created_at TIMESTAMPTZ DEFAULT NOW(),
  89. updated_at TIMESTAMPTZ DEFAULT NOW(),
  90. {parent_constraint}
  91. );
  92. CREATE INDEX IF NOT EXISTS {table_name}_name_idx
  93. ON {self._get_table_name(table_name)} (name);
  94. CREATE INDEX IF NOT EXISTS {table_name}_parent_id_idx
  95. ON {self._get_table_name(table_name)} (parent_id);
  96. CREATE INDEX IF NOT EXISTS {table_name}_category_idx
  97. ON {self._get_table_name(table_name)} (category);
  98. """
  99. await self.connection_manager.execute_query(QUERY)
  100. async def create(
  101. self,
  102. parent_id: UUID,
  103. store_type: StoreType,
  104. name: str,
  105. category: Optional[str] = None,
  106. description: Optional[str] = None,
  107. description_embedding: Optional[list[float] | str] = None,
  108. chunk_ids: Optional[list[UUID]] = None,
  109. metadata: Optional[dict[str, Any] | str] = None,
  110. ) -> Entity:
  111. """Create a new entity in the specified store."""
  112. table_name = self._get_entity_table_for_store(store_type)
  113. if isinstance(metadata, str):
  114. with contextlib.suppress(json.JSONDecodeError):
  115. metadata = json.loads(metadata)
  116. if isinstance(description_embedding, list):
  117. description_embedding = str(description_embedding)
  118. query = f"""
  119. INSERT INTO {self._get_table_name(table_name)}
  120. (name, category, description, parent_id, description_embedding, chunk_ids, metadata)
  121. VALUES ($1, $2, $3, $4, $5, $6, $7)
  122. RETURNING id, name, category, description, parent_id, chunk_ids, metadata
  123. """
  124. params = [
  125. name,
  126. category,
  127. description,
  128. parent_id,
  129. description_embedding,
  130. chunk_ids,
  131. json.dumps(metadata) if metadata else None,
  132. ]
  133. result = await self.connection_manager.fetchrow_query(
  134. query=query,
  135. params=params,
  136. )
  137. return Entity(
  138. id=result["id"],
  139. name=result["name"],
  140. category=result["category"],
  141. description=result["description"],
  142. parent_id=result["parent_id"],
  143. chunk_ids=result["chunk_ids"],
  144. metadata=result["metadata"],
  145. )
  146. async def get(
  147. self,
  148. parent_id: UUID,
  149. store_type: StoreType,
  150. offset: int,
  151. limit: int,
  152. entity_ids: Optional[list[UUID]] = None,
  153. entity_names: Optional[list[str]] = None,
  154. include_embeddings: bool = False,
  155. ):
  156. """Retrieve entities from the specified store."""
  157. table_name = self._get_entity_table_for_store(store_type)
  158. conditions = ["parent_id = $1"]
  159. params: list[Any] = [parent_id]
  160. param_index = 2
  161. if entity_ids:
  162. conditions.append(f"id = ANY(${param_index})")
  163. params.append(entity_ids)
  164. param_index += 1
  165. if entity_names:
  166. conditions.append(f"name = ANY(${param_index})")
  167. params.append(entity_names)
  168. param_index += 1
  169. select_fields = """
  170. id, name, category, description, parent_id,
  171. chunk_ids, metadata
  172. """
  173. if include_embeddings:
  174. select_fields += ", description_embedding"
  175. COUNT_QUERY = f"""
  176. SELECT COUNT(*)
  177. FROM {self._get_table_name(table_name)}
  178. WHERE {' AND '.join(conditions)}
  179. """
  180. count_params = params[: param_index - 1]
  181. count = (
  182. await self.connection_manager.fetch_query(
  183. COUNT_QUERY, count_params
  184. )
  185. )[0]["count"]
  186. QUERY = f"""
  187. SELECT {select_fields}
  188. FROM {self._get_table_name(table_name)}
  189. WHERE {' AND '.join(conditions)}
  190. ORDER BY created_at
  191. OFFSET ${param_index}
  192. """
  193. params.append(offset)
  194. param_index += 1
  195. if limit != -1:
  196. QUERY += f" LIMIT ${param_index}"
  197. params.append(limit)
  198. rows = await self.connection_manager.fetch_query(QUERY, params)
  199. entities = []
  200. for row in rows:
  201. # Convert the Record to a dictionary
  202. entity_dict = dict(row)
  203. # Process metadata if it exists and is a string
  204. if isinstance(entity_dict["metadata"], str):
  205. with contextlib.suppress(json.JSONDecodeError):
  206. entity_dict["metadata"] = json.loads(
  207. entity_dict["metadata"]
  208. )
  209. entities.append(Entity(**entity_dict))
  210. return entities, count
  211. async def update(
  212. self,
  213. entity_id: UUID,
  214. store_type: StoreType,
  215. name: Optional[str] = None,
  216. description: Optional[str] = None,
  217. description_embedding: Optional[list[float] | str] = None,
  218. category: Optional[str] = None,
  219. metadata: Optional[dict] = None,
  220. ) -> Entity:
  221. """Update an entity in the specified store."""
  222. table_name = self._get_entity_table_for_store(store_type)
  223. update_fields = []
  224. params: list[Any] = []
  225. param_index = 1
  226. if isinstance(metadata, str):
  227. with contextlib.suppress(json.JSONDecodeError):
  228. metadata = json.loads(metadata)
  229. if name is not None:
  230. update_fields.append(f"name = ${param_index}")
  231. params.append(name)
  232. param_index += 1
  233. if description is not None:
  234. update_fields.append(f"description = ${param_index}")
  235. params.append(description)
  236. param_index += 1
  237. if description_embedding is not None:
  238. update_fields.append(f"description_embedding = ${param_index}")
  239. params.append(description_embedding)
  240. param_index += 1
  241. if category is not None:
  242. update_fields.append(f"category = ${param_index}")
  243. params.append(category)
  244. param_index += 1
  245. if metadata is not None:
  246. update_fields.append(f"metadata = ${param_index}")
  247. params.append(json.dumps(metadata))
  248. param_index += 1
  249. if not update_fields:
  250. raise R2RException(status_code=400, message="No fields to update")
  251. update_fields.append("updated_at = NOW()")
  252. params.append(entity_id)
  253. query = f"""
  254. UPDATE {self._get_table_name(table_name)}
  255. SET {', '.join(update_fields)}
  256. WHERE id = ${param_index}\
  257. RETURNING id, name, category, description, parent_id, chunk_ids, metadata
  258. """
  259. try:
  260. result = await self.connection_manager.fetchrow_query(
  261. query=query,
  262. params=params,
  263. )
  264. return Entity(
  265. id=result["id"],
  266. name=result["name"],
  267. category=result["category"],
  268. description=result["description"],
  269. parent_id=result["parent_id"],
  270. chunk_ids=result["chunk_ids"],
  271. metadata=result["metadata"],
  272. )
  273. except Exception as e:
  274. raise HTTPException(
  275. status_code=500,
  276. detail=f"An error occurred while updating the entity: {e}",
  277. ) from e
  278. async def delete(
  279. self,
  280. parent_id: UUID,
  281. entity_ids: Optional[list[UUID]] = None,
  282. store_type: StoreType = StoreType.GRAPHS,
  283. ) -> None:
  284. """
  285. Delete entities from the specified store.
  286. If entity_ids is not provided, deletes all entities for the given parent_id.
  287. Args:
  288. parent_id (UUID): Parent ID (collection_id or document_id)
  289. entity_ids (Optional[list[UUID]]): Specific entity IDs to delete. If None, deletes all entities for parent_id
  290. store_type (StoreType): Type of store (graph or document)
  291. Returns:
  292. list[UUID]: List of deleted entity IDs
  293. Raises:
  294. R2RException: If specific entities were requested but not all found
  295. """
  296. table_name = self._get_entity_table_for_store(store_type)
  297. if entity_ids is None:
  298. # Delete all entities for the parent_id
  299. QUERY = f"""
  300. DELETE FROM {self._get_table_name(table_name)}
  301. WHERE parent_id = $1
  302. RETURNING id
  303. """
  304. results = await self.connection_manager.fetch_query(
  305. QUERY, [parent_id]
  306. )
  307. else:
  308. # Delete specific entities
  309. QUERY = f"""
  310. DELETE FROM {self._get_table_name(table_name)}
  311. WHERE id = ANY($1) AND parent_id = $2
  312. RETURNING id
  313. """
  314. results = await self.connection_manager.fetch_query(
  315. QUERY, [entity_ids, parent_id]
  316. )
  317. # Check if all requested entities were deleted
  318. deleted_ids = [row["id"] for row in results]
  319. if entity_ids and len(deleted_ids) != len(entity_ids):
  320. raise R2RException(
  321. f"Some entities not found in {store_type} store or no permission to delete",
  322. 404,
  323. )
  324. class PostgresRelationshipsHandler(Handler):
  325. def __init__(self, *args: Any, **kwargs: Any) -> None:
  326. self.project_name: str = kwargs.get("project_name") # type: ignore
  327. self.connection_manager: PostgresConnectionManager = kwargs.get("connection_manager") # type: ignore
  328. self.dimension: int = kwargs.get("dimension") # type: ignore
  329. self.quantization_type: VectorQuantizationType = kwargs.get("quantization_type") # type: ignore
  330. def _get_table_name(self, table: str) -> str:
  331. """Get the fully qualified table name."""
  332. return f'"{self.project_name}"."{table}"'
  333. def _get_relationship_table_for_store(self, store_type: StoreType) -> str:
  334. """Get the appropriate table name for the store type."""
  335. if isinstance(store_type, StoreType):
  336. store_type = store_type.value
  337. return f"{store_type}_relationships"
  338. def _get_parent_constraint(self, store_type: StoreType) -> str:
  339. """Get the appropriate foreign key constraint for the store type."""
  340. if store_type == StoreType.GRAPHS:
  341. return f"""
  342. CONSTRAINT fk_graph
  343. FOREIGN KEY(parent_id)
  344. REFERENCES {self._get_table_name("graphs")}(id)
  345. ON DELETE CASCADE
  346. """
  347. else:
  348. return f"""
  349. CONSTRAINT fk_document
  350. FOREIGN KEY(parent_id)
  351. REFERENCES {self._get_table_name("documents")}(id)
  352. ON DELETE CASCADE
  353. """
  354. async def create_tables(self) -> None:
  355. """Create separate tables for graph and document relationships."""
  356. for store_type in StoreType:
  357. table_name = self._get_relationship_table_for_store(store_type)
  358. parent_constraint = self._get_parent_constraint(store_type)
  359. vector_column_str = _decorate_vector_type(
  360. f"({self.dimension})", self.quantization_type
  361. )
  362. QUERY = f"""
  363. CREATE TABLE IF NOT EXISTS {self._get_table_name(table_name)} (
  364. id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  365. subject TEXT NOT NULL,
  366. predicate TEXT NOT NULL,
  367. object TEXT NOT NULL,
  368. description TEXT,
  369. description_embedding {vector_column_str},
  370. subject_id UUID,
  371. object_id UUID,
  372. weight FLOAT DEFAULT 1.0,
  373. chunk_ids UUID[],
  374. parent_id UUID NOT NULL,
  375. metadata JSONB,
  376. created_at TIMESTAMPTZ DEFAULT NOW(),
  377. updated_at TIMESTAMPTZ DEFAULT NOW(),
  378. {parent_constraint}
  379. );
  380. CREATE INDEX IF NOT EXISTS {table_name}_subject_idx
  381. ON {self._get_table_name(table_name)} (subject);
  382. CREATE INDEX IF NOT EXISTS {table_name}_object_idx
  383. ON {self._get_table_name(table_name)} (object);
  384. CREATE INDEX IF NOT EXISTS {table_name}_predicate_idx
  385. ON {self._get_table_name(table_name)} (predicate);
  386. CREATE INDEX IF NOT EXISTS {table_name}_parent_id_idx
  387. ON {self._get_table_name(table_name)} (parent_id);
  388. CREATE INDEX IF NOT EXISTS {table_name}_subject_id_idx
  389. ON {self._get_table_name(table_name)} (subject_id);
  390. CREATE INDEX IF NOT EXISTS {table_name}_object_id_idx
  391. ON {self._get_table_name(table_name)} (object_id);
  392. """
  393. await self.connection_manager.execute_query(QUERY)
  394. async def create(
  395. self,
  396. subject: str,
  397. subject_id: UUID,
  398. predicate: str,
  399. object: str,
  400. object_id: UUID,
  401. parent_id: UUID,
  402. store_type: StoreType,
  403. description: str | None = None,
  404. weight: float | None = 1.0,
  405. chunk_ids: Optional[list[UUID]] = None,
  406. description_embedding: Optional[list[float] | str] = None,
  407. metadata: Optional[dict[str, Any] | str] = None,
  408. ) -> Relationship:
  409. """Create a new relationship in the specified store."""
  410. table_name = self._get_relationship_table_for_store(store_type)
  411. if isinstance(metadata, str):
  412. with contextlib.suppress(json.JSONDecodeError):
  413. metadata = json.loads(metadata)
  414. if isinstance(description_embedding, list):
  415. description_embedding = str(description_embedding)
  416. query = f"""
  417. INSERT INTO {self._get_table_name(table_name)}
  418. (subject, predicate, object, description, subject_id, object_id,
  419. weight, chunk_ids, parent_id, description_embedding, metadata)
  420. VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
  421. RETURNING id, subject, predicate, object, description, subject_id, object_id, weight, chunk_ids, parent_id, metadata
  422. """
  423. params = [
  424. subject,
  425. predicate,
  426. object,
  427. description,
  428. subject_id,
  429. object_id,
  430. weight,
  431. chunk_ids,
  432. parent_id,
  433. description_embedding,
  434. json.dumps(metadata) if metadata else None,
  435. ]
  436. result = await self.connection_manager.fetchrow_query(
  437. query=query,
  438. params=params,
  439. )
  440. return Relationship(
  441. id=result["id"],
  442. subject=result["subject"],
  443. predicate=result["predicate"],
  444. object=result["object"],
  445. description=result["description"],
  446. subject_id=result["subject_id"],
  447. object_id=result["object_id"],
  448. weight=result["weight"],
  449. chunk_ids=result["chunk_ids"],
  450. parent_id=result["parent_id"],
  451. metadata=result["metadata"],
  452. )
  453. async def get(
  454. self,
  455. parent_id: UUID,
  456. store_type: StoreType,
  457. offset: int,
  458. limit: int,
  459. relationship_ids: Optional[list[UUID]] = None,
  460. entity_names: Optional[list[str]] = None,
  461. relationship_types: Optional[list[str]] = None,
  462. include_metadata: bool = False,
  463. ):
  464. """
  465. Get relationships from the specified store.
  466. Args:
  467. parent_id: UUID of the parent (collection_id or document_id)
  468. store_type: Type of store (graph or document)
  469. offset: Number of records to skip
  470. limit: Maximum number of records to return (-1 for no limit)
  471. relationship_ids: Optional list of specific relationship IDs to retrieve
  472. entity_names: Optional list of entity names to filter by (matches subject or object)
  473. relationship_types: Optional list of relationship types (predicates) to filter by
  474. include_metadata: Whether to include metadata in the response
  475. Returns:
  476. Tuple of (list of relationships, total count)
  477. """
  478. table_name = self._get_relationship_table_for_store(store_type)
  479. conditions = ["parent_id = $1"]
  480. params: list[Any] = [parent_id]
  481. param_index = 2
  482. if relationship_ids:
  483. conditions.append(f"id = ANY(${param_index})")
  484. params.append(relationship_ids)
  485. param_index += 1
  486. if entity_names:
  487. conditions.append(
  488. f"(subject = ANY(${param_index}) OR object = ANY(${param_index}))"
  489. )
  490. params.append(entity_names)
  491. param_index += 1
  492. if relationship_types:
  493. conditions.append(f"predicate = ANY(${param_index})")
  494. params.append(relationship_types)
  495. param_index += 1
  496. select_fields = """
  497. id, subject, predicate, object, description,
  498. subject_id, object_id, weight, chunk_ids,
  499. parent_id
  500. """
  501. if include_metadata:
  502. select_fields += ", metadata"
  503. # Count query
  504. COUNT_QUERY = f"""
  505. SELECT COUNT(*)
  506. FROM {self._get_table_name(table_name)}
  507. WHERE {' AND '.join(conditions)}
  508. """
  509. count_params = params[: param_index - 1]
  510. count = (
  511. await self.connection_manager.fetch_query(
  512. COUNT_QUERY, count_params
  513. )
  514. )[0]["count"]
  515. # Main query
  516. QUERY = f"""
  517. SELECT {select_fields}
  518. FROM {self._get_table_name(table_name)}
  519. WHERE {' AND '.join(conditions)}
  520. ORDER BY created_at
  521. OFFSET ${param_index}
  522. """
  523. params.append(offset)
  524. param_index += 1
  525. if limit != -1:
  526. QUERY += f" LIMIT ${param_index}"
  527. params.append(limit)
  528. rows = await self.connection_manager.fetch_query(QUERY, params)
  529. relationships = []
  530. for row in rows:
  531. relationship_dict = dict(row)
  532. if include_metadata and isinstance(
  533. relationship_dict["metadata"], str
  534. ):
  535. with contextlib.suppress(json.JSONDecodeError):
  536. relationship_dict["metadata"] = json.loads(
  537. relationship_dict["metadata"]
  538. )
  539. elif not include_metadata:
  540. relationship_dict.pop("metadata", None)
  541. relationships.append(Relationship(**relationship_dict))
  542. return relationships, count
  543. async def update(
  544. self,
  545. relationship_id: UUID,
  546. store_type: StoreType,
  547. subject: Optional[str],
  548. subject_id: Optional[UUID],
  549. predicate: Optional[str],
  550. object: Optional[str],
  551. object_id: Optional[UUID],
  552. description: Optional[str],
  553. description_embedding: Optional[list[float] | str],
  554. weight: Optional[float],
  555. metadata: Optional[dict[str, Any] | str],
  556. ) -> Relationship:
  557. """Update multiple relationships in the specified store."""
  558. table_name = self._get_relationship_table_for_store(store_type)
  559. update_fields = []
  560. params: list = []
  561. param_index = 1
  562. if isinstance(metadata, str):
  563. with contextlib.suppress(json.JSONDecodeError):
  564. metadata = json.loads(metadata)
  565. if subject is not None:
  566. update_fields.append(f"subject = ${param_index}")
  567. params.append(subject)
  568. param_index += 1
  569. if subject_id is not None:
  570. update_fields.append(f"subject_id = ${param_index}")
  571. params.append(subject_id)
  572. param_index += 1
  573. if predicate is not None:
  574. update_fields.append(f"predicate = ${param_index}")
  575. params.append(predicate)
  576. param_index += 1
  577. if object is not None:
  578. update_fields.append(f"object = ${param_index}")
  579. params.append(object)
  580. param_index += 1
  581. if object_id is not None:
  582. update_fields.append(f"object_id = ${param_index}")
  583. params.append(object_id)
  584. param_index += 1
  585. if description is not None:
  586. update_fields.append(f"description = ${param_index}")
  587. params.append(description)
  588. param_index += 1
  589. if description_embedding is not None:
  590. update_fields.append(f"description_embedding = ${param_index}")
  591. params.append(description_embedding)
  592. param_index += 1
  593. if weight is not None:
  594. update_fields.append(f"weight = ${param_index}")
  595. params.append(weight)
  596. param_index += 1
  597. if not update_fields:
  598. raise R2RException(status_code=400, message="No fields to update")
  599. update_fields.append("updated_at = NOW()")
  600. params.append(relationship_id)
  601. query = f"""
  602. UPDATE {self._get_table_name(table_name)}
  603. SET {', '.join(update_fields)}
  604. WHERE id = ${param_index}
  605. RETURNING id, subject, predicate, object, description, subject_id, object_id, weight, chunk_ids, parent_id, metadata
  606. """
  607. try:
  608. result = await self.connection_manager.fetchrow_query(
  609. query=query,
  610. params=params,
  611. )
  612. return Relationship(
  613. id=result["id"],
  614. subject=result["subject"],
  615. predicate=result["predicate"],
  616. object=result["object"],
  617. description=result["description"],
  618. subject_id=result["subject_id"],
  619. object_id=result["object_id"],
  620. weight=result["weight"],
  621. chunk_ids=result["chunk_ids"],
  622. parent_id=result["parent_id"],
  623. metadata=result["metadata"],
  624. )
  625. except Exception as e:
  626. raise HTTPException(
  627. status_code=500,
  628. detail=f"An error occurred while updating the relationship: {e}",
  629. ) from e
  630. async def delete(
  631. self,
  632. parent_id: UUID,
  633. relationship_ids: Optional[list[UUID]] = None,
  634. store_type: StoreType = StoreType.GRAPHS,
  635. ) -> None:
  636. """
  637. Delete relationships from the specified store.
  638. If relationship_ids is not provided, deletes all relationships for the given parent_id.
  639. Args:
  640. parent_id: UUID of the parent (collection_id or document_id)
  641. relationship_ids: Optional list of specific relationship IDs to delete
  642. store_type: Type of store (graph or document)
  643. Returns:
  644. List of deleted relationship IDs
  645. Raises:
  646. R2RException: If specific relationships were requested but not all found
  647. """
  648. table_name = self._get_relationship_table_for_store(store_type)
  649. if relationship_ids is None:
  650. QUERY = f"""
  651. DELETE FROM {self._get_table_name(table_name)}
  652. WHERE parent_id = $1
  653. RETURNING id
  654. """
  655. results = await self.connection_manager.fetch_query(
  656. QUERY, [parent_id]
  657. )
  658. else:
  659. QUERY = f"""
  660. DELETE FROM {self._get_table_name(table_name)}
  661. WHERE id = ANY($1) AND parent_id = $2
  662. RETURNING id
  663. """
  664. results = await self.connection_manager.fetch_query(
  665. QUERY, [relationship_ids, parent_id]
  666. )
  667. deleted_ids = [row["id"] for row in results]
  668. if relationship_ids and len(deleted_ids) != len(relationship_ids):
  669. raise R2RException(
  670. f"Some relationships not found in {store_type} store or no permission to delete",
  671. 404,
  672. )
  673. class PostgresCommunitiesHandler(Handler):
  674. def __init__(self, *args: Any, **kwargs: Any) -> None:
  675. self.project_name: str = kwargs.get("project_name") # type: ignore
  676. self.connection_manager: PostgresConnectionManager = kwargs.get("connection_manager") # type: ignore
  677. self.dimension: int = kwargs.get("dimension") # type: ignore
  678. self.quantization_type: VectorQuantizationType = kwargs.get("quantization_type") # type: ignore
  679. async def create_tables(self) -> None:
  680. vector_column_str = _decorate_vector_type(
  681. f"({self.dimension})", self.quantization_type
  682. )
  683. query = f"""
  684. CREATE TABLE IF NOT EXISTS {self._get_table_name("graphs_communities")} (
  685. id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  686. collection_id UUID,
  687. community_id UUID,
  688. level INT,
  689. name TEXT NOT NULL,
  690. summary TEXT NOT NULL,
  691. findings TEXT[],
  692. rating FLOAT,
  693. rating_explanation TEXT,
  694. description_embedding {vector_column_str} NOT NULL,
  695. created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  696. updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
  697. metadata JSONB,
  698. UNIQUE (community_id, level, collection_id)
  699. );"""
  700. await self.connection_manager.execute_query(query)
  701. async def create(
  702. self,
  703. parent_id: UUID,
  704. store_type: StoreType,
  705. name: str,
  706. summary: str,
  707. findings: Optional[list[str]],
  708. rating: Optional[float],
  709. rating_explanation: Optional[str],
  710. description_embedding: Optional[list[float] | str] = None,
  711. ) -> Community:
  712. table_name = "graphs_communities"
  713. if isinstance(description_embedding, list):
  714. description_embedding = str(description_embedding)
  715. query = f"""
  716. INSERT INTO {self._get_table_name(table_name)}
  717. (collection_id, name, summary, findings, rating, rating_explanation, description_embedding)
  718. VALUES ($1, $2, $3, $4, $5, $6, $7)
  719. RETURNING id, collection_id, name, summary, findings, rating, rating_explanation, created_at, updated_at
  720. """
  721. params = [
  722. parent_id,
  723. name,
  724. summary,
  725. findings,
  726. rating,
  727. rating_explanation,
  728. description_embedding,
  729. ]
  730. try:
  731. result = await self.connection_manager.fetchrow_query(
  732. query=query,
  733. params=params,
  734. )
  735. return Community(
  736. id=result["id"],
  737. collection_id=result["collection_id"],
  738. name=result["name"],
  739. summary=result["summary"],
  740. findings=result["findings"],
  741. rating=result["rating"],
  742. rating_explanation=result["rating_explanation"],
  743. created_at=result["created_at"],
  744. updated_at=result["updated_at"],
  745. )
  746. except Exception as e:
  747. raise HTTPException(
  748. status_code=500,
  749. detail=f"An error occurred while creating the community: {e}",
  750. ) from e
  751. async def update(
  752. self,
  753. community_id: UUID,
  754. store_type: StoreType,
  755. name: Optional[str] = None,
  756. summary: Optional[str] = None,
  757. summary_embedding: Optional[list[float] | str] = None,
  758. findings: Optional[list[str]] = None,
  759. rating: Optional[float] = None,
  760. rating_explanation: Optional[str] = None,
  761. ) -> Community:
  762. table_name = "graphs_communities"
  763. update_fields = []
  764. params: list[Any] = []
  765. param_index = 1
  766. if name is not None:
  767. update_fields.append(f"name = ${param_index}")
  768. params.append(name)
  769. param_index += 1
  770. if summary is not None:
  771. update_fields.append(f"summary = ${param_index}")
  772. params.append(summary)
  773. param_index += 1
  774. if summary_embedding is not None:
  775. update_fields.append(f"description_embedding = ${param_index}")
  776. params.append(summary_embedding)
  777. param_index += 1
  778. if findings is not None:
  779. update_fields.append(f"findings = ${param_index}")
  780. params.append(findings)
  781. param_index += 1
  782. if rating is not None:
  783. update_fields.append(f"rating = ${param_index}")
  784. params.append(rating)
  785. param_index += 1
  786. if rating_explanation is not None:
  787. update_fields.append(f"rating_explanation = ${param_index}")
  788. params.append(rating_explanation)
  789. param_index += 1
  790. if not update_fields:
  791. raise R2RException(status_code=400, message="No fields to update")
  792. update_fields.append("updated_at = NOW()")
  793. params.append(community_id)
  794. query = f"""
  795. UPDATE {self._get_table_name(table_name)}
  796. SET {", ".join(update_fields)}
  797. WHERE id = ${param_index}\
  798. RETURNING id, community_id, name, summary, findings, rating, rating_explanation, created_at, updated_at
  799. """
  800. try:
  801. result = await self.connection_manager.fetchrow_query(
  802. query, params
  803. )
  804. return Community(
  805. id=result["id"],
  806. community_id=result["community_id"],
  807. name=result["name"],
  808. summary=result["summary"],
  809. findings=result["findings"],
  810. rating=result["rating"],
  811. rating_explanation=result["rating_explanation"],
  812. created_at=result["created_at"],
  813. updated_at=result["updated_at"],
  814. )
  815. except Exception as e:
  816. raise HTTPException(
  817. status_code=500,
  818. detail=f"An error occurred while updating the community: {e}",
  819. ) from e
  820. async def delete(
  821. self,
  822. parent_id: UUID,
  823. community_id: UUID = None,
  824. ) -> None:
  825. table_name = "graphs_communities"
  826. params = [community_id, parent_id]
  827. # Delete the community
  828. query = f"""
  829. DELETE FROM {self._get_table_name(table_name)}
  830. WHERE id = $1 AND collection_id = $2
  831. """
  832. try:
  833. await self.connection_manager.execute_query(query, params)
  834. except Exception as e:
  835. raise HTTPException(
  836. status_code=500,
  837. detail=f"An error occurred while deleting the community: {e}",
  838. )
  839. async def delete_all_communities(
  840. self,
  841. parent_id: UUID,
  842. ) -> None:
  843. table_name = "graphs_communities"
  844. params = [parent_id]
  845. # Delete all communities for the parent_id
  846. query = f"""
  847. DELETE FROM {self._get_table_name(table_name)}
  848. WHERE collection_id = $1
  849. """
  850. try:
  851. await self.connection_manager.execute_query(query, params)
  852. except Exception as e:
  853. raise HTTPException(
  854. status_code=500,
  855. detail=f"An error occurred while deleting communities: {e}",
  856. )
  857. async def get(
  858. self,
  859. parent_id: UUID,
  860. store_type: StoreType,
  861. offset: int,
  862. limit: int,
  863. community_ids: Optional[list[UUID]] = None,
  864. community_names: Optional[list[str]] = None,
  865. include_embeddings: bool = False,
  866. ):
  867. """Retrieve communities from the specified store."""
  868. # Do we ever want to get communities from document store?
  869. table_name = "graphs_communities"
  870. conditions = ["collection_id = $1"]
  871. params: list[Any] = [parent_id]
  872. param_index = 2
  873. if community_ids:
  874. conditions.append(f"id = ANY(${param_index})")
  875. params.append(community_ids)
  876. param_index += 1
  877. if community_names:
  878. conditions.append(f"name = ANY(${param_index})")
  879. params.append(community_names)
  880. param_index += 1
  881. select_fields = """
  882. id, community_id, name, summary, findings, rating,
  883. rating_explanation, level, created_at, updated_at
  884. """
  885. if include_embeddings:
  886. select_fields += ", description_embedding"
  887. COUNT_QUERY = f"""
  888. SELECT COUNT(*)
  889. FROM {self._get_table_name(table_name)}
  890. WHERE {' AND '.join(conditions)}
  891. """
  892. count = (
  893. await self.connection_manager.fetch_query(
  894. COUNT_QUERY, params[: param_index - 1]
  895. )
  896. )[0]["count"]
  897. QUERY = f"""
  898. SELECT {select_fields}
  899. FROM {self._get_table_name(table_name)}
  900. WHERE {' AND '.join(conditions)}
  901. ORDER BY created_at
  902. OFFSET ${param_index}
  903. """
  904. params.append(offset)
  905. param_index += 1
  906. if limit != -1:
  907. QUERY += f" LIMIT ${param_index}"
  908. params.append(limit)
  909. rows = await self.connection_manager.fetch_query(QUERY, params)
  910. communities = []
  911. for row in rows:
  912. community_dict = dict(row)
  913. communities.append(Community(**community_dict))
  914. return communities, count
  915. class PostgresGraphsHandler(Handler):
  916. """Handler for Knowledge Graph METHODS in PostgreSQL."""
  917. TABLE_NAME = "graphs"
  918. def __init__(
  919. self,
  920. *args: Any,
  921. **kwargs: Any,
  922. ) -> None:
  923. self.project_name: str = kwargs.get("project_name") # type: ignore
  924. self.connection_manager: PostgresConnectionManager = kwargs.get("connection_manager") # type: ignore
  925. self.dimension: int = kwargs.get("dimension") # type: ignore
  926. self.quantization_type: VectorQuantizationType = kwargs.get("quantization_type") # type: ignore
  927. self.collections_handler: PostgresCollectionsHandler = kwargs.get("collections_handler") # type: ignore
  928. self.entities = PostgresEntitiesHandler(*args, **kwargs)
  929. self.relationships = PostgresRelationshipsHandler(*args, **kwargs)
  930. self.communities = PostgresCommunitiesHandler(*args, **kwargs)
  931. self.handlers = [
  932. self.entities,
  933. self.relationships,
  934. self.communities,
  935. ]
  936. import networkx as nx
  937. self.nx = nx
  938. async def create_tables(self) -> None:
  939. """Create the graph tables with mandatory collection_id support."""
  940. QUERY = f"""
  941. CREATE TABLE IF NOT EXISTS {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)} (
  942. id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
  943. collection_id UUID NOT NULL,
  944. name TEXT NOT NULL,
  945. description TEXT,
  946. status TEXT NOT NULL,
  947. document_ids UUID[],
  948. metadata JSONB,
  949. created_at TIMESTAMPTZ DEFAULT NOW(),
  950. updated_at TIMESTAMPTZ DEFAULT NOW()
  951. );
  952. CREATE INDEX IF NOT EXISTS graph_collection_id_idx
  953. ON {self._get_table_name("graphs")} (collection_id);
  954. """
  955. await self.connection_manager.execute_query(QUERY)
  956. for handler in self.handlers:
  957. await handler.create_tables()
  958. async def create(
  959. self,
  960. collection_id: UUID,
  961. name: Optional[str] = None,
  962. description: Optional[str] = None,
  963. status: str = "pending",
  964. ) -> GraphResponse:
  965. """Create a new graph associated with a collection."""
  966. name = name or f"Graph {collection_id}"
  967. description = description or ""
  968. query = f"""
  969. INSERT INTO {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  970. (id, collection_id, name, description, status)
  971. VALUES ($1, $2, $3, $4, $5)
  972. RETURNING id, collection_id, name, description, status, created_at, updated_at, document_ids
  973. """
  974. params = [
  975. collection_id,
  976. collection_id,
  977. name,
  978. description,
  979. status,
  980. ]
  981. try:
  982. result = await self.connection_manager.fetchrow_query(
  983. query=query,
  984. params=params,
  985. )
  986. return GraphResponse(
  987. id=result["id"],
  988. collection_id=result["collection_id"],
  989. name=result["name"],
  990. description=result["description"],
  991. status=result["status"],
  992. created_at=result["created_at"],
  993. updated_at=result["updated_at"],
  994. document_ids=result["document_ids"] or [],
  995. )
  996. except UniqueViolationError:
  997. raise R2RException(
  998. message="Graph with this ID already exists",
  999. status_code=409,
  1000. )
  1001. async def reset(self, parent_id: UUID) -> None:
  1002. """
  1003. Completely reset a graph and all associated data.
  1004. """
  1005. await self.entities.delete(
  1006. parent_id=parent_id, store_type=StoreType.GRAPHS
  1007. )
  1008. await self.relationships.delete(
  1009. parent_id=parent_id, store_type=StoreType.GRAPHS
  1010. )
  1011. await self.communities.delete_all_communities(parent_id=parent_id)
  1012. return
  1013. async def list_graphs(
  1014. self,
  1015. offset: int,
  1016. limit: int,
  1017. # filter_user_ids: Optional[list[UUID]] = None,
  1018. filter_graph_ids: Optional[list[UUID]] = None,
  1019. filter_collection_id: Optional[UUID] = None,
  1020. ) -> dict[str, list[GraphResponse] | int]:
  1021. conditions = []
  1022. params: list[Any] = []
  1023. param_index = 1
  1024. if filter_graph_ids:
  1025. conditions.append(f"id = ANY(${param_index})")
  1026. params.append(filter_graph_ids)
  1027. param_index += 1
  1028. # if filter_user_ids:
  1029. # conditions.append(f"user_id = ANY(${param_index})")
  1030. # params.append(filter_user_ids)
  1031. # param_index += 1
  1032. if filter_collection_id:
  1033. conditions.append(f"collection_id = ${param_index}")
  1034. params.append(filter_collection_id)
  1035. param_index += 1
  1036. where_clause = (
  1037. f"WHERE {' AND '.join(conditions)}" if conditions else ""
  1038. )
  1039. query = f"""
  1040. WITH RankedGraphs AS (
  1041. SELECT
  1042. id, collection_id, name, description, status, created_at, updated_at, document_ids,
  1043. COUNT(*) OVER() as total_entries,
  1044. ROW_NUMBER() OVER (PARTITION BY collection_id ORDER BY created_at DESC) as rn
  1045. FROM {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  1046. {where_clause}
  1047. )
  1048. SELECT * FROM RankedGraphs
  1049. WHERE rn = 1
  1050. ORDER BY created_at DESC
  1051. OFFSET ${param_index} LIMIT ${param_index + 1}
  1052. """
  1053. params.extend([offset, limit])
  1054. try:
  1055. results = await self.connection_manager.fetch_query(query, params)
  1056. if not results:
  1057. return {"results": [], "total_entries": 0}
  1058. total_entries = results[0]["total_entries"] if results else 0
  1059. graphs = [
  1060. GraphResponse(
  1061. id=row["id"],
  1062. document_ids=row["document_ids"] or [],
  1063. name=row["name"],
  1064. collection_id=row["collection_id"],
  1065. description=row["description"],
  1066. status=row["status"],
  1067. created_at=row["created_at"],
  1068. updated_at=row["updated_at"],
  1069. )
  1070. for row in results
  1071. ]
  1072. return {"results": graphs, "total_entries": total_entries}
  1073. except Exception as e:
  1074. raise HTTPException(
  1075. status_code=500,
  1076. detail=f"An error occurred while fetching graphs: {e}",
  1077. ) from e
  1078. async def get(
  1079. self, offset: int, limit: int, graph_id: Optional[UUID] = None
  1080. ):
  1081. if graph_id is None:
  1082. params = [offset, limit]
  1083. QUERY = f"""
  1084. SELECT * FROM {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  1085. OFFSET $1 LIMIT $2
  1086. """
  1087. ret = await self.connection_manager.fetch_query(QUERY, params)
  1088. COUNT_QUERY = f"""
  1089. SELECT COUNT(*) FROM {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  1090. """
  1091. count = (await self.connection_manager.fetch_query(COUNT_QUERY))[
  1092. 0
  1093. ]["count"]
  1094. return {
  1095. "results": [Graph(**row) for row in ret],
  1096. "total_entries": count,
  1097. }
  1098. else:
  1099. QUERY = f"""
  1100. SELECT * FROM {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)} WHERE id = $1
  1101. """
  1102. params = [graph_id] # type: ignore
  1103. return {
  1104. "results": [
  1105. Graph(
  1106. **await self.connection_manager.fetchrow_query(
  1107. QUERY, params
  1108. )
  1109. )
  1110. ]
  1111. }
  1112. async def add_documents(self, id: UUID, document_ids: list[UUID]) -> bool:
  1113. """
  1114. Add documents to the graph by copying their entities and relationships.
  1115. """
  1116. # Copy entities from document_entity to graphs_entities
  1117. ENTITY_COPY_QUERY = f"""
  1118. INSERT INTO {self._get_table_name("graphs_entities")} (
  1119. name, category, description, parent_id, description_embedding,
  1120. chunk_ids, metadata
  1121. )
  1122. SELECT
  1123. name, category, description, $1, description_embedding,
  1124. chunk_ids, metadata
  1125. FROM {self._get_table_name("documents_entities")}
  1126. WHERE parent_id = ANY($2)
  1127. """
  1128. await self.connection_manager.execute_query(
  1129. ENTITY_COPY_QUERY, [id, document_ids]
  1130. )
  1131. # Copy relationships from documents_relationships to graphs_relationships
  1132. RELATIONSHIP_COPY_QUERY = f"""
  1133. INSERT INTO {self._get_table_name("graphs_relationships")} (
  1134. subject, predicate, object, description, subject_id, object_id,
  1135. weight, chunk_ids, parent_id, metadata, description_embedding
  1136. )
  1137. SELECT
  1138. subject, predicate, object, description, subject_id, object_id,
  1139. weight, chunk_ids, $1, metadata, description_embedding
  1140. FROM {self._get_table_name("documents_relationships")}
  1141. WHERE parent_id = ANY($2)
  1142. """
  1143. await self.connection_manager.execute_query(
  1144. RELATIONSHIP_COPY_QUERY, [id, document_ids]
  1145. )
  1146. # Add document_ids to the graph
  1147. UPDATE_GRAPH_QUERY = f"""
  1148. UPDATE {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  1149. SET document_ids = array_cat(
  1150. CASE
  1151. WHEN document_ids IS NULL THEN ARRAY[]::uuid[]
  1152. ELSE document_ids
  1153. END,
  1154. $2::uuid[]
  1155. )
  1156. WHERE id = $1
  1157. """
  1158. await self.connection_manager.execute_query(
  1159. UPDATE_GRAPH_QUERY, [id, document_ids]
  1160. )
  1161. return True
  1162. async def update(
  1163. self,
  1164. collection_id: UUID,
  1165. name: Optional[str] = None,
  1166. description: Optional[str] = None,
  1167. ) -> GraphResponse:
  1168. """Update an existing graph."""
  1169. update_fields = []
  1170. params: list = []
  1171. param_index = 1
  1172. if name is not None:
  1173. update_fields.append(f"name = ${param_index}")
  1174. params.append(name)
  1175. param_index += 1
  1176. if description is not None:
  1177. update_fields.append(f"description = ${param_index}")
  1178. params.append(description)
  1179. param_index += 1
  1180. if not update_fields:
  1181. raise R2RException(status_code=400, message="No fields to update")
  1182. update_fields.append("updated_at = NOW()")
  1183. params.append(collection_id)
  1184. query = f"""
  1185. UPDATE {self._get_table_name(PostgresGraphsHandler.TABLE_NAME)}
  1186. SET {', '.join(update_fields)}
  1187. WHERE id = ${param_index}
  1188. RETURNING id, name, description, status, created_at, updated_at, collection_id, document_ids
  1189. """
  1190. try:
  1191. result = await self.connection_manager.fetchrow_query(
  1192. query, params
  1193. )
  1194. if not result:
  1195. raise R2RException(status_code=404, message="Graph not found")
  1196. return GraphResponse(
  1197. id=result["id"],
  1198. collection_id=result["collection_id"],
  1199. name=result["name"],
  1200. description=result["description"],
  1201. status=result["status"],
  1202. created_at=result["created_at"],
  1203. document_ids=result["document_ids"] or [],
  1204. updated_at=result["updated_at"],
  1205. )
  1206. except Exception as e:
  1207. raise HTTPException(
  1208. status_code=500,
  1209. detail=f"An error occurred while updating the graph: {e}",
  1210. ) from e
  1211. async def get_creation_estimate(
  1212. self,
  1213. graph_creation_settings: KGCreationSettings,
  1214. document_id: Optional[UUID] = None,
  1215. collection_id: Optional[UUID] = None,
  1216. ):
  1217. """Get the estimated cost and time for creating a KG."""
  1218. if bool(document_id) ^ bool(collection_id) is False:
  1219. raise ValueError(
  1220. "Exactly one of document_id or collection_id must be provided."
  1221. )
  1222. # todo: harmonize the document_id and id fields: postgres table contains document_id, but other places use id.
  1223. document_ids = (
  1224. [document_id]
  1225. if document_id
  1226. else [
  1227. doc.id for doc in (await self.collections_handler.documents_in_collection(collection_id, offset=0, limit=-1))["results"] # type: ignore
  1228. ]
  1229. )
  1230. chunk_counts = await self.connection_manager.fetch_query(
  1231. f"SELECT document_id, COUNT(*) as chunk_count FROM {self._get_table_name('vectors')} "
  1232. f"WHERE document_id = ANY($1) GROUP BY document_id",
  1233. [document_ids],
  1234. )
  1235. total_chunks = (
  1236. sum(doc["chunk_count"] for doc in chunk_counts)
  1237. // graph_creation_settings.chunk_merge_count
  1238. )
  1239. estimated_entities = (total_chunks * 10, total_chunks * 20)
  1240. estimated_relationships = (
  1241. int(estimated_entities[0] * 1.25),
  1242. int(estimated_entities[1] * 1.5),
  1243. )
  1244. estimated_llm_calls = (
  1245. total_chunks * 2 + estimated_entities[0],
  1246. total_chunks * 2 + estimated_entities[1],
  1247. )
  1248. total_in_out_tokens = tuple(
  1249. 2000 * calls // 1000000 for calls in estimated_llm_calls
  1250. )
  1251. cost_per_million = llm_cost_per_million_tokens(
  1252. graph_creation_settings.generation_config.model
  1253. )
  1254. estimated_cost = tuple(
  1255. tokens * cost_per_million for tokens in total_in_out_tokens
  1256. )
  1257. total_time_in_minutes = tuple(
  1258. tokens * 10 / 60 for tokens in total_in_out_tokens
  1259. )
  1260. return {
  1261. "message": 'Ran Graph Creation Estimate (not the actual run). Note that these are estimated ranges, actual values may vary. To run the KG creation process, run `extract-triples` with `--run` in the cli, or `run_type="run"` in the client.',
  1262. "document_count": len(document_ids),
  1263. "number_of_jobs_created": len(document_ids) + 1,
  1264. "total_chunks": total_chunks,
  1265. "estimated_entities": _get_str_estimation_output(
  1266. estimated_entities
  1267. ),
  1268. "estimated_relationships": _get_str_estimation_output(
  1269. estimated_relationships
  1270. ),
  1271. "estimated_llm_calls": _get_str_estimation_output(
  1272. estimated_llm_calls
  1273. ),
  1274. "estimated_total_in_out_tokens_in_millions": _get_str_estimation_output(
  1275. total_in_out_tokens
  1276. ),
  1277. "estimated_cost_in_usd": _get_str_estimation_output(
  1278. estimated_cost
  1279. ),
  1280. "estimated_total_time_in_minutes": "Depends on your API key tier. Accurate estimate coming soon. Rough estimate: "
  1281. + _get_str_estimation_output(total_time_in_minutes),
  1282. }
  1283. async def get_enrichment_estimate(
  1284. self,
  1285. collection_id: UUID | None = None,
  1286. graph_id: UUID | None = None,
  1287. graph_enrichment_settings: KGEnrichmentSettings = KGEnrichmentSettings(),
  1288. ):
  1289. """Get the estimated cost and time for enriching a KG."""
  1290. if collection_id is not None:
  1291. document_ids = [
  1292. doc.id
  1293. for doc in (
  1294. await self.collections_handler.documents_in_collection(collection_id, offset=0, limit=-1) # type: ignore
  1295. )["results"]
  1296. ]
  1297. # Get entity and relationship counts
  1298. entity_count = (
  1299. await self.connection_manager.fetch_query(
  1300. f"SELECT COUNT(*) FROM {self._get_table_name('entity')} WHERE document_id = ANY($1);",
  1301. [document_ids],
  1302. )
  1303. )[0]["count"]
  1304. if not entity_count:
  1305. raise ValueError(
  1306. "No entities found in the graph. Please run `extract-triples` first."
  1307. )
  1308. relationship_count = (
  1309. await self.connection_manager.fetch_query(
  1310. f"""SELECT COUNT(*) FROM {self._get_table_name("documents_relationships")} WHERE document_id = ANY($1);""",
  1311. [document_ids],
  1312. )
  1313. )[0]["count"]
  1314. else:
  1315. entity_count = (
  1316. await self.connection_manager.fetch_query(
  1317. f"SELECT COUNT(*) FROM {self._get_table_name('entity')} WHERE $1 = ANY(graph_ids);",
  1318. [graph_id],
  1319. )
  1320. )[0]["count"]
  1321. if not entity_count:
  1322. raise ValueError(
  1323. "No entities found in the graph. Please run `extract-triples` first."
  1324. )
  1325. relationship_count = (
  1326. await self.connection_manager.fetch_query(
  1327. f"SELECT COUNT(*) FROM {self._get_table_name('relationship')} WHERE $1 = ANY(graph_ids);",
  1328. [graph_id],
  1329. )
  1330. )[0]["count"]
  1331. # Calculate estimates
  1332. estimated_llm_calls = (entity_count // 10, entity_count // 5)
  1333. tokens_in_millions = tuple(
  1334. 2000 * calls / 1000000 for calls in estimated_llm_calls
  1335. )
  1336. cost_per_million = llm_cost_per_million_tokens(
  1337. graph_enrichment_settings.generation_config.model # type: ignore
  1338. )
  1339. estimated_cost = tuple(
  1340. tokens * cost_per_million for tokens in tokens_in_millions
  1341. )
  1342. estimated_time = tuple(
  1343. tokens * 10 / 60 for tokens in tokens_in_millions
  1344. )
  1345. return {
  1346. "message": 'Ran Graph Enrichment Estimate (not the actual run). Note that these are estimated ranges, actual values may vary. To run the KG enrichment process, run `build-communities` with `--run` in the cli, or `run_type="run"` in the client.',
  1347. "total_entities": entity_count,
  1348. "total_relationships": relationship_count,
  1349. "estimated_llm_calls": _get_str_estimation_output(
  1350. estimated_llm_calls
  1351. ),
  1352. "estimated_total_in_out_tokens_in_millions": _get_str_estimation_output(
  1353. tokens_in_millions
  1354. ),
  1355. "estimated_cost_in_usd": _get_str_estimation_output(
  1356. estimated_cost
  1357. ),
  1358. "estimated_total_time_in_minutes": "Depends on your API key tier. Accurate estimate coming soon. Rough estimate: "
  1359. + _get_str_estimation_output(estimated_time),
  1360. }
  1361. async def get_deduplication_estimate(
  1362. self,
  1363. collection_id: UUID,
  1364. kg_deduplication_settings: KGEntityDeduplicationSettings,
  1365. ):
  1366. """Get the estimated cost and time for deduplicating entities in a KG."""
  1367. try:
  1368. query = f"""
  1369. SELECT name, count(name)
  1370. FROM {self._get_table_name("entity")}
  1371. WHERE document_id = ANY(
  1372. SELECT document_id FROM {self._get_table_name("documents")}
  1373. WHERE $1 = ANY(collection_ids)
  1374. )
  1375. GROUP BY name
  1376. HAVING count(name) >= 5
  1377. """
  1378. entities = await self.connection_manager.fetch_query(
  1379. query, [collection_id]
  1380. )
  1381. num_entities = len(entities)
  1382. estimated_llm_calls = (num_entities, num_entities)
  1383. tokens_in_millions = (
  1384. estimated_llm_calls[0] * 1000 / 1000000,
  1385. estimated_llm_calls[1] * 5000 / 1000000,
  1386. )
  1387. cost_per_million = llm_cost_per_million_tokens(
  1388. kg_deduplication_settings.generation_config.model
  1389. )
  1390. estimated_cost = (
  1391. tokens_in_millions[0] * cost_per_million,
  1392. tokens_in_millions[1] * cost_per_million,
  1393. )
  1394. estimated_time = (
  1395. tokens_in_millions[0] * 10 / 60,
  1396. tokens_in_millions[1] * 10 / 60,
  1397. )
  1398. return {
  1399. "message": "Ran Deduplication Estimate (not the actual run). Note that these are estimated ranges.",
  1400. "num_entities": num_entities,
  1401. "estimated_llm_calls": _get_str_estimation_output(
  1402. estimated_llm_calls
  1403. ),
  1404. "estimated_total_in_out_tokens_in_millions": _get_str_estimation_output(
  1405. tokens_in_millions
  1406. ),
  1407. "estimated_cost_in_usd": _get_str_estimation_output(
  1408. estimated_cost
  1409. ),
  1410. "estimated_total_time_in_minutes": _get_str_estimation_output(
  1411. estimated_time
  1412. ),
  1413. }
  1414. except UndefinedTableError:
  1415. raise R2RException(
  1416. "Entity embedding table not found. Please run `extract-triples` first.",
  1417. 404,
  1418. )
  1419. except Exception as e:
  1420. logger.error(f"Error in get_deduplication_estimate: {str(e)}")
  1421. raise HTTPException(
  1422. 500, "Error fetching deduplication estimate."
  1423. ) from e
  1424. async def get_entities(
  1425. self,
  1426. parent_id: UUID,
  1427. offset: int,
  1428. limit: int,
  1429. entity_ids: Optional[list[UUID]] = None,
  1430. entity_names: Optional[list[str]] = None,
  1431. include_embeddings: bool = False,
  1432. ) -> tuple[list[Entity], int]:
  1433. """
  1434. Get entities for a graph.
  1435. Args:
  1436. offset: Number of records to skip
  1437. limit: Maximum number of records to return (-1 for no limit)
  1438. parent_id: UUID of the collection
  1439. entity_ids: Optional list of entity IDs to filter by
  1440. entity_names: Optional list of entity names to filter by
  1441. include_embeddings: Whether to include embeddings in the response
  1442. Returns:
  1443. Tuple of (list of entities, total count)
  1444. """
  1445. conditions = ["parent_id = $1"]
  1446. params: list[Any] = [parent_id]
  1447. param_index = 2
  1448. if entity_ids:
  1449. conditions.append(f"id = ANY(${param_index})")
  1450. params.append(entity_ids)
  1451. param_index += 1
  1452. if entity_names:
  1453. conditions.append(f"name = ANY(${param_index})")
  1454. params.append(entity_names)
  1455. param_index += 1
  1456. # Count query - uses the same conditions but without offset/limit
  1457. COUNT_QUERY = f"""
  1458. SELECT COUNT(*)
  1459. FROM {self._get_table_name("graphs_entities")}
  1460. WHERE {' AND '.join(conditions)}
  1461. """
  1462. count = (
  1463. await self.connection_manager.fetch_query(COUNT_QUERY, params)
  1464. )[0]["count"]
  1465. # Define base columns to select
  1466. select_fields = """
  1467. id, name, category, description, parent_id,
  1468. chunk_ids, metadata
  1469. """
  1470. if include_embeddings:
  1471. select_fields += ", description_embedding"
  1472. # Main query for fetching entities with pagination
  1473. QUERY = f"""
  1474. SELECT {select_fields}
  1475. FROM {self._get_table_name("graphs_entities")}
  1476. WHERE {' AND '.join(conditions)}
  1477. ORDER BY created_at
  1478. OFFSET ${param_index}
  1479. """
  1480. params.append(offset)
  1481. param_index += 1
  1482. if limit != -1:
  1483. QUERY += f" LIMIT ${param_index}"
  1484. params.append(limit)
  1485. rows = await self.connection_manager.fetch_query(QUERY, params)
  1486. entities = []
  1487. for row in rows:
  1488. entity_dict = dict(row)
  1489. if isinstance(entity_dict["metadata"], str):
  1490. with contextlib.suppress(json.JSONDecodeError):
  1491. entity_dict["metadata"] = json.loads(
  1492. entity_dict["metadata"]
  1493. )
  1494. entities.append(Entity(**entity_dict))
  1495. return entities, count
  1496. async def get_relationships(
  1497. self,
  1498. parent_id: UUID,
  1499. offset: int,
  1500. limit: int,
  1501. relationship_ids: Optional[list[UUID]] = None,
  1502. relationship_types: Optional[list[str]] = None,
  1503. include_embeddings: bool = False,
  1504. ) -> tuple[list[Relationship], int]:
  1505. """
  1506. Get relationships for a graph.
  1507. Args:
  1508. parent_id: UUID of the graph
  1509. offset: Number of records to skip
  1510. limit: Maximum number of records to return (-1 for no limit)
  1511. relationship_ids: Optional list of relationship IDs to filter by
  1512. relationship_types: Optional list of relationship types to filter by
  1513. include_metadata: Whether to include metadata in the response
  1514. Returns:
  1515. Tuple of (list of relationships, total count)
  1516. """
  1517. conditions = ["parent_id = $1"]
  1518. params: list[Any] = [parent_id]
  1519. param_index = 2
  1520. if relationship_ids:
  1521. conditions.append(f"id = ANY(${param_index})")
  1522. params.append(relationship_ids)
  1523. param_index += 1
  1524. if relationship_types:
  1525. conditions.append(f"predicate = ANY(${param_index})")
  1526. params.append(relationship_types)
  1527. param_index += 1
  1528. # Count query - uses the same conditions but without offset/limit
  1529. COUNT_QUERY = f"""
  1530. SELECT COUNT(*)
  1531. FROM {self._get_table_name("graphs_relationships")}
  1532. WHERE {' AND '.join(conditions)}
  1533. """
  1534. count = (
  1535. await self.connection_manager.fetch_query(COUNT_QUERY, params)
  1536. )[0]["count"]
  1537. # Define base columns to select
  1538. select_fields = """
  1539. id, subject, predicate, object, weight, chunk_ids, parent_id, metadata
  1540. """
  1541. if include_embeddings:
  1542. select_fields += ", description_embedding"
  1543. # Main query for fetching relationships with pagination
  1544. QUERY = f"""
  1545. SELECT {select_fields}
  1546. FROM {self._get_table_name("graphs_relationships")}
  1547. WHERE {' AND '.join(conditions)}
  1548. ORDER BY created_at
  1549. OFFSET ${param_index}
  1550. """
  1551. params.append(offset)
  1552. param_index += 1
  1553. if limit != -1:
  1554. QUERY += f" LIMIT ${param_index}"
  1555. params.append(limit)
  1556. rows = await self.connection_manager.fetch_query(QUERY, params)
  1557. relationships = []
  1558. for row in rows:
  1559. relationship_dict = dict(row)
  1560. if isinstance(relationship_dict["metadata"], str):
  1561. with contextlib.suppress(json.JSONDecodeError):
  1562. relationship_dict["metadata"] = json.loads(
  1563. relationship_dict["metadata"]
  1564. )
  1565. relationships.append(Relationship(**relationship_dict))
  1566. return relationships, count
  1567. async def add_entities(
  1568. self,
  1569. entities: list[Entity],
  1570. table_name: str,
  1571. conflict_columns: list[str] = [],
  1572. ) -> asyncpg.Record:
  1573. """
  1574. Upsert entities into the entities_raw table. These are raw entities extracted from the document.
  1575. Args:
  1576. entities: list[Entity]: list of entities to upsert
  1577. collection_name: str: name of the collection
  1578. Returns:
  1579. result: asyncpg.Record: result of the upsert operation
  1580. """
  1581. cleaned_entities = []
  1582. for entity in entities:
  1583. entity_dict = entity.to_dict()
  1584. entity_dict["chunk_ids"] = (
  1585. entity_dict["chunk_ids"]
  1586. if entity_dict.get("chunk_ids")
  1587. else []
  1588. )
  1589. entity_dict["description_embedding"] = (
  1590. str(entity_dict["description_embedding"])
  1591. if entity_dict.get("description_embedding") # type: ignore
  1592. else None
  1593. )
  1594. cleaned_entities.append(entity_dict)
  1595. return await _add_objects(
  1596. objects=cleaned_entities,
  1597. full_table_name=self._get_table_name(table_name),
  1598. connection_manager=self.connection_manager,
  1599. conflict_columns=conflict_columns,
  1600. )
  1601. async def get_all_relationships(
  1602. self,
  1603. collection_id: UUID | None,
  1604. graph_id: UUID | None,
  1605. document_ids: Optional[list[UUID]] = None,
  1606. ) -> list[Relationship]:
  1607. QUERY = f"""
  1608. SELECT id, subject, predicate, weight, object, parent_id FROM {self._get_table_name("graphs_relationships")} WHERE parent_id = ANY($1)
  1609. """
  1610. relationships = await self.connection_manager.fetch_query(
  1611. QUERY, [collection_id]
  1612. )
  1613. return [Relationship(**relationship) for relationship in relationships]
  1614. async def has_document(self, graph_id: UUID, document_id: UUID) -> bool:
  1615. """
  1616. Check if a document exists in the graph's document_ids array.
  1617. Args:
  1618. graph_id (UUID): ID of the graph to check
  1619. document_id (UUID): ID of the document to look for
  1620. Returns:
  1621. bool: True if document exists in graph, False otherwise
  1622. Raises:
  1623. R2RException: If graph not found
  1624. """
  1625. QUERY = f"""
  1626. SELECT EXISTS (
  1627. SELECT 1
  1628. FROM {self._get_table_name("graphs")}
  1629. WHERE id = $1
  1630. AND document_ids IS NOT NULL
  1631. AND $2 = ANY(document_ids)
  1632. ) as exists;
  1633. """
  1634. result = await self.connection_manager.fetchrow_query(
  1635. QUERY, [graph_id, document_id]
  1636. )
  1637. if result is None:
  1638. raise R2RException(f"Graph {graph_id} not found", 404)
  1639. return result["exists"]
  1640. async def get_communities(
  1641. self,
  1642. parent_id: UUID,
  1643. offset: int,
  1644. limit: int,
  1645. community_ids: Optional[list[UUID]] = None,
  1646. include_embeddings: bool = False,
  1647. ) -> tuple[list[Community], int]:
  1648. """
  1649. Get communities for a graph.
  1650. Args:
  1651. collection_id: UUID of the collection
  1652. offset: Number of records to skip
  1653. limit: Maximum number of records to return (-1 for no limit)
  1654. community_ids: Optional list of community IDs to filter by
  1655. include_embeddings: Whether to include embeddings in the response
  1656. Returns:
  1657. Tuple of (list of communities, total count)
  1658. """
  1659. conditions = ["collection_id = $1"]
  1660. params: list[Any] = [parent_id]
  1661. param_index = 2
  1662. if community_ids:
  1663. conditions.append(f"id = ANY(${param_index})")
  1664. params.append(community_ids)
  1665. param_index += 1
  1666. select_fields = """
  1667. id, collection_id, name, summary, findings, rating, rating_explanation
  1668. """
  1669. if include_embeddings:
  1670. select_fields += ", description_embedding"
  1671. COUNT_QUERY = f"""
  1672. SELECT COUNT(*)
  1673. FROM {self._get_table_name("graphs_communities")}
  1674. WHERE {' AND '.join(conditions)}
  1675. """
  1676. count = (
  1677. await self.connection_manager.fetch_query(COUNT_QUERY, params)
  1678. )[0]["count"]
  1679. QUERY = f"""
  1680. SELECT {select_fields}
  1681. FROM {self._get_table_name("graphs_communities")}
  1682. WHERE {' AND '.join(conditions)}
  1683. ORDER BY created_at
  1684. OFFSET ${param_index}
  1685. """
  1686. params.append(offset)
  1687. param_index += 1
  1688. if limit != -1:
  1689. QUERY += f" LIMIT ${param_index}"
  1690. params.append(limit)
  1691. rows = await self.connection_manager.fetch_query(QUERY, params)
  1692. communities = []
  1693. for row in rows:
  1694. community_dict = dict(row)
  1695. communities.append(Community(**community_dict))
  1696. return communities, count
  1697. async def add_community(self, community: Community) -> None:
  1698. # TODO: Fix in the short term.
  1699. # we need to do this because postgres insert needs to be a string
  1700. community.description_embedding = str(community.description_embedding) # type: ignore[assignment]
  1701. non_null_attrs = {
  1702. k: v for k, v in community.__dict__.items() if v is not None
  1703. }
  1704. columns = ", ".join(non_null_attrs.keys())
  1705. placeholders = ", ".join(f"${i+1}" for i in range(len(non_null_attrs)))
  1706. conflict_columns = ", ".join(
  1707. [f"{k} = EXCLUDED.{k}" for k in non_null_attrs]
  1708. )
  1709. QUERY = f"""
  1710. INSERT INTO {self._get_table_name("graphs_communities")} ({columns})
  1711. VALUES ({placeholders})
  1712. ON CONFLICT (community_id, level, collection_id) DO UPDATE SET
  1713. {conflict_columns}
  1714. """
  1715. await self.connection_manager.execute_many(
  1716. QUERY, [tuple(non_null_attrs.values())]
  1717. )
  1718. # async def delete(self, collection_id: UUID, cascade: bool = False) -> None:
  1719. async def delete(self, collection_id: UUID) -> None:
  1720. graphs = await self.get(graph_id=collection_id, offset=0, limit=-1)
  1721. if len(graphs["results"]) == 0:
  1722. raise R2RException(
  1723. message=f"Graph not found for collection {collection_id}",
  1724. status_code=404,
  1725. )
  1726. await self.reset(collection_id)
  1727. # set status to PENDING for this collection.
  1728. QUERY = f"""
  1729. UPDATE {self._get_table_name("collections")} SET graph_cluster_status = $1 WHERE id = $2
  1730. """
  1731. await self.connection_manager.execute_query(
  1732. QUERY, [KGExtractionStatus.PENDING, collection_id]
  1733. )
  1734. # Delete the graph
  1735. QUERY = f"""
  1736. DELETE FROM {self._get_table_name("graphs")} WHERE collection_id = $1
  1737. """
  1738. # if cascade:
  1739. # documents = []
  1740. # document_response = (
  1741. # await self.collections_handler.documents_in_collection(
  1742. # offset=0,
  1743. # limit=100,
  1744. # collection_id=collection_id,
  1745. # )
  1746. # )["results"]
  1747. # documents.extend(document_response)
  1748. # document_ids = [doc.id for doc in documents]
  1749. # for document_id in document_ids:
  1750. # self.entities.delete(
  1751. # parent_id=document_id, store_type=StoreType.DOCUMENTS
  1752. # )
  1753. # self.relationships.delete(
  1754. # parent_id=document_id, store_type=StoreType.DOCUMENTS
  1755. # )
  1756. # # setting the extraction status to PENDING for the documents in this collection.
  1757. # QUERY = f"""
  1758. # UPDATE {self._get_table_name("documents")} SET extraction_status = $1 WHERE $2::uuid = ANY(collection_ids)
  1759. # """
  1760. # await self.connection_manager.execute_query(
  1761. # QUERY, [KGExtractionStatus.PENDING, collection_id]
  1762. # )
  1763. async def perform_graph_clustering(
  1764. self,
  1765. collection_id: UUID,
  1766. leiden_params: dict[str, Any],
  1767. clustering_mode: str,
  1768. ) -> Tuple[int, Any]:
  1769. """
  1770. Calls the external clustering service to cluster the KG.
  1771. """
  1772. offset = 0
  1773. page_size = 1000
  1774. all_relationships = []
  1775. while True:
  1776. relationships, count = await self.relationships.get(
  1777. parent_id=collection_id,
  1778. store_type=StoreType.GRAPHS,
  1779. offset=offset,
  1780. limit=page_size,
  1781. )
  1782. if not relationships:
  1783. break
  1784. all_relationships.extend(relationships)
  1785. offset += len(relationships)
  1786. if offset >= count:
  1787. break
  1788. relationship_ids_cache = await self._get_relationship_ids_cache(
  1789. all_relationships
  1790. )
  1791. logger.info(
  1792. f"Clustering over {len(all_relationships)} relationships for {collection_id} with settings: {leiden_params}"
  1793. )
  1794. return await self._cluster_and_add_community_info(
  1795. relationships=all_relationships,
  1796. relationship_ids_cache=relationship_ids_cache,
  1797. leiden_params=leiden_params,
  1798. collection_id=collection_id,
  1799. clustering_mode=clustering_mode,
  1800. )
  1801. async def _call_clustering_service(
  1802. self, relationships: list[Relationship], leiden_params: dict[str, Any]
  1803. ) -> list[dict]:
  1804. """
  1805. Calls the external Graspologic clustering service, sending relationships and parameters.
  1806. Expects a response with 'communities' field.
  1807. """
  1808. # Convert relationships to a JSON-friendly format
  1809. rel_data = []
  1810. for r in relationships:
  1811. rel_data.append(
  1812. {
  1813. "id": str(r.id),
  1814. "subject": r.subject,
  1815. "object": r.object,
  1816. "weight": r.weight if r.weight is not None else 1.0,
  1817. }
  1818. )
  1819. endpoint = os.environ.get("CLUSTERING_SERVICE_URL")
  1820. if not endpoint:
  1821. raise ValueError("CLUSTERING_SERVICE_URL not set.")
  1822. url = f"{endpoint}/cluster"
  1823. payload = {"relationships": rel_data, "leiden_params": leiden_params}
  1824. async with httpx.AsyncClient() as client:
  1825. response = await client.post(url, json=payload, timeout=3600)
  1826. response.raise_for_status()
  1827. data = response.json()
  1828. communities = data.get("communities", [])
  1829. return communities
  1830. async def _create_graph_and_cluster(
  1831. self,
  1832. relationships: list[Relationship],
  1833. leiden_params: dict[str, Any],
  1834. clustering_mode: str = "remote",
  1835. ) -> Any:
  1836. """
  1837. Create a graph and cluster it. If clustering_mode='local', use hierarchical_leiden locally.
  1838. If clustering_mode='remote', call the external service.
  1839. """
  1840. if clustering_mode == "remote":
  1841. logger.info("Sending request to external clustering service...")
  1842. communities = await self._call_clustering_service(
  1843. relationships, leiden_params
  1844. )
  1845. logger.info("Received communities from clustering service.")
  1846. return communities
  1847. else:
  1848. # Local mode: run hierarchical_leiden directly
  1849. G = self.nx.Graph()
  1850. for relationship in relationships:
  1851. G.add_edge(
  1852. relationship.subject,
  1853. relationship.object,
  1854. weight=relationship.weight,
  1855. id=relationship.id,
  1856. )
  1857. logger.info(
  1858. f"Graph has {len(G.nodes)} nodes and {len(G.edges)} edges"
  1859. )
  1860. return await self._compute_leiden_communities(G, leiden_params)
  1861. async def _cluster_and_add_community_info(
  1862. self,
  1863. relationships: list[Relationship],
  1864. relationship_ids_cache: dict[str, list[int]],
  1865. leiden_params: dict[str, Any],
  1866. collection_id: Optional[UUID] = None,
  1867. clustering_mode: str = "local",
  1868. ) -> Tuple[int, Any]:
  1869. # clear if there is any old information
  1870. conditions = []
  1871. if collection_id is not None:
  1872. conditions.append("collection_id = $1")
  1873. await asyncio.sleep(0.1)
  1874. start_time = time.time()
  1875. logger.info(f"Creating graph and clustering for {collection_id}")
  1876. hierarchical_communities = await self._create_graph_and_cluster(
  1877. relationships=relationships,
  1878. leiden_params=leiden_params,
  1879. clustering_mode=clustering_mode,
  1880. )
  1881. logger.info(
  1882. f"Computing Leiden communities completed, time {time.time() - start_time:.2f} seconds."
  1883. )
  1884. def relationship_ids(node: str) -> list[int]:
  1885. return relationship_ids_cache.get(node, [])
  1886. logger.info(
  1887. f"Cached {len(relationship_ids_cache)} relationship ids, time {time.time() - start_time:.2f} seconds."
  1888. )
  1889. # If remote: hierarchical_communities is a list of dicts like:
  1890. # [{"node": str, "cluster": int, "level": int}, ...]
  1891. # If local: hierarchical_communities is the returned structure from hierarchical_leiden (list of named tuples)
  1892. if clustering_mode == "remote":
  1893. if not hierarchical_communities:
  1894. num_communities = 0
  1895. else:
  1896. num_communities = (
  1897. max(item["cluster"] for item in hierarchical_communities)
  1898. + 1
  1899. )
  1900. else:
  1901. # Local mode: hierarchical_communities returned by hierarchical_leiden
  1902. # According to the original code, it's likely a list of items with .cluster attribute
  1903. if not hierarchical_communities:
  1904. num_communities = 0
  1905. else:
  1906. num_communities = (
  1907. max(item.cluster for item in hierarchical_communities) + 1
  1908. )
  1909. logger.info(
  1910. f"Generated {num_communities} communities, time {time.time() - start_time:.2f} seconds."
  1911. )
  1912. return num_communities, hierarchical_communities
  1913. async def _get_relationship_ids_cache(
  1914. self, relationships: list[Relationship]
  1915. ) -> dict[str, list[int]]:
  1916. relationship_ids_cache: dict[str, list[int]] = {}
  1917. for relationship in relationships:
  1918. if relationship.subject is not None:
  1919. relationship_ids_cache.setdefault(relationship.subject, [])
  1920. if relationship.id is not None:
  1921. relationship_ids_cache[relationship.subject].append(
  1922. relationship.id
  1923. )
  1924. if relationship.object is not None:
  1925. relationship_ids_cache.setdefault(relationship.object, [])
  1926. if relationship.id is not None:
  1927. relationship_ids_cache[relationship.object].append(
  1928. relationship.id
  1929. )
  1930. return relationship_ids_cache
  1931. async def get_entity_map(
  1932. self, offset: int, limit: int, document_id: UUID
  1933. ) -> dict[str, dict[str, list[dict[str, Any]]]]:
  1934. QUERY1 = f"""
  1935. WITH entities_list AS (
  1936. SELECT DISTINCT name
  1937. FROM {self._get_table_name("documents_entities")}
  1938. WHERE parent_id = $1
  1939. ORDER BY name ASC
  1940. LIMIT {limit} OFFSET {offset}
  1941. )
  1942. SELECT e.name, e.description, e.category,
  1943. (SELECT array_agg(DISTINCT x) FROM unnest(e.chunk_ids) x) AS chunk_ids,
  1944. e.parent_id
  1945. FROM {self._get_table_name("documents_entities")} e
  1946. JOIN entities_list el ON e.name = el.name
  1947. GROUP BY e.name, e.description, e.category, e.chunk_ids, e.parent_id
  1948. ORDER BY e.name;"""
  1949. entities_list = await self.connection_manager.fetch_query(
  1950. QUERY1, [document_id]
  1951. )
  1952. entities_list = [Entity(**entity) for entity in entities_list]
  1953. QUERY2 = f"""
  1954. WITH entities_list AS (
  1955. SELECT DISTINCT name
  1956. FROM {self._get_table_name("documents_entities")}
  1957. WHERE parent_id = $1
  1958. ORDER BY name ASC
  1959. LIMIT {limit} OFFSET {offset}
  1960. )
  1961. SELECT DISTINCT t.subject, t.predicate, t.object, t.weight, t.description,
  1962. (SELECT array_agg(DISTINCT x) FROM unnest(t.chunk_ids) x) AS chunk_ids, t.parent_id
  1963. FROM {self._get_table_name("documents_relationships")} t
  1964. JOIN entities_list el ON t.subject = el.name
  1965. ORDER BY t.subject, t.predicate, t.object;
  1966. """
  1967. relationships_list = await self.connection_manager.fetch_query(
  1968. QUERY2, [document_id]
  1969. )
  1970. relationships_list = [
  1971. Relationship(**relationship) for relationship in relationships_list
  1972. ]
  1973. entity_map: dict[str, dict[str, list[Any]]] = {}
  1974. for entity in entities_list:
  1975. if entity.name not in entity_map:
  1976. entity_map[entity.name] = {"entities": [], "relationships": []}
  1977. entity_map[entity.name]["entities"].append(entity)
  1978. for relationship in relationships_list:
  1979. if relationship.subject in entity_map:
  1980. entity_map[relationship.subject]["relationships"].append(
  1981. relationship
  1982. )
  1983. if relationship.object in entity_map:
  1984. entity_map[relationship.object]["relationships"].append(
  1985. relationship
  1986. )
  1987. return entity_map
  1988. async def graph_search(
  1989. self, query: str, **kwargs: Any
  1990. ) -> AsyncGenerator[Any, None]:
  1991. """
  1992. Perform semantic search with similarity scores while maintaining exact same structure.
  1993. """
  1994. query_embedding = kwargs.get("query_embedding", None)
  1995. if query_embedding is None:
  1996. raise ValueError(
  1997. "query_embedding must be provided for semantic search"
  1998. )
  1999. search_type = kwargs.get(
  2000. "search_type", "entities"
  2001. ) # entities | relationships | communities
  2002. embedding_type = kwargs.get("embedding_type", "description_embedding")
  2003. property_names = kwargs.get("property_names", ["name", "description"])
  2004. # Add metadata if not present
  2005. if "metadata" not in property_names:
  2006. property_names.append("metadata")
  2007. filters = kwargs.get("filters", {})
  2008. limit = kwargs.get("limit", 10)
  2009. use_fulltext_search = kwargs.get("use_fulltext_search", True)
  2010. use_hybrid_search = kwargs.get("use_hybrid_search", True)
  2011. if use_hybrid_search or use_fulltext_search:
  2012. logger.warning(
  2013. "Hybrid and fulltext search not supported for graph search, ignoring."
  2014. )
  2015. table_name = f"graphs_{search_type}"
  2016. property_names_str = ", ".join(property_names)
  2017. # Build the WHERE clause from filters
  2018. params: list[str | int | bytes] = [
  2019. json.dumps(query_embedding),
  2020. limit,
  2021. ]
  2022. conditions_clause = self._build_filters(filters, params, search_type)
  2023. where_clause = (
  2024. f"WHERE {conditions_clause}" if conditions_clause else ""
  2025. )
  2026. # Construct the query
  2027. # Note: For vector similarity, we use <=> for distance. The smaller the number, the more similar.
  2028. # We'll convert that to similarity_score by doing (1 - distance).
  2029. QUERY = f"""
  2030. SELECT
  2031. {property_names_str},
  2032. ({embedding_type} <=> $1) as similarity_score
  2033. FROM {self._get_table_name(table_name)}
  2034. {where_clause}
  2035. ORDER BY {embedding_type} <=> $1
  2036. LIMIT $2;
  2037. """
  2038. results = await self.connection_manager.fetch_query(
  2039. QUERY, tuple(params)
  2040. )
  2041. for result in results:
  2042. output = {
  2043. prop: result[prop] for prop in property_names if prop in result
  2044. }
  2045. output["similarity_score"] = 1 - float(result["similarity_score"])
  2046. yield output
  2047. def _build_filters(
  2048. self, filter_dict: dict, parameters: list[Any], search_type: str
  2049. ) -> str:
  2050. """
  2051. Build a WHERE clause from a nested filter dictionary for the graph search.
  2052. For communities we use collection_id as primary key filter; for entities/relationships we use parent_id.
  2053. """
  2054. # Determine primary identifier column depending on search_type
  2055. # communities: use collection_id
  2056. # entities/relationships: use parent_id
  2057. base_id_column = (
  2058. "collection_id" if search_type == "communities" else "parent_id"
  2059. )
  2060. def parse_condition(key: str, value: Any) -> str:
  2061. # This function returns a single condition (string) or empty if no valid condition.
  2062. # Supported keys:
  2063. # - base_id_column (collection_id or parent_id)
  2064. # - metadata fields: metadata.some_field
  2065. # Supported ops: $eq, $ne, $lt, $lte, $gt, $gte, $in, $contains
  2066. if key == base_id_column:
  2067. # e.g. {"collection_id": {"$eq": "<some-uuid>"}}
  2068. if isinstance(value, dict):
  2069. op, clause = next(iter(value.items()))
  2070. if op == "$eq":
  2071. parameters.append(str(clause))
  2072. return f"{base_id_column} = ${len(parameters)}::uuid"
  2073. elif op == "$in":
  2074. # $in expects a list of UUIDs
  2075. parameters.append([str(x) for x in clause])
  2076. return f"{base_id_column} = ANY(${len(parameters)}::uuid[])"
  2077. else:
  2078. # direct equality?
  2079. parameters.append(str(value))
  2080. return f"{base_id_column} = ${len(parameters)}::uuid"
  2081. elif key.startswith("metadata."):
  2082. # Handle metadata filters
  2083. # Example: {"metadata.some_key": {"$eq": "value"}}
  2084. field = key.split("metadata.")[1]
  2085. if isinstance(value, dict):
  2086. op, clause = next(iter(value.items()))
  2087. if op == "$eq":
  2088. parameters.append(clause)
  2089. return f"(metadata->>'{field}') = ${len(parameters)}"
  2090. elif op == "$ne":
  2091. parameters.append(clause)
  2092. return f"(metadata->>'{field}') != ${len(parameters)}"
  2093. elif op == "$lt":
  2094. parameters.append(clause)
  2095. return f"(metadata->>'{field}')::float < ${len(parameters)}::float"
  2096. elif op == "$lte":
  2097. parameters.append(clause)
  2098. return f"(metadata->>'{field}')::float <= ${len(parameters)}::float"
  2099. elif op == "$gt":
  2100. parameters.append(clause)
  2101. return f"(metadata->>'{field}')::float > ${len(parameters)}::float"
  2102. elif op == "$gte":
  2103. parameters.append(clause)
  2104. return f"(metadata->>'{field}')::float >= ${len(parameters)}::float"
  2105. elif op == "$in":
  2106. # Ensure clause is a list
  2107. if not isinstance(clause, list):
  2108. raise Exception(
  2109. "argument to $in filter must be a list"
  2110. )
  2111. # Append the Python list as a parameter; many drivers can convert Python lists to arrays
  2112. parameters.append(clause)
  2113. # Cast the parameter to a text array type
  2114. return f"(metadata->>'{key}')::text = ANY(${len(parameters)}::text[])"
  2115. # elif op == "$in":
  2116. # # For $in, we assume an array of values and check if the field is in that set.
  2117. # # Note: This is simplistic, adjust as needed.
  2118. # parameters.append(clause)
  2119. # # convert field to text and check membership
  2120. # return f"(metadata->>'{field}') = ANY(SELECT jsonb_array_elements_text(${len(parameters)}::jsonb))"
  2121. elif op == "$contains":
  2122. # $contains for metadata likely means metadata @> clause in JSON.
  2123. # If clause is dict or list, we use json containment.
  2124. parameters.append(json.dumps(clause))
  2125. return f"metadata @> ${len(parameters)}::jsonb"
  2126. else:
  2127. # direct equality
  2128. parameters.append(value)
  2129. return f"(metadata->>'{field}') = ${len(parameters)}"
  2130. # Add additional conditions for other columns if needed
  2131. # If key not recognized, return empty so it doesn't break query
  2132. return ""
  2133. def parse_filter(fd: dict) -> str:
  2134. filter_conditions = []
  2135. for k, v in fd.items():
  2136. if k == "$and":
  2137. and_parts = [parse_filter(sub) for sub in v if sub]
  2138. # Remove empty strings
  2139. and_parts = [x for x in and_parts if x.strip()]
  2140. if and_parts:
  2141. filter_conditions.append(
  2142. f"({' AND '.join(and_parts)})"
  2143. )
  2144. elif k == "$or":
  2145. or_parts = [parse_filter(sub) for sub in v if sub]
  2146. # Remove empty strings
  2147. or_parts = [x for x in or_parts if x.strip()]
  2148. if or_parts:
  2149. filter_conditions.append(f"({' OR '.join(or_parts)})")
  2150. else:
  2151. # Regular condition
  2152. c = parse_condition(k, v)
  2153. if c and c.strip():
  2154. filter_conditions.append(c)
  2155. if not filter_conditions:
  2156. return ""
  2157. if len(filter_conditions) == 1:
  2158. return filter_conditions[0]
  2159. return " AND ".join(filter_conditions)
  2160. return parse_filter(filter_dict)
  2161. async def _compute_leiden_communities(
  2162. self,
  2163. graph: Any,
  2164. leiden_params: dict[str, Any],
  2165. ) -> Any:
  2166. """Compute Leiden communities."""
  2167. try:
  2168. from graspologic.partition import hierarchical_leiden
  2169. if "random_seed" not in leiden_params:
  2170. leiden_params["random_seed"] = (
  2171. 7272 # add seed to control randomness
  2172. )
  2173. start_time = time.time()
  2174. logger.info(
  2175. f"Running Leiden clustering with params: {leiden_params}"
  2176. )
  2177. community_mapping = hierarchical_leiden(graph, **leiden_params)
  2178. logger.info(
  2179. f"Leiden clustering completed in {time.time() - start_time:.2f} seconds."
  2180. )
  2181. return community_mapping
  2182. except ImportError as e:
  2183. raise ImportError("Please install the graspologic package.") from e
  2184. async def get_existing_document_entity_chunk_ids(
  2185. self, document_id: UUID
  2186. ) -> list[str]:
  2187. QUERY = f"""
  2188. SELECT DISTINCT unnest(chunk_ids) AS chunk_id FROM {self._get_table_name("documents_entities")} WHERE parent_id = $1
  2189. """
  2190. return [
  2191. item["chunk_id"]
  2192. for item in await self.connection_manager.fetch_query(
  2193. QUERY, [document_id]
  2194. )
  2195. ]
  2196. async def get_entity_count(
  2197. self,
  2198. collection_id: Optional[UUID] = None,
  2199. document_id: Optional[UUID] = None,
  2200. distinct: bool = False,
  2201. entity_table_name: str = "entity",
  2202. ) -> int:
  2203. if collection_id is None and document_id is None:
  2204. raise ValueError(
  2205. "Either collection_id or document_id must be provided."
  2206. )
  2207. conditions = ["parent_id = $1"]
  2208. params = [str(document_id)]
  2209. count_value = "DISTINCT name" if distinct else "*"
  2210. QUERY = f"""
  2211. SELECT COUNT({count_value}) FROM {self._get_table_name(entity_table_name)}
  2212. WHERE {" AND ".join(conditions)}
  2213. """
  2214. return (await self.connection_manager.fetch_query(QUERY, params))[0][
  2215. "count"
  2216. ]
  2217. async def update_entity_descriptions(self, entities: list[Entity]):
  2218. query = f"""
  2219. UPDATE {self._get_table_name("graphs_entities")}
  2220. SET description = $3, description_embedding = $4
  2221. WHERE name = $1 AND graph_id = $2
  2222. """
  2223. inputs = [
  2224. (
  2225. entity.name,
  2226. entity.parent_id,
  2227. entity.description,
  2228. entity.description_embedding,
  2229. )
  2230. for entity in entities
  2231. ]
  2232. await self.connection_manager.execute_many(query, inputs) # type: ignore
  2233. def _json_serialize(obj):
  2234. if isinstance(obj, UUID):
  2235. return str(obj)
  2236. elif isinstance(obj, (datetime.datetime, datetime.date)):
  2237. return obj.isoformat()
  2238. raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
  2239. async def _add_objects(
  2240. objects: list[dict],
  2241. full_table_name: str,
  2242. connection_manager: PostgresConnectionManager,
  2243. conflict_columns: list[str] = [],
  2244. exclude_metadata: list[str] = [],
  2245. ) -> list[UUID]:
  2246. """
  2247. Bulk insert objects into the specified table using jsonb_to_recordset.
  2248. """
  2249. # Exclude specified metadata and prepare data
  2250. cleaned_objects = []
  2251. for obj in objects:
  2252. cleaned_obj = {
  2253. k: v
  2254. for k, v in obj.items()
  2255. if k not in exclude_metadata and v is not None
  2256. }
  2257. cleaned_objects.append(cleaned_obj)
  2258. # Serialize the list of objects to JSON
  2259. json_data = json.dumps(cleaned_objects, default=_json_serialize)
  2260. # Prepare the column definitions for jsonb_to_recordset
  2261. columns = cleaned_objects[0].keys()
  2262. column_defs = []
  2263. for col in columns:
  2264. # Map Python types to PostgreSQL types
  2265. sample_value = cleaned_objects[0][col]
  2266. if "embedding" in col:
  2267. pg_type = "vector"
  2268. elif "chunk_ids" in col or "document_ids" in col or "graph_ids" in col:
  2269. pg_type = "uuid[]"
  2270. elif col == "id" or "_id" in col:
  2271. pg_type = "uuid"
  2272. elif isinstance(sample_value, str):
  2273. pg_type = "text"
  2274. elif isinstance(sample_value, UUID):
  2275. pg_type = "uuid"
  2276. elif isinstance(sample_value, (int, float)):
  2277. pg_type = "numeric"
  2278. elif isinstance(sample_value, list) and all(
  2279. isinstance(x, UUID) for x in sample_value
  2280. ):
  2281. pg_type = "uuid[]"
  2282. elif isinstance(sample_value, list):
  2283. pg_type = "jsonb"
  2284. elif isinstance(sample_value, dict):
  2285. pg_type = "jsonb"
  2286. elif isinstance(sample_value, bool):
  2287. pg_type = "boolean"
  2288. elif isinstance(sample_value, (datetime.datetime, datetime.date)):
  2289. pg_type = "timestamp"
  2290. else:
  2291. raise TypeError(
  2292. f"Unsupported data type for column '{col}': {type(sample_value)}"
  2293. )
  2294. column_defs.append(f"{col} {pg_type}")
  2295. columns_str = ", ".join(columns)
  2296. column_defs_str = ", ".join(column_defs)
  2297. if conflict_columns:
  2298. conflict_columns_str = ", ".join(conflict_columns)
  2299. update_columns_str = ", ".join(
  2300. f"{col}=EXCLUDED.{col}"
  2301. for col in columns
  2302. if col not in conflict_columns
  2303. )
  2304. on_conflict_clause = f"ON CONFLICT ({conflict_columns_str}) DO UPDATE SET {update_columns_str}"
  2305. else:
  2306. on_conflict_clause = ""
  2307. QUERY = f"""
  2308. INSERT INTO {full_table_name} ({columns_str})
  2309. SELECT {columns_str}
  2310. FROM jsonb_to_recordset($1::jsonb)
  2311. AS x({column_defs_str})
  2312. {on_conflict_clause}
  2313. RETURNING id;
  2314. """
  2315. # Execute the query
  2316. result = await connection_manager.fetch_query(QUERY, [json_data])
  2317. # Extract and return the IDs
  2318. return [record["id"] for record in result]