Step 1: Define Your Functions: Describe the external tools or APIs available to the model. Provide a name, description, and parameters (using JSON Schema format) for each function. The parameters define the arguments the function accepts.
Step 2: Call the Chat Completions API with Function Definitions: Include your defined functions in the functions parameter of the chat.completions.create API call. Send the user's message as usual in the messages array.
Step 3: Check for Function Call Response: After receiving the API response, inspect the response.choices[0].message.function_call field. If present, the model has decided to call one of your defined functions.
Step 4: Parse and Validate the Function Call: Extract the name and arguments (a JSON string) from the function_call object. Parse the arguments string into a Python dictionary or similar data structure. Validate the arguments against your function's expected schema.
Step 5: Execute the External Tool/Function: Use the parsed function_name and arguments to invoke your actual backend function or make the external API call (e.g., fetch weather data, query database).
Step 6: Return Tool Output to the Model: Add two new messages to your messages array: first, the original function_call message from the model, and second, a function role message containing the name of the called function and its content (the output from the executed tool).
Step 7: Call the Chat Completions API Again: Resend the updated messages array (including the tool output) to the chat.completions.create endpoint. The model will then use the tool's output to generate a natural language response for the user.