Skip to main content

Getting Started with the OpenAI Python SDK

Useful Resources


Architecture

What You'll Learn

In this quickstart guide, you'll build a simple Python script that interacts with OpenAI's API. You’ll learn how to:

  • Authenticate using your API key
  • Send a prompt to a language model
  • Display the response in your terminal

Prerequisites

pip install openai
  • Setting up Environment Variable for OPENAI_API_KEY in Google Collab
%env OPENAI_API_KEY=sk-proj-gjH6z74SeS7nhChI1o8afV0Gcqj3TqnOn1dK4A

Example Script

Here’s a basic script to send a prompt and receive a response:

from openai import OpenAI

client = OpenAI()

response = client.responses.create(
model="gpt-4.1-nano",
input=input("Enter your prompt: ")
)

print(response.output_text)

How It Works

  • from openai import OpenAI: Imports the OpenAI SDK.
  • OpenAI(api_key=...): Authenticates the client using your API key.
  • client.responses.create(...): Sends a request using the specified model.
  • input(...): Captures user input from the terminal.
  • print(...): Outputs the model's reply to the console.
Keep Your API Key Secure

Never expose your API key in public code or repositories. Use environment variables or secure key management solutions to store it safely.