-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagents.py
276 lines (220 loc) · 9 KB
/
agents.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
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
274
275
276
from typing import Optional, Union
try:
from unstructured.documents.elements import Element
except ImportError:
Element = None
from camel.agents import ChatAgent
from camel.messages import BaseMessage
from camel.models import BaseModelBackend
from camel.prompts import TextPrompt
from camel.storages.graph_storages.graph_element import (
GraphElement,
Node,
Relationship,
)
from camel.types import RoleType
text_prompt = """
You are tasked with extracting nodes and relationships from given content and
structures them into Node and Relationship objects. Here's the outline of what
you needs to do:
Content Extraction:
You should be able to process input content and identify entities mentioned
within it.
Entities can be any noun phrases or concepts that represent distinct entities
in the context of the given content.
Node Extraction:
For each identified entity, you should create a Node object.
Each Node object should have a unique identifier (id) and a type (type).
Additional properties associated with the node can also be extracted and
stored.
Relationship Extraction:
You should identify relationships between entities mentioned in the content.
For each relationship, create a Relationship object.
A Relationship object should have a subject (subj) and an object (obj) which
are Node objects representing the entities involved in the relationship.
Each relationship should also have a type (type), and additional properties if
applicable.
Output Formatting:
The extracted nodes and relationships should be formatted as instances of the
provided Node and Relationship classes.
Ensure that the extracted data adheres to the structure defined by the classes.
Output the structured data in a format that can be easily validated against
the provided code.
Instructions for you:
Read the provided content thoroughly.
Identify distinct entities mentioned in the content and categorize them as
nodes.
Determine relationships between these entities and represent them as directed
relationships.
Provide the extracted nodes and relationships in the specified format below.
Example for you:
Example Content:
"John works at XYZ Corporation. He is a software engineer. The company is
located in New York City."
Expected Output:
Nodes:
Node(id='John', type='Person')
Node(id='XYZ Corporation', type='Organization')
Node(id='New York City', type='Location')
Relationships:
Relationship(subj=Node(id='John', type='Person'), obj=Node(id='XYZ
Corporation', type='Organization'), type='WorksAt')
Relationship(subj=Node(id='John', type='Person'), obj=Node(id='New York City',
type='Location'), type='ResidesIn')
===== TASK =====
Please extracts nodes and relationships from given content and structures them
into Node and Relationship objects.
{task}
"""
class KnowledgeGraphAgent(ChatAgent):
r"""An agent that can extract node and relationship information for
different entities from given `Element` content.
Attributes:
task_prompt (TextPrompt): A prompt for the agent to extract node and
relationship information for different entities.
"""
def __init__(
self,
model: Optional[BaseModelBackend] = None,
) -> None:
r"""Initialize the `KnowledgeGraphAgent`.
Args:
model (BaseModelBackend, optional): The model backend to use for
generating responses. (default: :obj:`OpenAIModel` with
`GPT_3_5_TURBO`)
"""
system_message = BaseMessage(
role_name="Graphify",
role_type=RoleType.ASSISTANT,
meta_dict=None,
content="Your mission is to transform unstructured content "
"into structured graph data. Extract nodes and relationships with "
"precision, and let the connections unfold. Your graphs will "
"illuminate the hidden connections within the chaos of "
"information.",
)
super().__init__(system_message, model=model)
def run(
self,
element: Union[str, Element],
parse_graph_elements: bool = False,
) -> Union[str, GraphElement]:
r"""Run the agent to extract node and relationship information.
Args:
element (Union[str, Element]): The input element or string.
parse_graph_elements (bool, optional): Whether to parse into
`GraphElement`. Defaults to `False`.
Returns:
Union[str, GraphElement]: The extracted node and relationship
information. If `parse_graph_elements` is `True` then return
`GraphElement`, else return `str`.
"""
self.reset()
self.element = element
knowledge_graph_prompt = TextPrompt(text_prompt)
knowledge_graph_generation = knowledge_graph_prompt.format(
task=str(element)
)
knowledge_graph_generation_msg = BaseMessage.make_user_message(
role_name="Graphify", content=knowledge_graph_generation
)
response = self.step(input_message=knowledge_graph_generation_msg)
content = response.msg.content
if parse_graph_elements:
content = self._parse_graph_elements(content)
return content
def _validate_node(self, node: Node) -> bool:
r"""Validate if the object is a valid Node.
Args:
node (Node): Object to be validated.
Returns:
bool: True if the object is a valid Node, False otherwise.
"""
return (
isinstance(node, Node)
and isinstance(node.id, (str, int))
and isinstance(node.type, str)
)
def _validate_relationship(self, relationship: Relationship) -> bool:
r"""Validate if the object is a valid Relationship.
Args:
relationship (Relationship): Object to be validated.
Returns:
bool: True if the object is a valid Relationship, False otherwise.
"""
return (
isinstance(relationship, Relationship)
and self._validate_node(relationship.subj)
and self._validate_node(relationship.obj)
and isinstance(relationship.type, str)
)
def _parse_graph_elements(self, input_string: str) -> GraphElement:
r"""Parses graph elements from given content.
Args:
input_string (str): The input content.
Returns:
GraphElement: The parsed graph elements.
"""
import re
# Regular expressions to extract nodes and relationships
node_pattern = r"Node\(id='(.*?)', type='(.*?)'\)"
rel_pattern = (
r"Relationship\(subj=Node\(id='(.*?)', type='(.*?)'\), "
r"obj=Node\(id='(.*?)', type='(.*?)'\), type='(.*?)'\)"
)
nodes = {}
relationships = []
# Extract nodes
for match in re.finditer(node_pattern, input_string):
id, type = match.groups()
properties = {'source': 'agent_created'}
if id not in nodes:
node = Node(id, type, properties)
if self._validate_node(node):
nodes[id] = node
# Extract relationships
for match in re.finditer(rel_pattern, input_string):
subj_id, subj_type, obj_id, obj_type, rel_type = match.groups()
properties = {'source': 'agent_created'}
if subj_id in nodes and obj_id in nodes:
subj = nodes[subj_id]
obj = nodes[obj_id]
relationship = Relationship(subj, obj, rel_type, properties)
if self._validate_relationship(relationship):
relationships.append(relationship)
return GraphElement(list(nodes.values()), relationships, self.element)
class InsightAgent(ChatAgent):
def __init__(
self,
model: Optional[BaseModelBackend] = None,
) -> None:
r"""Initialize the `InsightAgent`.
Args:
model (BaseModelBackend, optional): The model backend to use for
generating responses. (default: :obj:`OpenAIModel` with
`GPT_3_5_TURBO`)
"""
system_message = BaseMessage(
role_name="InsightAgent",
role_type=RoleType.ASSISTANT,
meta_dict=None,
content="Your mission is to answer user's query based on the relationship information provided to you. Your output language should match with the query language, if the query is in Chinses, you should also answer in Chinese",
)
super().__init__(system_message, model=model)
def run(
self,
relationship_info: str,
query: str,
) -> str:
prompt = (
f"Based on the realationship information below "
f"{relationship_info}). "
f"Please answer to my question:"
f"{query}). "
)
insight_generation_msg = BaseMessage.make_user_message(
role_name="User", content=prompt
)
response = self.step(input_message=insight_generation_msg)
content = response.msg.content
return content