Chat completion is a programmable API call that sends a sequence of conversational messages to an OpenAI language model and returns an assistant response. Treat it as a pipeline function: define the task, supply context and parameters, then consume the result in Python rather than relying on a chat interface. section 5.3 section 5.3.1
A request combines a few practical controls:
- Use a system message to set overall behavior, a user message to provide the task, and an assistant message to represent a model response. section 5.3.1
- Select a model, cap output with max_tokens, and tune response randomness with temperature. section 5.3.1
- Keep the API key in an environment file and load it into the Python application rather than placing it in the prompt. section 5.3.1
- Account for token-based cost: both prompt input and generated output contribute to usage. section 5.3.1
Listing 5.3 Sample Prompt and Response Functionality
import openai #A
import os #B
from dotenv import load_dotenv
load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY") #C
prompt = "How are you today?" #D
response = openai.chat.completions.create( #E
model="gpt-4o", #F
messages=[ #G
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": prompt}
],
max_tokens=100, #H
temperature=0.5 #I
)
print(response) #J
The listing shows a minimal Python request: load an API key, create system and user messages, call chat.completions.create, and set model, max_tokens, and temperature. section 5.3.1
Sentiment enrichment in a data pipeline
For each article, build a prompt asking for positive, negative, or neutral sentiment, send it as a user message, and use the returned answer to enrich the article. Start with plain-text responses, then refine prompts and add structured formatting or JSON schemas when downstream code needs predictable fields. section 5.3 section 5.5
Chat completion can also express data-quality expectations in plain language: detect invalid values, standardize formats, map categories, or remove unwanted fields. For cleanup workflows, move beyond free-form output by using response formats and data classes, then process records in bounded calls instead of sending an entire dataset at once. section 6.0 section 6.2 section 6.4
Generated results remain part of a controlled workflow. Verify that requested values are numeric and well formed, aggregate or inspect outputs, and keep conventional Python transformations available for comparison or validation. section 5.5 section 6.4

