Structuring an API call

Developing AI Systems with the OpenAI API

Francesca Donadoni

Curriculum Manager, DataCamp

Progress Snapshot

A black and white logo with the words "opal library" written on it

Developing AI Systems with the OpenAI API

Progress Snapshot

A diagram listing the OpenAI library with logo, and API call with an API icon

Developing AI Systems with the OpenAI API

Progress Snapshot

A diagram listing the OpenAI library with logo, a generic API call with an API icon, and a response message with its icon

Developing AI Systems with the OpenAI API

Progress Snapshot

from openai import OpenAI
client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "user", "content": "Who developed ChatGPT?"} ] )
print(response.choices[0].message.content)
ChatGPT was developed by OpenAI, an artificial intelligence research lab.
Developing AI Systems with the OpenAI API

Challenges of a production environment

  Two individuals studying a map with a compass, planning their route

  A mobile phone showing a map application using GPS

Developing AI Systems with the OpenAI API

Challenges of a production environment

 

  • Error Handling
    • Displaying user-friendly error messages
    • Alternatives for when the service is unavailable

 

  • Moderation and Safety
    • Control unwanted inputs
    • Minimizing the risk of data leaks

 

  • Testing and Validation
    • Checking for responses that are out of topic
    • Testing for inconsistent behavior

 

  • Communication with External Systems
    • Calling external functions and APIs
    • Optimizing response times
Developing AI Systems with the OpenAI API

Components of an OpenAI API request

from openai import OpenAI

client = OpenAI(api_key="ENTER YOUR KEY HERE")

response = client.chat.completions.create(
  model="gpt-4o-mini",

messages=[ {"role": "user", "content": "Please write down five trees with their scientific names in json format."} ],
response_format={"type": "json_object"}
)
Developing AI Systems with the OpenAI API

Components of an OpenAI API response

 

print(response.choices[0].message.content)
{
  "trees": [
    {"commonName": "Oak", "scientificName": "Quercus"},
    {"commonName": "Maple", "scientificName": "Acer"},
    {"commonName": "Pine", "scientificName": "Pinus"},
    {"commonName": "Birch", "scientificName": "Betula"},
    {"commonName": "Willow", "scientificName": "Salix"}
  ]
}
Developing AI Systems with the OpenAI API

What's next

 

  • Integration in production
  • Calling external functions
  • Best practices

A person with a backpack and a map pointing to a destination

Developing AI Systems with the OpenAI API

Let's practice!

Developing AI Systems with the OpenAI API

Preparing Video For Download...