Ensure each function has a precise signature and a comprehensive docstring describing its purpose and parameters.
Convert Functions to JSON Schemas
Utilize Python’s inspect module to extract function signatures and convert them into JSON schemas compatible with the ChatGPT API.
Convert tool defined in class into schema
To convert a tool defined in a class into a schema compatible with the ChatGPT API, you can extract the methods of the class (treated as tools) and map their details (like name, description, and parameters) into the schema format.
Class to schema
How to use it?
Instantiate the Class and Convert to Schemas
Example output of tool_schemas
Register the Tools with the ChatGPT API
Implement the Chat Interaction Loop:
A function to handle user input, manage conversation history, use tools and interact with the ChatGPT API.
Call the Methods Dynamically (Future work)
Calling methods dynamically means to invoking a method at runtime without hardcoding its name. Instead of directly calling math_tools.add(3, 4), you use the method’s name (as a string) and dynamically look up and execute it.
This is useful when:
• The method to be called isn’t known until runtime.
• You want to map string names (e.g., from a user query or an API) to actual method calls.
• You need flexibility to handle multiple methods without writing individual if-else or switch statements.
Example in Real Use Case
Suppose you integrate this with an API like ChatGPT:
The user asks the assistant: “Add 3 and 4”.
The assistant recognizes the operation “add”.
The corresponding method (MathTools.add) is dynamically identified and invoked using tool_map.
The result (7) is returned to the user.
This dynamic lookup ensures the assistant is extensible and doesn’t require hardcoded mappings for every possible operation.
Code Example
Handle Tool Invocation Dynamically
After receiving the response, check if the assistant has identified a function call.
Dynamically map the tool name to its corresponding method and invoke it.
Full example
Send the Result Back to ChatGPT:
• Use the result obtained from the dynamically invoked method to respond back to the user.