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")