Agentic AI: M3_UGL_1 Hardcoded Function

In the M3 Agentic AI ungraded lab exercise, executing tool calls is hardcoded:

# Run the tool locally
tool_result = get_current_time()

While this approach reduces initial code complexity, I find it severely limits the utility and scalability of the code. A more flexible approach would be to dynamically extract function names and arguments from the JSON response and execute them programmatically.

Here is one of the ways in which you can extract the function name and arguments and use them to execute the function programmatically. This code assumes that the JSON schema would not change.

from datetime import datetime
import json

function_registry = {}

def register_function(func):
    """Decorator to register functions"""
    function_registry[func.__name__] = func
    return func

# Register your functions
@register_function
def get_current_time():
    """
    Returns the current time as a string.
    """
    return datetime.now().strftime("%H:%M:%S")


# Load function name from JSON
with open('response.json', 'r') as f:
    response = json.load(f)
    func_name = response['choices'][0]['message']['tool_calls'][0]['function']['name']
    func_args_json = response['choices'][0]['message']['tool_calls'][0]['function']['arguments']

    # Parse the JSON string into a dictionary
    func_args = json.loads(func_args_json)  # Converts "{}" to {}

if func_name in function_registry:
    """ Assuming arguments are passed as a dictionary """
    result = function_registry[func_name](**func_args)
    print(f"Result: {result}")
else:
    print(f"Function '{func_name}' is not allowed")

Hi Umar_Faran_Mir,

One reason why the function call is hardcoded here may be that the code is easier to follow for learners. But extracting the function name and arguments from the JSON would indeed be more elegant and flexible.

Thanks for your comment and code snippet!

1 Like

My comment was premature, as the implementations in later modules were indeed done programmatically. Thanks.

Hi Umar_Faran_Mir,

Your comment may be useful to other learners wondering about the same issue. Your registry decorator may give other learners ideas. So thanks again!

1 Like