Relation Extraction
The RelationExtraction task performs joint entity and relation extraction, identifying relationships between entities in text.
Usage
relations = {
"works_for": "A person works for a company or organization.",
"located_in": "A place or organization is located in a city, country, or region.",
"founded": "A person founded a company or organization.",
}
fewshot_examples = [
relation_extraction.FewshotExample(
text="Clara Barton founded the American Red Cross.",
triplets=[
RelationTriplet(
head=RelationEntity(text="Clara Barton", entity_type="PERSON"),
relation="founded",
tail=RelationEntity(text="American Red Cross", entity_type="ORGANIZATION"),
)
],
),
relation_extraction.FewshotExample(
text="Irving Stowe founded Greenpeace.",
triplets=[
RelationTriplet(
head=RelationEntity(text="Irving Stowe", entity_type="PERSON"),
relation="founded",
tail=RelationEntity(text="Greenpeace", entity_type="ORGANIZATION"),
)
],
),
]
fewshot_args = {"fewshot_examples": fewshot_examples} if fewshot else {}
task = relation_extraction.RelationExtraction(
relations=relations,
model=batch_runtime.model,
model_settings=batch_runtime.model_settings,
batch_size=batch_runtime.batch_size,
entity_types=["PERSON", "ORGANIZATION", "LOCATION"],
**fewshot_args
)
pipe = Pipeline(task)
docs = list(pipe(relation_extraction_docs))
Results
The RelationExtraction task returns a unified Result object containing a list of RelationTriplet objects.
class Result(pydantic.BaseModel):
"""Result of a relation extraction task.
Attributes:
triplets: List of extracted relation triplets.
"""
triplets: list[RelationTriplet]
Each RelationTriplet consists of:
- head: A RelationEntity representing the subject.
- relation: The string identifier of the relationship.
- tail: A RelationEntity representing the object.
A RelationEntity includes the surface text, entity_type, and character start/end offsets.
Relation extraction predictive task.
RelationExtraction
Bases: PredictiveTask[TaskPromptSignature, TaskResult, _TaskBridge]
Extract relations between entities in text.
Source code in sieves/tasks/predictive/relation_extraction/core.py
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 | |
fewshot_examples
property
Return few-shot examples.
Returns:
| Type | Description |
|---|---|
Sequence[FewshotExample]
|
Few-shot examples. |
id
property
Return task ID.
Used by pipeline for results and dependency management.
Returns:
| Type | Description |
|---|---|
str
|
Task ID. |
prompt_signature_description
property
Return prompt signature description.
Returns:
| Type | Description |
|---|---|
str | None
|
Prompt signature description. |
prompt_template
property
Return prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template. |
__add__(other)
Chain this task with another task or pipeline using the + operator.
This returns a new Pipeline that executes this task first, followed by the
task(s) in other. The original task(s)/pipeline are not mutated.
Cache semantics:
- If other is a Pipeline, the resulting pipeline adopts other's
use_cache setting (because the left-hand side is a single task).
- If other is a Task, the resulting pipeline defaults to use_cache=True.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Task | Pipeline
|
A |
required |
Returns:
| Type | Description |
|---|---|
Pipeline
|
A new |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Source code in sieves/tasks/core.py
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 | |
__call__(docs)
Execute task with conditional logic.
Checks the condition for each document without materializing all docs upfront. Passes all documents that pass the condition to _call() for proper batching. Documents that fail the condition have results[task_id] set to None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Iterable[Doc]
|
Docs to process. |
required |
Returns:
| Type | Description |
|---|---|
Iterable[Doc]
|
Processed docs (in original order). |
Source code in sieves/tasks/core.py
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 | |
__init__(relations, model, entity_types=None, task_id=None, include_meta=True, batch_size=-1, prompt_instructions=None, fewshot_examples=(), model_settings=ModelSettings(), condition=None)
Initialize RelationExtraction task.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
relations
|
Sequence[str] | dict[str, str]
|
Relations to extract. Can be a list of relation types or a dict mapping types to descriptions. |
required |
model
|
TaskModel
|
Model to use. |
required |
entity_types
|
Sequence[str] | dict[str, str] | None
|
Optional constraints on entity types involved in relations. |
None
|
task_id
|
str | None
|
Task ID. |
None
|
include_meta
|
bool
|
Whether to include meta information generated by the task. |
True
|
batch_size
|
int
|
Batch size to use for inference. Use -1 to process all documents at once. |
-1
|
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
None
|
fewshot_examples
|
Sequence[FewshotExample]
|
Few-shot examples. |
()
|
model_settings
|
ModelSettings
|
Settings for structured generation. |
ModelSettings()
|
condition
|
Callable[[Doc], bool] | None
|
Optional callable that determines whether to process each document. |
None
|
Source code in sieves/tasks/predictive/relation_extraction/core.py
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 | |
deserialize(config, **kwargs)
classmethod
Generate PredictiveTask instance from config.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
Config
|
Config to generate instance from. |
required |
kwargs
|
dict[str, Any]
|
Values to inject into loaded config. |
{}
|
Returns:
| Type | Description |
|---|---|
PredictiveTask[TaskPromptSignature, TaskResult, TaskBridge]
|
Deserialized PredictiveTask instance. |
Source code in sieves/tasks/predictive/core.py
241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
optimize(optimizer, verbose=True)
Optimize task prompt and few-shot examples with the available optimization config.
Updates task to use best prompt and few-shot examples found by the optimizer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
optimizer
|
Optimizer
|
Optimizer to run. |
required |
verbose
|
bool
|
Whether to suppress output. DSPy produces a good amount of logs, so this can be useful to not pollute your terminal. Only warnings and errors will be printed. |
True
|
Returns:
| Type | Description |
|---|---|
tuple[str, Sequence[FewshotExample]]
|
Best found prompt and few-shot examples. |
Source code in sieves/tasks/predictive/core.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 | |
serialize()
Serialize task.
Returns:
| Type | Description |
|---|---|
Config
|
Config instance. |
Source code in sieves/tasks/core.py
136 137 138 139 140 141 | |
Bridges for relation extraction task.
DSPyRelationExtraction
Bases: RelationExtractionBridge[PromptSignature, Result, InferenceMode]
DSPy bridge for relation extraction.
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
prompt_template
property
Return prompt template.
Chains _prompt_instructions, _prompt_example_template and _prompt_conclusion.
Note: different model have different expectations as to how a prompt should look like. E.g. outlines supports the Jinja 2 templating format for insertion of values and few-shot examples, whereas DSPy integrates these things in a different value in the workflow and hence expects the prompt not to include these things. Mind model-specific expectations when creating a prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template as string. None if not used by model wrapper. |
__init__(task_id, relations, entity_types, prompt_instructions, model_settings)
Initialize RelationExtractionBridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Task ID. |
required |
relations
|
list[str] | dict[str, str]
|
Relation types to extract. |
required |
entity_types
|
list[str] | dict[str, str] | None
|
Entity types to consider. |
required |
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
required |
model_settings
|
ModelSettings
|
Model settings. |
required |
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
extract(docs)
Extract all values from doc instances that are to be injected into the prompts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Sequence[Doc]
|
Docs to extract values from. |
required |
Returns:
| Type | Description |
|---|---|
Sequence[dict[str, Any]]
|
All values from doc instances that are to be injected into the prompts as a sequence. |
Source code in sieves/tasks/predictive/bridges.py
107 108 109 110 111 112 113 | |
LangChainRelationExtraction
Bases: PydanticBasedRelationExtraction[InferenceMode]
LangChain bridge for relation extraction.
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
304 305 306 307 308 309 310 | |
prompt_template
property
Return prompt template.
Chains _prompt_instructions, _prompt_example_template and _prompt_conclusion.
Note: different model have different expectations as to how a prompt should look like. E.g. outlines supports the Jinja 2 templating format for insertion of values and few-shot examples, whereas DSPy integrates these things in a different value in the workflow and hence expects the prompt not to include these things. Mind model-specific expectations when creating a prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template as string. None if not used by model wrapper. |
__init__(task_id, relations, entity_types, prompt_instructions, model_settings)
Initialize RelationExtractionBridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Task ID. |
required |
relations
|
list[str] | dict[str, str]
|
Relation types to extract. |
required |
entity_types
|
list[str] | dict[str, str] | None
|
Entity types to consider. |
required |
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
required |
model_settings
|
ModelSettings
|
Model settings. |
required |
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
extract(docs)
Extract all values from doc instances that are to be injected into the prompts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Sequence[Doc]
|
Docs to extract values from. |
required |
Returns:
| Type | Description |
|---|---|
Sequence[dict[str, Any]]
|
All values from doc instances that are to be injected into the prompts as a sequence. |
Source code in sieves/tasks/predictive/bridges.py
107 108 109 110 111 112 113 | |
OutlinesRelationExtraction
Bases: PydanticBasedRelationExtraction[InferenceMode]
Outlines bridge for relation extraction.
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
295 296 297 298 299 300 301 | |
prompt_template
property
Return prompt template.
Chains _prompt_instructions, _prompt_example_template and _prompt_conclusion.
Note: different model have different expectations as to how a prompt should look like. E.g. outlines supports the Jinja 2 templating format for insertion of values and few-shot examples, whereas DSPy integrates these things in a different value in the workflow and hence expects the prompt not to include these things. Mind model-specific expectations when creating a prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template as string. None if not used by model wrapper. |
__init__(task_id, relations, entity_types, prompt_instructions, model_settings)
Initialize RelationExtractionBridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Task ID. |
required |
relations
|
list[str] | dict[str, str]
|
Relation types to extract. |
required |
entity_types
|
list[str] | dict[str, str] | None
|
Entity types to consider. |
required |
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
required |
model_settings
|
ModelSettings
|
Model settings. |
required |
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
extract(docs)
Extract all values from doc instances that are to be injected into the prompts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Sequence[Doc]
|
Docs to extract values from. |
required |
Returns:
| Type | Description |
|---|---|
Sequence[dict[str, Any]]
|
All values from doc instances that are to be injected into the prompts as a sequence. |
Source code in sieves/tasks/predictive/bridges.py
107 108 109 110 111 112 113 | |
PydanticBasedRelationExtraction
Bases: RelationExtractionBridge[BaseModel, BaseModel | list[Any], ModelWrapperInferenceMode], ABC
Base class for Pydantic-based relation extraction bridges.
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 | |
inference_mode
abstractmethod
property
Return inference mode.
Returns:
| Type | Description |
|---|---|
ModelWrapperInferenceMode
|
Inference mode. |
prompt_template
property
Return prompt template.
Chains _prompt_instructions, _prompt_example_template and _prompt_conclusion.
Note: different model have different expectations as to how a prompt should look like. E.g. outlines supports the Jinja 2 templating format for insertion of values and few-shot examples, whereas DSPy integrates these things in a different value in the workflow and hence expects the prompt not to include these things. Mind model-specific expectations when creating a prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template as string. None if not used by model wrapper. |
__init__(task_id, relations, entity_types, prompt_instructions, model_settings)
Initialize RelationExtractionBridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Task ID. |
required |
relations
|
list[str] | dict[str, str]
|
Relation types to extract. |
required |
entity_types
|
list[str] | dict[str, str] | None
|
Entity types to consider. |
required |
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
required |
model_settings
|
ModelSettings
|
Model settings. |
required |
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
extract(docs)
Extract all values from doc instances that are to be injected into the prompts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Sequence[Doc]
|
Docs to extract values from. |
required |
Returns:
| Type | Description |
|---|---|
Sequence[dict[str, Any]]
|
All values from doc instances that are to be injected into the prompts as a sequence. |
Source code in sieves/tasks/predictive/bridges.py
107 108 109 110 111 112 113 | |
RelationExtractionBridge
Bases: Bridge[_BridgePromptSignature, _BridgeResult, ModelWrapperInferenceMode], ABC
Abstract base class for relation extraction bridges.
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
inference_mode
abstractmethod
property
Return inference mode.
Returns:
| Type | Description |
|---|---|
ModelWrapperInferenceMode
|
Inference mode. |
prompt_signature
abstractmethod
property
Create output signature.
E.g.: Signature in DSPy, Pydantic objects in outlines, JSON schema in jsonformers.
This is model type-specific.
Returns:
| Type | Description |
|---|---|
type[TaskPromptSignature] | TaskPromptSignature
|
Output signature object. This can be an instance (e.g. a regex string) or a class (e.g. a Pydantic class). |
prompt_template
property
Return prompt template.
Chains _prompt_instructions, _prompt_example_template and _prompt_conclusion.
Note: different model have different expectations as to how a prompt should look like. E.g. outlines supports the Jinja 2 templating format for insertion of values and few-shot examples, whereas DSPy integrates these things in a different value in the workflow and hence expects the prompt not to include these things. Mind model-specific expectations when creating a prompt template.
Returns:
| Type | Description |
|---|---|
str
|
Prompt template as string. None if not used by model wrapper. |
__init__(task_id, relations, entity_types, prompt_instructions, model_settings)
Initialize RelationExtractionBridge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
task_id
|
str
|
Task ID. |
required |
relations
|
list[str] | dict[str, str]
|
Relation types to extract. |
required |
entity_types
|
list[str] | dict[str, str] | None
|
Entity types to consider. |
required |
prompt_instructions
|
str | None
|
Custom prompt instructions. If None, default instructions are used. |
required |
model_settings
|
ModelSettings
|
Model settings. |
required |
Source code in sieves/tasks/predictive/relation_extraction/bridges.py
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 | |
extract(docs)
Extract all values from doc instances that are to be injected into the prompts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
docs
|
Sequence[Doc]
|
Docs to extract values from. |
required |
Returns:
| Type | Description |
|---|---|
Sequence[dict[str, Any]]
|
All values from doc instances that are to be injected into the prompts as a sequence. |
Source code in sieves/tasks/predictive/bridges.py
107 108 109 110 111 112 113 | |
Schemas for relation extraction task.
FewshotExample
Bases: FewshotExample
Few-shot example for relation extraction.
Attributes: text: Input text. triplets: Expected relation triplets.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 | |
input_fields
property
Defines which fields are inputs.
Returns:
| Type | Description |
|---|---|
Sequence[str]
|
Sequence of field names. |
target_fields
property
Return target fields.
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
Target fields. |
from_dspy(example)
classmethod
Convert from dspy.Example.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
example
|
Example
|
Example as |
required |
Returns:
| Type | Description |
|---|---|
Self
|
Example as |
Source code in sieves/tasks/predictive/schemas/core.py
63 64 65 66 67 68 69 70 | |
to_dspy()
Convert to dspy.Example.
Returns:
| Type | Description |
|---|---|
Example
|
Example as |
Source code in sieves/tasks/predictive/schemas/core.py
56 57 58 59 60 61 | |
RelationEntity
Bases: BaseModel
Entity involved in a relation.
Attributes: text: Surface text of the entity. entity_type: Type of the entity.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
13 14 15 16 17 18 19 20 21 22 | |
RelationEntityWithContext
Bases: BaseModel
Entity mention with text span, type, and context for span discovery.
Attributes: text: Surface text of the entity. context: Short context around the entity. entity_type: Type of the entity.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
53 54 55 56 57 58 59 60 61 62 63 64 | |
RelationTriplet
Bases: BaseModel
Triplet representing a relation between two entities.
Attributes: head: The subject entity. relation: The type of relation. tail: The object entity.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
25 26 27 28 29 30 31 32 33 34 35 36 | |
RelationTripletWithContext
Bases: BaseModel
Triplet with context for span discovery.
Attributes: head: The head entity with context. relation: The relation type. tail: The tail entity with context.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
67 68 69 70 71 72 73 74 75 76 77 78 | |
Result
Bases: BaseModel
Result of a relation extraction task.
Attributes: triplets: List of extracted relation triplets.
Source code in sieves/tasks/predictive/schemas/relation_extraction.py
40 41 42 43 44 45 46 47 | |