lionagi 0.0.208__py3-none-any.whl → 0.0.210__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- lionagi/__init__.py +4 -6
- lionagi/api_service/base_endpoint.py +65 -0
- lionagi/api_service/base_rate_limiter.py +121 -0
- lionagi/api_service/base_service.py +146 -0
- lionagi/api_service/chat_completion.py +6 -0
- lionagi/api_service/embeddings.py +6 -0
- lionagi/api_service/payload_package.py +47 -0
- lionagi/api_service/status_tracker.py +29 -0
- lionagi/core/__init__.py +5 -9
- lionagi/core/branch.py +1191 -0
- lionagi/core/flow.py +423 -0
- lionagi/core/{instruction_set/instruction_set.py → instruction_set.py} +3 -3
- lionagi/core/session.py +872 -0
- lionagi/schema/__init__.py +5 -8
- lionagi/schema/base_schema.py +821 -0
- lionagi/{_services → services}/base_service.py +4 -4
- lionagi/{_services → services}/oai.py +4 -4
- lionagi/structures/graph.py +1 -1
- lionagi/structures/relationship.py +1 -1
- lionagi/structures/structure.py +1 -1
- lionagi/tools/tool_manager.py +0 -163
- lionagi/tools/tool_util.py +2 -1
- lionagi/utils/__init__.py +7 -14
- lionagi/utils/api_util.py +63 -2
- lionagi/utils/core_utils.py +338 -0
- lionagi/utils/sys_util.py +3 -3
- lionagi/version.py +1 -1
- {lionagi-0.0.208.dist-info → lionagi-0.0.210.dist-info}/METADATA +28 -29
- lionagi-0.0.210.dist-info/RECORD +56 -0
- lionagi/_services/anthropic.py +0 -79
- lionagi/_services/anyscale.py +0 -0
- lionagi/_services/azure.py +0 -1
- lionagi/_services/bedrock.py +0 -0
- lionagi/_services/everlyai.py +0 -0
- lionagi/_services/gemini.py +0 -0
- lionagi/_services/gpt4all.py +0 -0
- lionagi/_services/huggingface.py +0 -0
- lionagi/_services/litellm.py +0 -33
- lionagi/_services/localai.py +0 -0
- lionagi/_services/openllm.py +0 -0
- lionagi/_services/openrouter.py +0 -44
- lionagi/_services/perplexity.py +0 -0
- lionagi/_services/predibase.py +0 -0
- lionagi/_services/rungpt.py +0 -0
- lionagi/_services/vllm.py +0 -0
- lionagi/_services/xinference.py +0 -0
- lionagi/agents/planner.py +0 -1
- lionagi/agents/prompter.py +0 -1
- lionagi/agents/scorer.py +0 -1
- lionagi/agents/summarizer.py +0 -1
- lionagi/agents/validator.py +0 -1
- lionagi/bridge/__init__.py +0 -22
- lionagi/bridge/langchain.py +0 -195
- lionagi/bridge/llama_index.py +0 -266
- lionagi/core/branch/__init__.py +0 -0
- lionagi/core/branch/branch.py +0 -841
- lionagi/core/branch/cluster.py +0 -1
- lionagi/core/branch/conversation.py +0 -787
- lionagi/core/core_util.py +0 -0
- lionagi/core/flow/__init__.py +0 -0
- lionagi/core/flow/flow.py +0 -19
- lionagi/core/flow/flow_util.py +0 -62
- lionagi/core/instruction_set/__init__.py +0 -0
- lionagi/core/messages/__init__.py +0 -0
- lionagi/core/sessions/__init__.py +0 -0
- lionagi/core/sessions/session.py +0 -504
- lionagi/datastores/__init__.py +0 -1
- lionagi/datastores/chroma.py +0 -1
- lionagi/datastores/deeplake.py +0 -1
- lionagi/datastores/elasticsearch.py +0 -1
- lionagi/datastores/lantern.py +0 -1
- lionagi/datastores/pinecone.py +0 -1
- lionagi/datastores/postgres.py +0 -1
- lionagi/datastores/qdrant.py +0 -1
- lionagi/loaders/__init__.py +0 -18
- lionagi/loaders/chunker.py +0 -166
- lionagi/loaders/load_util.py +0 -240
- lionagi/loaders/reader.py +0 -122
- lionagi/models/__init__.py +0 -0
- lionagi/models/base_model.py +0 -0
- lionagi/models/imodel.py +0 -53
- lionagi/schema/async_queue.py +0 -158
- lionagi/schema/base_condition.py +0 -1
- lionagi/schema/base_node.py +0 -422
- lionagi/schema/base_tool.py +0 -44
- lionagi/schema/data_logger.py +0 -126
- lionagi/schema/data_node.py +0 -88
- lionagi/schema/status_tracker.py +0 -37
- lionagi/tests/test_utils/test_encrypt_util.py +0 -323
- lionagi/utils/encrypt_util.py +0 -283
- lionagi/utils/url_util.py +0 -55
- lionagi-0.0.208.dist-info/RECORD +0 -106
- lionagi/{agents → api_service}/__init__.py +0 -0
- lionagi/core/{branch/branch_manager.py → branch_manager.py} +0 -0
- lionagi/core/{messages/messages.py → messages.py} +3 -3
- /lionagi/{_services → services}/__init__.py +0 -0
- /lionagi/{_services → services}/mistralai.py +0 -0
- /lionagi/{_services → services}/mlx_service.py +0 -0
- /lionagi/{_services → services}/ollama.py +0 -0
- /lionagi/{_services → services}/services.py +0 -0
- /lionagi/{_services → services}/transformers.py +0 -0
- {lionagi-0.0.208.dist-info → lionagi-0.0.210.dist-info}/LICENSE +0 -0
- {lionagi-0.0.208.dist-info → lionagi-0.0.210.dist-info}/WHEEL +0 -0
- {lionagi-0.0.208.dist-info → lionagi-0.0.210.dist-info}/top_level.txt +0 -0
lionagi/schema/async_queue.py
DELETED
@@ -1,158 +0,0 @@
|
|
1
|
-
# import asyncio
|
2
|
-
# from typing import Any, Callable
|
3
|
-
# from ..utils.call_util import tcall
|
4
|
-
|
5
|
-
# class AsyncQueue:
|
6
|
-
# """
|
7
|
-
# A queue class that handles asynchronous operations using asyncio.
|
8
|
-
|
9
|
-
# This class provides an asynchronous queue that can enqueue items, process them
|
10
|
-
# asynchronously, and support graceful shutdowns. It is designed to facilitate
|
11
|
-
# concurrent task processing in an orderly and controlled manner.
|
12
|
-
|
13
|
-
# Attributes:
|
14
|
-
# queue (asyncio.Queue):
|
15
|
-
# A queue to hold items for asynchronous processing.
|
16
|
-
# _stop_event (asyncio.Event):
|
17
|
-
# An event to signal when the queue should stop processing.
|
18
|
-
|
19
|
-
# Methods:
|
20
|
-
# enqueue(item):
|
21
|
-
# Add an item to the queue for processing.
|
22
|
-
# dequeue():
|
23
|
-
# Remove and return an item from the queue.
|
24
|
-
# join():
|
25
|
-
# Wait until all items in the queue have been processed.
|
26
|
-
# stop():
|
27
|
-
# Signal to stop processing new items in the queue.
|
28
|
-
# stopped():
|
29
|
-
# Check if the queue has been signaled to stop.
|
30
|
-
# process_requests(func):
|
31
|
-
# Process items using a provided function.
|
32
|
-
# """
|
33
|
-
|
34
|
-
# def __init__(self) -> None:
|
35
|
-
# """
|
36
|
-
# Initializes an AsyncQueue object with an empty asyncio Queue and a stop event.
|
37
|
-
# """
|
38
|
-
# self.queue = asyncio.Queue()
|
39
|
-
# self._stop_event = asyncio.Event()
|
40
|
-
|
41
|
-
# async def enqueue(self, item: Any) -> None:
|
42
|
-
# """
|
43
|
-
# Asynchronously add an item to the queue for processing.
|
44
|
-
|
45
|
-
# Parameters:
|
46
|
-
# item (Any): The item to be added to the queue.
|
47
|
-
|
48
|
-
# Example:
|
49
|
-
# >>> async_queue = AsyncQueue()
|
50
|
-
# >>> asyncio.run(async_queue.enqueue('Task 1'))
|
51
|
-
# """
|
52
|
-
# await self.queue.put(item)
|
53
|
-
|
54
|
-
# async def dequeue(self) -> Any:
|
55
|
-
# """
|
56
|
-
# Asynchronously remove and return an item from the queue.
|
57
|
-
|
58
|
-
# If the queue is empty, this method will wait until an item is available.
|
59
|
-
|
60
|
-
# Returns:
|
61
|
-
# Any: The next item from the queue.
|
62
|
-
|
63
|
-
# Example:
|
64
|
-
# >>> async_queue = AsyncQueue()
|
65
|
-
# >>> asyncio.run(async_queue.enqueue('Task 1'))
|
66
|
-
# >>> asyncio.run(async_queue.dequeue())
|
67
|
-
# 'Task 1'
|
68
|
-
# """
|
69
|
-
# return await self.queue.get()
|
70
|
-
|
71
|
-
# async def join(self) -> None:
|
72
|
-
# """
|
73
|
-
# Asynchronously wait until all items in the queue have been processed.
|
74
|
-
|
75
|
-
# This method blocks until every item that has been enqueued is processed,
|
76
|
-
# ensuring that all tasks are completed.
|
77
|
-
|
78
|
-
# Example:
|
79
|
-
# >>> async_queue = AsyncQueue()
|
80
|
-
# >>> asyncio.run(async_queue.enqueue('Task 1'))
|
81
|
-
# >>> asyncio.run(async_queue.join()) # This will block until 'Task 1' is processed.
|
82
|
-
# """
|
83
|
-
# await self.queue.join()
|
84
|
-
|
85
|
-
# async def stop(self) -> None:
|
86
|
-
# """
|
87
|
-
# Signal the queue to stop processing new items.
|
88
|
-
|
89
|
-
# Once called, the queue will not process any new items after the current ones
|
90
|
-
# are completed, allowing for a graceful shutdown.
|
91
|
-
|
92
|
-
# Example:
|
93
|
-
# >>> async_queue = AsyncQueue()
|
94
|
-
# >>> asyncio.run(async_queue.stop()) # This signals the queue to stop processing.
|
95
|
-
# """
|
96
|
-
# self._stop_event.set()
|
97
|
-
|
98
|
-
# def stopped(self) -> bool:
|
99
|
-
# """
|
100
|
-
# Check if the queue has been signaled to stop processing.
|
101
|
-
|
102
|
-
# Returns:
|
103
|
-
# bool: True if a stop has been signaled, False otherwise.
|
104
|
-
|
105
|
-
# Example:
|
106
|
-
# >>> async_queue = AsyncQueue()
|
107
|
-
# >>> asyncio.run(async_queue.stop())
|
108
|
-
# >>> async_queue.stopped()
|
109
|
-
# True
|
110
|
-
# """
|
111
|
-
# return self._stop_event.is_set()
|
112
|
-
|
113
|
-
# # async def process_requests(self, func: Callable[[Any], Any]) -> None:
|
114
|
-
# # """
|
115
|
-
# # Asynchronously process items from the queue using the provided function.
|
116
|
-
|
117
|
-
# # Continuously dequeues items and applies the given function to each.
|
118
|
-
# # The processing stops when the queue is signaled to stop or a sentinel value (`None`) is dequeued.
|
119
|
-
|
120
|
-
# # Parameters:
|
121
|
-
# # func (Callable[[Any], Any]): A coroutine function to process items from the queue.
|
122
|
-
|
123
|
-
# # Example:
|
124
|
-
# # >>> async def sample_processing(task):
|
125
|
-
# # ... print("Processing:", task)
|
126
|
-
# # >>> async_queue = AsyncQueue()
|
127
|
-
# # >>> asyncio.run(async_queue.enqueue('Task 1'))
|
128
|
-
# # >>> asyncio.run(async_queue.process_requests(sample_processing))
|
129
|
-
# # Processing: Task 1
|
130
|
-
# # """
|
131
|
-
# # while not self.stopped():
|
132
|
-
# # item = await self.dequeue()
|
133
|
-
# # if item is None: # Using `None` as a sentinel value to cease processing.
|
134
|
-
# # await self.stop()
|
135
|
-
# # break
|
136
|
-
# # await func(item)
|
137
|
-
|
138
|
-
# async def process_requests(self, func, timeout=None):
|
139
|
-
# """
|
140
|
-
# Process items with timeout management for each task.
|
141
|
-
# """
|
142
|
-
# tasks = set()
|
143
|
-
# while not self.stopped():
|
144
|
-
# if len(tasks) >= self.max_concurrent_tasks:
|
145
|
-
# done, tasks = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
146
|
-
|
147
|
-
# item = await self.dequeue()
|
148
|
-
# if item is None:
|
149
|
-
# await self.stop()
|
150
|
-
# break
|
151
|
-
|
152
|
-
# # Wrap the function call with tcall for timeout handling
|
153
|
-
# task = asyncio.create_task(tcall(item, func, timeout=timeout))
|
154
|
-
# tasks.add(task)
|
155
|
-
|
156
|
-
# if tasks:
|
157
|
-
# await asyncio.wait(tasks)
|
158
|
-
|
lionagi/schema/base_condition.py
DELETED
@@ -1 +0,0 @@
|
|
1
|
-
# TODO
|
lionagi/schema/base_node.py
DELETED
@@ -1,422 +0,0 @@
|
|
1
|
-
import json
|
2
|
-
import xml.etree.ElementTree as ET
|
3
|
-
from typing import Any, Dict, Optional, TypeVar, Type, List, Callable, Union
|
4
|
-
from pydantic import BaseModel, Field, AliasChoices
|
5
|
-
|
6
|
-
from ..utils.sys_util import create_id, change_dict_key, is_schema
|
7
|
-
from ..utils.encrypt_util import EncrytionUtil
|
8
|
-
|
9
|
-
T = TypeVar('T', bound='BaseNode')
|
10
|
-
|
11
|
-
|
12
|
-
class BaseNode(BaseModel):
|
13
|
-
"""
|
14
|
-
The base class for nodes containing general information and metadata.
|
15
|
-
|
16
|
-
Attributes:
|
17
|
-
id_ (str): The unique identifier for the node.
|
18
|
-
metadata (Dict[str, Any]): Additional metadata for the node.
|
19
|
-
label (Optional[str]): An optional label for the node.
|
20
|
-
related_nodes (List[str]): List of related node IDs.
|
21
|
-
content (Union[str, Dict[str, Any], None, Any]): The content of the node.
|
22
|
-
|
23
|
-
Examples:
|
24
|
-
>>> node = BaseNode(content="Example content")
|
25
|
-
>>> node_dict = node.to_dict()
|
26
|
-
>>> json_str = node.to_json()
|
27
|
-
>>> same_node = BaseNode.from_json(json_str)
|
28
|
-
"""
|
29
|
-
|
30
|
-
id_: str = Field(default_factory=lambda: str(create_id()), alias="node_id")
|
31
|
-
metadata: Dict[str, Any] = Field(default_factory=dict)
|
32
|
-
label: Optional[str] = None
|
33
|
-
related_nodes: List[str] = Field(default_factory=list)
|
34
|
-
content: Union[str, Dict[str, Any], None, Any] = Field(
|
35
|
-
default=None, validation_alias=AliasChoices('text', 'page_content', 'chunk_content')
|
36
|
-
)
|
37
|
-
|
38
|
-
class Config:
|
39
|
-
extra = 'allow'
|
40
|
-
populate_by_name = True
|
41
|
-
validate_assignment = True
|
42
|
-
validate_return = True
|
43
|
-
str_strip_whitespace = True
|
44
|
-
|
45
|
-
@classmethod
|
46
|
-
def from_dict(cls, data: Dict[str, Any]) -> T:
|
47
|
-
"""
|
48
|
-
Creates an instance of the class from a dictionary.
|
49
|
-
|
50
|
-
Args:
|
51
|
-
data: A dictionary containing the node's data.
|
52
|
-
|
53
|
-
Returns:
|
54
|
-
An instance of the class.
|
55
|
-
|
56
|
-
Examples:
|
57
|
-
>>> data = {"content": "Example content"}
|
58
|
-
>>> node = BaseNode.from_dict(data)
|
59
|
-
"""
|
60
|
-
return cls(**data)
|
61
|
-
|
62
|
-
@classmethod
|
63
|
-
def from_json(cls: Type[T], json_str: str, **kwargs) -> T:
|
64
|
-
"""
|
65
|
-
Creates an instance of the class from a JSON string.
|
66
|
-
|
67
|
-
Args:
|
68
|
-
json_str: A JSON string containing the node's data.
|
69
|
-
**kwargs: Additional keyword arguments to pass to json.loads.
|
70
|
-
|
71
|
-
Returns:
|
72
|
-
An instance of the class.
|
73
|
-
|
74
|
-
Examples:
|
75
|
-
>>> json_str = '{"content": "Example content"}'
|
76
|
-
>>> node = BaseNode.from_json(json_str)
|
77
|
-
"""
|
78
|
-
try:
|
79
|
-
data = json.loads(json_str, **kwargs)
|
80
|
-
return cls(**data)
|
81
|
-
except json.JSONDecodeError as e:
|
82
|
-
raise ValueError("Invalid JSON string provided for deserialization.") from e
|
83
|
-
|
84
|
-
@classmethod
|
85
|
-
def from_xml(cls, xml_str: str) -> T:
|
86
|
-
"""
|
87
|
-
Creates an instance of the class from an XML string.
|
88
|
-
|
89
|
-
Args:
|
90
|
-
xml_str: An XML string containing the node's data.
|
91
|
-
|
92
|
-
Returns:
|
93
|
-
An instance of the class.
|
94
|
-
|
95
|
-
Examples:
|
96
|
-
>>> xml_str = "<BaseNode><content>Example content</content></BaseNode>"
|
97
|
-
>>> node = BaseNode.from_xml(xml_str)
|
98
|
-
"""
|
99
|
-
root = ET.fromstring(xml_str)
|
100
|
-
data = cls._xml_to_dict(root)
|
101
|
-
return cls(**data)
|
102
|
-
|
103
|
-
def to_json(self) -> str:
|
104
|
-
"""
|
105
|
-
Converts the instance to a JSON string.
|
106
|
-
|
107
|
-
Returns:
|
108
|
-
A JSON string representing the node.
|
109
|
-
|
110
|
-
Examples:
|
111
|
-
>>> node = BaseNode(content="Example content")
|
112
|
-
>>> json_str = node.to_json()
|
113
|
-
"""
|
114
|
-
return self.model_dump_json(by_alias=True)
|
115
|
-
|
116
|
-
def to_dict(self) -> Dict[str, Any]:
|
117
|
-
"""
|
118
|
-
Converts the instance to a dictionary.
|
119
|
-
|
120
|
-
Returns:
|
121
|
-
A dictionary representing the node.
|
122
|
-
|
123
|
-
Examples:
|
124
|
-
>>> node = BaseNode(content="Example content")
|
125
|
-
>>> node_dict = node.to_dict()
|
126
|
-
"""
|
127
|
-
return self.model_dump(by_alias=True)
|
128
|
-
|
129
|
-
def to_xml(self) -> str:
|
130
|
-
"""
|
131
|
-
Converts the instance to an XML string.
|
132
|
-
|
133
|
-
Returns:
|
134
|
-
An XML string representing the node.
|
135
|
-
|
136
|
-
Examples:
|
137
|
-
>>> node = BaseNode(content="Example content")
|
138
|
-
>>> xml_str = node.to_xml()
|
139
|
-
"""
|
140
|
-
root = ET.Element(self.__class__.__name__)
|
141
|
-
for attr, value in self.to_dict().items():
|
142
|
-
child = ET.SubElement(root, attr)
|
143
|
-
child.text = str(value)
|
144
|
-
return ET.tostring(root, encoding='unicode')
|
145
|
-
|
146
|
-
def validate_content(self, schema: Dict[str, type]) -> bool:
|
147
|
-
"""
|
148
|
-
Validates the node's content against a schema.
|
149
|
-
|
150
|
-
Args:
|
151
|
-
schema: The schema to validate against.
|
152
|
-
|
153
|
-
Returns:
|
154
|
-
True if the content matches the schema, False otherwise.
|
155
|
-
|
156
|
-
Examples:
|
157
|
-
>>> schema = {"title": str, "body": str}
|
158
|
-
>>> node = BaseNode(content={"title": "Example", "body": "Content"})
|
159
|
-
>>> node.validate_content(schema)
|
160
|
-
"""
|
161
|
-
if not isinstance(self.content, dict):
|
162
|
-
return False
|
163
|
-
return is_schema(self.content, schema)
|
164
|
-
|
165
|
-
@property
|
166
|
-
def meta_keys(self) -> List[str]:
|
167
|
-
"""
|
168
|
-
List of metadata keys.
|
169
|
-
|
170
|
-
Returns:
|
171
|
-
A list of keys in the metadata dictionary.
|
172
|
-
|
173
|
-
Examples:
|
174
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
175
|
-
>>> node.meta_keys
|
176
|
-
"""
|
177
|
-
return list(self.metadata.keys())
|
178
|
-
|
179
|
-
def has_meta_key(self, key: str) -> bool:
|
180
|
-
"""
|
181
|
-
Checks if a metadata key exists.
|
182
|
-
|
183
|
-
Args:
|
184
|
-
key: The metadata key to check for.
|
185
|
-
|
186
|
-
Returns:
|
187
|
-
True if the key exists, False otherwise.
|
188
|
-
|
189
|
-
Examples:
|
190
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
191
|
-
>>> node.has_meta_key("author")
|
192
|
-
"""
|
193
|
-
return key in self.metadata
|
194
|
-
|
195
|
-
def get_meta_key(self, key: str) -> Any:
|
196
|
-
"""
|
197
|
-
Retrieves a value from the metadata dictionary.
|
198
|
-
|
199
|
-
Args:
|
200
|
-
key: The key for the value to retrieve.
|
201
|
-
|
202
|
-
Returns:
|
203
|
-
The value associated with the key, if it exists.
|
204
|
-
|
205
|
-
Examples:
|
206
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
207
|
-
>>> node.get_meta_key("author")
|
208
|
-
"""
|
209
|
-
return self.metadata.get(key)
|
210
|
-
|
211
|
-
def change_meta_key(self, old_key: str, new_key: str) -> bool:
|
212
|
-
"""
|
213
|
-
Changes a key in the metadata dictionary.
|
214
|
-
|
215
|
-
Args:
|
216
|
-
old_key: The old key name.
|
217
|
-
new_key: The new key name.
|
218
|
-
|
219
|
-
Returns:
|
220
|
-
True if the key was changed successfully, False otherwise.
|
221
|
-
|
222
|
-
Examples:
|
223
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
224
|
-
>>> node.change_meta_key("author", "creator")
|
225
|
-
"""
|
226
|
-
if old_key in self.metadata:
|
227
|
-
change_dict_key(self.metadata, old_key=old_key, new_key=new_key)
|
228
|
-
return True
|
229
|
-
return False
|
230
|
-
|
231
|
-
def delete_meta_key(self, key: str) -> bool:
|
232
|
-
"""
|
233
|
-
Deletes a key from the metadata dictionary.
|
234
|
-
|
235
|
-
Args:
|
236
|
-
key: The key to delete.
|
237
|
-
|
238
|
-
Returns:
|
239
|
-
True if the key was deleted, False otherwise.
|
240
|
-
|
241
|
-
Examples:
|
242
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
243
|
-
>>> node.delete_meta_key("author")
|
244
|
-
"""
|
245
|
-
if key in self.metadata:
|
246
|
-
del self.metadata[key]
|
247
|
-
return True
|
248
|
-
return False
|
249
|
-
|
250
|
-
def merge_meta(self, other_metadata: Dict[str, Any], overwrite: bool = False) -> None:
|
251
|
-
"""
|
252
|
-
Merges another metadata dictionary into the current metadata.
|
253
|
-
|
254
|
-
Args:
|
255
|
-
other_metadata: The metadata dictionary to merge.
|
256
|
-
overwrite: If True, existing keys will be overwritten.
|
257
|
-
|
258
|
-
Examples:
|
259
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
260
|
-
>>> new_meta = {"editor": "Jane Smith"}
|
261
|
-
>>> node.merge_meta(new_meta)
|
262
|
-
"""
|
263
|
-
if not overwrite:
|
264
|
-
other_metadata = ({
|
265
|
-
k: v for k, v in other_metadata.items()
|
266
|
-
if k not in self.metadata
|
267
|
-
})
|
268
|
-
self.metadata.update(other_metadata)
|
269
|
-
|
270
|
-
def clear_meta(self) -> None:
|
271
|
-
"""
|
272
|
-
Clears the metadata dictionary.
|
273
|
-
|
274
|
-
Examples:
|
275
|
-
>>> node = BaseNode(metadata={"author": "John Doe"})
|
276
|
-
>>> node.clear_meta()
|
277
|
-
"""
|
278
|
-
|
279
|
-
self.metadata.clear()
|
280
|
-
|
281
|
-
def filter_meta(self, filter_func: Callable[[Any], bool]) -> Dict[str, Any]:
|
282
|
-
"""
|
283
|
-
Filters the metadata dictionary based on a filter function.
|
284
|
-
|
285
|
-
Args:
|
286
|
-
filter_func: The function to filter metadata items.
|
287
|
-
|
288
|
-
Returns:
|
289
|
-
A dictionary containing the filtered metadata items.
|
290
|
-
|
291
|
-
Examples:
|
292
|
-
>>> node = BaseNode(metadata={"author": "John Doe", "year": 2020})
|
293
|
-
>>> filtered_meta = node.filter_meta(lambda x: isinstance(x, str))
|
294
|
-
"""
|
295
|
-
return {k: v for k, v in self.metadata.items() if filter_func(v)}
|
296
|
-
|
297
|
-
def validate_meta(self, schema: Dict[str, type]) -> bool:
|
298
|
-
"""
|
299
|
-
Validates the metadata against a schema.
|
300
|
-
|
301
|
-
Args:
|
302
|
-
schema: The schema to validate against.
|
303
|
-
|
304
|
-
Returns:
|
305
|
-
True if the metadata matches the schema, False otherwise.
|
306
|
-
|
307
|
-
Examples:
|
308
|
-
>>> schema = {"author": str, "year": int}
|
309
|
-
>>> node = BaseNode(metadata={"author": "John Doe", "year": 2020})
|
310
|
-
>>> node.validate_meta(schema)
|
311
|
-
"""
|
312
|
-
return is_schema(dict_=self.metadata, schema=schema)
|
313
|
-
|
314
|
-
def encrypt_content(self, key: str) -> None:
|
315
|
-
"""
|
316
|
-
Encrypts the node's content.
|
317
|
-
|
318
|
-
Args:
|
319
|
-
key: The encryption key.
|
320
|
-
|
321
|
-
Examples:
|
322
|
-
>>> node = BaseNode(content="Sensitive information")
|
323
|
-
>>> node.encrypt_content("my_secret_key")
|
324
|
-
"""
|
325
|
-
self.content = EncrytionUtil.encrypt(self.content, key)
|
326
|
-
|
327
|
-
def decrypt_content(self, key: str) -> None:
|
328
|
-
"""
|
329
|
-
Decrypts the node's content.
|
330
|
-
|
331
|
-
Args:
|
332
|
-
key: The decryption key.
|
333
|
-
|
334
|
-
Examples:
|
335
|
-
>>> node = BaseNode(content="Encrypted content")
|
336
|
-
>>> node.decrypt_content("my_secret_key")
|
337
|
-
"""
|
338
|
-
self.content = EncrytionUtil.decrypt(self.content, key)
|
339
|
-
|
340
|
-
def add_related_node(self, node_id: str) -> bool:
|
341
|
-
"""
|
342
|
-
Adds a related node ID to the list of related nodes.
|
343
|
-
|
344
|
-
Args:
|
345
|
-
node_id: The ID of the related node to add.
|
346
|
-
|
347
|
-
Returns:
|
348
|
-
True if the ID was added, False if it was already in the list.
|
349
|
-
|
350
|
-
Examples:
|
351
|
-
>>> node = BaseNode()
|
352
|
-
>>> related_node_id = "123456"
|
353
|
-
>>> node.add_related_node(related_node_id)
|
354
|
-
"""
|
355
|
-
if node_id not in self.related_nodes:
|
356
|
-
self.related_nodes.append(node_id)
|
357
|
-
return True
|
358
|
-
return False
|
359
|
-
|
360
|
-
def remove_related_node(self, node_id: str) -> bool:
|
361
|
-
"""
|
362
|
-
Removes a related node ID from the list of related nodes.
|
363
|
-
|
364
|
-
Args:
|
365
|
-
node_id: The ID of the related node to remove.
|
366
|
-
|
367
|
-
Returns:
|
368
|
-
True if the ID was removed, False if it was not in the list.
|
369
|
-
|
370
|
-
Examples:
|
371
|
-
>>> node = BaseNode(related_nodes=["123456"])
|
372
|
-
>>> related_node_id = "123456"
|
373
|
-
>>> node.remove_related_node(related_node_id)
|
374
|
-
"""
|
375
|
-
if node_id in self.related_nodes:
|
376
|
-
self.related_nodes.remove(node_id)
|
377
|
-
return True
|
378
|
-
return False
|
379
|
-
|
380
|
-
def __str__(self) -> str:
|
381
|
-
"""String representation of the BaseNode instance."""
|
382
|
-
content_preview = (str(self.content)[:75] + '...') if len(str(self.content)) > 75 else str(self.content)
|
383
|
-
metadata_preview = str(self.metadata)[:75] + '...' if len(str(self.metadata)) > 75 else str(self.metadata)
|
384
|
-
related_nodes_preview = ', '.join(self.related_nodes[:3]) + ('...' if len(self.related_nodes) > 3 else '')
|
385
|
-
return (f"{self.__class__.__name__}(id={self.id_}, label={self.label}, "
|
386
|
-
f"content='{content_preview}', metadata='{metadata_preview}', "
|
387
|
-
f"related_nodes=[{related_nodes_preview}])")
|
388
|
-
|
389
|
-
def __repr__(self):
|
390
|
-
"""Machine-readable representation of the BaseNode instance."""
|
391
|
-
return f"{self.__class__.__name__}({self.to_json()})"
|
392
|
-
|
393
|
-
@staticmethod
|
394
|
-
def _xml_to_dict(root: ET.Element) -> Dict[str, Any]:
|
395
|
-
data = {}
|
396
|
-
for child in root:
|
397
|
-
data[child.tag] = child.text
|
398
|
-
return data
|
399
|
-
|
400
|
-
|
401
|
-
# def is_empty(self) -> bool:
|
402
|
-
# return not self.content and not self.metadata
|
403
|
-
|
404
|
-
# def copy(self, n: int = 1) -> Union[List[T], T]:
|
405
|
-
# return create_copy(self, n)
|
406
|
-
|
407
|
-
# def data_equals(self, other: 'BaseNode') -> bool:
|
408
|
-
# return (
|
409
|
-
# self.content == other.content and
|
410
|
-
# self.metadata == other.metadata and
|
411
|
-
# self.related_nodes == other.related_nodes
|
412
|
-
# )
|
413
|
-
|
414
|
-
# def is_copy_of(self, other: 'BaseNode') -> bool:
|
415
|
-
# return (
|
416
|
-
# self.data_equals(other) and
|
417
|
-
# self is not other
|
418
|
-
# )
|
419
|
-
|
420
|
-
# def __eq__(self, other: 'BaseNode') -> bool:
|
421
|
-
# # return (self.id_ == other.id_ and self.data_equals(other))
|
422
|
-
# return self.id_ == other.id_
|
lionagi/schema/base_tool.py
DELETED
@@ -1,44 +0,0 @@
|
|
1
|
-
from typing import Any
|
2
|
-
from pydantic import field_serializer
|
3
|
-
from .base_node import BaseNode
|
4
|
-
|
5
|
-
class Tool(BaseNode):
|
6
|
-
"""
|
7
|
-
A class representing a tool with a function, content, parser, and schema.
|
8
|
-
|
9
|
-
Attributes:
|
10
|
-
func (Callable): The function associated with the tool.
|
11
|
-
content (Any, optional): The content to be processed by the tool. Defaults to None.
|
12
|
-
parser (Any, optional): The parser to be used with the tool. Defaults to None.
|
13
|
-
schema_ (Dict): The schema definition for the tool.
|
14
|
-
|
15
|
-
Examples:
|
16
|
-
>>> tool = Tool(func=my_function, schema_={'type': 'string'})
|
17
|
-
>>> serialized_func = tool.serialize_func()
|
18
|
-
>>> print(serialized_func)
|
19
|
-
'my_function'
|
20
|
-
"""
|
21
|
-
|
22
|
-
func: Any
|
23
|
-
content: Any = None
|
24
|
-
parser: Any = None
|
25
|
-
schema_: dict
|
26
|
-
|
27
|
-
@field_serializer('func')
|
28
|
-
def serialize_func(self, func):
|
29
|
-
"""
|
30
|
-
Serialize the function to its name.
|
31
|
-
|
32
|
-
Args:
|
33
|
-
func (Callable): The function to serialize.
|
34
|
-
|
35
|
-
Returns:
|
36
|
-
str: The name of the function.
|
37
|
-
|
38
|
-
Examples:
|
39
|
-
>>> def my_function():
|
40
|
-
... pass
|
41
|
-
>>> Tool.serialize_func(my_function)
|
42
|
-
'my_function'
|
43
|
-
"""
|
44
|
-
return func.__name__
|