search
HomeTechnology peripheralsAIOpenAI Function Calling Tutorial: Generate Structured Output

Using OpenAI Without Function Calling

In this section, we will generate responses using the GPT-3.5-Turbo model without function calling to see if we get consistent output or not.

Before installing the OpenAI Python API, you must obtain an API key and set it up on your local system. Follow the GPT-3.5 and GPT-4 via the OpenAI API in Python tutorial to learn how to get the API key and set it up. The tutorial also includes examples of setting up environment variables in DataLab, DataCamp's AI-enabled data notebook.

For further assistance, check out the code in OpenAI Function Calling workbook on DataLab.

Upgrade the OpenAI Python API to V1 using:

pip install --upgrade openai -q

After that, initiate the OpenAI client using the API key.

import os
from openai import OpenAI

client = OpenAI(
  api_key=os.environ['OPENAI_API_KEY'],
)

Note: OpenAI no longer offers free credits to new users, so you have to buy them to use the API.

We will write a random student description. Either you can come up with your own text or use ChatGPT to generate one for you.

student_1_description = "David Nguyen is a sophomore majoring in computer science at Stanford University. He is Asian American and has a 3.8 GPA. David is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after graduating."

In the next part, we will write a prompt to extract student information from the text and return the output as a JSON object. We will extract the name, major, school, grades, and clubs in the student description.

# A simple prompt to extract information from "student_description" in a JSON format.
prompt1 = f'''
Please extract the following information from the given text and return it as a JSON object:

name
major
school
grades
club

This is the body of text to extract the information from:
{student_1_description}
'''

Add the prompt to the OpenAI API chat completion module to generate the response.

# Generating response back from gpt-3.5-turbo
openai_response = client.chat.completions.create(
    model = 'gpt-3.5-turbo',
    messages = [{'role': 'user', 'content': prompt_1}]
)

openai_response.choices[0].message.content

The response is quite good. Let’s convert it into JSON to understand it better.

'{\n  "name": "David Nguyen",\n  "major": "computer science",\n  "school": "Stanford University",\n  "grades": "3.8 GPA",\n  "club": "Robotics Club"\n}'

We will use the `json` library to convert the text into a JSON object.

import json

# Loading the response as a JSON object
json_response = json.loads(openai_response.choices[0].message.content)
json_response

The final result is pretty much perfect. So, why do we need Function Calling?

{'name': 'David Nguyen',
 'major': 'computer science',
 'school': 'Stanford University',
 'grades': '3.8 GPA',
 'club': 'Robotics Club'}

Let’s try the same prompt, but using a different student description.

student_2_description="Ravi Patel is a sophomore majoring in computer science at the University of Michigan. He is South Asian Indian American and has a 3.7 GPA. Ravi is an active member of the university's Chess Club and the South Asian Student Association. He hopes to pursue a career in software engineering after graduating."

We will just change the student description text in the prompt.

prompt2 = f'''
Please extract the following information from the given text and return it as a JSON object:

name
major
school
grades
club

This is the body of text to extract the information from:
{student_2_description}
'''

And, run the chat completion function using the second prompt.

# Generating response back from gpt-3.5-turbo
openai_response = client.chat.completions.create(
    model = 'gpt-3.5-turbo',
    messages = [{'role': 'user', 'content': prompt_2}]
)

# Loading the response as a JSON object
json_response = json.loads(openai_response.choices[0].message.content)
json_response

As you can see, it is not consistent. Instead of returning one club, it has returned the list of clubs joined by Ravi. It is also different from the first student.

{'name': 'Ravi Patel',
 'major': 'computer science',
 'school': 'University of Michigan',
 'grades': '3.7 GPA',
 'club': ['Chess Club', 'South Asian Student Association']}

OpenAI Function Calling Example

To resolve this issue, we will now use a recently introduced feature called Function Calling. It is essential to create a custom function to add necessary information to a list of dictionaries so that the OpenAI API can understand its functionality.

  • name: write the Python function name that you have recently created.
  • description: the functionality of the function.
  • parameters: within the “properties”, we will write the name of the arguments, type, and description. It will help OpenAI API to identify the world that we are looking for.

Note: Make sure you are following the correct pattern. Learn more about function calling by reading the official documentation.

pip install --upgrade openai -q

Next, we will generate responses for two student descriptions using a custom function added to the "functions" argument. After that, we will convert the text response into a JSON object and print it.

import os
from openai import OpenAI

client = OpenAI(
  api_key=os.environ['OPENAI_API_KEY'],
)

As we can see, we got uniform output. We even got grades in numeric instead of string. Consistent output is essential for creating bug-free AI applications.

student_1_description = "David Nguyen is a sophomore majoring in computer science at Stanford University. He is Asian American and has a 3.8 GPA. David is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after graduating."

Multiple Custom Functions

You can add multiple custom functions to the chat completion function. In this section, we will see the magical capabilities of OpenAI API and how it automatically selects the correct function and returns the right arguments.

In the Python list of the dictionary, we will add another function called “extract_school_info,” which will help us extract university information from the text.

To achieve this, you have to add another dictionary of a function with name, description, and parameters.

# A simple prompt to extract information from "student_description" in a JSON format.
prompt1 = f'''
Please extract the following information from the given text and return it as a JSON object:

name
major
school
grades
club

This is the body of text to extract the information from:
{student_1_description}
'''

We will generate a “Stanford University” description using ChatGPT to test our function.

# Generating response back from gpt-3.5-turbo
openai_response = client.chat.completions.create(
    model = 'gpt-3.5-turbo',
    messages = [{'role': 'user', 'content': prompt_1}]
)

openai_response.choices[0].message.content

Create the list of student and school descriptions and pass it through the OpenAI chat completion function to generate the response. Make sure you have provided the updated custom function.

'{\n  "name": "David Nguyen",\n  "major": "computer science",\n  "school": "Stanford University",\n  "grades": "3.8 GPA",\n  "club": "Robotics Club"\n}'

The GPT-3.5-Turbo model has automatically selected the correct function for different description types. We get perfect JSON output for the student and the school.

import json

# Loading the response as a JSON object
json_response = json.loads(openai_response.choices[0].message.content)
json_response

We can even look under the name that the repose is generated using the “extract_school_info” function.

OpenAI Function Calling Tutorial: Generate Structured Output

Applications of Function Calling

In this section, we will build a stable text summarizer that will summarize the school and student information in a certain way.

First, we will create two Python functions, extract_student_info and extract_school_info, that take the arguments from function calling and return a summarized string.

pip install --upgrade openai -q
  1. Create the Python list, which consists of student one description, random prompt, and school one description. The random prompt is added to validate the automatic function calling mechanic.
  2. We will generate the response using each text in the `descriptions` list.
  3. If a function call is used, we will get the name of the function and, based on it, apply the relevant arguments to the function using the response. Otherwise, return the normal response.
  4. Print the outputs of all three samples.
import os
from openai import OpenAI

client = OpenAI(
  api_key=os.environ['OPENAI_API_KEY'],
)
  • Sample#1: The GPT model has selected “extract_student_info,” and we got a short summary about the student.
  • Sample#2: The GPT model has not selected any function and treated the prompt as a regular question, and as a result, we got the biography of Abraham Lincoln.
  • Sample#3: The GPT model has selected “extract_school_info,” and we got a short summary about Stanford University.
student_1_description = "David Nguyen is a sophomore majoring in computer science at Stanford University. He is Asian American and has a 3.8 GPA. David is known for his programming skills and is an active member of the university's Robotics Club. He hopes to pursue a career in artificial intelligence after graduating."

Conclusion

In this tutorial, we learned about OpenAI's function calling. We also learned how to use it to generate consistent outputs, create multiple functions, and build a reliable text summarizer.

If you want to learn more about the OpenAI API, consider taking the Working with OpenAI API course and using the OpenAI API in Python cheat sheet to create your first AI-powered project.

FAQs

How does OpenAI function calling handle complex nested JSON outputs?

OpenAI function calling allows you to define nested JSON structures in the function schema. By specifying the hierarchical relationships within the parameters property, you can ensure the model generates properly nested and structured JSON outputs for complex data requirements.

Can OpenAI function calling be used with external APIs or databases?

Yes, OpenAI function calling can be integrated with external APIs or databases by creating custom functions that execute API calls or database queries based on the arguments passed from the model. This enables dynamic interactions with external systems while maintaining consistent and structured responses.

What happens if the model’s function call doesn’t match any defined functions?

If the model’s function call doesn’t match a defined function or the provided schema, the function call is not triggered, and the model treats the input as a standard text-based prompt, returning a typical text-based response instead. This ensures flexibility in handling varied input types.

Earn a Top AI Certification

Demonstrate you can effectively and responsibly use AI.Get Certified, Get Hired

The above is the detailed content of OpenAI Function Calling Tutorial: Generate Structured Output. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Can't use ChatGPT! Explaining the causes and solutions that can be tested immediately [Latest 2025]Can't use ChatGPT! Explaining the causes and solutions that can be tested immediately [Latest 2025]May 14, 2025 am 05:04 AM

ChatGPT is not accessible? This article provides a variety of practical solutions! Many users may encounter problems such as inaccessibility or slow response when using ChatGPT on a daily basis. This article will guide you to solve these problems step by step based on different situations. Causes of ChatGPT's inaccessibility and preliminary troubleshooting First, we need to determine whether the problem lies in the OpenAI server side, or the user's own network or device problems. Please follow the steps below to troubleshoot: Step 1: Check the official status of OpenAI Visit the OpenAI Status page (status.openai.com) to see if the ChatGPT service is running normally. If a red or yellow alarm is displayed, it means Open

Calculating The Risk Of ASI Starts With Human MindsCalculating The Risk Of ASI Starts With Human MindsMay 14, 2025 am 05:02 AM

On 10 May 2025, MIT physicist Max Tegmark told The Guardian that AI labs should emulate Oppenheimer’s Trinity-test calculus before releasing Artificial Super-Intelligence. “My assessment is that the 'Compton constant', the probability that a race to

An easy-to-understand explanation of how to write and compose lyrics and recommended tools in ChatGPTAn easy-to-understand explanation of how to write and compose lyrics and recommended tools in ChatGPTMay 14, 2025 am 05:01 AM

AI music creation technology is changing with each passing day. This article will use AI models such as ChatGPT as an example to explain in detail how to use AI to assist music creation, and explain it with actual cases. We will introduce how to create music through SunoAI, AI jukebox on Hugging Face, and Python's Music21 library. Through these technologies, everyone can easily create original music. However, it should be noted that the copyright issue of AI-generated content cannot be ignored, and you must be cautious when using it. Let’s explore the infinite possibilities of AI in the music field together! OpenAI's latest AI agent "OpenAI Deep Research" introduces: [ChatGPT]Ope

What is ChatGPT-4? A thorough explanation of what you can do, the pricing, and the differences from GPT-3.5!What is ChatGPT-4? A thorough explanation of what you can do, the pricing, and the differences from GPT-3.5!May 14, 2025 am 05:00 AM

The emergence of ChatGPT-4 has greatly expanded the possibility of AI applications. Compared with GPT-3.5, ChatGPT-4 has significantly improved. It has powerful context comprehension capabilities and can also recognize and generate images. It is a universal AI assistant. It has shown great potential in many fields such as improving business efficiency and assisting creation. However, at the same time, we must also pay attention to the precautions in its use. This article will explain the characteristics of ChatGPT-4 in detail and introduce effective usage methods for different scenarios. The article contains skills to make full use of the latest AI technologies, please refer to it. OpenAI's latest AI agent, please click the link below for details of "OpenAI Deep Research"

Explaining how to use the ChatGPT app! Japanese support and voice conversation functionExplaining how to use the ChatGPT app! Japanese support and voice conversation functionMay 14, 2025 am 04:59 AM

ChatGPT App: Unleash your creativity with the AI ​​assistant! Beginner's Guide The ChatGPT app is an innovative AI assistant that handles a wide range of tasks, including writing, translation, and question answering. It is a tool with endless possibilities that is useful for creative activities and information gathering. In this article, we will explain in an easy-to-understand way for beginners, from how to install the ChatGPT smartphone app, to the features unique to apps such as voice input functions and plugins, as well as the points to keep in mind when using the app. We'll also be taking a closer look at plugin restrictions and device-to-device configuration synchronization

How do I use the Chinese version of ChatGPT? Explanation of registration procedures and feesHow do I use the Chinese version of ChatGPT? Explanation of registration procedures and feesMay 14, 2025 am 04:56 AM

ChatGPT Chinese version: Unlock new experience of Chinese AI dialogue ChatGPT is popular all over the world, did you know it also offers a Chinese version? This powerful AI tool not only supports daily conversations, but also handles professional content and is compatible with Simplified and Traditional Chinese. Whether it is a user in China or a friend who is learning Chinese, you can benefit from it. This article will introduce in detail how to use ChatGPT Chinese version, including account settings, Chinese prompt word input, filter use, and selection of different packages, and analyze potential risks and response strategies. In addition, we will also compare ChatGPT Chinese version with other Chinese AI tools to help you better understand its advantages and application scenarios. OpenAI's latest AI intelligence

5 AI Agent Myths You Need To Stop Believing Now5 AI Agent Myths You Need To Stop Believing NowMay 14, 2025 am 04:54 AM

These can be thought of as the next leap forward in the field of generative AI, which gave us ChatGPT and other large-language-model chatbots. Rather than simply answering questions or generating information, they can take action on our behalf, inter

An easy-to-understand explanation of the illegality of creating and managing multiple accounts using ChatGPTAn easy-to-understand explanation of the illegality of creating and managing multiple accounts using ChatGPTMay 14, 2025 am 04:50 AM

Efficient multiple account management techniques using ChatGPT | A thorough explanation of how to use business and private life! ChatGPT is used in a variety of situations, but some people may be worried about managing multiple accounts. This article will explain in detail how to create multiple accounts for ChatGPT, what to do when using it, and how to operate it safely and efficiently. We also cover important points such as the difference in business and private use, and complying with OpenAI's terms of use, and provide a guide to help you safely utilize multiple accounts. OpenAI

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor