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.
To use the OpenAI API, set up your Python environment with the openai library:
OpenAIis the client for sending requests.OpenAIErrorhelps 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.
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:
Key parts:
model: Which AI model to use, e.g.,"gpt-4o".messages: List of conversation messages. The user's message is the prompt.
The API returns a response object. The main field is choices, a list of possible completions.
To print the response:
completion.choices[0].message.contentis the generated text.strip()removes extra whitespace.
Always check that a completion exists before accessing it to avoid errors.
Error handling is also key:
OpenAIErrorcatches API-specific issues.- The general
Exceptionblock catches other errors, such as network problems.
This ensures your program gives useful feedback and exits cleanly if something fails.
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.
