How do I call the OpenAI API using Python?

Asked 15 hours ago Updated 14 hours ago 31 views

1 Answer


0

OpenAI provides an official Python SDK that lets you use its models in your own applications with just a few lines of code. Here is a simple path to your first working request.

Step 1: Create an API key. Sign in to the OpenAI developer platform at platform.openai.com, set up billing and create an API key in the API keys section. Copy it immediately and store it securely. Note that a ChatGPT subscription does not include API usage; API billing is separate.

Step 2: Set the key as an environment variable named OPENAI_API_KEY. Keep it out of your code and out of version control.

Step 3: Install the SDK. Run: pip install openai

Step 4: Make your first request. OpenAI's current recommended interface is the Responses API. A basic call looks like:

from openai import OpenAI
client = OpenAI()
response = client.responses.create(model="MODEL_NAME", input="Write a one-line tagline for a bakery in Lucknow.")
print(response.output_text)

Replace MODEL_NAME with a current model from OpenAI's models documentation. The client reads your API key from the environment variable automatically.

You may also see older examples using the Chat Completions API, with client.chat.completions.create and a list of messages. It is still widely used and supported, and many tutorials and other providers follow its format. For new projects, check OpenAI's documentation for current recommendations.

Key concepts:

Instructions: you can provide system-level instructions to shape the model's behaviour.
Conversation state: for multi-turn chats, you either send previous messages or use the API's features for continuing a conversation.
Tokens: you pay for input and output tokens, with different prices per model.
Usage: responses include token counts for tracking costs.

Features to explore next:

1. Streaming responses for a faster user experience.
2. Function calling, so the model can use your tools.
3. Built-in tools, such as web search and file search, available in the Responses API.
4. Structured outputs for reliable JSON.
5. Image inputs and image generation.
6. The Batch API for cheaper bulk processing.

Good practices:

Set usage limits in the dashboard while learning.
Handle errors and rate limits with retries.
Validate outputs before your code acts on them.
Keep API calls on your server, never in client-side code.

The OpenAI documentation and cookbook contain many examples to build on once your first request works.

Write Your Answer