The most surprising thing about the OpenAI API is how little boilerplate code you actually need to get started.
Let’s make a call.
First, you’ll need an API key. Grab one from your OpenAI account settings. Then, install the openai Python library:
pip install openai
Now, you can write your first script. This example uses the ChatCompletion endpoint to ask a simple question.
import openai
# Set your API key here
openai.api_key = "YOUR_API_KEY"
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response.choices[0].message.content)
Replace "YOUR_API_KEY" with your actual key. Running this script will output:
The capital of France is Paris.
This might seem straightforward, but there’s a lot happening under the hood. The openai.ChatCompletion.create function is the core of interacting with the chat models.
The model parameter specifies which AI model to use. "gpt-3.5-turbo" is a fast and capable model, good for many general tasks. Other models, like "gpt-4", offer more advanced reasoning but are slower and more expensive.
The messages parameter is a list of message objects. Each object has a role (either "system", "user", or "assistant") and content (the text of the message).
- The
"system"message sets the behavior of the assistant. It’s like giving instructions to an AI before a conversation starts. - The
"user"message is what you, the user, say. - The
"assistant"role is used for the AI’s responses, which you can include in subsequent calls to maintain conversation history.
The response object contains the AI’s answer. response.choices is a list of possible completions, and we’re taking the first one ([0]). Inside that, message.content holds the actual text generated by the model.
The mental model to hold onto is that you’re not just sending a prompt; you’re constructing a conversation. Even for a single question, the API expects a list of messages. This structure allows for multi-turn dialogues where the AI remembers previous exchanges. You can build complex interactions by simply appending your messages and the AI’s previous responses to this list for each new API call.
The temperature parameter, which you can add to the create call, controls randomness. A higher temperature (e.g., 0.8) makes the output more diverse and creative, while a lower temperature (e.g., 0.2) makes it more focused and deterministic.
The next step is to explore how to manage conversation history effectively and implement more complex prompts using the messages array.