lionagi 0.1.1__py3-none-any.whl → 0.2.0__py3-none-any.whl
Sign up to get free protection for your applications and to get access to all the features.
- lionagi/__init__.py +60 -5
- lionagi/core/__init__.py +0 -25
- lionagi/core/_setting/_setting.py +59 -0
- lionagi/core/action/__init__.py +14 -0
- lionagi/core/action/function_calling.py +136 -0
- lionagi/core/action/manual.py +1 -0
- lionagi/core/action/node.py +109 -0
- lionagi/core/action/tool.py +114 -0
- lionagi/core/action/tool_manager.py +356 -0
- lionagi/core/agent/base_agent.py +27 -13
- lionagi/core/agent/eval/evaluator.py +1 -0
- lionagi/core/agent/eval/vote.py +40 -0
- lionagi/core/agent/learn/learner.py +59 -0
- lionagi/core/agent/plan/unit_template.py +1 -0
- lionagi/core/collections/__init__.py +17 -0
- lionagi/core/{generic/data_logger.py → collections/_logger.py} +69 -55
- lionagi/core/collections/abc/__init__.py +53 -0
- lionagi/core/collections/abc/component.py +615 -0
- lionagi/core/collections/abc/concepts.py +297 -0
- lionagi/core/collections/abc/exceptions.py +150 -0
- lionagi/core/collections/abc/util.py +45 -0
- lionagi/core/collections/exchange.py +161 -0
- lionagi/core/collections/flow.py +426 -0
- lionagi/core/collections/model.py +419 -0
- lionagi/core/collections/pile.py +913 -0
- lionagi/core/collections/progression.py +236 -0
- lionagi/core/collections/util.py +64 -0
- lionagi/core/director/direct.py +314 -0
- lionagi/core/director/director.py +2 -0
- lionagi/core/{execute/branch_executor.py → engine/branch_engine.py} +134 -97
- lionagi/core/{execute/instruction_map_executor.py → engine/instruction_map_engine.py} +80 -55
- lionagi/{experimental/directive/evaluator → core/engine}/script_engine.py +17 -1
- lionagi/core/executor/base_executor.py +90 -0
- lionagi/core/{execute/structure_executor.py → executor/graph_executor.py} +83 -67
- lionagi/core/{execute → executor}/neo4j_executor.py +70 -67
- lionagi/core/generic/__init__.py +3 -33
- lionagi/core/generic/edge.py +42 -92
- lionagi/core/generic/edge_condition.py +16 -0
- lionagi/core/generic/graph.py +236 -0
- lionagi/core/generic/hyperedge.py +1 -0
- lionagi/core/generic/node.py +156 -221
- lionagi/core/generic/tree.py +48 -0
- lionagi/core/generic/tree_node.py +79 -0
- lionagi/core/mail/__init__.py +12 -0
- lionagi/core/mail/mail.py +25 -0
- lionagi/core/mail/mail_manager.py +139 -58
- lionagi/core/mail/package.py +45 -0
- lionagi/core/mail/start_mail.py +36 -0
- lionagi/core/message/__init__.py +19 -0
- lionagi/core/message/action_request.py +133 -0
- lionagi/core/message/action_response.py +135 -0
- lionagi/core/message/assistant_response.py +95 -0
- lionagi/core/message/instruction.py +234 -0
- lionagi/core/message/message.py +101 -0
- lionagi/core/message/system.py +86 -0
- lionagi/core/message/util.py +283 -0
- lionagi/core/report/__init__.py +4 -0
- lionagi/core/report/base.py +217 -0
- lionagi/core/report/form.py +231 -0
- lionagi/core/report/report.py +166 -0
- lionagi/core/report/util.py +28 -0
- lionagi/core/rule/_default.py +16 -0
- lionagi/core/rule/action.py +99 -0
- lionagi/core/rule/base.py +238 -0
- lionagi/core/rule/boolean.py +56 -0
- lionagi/core/rule/choice.py +47 -0
- lionagi/core/rule/mapping.py +96 -0
- lionagi/core/rule/number.py +71 -0
- lionagi/core/rule/rulebook.py +109 -0
- lionagi/core/rule/string.py +52 -0
- lionagi/core/rule/util.py +35 -0
- lionagi/core/session/branch.py +431 -0
- lionagi/core/session/directive_mixin.py +287 -0
- lionagi/core/session/session.py +229 -903
- lionagi/core/structure/__init__.py +1 -0
- lionagi/core/structure/chain.py +1 -0
- lionagi/core/structure/forest.py +1 -0
- lionagi/core/structure/graph.py +1 -0
- lionagi/core/structure/tree.py +1 -0
- lionagi/core/unit/__init__.py +5 -0
- lionagi/core/unit/parallel_unit.py +245 -0
- lionagi/core/unit/template/action.py +81 -0
- lionagi/core/unit/template/base.py +51 -0
- lionagi/core/unit/template/plan.py +84 -0
- lionagi/core/unit/template/predict.py +109 -0
- lionagi/core/unit/template/score.py +124 -0
- lionagi/core/unit/template/select.py +104 -0
- lionagi/core/unit/unit.py +362 -0
- lionagi/core/unit/unit_form.py +305 -0
- lionagi/core/unit/unit_mixin.py +1168 -0
- lionagi/core/unit/util.py +71 -0
- lionagi/core/validator/validator.py +364 -0
- lionagi/core/work/work.py +74 -0
- lionagi/core/work/work_function.py +92 -0
- lionagi/core/work/work_queue.py +81 -0
- lionagi/core/work/worker.py +195 -0
- lionagi/core/work/worklog.py +124 -0
- lionagi/experimental/compressor/base.py +46 -0
- lionagi/experimental/compressor/llm_compressor.py +247 -0
- lionagi/experimental/compressor/llm_summarizer.py +61 -0
- lionagi/experimental/compressor/util.py +70 -0
- lionagi/experimental/directive/__init__.py +19 -0
- lionagi/experimental/directive/parser/base_parser.py +69 -2
- lionagi/experimental/directive/{template_ → template}/base_template.py +17 -1
- lionagi/{libs/ln_tokenizer.py → experimental/directive/tokenizer.py} +16 -0
- lionagi/experimental/{directive/evaluator → evaluator}/ast_evaluator.py +16 -0
- lionagi/experimental/{directive/evaluator → evaluator}/base_evaluator.py +16 -0
- lionagi/experimental/knowledge/__init__.py +0 -0
- lionagi/experimental/knowledge/base.py +10 -0
- lionagi/experimental/knowledge/graph.py +0 -0
- lionagi/experimental/memory/__init__.py +0 -0
- lionagi/experimental/strategies/__init__.py +0 -0
- lionagi/experimental/strategies/base.py +1 -0
- lionagi/integrations/bridge/langchain_/documents.py +4 -0
- lionagi/integrations/bridge/llamaindex_/index.py +30 -0
- lionagi/integrations/bridge/llamaindex_/llama_index_bridge.py +6 -0
- lionagi/integrations/chunker/chunk.py +161 -24
- lionagi/integrations/config/oai_configs.py +34 -3
- lionagi/integrations/config/openrouter_configs.py +14 -2
- lionagi/integrations/loader/load.py +122 -21
- lionagi/integrations/loader/load_util.py +6 -77
- lionagi/integrations/provider/_mapping.py +46 -0
- lionagi/integrations/provider/litellm.py +2 -1
- lionagi/integrations/provider/mlx_service.py +16 -9
- lionagi/integrations/provider/oai.py +91 -4
- lionagi/integrations/provider/ollama.py +6 -5
- lionagi/integrations/provider/openrouter.py +115 -8
- lionagi/integrations/provider/services.py +2 -2
- lionagi/integrations/provider/transformers.py +18 -22
- lionagi/integrations/storage/__init__.py +3 -3
- lionagi/integrations/storage/neo4j.py +52 -60
- lionagi/integrations/storage/storage_util.py +45 -47
- lionagi/integrations/storage/structure_excel.py +285 -0
- lionagi/integrations/storage/to_excel.py +23 -7
- lionagi/libs/__init__.py +26 -1
- lionagi/libs/ln_api.py +75 -20
- lionagi/libs/ln_context.py +37 -0
- lionagi/libs/ln_convert.py +21 -9
- lionagi/libs/ln_func_call.py +69 -28
- lionagi/libs/ln_image.py +107 -0
- lionagi/libs/ln_nested.py +26 -11
- lionagi/libs/ln_parse.py +82 -23
- lionagi/libs/ln_queue.py +16 -0
- lionagi/libs/ln_tokenize.py +164 -0
- lionagi/libs/ln_validate.py +16 -0
- lionagi/libs/special_tokens.py +172 -0
- lionagi/libs/sys_util.py +95 -24
- lionagi/lions/coder/code_form.py +13 -0
- lionagi/lions/coder/coder.py +50 -3
- lionagi/lions/coder/util.py +30 -25
- lionagi/tests/libs/test_func_call.py +23 -21
- lionagi/tests/libs/test_nested.py +36 -21
- lionagi/tests/libs/test_parse.py +1 -1
- lionagi/tests/test_core/collections/__init__.py +0 -0
- lionagi/tests/test_core/collections/test_component.py +206 -0
- lionagi/tests/test_core/collections/test_exchange.py +138 -0
- lionagi/tests/test_core/collections/test_flow.py +145 -0
- lionagi/tests/test_core/collections/test_pile.py +171 -0
- lionagi/tests/test_core/collections/test_progression.py +129 -0
- lionagi/tests/test_core/generic/__init__.py +0 -0
- lionagi/tests/test_core/generic/test_edge.py +67 -0
- lionagi/tests/test_core/generic/test_graph.py +96 -0
- lionagi/tests/test_core/generic/test_node.py +106 -0
- lionagi/tests/test_core/generic/test_tree_node.py +73 -0
- lionagi/tests/test_core/test_branch.py +115 -294
- lionagi/tests/test_core/test_form.py +46 -0
- lionagi/tests/test_core/test_report.py +105 -0
- lionagi/tests/test_core/test_validator.py +111 -0
- lionagi/version.py +1 -1
- lionagi-0.2.0.dist-info/LICENSE +202 -0
- lionagi-0.2.0.dist-info/METADATA +272 -0
- lionagi-0.2.0.dist-info/RECORD +240 -0
- lionagi/core/branch/base.py +0 -653
- lionagi/core/branch/branch.py +0 -474
- lionagi/core/branch/flow_mixin.py +0 -96
- lionagi/core/branch/util.py +0 -323
- lionagi/core/direct/__init__.py +0 -19
- lionagi/core/direct/cot.py +0 -123
- lionagi/core/direct/plan.py +0 -164
- lionagi/core/direct/predict.py +0 -166
- lionagi/core/direct/react.py +0 -171
- lionagi/core/direct/score.py +0 -279
- lionagi/core/direct/select.py +0 -170
- lionagi/core/direct/sentiment.py +0 -1
- lionagi/core/direct/utils.py +0 -110
- lionagi/core/direct/vote.py +0 -64
- lionagi/core/execute/base_executor.py +0 -47
- lionagi/core/flow/baseflow.py +0 -23
- lionagi/core/flow/monoflow/ReAct.py +0 -238
- lionagi/core/flow/monoflow/__init__.py +0 -9
- lionagi/core/flow/monoflow/chat.py +0 -95
- lionagi/core/flow/monoflow/chat_mixin.py +0 -253
- lionagi/core/flow/monoflow/followup.py +0 -213
- lionagi/core/flow/polyflow/__init__.py +0 -1
- lionagi/core/flow/polyflow/chat.py +0 -251
- lionagi/core/form/action_form.py +0 -26
- lionagi/core/form/field_validator.py +0 -287
- lionagi/core/form/form.py +0 -302
- lionagi/core/form/mixin.py +0 -214
- lionagi/core/form/scored_form.py +0 -13
- lionagi/core/generic/action.py +0 -26
- lionagi/core/generic/component.py +0 -455
- lionagi/core/generic/condition.py +0 -44
- lionagi/core/generic/mail.py +0 -90
- lionagi/core/generic/mailbox.py +0 -36
- lionagi/core/generic/relation.py +0 -70
- lionagi/core/generic/signal.py +0 -22
- lionagi/core/generic/structure.py +0 -362
- lionagi/core/generic/transfer.py +0 -20
- lionagi/core/generic/work.py +0 -40
- lionagi/core/graph/graph.py +0 -126
- lionagi/core/graph/tree.py +0 -190
- lionagi/core/mail/schema.py +0 -63
- lionagi/core/messages/schema.py +0 -325
- lionagi/core/tool/__init__.py +0 -5
- lionagi/core/tool/tool.py +0 -28
- lionagi/core/tool/tool_manager.py +0 -282
- lionagi/experimental/tool/function_calling.py +0 -43
- lionagi/experimental/tool/manual.py +0 -66
- lionagi/experimental/tool/schema.py +0 -59
- lionagi/experimental/tool/tool_manager.py +0 -138
- lionagi/experimental/tool/util.py +0 -16
- lionagi/experimental/work/_logger.py +0 -25
- lionagi/experimental/work/schema.py +0 -30
- lionagi/experimental/work/tests.py +0 -72
- lionagi/experimental/work/work_function.py +0 -89
- lionagi/experimental/work/worker.py +0 -12
- lionagi/integrations/bridge/llamaindex_/get_index.py +0 -294
- lionagi/tests/test_core/test_base_branch.py +0 -426
- lionagi/tests/test_core/test_chat_flow.py +0 -63
- lionagi/tests/test_core/test_mail_manager.py +0 -75
- lionagi/tests/test_core/test_prompts.py +0 -51
- lionagi/tests/test_core/test_session.py +0 -254
- lionagi/tests/test_core/test_session_base_util.py +0 -313
- lionagi/tests/test_core/test_tool_manager.py +0 -95
- lionagi-0.1.1.dist-info/LICENSE +0 -9
- lionagi-0.1.1.dist-info/METADATA +0 -174
- lionagi-0.1.1.dist-info/RECORD +0 -190
- /lionagi/core/{branch → _setting}/__init__.py +0 -0
- /lionagi/core/{execute → agent/eval}/__init__.py +0 -0
- /lionagi/core/{flow → agent/learn}/__init__.py +0 -0
- /lionagi/core/{form → agent/plan}/__init__.py +0 -0
- /lionagi/core/{branch/executable_branch.py → agent/plan/plan.py} +0 -0
- /lionagi/core/{graph → director}/__init__.py +0 -0
- /lionagi/core/{messages → engine}/__init__.py +0 -0
- /lionagi/{experimental/directive/evaluator → core/engine}/sandbox_.py +0 -0
- /lionagi/{experimental/directive/evaluator → core/executor}/__init__.py +0 -0
- /lionagi/{experimental/directive/template_ → core/rule}/__init__.py +0 -0
- /lionagi/{experimental/tool → core/unit/template}/__init__.py +0 -0
- /lionagi/{experimental/work → core/validator}/__init__.py +0 -0
- /lionagi/core/{flow/mono_chat_mixin.py → work/__init__.py} +0 -0
- /lionagi/experimental/{work/exchange.py → compressor/__init__.py} +0 -0
- /lionagi/experimental/{work/util.py → directive/template/__init__.py} +0 -0
- /lionagi/experimental/directive/{schema.py → template/schema.py} +0 -0
- /lionagi/{tests/libs/test_async.py → experimental/evaluator/__init__.py} +0 -0
- {lionagi-0.1.1.dist-info → lionagi-0.2.0.dist-info}/WHEEL +0 -0
- {lionagi-0.1.1.dist-info → lionagi-0.2.0.dist-info}/top_level.txt +0 -0
@@ -1,282 +0,0 @@
|
|
1
|
-
import asyncio
|
2
|
-
|
3
|
-
from typing import Tuple, Any, TypeVar, Callable
|
4
|
-
from lionagi.libs import func_call, convert, ParseUtil
|
5
|
-
|
6
|
-
from lionagi.core.tool.tool import Tool, TOOL_TYPE
|
7
|
-
|
8
|
-
T = TypeVar("T", bound=Tool)
|
9
|
-
|
10
|
-
|
11
|
-
class ToolManager:
|
12
|
-
"""
|
13
|
-
A manager class for handling the registration and invocation of tools that are subclasses of Tool.
|
14
|
-
|
15
|
-
This class maintains a registry of tool instances, allowing for dynamic invocation based on
|
16
|
-
tool name and provided arguments. It supports both synchronous and asynchronous tool function
|
17
|
-
calls.
|
18
|
-
|
19
|
-
Attributes:
|
20
|
-
registry (dict[str, Tool]): A dictionary to hold registered tools, keyed by their names.
|
21
|
-
"""
|
22
|
-
|
23
|
-
registry: dict = {}
|
24
|
-
|
25
|
-
def name_existed(self, name: str) -> bool:
|
26
|
-
"""
|
27
|
-
Checks if a tool name already exists in the registry.
|
28
|
-
|
29
|
-
Args:
|
30
|
-
name (str): The name of the tool to check.
|
31
|
-
|
32
|
-
Returns:
|
33
|
-
bool: True if the name exists, False otherwise.
|
34
|
-
"""
|
35
|
-
return name in self.registry
|
36
|
-
|
37
|
-
@property
|
38
|
-
def has_tools(self):
|
39
|
-
return self.registry != {}
|
40
|
-
|
41
|
-
def _register_tool(self, tool: Tool | Callable) -> None:
|
42
|
-
"""
|
43
|
-
Registers a tool in the registry. Raises a TypeError if the object is not an instance of Tool.
|
44
|
-
|
45
|
-
Args:
|
46
|
-
tool (Tool): The tool instance to register.
|
47
|
-
|
48
|
-
Raises:
|
49
|
-
TypeError: If the provided object is not an instance of Tool.
|
50
|
-
"""
|
51
|
-
if isinstance(tool, Callable):
|
52
|
-
tool = func_to_tool(tool)[0]
|
53
|
-
if not isinstance(tool, Tool):
|
54
|
-
raise TypeError("Please register a Tool object.")
|
55
|
-
name = tool.schema_["function"]["name"]
|
56
|
-
self.registry.update({name: tool})
|
57
|
-
|
58
|
-
async def invoke(self, func_calls: Tuple[str, dict[str, Any]]) -> Any:
|
59
|
-
"""
|
60
|
-
Invokes a registered tool's function with the given arguments. Supports both coroutine and regular functions.
|
61
|
-
|
62
|
-
Args:
|
63
|
-
func_call (Tuple[str, Dict[str, Any]]): A tuple containing the function name and a dictionary of keyword arguments.
|
64
|
-
|
65
|
-
Returns:
|
66
|
-
Any: The result of the function call.
|
67
|
-
|
68
|
-
Raises:
|
69
|
-
ValueError: If the function name is not registered or if there's an error during function invocation.
|
70
|
-
"""
|
71
|
-
name, kwargs = func_calls
|
72
|
-
if not self.name_existed(name):
|
73
|
-
raise ValueError(f"Function {name} is not registered.")
|
74
|
-
tool = self.registry[name]
|
75
|
-
func = tool.func
|
76
|
-
parser = tool.parser
|
77
|
-
try:
|
78
|
-
if func_call.is_coroutine_func(func):
|
79
|
-
tasks = [func_call.call_handler(func, **kwargs)]
|
80
|
-
out = await asyncio.gather(*tasks)
|
81
|
-
return parser(out[0]) if parser else out[0]
|
82
|
-
else:
|
83
|
-
out = func(**kwargs)
|
84
|
-
return parser(out) if parser else out
|
85
|
-
except Exception as e:
|
86
|
-
raise ValueError(
|
87
|
-
f"Error when invoking function {name} with arguments {kwargs} with error message {e}"
|
88
|
-
) from e
|
89
|
-
|
90
|
-
@staticmethod
|
91
|
-
def get_function_call(response: dict) -> Tuple[str, dict]:
|
92
|
-
"""
|
93
|
-
Extracts a function call and arguments from a response dictionary.
|
94
|
-
|
95
|
-
Args:
|
96
|
-
response (dict): The response dictionary containing the function call information.
|
97
|
-
|
98
|
-
Returns:
|
99
|
-
Tuple[str, dict]: A tuple containing the function name and a dictionary of arguments.
|
100
|
-
|
101
|
-
Raises:
|
102
|
-
ValueError: If the response does not contain valid function call information.
|
103
|
-
"""
|
104
|
-
try:
|
105
|
-
func = response["action"][7:]
|
106
|
-
args = convert.to_dict(response["arguments"])
|
107
|
-
return func, args
|
108
|
-
except Exception:
|
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
|
-
Registers multiple tools in the registry.
|
119
|
-
|
120
|
-
Args:
|
121
|
-
tools (list[Tool]): A list of tool instances to register.
|
122
|
-
"""
|
123
|
-
func_call.lcall(tools, self._register_tool)
|
124
|
-
|
125
|
-
def to_tool_schema_list(self) -> list[dict[str, Any]]:
|
126
|
-
"""
|
127
|
-
Generates a list of schemas for all registered tools.
|
128
|
-
|
129
|
-
Returns:
|
130
|
-
list[dict[str, Any]]: A list of tool schemas.
|
131
|
-
|
132
|
-
"""
|
133
|
-
return [tool.schema_ for tool in self.registry.values()]
|
134
|
-
|
135
|
-
def parse_tool(self, tools: TOOL_TYPE, **kwargs) -> dict:
|
136
|
-
"""
|
137
|
-
Parses tool information and generates a dictionary for tool invocation.
|
138
|
-
|
139
|
-
Args:
|
140
|
-
tools: Tool information which can be a single Tool instance, a list of Tool instances, a tool name, or a list of tool names.
|
141
|
-
**kwargs: Additional keyword arguments.
|
142
|
-
|
143
|
-
Returns:
|
144
|
-
dict: A dictionary containing tool schema information and any additional keyword arguments.
|
145
|
-
|
146
|
-
Raises:
|
147
|
-
ValueError: If a tool name is provided that is not registered.
|
148
|
-
"""
|
149
|
-
|
150
|
-
def tool_check(tool):
|
151
|
-
if isinstance(tool, dict):
|
152
|
-
return tool
|
153
|
-
elif isinstance(tool, Tool):
|
154
|
-
return tool.schema_
|
155
|
-
elif isinstance(tool, str):
|
156
|
-
if self.name_existed(tool):
|
157
|
-
tool: Tool = self.registry[tool]
|
158
|
-
return tool.schema_
|
159
|
-
else:
|
160
|
-
raise ValueError(f"Function {tool} is not registered.")
|
161
|
-
|
162
|
-
if isinstance(tools, bool):
|
163
|
-
tool_kwarg = {"tools": self.to_tool_schema_list()}
|
164
|
-
kwargs = tool_kwarg | kwargs
|
165
|
-
|
166
|
-
else:
|
167
|
-
if not isinstance(tools, list):
|
168
|
-
tools = [tools]
|
169
|
-
tool_kwarg = {"tools": func_call.lcall(tools, tool_check)}
|
170
|
-
kwargs = tool_kwarg | kwargs
|
171
|
-
|
172
|
-
return kwargs
|
173
|
-
|
174
|
-
|
175
|
-
def func_to_tool(
|
176
|
-
func_: Callable | list[Callable], parser=None, docstring_style="google"
|
177
|
-
):
|
178
|
-
"""
|
179
|
-
Transforms a given function into a Tool object, equipped with a schema derived
|
180
|
-
from its docstring. This process involves parsing the function's docstring based
|
181
|
-
on a specified style ('google' or 'reST') to extract relevant metadata and
|
182
|
-
parameters, which are then used to construct a comprehensive schema for the Tool.
|
183
|
-
This schema facilitates the integration of the function with systems or
|
184
|
-
frameworks that rely on structured metadata for automation, documentation, or
|
185
|
-
interface generation purposes.
|
186
|
-
|
187
|
-
The function to be transformed can be any Callable that adheres to the
|
188
|
-
specified docstring conventions. The resulting Tool object encapsulates the
|
189
|
-
original function, allowing it to be utilized within environments that require
|
190
|
-
objects with structured metadata.
|
191
|
-
|
192
|
-
Args:
|
193
|
-
func_ (Callable): The function to be transformed into a Tool object. This
|
194
|
-
function should have a docstring that follows the
|
195
|
-
specified docstring style for accurate schema generation.
|
196
|
-
parser (Optional[Any]): An optional parser object associated with the Tool.
|
197
|
-
This parameter is currently not utilized in the
|
198
|
-
transformation process but is included for future
|
199
|
-
compatibility and extension purposes.
|
200
|
-
docstring_style (str): The format of the docstring to be parsed, indicating
|
201
|
-
the convention used in the function's docstring.
|
202
|
-
Supports 'google' for Google-style docstrings and
|
203
|
-
'reST' for reStructuredText-style docstrings. The
|
204
|
-
chosen style affects how the docstring is parsed and
|
205
|
-
how the schema is generated.
|
206
|
-
|
207
|
-
Returns:
|
208
|
-
Tool: An object representing the original function wrapped as a Tool, along
|
209
|
-
with its generated schema. This Tool object can be used in systems that
|
210
|
-
require detailed metadata about functions, facilitating tasks such as
|
211
|
-
automatic documentation generation, user interface creation, or
|
212
|
-
integration with other software tools.
|
213
|
-
|
214
|
-
Examples:
|
215
|
-
>>> def example_function_google(param1: int, param2: str) -> bool:
|
216
|
-
... '''
|
217
|
-
... An example function using Google style docstrings.
|
218
|
-
...
|
219
|
-
... Args:
|
220
|
-
... param1 (int): The first parameter, demonstrating an integer input_.
|
221
|
-
... param2 (str): The second parameter, demonstrating a string input_.
|
222
|
-
...
|
223
|
-
... Returns:
|
224
|
-
... bool: A boolean value, illustrating the return type.
|
225
|
-
... '''
|
226
|
-
... return True
|
227
|
-
...
|
228
|
-
>>> tool_google = func_to_tool(example_function_google, docstring_style='google')
|
229
|
-
>>> print(isinstance(tool_google, Tool))
|
230
|
-
True
|
231
|
-
|
232
|
-
>>> def example_function_reST(param1: int, param2: str) -> bool:
|
233
|
-
... '''
|
234
|
-
... An example function using reStructuredText (reST) style docstrings.
|
235
|
-
...
|
236
|
-
... :param param1: The first parameter, demonstrating an integer input_.
|
237
|
-
... :type param1: int
|
238
|
-
... :param param2: The second parameter, demonstrating a string input_.
|
239
|
-
... :type param2: str
|
240
|
-
... :returns: A boolean value, illustrating the return type.
|
241
|
-
... :rtype: bool
|
242
|
-
... '''
|
243
|
-
... return True
|
244
|
-
...
|
245
|
-
>>> tool_reST = func_to_tool(example_function_reST, docstring_style='reST')
|
246
|
-
>>> print(isinstance(tool_reST, Tool))
|
247
|
-
True
|
248
|
-
|
249
|
-
Note:
|
250
|
-
The transformation process relies heavily on the accuracy and completeness of
|
251
|
-
the function's docstring. Functions with incomplete or incorrectly formatted
|
252
|
-
docstrings may result in incomplete or inaccurate Tool schemas.
|
253
|
-
"""
|
254
|
-
|
255
|
-
fs = []
|
256
|
-
funcs = convert.to_list(func_, flatten=True, dropna=True)
|
257
|
-
parsers = convert.to_list(parser, flatten=True, dropna=True)
|
258
|
-
|
259
|
-
if parser:
|
260
|
-
if len(funcs) != len(parsers) != 1:
|
261
|
-
raise ValueError(
|
262
|
-
"Length of parser must match length of func. Except if you only pass one"
|
263
|
-
)
|
264
|
-
|
265
|
-
for idx in range(len(funcs)):
|
266
|
-
f_ = lambda _f: Tool(
|
267
|
-
func=_f,
|
268
|
-
schema_=ParseUtil._func_to_schema(_f, style=docstring_style),
|
269
|
-
parser=parsers[idx] if len(parsers) > 1 else parsers[0],
|
270
|
-
)
|
271
|
-
|
272
|
-
fs.append(f_)
|
273
|
-
|
274
|
-
else:
|
275
|
-
fs = func_call.lcall(
|
276
|
-
funcs,
|
277
|
-
lambda _f: Tool(
|
278
|
-
func=_f, schema_=ParseUtil._func_to_schema(_f, style=docstring_style)
|
279
|
-
),
|
280
|
-
)
|
281
|
-
|
282
|
-
return fs
|
@@ -1,43 +0,0 @@
|
|
1
|
-
from typing import Any, Callable
|
2
|
-
from pydantic import BaseModel, Field, field_serializer
|
3
|
-
from functools import singledispatchmethod
|
4
|
-
from lionagi.libs import convert
|
5
|
-
|
6
|
-
|
7
|
-
class FunctionCalling(BaseModel):
|
8
|
-
func: Any = Field(..., alias="function")
|
9
|
-
kwargs: Any = Field({}, alias="arguments")
|
10
|
-
|
11
|
-
@field_serializer("func")
|
12
|
-
def serialize_func(self, func: Callable):
|
13
|
-
return func.__name__
|
14
|
-
|
15
|
-
@property
|
16
|
-
def func_name(self):
|
17
|
-
return self.func.__name__
|
18
|
-
|
19
|
-
@classmethod
|
20
|
-
@singledispatchmethod
|
21
|
-
def create(cls, func_call: Any):
|
22
|
-
raise TypeError(f"Unsupported type {type(func_call)}")
|
23
|
-
|
24
|
-
@create.register
|
25
|
-
def _(cls, func_call: tuple):
|
26
|
-
if len(func_call) == 2:
|
27
|
-
return cls(func=func_call[0], kwargs=func_call[1])
|
28
|
-
else:
|
29
|
-
raise ValueError(f"Invalid tuple length {len(func_call)}")
|
30
|
-
|
31
|
-
@create.register
|
32
|
-
def _(cls, func_call: dict):
|
33
|
-
return cls(**func_call)
|
34
|
-
|
35
|
-
@create.register
|
36
|
-
def _(cls, func_call: str):
|
37
|
-
try:
|
38
|
-
return cls(**convert.to_dict(func_call))
|
39
|
-
except Exception as e:
|
40
|
-
raise ValueError(f"Invalid string {func_call}") from e
|
41
|
-
|
42
|
-
def __str__(self):
|
43
|
-
return f"{self.func_name}({self.kwargs})"
|
@@ -1,66 +0,0 @@
|
|
1
|
-
import re
|
2
|
-
from typing import Dict, Union, Callable, Any
|
3
|
-
|
4
|
-
|
5
|
-
class BaseManual:
|
6
|
-
def __init__(self, template_str: str):
|
7
|
-
self.template_str = template_str
|
8
|
-
|
9
|
-
def _evaluate_condition(self, match, context):
|
10
|
-
condition, text = match.groups()
|
11
|
-
# Future implementations might parse and evaluate the condition more thoroughly
|
12
|
-
return text if condition in context and context[condition] else ""
|
13
|
-
|
14
|
-
def _render_conditionals(self, context: Dict[str, Union[str, int, float]]) -> str:
|
15
|
-
conditional_pattern = re.compile(r"\{if (.*?)\}(.*?)\{endif\}", re.DOTALL)
|
16
|
-
return conditional_pattern.sub(
|
17
|
-
lambda match: self._evaluate_condition(match, context), self.template_str
|
18
|
-
)
|
19
|
-
|
20
|
-
def _replace_callable(self, match, context):
|
21
|
-
key = match.group(1)
|
22
|
-
if key in context:
|
23
|
-
value = context[key]
|
24
|
-
return str(value() if callable(value) else value)
|
25
|
-
return match.group(0) # Unmatched placeholders remain unchanged.
|
26
|
-
|
27
|
-
def _render_placeholders(
|
28
|
-
self,
|
29
|
-
rendered_template: str,
|
30
|
-
context: Dict[str, Union[str, int, float, Callable]],
|
31
|
-
) -> str:
|
32
|
-
return re.sub(
|
33
|
-
r"\{(\w+)\}",
|
34
|
-
lambda match: self._replace_callable(match, context),
|
35
|
-
rendered_template,
|
36
|
-
)
|
37
|
-
|
38
|
-
def generate(self, context: Dict[str, Union[str, int, float, Callable]]) -> str:
|
39
|
-
"""
|
40
|
-
Generates output by first processing conditionals, then rendering placeholders,
|
41
|
-
including executing callable objects for dynamic data generation.
|
42
|
-
"""
|
43
|
-
template_with_conditionals = self._render_conditionals(context)
|
44
|
-
final_output = self._render_placeholders(template_with_conditionals, context)
|
45
|
-
return final_output
|
46
|
-
|
47
|
-
|
48
|
-
# from experiments.executor.executor import SafeEvaluator
|
49
|
-
|
50
|
-
# class DecisionTreeManual:
|
51
|
-
# def __init__(self, root):
|
52
|
-
# self.root = root
|
53
|
-
# self.evaluator = SafeEvaluator()
|
54
|
-
|
55
|
-
# def evaluate(self, context):
|
56
|
-
# return self._traverse_tree(self.root, context)
|
57
|
-
|
58
|
-
# def _traverse_tree(self, node, context):
|
59
|
-
# if isinstance(node, CompositeActionNode) or isinstance(node, ActionNode):
|
60
|
-
# return node.execute(context)
|
61
|
-
# elif isinstance(node, DecisionNode):
|
62
|
-
# condition_result = self.evaluator.evaluate(node.condition, context)
|
63
|
-
# next_node = node.true_branch if condition_result else node.false_branch
|
64
|
-
# return self._traverse_tree(next_node, context)
|
65
|
-
# else:
|
66
|
-
# raise ValueError("Invalid node type.")
|
@@ -1,59 +0,0 @@
|
|
1
|
-
from typing import Any
|
2
|
-
from pydantic import field_serializer
|
3
|
-
from functools import singledispatchmethod
|
4
|
-
from lionagi import logging as _logging
|
5
|
-
from lionagi.libs import func_call, AsyncUtil
|
6
|
-
from lionagi.core.generic.node import Node
|
7
|
-
from .function_calling import FunctionCalling
|
8
|
-
|
9
|
-
|
10
|
-
class Tool(Node):
|
11
|
-
|
12
|
-
func: Any
|
13
|
-
schema_: dict | None = None
|
14
|
-
manual: Any | None = None
|
15
|
-
parser: Any | None = None
|
16
|
-
pre_processor: Any | None = None
|
17
|
-
post_processor: Any | None = None
|
18
|
-
|
19
|
-
@property
|
20
|
-
def name(self):
|
21
|
-
return self.schema_["function"]["name"]
|
22
|
-
|
23
|
-
@field_serializer("func")
|
24
|
-
def serialize_func(self, func):
|
25
|
-
return func.__name__
|
26
|
-
|
27
|
-
@singledispatchmethod
|
28
|
-
async def invoke(self, values: Any) -> Any:
|
29
|
-
raise TypeError(f"Unsupported type {type(values)}")
|
30
|
-
|
31
|
-
@invoke.register
|
32
|
-
async def _(self, kwargs: dict):
|
33
|
-
|
34
|
-
out = None
|
35
|
-
|
36
|
-
if self.pre_processor:
|
37
|
-
kwargs = await func_call.unified_call(self.pre_processor, kwargs)
|
38
|
-
try:
|
39
|
-
out = await func_call.unified_call(self.func, **kwargs)
|
40
|
-
|
41
|
-
except Exception as e:
|
42
|
-
_logging.error(f"Error invoking function {self.func_name}: {e}")
|
43
|
-
return None
|
44
|
-
|
45
|
-
if self.post_processor:
|
46
|
-
return await func_call.unified_call(self.post_processor, out)
|
47
|
-
|
48
|
-
return out
|
49
|
-
|
50
|
-
@invoke.register
|
51
|
-
async def _(self, function_calls: FunctionCalling):
|
52
|
-
return await self.invoke(function_calls.kwargs)
|
53
|
-
|
54
|
-
@invoke.register
|
55
|
-
async def _(self, values: list):
|
56
|
-
return await func_call.alcall(self.invoke, values)
|
57
|
-
|
58
|
-
|
59
|
-
TOOL_TYPE = bool | Tool | str | list[Tool | str | dict] | dict
|
@@ -1,138 +0,0 @@
|
|
1
|
-
import asyncio
|
2
|
-
from functools import singledispatchmethod
|
3
|
-
from collections import deque
|
4
|
-
from typing import Tuple, Any, TypeVar, Callable
|
5
|
-
from lionagi.libs import func_call, convert, ParseUtil
|
6
|
-
from lionagi import logging as _logging
|
7
|
-
from .schema import Tool, TOOL_TYPE
|
8
|
-
from .util import func_to_tool, parse_tool_response
|
9
|
-
from .function_calling import FunctionCalling
|
10
|
-
|
11
|
-
T = TypeVar("T", bound=Tool)
|
12
|
-
|
13
|
-
|
14
|
-
class ToolManager:
|
15
|
-
|
16
|
-
def __init__(
|
17
|
-
self,
|
18
|
-
tool_registry: dict = {},
|
19
|
-
function_calling_tasks: dict[str : deque[FunctionCalling]] = {},
|
20
|
-
):
|
21
|
-
self.registry = tool_registry
|
22
|
-
self.function_calling_tasks = function_calling_tasks
|
23
|
-
|
24
|
-
@singledispatchmethod
|
25
|
-
def register_tools(self, tools: Any):
|
26
|
-
raise TypeError(f"Unsupported type {type(tools)}")
|
27
|
-
|
28
|
-
@register_tools.register(Tool)
|
29
|
-
def _(self, tools):
|
30
|
-
name = tools.schema_["function"]["name"]
|
31
|
-
if self._has_name(name):
|
32
|
-
err_msg = f"Function {name} is already registered."
|
33
|
-
_logging.error(err_msg)
|
34
|
-
raise ValueError(err_msg)
|
35
|
-
else:
|
36
|
-
self.registry[name] = tools
|
37
|
-
self.function_calling_tasks[name] = deque()
|
38
|
-
return True
|
39
|
-
|
40
|
-
@register_tools.register(Callable)
|
41
|
-
def _(self, tools):
|
42
|
-
tool = func_to_tool(tools)[0]
|
43
|
-
return self.register_tools(tool)
|
44
|
-
|
45
|
-
@register_tools.register(list)
|
46
|
-
def _(self, tools):
|
47
|
-
return func_call.lcall(tools, self.register_tools)
|
48
|
-
|
49
|
-
@singledispatchmethod
|
50
|
-
def register_function_calling(self, func_params: Any):
|
51
|
-
raise TypeError(f"Unsupported type {type(func_params)}")
|
52
|
-
|
53
|
-
@register_function_calling.register(tuple)
|
54
|
-
def _(self, func_params):
|
55
|
-
func = self.registry[func_params[0]].func
|
56
|
-
kwargs = func_params[1]
|
57
|
-
_function_calling = FunctionCalling(func=func, kwargs=kwargs)
|
58
|
-
self.function_calling_tasks[func.__name__].append(_function_calling)
|
59
|
-
return True
|
60
|
-
|
61
|
-
@register_function_calling.register(dict)
|
62
|
-
def _(self, response):
|
63
|
-
tuple_ = parse_tool_response(response)
|
64
|
-
return self.register_function_calling(tuple_)
|
65
|
-
|
66
|
-
@register_function_calling.register(list)
|
67
|
-
def _(self, func_params):
|
68
|
-
return func_call.lcall(func_params, self.register_function_calling)
|
69
|
-
|
70
|
-
async def invoke(self, func_params: Tuple[str, dict[str, Any]]) -> Any:
|
71
|
-
name, kwargs = func_params
|
72
|
-
if not self._has_name(name):
|
73
|
-
raise ValueError(f"Function {name} is not registered.")
|
74
|
-
tool = self.registry[name]
|
75
|
-
func = tool.func
|
76
|
-
parser = tool.parser
|
77
|
-
try:
|
78
|
-
out = await func_call.unified_call(func, **kwargs)
|
79
|
-
return parser(out) if parser else out
|
80
|
-
|
81
|
-
except Exception as e:
|
82
|
-
raise ValueError(
|
83
|
-
f"Error when invoking function {name} with arguments {kwargs} with error message {e}"
|
84
|
-
) from e
|
85
|
-
|
86
|
-
@property
|
87
|
-
def _schema_list(self) -> list[dict[str, Any]]:
|
88
|
-
return [tool.schema_ for tool in self.registry.values()]
|
89
|
-
|
90
|
-
def get_tool_schema(self, tools: TOOL_TYPE, **kwargs):
|
91
|
-
if isinstance(tools, bool):
|
92
|
-
tool_kwarg = {"tools": self._schema_list}
|
93
|
-
return tool_kwarg | kwargs
|
94
|
-
|
95
|
-
else:
|
96
|
-
if not isinstance(tools, list):
|
97
|
-
tools = [tools]
|
98
|
-
tool_kwarg = {"tools": self._get_tool_schema(tools)}
|
99
|
-
return tool_kwarg | kwargs
|
100
|
-
|
101
|
-
def _has_name(self, name: str) -> bool:
|
102
|
-
return name in self.registry
|
103
|
-
|
104
|
-
@singledispatchmethod
|
105
|
-
def _get_tool_schema(self, tool: Any) -> dict:
|
106
|
-
raise TypeError(f"Unsupported type {type(tool)}")
|
107
|
-
|
108
|
-
@_get_tool_schema.register(dict)
|
109
|
-
def _(self, tool):
|
110
|
-
"""
|
111
|
-
assuming that the tool is a schema
|
112
|
-
"""
|
113
|
-
return tool
|
114
|
-
|
115
|
-
@_get_tool_schema.register(Tool)
|
116
|
-
def _(self, tool):
|
117
|
-
if self._has_name(tool.name):
|
118
|
-
return self.registry[tool.name].schema_
|
119
|
-
else:
|
120
|
-
err_msg = f"Function {tool.name} is not registered."
|
121
|
-
_logging.error(err_msg)
|
122
|
-
raise ValueError(err_msg)
|
123
|
-
|
124
|
-
@_get_tool_schema.register(str)
|
125
|
-
def _(self, tool):
|
126
|
-
"""
|
127
|
-
assuming that the tool is a name
|
128
|
-
"""
|
129
|
-
if self._has_name(tool):
|
130
|
-
return self.registry[tool].schema_
|
131
|
-
else:
|
132
|
-
err_msg = f"Function {tool} is not registered."
|
133
|
-
_logging.error(err_msg)
|
134
|
-
raise ValueError(err_msg)
|
135
|
-
|
136
|
-
@_get_tool_schema.register(list)
|
137
|
-
def _(self, tools):
|
138
|
-
return func_call.lcall(tools, self._get_tool_schema)
|
@@ -1,16 +0,0 @@
|
|
1
|
-
from typing import Tuple
|
2
|
-
from lionagi.libs import convert
|
3
|
-
|
4
|
-
|
5
|
-
def parse_tool_response(response: dict) -> Tuple[str, dict]:
|
6
|
-
try:
|
7
|
-
func = response["action"][7:]
|
8
|
-
args = convert.to_dict(response["arguments"])
|
9
|
-
return func, args
|
10
|
-
except Exception:
|
11
|
-
try:
|
12
|
-
func = response["recipient_name"].split(".")[-1]
|
13
|
-
args = response["parameters"]
|
14
|
-
return func, args
|
15
|
-
except:
|
16
|
-
raise ValueError("response is not a valid function call")
|
@@ -1,25 +0,0 @@
|
|
1
|
-
from collections import deque
|
2
|
-
from typing import Dict
|
3
|
-
from pydantic import BaseModel, Field
|
4
|
-
from .schema import Work, WorkStatus
|
5
|
-
|
6
|
-
|
7
|
-
class WorkLog(BaseModel):
|
8
|
-
"""Model to store and manage work logs."""
|
9
|
-
|
10
|
-
logs: Dict[str, Work] = Field(default={}, description="Logs of work items")
|
11
|
-
pending: deque = Field(
|
12
|
-
default_factory=deque, description="Priority queue of pending work items"
|
13
|
-
)
|
14
|
-
errored: deque = Field(
|
15
|
-
default_factory=deque, description="Queue of errored work items"
|
16
|
-
)
|
17
|
-
|
18
|
-
def append(self, work: Work):
|
19
|
-
"""Append a work item to the logs and pending queue."""
|
20
|
-
self.logs[str(work.form_id)] = work
|
21
|
-
self.pending.append(str(work.form_id))
|
22
|
-
|
23
|
-
def get_by_status(self, status: WorkStatus) -> Dict[str, Work]:
|
24
|
-
"""Get work items by their status."""
|
25
|
-
return {wid: work for wid, work in self.logs.items() if work.status == status}
|
@@ -1,30 +0,0 @@
|
|
1
|
-
from enum import Enum
|
2
|
-
from typing import Any, Dict, List
|
3
|
-
from pydantic import Field
|
4
|
-
from lionagi.core.generic import BaseComponent
|
5
|
-
|
6
|
-
|
7
|
-
class WorkStatus(str, Enum):
|
8
|
-
"""Enum to represent different statuses of work."""
|
9
|
-
|
10
|
-
PENDING = "PENDING"
|
11
|
-
IN_PROGRESS = "IN_PROGRESS"
|
12
|
-
COMPLETED = "COMPLETED"
|
13
|
-
FAILED = "FAILED"
|
14
|
-
CANCELLED = "CANCELLED"
|
15
|
-
|
16
|
-
|
17
|
-
class Work(BaseComponent):
|
18
|
-
"""Base component for handling individual units of work."""
|
19
|
-
|
20
|
-
form_id: str = Field(..., description="ID of the form for this work")
|
21
|
-
priority: int = Field(default=0, description="Priority of the work")
|
22
|
-
status: WorkStatus = Field(
|
23
|
-
default=WorkStatus.PENDING, description="Current status of the work"
|
24
|
-
)
|
25
|
-
deliverables: Dict[str, Any] | list = Field(
|
26
|
-
default={}, description="Deliverables produced by the work"
|
27
|
-
)
|
28
|
-
dependencies: List["Work"] = Field(
|
29
|
-
default_factory=list, description="List of work items this work depends on"
|
30
|
-
)
|