Wraps a user-defined function to accept arguments as a dictionary. Args: user_function (Callable): The user-defined function to wrap. Returns: Callable: The wrapped function.
(user_function: Callable, with_task=False)
| 28 | |
| 29 | |
| 30 | def wrap_user_function(user_function: Callable, with_task=False) -> Callable: |
| 31 | """ |
| 32 | Wraps a user-defined function to accept arguments as a dictionary. |
| 33 | |
| 34 | Args: |
| 35 | user_function (Callable): The user-defined function to wrap. |
| 36 | |
| 37 | Returns: |
| 38 | Callable: The wrapped function. |
| 39 | """ |
| 40 | |
| 41 | @functools.wraps(user_function) |
| 42 | async def wrapper(*args): |
| 43 | # Get the parameter names of the user-defined function |
| 44 | user_function_params = list(inspect.signature(user_function).parameters.keys()) |
| 45 | |
| 46 | # Create a dictionary of parameter names and their corresponding values from *args |
| 47 | params_values = { |
| 48 | param_name: arg for param_name, arg in zip(user_function_params, args) |
| 49 | } |
| 50 | |
| 51 | if with_task: |
| 52 | await context.emitter.task_start() |
| 53 | |
| 54 | try: |
| 55 | # Call the user-defined function with the arguments |
| 56 | if inspect.iscoroutinefunction(user_function): |
| 57 | return await user_function(**params_values) |
| 58 | else: |
| 59 | return user_function(**params_values) |
| 60 | except CancelledError: |
| 61 | pass |
| 62 | except Exception as e: |
| 63 | logger.exception(e) |
| 64 | if with_task: |
| 65 | from chainlit.message import ErrorMessage |
| 66 | |
| 67 | await ErrorMessage( |
| 68 | content=str(e) or e.__class__.__name__, author="Error" |
| 69 | ).send() |
| 70 | finally: |
| 71 | if with_task: |
| 72 | await context.emitter.task_end() |
| 73 | |
| 74 | return wrapper |
| 75 | |
| 76 | |
| 77 | def make_module_getattr(registry): |
no outgoing calls
searching dependent graphs…