The OpenAI Python module provides a convenient client for calling OpenAI APIs from Python programs. Install it with pip, create an OpenAI client with an API key, and send structured messages to an endpoint. section 9.2.3
A basic request follows these steps:
- Import OpenAI and instantiate the client with an API key. section 9.2.3
- Build messages with system, user, or assistant roles; system sets context, while user supplies the instruction. section 9.2.3
- Call the chat completions endpoint with a model and messages, then read the returned response content. section 9.2.3
Request a short explanation
Create a system message asking for helpful programming assistance and a user message such as “Explain what Streamlit is in 10 words or fewer.” Send both messages with model="gpt-5.1" and read completion.choices[0].message.content. section 9.2.3
Listing 9.1 Creating the Llm class in llm.py
from openai import OpenAI
class Llm:
def __init__(self, api_key):
self.client = OpenAI(api_key=api_key)
@staticmethod
def construct_messages(user_msg, sys_msg=None):
messages = []
if sys_msg:
messages.append({"role": "system", "content": sys_msg})
messages.append({"role": "user", "content": user_msg})
return messages
def ask(self, user_msg, sys_msg=None):
messages = self.construct_messages(user_msg, sys_msg)
completion = self.client.chat.completions.create(
model="gpt-5.1",
messages=messages
)
return completion.choices[0].message.content
Encapsulate the OpenAI client in an Llm class so application code can ask questions without handling message construction or API logistics directly. section 9.2.4

