Lesson Introduction

Welcome! Today, you'll learn how to make your first request to the OpenAI Completions API using Python. This is the groundwork for learning more advanced techniques for building AI assistants, which we'll explore further in this course path. In this lesson, you'll discover how to send a prompt, get a response, and handle basic errors — essential skills for developing your own AI agents. By mastering these basics, you'll be prepared to tackle more complex assistant behaviors and applications as you progress through the course.

Setting Up the Environment and Error Handling

To use the OpenAI API, set up your Python environment with the openai library:

from openai import OpenAI, OpenAIError
  • OpenAI is the client for sending requests.
  • OpenAIError helps handle API errors.

Your API key should be set as the OPENAI_API_KEY environment variable. This key is required for authentication.

Error handling is important. If something goes wrong — such as a network issue or a bad key — your program should handle it gracefully. You'll see how to do this with try and except blocks in the examples.

Constructing and Sending a Request

To interact with the API, send a request with a prompt. For chat models, the prompt is a list of messages, each with a role and content.

Each message has a role that determines its purpose in the conversation:

  • "system": Sets instructions or context for the assistant (e.g., "You are a helpful assistant.").
  • "user": Represents input from the end user (e.g., a question or command).
  • "assistant": Represents responses from the AI assistant.

Typically, you start with a "system" message to guide the assistant’s behavior, followed by "user" messages for user input, and the API generates the next "assistant" message as a response.

Here’s a basic example:

from openai import OpenAI

client = OpenAI()
messages = [
    {"role": "user", "content": "What is the capital of France?"}
]
completion = client.chat.completions.create(
    model="gpt-4o",
    messages=messages,
    max_tokens=50
)
print(completion.choices[0].message.content.strip())  # Paris is the capital of France.

Key parts:

  • model: Which AI model to use, e.g., "gpt-4o".
  • messages: List of conversation messages. The user's message is the prompt.
  • max_tokens: Limits the response length. One token is about four characters or a word.

Think of this as sending a question to a smart assistant and waiting for its answer.

Handling and Interpreting the Response

The API returns a response object. The main field is choices, a list of possible completions.

To print the response:

if completion and hasattr(completion, "choices") and len(completion.choices) > 0:
    print("Completion:", completion.choices[0].message.content.strip())  # Completion: Paris is the capital of France.
else:
    print("No completion returned.")  # No completion returned.
  • completion.choices[0].message.content is the generated text.
  • strip() removes extra whitespace.

Always check that a completion exists before accessing it to avoid errors.

Error Handling in Practice

Error handling is also key:

import sys
from openai import OpenAI, OpenAIError

try:
    # ... (send request as above)
except OpenAIError as oe:
    print(f"OpenAI API Error: {oe}", file=sys.stderr)  # OpenAI API Error: <error message>
    sys.exit(2)
except Exception as e:
    print(f"Error: {e}", file=sys.stderr)  # Error: <error message>
    sys.exit(3)
  • OpenAIError catches API-specific issues.
  • The general Exception block catches other errors, such as network problems.

This ensures your program gives useful feedback and exits cleanly if something fails.

Lesson Summary and Practice Introduction

You’ve learned how to send your first prompt to the OpenAI Completions API using Python. You now know how to set up your environment, build a request, read the response, and handle errors. These are the basics for building AI-powered applications.

Next, you’ll move to hands-on practice. You’ll send your own prompts and explore different responses, reinforcing what you’ve learned and preparing for more advanced AI agent development.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal