From the course: OpenAI API and MCP Development
Using tools and calling functions
From the course: OpenAI API and MCP Development
Using tools and calling functions
Language models are non-deterministic, meaning that you cannot predict what's going to be the response or output from a language model. This is when it is necessary to use structured outputs using JSON. So this is a feature that you use to always ensure that models always follow a specific format, every time. So we're going to be able to do that by controlling the way that we generate outputs using function calling, but also when we call functions. We're going to use a specific JSON format to use this information using a specific and always the same format. So right now we are at step two, when we want to call the tools. Let's go back to our example. So that's going to be step two here, line 102. And we're going to deal with here calling functions. All right, so that's going to be whenever we know that tool calls needs to be called, actually. So this is going to be handled here, line 97, only if there is no need to call tools or any function. And inside this function call function, so what happens is that we're going to iterate through every tool calls and get the response after calling here, in this case, an external API. So we're going to get the information from the API, which is the location, the unit, but also the actual information after calling an API, which is related to getting the weather forecasts. And then we're going to print here line 69, the function response. Then we use this information to provide with very specific information here using this object format with the function name and the function response. OK, so let's try that. So I'm going to run with PythonMain.py. And the question I'm going to ask is, what is the weather in London? All right, so here you have the chat completion object. And right below, you can see this object. I'm going to highlight this one so you have the location, which is London, which is the actual city that I have requested about. So that's correct. Then the temperature, which is for now 10 degrees. But I think it's actually correct, because this is calling the API. Then we have the unit, temperature unit, which is Celsius, and the forecast, which is overcast clouds. And if we check the weather right now, I'm going to say London weather. So right now, this is correct. This is exactly 10 degrees, just like the way that it was returned to our language model, using the language models, but also using function calling. So what we've done here is to allow the language models to call a function. This function role is to interact with an API that returns as information. So part of the request, which is the location, the temperature unit, but also the actual weather data information. So the next part will be to actually understand how we can interact with the external API.