We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

Calling Functions

Okay, now our agent can choose which function to call; it's time to actually call the function. This will require a bit of ceremony.

Assignment

  1. def call_function(tool_call, verbose: bool = False) -> dict:
    

    I put this function in call_function.py – the same module where I defined the list of available functions. As always, organize your code as you see fit.

    The tool_call argument is one of the tool-call objects from message.tool_calls. The three things we care about are:

    • tool_call.function.name: the name of the function (a string)
    • tool_call.function.arguments: the arguments, as a JSON string
    • tool_call.id: a unique ID for this call (we'll need it when we send the result back)
  2. function_name = tool_call.function.name
    function_args = json.loads(tool_call.function.arguments or "{}")
    
  3. print(f" - Calling function: {function_name}({function_args})")
    

    Otherwise, just print the name:

    print(f" - Calling function: {function_name}")
    
  4. from collections.abc import Callable
    
    function_map: dict[str, Callable[..., str]] = {
        "get_file_content": get_file_content,
        # etc.
    }
    
    • "role": "tool"
    • "tool_call_id": set to tool_call.id (this is how the model matches a result to the request it made)
    • "content": the string result of the function

    If the provided function name is not found in your mapping, return a tool message describing the error:

    return {
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": f"Error: Unknown function: {function_name}",
    }
    
    • The values in your map of function name -> function are callable functions, so you can just call the one you need, e.g., function_map[function_name]().
    • The syntax to pass a dictionary into a function using keyword arguments is some_function(**some_args).
    • Assign the result to a variable, e.g. result. Remember that all of our LLM-callable functions return strings.
  5. return {
        "role": "tool",
        "tool_call_id": tool_call.id,
        "content": result,
    }
    
    1. print(f"-> {result_message['content']}")
      
    • List a directory's contents.
    • Get a file's contents.
    • Write some text to a file (don't overwrite anything important; maybe create a new file).
    • Execute the calculator app's tests (tests.py).

We aren't passing the function call results back to the LLM just yet.

Submit the CLI tests.