Core Embeddings#
Core Embedding module#
serapeum.core.embeddings
#
Embedding module.
BaseEmbedding
#
Bases: SerializableModel, CallMixin, ABC
Abstract base class for all embedding model implementations.
This class provides the core interface and shared functionality for converting text into dense vector embeddings. It supports both query and document embedding, with optional caching, batching, and async operations.
Subclasses must implement the abstract methods for generating embeddings from text and queries. The class handles caching, batching, and progress tracking automatically.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
Name of the embedding model. Defaults to "unknown". |
batch_size |
int
|
Number of texts to process in each batch. Must be between 1 and 2048. Defaults to 10. |
num_workers |
int | None
|
Number of worker threads for async operations. If None, uses default async behavior without worker pooling. |
cache_store |
Any | None
|
Optional key-value store for caching embeddings. Must implement get(), aget(), put(), and aput() methods. When provided, embeddings are cached using a key combining text and model configuration. |
Notes
This is an abstract base class and cannot be instantiated directly. Subclasses must implement _get_query_embedding, _aget_query_embedding, and _get_text_embedding methods.
See Also
serapeum.providers.ollama.embeddings.OllamaEmbedding: Concrete implementation for Ollama embedding models. CallMixin: Mixin providing call and acall methods. SerializableModel: Base Pydantic model with serialization support.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
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 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 | |
__call__(nodes, **kwargs)
#
Embed a sequence of nodes by calling the embedding model.
This makes the embedding model callable, allowing it to be used as a function. Extracts text content from each node, generates embeddings, and assigns them back to the nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
Sequence[BaseNode]
|
Sequence of BaseNode objects to embed. |
required |
**kwargs
|
Any
|
Additional keyword arguments passed to get_text_embedding_batch. |
{}
|
Returns:
| Type | Description |
|---|---|
Sequence[BaseNode]
|
The input sequence of nodes with embeddings assigned to each node's |
Sequence[BaseNode]
|
embedding attribute. |
See Also
acall: Async version of this method. get_text_embedding_batch: Method used internally for batch embedding. MetadataMode.EMBED: Mode used to extract content from nodes.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
acall(nodes, **kwargs)
async
#
Asynchronously embed a sequence of nodes.
Async version of call(). Extracts text content from each node, generates embeddings asynchronously, and assigns them back to the nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
Sequence[BaseNode]
|
Sequence of BaseNode objects to embed. |
required |
**kwargs
|
Any
|
Additional keyword arguments passed to aget_text_embedding_batch. |
{}
|
Returns:
| Type | Description |
|---|---|
Sequence[BaseNode]
|
The input sequence of nodes with embeddings assigned to each node's |
Sequence[BaseNode]
|
embedding attribute. |
See Also
call: Sync version of this method. aget_text_embedding_batch: Method used internally for async batch embedding. MetadataMode.EMBED: Mode used to extract content from nodes.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
aget_agg_embedding_from_queries(queries, agg_fn=None)
async
#
Asynchronously generate an aggregated embedding from multiple queries.
Async version of get_agg_embedding_from_queries(). Embeds each query asynchronously and then combines them using an aggregation function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
list[str]
|
List of query strings to embed and aggregate. |
required |
agg_fn
|
Callable[..., Embedding] | None
|
Optional aggregation function that takes a list of embeddings and returns a single embedding. Defaults to mean_agg. |
None
|
Returns:
| Type | Description |
|---|---|
Embedding
|
Single aggregated embedding vector as a list of floats. |
See Also
get_agg_embedding_from_queries: Sync version of this method. aget_query_embedding: Used internally to embed each query. mean_agg: Default aggregation function.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
aget_query_embedding(query)
async
#
Asynchronously generate an embedding vector for a query string.
Async version of get_query_embedding(). Embeds the input query into a dense vector representation with cache support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Query text to embed. |
required |
Returns:
| Type | Description |
|---|---|
Embedding
|
Embedding vector as a list of floats. |
See Also
get_query_embedding: Sync version of this method. aget_text_embedding: For embedding document text asynchronously. _aget_query_embedding: Internal async implementation method.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
aget_text_embedding(text)
async
#
Asynchronously generate an embedding vector for document text.
Async version of get_text_embedding(). Embeds the input text into a dense vector representation with cache support.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Document text to embed. |
required |
Returns:
| Type | Description |
|---|---|
Embedding
|
Embedding vector as a list of floats. |
See Also
get_text_embedding: Sync version of this method. aget_query_embedding: For embedding queries asynchronously. aget_text_embedding_batch: For embedding multiple texts efficiently. _aget_text_embedding: Internal async implementation method.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
aget_text_embedding_batch(texts, show_progress=False, **kwargs)
async
#
Asynchronously generate embeddings for multiple texts with batching.
Async version of get_text_embedding_batch(). Processes texts in batches with concurrent execution for improved performance. Supports worker pooling if num_workers is set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
list[str]
|
List of document texts to embed. |
required |
show_progress
|
bool
|
Whether to display a progress bar. Defaults to False. Requires tqdm package for progress tracking. |
False
|
**kwargs
|
Any
|
Additional keyword arguments (reserved for future use). |
{}
|
Returns:
| Type | Description |
|---|---|
list[Embedding]
|
List of embedding vectors, one for each input text, in the same order. |
Notes
When num_workers > 1, uses worker pooling for concurrent batch processing. When show_progress=True, attempts to use tqdm.asyncio for progress tracking.
See Also
get_text_embedding_batch: Sync version of this method. aget_text_embedding: For embedding a single text asynchronously. _aget_text_embeddings: Internal async batch processing method.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 | |
get_agg_embedding_from_queries(queries, agg_fn=None)
#
Generate a single aggregated embedding from multiple query strings.
Embeds each query individually and then combines them using an aggregation function. This is useful for creating a unified representation from multiple related queries or questions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
queries
|
list[str]
|
List of query strings to embed and aggregate. |
required |
agg_fn
|
Callable[..., Embedding] | None
|
Optional aggregation function that takes a list of embeddings and returns a single embedding. Defaults to mean_agg (arithmetic mean). |
None
|
Returns:
| Type | Description |
|---|---|
Embedding
|
Single aggregated embedding vector as a list of floats. |
See Also
aget_agg_embedding_from_queries: Async version of this method. mean_agg: Default aggregation function. get_query_embedding: Used internally to embed each query.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
get_query_embedding(query)
#
Generate an embedding vector for a query string.
Embeds the input query into a dense vector representation optimized for retrieval tasks. When caching is enabled, checks the cache first and stores new embeddings automatically.
Depending on the model, a special instruction may be prepended to the raw query string to optimize for specific tasks. For example, some models use "Represent the question for retrieving supporting documents: ".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query
|
str
|
Query text to embed. |
required |
Returns:
| Type | Description |
|---|---|
Embedding
|
Embedding vector as a list of floats. |
See Also
aget_query_embedding: Async version of this method. get_text_embedding: For embedding document text (not queries). _get_query_embedding: Internal implementation method.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
get_text_embedding(text)
#
Generate an embedding vector for document text.
Embeds the input text into a dense vector representation optimized for document representation tasks. When caching is enabled, checks the cache first and stores new embeddings automatically.
Depending on the model, a special instruction may be prepended to the raw text string to optimize for document retrieval. For example, some models use "Represent the document for retrieval: ".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
text
|
str
|
Document text to embed. |
required |
Returns:
| Type | Description |
|---|---|
Embedding
|
Embedding vector as a list of floats. |
See Also
aget_text_embedding: Async version of this method. get_query_embedding: For embedding queries (not documents). get_text_embedding_batch: For embedding multiple texts efficiently. _get_text_embedding: Internal implementation method.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
get_text_embedding_batch(texts, show_progress=False, **kwargs)
#
Generate embeddings for multiple texts with automatic batching.
Processes a list of texts in batches according to self.batch_size. Supports optional progress tracking and automatic caching if cache_store is configured.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
texts
|
list[str]
|
List of document texts to embed. |
required |
show_progress
|
bool
|
Whether to display a progress bar. Defaults to False. |
False
|
**kwargs
|
Any
|
Additional keyword arguments (reserved for future use). |
{}
|
Returns:
| Type | Description |
|---|---|
list[Embedding]
|
List of embedding vectors, one for each input text, in the same order. |
See Also
aget_text_embedding_batch: Async version with parallel processing. get_text_embedding: For embedding a single text. _get_text_embeddings: Internal batch processing method. _get_text_embeddings_cached: Internal cached batch processing.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
similarity(embedding1, embedding2, mode=SimilarityMode.DEFAULT)
staticmethod
#
Calculate similarity between two embedding vectors.
Static method wrapper for the module-level similarity() function. Provides a convenient way to compute similarity directly from the class.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
embedding1
|
Embedding
|
First embedding vector (list of floats). |
required |
embedding2
|
Embedding
|
Second embedding vector (list of floats). |
required |
mode
|
SimilarityMode
|
Similarity computation mode. Defaults to cosine similarity. |
DEFAULT
|
Returns:
| Type | Description |
|---|---|
float
|
Similarity score as a float. Interpretation depends on the mode. |
Examples:
-
Computing cosine similarity
-
Using different similarity modes
See Also
similarity: Module-level function that performs the actual calculation. SimilarityMode: Enum defining available similarity modes.
Source code in libs/core/src/serapeum/core/base/embeddings/base.py
BaseNode
#
Bases: SerializableModel, ABC
Abstract base class for document nodes with metadata and relationship management.
BaseNode provides the foundational functionality for representing chunks of documents with rich metadata, embeddings, and hierarchical relationships. It supports selective metadata inclusion for different contexts (LLM vs embeddings), automatic change detection via hashing, and efficient relationship caching.
Key features: - Automatic UUID generation for node identification - Metadata management with selective inclusion/exclusion for LLM and embedding contexts - Relationship tracking (source, parent, children, previous, next) - Embedding storage and retrieval - Cached LinkedNodes computation with automatic invalidation - Customizable metadata formatting and serialization
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier for the node (auto-generated UUID if not provided). |
embedding |
list[float] | None
|
Optional vector embedding for the node's content. |
metadata |
dict[str, Any]
|
Flat dictionary of metadata fields used for context and filtering. |
excluded_embed_metadata_keys |
list[str]
|
Metadata keys excluded from embedding context. |
excluded_llm_metadata_keys |
list[str]
|
Metadata keys excluded from LLM context. |
links |
dict[Annotated[NodeType, EnumNameSerializer], NodeInfoType]
|
Dictionary mapping NodeType to NodeInfo for relationships. |
metadata_template |
str
|
Template string for formatting metadata (default: "{key}: {value}"). |
metadata_separator |
str
|
Separator between metadata fields (default: newline). |
Note
This is an abstract base class. Subclasses must implement: - get_type(): Return the node's content type identifier - get_content(): Return the node's content with optional metadata - set_content(): Update the node's content - hash: Property returning the content hash for change detection
Examples:
- Creating a concrete node subclass
>>> from serapeum.core.base.embeddings.types import BaseNode, MetadataMode, NodeType, NodeInfo >>> import hashlib >>> from pydantic import Field >>> >>> class TextNode(BaseNode): ... text: str = Field(default="", description="Text content of the node") ... ... @classmethod ... def get_type(cls) -> str: ... return "text" ... ... def get_content(self, metadata_mode: MetadataMode = MetadataMode.ALL) -> str: ... metadata_str = self.get_metadata_str(mode=metadata_mode) ... return f"{metadata_str}\\n{self.text}" if metadata_str else self.text ... ... def set_content(self, value: str) -> None: ... self.text = value ... ... @property ... def hash(self) -> str: ... return hashlib.sha256(self.text.encode()).hexdigest()- Create a node with metadata
- Using metadata exclusion for different contexts
>>> node = TextNode( ... text="Sensitive content", ... metadata={"public": "yes", "internal_id": "secret123"}, ... excluded_llm_metadata_keys=["internal_id"] ... )- For LLM context (excludes internal_id)
- Setting up node relationships
>>> parent = NodeInfo(id="parent-doc", type="document") >>> child = NodeInfo(id="child-chunk", type="text") >>> >>> node = TextNode( ... text="Child content", ... links={NodeType.PARENT: parent, NodeType.SOURCE: parent} ... ) >>> node.linked_nodes.parent.id 'parent-doc' >>> node.source_id 'parent-doc' - Working with embeddings
See Also
NodeInfo: Lightweight reference to a node. LinkedNodes: Container for node relationships. MetadataMode: Controls metadata inclusion in different contexts. SerializableModel: Base class providing serialization capabilities.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 | |
hash
abstractmethod
property
#
Get hash of node.
linked_nodes
property
#
Get linked nodes from the links dictionary.
This property validates and converts the links dictionary into a LinkedNodes object. The result is cached and automatically invalidated when the links field is reassigned through Pydantic's field validation.
Returns:
| Name | Type | Description |
|---|---|---|
LinkedNodes |
LinkedNodes
|
A validated and cached LinkedNodes object. |
Note
- Cache is automatically cleared when
linksis reassigned - For in-place mutations (e.g., node.links[key] = value), you must either reassign the entire dict OR call _clear_linked_nodes_cache()
- Uses Pydantic's @field_validator to manage cache invalidation
Examples:
>>> from serapeum.core.base.embeddings.types import BaseNode, NodeInfo, NodeType, MetadataMode
>>> import hashlib
>>> from pydantic import Field
>>> class TextNode(BaseNode):
... text: str = Field(default="")
... @classmethod
... def get_type(cls) -> str:
... return "text"
... def get_content(self, metadata_mode=MetadataMode.ALL) -> str:
... return self.text
... def set_content(self, value: str) -> None:
... self.text = value
... @property
... def hash(self) -> str:
... return hashlib.sha256(self.text.encode()).hexdigest()
>>> node = TextNode(text="Sample")
>>> source_ref = NodeInfo(id="doc-123", type="document")
>>> node.links = {NodeType.SOURCE: source_ref}
>>> node.linked_nodes.source.id
'doc-123'
>>> node = TextNode(text="Sample", links={})
>>> prev_ref = NodeInfo(id="prev-chunk", type="text")
>>> node.links[NodeType.PREVIOUS] = prev_ref
>>> node._clear_linked_nodes_cache()
>>> node.linked_nodes.previous.id
'prev-chunk'
>>> node = TextNode(text="Sample")
>>> parent = NodeInfo(id="parent-1", type="document")
>>> child1 = NodeInfo(id="child-1", type="text")
>>> child2 = NodeInfo(id="child-2", type="text")
>>> node.links = {NodeType.PARENT: parent, NodeType.CHILD: [child1, child2]}
>>> node.linked_nodes.parent.id
'parent-1'
>>> [c.id for c in node.linked_nodes.children]
['child-1', 'child-2']
get_embedding()
#
Get embedding.
Raises:
| Type | Description |
|---|---|
ValueError
|
if embedding is None. |
get_metadata_str(mode=MetadataMode.ALL)
#
Metadata info string.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
CallMixin
#
Bases: ABC
Base class for node transformation components.
CallMixin defines the interface for components that transform sequences of nodes, such as embedders, parsers, or metadata enrichers. It provides both synchronous and asynchronous calling interfaces.
The mixin uses callable syntax (obj(nodes)) for synchronous transforms and
obj.acall(nodes) for asynchronous transforms, enabling composable pipelines.
Attributes:
| Name | Type | Description |
|---|---|---|
model_config |
Pydantic configuration allowing arbitrary types in subclasses. |
Examples:
>>> from serapeum.core.base.embeddings.types import CallMixin, BaseNode, MetadataMode
>>> from typing import Sequence, Any
>>> import hashlib
>>> from pydantic import Field
>>> class TextNode(BaseNode):
... text: str = Field(default="")
... @classmethod
... def get_type(cls) -> str:
... return "text"
... def get_content(self, metadata_mode=MetadataMode.ALL) -> str:
... return self.text
... def set_content(self, value: str) -> None:
... self.text = value
... @property
... def hash(self) -> str:
... return hashlib.sha256(self.text.encode()).hexdigest()
>>> class UppercaseTransform(CallMixin):
... def __call__(self, nodes: Sequence[BaseNode], **kwargs: Any) -> Sequence[BaseNode]:
... result = []
... for node in nodes:
... node.set_content(node.get_content().upper())
... result.append(node)
... return result
>>> transformer = UppercaseTransform()
>>> nodes = [TextNode(text="hello"), TextNode(text="world")]
>>> transformed = transformer(nodes)
>>> transformed[0].get_content()
'HELLO'
>>> transformed[1].get_content()
'WORLD'
See Also
BaseEmbedding: Uses CallMixin to enable embedding nodes. BaseNode: The node type that this mixin transforms.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
__call__(nodes, **kwargs)
abstractmethod
#
Transform a sequence of nodes synchronously.
Subclasses must implement this method to define their transformation logic.
This method is called when the object is invoked directly: obj(nodes).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
Sequence[BaseNode]
|
Sequence of BaseNode instances to transform. |
required |
**kwargs
|
Any
|
Additional keyword arguments specific to the transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Sequence[BaseNode]
|
Transformed sequence of BaseNode instances. |
Examples:
>>> from serapeum.core.base.embeddings.types import CallMixin, BaseNode, MetadataMode
>>> import hashlib
>>> from pydantic import Field
>>> class TextNode(BaseNode):
... text: str = Field(default="")
... @classmethod
... def get_type(cls) -> str:
... return "text"
... def get_content(self, metadata_mode=MetadataMode.ALL) -> str:
... return self.text
... def set_content(self, value: str) -> None:
... self.text = value
... @property
... def hash(self) -> str:
... return hashlib.sha256(self.text.encode()).hexdigest()
>>> class MetadataAdder(CallMixin):
... def __call__(self, nodes, **kwargs):
... result = []
... for i, node in enumerate(nodes):
... node.metadata["index"] = i
... result.append(node)
... return result
>>> adder = MetadataAdder()
>>> nodes = [TextNode(text="first"), TextNode(text="second")]
>>> processed = adder(nodes)
>>> processed[0].metadata["index"]
0
>>> processed[1].metadata["index"]
1
Note
Implementations should preserve node identity where possible and avoid mutating input nodes unless explicitly documented.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
acall(nodes, **kwargs)
async
#
Transform a sequence of nodes asynchronously.
Default implementation delegates to synchronous __call__. Subclasses
can override this for true async implementations (e.g., async API calls).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes
|
Sequence[BaseNode]
|
Sequence of BaseNode instances to transform. |
required |
**kwargs
|
Any
|
Additional keyword arguments specific to the transformation. |
{}
|
Returns:
| Type | Description |
|---|---|
Sequence[BaseNode]
|
Transformed sequence of BaseNode instances. |
Examples:
>>> import asyncio
>>> from serapeum.core.base.embeddings.types import CallMixin, BaseNode, MetadataMode
>>> import hashlib
>>> from pydantic import Field
>>> class TextNode(BaseNode):
... text: str = Field(default="")
... @classmethod
... def get_type(cls) -> str:
... return "text"
... def get_content(self, metadata_mode=MetadataMode.ALL) -> str:
... return self.text
... def set_content(self, value: str) -> None:
... self.text = value
... @property
... def hash(self) -> str:
... return hashlib.sha256(self.text.encode()).hexdigest()
>>> class AsyncTransform(CallMixin):
... def __call__(self, nodes, **kwargs):
... return nodes
... async def acall(self, nodes, **kwargs):
... await asyncio.sleep(0)
... for node in nodes:
... node.metadata["async_processed"] = True
... return nodes
>>> transform = AsyncTransform()
>>> nodes = [TextNode(text="test")]
>>> result = asyncio.run(transform.acall(nodes))
>>> result[0].metadata["async_processed"]
True
>>> class SyncOnlyTransform(CallMixin):
... def __call__(self, nodes, **kwargs):
... for node in nodes:
... node.metadata["processed"] = True
... return nodes
>>> sync_transform = SyncOnlyTransform()
>>> nodes = [TextNode(text="test")]
>>> result = asyncio.run(sync_transform.acall(nodes))
>>> result[0].metadata["processed"]
True
Note
If no true async implementation is needed, the default delegation
to __call__ is sufficient. Override only if the transformation
benefits from async/await (e.g., I/O operations).
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 | |
LinkedNodes
#
Bases: SerializableModel
Immutable container for node relationships in a document hierarchy.
LinkedNodes manages references between nodes in a document structure, supporting linear sequences (previous/next), hierarchical relationships (parent/children), and source document tracking. The model is frozen to prevent accidental mutation of relationship structures.
Attributes:
| Name | Type | Description |
|---|---|---|
source |
NodeInfo | None
|
Reference to the original source document node. |
previous |
NodeInfo | None
|
Reference to the previous node in a sequence. |
next |
NodeInfo | None
|
Reference to the next node in a sequence. |
parent |
NodeInfo | None
|
Reference to the parent node in a hierarchy. |
children |
list[NodeInfo] | None
|
List of child node references in a hierarchy. |
Examples:
- Creating a linear sequence of nodes
- Building hierarchical relationships
- Using factory method with NodeType enum
- Accessing source ID property
See Also
NodeType: Enum defining relationship types. NodeInfo: References stored in relationship fields. BaseNode.linked_nodes: Property that creates LinkedNodes from links dict.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 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 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
source_id
property
#
Get the ID of the source node if it exists.
Convenience property for accessing the source node's ID without checking if source is None first.
Returns:
| Type | Description |
|---|---|
str | None
|
The source node's ID string, or None if no source is set. |
Examples:
- Accessing source ID when source exists
- Accessing when source is None
See Also
BaseNode.source_id: Uses this property for node source tracking.
as_dict()
#
Convert LinkedNodes to a dictionary mapping NodeType to NodeInfo.
Creates a dictionary representation with NodeType enum keys and NodeInfo values. None values are excluded from the result to create a compact representation containing only active relationships.
Returns:
| Type | Description |
|---|---|
dict[NodeType, NodeInfoType | None]
|
Dictionary with NodeType keys and NodeInfo/list[NodeInfo] values. |
dict[NodeType, NodeInfoType | None]
|
Only non-None relationships are included. |
Examples:
- Converting to dict with multiple relationships
- None values are excluded
- Round-trip with create method
See Also
LinkedNodes.create: Factory method for creating from dict. BaseNode.links: Uses this format for storing relationships.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
create(linked_nodes_info)
classmethod
#
Create LinkedNodes from a dict mapping NodeType to NodeInfo/list.
Factory method that converts a dictionary with NodeType keys into a validated LinkedNodes instance. Pydantic validators automatically check that single-node fields contain NodeInfo and children contains a list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
linked_nodes_info
|
dict[NodeType, NodeInfoType]
|
Dictionary mapping NodeType enum values to either NodeInfo (for single relationships) or list[NodeInfo] (for children). Missing keys are treated as None. |
required |
Returns:
| Type | Description |
|---|---|
'LinkedNodes'
|
A new LinkedNodes instance with validated relationships. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a single-node field (SOURCE, PREVIOUS, NEXT, PARENT) receives a list, or if children receives a non-list value. |
Examples:
- Creating from a dict with mixed relationships
>>> from serapeum.core.base.embeddings.types import LinkedNodes, NodeInfo, NodeType >>> source = NodeInfo(id="doc-1") >>> parent = NodeInfo(id="section-1") >>> children = [NodeInfo(id="para-1"), NodeInfo(id="para-2")] >>> links_dict = { ... NodeType.SOURCE: source, ... NodeType.PARENT: parent, ... NodeType.CHILD: children ... } >>> links = LinkedNodes.create(links_dict) >>> links.source.id 'doc-1' - Creating with only some relationships
- Empty dict creates all-None instance
See Also
LinkedNodes.as_dict: Inverse operation converting LinkedNodes to dict. NodeType: Enum defining valid relationship types.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
validate_children_list(v)
classmethod
#
Validate that children field contains a list of NodeInfo objects.
Ensures the children field is a list (not a single NodeInfo instance). Called automatically by Pydantic during model instantiation and validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Any
|
Value to validate, expected to be list[NodeInfo] or None. |
required |
Returns:
| Type | Description |
|---|---|
list[NodeInfo] | None
|
The validated list of NodeInfo instances or None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If v is not None and not a list. |
Examples:
- Valid children list
- Invalid single NodeInfo for children raises ValidationError
- Empty children list is valid
Note
This validator is specific to the children field, which represents one-to-many relationships.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
validate_single_node(v)
classmethod
#
Validate that single-node fields contain NodeInfo objects.
Ensures that source, previous, next, and parent fields contain exactly one NodeInfo instance (not a list). Called automatically by Pydantic during model instantiation and validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
Any
|
Value to validate, expected to be NodeInfo or None. |
required |
Returns:
| Type | Description |
|---|---|
NodeInfo | None
|
The validated NodeInfo instance or None. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If v is not None and not a NodeInfo instance. |
Examples:
- Valid single node assignment
- Invalid list assignment to single-node field raises ValidationError
Note
This validator applies to: source, previous, next, parent fields. The children field has a separate validator for list validation.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
MetadataMode
#
Bases: str, Enum
Enumeration for controlling which metadata is included in different contexts.
Different use cases require different metadata visibility. For example, you might exclude certain metadata from embeddings (to avoid semantic pollution) while including it for LLM context (to provide additional information).
Attributes:
| Name | Type | Description |
|---|---|---|
ALL |
Include all metadata fields. |
|
EMBED |
Include only metadata for embedding generation (excludes fields in excluded_embed_metadata_keys). |
|
LLM |
Include only metadata for LLM context (excludes fields in excluded_llm_metadata_keys). |
|
NONE |
Exclude all metadata. |
Examples:
- Filtering metadata for embeddings
- Using with node content retrieval (conceptual)
- All mode values are plain strings
See Also
BaseNode.get_content: Uses this mode to control metadata inclusion. BaseNode.get_metadata_str: Filters metadata based on this mode. BaseNode.excluded_embed_metadata_keys: Metadata excluded for EMBED mode. BaseNode.excluded_llm_metadata_keys: Metadata excluded for LLM mode.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
MockEmbedding
#
Bases: BaseEmbedding
Mock embedding model for testing purposes.
Returns constant embedding vectors (all 0.5 values) for any input, allowing tests to run without requiring a real embedding model. This is useful for unit testing, integration testing, and development without the overhead of loading actual models or making API calls.
All embeddings returned are deterministic vectors of the specified dimension, filled with 0.5 values. This makes tests reproducible and fast.
Attributes:
| Name | Type | Description |
|---|---|---|
embed_dim |
int
|
Embedding dimension (must be positive). |
model_name |
str
|
Model name identifier (defaults to "mock-embedding"). |
Examples:
-
Creating a mock embedding model
-
Getting embeddings returns constant vectors
-
All inputs produce identical constant vectors
-
Validation of embed_dim
See Also
BaseEmbedding: Abstract base class that MockEmbedding implements.
Source code in libs/core/src/serapeum/core/embeddings/types.py
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 | |
class_name()
classmethod
#
Return the class name identifier.
Returns:
| Type | Description |
|---|---|
str
|
String "MockEmbedding" identifying this class. |
Examples:
- Getting the class name
Source code in libs/core/src/serapeum/core/embeddings/types.py
validate_embed_dim(v)
classmethod
#
Validate that embed_dim is positive.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
v
|
int
|
The embed_dim value to validate. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The validated embed_dim. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If embed_dim is not positive. |
Source code in libs/core/src/serapeum/core/embeddings/types.py
NodeContentType
#
Bases: str, Enum
Enumeration of content types that can be stored in a node.
This enum classifies the type of content a node contains, which helps downstream components (LLMs, embeddings, parsers) handle the content appropriately. String-based enum values enable direct serialization.
Attributes:
| Name | Type | Description |
|---|---|---|
TEXT |
Plain text content, the most common node type. |
|
IMAGE |
Image data or references to images. |
|
INDEX |
Index structures or metadata about other nodes. |
|
DOCUMENT |
Complete document content before chunking. |
|
MULTIMODAL |
Content combining multiple modalities (text + images). |
Examples:
- Checking content type
- Using in node metadata
- String comparison
See Also
NodeInfo: Uses this enum to specify node content type. BaseNode.get_type: Abstract method returning content type string.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
NodeInfo
#
Bases: SerializableModel
Lightweight reference to a node with essential identification metadata.
NodeInfo provides a compact representation of a node without its full content, useful for creating references and relationships between nodes. It includes the node's ID, content type, metadata, and optional hash for change detection.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
str
|
Unique identifier for the node. |
type |
Annotated[NodeContentType, EnumNameSerializer] | str | None
|
Content type classification (NodeContentType enum or string). |
metadata |
dict[str, Any]
|
Arbitrary metadata dictionary for the node. |
hash |
str | None
|
Optional hash value for detecting content changes. |
Examples:
- Creating a basic node reference
- Serialization and deserialization
- Using with hash for change detection
See Also
BaseNode: Full node implementation that generates NodeInfo. LinkedNodes: Container for node relationships using NodeInfo. SerializableModel: Base class providing serialization methods.
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
class_name()
classmethod
#
Return the class name identifier for serialization.
Returns:
| Type | Description |
|---|---|
str
|
Always returns "NodeInfo" as the stable class identifier. |
Examples:
- Getting class name
Source code in libs/core/src/serapeum/core/base/embeddings/types.py
NodeType
#
Bases: str, Enum
Node links used in BaseNode class.
Attributes:
| Name | Type | Description |
|---|---|---|
SOURCE |
The node is the source document. |
|
PREVIOUS |
The node is the previous node in the document. |
|
NEXT |
The node is the next node in the document. |
|
PARENT |
The node is the parent node in the document. |
|
CHILD |
The node is a child node in the document. |