Function calling, now called tools, is the most reliable way to get structured JSON from a model when the model needs to trigger your code. You define a schema and the model returns a JSON object that matches it exactly, in the tool call arguments rather than in the message text. The model does not run any code itself: it generates the JSON arguments that you would pass to the function, and you are responsible for calling the function and returning the result.
What you need
- An API client with function calling support
- A real function the model may call, such as a weather lookup
- Code to parse the tool call arguments and run the function
Step 1: Define the function with a schema
Define a function called get_weather with a description and parameters: location as a string and unit as a string with the enum celsius and fahrenheit, with location required. The description tells the model when to call it.
Step 2: Read the tool call arguments
Send the user message with the tools list. If the model calls the tool, the arguments arrive as JSON in the tool call, not in the message content. Parse them before using them.
Step 3: Run the function and return the result
Call your real weather function with the parsed location and unit, then send the result back to the model with the tool call id, so the model can write its answer from real data.
Worked example: synthetic weather function call
The table below is a synthetic example. It shows the expected result of a function-calling round trip; no API call was made.
| Step | Value | Check |
|---|---|---|
| User message | Get the weather in San Francisco | Pass |
| Tool call | get_weather, location San Francisco, unit celsius | Pass |
| Function result | 18 degrees, clear | Returned with tool call id |
| Final answer | Uses the real result | Pass |
Expected result (UNTESTED). the model calls get_weather with the right arguments, the real function runs, and the final answer uses the returned weather. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- The model does not run code; it only proposes the call, and your code must execute it.
- Regular function calling guarantees valid JSON but not exact schema adherence; strict mode constrains the model to the exact schema.
- If you are connecting the model to tools, functions or data, use function calling; if you want to structure the model reply to the user, use a structured text.format instead.
- Always validate the parsed arguments before running the function; a schema-correct call can still carry a wrong value.
