How to beginner · 3 min read

How to send a chat request with openai python

Quick answer
Use the OpenAI Python SDK v1 by importing OpenAI, initializing the client with your API key from os.environ, and calling client.chat.completions.create with the desired model and messages. Extract the response text from response.choices[0].message.content.

PREREQUISITES

  • Python 3.8+
  • OpenAI API key (free tier works)
  • pip install openai>=1.0

Setup

Install the official OpenAI Python SDK version 1 or higher and set your API key as an environment variable for secure access.

bash
pip install openai>=1.0

Step by step

This example shows how to send a chat request to the gpt-4o model using the OpenAI Python SDK v1. It prints the assistant's reply.

python
import os
from openai import OpenAI

client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello, how are you?"}]
)

print(response.choices[0].message.content)
output
Hello! I'm doing great, thank you. How can I assist you today?

Common variations

  • Use different models like gpt-4o-mini for faster responses.
  • Send multiple messages in the conversation history.
  • Use async calls with asyncio and await for concurrency.
python
import os
import asyncio
from openai import OpenAI

async def async_chat():
    client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
    response = await client.chat.completions.acreate(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": "Tell me a joke."}]
    )
    print(response.choices[0].message.content)

asyncio.run(async_chat())
output
Why don't scientists trust atoms? Because they make up everything!

Troubleshooting

  • If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly.
  • For rate limit errors, reduce request frequency or upgrade your plan.
  • Check network connectivity if requests time out.

Key Takeaways

  • Always use the OpenAI Python SDK v1 with OpenAI client and environment variables for API keys.
  • Call client.chat.completions.create with the correct model and message format to send chat requests.
  • Use async methods for scalable applications requiring concurrency.
  • Handle common errors by verifying API keys and managing rate limits.
  • Model names and SDK patterns may evolve; check official docs regularly.
Verified 2026-04 · gpt-4o, gpt-4o-mini
Verify ↗