Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/features/tool_calling.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ Next, make a request to the model that should result in it using the available t
tool_call = response.choices[0].message.tool_calls[0].function
print(f"Function called: {tool_call.name}")
print(f"Arguments: {tool_call.arguments}")
print(f"Result: {get_weather(**json.loads(tool_call.arguments))}")
print(f"Result: {tool_functions[tool_call.name](**json.loads(tool_call.arguments))}")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This change is a great improvement to the documentation as it demonstrates a more robust and scalable pattern for tool calling.

However, the current implementation tool_functions[tool_call.name] is susceptible to a KeyError if the model hallucinates a function name that is not defined in the tool_functions dictionary. While this might be acceptable for a simple example, making it more robust would be highly beneficial for users who might adapt this code for production use.

Consider adding error handling to gracefully manage cases where the function name is not found. Here's a more robust approach:

    # Safely get the function from the dictionary
    func_to_call = tool_functions.get(tool_call.name)

    if func_to_call:
        # It's also good practice to handle potential JSON and argument errors
        try:
            arguments = json.loads(tool_call.arguments)
            result = func_to_call(**arguments)
            print(f"Result: {result}")
        except (json.JSONDecodeError, TypeError) as e:
            print(f"Error calling function '{tool_call.name}': {e}")
    else:
        print(f"Error: Function '{tool_call.name}' not found.")

Since this change would expand a single line into multiple, I'm providing it here for your consideration rather than as a direct suggestion. This would help users writing production code to be aware of potential pitfalls.

```

Example output:
Expand Down
Loading