forked from cocoindex-io/cocoindex
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
191 lines (175 loc) · 6.32 KB
/
main.py
File metadata and controls
191 lines (175 loc) · 6.32 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
"""
This example shows how to extract relationships from documents and build a knowledge graph.
"""
import dataclasses
import cocoindex
import os
neo4j_conn_spec = cocoindex.add_auth_entry(
"Neo4jConnection",
cocoindex.targets.Neo4jConnection(
uri="bolt://localhost:7687",
user="neo4j",
password="cocoindex",
),
)
GraphDbSpec = cocoindex.targets.Neo4j
GraphDbConnection = cocoindex.targets.Neo4jConnection
GraphDbDeclaration = cocoindex.targets.Neo4jDeclaration
conn_spec = neo4j_conn_spec
@dataclasses.dataclass
class DocumentSummary:
"""Describe a summary of a document."""
title: str
summary: str
@dataclasses.dataclass
class Relationship:
"""
Describe a relationship between two entities.
Subject and object should be Core CocoIndex concepts only, should be nouns. For example, `CocoIndex`, `Incremental Processing`, `ETL`, `Data` etc.
"""
subject: str
predicate: str
object: str
@cocoindex.flow_def(name="DocsToKG")
def docs_to_kg_flow(
flow_builder: cocoindex.FlowBuilder, data_scope: cocoindex.DataScope
) -> None:
"""
Define an example flow that extracts relationship from files and build knowledge graph.
"""
data_scope["documents"] = flow_builder.add_source(
cocoindex.sources.LocalFile(
path=os.path.join("..", "..", "docs", "docs", "core"),
included_patterns=["*.md", "*.mdx"],
)
)
document_node = data_scope.add_collector()
entity_relationship = data_scope.add_collector()
entity_mention = data_scope.add_collector()
with data_scope["documents"].row() as doc:
# extract summary from document
doc["summary"] = doc["content"].transform(
cocoindex.functions.ExtractByLlm(
llm_spec=cocoindex.LlmSpec(
# Supported LLM: https://cocoindex.io/docs/ai/llm
api_type=cocoindex.LlmApiType.OLLAMA,
model="llama3.2",
),
# Alternative: Use OpenAI API model instead of Ollama
# llm_spec=cocoindex.LlmSpec(
# api_type=cocoindex.LlmApiType.OPENAI,
# model="gpt-4o",
# ),
output_type=DocumentSummary,
instruction="Please summarize the content of the document.",
)
)
document_node.collect(
filename=doc["filename"],
title=doc["summary"]["title"],
summary=doc["summary"]["summary"],
)
# extract relationships from document
doc["relationships"] = doc["content"].transform(
cocoindex.functions.ExtractByLlm(
llm_spec=cocoindex.LlmSpec(
# Supported LLM: https://cocoindex.io/docs/ai/llm
api_type=cocoindex.LlmApiType.OLLAMA,
model="llama3.2",
),
# Alternative: Use OpenAI API model instead of Ollama
# llm_spec=cocoindex.LlmSpec(
# api_type=cocoindex.LlmApiType.OPENAI,
# model="gpt-4o",
# ),
output_type=list[Relationship],
instruction=(
"Please extract relationships from CocoIndex documents. "
"Focus on concepts and ignore examples and code. "
),
)
)
with doc["relationships"].row() as relationship:
# relationship between two entities
entity_relationship.collect(
id=cocoindex.GeneratedField.UUID,
subject=relationship["subject"],
object=relationship["object"],
predicate=relationship["predicate"],
)
# mention of an entity in a document, for subject
entity_mention.collect(
id=cocoindex.GeneratedField.UUID,
entity=relationship["subject"],
filename=doc["filename"],
)
# mention of an entity in a document, for object
entity_mention.collect(
id=cocoindex.GeneratedField.UUID,
entity=relationship["object"],
filename=doc["filename"],
)
# export to neo4j
document_node.export(
"document_node",
GraphDbSpec(
connection=conn_spec, mapping=cocoindex.targets.Nodes(label="Document")
),
primary_key_fields=["filename"],
)
# Declare reference Node to reference entity node in a relationship
flow_builder.declare(
GraphDbDeclaration(
connection=conn_spec,
nodes_label="Entity",
primary_key_fields=["value"],
)
)
entity_relationship.export(
"entity_relationship",
GraphDbSpec(
connection=conn_spec,
mapping=cocoindex.targets.Relationships(
rel_type="RELATIONSHIP",
source=cocoindex.targets.NodeFromFields(
label="Entity",
fields=[
cocoindex.targets.TargetFieldMapping(
source="subject", target="value"
),
],
),
target=cocoindex.targets.NodeFromFields(
label="Entity",
fields=[
cocoindex.targets.TargetFieldMapping(
source="object", target="value"
),
],
),
),
),
primary_key_fields=["id"],
)
entity_mention.export(
"entity_mention",
GraphDbSpec(
connection=conn_spec,
mapping=cocoindex.targets.Relationships(
rel_type="MENTION",
source=cocoindex.targets.NodeFromFields(
label="Document",
fields=[cocoindex.targets.TargetFieldMapping("filename")],
),
target=cocoindex.targets.NodeFromFields(
label="Entity",
fields=[
cocoindex.targets.TargetFieldMapping(
source="entity", target="value"
)
],
),
),
),
primary_key_fields=["id"],
)