|
| 1 | +"""HTTP adapter for the on-premise Graphiti bridge service.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import json |
| 6 | +from types import SimpleNamespace |
| 7 | +from typing import Any |
| 8 | +from urllib.error import HTTPError |
| 9 | +from urllib.parse import quote, urlencode |
| 10 | +from urllib.request import Request, urlopen |
| 11 | + |
| 12 | +from .base import GraphMemoryAdapter |
| 13 | +from ..config import Config |
| 14 | + |
| 15 | + |
| 16 | +class GraphitiBridgeGraphMemoryAdapter(GraphMemoryAdapter): |
| 17 | + """Graph memory adapter backed by the local Graphiti bridge service.""" |
| 18 | + |
| 19 | + def __init__(self, api_key: str | None = None, base_url: str | None = None): |
| 20 | + self.base_url = (base_url or Config.GRAPHITI_BRIDGE_URL).rstrip("/") |
| 21 | + self._node_graph_index: dict[str, str] = {} |
| 22 | + |
| 23 | + @property |
| 24 | + def raw_client(self) -> None: |
| 25 | + return None |
| 26 | + |
| 27 | + def create_graph(self, graph_id: str, name: str, description: str) -> Any: |
| 28 | + return self._to_namespace(self._request("POST", "/graphs", {"graph_id": graph_id, "name": name, "description": description})) |
| 29 | + |
| 30 | + def set_ontology(self, graph_id: str, ontology: dict[str, Any]) -> Any: |
| 31 | + return self._request("POST", f"/graphs/{quote(graph_id)}/ontology", ontology) |
| 32 | + |
| 33 | + def add_text_batch(self, graph_id: str, chunks: list[str]) -> list[Any]: |
| 34 | + data = self._request("POST", f"/graphs/{quote(graph_id)}/episodes", {"chunks": chunks}) |
| 35 | + return [self._episode(item) for item in data.get("episodes", [])] |
| 36 | + |
| 37 | + def add_text(self, graph_id: str, text: str) -> Any: |
| 38 | + data = self._request("POST", f"/graphs/{quote(graph_id)}/episodes", {"text": text}) |
| 39 | + episodes = data.get("episodes", []) |
| 40 | + return self._episode(episodes[0]) if episodes else self._episode({"uuid": None, "processed": True}) |
| 41 | + |
| 42 | + def get_episode(self, episode_uuid: str) -> Any: |
| 43 | + return self._episode({"uuid": episode_uuid, "processed": True}) |
| 44 | + |
| 45 | + def get_all_nodes(self, graph_id: str) -> list[Any]: |
| 46 | + data = self._request("GET", f"/graphs/{quote(graph_id)}/nodes") |
| 47 | + nodes = [self._node(item) for item in data.get("nodes", [])] |
| 48 | + for node in nodes: |
| 49 | + self._node_graph_index[node.uuid_] = graph_id |
| 50 | + return nodes |
| 51 | + |
| 52 | + def get_all_edges(self, graph_id: str) -> list[Any]: |
| 53 | + data = self._request("GET", f"/graphs/{quote(graph_id)}/edges") |
| 54 | + return [self._edge(item) for item in data.get("edges", [])] |
| 55 | + |
| 56 | + def search(self, graph_id: str, query: str, limit: int = 10, scope: str = "edges", **kwargs: Any) -> Any: |
| 57 | + data = self._request("POST", f"/graphs/{quote(graph_id)}/search", {"query": query, "limit": limit, "scope": scope}) |
| 58 | + nodes = [self._node(item) for item in data.get("nodes", [])] |
| 59 | + for node in nodes: |
| 60 | + self._node_graph_index[node.uuid_] = graph_id |
| 61 | + return SimpleNamespace(edges=[self._edge(item) for item in data.get("edges", [])], nodes=nodes) |
| 62 | + |
| 63 | + def get_node(self, node_uuid: str) -> Any: |
| 64 | + graph_id = self._node_graph_index.get(node_uuid) |
| 65 | + if not graph_id: |
| 66 | + return None |
| 67 | + query = urlencode({"graph_id": graph_id}) |
| 68 | + data = self._request("GET", f"/nodes/{quote(node_uuid)}?{query}") |
| 69 | + node = data.get("node") |
| 70 | + return self._node(node) if node else None |
| 71 | + |
| 72 | + def get_node_edges(self, node_uuid: str) -> list[Any]: |
| 73 | + graph_id = self._node_graph_index.get(node_uuid) |
| 74 | + if not graph_id: |
| 75 | + return [] |
| 76 | + query = urlencode({"graph_id": graph_id}) |
| 77 | + data = self._request("GET", f"/nodes/{quote(node_uuid)}/edges?{query}") |
| 78 | + return [self._edge(item) for item in data.get("edges", [])] |
| 79 | + |
| 80 | + def delete_graph(self, graph_id: str) -> Any: |
| 81 | + return self._request("DELETE", f"/graphs/{quote(graph_id)}") |
| 82 | + |
| 83 | + def _request(self, method: str, path: str, payload: dict[str, Any] | None = None) -> dict[str, Any]: |
| 84 | + body = None if payload is None else json.dumps(payload).encode("utf-8") |
| 85 | + headers = {"Content-Type": "application/json"} |
| 86 | + req = Request(f"{self.base_url}{path}", data=body, headers=headers, method=method) |
| 87 | + try: |
| 88 | + with urlopen(req, timeout=120) as response: |
| 89 | + raw = response.read().decode("utf-8") |
| 90 | + return json.loads(raw) if raw else {} |
| 91 | + except HTTPError as exc: |
| 92 | + error_body = exc.read().decode("utf-8", errors="replace") |
| 93 | + raise RuntimeError(f"Graphiti bridge request failed: {exc.code} {error_body}") from exc |
| 94 | + |
| 95 | + def _episode(self, data: dict[str, Any]) -> Any: |
| 96 | + uuid = data.get("uuid") or data.get("uuid_") |
| 97 | + return SimpleNamespace(uuid_=uuid, uuid=uuid, processed=data.get("processed", True)) |
| 98 | + |
| 99 | + def _node(self, data: dict[str, Any]) -> Any: |
| 100 | + uuid = data.get("uuid") or data.get("uuid_") or "" |
| 101 | + return SimpleNamespace( |
| 102 | + uuid_=uuid, |
| 103 | + uuid=uuid, |
| 104 | + name=data.get("name") or "", |
| 105 | + labels=data.get("labels") or [], |
| 106 | + summary=data.get("summary") or "", |
| 107 | + attributes=data.get("attributes") or {}, |
| 108 | + created_at=data.get("created_at"), |
| 109 | + ) |
| 110 | + |
| 111 | + def _edge(self, data: dict[str, Any]) -> Any: |
| 112 | + uuid = data.get("uuid") or data.get("uuid_") or "" |
| 113 | + return SimpleNamespace( |
| 114 | + uuid_=uuid, |
| 115 | + uuid=uuid, |
| 116 | + name=data.get("name") or "", |
| 117 | + fact=data.get("fact") or "", |
| 118 | + source_node_uuid=data.get("source_node_uuid") or "", |
| 119 | + target_node_uuid=data.get("target_node_uuid") or "", |
| 120 | + attributes=data.get("attributes") or {}, |
| 121 | + created_at=data.get("created_at"), |
| 122 | + valid_at=data.get("valid_at"), |
| 123 | + invalid_at=data.get("invalid_at"), |
| 124 | + expired_at=data.get("expired_at"), |
| 125 | + ) |
| 126 | + |
| 127 | + def _to_namespace(self, data: dict[str, Any]) -> Any: |
| 128 | + return SimpleNamespace(**data) |
0 commit comments