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
lionagi/libs/ln_convert.py
CHANGED
@@ -1,3 +1,19 @@
|
|
1
|
+
"""
|
2
|
+
Copyright 2024 HaiyangLi
|
3
|
+
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
+
you may not use this file except in compliance with the License.
|
6
|
+
You may obtain a copy of the License at
|
7
|
+
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
9
|
+
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
+
See the License for the specific language governing permissions and
|
14
|
+
limitations under the License.
|
15
|
+
"""
|
16
|
+
|
1
17
|
import json
|
2
18
|
import re
|
3
19
|
from functools import singledispatch
|
@@ -361,6 +377,8 @@ def _(
|
|
361
377
|
reset_index: bool = True,
|
362
378
|
**kwargs,
|
363
379
|
) -> pd.DataFrame:
|
380
|
+
if not input_:
|
381
|
+
return pd.DataFrame()
|
364
382
|
if not isinstance(input_[0], (pd.DataFrame, pd.Series, pd.core.generic.NDFrame)):
|
365
383
|
if drop_kwargs is None:
|
366
384
|
drop_kwargs = {}
|
@@ -400,7 +418,7 @@ def to_num(
|
|
400
418
|
*,
|
401
419
|
upper_bound: int | float | None = None,
|
402
420
|
lower_bound: int | float | None = None,
|
403
|
-
num_type: Type[int | float] =
|
421
|
+
num_type: Type[int | float] = float,
|
404
422
|
precision: int | None = None,
|
405
423
|
) -> int | float:
|
406
424
|
"""
|
@@ -423,15 +441,9 @@ def to_num(
|
|
423
441
|
return _str_to_num(str_, upper_bound, lower_bound, num_type, precision)
|
424
442
|
|
425
443
|
|
426
|
-
def to_readable_dict(input_: Any
|
444
|
+
def to_readable_dict(input_: Any) -> str:
|
427
445
|
"""
|
428
|
-
Converts a given input to a readable dictionary format
|
429
|
-
|
430
|
-
Args:
|
431
|
-
input_ (Any | list[Any]): The input to convert to a readable dictionary format.
|
432
|
-
|
433
|
-
Returns:
|
434
|
-
str | list[str]: The readable dictionary format of the input.
|
446
|
+
Converts a given input to a readable dictionary format
|
435
447
|
"""
|
436
448
|
|
437
449
|
try:
|
lionagi/libs/ln_func_call.py
CHANGED
@@ -1,3 +1,19 @@
|
|
1
|
+
"""
|
2
|
+
Copyright 2024 HaiyangLi
|
3
|
+
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
+
you may not use this file except in compliance with the License.
|
6
|
+
You may obtain a copy of the License at
|
7
|
+
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
9
|
+
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
+
See the License for the specific language governing permissions and
|
14
|
+
limitations under the License.
|
15
|
+
"""
|
16
|
+
|
1
17
|
from __future__ import annotations
|
2
18
|
|
3
19
|
import functools
|
@@ -115,12 +131,12 @@ async def alcall(
|
|
115
131
|
tasks = []
|
116
132
|
if input_ is not None:
|
117
133
|
lst = to_list(input_)
|
118
|
-
tasks = [
|
134
|
+
tasks = [call_handler(func, i, **kwargs) for i in lst]
|
119
135
|
|
120
136
|
else:
|
121
|
-
tasks = [
|
137
|
+
tasks = [call_handler(func, **kwargs)]
|
122
138
|
|
123
|
-
outs = await
|
139
|
+
outs = await asyncio.gather(*tasks)
|
124
140
|
outs_ = []
|
125
141
|
for i in outs:
|
126
142
|
outs_.append(await i if isinstance(i, (Coroutine, asyncio.Future)) else i)
|
@@ -128,6 +144,11 @@ async def alcall(
|
|
128
144
|
return to_list(outs_, flatten=flatten, dropna=dropna)
|
129
145
|
|
130
146
|
|
147
|
+
async def pcall(funcs):
|
148
|
+
task = [call_handler(func) for func in funcs]
|
149
|
+
return await asyncio.gather(*task)
|
150
|
+
|
151
|
+
|
131
152
|
async def mcall(
|
132
153
|
input_: Any, /, func: Any, *, explode: bool = False, **kwargs
|
133
154
|
) -> tuple[Any]:
|
@@ -290,10 +311,12 @@ async def rcall(
|
|
290
311
|
func: Callable,
|
291
312
|
*args,
|
292
313
|
retries: int = 0,
|
293
|
-
delay: float = 1
|
294
|
-
backoff_factor: float = 2
|
314
|
+
delay: float = 0.1,
|
315
|
+
backoff_factor: float = 2,
|
295
316
|
default: Any = None,
|
296
317
|
timeout: float | None = None,
|
318
|
+
timing: bool = False,
|
319
|
+
verbose: bool = True,
|
297
320
|
**kwargs,
|
298
321
|
) -> Any:
|
299
322
|
"""
|
@@ -339,20 +362,34 @@ async def rcall(
|
|
339
362
|
last_exception = None
|
340
363
|
result = None
|
341
364
|
|
365
|
+
start = SysUtil.get_now(datetime_=False)
|
342
366
|
for attempt in range(retries + 1) if retries == 0 else range(retries):
|
343
367
|
try:
|
368
|
+
err_msg = f"Attempt {attempt + 1}/{retries}: " if retries > 0 else None
|
369
|
+
if timing:
|
370
|
+
return (
|
371
|
+
await _tcall(
|
372
|
+
func, *args, err_msg=err_msg, timeout=timeout, **kwargs
|
373
|
+
),
|
374
|
+
SysUtil.get_now(datetime_=False) - start,
|
375
|
+
)
|
376
|
+
|
344
377
|
return await _tcall(func, *args, timeout=timeout, **kwargs)
|
345
378
|
except Exception as e:
|
346
379
|
last_exception = e
|
347
380
|
if attempt < retries:
|
348
|
-
|
381
|
+
if verbose:
|
382
|
+
print(f"Attempt {attempt + 1}/{retries} failed: {e}, retrying...")
|
383
|
+
await asyncio.sleep(delay)
|
349
384
|
delay *= backoff_factor
|
350
385
|
else:
|
351
386
|
break
|
352
387
|
if result is None and default is not None:
|
353
388
|
return default
|
354
389
|
elif last_exception is not None:
|
355
|
-
raise
|
390
|
+
raise RuntimeError(
|
391
|
+
f"Operation failed after {retries+1} attempts: {last_exception}"
|
392
|
+
) from last_exception
|
356
393
|
else:
|
357
394
|
raise RuntimeError("rcall failed without catching an exception")
|
358
395
|
|
@@ -395,8 +432,8 @@ async def _alcall(
|
|
395
432
|
[1, 4, 9]
|
396
433
|
"""
|
397
434
|
lst = to_list(input_)
|
398
|
-
tasks = [
|
399
|
-
outs = await
|
435
|
+
tasks = [call_handler(func, i, **kwargs) for i in lst]
|
436
|
+
outs = await asyncio.gather(*tasks)
|
400
437
|
return to_list(outs, flatten=flatten)
|
401
438
|
|
402
439
|
|
@@ -435,11 +472,11 @@ async def _tcall(
|
|
435
472
|
"""
|
436
473
|
start_time = SysUtil.get_now(datetime_=False)
|
437
474
|
try:
|
438
|
-
await
|
475
|
+
await asyncio.sleep(delay)
|
439
476
|
# Apply timeout to the function call
|
440
477
|
if timeout is not None:
|
441
478
|
coro = ""
|
442
|
-
if
|
479
|
+
if is_coroutine_func(func):
|
443
480
|
coro = func(*args, **kwargs)
|
444
481
|
else:
|
445
482
|
|
@@ -451,14 +488,13 @@ async def _tcall(
|
|
451
488
|
result = await asyncio.wait_for(coro, timeout)
|
452
489
|
|
453
490
|
else:
|
454
|
-
if
|
491
|
+
if is_coroutine_func(func):
|
455
492
|
return await func(*args, **kwargs)
|
456
493
|
return func(*args, **kwargs)
|
457
494
|
duration = SysUtil.get_now(datetime_=False) - start_time
|
458
495
|
return (result, duration) if timing else result
|
459
496
|
except asyncio.TimeoutError as e:
|
460
|
-
err_msg = f"{err_msg}
|
461
|
-
print(err_msg)
|
497
|
+
err_msg = f"{err_msg or ''}Timeout {timeout} seconds exceeded"
|
462
498
|
if ignore_err:
|
463
499
|
return (
|
464
500
|
(default, SysUtil.get_now(datetime_=False) - start_time)
|
@@ -466,10 +502,9 @@ async def _tcall(
|
|
466
502
|
else default
|
467
503
|
)
|
468
504
|
else:
|
469
|
-
raise
|
505
|
+
raise asyncio.TimeoutError(err_msg) # Re-raise the timeout exception
|
470
506
|
except Exception as e:
|
471
507
|
err_msg = f"{err_msg} Error: {e}" if err_msg else f"An error occurred: {e}"
|
472
|
-
print(err_msg)
|
473
508
|
if ignore_err:
|
474
509
|
return (
|
475
510
|
(default, SysUtil.get_now(datetime_=False) - start_time)
|
@@ -537,7 +572,11 @@ class CallDecorator:
|
|
537
572
|
|
538
573
|
@staticmethod
|
539
574
|
def retry(
|
540
|
-
retries: int = 3,
|
575
|
+
retries: int = 3,
|
576
|
+
delay: float = 2.0,
|
577
|
+
backoff_factor: float = 2.0,
|
578
|
+
default=...,
|
579
|
+
verbose=True,
|
541
580
|
) -> Callable:
|
542
581
|
"""
|
543
582
|
Decorates an asynchronous function to automatically retry on failure,
|
@@ -581,6 +620,8 @@ class CallDecorator:
|
|
581
620
|
retries=retries,
|
582
621
|
delay=delay,
|
583
622
|
backoff_factor=backoff_factor,
|
623
|
+
default=default,
|
624
|
+
verbose=verbose,
|
584
625
|
**kwargs,
|
585
626
|
)
|
586
627
|
|
@@ -690,7 +731,7 @@ class CallDecorator:
|
|
690
731
|
"""
|
691
732
|
|
692
733
|
def decorator(func: Callable[..., list[Any]]) -> Callable:
|
693
|
-
if
|
734
|
+
if is_coroutine_func(func):
|
694
735
|
|
695
736
|
@functools.wraps(func)
|
696
737
|
async def async_wrapper(*args, **kwargs) -> list[Any]:
|
@@ -748,7 +789,7 @@ class CallDecorator:
|
|
748
789
|
"""
|
749
790
|
|
750
791
|
def decorator(func: Callable) -> Callable:
|
751
|
-
if not any(
|
792
|
+
if not any(is_coroutine_func(f) for f in functions):
|
752
793
|
|
753
794
|
@functools.wraps(func)
|
754
795
|
def sync_wrapper(*args, **kwargs):
|
@@ -763,7 +804,7 @@ class CallDecorator:
|
|
763
804
|
return value
|
764
805
|
|
765
806
|
return sync_wrapper
|
766
|
-
elif all(
|
807
|
+
elif all(is_coroutine_func(f) for f in functions):
|
767
808
|
|
768
809
|
@functools.wraps(func)
|
769
810
|
async def async_wrapper(*args, **kwargs):
|
@@ -827,7 +868,7 @@ class CallDecorator:
|
|
827
868
|
"""
|
828
869
|
|
829
870
|
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
|
830
|
-
if
|
871
|
+
if is_coroutine_func(func):
|
831
872
|
|
832
873
|
@functools.wraps(func)
|
833
874
|
async def async_wrapper(*args, **kwargs) -> Any:
|
@@ -889,7 +930,7 @@ class CallDecorator:
|
|
889
930
|
... # will return the cached result without re-executing the function body.
|
890
931
|
"""
|
891
932
|
|
892
|
-
if
|
933
|
+
if is_coroutine_func(func):
|
893
934
|
# Asynchronous function handling
|
894
935
|
@AsyncUtil.cached(ttl=ttl)
|
895
936
|
async def cached_async(*args, **kwargs) -> Any:
|
@@ -993,7 +1034,7 @@ class CallDecorator:
|
|
993
1034
|
"""
|
994
1035
|
|
995
1036
|
def decorator(func: Callable[..., list[Any]]) -> Callable:
|
996
|
-
if
|
1037
|
+
if is_coroutine_func(func):
|
997
1038
|
|
998
1039
|
@functools.wraps(func)
|
999
1040
|
async def async_wrapper(*args, **kwargs) -> Any:
|
@@ -1039,11 +1080,11 @@ class CallDecorator:
|
|
1039
1080
|
"""
|
1040
1081
|
|
1041
1082
|
def decorator(func: Callable) -> Callable:
|
1042
|
-
if not
|
1083
|
+
if not is_coroutine_func(func):
|
1043
1084
|
raise TypeError(
|
1044
1085
|
"max_concurrency decorator can only be used with async functions."
|
1045
1086
|
)
|
1046
|
-
semaphore =
|
1087
|
+
semaphore = asyncio.Semaphore(limit)
|
1047
1088
|
|
1048
1089
|
@functools.wraps(func)
|
1049
1090
|
async def wrapper(*args, **kwargs):
|
@@ -1089,7 +1130,7 @@ class CallDecorator:
|
|
1089
1130
|
@functools.wraps(fn)
|
1090
1131
|
def wrapper(*args, **kwargs):
|
1091
1132
|
future = pool.submit(fn, *args, **kwargs)
|
1092
|
-
return
|
1133
|
+
return asyncio.wrap_future(future) # make it awaitable
|
1093
1134
|
|
1094
1135
|
return wrapper
|
1095
1136
|
|
@@ -1233,8 +1274,8 @@ async def call_handler(
|
|
1233
1274
|
except Exception as e:
|
1234
1275
|
if error_map:
|
1235
1276
|
_custom_error_handler(e, error_map)
|
1236
|
-
else:
|
1237
|
-
|
1277
|
+
# else:
|
1278
|
+
# logging.error(f"Error in call_handler: {e}")
|
1238
1279
|
raise
|
1239
1280
|
|
1240
1281
|
|
lionagi/libs/ln_image.py
ADDED
@@ -0,0 +1,107 @@
|
|
1
|
+
import base64
|
2
|
+
import numpy as np
|
3
|
+
from typing import Optional
|
4
|
+
from .sys_util import SysUtil
|
5
|
+
|
6
|
+
|
7
|
+
class ImageUtil:
|
8
|
+
|
9
|
+
@staticmethod
|
10
|
+
def preprocess_image(
|
11
|
+
image: np.ndarray, color_conversion_code: Optional[int] = None
|
12
|
+
) -> np.ndarray:
|
13
|
+
SysUtil.check_import("cv2", pip_name="opencv-python")
|
14
|
+
import cv2
|
15
|
+
|
16
|
+
color_conversion_code = color_conversion_code or cv2.COLOR_BGR2RGB
|
17
|
+
return cv2.cvtColor(image, color_conversion_code)
|
18
|
+
|
19
|
+
@staticmethod
|
20
|
+
def encode_image_to_base64(image: np.ndarray, file_extension: str = ".jpg") -> str:
|
21
|
+
SysUtil.check_import("cv2", pip_name="opencv-python")
|
22
|
+
import cv2
|
23
|
+
|
24
|
+
success, buffer = cv2.imencode(file_extension, image)
|
25
|
+
if not success:
|
26
|
+
raise ValueError(f"Could not encode image to {file_extension} format.")
|
27
|
+
encoded_image = base64.b64encode(buffer).decode("utf-8")
|
28
|
+
return encoded_image
|
29
|
+
|
30
|
+
@staticmethod
|
31
|
+
def read_image_to_array(
|
32
|
+
image_path: str, color_flag: Optional[int] = None
|
33
|
+
) -> np.ndarray:
|
34
|
+
SysUtil.check_import("cv2", pip_name="opencv-python")
|
35
|
+
import cv2
|
36
|
+
|
37
|
+
image = cv2.imread(image_path, color_flag)
|
38
|
+
color_flag = color_flag or cv2.IMREAD_COLOR
|
39
|
+
if image is None:
|
40
|
+
raise ValueError(f"Could not read image from path: {image_path}")
|
41
|
+
return image
|
42
|
+
|
43
|
+
@staticmethod
|
44
|
+
def read_image_to_base64(
|
45
|
+
image_path: str,
|
46
|
+
color_flag: Optional[int] = None,
|
47
|
+
) -> str:
|
48
|
+
image_path = str(image_path)
|
49
|
+
image = ImageUtil.read_image_to_array(image_path, color_flag)
|
50
|
+
|
51
|
+
file_extension = "." + image_path.split(".")[-1]
|
52
|
+
return ImageUtil.encode_image_to_base64(image, file_extension)
|
53
|
+
|
54
|
+
# @staticmethod
|
55
|
+
# def encode_image(image_path):
|
56
|
+
# with open(image_path, "rb") as image_file:
|
57
|
+
# return base64.b64encode(image_file.read()).decode("utf-8")
|
58
|
+
|
59
|
+
@staticmethod
|
60
|
+
def calculate_image_token_usage_from_base64(image_base64: str, detail):
|
61
|
+
"""
|
62
|
+
Calculate the token usage for processing OpenAI images from a base64-encoded string.
|
63
|
+
|
64
|
+
Parameters:
|
65
|
+
image_base64 (str): The base64-encoded string of the image.
|
66
|
+
detail (str): The detail level of the image, either 'low' or 'high'.
|
67
|
+
|
68
|
+
Returns:
|
69
|
+
int: The total token cost for processing the image.
|
70
|
+
"""
|
71
|
+
import base64
|
72
|
+
from io import BytesIO
|
73
|
+
from PIL import Image
|
74
|
+
|
75
|
+
# Decode the base64 string to get image data
|
76
|
+
if "data:image/jpeg;base64," in image_base64:
|
77
|
+
image_base64 = image_base64.split("data:image/jpeg;base64,")[1]
|
78
|
+
image_base64.strip("{}")
|
79
|
+
|
80
|
+
image_data = base64.b64decode(image_base64)
|
81
|
+
image = Image.open(BytesIO(image_data))
|
82
|
+
|
83
|
+
# Get image dimensions
|
84
|
+
width, height = image.size
|
85
|
+
|
86
|
+
if detail == "low":
|
87
|
+
return 85
|
88
|
+
|
89
|
+
# Scale to fit within a 2048 x 2048 square
|
90
|
+
max_dimension = 2048
|
91
|
+
if width > max_dimension or height > max_dimension:
|
92
|
+
scale_factor = max_dimension / max(width, height)
|
93
|
+
width = int(width * scale_factor)
|
94
|
+
height = int(height * scale_factor)
|
95
|
+
|
96
|
+
# Scale such that the shortest side is 768px
|
97
|
+
min_side = 768
|
98
|
+
if min(width, height) > min_side:
|
99
|
+
scale_factor = min_side / min(width, height)
|
100
|
+
width = int(width * scale_factor)
|
101
|
+
height = int(height * scale_factor)
|
102
|
+
|
103
|
+
# Calculate the number of 512px squares
|
104
|
+
num_squares = (width // 512) * (height // 512)
|
105
|
+
token_cost = 170 * num_squares + 85
|
106
|
+
|
107
|
+
return token_cost
|
lionagi/libs/ln_nested.py
CHANGED
@@ -1,3 +1,19 @@
|
|
1
|
+
"""
|
2
|
+
Copyright 2024 HaiyangLi
|
3
|
+
|
4
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
5
|
+
you may not use this file except in compliance with the License.
|
6
|
+
You may obtain a copy of the License at
|
7
|
+
|
8
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
9
|
+
|
10
|
+
Unless required by applicable law or agreed to in writing, software
|
11
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
12
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
13
|
+
See the License for the specific language governing permissions and
|
14
|
+
limitations under the License.
|
15
|
+
"""
|
16
|
+
|
1
17
|
from collections import defaultdict
|
2
18
|
from itertools import chain
|
3
19
|
from typing import Any, Generator, Callable
|
@@ -52,7 +68,7 @@ def nset(nested_structure: dict | list, indices: list[int | str], value: Any) ->
|
|
52
68
|
def nget(
|
53
69
|
nested_structure: dict | list,
|
54
70
|
indices: list[int | str],
|
55
|
-
default
|
71
|
+
default=...,
|
56
72
|
) -> Any:
|
57
73
|
"""
|
58
74
|
retrieves a value from a nested list or dictionary structure, with an option to
|
@@ -98,12 +114,12 @@ def nget(
|
|
98
114
|
return target_container[last_index]
|
99
115
|
elif isinstance(target_container, dict) and last_index in target_container:
|
100
116
|
return target_container[last_index]
|
101
|
-
elif default is not
|
117
|
+
elif default is not ...:
|
102
118
|
return default
|
103
119
|
else:
|
104
120
|
raise LookupError("Target not found and no default value provided.")
|
105
121
|
except (IndexError, KeyError, TypeError):
|
106
|
-
if default is not
|
122
|
+
if default is not ...:
|
107
123
|
return default
|
108
124
|
else:
|
109
125
|
raise LookupError("Target not found and no default value provided.")
|
@@ -116,7 +132,7 @@ def nmerge(
|
|
116
132
|
*,
|
117
133
|
overwrite: bool = False,
|
118
134
|
dict_sequence: bool = False,
|
119
|
-
sequence_separator: str = "_",
|
135
|
+
sequence_separator: str = "[^_^]",
|
120
136
|
sort_list: bool = False,
|
121
137
|
custom_sort: Callable[[Any], Any] | None = None,
|
122
138
|
) -> dict | list:
|
@@ -176,7 +192,7 @@ def flatten(
|
|
176
192
|
/,
|
177
193
|
*,
|
178
194
|
parent_key: str = "",
|
179
|
-
sep: str = "_",
|
195
|
+
sep: str = "[^_^]",
|
180
196
|
max_depth: int | None = None,
|
181
197
|
inplace: bool = False,
|
182
198
|
dict_only: bool = False,
|
@@ -238,7 +254,7 @@ def unflatten(
|
|
238
254
|
flat_dict: dict[str, Any],
|
239
255
|
/,
|
240
256
|
*,
|
241
|
-
sep: str = "_",
|
257
|
+
sep: str = "[^_^]",
|
242
258
|
custom_logic: Callable[[str], Any] | None = None,
|
243
259
|
max_depth: int | None = None,
|
244
260
|
) -> dict | list:
|
@@ -330,7 +346,7 @@ def ninsert(
|
|
330
346
|
indices: list[str | int],
|
331
347
|
value: Any,
|
332
348
|
*,
|
333
|
-
sep: str = "_",
|
349
|
+
sep: str = "[^_^]",
|
334
350
|
max_depth: int | None = None,
|
335
351
|
current_depth: int = 0,
|
336
352
|
) -> None:
|
@@ -393,12 +409,11 @@ def ninsert(
|
|
393
409
|
nested_structure[last_part] = value
|
394
410
|
|
395
411
|
|
396
|
-
# noinspection PyDecorator
|
397
412
|
def get_flattened_keys(
|
398
413
|
nested_structure: Any,
|
399
414
|
/,
|
400
415
|
*,
|
401
|
-
sep: str = "_",
|
416
|
+
sep: str = "[^_^]",
|
402
417
|
max_depth: int | None = None,
|
403
418
|
dict_only: bool = False,
|
404
419
|
inplace: bool = False,
|
@@ -448,7 +463,7 @@ def _dynamic_flatten_in_place(
|
|
448
463
|
/,
|
449
464
|
*,
|
450
465
|
parent_key: str = "",
|
451
|
-
sep: str = "_",
|
466
|
+
sep: str = "[^_^]",
|
452
467
|
max_depth: int | None = None,
|
453
468
|
current_depth: int = 0,
|
454
469
|
dict_only: bool = False,
|
@@ -581,7 +596,7 @@ def _deep_update(original: dict, update: dict) -> dict:
|
|
581
596
|
def _dynamic_flatten_generator(
|
582
597
|
nested_structure: Any,
|
583
598
|
parent_key: tuple[str, ...],
|
584
|
-
sep: str = "_",
|
599
|
+
sep: str = "[^_^]",
|
585
600
|
max_depth: int | None = None,
|
586
601
|
current_depth: int = 0,
|
587
602
|
dict_only: bool = False,
|