Basics¶
Let's start with a simple example to query the OpenAI API. All the other more complex examples will be based on this one.
Setup¶
Install the dependencies and configure your API key.
On Google Colab, store your key in Colab Secrets first: click the key icon in the left sidebar, add a secret named OPENAI_API_KEY, and enable notebook access. Running locally, put the key in a .env file or in the OPENAI_API_KEY environment variable (see handling API keys).
%pip install -q openai python-dotenv
import os
from dotenv import load_dotenv
load_dotenv() # loads a .env file from the working directory, if there is one
if "OPENAI_API_KEY" not in os.environ:
try:
# On Google Colab, read the key from Colab Secrets
from google.colab import userdata
os.environ["OPENAI_API_KEY"] = userdata.get("OPENAI_API_KEY")
except ImportError:
raise RuntimeError("Set OPENAI_API_KEY in your environment or in a .env file")
Example on sentiment analysis¶
Considering the following sentiment analysis tasks. We have some text messages and we want to know if it is positive or negative. One way to do this is to ask ChatGPT to produce binary labels. But to get the nuanced results, we can let it generate a score in the range of -1 to 1, where -1 means negative and 1 means positive. Here is the code
from openai import OpenAI
text_message = "The service here is very good!"
system_prompt = "You are an expert on sentiment analysis. Your job is to evaluate the sentiment of the given text message."
user_instruction = f"Given the following text message: '{text_message}', please evaluate its sentiment by giving a score in the range of -1 to 1, where -1 means negative and 1 means positive. Also explain why."
client = OpenAI()
response = client.responses.create(
model="gpt-5.6-luna",
instructions=system_prompt,
input=user_instruction,
)
print(response.output_text)
Sentiment score: **0.9** The message expresses strong positive sentiment, praising the service as “very good.”
We use gpt-5.6-luna throughout this tutorial. It is a small, low-cost OpenAI model ($0.20 per 1M input tokens, $1.20 per 1M output tokens) that works well for large-scale text processing.
Note that the response might be different every time you run it. GPT-5.6 models are reasoning models and do not accept the temperature parameter (passing it returns an error), so there is no way to make the output deterministic. What you can control is how much reasoning the model does, through the reasoning parameter, for example reasoning={"effort": "none"} for faster and cheaper responses.
Next steps¶
The script above is very simple and effective. But in computational social science research, we often have tens of thousands of text messages to process. And using the simple script above becomes difficult for a couple of reasons:
- The output is in plain text. Although it's easy for human to extract the key information, dealing with it using programs is difficult.
- Running the script to process your text messages one by one can be slow.
To deal with issue 1, we can leverage the structured output of OpenAI's API to specify the output format. See structured output for details.
For issue 2, there are two options:
- If you need the results immediately, you can consider using the async programming to accelerate the querying process. See async programming for details.
- If you are not in a rush, you can use the batch API to process large amounts of data with reduced cost. See batch processing for details.
Personally, I prefer the second option because it can significantly reduce the cost and doesn't need to deal with the async programming. However, not every provider supports batch API.