-
Notifications
You must be signed in to change notification settings - Fork 4.6k
/
test_base.py
238 lines (206 loc) · 7.89 KB
/
test_base.py
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
"""Test knowledge graph index."""
from typing import Any, Dict, List, Tuple
from unittest.mock import patch
import pytest
from llama_index.legacy.embeddings.base import BaseEmbedding
from llama_index.legacy.indices.knowledge_graph.base import KnowledgeGraphIndex
from llama_index.legacy.schema import Document, TextNode
from llama_index.legacy.service_context import ServiceContext
from tests.mock_utils.mock_prompts import (
MOCK_KG_TRIPLET_EXTRACT_PROMPT,
MOCK_QUERY_KEYWORD_EXTRACT_PROMPT,
)
class MockEmbedding(BaseEmbedding):
@classmethod
def class_name(cls) -> str:
return "MockEmbedding"
async def _aget_query_embedding(self, query: str) -> List[float]:
del query
return [0, 0, 1, 0, 0]
async def _aget_text_embedding(self, text: str) -> List[float]:
# assume dimensions are 4
if text == "('foo', 'is', 'bar')":
return [1, 0, 0, 0]
elif text == "('hello', 'is not', 'world')":
return [0, 1, 0, 0]
elif text == "('Jane', 'is mother of', 'Bob')":
return [0, 0, 1, 0]
elif text == "foo":
return [0, 0, 0, 1]
else:
raise ValueError("Invalid text for `mock_get_text_embedding`.")
def _get_text_embedding(self, text: str) -> List[float]:
"""Mock get text embedding."""
# assume dimensions are 4
if text == "('foo', 'is', 'bar')":
return [1, 0, 0, 0]
elif text == "('hello', 'is not', 'world')":
return [0, 1, 0, 0]
elif text == "('Jane', 'is mother of', 'Bob')":
return [0, 0, 1, 0]
elif text == "foo":
return [0, 0, 0, 1]
else:
raise ValueError("Invalid text for `mock_get_text_embedding`.")
def _get_query_embedding(self, query: str) -> List[float]:
"""Mock get query embedding."""
del query
return [0, 0, 1, 0, 0]
@pytest.fixture()
def struct_kwargs() -> Tuple[Dict, Dict]:
"""Index kwargs."""
index_kwargs = {
"kg_triple_extract_template": MOCK_KG_TRIPLET_EXTRACT_PROMPT,
}
query_kwargs = {
"query_keyword_extract_template": MOCK_QUERY_KEYWORD_EXTRACT_PROMPT,
}
return index_kwargs, query_kwargs
def mock_extract_triplets(text: str) -> List[Tuple[str, str, str]]:
"""Mock extract triplets."""
lines = text.split("\n")
triplets: List[Tuple[str, str, str]] = []
for line in lines:
tokens = line[1:-1].split(",")
tokens = [t.strip() for t in tokens]
subj, pred, obj = tokens
triplets.append((subj, pred, obj))
return triplets
@patch.object(
KnowledgeGraphIndex, "_extract_triplets", side_effect=mock_extract_triplets
)
def test_build_kg_manual(
_patch_extract_triplets: Any,
mock_service_context: ServiceContext,
) -> None:
"""Test build knowledge graph."""
index = KnowledgeGraphIndex([], service_context=mock_service_context)
tuples = [
("foo", "is", "bar"),
("hello", "is not", "world"),
("Jane", "is mother of", "Bob"),
]
nodes = [TextNode(text=str(tup)) for tup in tuples]
for tup, node in zip(tuples, nodes):
# add node
index.add_node([tup[0], tup[2]], node)
# add triplet
index.upsert_triplet(tup)
# NOTE: in these unit tests, document text == triplets
docstore_nodes = index.docstore.get_nodes(list(index.index_struct.node_ids))
table_chunks = {n.get_content() for n in docstore_nodes}
assert len(table_chunks) == 3
assert "('foo', 'is', 'bar')" in table_chunks
assert "('hello', 'is not', 'world')" in table_chunks
assert "('Jane', 'is mother of', 'Bob')" in table_chunks
# test that expected keys are present in table
# NOTE: in mock keyword extractor, stopwords are not filtered
assert index.index_struct.table.keys() == {
"foo",
"bar",
"hello",
"world",
"Jane",
"Bob",
}
# test upsert_triplet_and_node
index = KnowledgeGraphIndex([], service_context=mock_service_context)
tuples = [
("foo", "is", "bar"),
("hello", "is not", "world"),
("Jane", "is mother of", "Bob"),
]
nodes = [TextNode(text=str(tup)) for tup in tuples]
for tup, node in zip(tuples, nodes):
index.upsert_triplet_and_node(tup, node)
# NOTE: in these unit tests, document text == triplets
docstore_nodes = index.docstore.get_nodes(list(index.index_struct.node_ids))
table_chunks = {n.get_content() for n in docstore_nodes}
assert len(table_chunks) == 3
assert "('foo', 'is', 'bar')" in table_chunks
assert "('hello', 'is not', 'world')" in table_chunks
assert "('Jane', 'is mother of', 'Bob')" in table_chunks
# test that expected keys are present in table
# NOTE: in mock keyword extractor, stopwords are not filtered
assert index.index_struct.table.keys() == {
"foo",
"bar",
"hello",
"world",
"Jane",
"Bob",
}
# try inserting same node twice
index = KnowledgeGraphIndex([], service_context=mock_service_context)
node = TextNode(text=str(("foo", "is", "bar")), id_="test_node")
index.upsert_triplet_and_node(tup, node)
index.upsert_triplet_and_node(tup, node)
@patch.object(
KnowledgeGraphIndex, "_extract_triplets", side_effect=mock_extract_triplets
)
def test_build_kg_similarity(
_patch_extract_triplets: Any,
documents: List[Document],
mock_service_context: ServiceContext,
) -> None:
"""Test build knowledge graph."""
mock_service_context.embed_model = MockEmbedding()
index = KnowledgeGraphIndex.from_documents(
documents, include_embeddings=True, service_context=mock_service_context
)
# get embedding dict from KG index struct
rel_text_embeddings = index.index_struct.embedding_dict
# check that all rel_texts were embedded
assert len(rel_text_embeddings) == 3
for rel_text, embedding in rel_text_embeddings.items():
assert embedding == MockEmbedding().get_text_embedding(rel_text)
@patch.object(
KnowledgeGraphIndex, "_extract_triplets", side_effect=mock_extract_triplets
)
def test_build_kg(
_patch_extract_triplets: Any,
documents: List[Document],
mock_service_context: ServiceContext,
) -> None:
"""Test build knowledge graph."""
index = KnowledgeGraphIndex.from_documents(
documents, service_context=mock_service_context
)
# NOTE: in these unit tests, document text == triplets
nodes = index.docstore.get_nodes(list(index.index_struct.node_ids))
table_chunks = {n.get_content() for n in nodes}
assert len(table_chunks) == 3
assert "(foo, is, bar)" in table_chunks
assert "(hello, is not, world)" in table_chunks
assert "(Jane, is mother of, Bob)" in table_chunks
# test that expected keys are present in table
# NOTE: in mock keyword extractor, stopwords are not filtered
assert index.index_struct.table.keys() == {
"foo",
"bar",
"hello",
"world",
"Jane",
"Bob",
}
# test ref doc info for three nodes, single doc
all_ref_doc_info = index.ref_doc_info
assert len(all_ref_doc_info) == 1
for ref_doc_info in all_ref_doc_info.values():
assert len(ref_doc_info.node_ids) == 3
def test__parse_triplet_response(
doc_triplets_with_text_around: List[Document],
mock_service_context: ServiceContext,
) -> None:
"""Test build knowledge graph with triplet response in other format."""
parsed_triplets = []
for doc_triplet in doc_triplets_with_text_around:
parsed_triplets.append(
KnowledgeGraphIndex._parse_triplet_response(doc_triplet.text)
)
assert len(parsed_triplets) == 1
assert len(parsed_triplets[0]) == 3
# Expecting Capitalized triplet Outputs
assert ("Foo", "Is", "Bar") in parsed_triplets[0]
assert ("Hello", "Is not", "World") in parsed_triplets[0]
assert ("Jane", "Is mother of", "Bob") in parsed_triplets[0]