lionagi 0.0.115__py3-none-any.whl → 0.0.204__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- lionagi/__init__.py +1 -2
- lionagi/_services/__init__.py +5 -0
- lionagi/_services/anthropic.py +79 -0
- lionagi/_services/base_service.py +414 -0
- lionagi/_services/oai.py +98 -0
- lionagi/_services/openrouter.py +44 -0
- lionagi/_services/services.py +91 -0
- lionagi/_services/transformers.py +46 -0
- lionagi/bridge/langchain.py +26 -16
- lionagi/bridge/llama_index.py +50 -20
- lionagi/configs/oai_configs.py +2 -14
- lionagi/configs/openrouter_configs.py +2 -2
- lionagi/core/__init__.py +7 -8
- lionagi/core/branch/branch.py +589 -0
- lionagi/core/branch/branch_manager.py +139 -0
- lionagi/core/branch/conversation.py +484 -0
- lionagi/core/core_util.py +59 -0
- lionagi/core/flow/flow.py +19 -0
- lionagi/core/flow/flow_util.py +62 -0
- lionagi/core/instruction_set/__init__.py +0 -5
- lionagi/core/instruction_set/instruction_set.py +343 -0
- lionagi/core/messages/messages.py +176 -0
- lionagi/core/sessions/__init__.py +0 -5
- lionagi/core/sessions/session.py +428 -0
- lionagi/loaders/chunker.py +51 -47
- lionagi/loaders/load_util.py +2 -2
- lionagi/loaders/reader.py +45 -39
- lionagi/models/imodel.py +53 -0
- lionagi/schema/async_queue.py +158 -0
- lionagi/schema/base_node.py +318 -147
- lionagi/schema/base_tool.py +31 -1
- lionagi/schema/data_logger.py +74 -38
- lionagi/schema/data_node.py +57 -6
- lionagi/structures/graph.py +132 -10
- lionagi/structures/relationship.py +58 -20
- lionagi/structures/structure.py +36 -25
- lionagi/tests/test_utils/test_api_util.py +219 -0
- lionagi/tests/test_utils/test_call_util.py +785 -0
- lionagi/tests/test_utils/test_encrypt_util.py +323 -0
- lionagi/tests/test_utils/test_io_util.py +238 -0
- lionagi/tests/test_utils/test_nested_util.py +338 -0
- lionagi/tests/test_utils/test_sys_util.py +358 -0
- lionagi/tools/tool_manager.py +186 -0
- lionagi/tools/tool_util.py +266 -3
- lionagi/utils/__init__.py +21 -61
- lionagi/utils/api_util.py +359 -71
- lionagi/utils/call_util.py +839 -264
- lionagi/utils/encrypt_util.py +283 -16
- lionagi/utils/io_util.py +178 -93
- lionagi/utils/nested_util.py +672 -0
- lionagi/utils/pd_util.py +57 -0
- lionagi/utils/sys_util.py +284 -156
- lionagi/utils/url_util.py +55 -0
- lionagi/version.py +1 -1
- {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/METADATA +21 -17
- lionagi-0.0.204.dist-info/RECORD +106 -0
- lionagi/core/conversations/__init__.py +0 -5
- lionagi/core/conversations/conversation.py +0 -107
- lionagi/core/flows/__init__.py +0 -8
- lionagi/core/flows/flow.py +0 -8
- lionagi/core/flows/flow_util.py +0 -62
- lionagi/core/instruction_set/instruction_sets.py +0 -7
- lionagi/core/sessions/sessions.py +0 -185
- lionagi/endpoints/__init__.py +0 -5
- lionagi/endpoints/audio.py +0 -17
- lionagi/endpoints/chatcompletion.py +0 -54
- lionagi/messages/__init__.py +0 -11
- lionagi/messages/instruction.py +0 -15
- lionagi/messages/message.py +0 -110
- lionagi/messages/response.py +0 -33
- lionagi/messages/system.py +0 -12
- lionagi/objs/__init__.py +0 -11
- lionagi/objs/abc_objs.py +0 -39
- lionagi/objs/async_queue.py +0 -135
- lionagi/objs/messenger.py +0 -85
- lionagi/objs/tool_manager.py +0 -253
- lionagi/services/__init__.py +0 -11
- lionagi/services/base_api_service.py +0 -230
- lionagi/services/oai.py +0 -34
- lionagi/services/openrouter.py +0 -31
- lionagi/tests/test_api_util.py +0 -46
- lionagi/tests/test_call_util.py +0 -115
- lionagi/tests/test_convert_util.py +0 -202
- lionagi/tests/test_encrypt_util.py +0 -33
- lionagi/tests/test_flat_util.py +0 -426
- lionagi/tests/test_sys_util.py +0 -0
- lionagi/utils/convert_util.py +0 -229
- lionagi/utils/flat_util.py +0 -599
- lionagi-0.0.115.dist-info/RECORD +0 -110
- /lionagi/{services → _services}/anyscale.py +0 -0
- /lionagi/{services → _services}/azure.py +0 -0
- /lionagi/{services → _services}/bedrock.py +0 -0
- /lionagi/{services → _services}/everlyai.py +0 -0
- /lionagi/{services → _services}/gemini.py +0 -0
- /lionagi/{services → _services}/gpt4all.py +0 -0
- /lionagi/{services → _services}/huggingface.py +0 -0
- /lionagi/{services → _services}/litellm.py +0 -0
- /lionagi/{services → _services}/localai.py +0 -0
- /lionagi/{services → _services}/mistralai.py +0 -0
- /lionagi/{services → _services}/ollama.py +0 -0
- /lionagi/{services → _services}/openllm.py +0 -0
- /lionagi/{services → _services}/perplexity.py +0 -0
- /lionagi/{services → _services}/predibase.py +0 -0
- /lionagi/{services → _services}/rungpt.py +0 -0
- /lionagi/{services → _services}/vllm.py +0 -0
- /lionagi/{services → _services}/xinference.py +0 -0
- /lionagi/{endpoints/assistants.py → agents/__init__.py} +0 -0
- /lionagi/{tools → agents}/planner.py +0 -0
- /lionagi/{tools → agents}/prompter.py +0 -0
- /lionagi/{tools → agents}/scorer.py +0 -0
- /lionagi/{tools → agents}/summarizer.py +0 -0
- /lionagi/{tools → agents}/validator.py +0 -0
- /lionagi/{endpoints/embeddings.py → core/branch/__init__.py} +0 -0
- /lionagi/{services/anthropic.py → core/branch/cluster.py} +0 -0
- /lionagi/{endpoints/finetune.py → core/flow/__init__.py} +0 -0
- /lionagi/{endpoints/image.py → core/messages/__init__.py} +0 -0
- /lionagi/{endpoints/moderation.py → models/__init__.py} +0 -0
- /lionagi/{endpoints/vision.py → models/base_model.py} +0 -0
- /lionagi/{objs → schema}/status_tracker.py +0 -0
- /lionagi/tests/{test_io_util.py → test_utils/__init__.py} +0 -0
- {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/LICENSE +0 -0
- {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/WHEEL +0 -0
- {lionagi-0.0.115.dist-info → lionagi-0.0.204.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,186 @@
|
|
1
|
+
import json
|
2
|
+
import asyncio
|
3
|
+
from typing import Dict, Union, List, Tuple, Any
|
4
|
+
from lionagi.utils import lcall
|
5
|
+
from lionagi.schema import BaseNode, Tool
|
6
|
+
|
7
|
+
|
8
|
+
class ToolManager(BaseNode):
|
9
|
+
"""
|
10
|
+
A manager class to handle registration and invocation of tools that are subclasses of Tool.
|
11
|
+
|
12
|
+
Attributes:
|
13
|
+
registry (Dict[str, Tool]): A dictionary to hold registered tools, using their names as keys.
|
14
|
+
"""
|
15
|
+
registry: Dict = {}
|
16
|
+
|
17
|
+
def name_existed(self, name: str) -> bool:
|
18
|
+
"""
|
19
|
+
Check if a tool name already exists in the registry.
|
20
|
+
|
21
|
+
Parameters:
|
22
|
+
name (str): The name of the tool to check.
|
23
|
+
|
24
|
+
Returns:
|
25
|
+
bool: True if the name exists, False otherwise.
|
26
|
+
|
27
|
+
Examples:
|
28
|
+
>>> tool_manager.name_existed('existing_tool')
|
29
|
+
True
|
30
|
+
>>> tool_manager.name_existed('nonexistent_tool')
|
31
|
+
False
|
32
|
+
"""
|
33
|
+
return True if name in self.registry.keys() else False
|
34
|
+
|
35
|
+
def _register_tool(self, tool: Tool) -> None:
|
36
|
+
"""
|
37
|
+
Register a new tool in the registry if it's an instance of Tool.
|
38
|
+
|
39
|
+
Parameters:
|
40
|
+
tool (Tool): The tool instance to register.
|
41
|
+
|
42
|
+
Raises:
|
43
|
+
TypeError: If the provided tool is not an instance of Tool.
|
44
|
+
|
45
|
+
Examples:
|
46
|
+
>>> tool_manager._register_tool(Tool())
|
47
|
+
# Tool is registered without any output
|
48
|
+
"""
|
49
|
+
if not isinstance(tool, Tool):
|
50
|
+
raise TypeError('Please register a Tool object.')
|
51
|
+
name = tool.schema_['function']['name']
|
52
|
+
self.registry.update({name: tool})
|
53
|
+
|
54
|
+
async def invoke(self, func_call: Tuple[str, Dict[str, Any]]) -> Any:
|
55
|
+
"""
|
56
|
+
Invoke a registered tool's function with the provided arguments.
|
57
|
+
|
58
|
+
Args:
|
59
|
+
func_call (Tuple[str, Dict[str, Any]]): A tuple containing the tool's function name and kwargs.
|
60
|
+
|
61
|
+
Returns:
|
62
|
+
Any: The result of the tool's function invocation.
|
63
|
+
|
64
|
+
Raises:
|
65
|
+
ValueError: If the function is not registered or an error occurs during invocation.
|
66
|
+
|
67
|
+
Examples:
|
68
|
+
>>> await tool_manager.invoke(('registered_function', {'arg1': 'value1'}))
|
69
|
+
# Result of the registered_function with given arguments
|
70
|
+
"""
|
71
|
+
name, kwargs = func_call
|
72
|
+
if self.name_existed(name):
|
73
|
+
tool = self.registry[name]
|
74
|
+
func = tool.func
|
75
|
+
parser = tool.parser
|
76
|
+
try:
|
77
|
+
if asyncio.iscoroutinefunction(func):
|
78
|
+
return await parser(func(**kwargs)) if parser else func(**kwargs)
|
79
|
+
else:
|
80
|
+
return parser(func(**kwargs)) if parser else func(**kwargs)
|
81
|
+
except Exception as e:
|
82
|
+
raise ValueError(f"Error when invoking function {name} with arguments {kwargs} with error message {e}")
|
83
|
+
else:
|
84
|
+
raise ValueError(f"Function {name} is not registered.")
|
85
|
+
|
86
|
+
@staticmethod
|
87
|
+
def get_function_call(response: Dict) -> Tuple[str, Dict]:
|
88
|
+
"""
|
89
|
+
Extract function name and arguments from a response JSON.
|
90
|
+
|
91
|
+
Parameters:
|
92
|
+
response (Dict): The JSON response containing function information.
|
93
|
+
|
94
|
+
Returns:
|
95
|
+
Tuple[str, Dict]: The function name and its arguments.
|
96
|
+
|
97
|
+
Raises:
|
98
|
+
ValueError: If the response is not a valid function call.
|
99
|
+
|
100
|
+
Examples:
|
101
|
+
>>> ToolManager.get_function_call({"action": "execute_add", "arguments": '{"x":1, "y":2}'})
|
102
|
+
('add', {'x': 1, 'y': 2})
|
103
|
+
"""
|
104
|
+
try:
|
105
|
+
func = response['action'][7:]
|
106
|
+
args = json.loads(response['arguments'])
|
107
|
+
return (func, args)
|
108
|
+
except:
|
109
|
+
try:
|
110
|
+
func = response['recipient_name'].split('.')[-1]
|
111
|
+
args = response['parameters']
|
112
|
+
return (func, args)
|
113
|
+
except:
|
114
|
+
raise ValueError('response is not a valid function call')
|
115
|
+
|
116
|
+
def register_tools(self, tools: List[Tool]) -> None:
|
117
|
+
"""
|
118
|
+
Register multiple tools using a given list.
|
119
|
+
|
120
|
+
Parameters:
|
121
|
+
tools (List[Tool]): A list of Tool instances to register.
|
122
|
+
|
123
|
+
Examples:
|
124
|
+
>>> tool_manager.register_tools([Tool(), Tool()])
|
125
|
+
# Multiple Tool instances registered
|
126
|
+
"""
|
127
|
+
lcall(tools, self._register_tool) #, update=update, new=new, prefix=prefix, postfix=postfix)
|
128
|
+
|
129
|
+
def to_tool_schema_list(self) -> List[Dict[str, Any]]:
|
130
|
+
"""
|
131
|
+
Convert the registry of tools to a list of their schemas.
|
132
|
+
|
133
|
+
Returns:
|
134
|
+
List[Dict[str, Any]]: A list of tool schemas.
|
135
|
+
|
136
|
+
Examples:
|
137
|
+
>>> tool_manager.to_tool_schema_list()
|
138
|
+
# Returns a list of registered tool schemas
|
139
|
+
"""
|
140
|
+
schema_list = []
|
141
|
+
for tool in self.registry.values():
|
142
|
+
schema_list.append(tool.schema_)
|
143
|
+
return schema_list
|
144
|
+
|
145
|
+
def _tool_parser(self, tools: Union[Dict, Tool, List[Tool], str, List[str], List[Dict]], **kwargs) -> Dict:
|
146
|
+
"""
|
147
|
+
Parse tools and additional keyword arguments to form a dictionary used for tool configuration.
|
148
|
+
|
149
|
+
Parameters:
|
150
|
+
tools: A single tool object, a list of tool objects, a tool name, a list of tool names, or a dictionary.
|
151
|
+
**kwargs: Additional keyword arguments.
|
152
|
+
|
153
|
+
Returns:
|
154
|
+
Dict: A dictionary of tools and additional keyword arguments.
|
155
|
+
|
156
|
+
Raises:
|
157
|
+
ValueError: If a tool name string does not correspond to a registered tool.
|
158
|
+
|
159
|
+
Examples:
|
160
|
+
>>> tool_manager._tool_parser('registered_tool')
|
161
|
+
# Returns a dictionary containing the schema of the registered tool
|
162
|
+
"""
|
163
|
+
def tool_check(tool):
|
164
|
+
if isinstance(tool, dict):
|
165
|
+
return tool
|
166
|
+
elif isinstance(tool, Tool):
|
167
|
+
return tool.schema_
|
168
|
+
elif isinstance(tool, str):
|
169
|
+
if self.name_existed(tool):
|
170
|
+
tool = self.registry[tool]
|
171
|
+
return tool.schema_
|
172
|
+
else:
|
173
|
+
raise ValueError(f'Function {tool} is not registered.')
|
174
|
+
|
175
|
+
if isinstance(tools, bool):
|
176
|
+
tool_kwarg = {"tools": self.to_tool_schema_list()}
|
177
|
+
kwargs = {**tool_kwarg, **kwargs}
|
178
|
+
|
179
|
+
else:
|
180
|
+
if not isinstance(tools, list):
|
181
|
+
tools = [tools]
|
182
|
+
tool_kwarg = {"tools": lcall(tools, tool_check)}
|
183
|
+
kwargs = {**tool_kwarg, **kwargs}
|
184
|
+
|
185
|
+
return kwargs
|
186
|
+
|
lionagi/tools/tool_util.py
CHANGED
@@ -1,7 +1,270 @@
|
|
1
|
-
|
2
|
-
from ..utils.convert_util import func_to_schema
|
1
|
+
import inspect
|
3
2
|
from ..schema.base_tool import Tool
|
4
3
|
|
4
|
+
def _extract_docstring_details_google(func):
|
5
|
+
"""
|
6
|
+
Extracts the function description and parameter descriptions from the
|
7
|
+
docstring following the Google style format.
|
8
|
+
|
9
|
+
Args:
|
10
|
+
func (Callable): The function from which to extract docstring details.
|
11
|
+
|
12
|
+
Returns:
|
13
|
+
Tuple[str, Dict[str, str]]: A tuple containing the function description
|
14
|
+
and a dictionary with parameter names as keys and their descriptions as values.
|
15
|
+
|
16
|
+
Examples:
|
17
|
+
>>> def example_function(param1: int, param2: str):
|
18
|
+
... '''Example function.
|
19
|
+
...
|
20
|
+
... Args:
|
21
|
+
... param1 (int): The first parameter.
|
22
|
+
... param2 (str): The second parameter.
|
23
|
+
... '''
|
24
|
+
... pass
|
25
|
+
>>> description, params = _extract_docstring_details_google(example_function)
|
26
|
+
>>> description
|
27
|
+
'Example function.'
|
28
|
+
>>> params == {'param1': 'The first parameter.', 'param2': 'The second parameter.'}
|
29
|
+
True
|
30
|
+
"""
|
31
|
+
docstring = inspect.getdoc(func)
|
32
|
+
if not docstring:
|
33
|
+
return "No description available.", {}
|
34
|
+
lines = docstring.split('\n')
|
35
|
+
func_description = lines[0].strip()
|
36
|
+
|
37
|
+
param_start_pos = 0
|
38
|
+
lines_len = len(lines)
|
39
|
+
|
40
|
+
params_description = {}
|
41
|
+
for i in range(1, lines_len):
|
42
|
+
if lines[i].startswith('Args') or lines[i].startswith('Arguments') or lines[i].startswith('Parameters'):
|
43
|
+
param_start_pos = i + 1
|
44
|
+
break
|
45
|
+
|
46
|
+
current_param = None
|
47
|
+
for i in range(param_start_pos, lines_len):
|
48
|
+
if lines[i] == '':
|
49
|
+
continue
|
50
|
+
elif lines[i].startswith(' '):
|
51
|
+
param_desc = lines[i].split(':', 1)
|
52
|
+
if len(param_desc) == 1:
|
53
|
+
params_description[current_param] += ' ' + param_desc[0].strip()
|
54
|
+
continue
|
55
|
+
param, desc = param_desc
|
56
|
+
param = param.split('(')[0].strip()
|
57
|
+
params_description[param] = desc.strip()
|
58
|
+
current_param = param
|
59
|
+
else:
|
60
|
+
break
|
61
|
+
return func_description, params_description
|
62
|
+
|
63
|
+
def _extract_docstring_details_rest(func):
|
64
|
+
"""
|
65
|
+
Extracts the function description and parameter descriptions from the
|
66
|
+
docstring following the reStructuredText (reST) style format.
|
67
|
+
|
68
|
+
Args:
|
69
|
+
func (Callable): The function from which to extract docstring details.
|
70
|
+
|
71
|
+
Returns:
|
72
|
+
Tuple[str, Dict[str, str]]: A tuple containing the function description
|
73
|
+
and a dictionary with parameter names as keys and their descriptions as values.
|
74
|
+
|
75
|
+
Examples:
|
76
|
+
>>> def example_function(param1: int, param2: str):
|
77
|
+
... '''Example function.
|
78
|
+
...
|
79
|
+
... :param param1: The first parameter.
|
80
|
+
... :type param1: int
|
81
|
+
... :param param2: The second parameter.
|
82
|
+
... :type param2: str
|
83
|
+
... '''
|
84
|
+
... pass
|
85
|
+
>>> description, params = _extract_docstring_details_rest(example_function)
|
86
|
+
>>> description
|
87
|
+
'Example function.'
|
88
|
+
>>> params == {'param1': 'The first parameter.', 'param2': 'The second parameter.'}
|
89
|
+
True
|
90
|
+
"""
|
91
|
+
docstring = inspect.getdoc(func)
|
92
|
+
if not docstring:
|
93
|
+
return "No description available.", {}
|
94
|
+
lines = docstring.split('\n')
|
95
|
+
func_description = lines[0].strip()
|
96
|
+
|
97
|
+
params_description = {}
|
98
|
+
current_param = None
|
99
|
+
for line in lines[1:]:
|
100
|
+
line = line.strip()
|
101
|
+
if line.startswith(':param'):
|
102
|
+
param_desc = line.split(':', 2)
|
103
|
+
_, param, desc = param_desc
|
104
|
+
param = param.split()[-1].strip()
|
105
|
+
params_description[param] = desc.strip()
|
106
|
+
current_param = param
|
107
|
+
elif line.startswith(' '):
|
108
|
+
params_description[current_param] += ' ' + line
|
109
|
+
|
110
|
+
return func_description, params_description
|
111
|
+
|
112
|
+
def _extract_docstring_details(func, style='google'):
|
113
|
+
"""
|
114
|
+
Extracts the function description and parameter descriptions from the
|
115
|
+
docstring of the given function using either Google style or reStructuredText
|
116
|
+
(reST) style format.
|
117
|
+
|
118
|
+
Args:
|
119
|
+
func (Callable): The function from which to extract docstring details.
|
120
|
+
style (str): The style of docstring to parse ('google' or 'reST').
|
121
|
+
|
122
|
+
Returns:
|
123
|
+
Tuple[str, Dict[str, str]]: A tuple containing the function description
|
124
|
+
and a dictionary with parameter names as keys and their descriptions as values.
|
125
|
+
|
126
|
+
Raises:
|
127
|
+
ValueError: If an unsupported style is provided.
|
128
|
+
|
129
|
+
Examples:
|
130
|
+
>>> def example_function(param1: int, param2: str):
|
131
|
+
... '''Example function.
|
132
|
+
...
|
133
|
+
... Args:
|
134
|
+
... param1 (int): The first parameter.
|
135
|
+
... param2 (str): The second parameter.
|
136
|
+
... '''
|
137
|
+
... pass
|
138
|
+
>>> description, params = _extract_docstring_details(example_function, style='google')
|
139
|
+
>>> description
|
140
|
+
'Example function.'
|
141
|
+
>>> params == {'param1': 'The first parameter.', 'param2': 'The second parameter.'}
|
142
|
+
True
|
143
|
+
"""
|
144
|
+
if style == 'google':
|
145
|
+
func_description, params_description = _extract_docstring_details_google(func)
|
146
|
+
elif style == 'reST':
|
147
|
+
func_description, params_description = _extract_docstring_details_rest(func)
|
148
|
+
else:
|
149
|
+
raise ValueError(f'{style} is not supported. Please choose either "google" or "reST".')
|
150
|
+
return func_description, params_description
|
151
|
+
|
152
|
+
def _python_to_json_type(py_type):
|
153
|
+
"""
|
154
|
+
Converts a Python type to its JSON type equivalent.
|
155
|
+
|
156
|
+
Args:
|
157
|
+
py_type (str): The name of the Python type.
|
158
|
+
|
159
|
+
Returns:
|
160
|
+
str: The corresponding JSON type.
|
161
|
+
|
162
|
+
Examples:
|
163
|
+
>>> _python_to_json_type('str')
|
164
|
+
'string'
|
165
|
+
>>> _python_to_json_type('int')
|
166
|
+
'number'
|
167
|
+
"""
|
168
|
+
type_mapping = {
|
169
|
+
'str': 'string',
|
170
|
+
'int': 'number',
|
171
|
+
'float': 'number',
|
172
|
+
'list': 'array',
|
173
|
+
'tuple': 'array',
|
174
|
+
'bool': 'boolean',
|
175
|
+
'dict': 'object'
|
176
|
+
}
|
177
|
+
return type_mapping.get(py_type, 'object')
|
178
|
+
|
179
|
+
def _func_to_schema(func, style='google'):
|
180
|
+
"""
|
181
|
+
Generates a schema description for a given function, using typing hints and
|
182
|
+
docstrings. The schema includes the function's name, description, and parameters.
|
183
|
+
|
184
|
+
Args:
|
185
|
+
func (Callable): The function to generate a schema for.
|
186
|
+
style (str): The docstring format ('google' or 'reST').
|
187
|
+
|
188
|
+
Returns:
|
189
|
+
Dict[str, Any]: A schema describing the function.
|
190
|
+
|
191
|
+
Examples:
|
192
|
+
>>> def example_function(param1: int, param2: str) -> bool:
|
193
|
+
... '''Example function.
|
194
|
+
...
|
195
|
+
... Args:
|
196
|
+
... param1 (int): The first parameter.
|
197
|
+
... param2 (str): The second parameter.
|
198
|
+
... '''
|
199
|
+
... return True
|
200
|
+
>>> schema = _func_to_schema(example_function)
|
201
|
+
>>> schema['function']['name']
|
202
|
+
'example_function'
|
203
|
+
"""
|
204
|
+
# Extracting function name and docstring details
|
205
|
+
func_name = func.__name__
|
206
|
+
func_description, params_description = _extract_docstring_details(func, style)
|
207
|
+
|
208
|
+
# Extracting parameters with typing hints
|
209
|
+
sig = inspect.signature(func)
|
210
|
+
parameters = {
|
211
|
+
"type": "object",
|
212
|
+
"properties": {},
|
213
|
+
"required": [],
|
214
|
+
}
|
215
|
+
|
216
|
+
for name, param in sig.parameters.items():
|
217
|
+
# Default type to string and update if type hint is available
|
218
|
+
param_type = "string"
|
219
|
+
if param.annotation is not inspect.Parameter.empty:
|
220
|
+
param_type = _python_to_json_type(param.annotation.__name__)
|
221
|
+
|
222
|
+
# Extract parameter description from docstring, if available
|
223
|
+
param_description = params_description.get(name, "No description available.")
|
224
|
+
|
225
|
+
# Assuming all parameters are required for simplicity
|
226
|
+
parameters["required"].append(name)
|
227
|
+
parameters["properties"][name] = {
|
228
|
+
"type": param_type,
|
229
|
+
"description": param_description,
|
230
|
+
}
|
231
|
+
|
232
|
+
# Constructing the schema
|
233
|
+
schema = {
|
234
|
+
"type": "function",
|
235
|
+
"function": {
|
236
|
+
"name": func_name,
|
237
|
+
"description": func_description,
|
238
|
+
"parameters": parameters,
|
239
|
+
}
|
240
|
+
}
|
241
|
+
return schema
|
242
|
+
|
5
243
|
def func_to_tool(func_, parser=None, docstring_style='google'):
|
6
|
-
|
244
|
+
"""
|
245
|
+
Wraps a function into a Tool object, using the provided docstring style to parse
|
246
|
+
the function's docstring and generate a schema.
|
247
|
+
|
248
|
+
Args:
|
249
|
+
func_ (Callable): The function to wrap into a Tool object.
|
250
|
+
parser (Any): The parser associated with the Tool (not used).
|
251
|
+
docstring_style (str): The docstring format ('google' or 'reST').
|
252
|
+
|
253
|
+
Returns:
|
254
|
+
Tool: A Tool object containing the wrapped function and its schema.
|
255
|
+
|
256
|
+
Examples:
|
257
|
+
>>> def example_function(param1: int, param2: str) -> bool:
|
258
|
+
... '''Example function.
|
259
|
+
...
|
260
|
+
... Args:
|
261
|
+
... param1 (int): The first parameter.
|
262
|
+
... param2 (str): The second parameter.
|
263
|
+
... '''
|
264
|
+
... return True
|
265
|
+
>>> tool = func_to_tool(example_function)
|
266
|
+
>>> isinstance(tool, Tool)
|
267
|
+
True
|
268
|
+
"""
|
269
|
+
schema = _func_to_schema(func_, docstring_style)
|
7
270
|
return Tool(func=func_, parser=parser, schema_=schema)
|
lionagi/utils/__init__.py
CHANGED
@@ -1,69 +1,29 @@
|
|
1
1
|
from .sys_util import (
|
2
|
-
|
3
|
-
|
4
|
-
|
5
|
-
)
|
2
|
+
get_timestamp, create_copy, create_path, split_path,
|
3
|
+
get_bins, change_dict_key, str_to_num, create_id,
|
4
|
+
as_dict)
|
6
5
|
|
7
|
-
from .
|
8
|
-
|
9
|
-
|
10
|
-
|
11
|
-
to_list
|
12
|
-
)
|
6
|
+
from .nested_util import (
|
7
|
+
to_readable_dict, nfilter, nset, nget,
|
8
|
+
nmerge, ninsert, flatten, unflatten,
|
9
|
+
is_structure_homogeneous, get_flattened_keys)
|
13
10
|
|
14
|
-
from .api_util import
|
15
|
-
|
16
|
-
|
17
|
-
)
|
18
|
-
from .encrypt_util import generate_encryption_key, encrypt, decrypt
|
19
|
-
from .convert_util import str_to_num, dict_to_xml, xml_to_dict
|
11
|
+
from .api_util import APIUtil
|
12
|
+
from .encrypt_util import EncrytionUtil
|
13
|
+
from .io_util import IOUtil
|
20
14
|
|
21
|
-
from .io_util import to_temp, to_csv, append_to_jsonl
|
22
15
|
from .call_util import (
|
23
|
-
|
24
|
-
mcall,
|
25
|
-
)
|
16
|
+
to_list,
|
17
|
+
lcall, alcall, mcall, tcall, bcall,
|
18
|
+
rcall, CallDecorator)
|
26
19
|
|
27
20
|
|
28
21
|
__all__ = [
|
29
|
-
'
|
30
|
-
'
|
31
|
-
'
|
32
|
-
'
|
33
|
-
'
|
34
|
-
'
|
35
|
-
'
|
36
|
-
|
37
|
-
'is_flattenable',
|
38
|
-
'dynamic_flatten',
|
39
|
-
'unflatten_to_list',
|
40
|
-
'flatten_iterable',
|
41
|
-
'flatten_iterable_to_list',
|
42
|
-
'create_copy',
|
43
|
-
'create_id',
|
44
|
-
'create_path',
|
45
|
-
'create_hash',
|
46
|
-
'change_dict_key',
|
47
|
-
'get_timestamp',
|
48
|
-
'get_bins',
|
49
|
-
'timestamp_to_datetime',
|
50
|
-
'is_schema',
|
51
|
-
'split_path',
|
52
|
-
'generate_encryption_key',
|
53
|
-
'encrypt', 'decrypt',
|
54
|
-
'str_to_num',
|
55
|
-
'to_list',
|
56
|
-
'dict_to_xml',
|
57
|
-
'xml_to_dict',
|
58
|
-
'to_temp',
|
59
|
-
'to_csv',
|
60
|
-
'append_to_jsonl',
|
61
|
-
'hcall',
|
62
|
-
'ahcall',
|
63
|
-
'lcall',
|
64
|
-
'alcall',
|
65
|
-
'mcall',
|
66
|
-
'amcall',
|
67
|
-
'ecall',
|
68
|
-
'aecall'
|
69
|
-
]
|
22
|
+
'get_timestamp', 'create_copy', 'create_path', 'split_path',
|
23
|
+
'get_bins', 'change_dict_key', 'str_to_num', 'create_id',
|
24
|
+
'as_dict', 'to_list', 'to_readable_dict', 'nfilter', 'nset',
|
25
|
+
'nget', 'nmerge', 'ninsert', 'flatten', 'unflatten',
|
26
|
+
'is_structure_homogeneous', 'get_flattened_keys', 'APIUtil',
|
27
|
+
'EncrytionUtil', 'IOUtil', 'lcall', 'alcall', 'mcall', 'tcall',
|
28
|
+
'bcall', 'rcall', 'CallDecorator'
|
29
|
+
]
|