liveBook · Manning

OpenAI API SDK

As explained in Build Python Web Apps with Streamlit

The OpenAI Python module is a client library for accessing OpenAI APIs from Python programs.

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

How Build Python Web Apps with Streamlit covers it

How deep it goes
Explains installation, client creation, message roles, requests, and response extraction; stops short of implementing other endpoints.
Examples
Uses a Streamlit explanation prompt and an Llm wrapper class with an ask method.
What it assumes
Assumes basic Python use and access to an OpenAI API key.
What you can do after
Apply it via the OpenAI Python library to send conversational prompts and retrieve generated text.
How it connects
Connects Python, API keys, prompts, message roles, chat completions, models, and large language models.

Also explained in

Compare how 2 books explain OpenAI API SDK →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Python Web Apps with Streamlit. The section links point to the parts of the book it draws on.