

0 / 2 embers
0 / 3000 xp
click for more info
Complete a lesson to start your streak
click for more info
Difficulty: 5
click for more info
Not enough gems
Cost: 6 gems
1: System Prompt
incomplete
2: Function Declaration
incomplete
3: More Declarations
incomplete
4: Calling Functions
incomplete
This lesson's interactive features are locked, please to keep using them
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.
def call_function(tool_call, verbose: bool = False) -> dict:Add this function to the existing call_function.py at the root of your project, alongside available_functions.
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)
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments or "{}")print(f" - Calling function: {function_name}({function_args})")Otherwise, just print the name:
print(f" - Calling function: {function_name}")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.
return {
"role": "tool",
"tool_call_id": tool_call.id,
"content": result,
}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.