Appendix C. Using the OpenAI API
Starting in Chapter 5, the book moves from chatting with an AI companion in a browser to calling the OpenAI API directly from Python. This appendix is a consolidated reference for the API patterns used from Chapter 5 through Chapter 12: making a call, choosing a model, getting structured data back, managing tokens and cost, and handling errors. For account creation, key generation, and SDK installation, see Appendix A.
This book uses the OpenAI Python SDK v1.0.0 or newer. If online examples you find use openai.ChatCompletion.create(), they are written for the old v0.x SDK and will not run against the code here.
C.1 The basic call
Every API interaction follows the same shape: import the library, make sure your key is available, and call the chat completions endpoint with a list of messages.
import os
import openai
openai.api_key = os.getenv("OPENAI_API_KEY")
response = openai.chat.completions.create(
model="gpt-4o",
messages=[
{"role": "user", "content": "Summarize what a data pipeline is."}
],
)
print(response.choices[0].message.content)
A few things to note:
- The key is read from the environment, never hardcoded (Appendix A). The client picks up OPENAI_API_KEY automatically, so setting openai.api_key is belt-and-suspenders.
- messages is a list, not a single string. That list is the whole conversation.
- The text you want is at response.choices[0].message.content.