-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathllama_index_extractors.py
248 lines (194 loc) · 7.65 KB
/
llama_index_extractors.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
from llama_index.core.extractors import BaseExtractor
from typing import List, Any, Sequence, Dict
from llama_index.core.schema import BaseNode, TextNode
from llama_index.core.llms.llm import LLM
from llama_index.core.prompts import PromptTemplate
from llama_index.core.async_utils import DEFAULT_NUM_WORKERS, run_jobs
from llama_index.core.bridge.pydantic import (
Field,
PrivateAttr,
SerializeAsAny,
)
from story_extractor import extract_story_json
# extract_story_json(llm: LLM, input: str)
DEFAULT_CHARACTER_EXTRACT_TEMPLATE = """\
Here is the content of the section:
{context_str}
List all of the characters, including name, description, personality, physical_appearance, role, gender, age, voice_description, relationships, internal_conflict
If something is not specified, you can leave it blank.
Example Character:
name: Pip the Penguin
description: A curious and adventurous young penguin with a big imagination, always dreaming of exploring the world
personality: Brave, imaginative, and kind-hearted
physical_appearance: A small penguin with a distinctive red scarf
role: Protagonist
internal_conflict: Pip often feels nervous about the unknown but learns to overcome his fears with Sally's support.
relationships:
- Sally the Seal, Best Friend, Sally is Pip's loyal and clever friend who accompanies him
Characters: """
class CharacterExtractor(BaseExtractor):
"""
Character extractor. Node-level extractor.
"""
llm: SerializeAsAny[LLM] = Field(description="The LLM to use for generation.")
prompt_template: str = Field(
default=DEFAULT_CHARACTER_EXTRACT_TEMPLATE,
description="Template to use when generating characters.",
)
def __init__(
self,
llm: LLM,
prompt_template: str = DEFAULT_CHARACTER_EXTRACT_TEMPLATE,
num_workers: int = DEFAULT_NUM_WORKERS,
**kwargs: Any,
):
super().__init__(
llm=llm,
prompt_template=prompt_template,
num_workers=num_workers,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
return "CharacterExtractor"
async def _agenerate_node_characters(self, node: BaseNode) -> str:
"""Generate a character list for a node."""
if self.is_text_node_only and not isinstance(node, TextNode):
return ""
context_str = node.get_content(metadata_mode=self.metadata_mode)
summary = await self.llm.apredict(
PromptTemplate(template=self.prompt_template), context_str=context_str
)
return summary.strip()
async def aextract(self, nodes: Sequence[BaseNode]) -> List[Dict]:
if not all(isinstance(node, TextNode) for node in nodes):
raise ValueError("Only `TextNode` is allowed for `Character` extractor")
node_summaries_jobs = []
for node in nodes:
node_summaries_jobs.append(self._agenerate_node_characters(node))
node_characters = await run_jobs(
node_summaries_jobs,
show_progress=self.show_progress,
workers=self.num_workers,
)
# Extract node-level summary metadata
metadata_list: List[Dict] = [{} for _ in nodes]
for i, metadata in enumerate(metadata_list):
metadata["characters"] = node_characters[i]
return metadata_list
DEFAULT_SCENE_EXTRACT_TEMPLATE = """\
Here is the content of the section:
{context_str}
List all of the scenes, including \
title, description, characters_involved, setting, time_of_day, location, lighting, mood, props, key_actions
If something is not specified, you can leave it blank.
Example Scene:
title: Finding the Map
description: Pip stumbles upon a bottle washed ashore, containing an old map
characters_involved:
- Pip
- Sally
setting: The icy shore near Pip's colony
time_of_day: Morning
location: Penguin Colony Shore
lighting: Bright sunlight reflecting off the icy sea
mood: Excited and full of wonder
props:
- The Treasure Map
key_actions:
- Pip holds the map up, showing Sally the exciting adventure ahead
Scenes: """
class SceneExtractor(BaseExtractor):
"""
Scene extractor. Node-level extractor.
"""
llm: SerializeAsAny[LLM] = Field(description="The LLM to use for generation.")
prompt_template: str = Field(
default=DEFAULT_SCENE_EXTRACT_TEMPLATE,
description="Template to use when generating scenes.",
)
def __init__(
self,
llm: LLM,
prompt_template: str = DEFAULT_SCENE_EXTRACT_TEMPLATE,
num_workers: int = DEFAULT_NUM_WORKERS,
**kwargs: Any,
):
super().__init__(
llm=llm,
prompt_template=prompt_template,
num_workers=num_workers,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
return "SceneExtractor"
async def _agenerate_node_scenes(self, node: BaseNode) -> str:
"""Generate a scene list for a node."""
if self.is_text_node_only and not isinstance(node, TextNode):
return ""
context_str = node.get_content(metadata_mode=self.metadata_mode)
summary = await self.llm.apredict(
PromptTemplate(template=self.prompt_template), context_str=context_str
)
return summary.strip()
async def aextract(self, nodes: Sequence[BaseNode]) -> List[Dict]:
if not all(isinstance(node, TextNode) for node in nodes):
raise ValueError("Only `TextNode` is allowed for `Scene` extractor")
node_summaries_jobs = []
for node in nodes:
node_summaries_jobs.append(self._agenerate_node_scenes(node))
node_scenes = await run_jobs(
node_summaries_jobs,
show_progress=self.show_progress,
workers=self.num_workers,
)
# Extract node-level summary metadata
metadata_list: List[Dict] = [{} for _ in nodes]
for i, metadata in enumerate(metadata_list):
metadata["scenes"] = node_scenes[i]
return metadata_list
class StoryExtractor(BaseExtractor):
"""
Story extractor. Node-level extractor.
"""
llm: SerializeAsAny[LLM] = Field(description="The LLM to use for generation.")
def __init__(
self,
llm: LLM,
num_workers: int = DEFAULT_NUM_WORKERS,
**kwargs: Any,
):
super().__init__(
llm=llm,
num_workers=num_workers,
**kwargs,
)
@classmethod
def class_name(cls) -> str:
return "StoryExtractor"
async def _agenerate_node_stories(self, node: BaseNode) -> str:
"""Generate a story list for a node."""
if self.is_text_node_only and not isinstance(node, TextNode):
return ""
context_str = node.get_content(metadata_mode=self.metadata_mode)
summary = await self.llm.apredict(
PromptTemplate(template=self.prompt_template), context_str=context_str
)
return summary.strip()
async def aextract(self, nodes: Sequence[BaseNode]) -> List[Dict]:
if not all(isinstance(node, TextNode) for node in nodes):
raise ValueError("Only `TextNode` is allowed for `STORY` extractor")
node_summaries_jobs = []
for node in nodes:
node_summaries_jobs.append(self._agenerate_node_stories(node))
node_stories = await run_jobs(
node_summaries_jobs,
show_progress=self.show_progress,
workers=self.num_workers,
)
# Extract node-level summary metadata
metadata_list: List[Dict] = [{} for _ in nodes]
for i, metadata in enumerate(metadata_list):
metadata["stories"] = node_stories[i]
return metadata_list