-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathtest_spanner_graph_retriever.py
More file actions
273 lines (248 loc) · 9.64 KB
/
test_spanner_graph_retriever.py
File metadata and controls
273 lines (248 loc) · 9.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import random
import string
import pytest
from google.cloud import spanner
from langchain_community.graphs.graph_document import GraphDocument, Node, Relationship
from langchain_core.documents import Document
from langchain_google_vertexai import ChatVertexAI, VertexAIEmbeddings
from langchain_google_spanner.graph_retriever import (
SpannerGraphTextToGQLRetriever,
SpannerGraphVectorContextRetriever,
)
from langchain_google_spanner.graph_store import SpannerGraphStore
project_id = os.environ["PROJECT_ID"]
instance_id = os.environ["INSTANCE_ID"]
database_id = os.environ["GOOGLE_DATABASE"]
def random_string(num_char=3):
return "".join(random.choice(string.ascii_letters) for _ in range(num_char))
def get_llm():
llm = ChatVertexAI(
model="gemini-2.0-flash-001",
temperature=0,
)
return llm
def get_embedding():
embeddings = VertexAIEmbeddings(model_name="text-embedding-004")
return embeddings
def get_spanner_graph():
suffix = random_string(num_char=3)
graph_name = "test_graph{}".format(suffix)
graph = SpannerGraphStore(
instance_id=instance_id,
database_id=database_id,
graph_name=graph_name,
client=spanner.Client(project=project_id),
)
return graph, suffix
def load_data(graph: SpannerGraphStore, suffix: str):
type_suffix = "_" + suffix
graph_documents = [
GraphDocument(
nodes=[
Node(
id="Elias Thorne",
type="Person" + type_suffix,
properties={
"name": "Elias Thorne",
"description": "lived in the desert",
},
),
Node(
id="Zephyr",
type="Animal" + type_suffix,
properties={"name": "Zephyr", "description": "pet falcon"},
),
Node(
id="Elara",
type="Person" + type_suffix,
properties={
"name": "Elara",
"description": "resided in the capital city",
},
),
Node(id="Desert", type="Location" + type_suffix, properties={}),
Node(id="Capital City", type="Location" + type_suffix, properties={}),
],
relationships=[
Relationship(
source=Node(
id="Elias Thorne", type="Person" + type_suffix, properties={}
),
target=Node(
id="Desert", type="Location" + type_suffix, properties={}
),
type="LivesIn",
properties={},
),
Relationship(
source=Node(
id="Elias Thorne", type="Person" + type_suffix, properties={}
),
target=Node(
id="Zephyr", type="Animal" + type_suffix, properties={}
),
type="Owns",
properties={},
),
Relationship(
source=Node(id="Elara", type="Person" + type_suffix, properties={}),
target=Node(
id="Capital City", type="Location" + type_suffix, properties={}
),
type="LivesIn",
properties={},
),
Relationship(
source=Node(
id="Elias Thorne", type="Person" + type_suffix, properties={}
),
target=Node(id="Elara", type="Person" + type_suffix, properties={}),
type="Sibling",
properties={},
),
],
source=Document(
metadata={},
page_content=(
"Elias Thorne lived in the desert. He was a skilled craftsman"
" who worked with sandstone. Elias had a pet falcon named"
" Zephyr. His sister, Elara, resided in the capital city and"
" ran a spice shop. They rarely met due to the distance."
),
),
)
]
# Add embeddings to the graph documents for Person nodes
embedding_service = get_embedding()
for graph_document in graph_documents:
for node in graph_document.nodes:
if node.type == "Person{}".format(type_suffix):
if "description" in node.properties:
node.properties["desc_embedding"] = embedding_service.embed_query(
node.properties["description"]
)
graph.add_graph_documents(graph_documents)
graph.refresh_schema()
class TestRetriever:
@pytest.fixture(scope="module")
def setup_db_load_data(self):
graph, suffix = get_spanner_graph()
load_data(graph, suffix)
yield graph, suffix
# teardown
graph.cleanup()
def test_spanner_graph_gql_retriever(self, setup_db_load_data):
graph, suffix = setup_db_load_data
retriever = SpannerGraphTextToGQLRetriever.from_params(
graph_store=graph,
llm=get_llm(),
)
response = retriever.invoke("Where does Elias Thorne's sibling live?")
assert len(response) == 1
assert "Capital City" in response[0].page_content
def test_spanner_graph_semantic_gql_retriever(self, setup_db_load_data):
graph, suffix = setup_db_load_data
suffix = "_" + suffix
retriever = SpannerGraphTextToGQLRetriever.from_params(
graph_store=graph,
llm=get_llm(),
embedding_service=get_embedding(),
)
retriever.add_example(
"Where does Sam Smith live?",
"""
GRAPH QAGraph
MATCH (n:Person{suffix} {{name: "Sam Smith"}})-[:LivesIn]->(l:Location{suffix})
RETURN l.id AS location_id
""".format(
suffix=suffix
),
)
retriever.add_example(
"Where does Sam Smith's sibling live?",
"""
GRAPH QAGraph
MATCH (n:Person{suffix} {{name: "Sam Smith"}})-[:Sibling]->(m:Person{suffix})-[:LivesIn]->(l:Location{suffix})
RETURN l.id AS location_id
""".format(
suffix=suffix
),
)
response = retriever.invoke("Where does Elias Thorne's sibling live?")
assert response == [
Document(metadata={}, page_content='{"location_id": "Capital City"}')
]
def test_spanner_graph_vector_node_retriever_error(self, setup_db_load_data):
with pytest.raises(ValueError):
graph, suffix = setup_db_load_data
suffix = "_" + suffix
SpannerGraphVectorContextRetriever.from_params(
graph_store=graph,
embedding_service=get_embedding(),
label_expr="Person{}".format(suffix),
embeddings_column="desc_embedding",
k=1,
)
def test_spanner_graph_vector_node_retriever(self, setup_db_load_data):
graph, suffix = setup_db_load_data
suffix = "_" + suffix
retriever = SpannerGraphVectorContextRetriever.from_params(
graph_store=graph,
embedding_service=get_embedding(),
label_expr="Person{}".format(suffix),
return_properties_list=["name"],
embeddings_column="desc_embedding",
top_k=1,
k=1,
)
response = retriever.invoke("Who lives in desert?")
assert len(response) == 1
assert "Elias Thorne" in response[0].page_content
def test_spanner_graph_vector_node_retriever_2(self, setup_db_load_data):
graph, suffix = setup_db_load_data
suffix = "_" + suffix
retriever = SpannerGraphVectorContextRetriever.from_params(
graph_store=graph,
embedding_service=get_embedding(),
label_expr="Person{}".format(suffix),
expand_by_hops=1,
embeddings_column="desc_embedding",
top_k=1,
k=10,
)
response = retriever.invoke(
"What do you know about the person who lives in desert?"
)
assert len(response) == 4
assert "Elias Thorne" in response[0].page_content
def test_spanner_graph_vector_node_retriever_0_hops(self, setup_db_load_data):
graph, suffix = setup_db_load_data
suffix = "_" + suffix
retriever = SpannerGraphVectorContextRetriever.from_params(
graph_store=graph,
embedding_service=get_embedding(),
label_expr="Person{}".format(suffix),
expand_by_hops=0,
embeddings_column="desc_embedding",
top_k=1,
k=10,
)
response = retriever.invoke(
"What do you know about the person who lives in desert?"
)
assert len(response) == 1
assert "Elias Thorne" in response[0].page_content