Overview

Appendix C. Using the OpenAI API

The appendix serves as a practical reference for moving from browser-based prompting to direct OpenAI API use in Python. It focuses on the patterns used throughout the book: sending a request, selecting an appropriate model, receiving structured results, estimating token usage, controlling cost, and recovering from errors. It also clarifies that the examples assume the newer Python SDK, so older code written for the v0.x interface will not work without changes.

At the core of API usage is a simple chat-completions call built from a conversation list, usually with a system message that sets rules and a user message that supplies the current record or question. The appendix emphasizes separating persistent instructions from per-item input because that makes one prompt reusable across many records in pipeline workflows. It also explains model choice as a tradeoff between capability and cost: use the more capable model for difficult reasoning or extraction tasks, and the cheaper model for high-volume, simpler steps.

A major theme is structured output, where a Pydantic schema defines the exact data shape expected from the model so the reply can be validated and returned as a ready-to-use object rather than free text. The appendix also highlights that token counts drive pricing, so reducing input size and choosing cheaper models are the most effective ways to control spending. Finally, it recommends wrapping API calls in retry logic with exponential backoff for transient failures, while avoiding retries for errors caused by bad inputs, and it provides a quick map of the main syntax differences between the old and current SDK styles.

FAQ

How do I make a basic OpenAI API call in Python?Use the OpenAI Python SDK, set your API key from the environment, and call openai.chat.completions.create() with a model and a list of messages. The result text is typically found at response.choices[0].message.content.
What is the difference between system and user messages?system messages set the rules, behavior, and instructions for the whole conversation. user messages contain the actual question or input data for that turn.
Which OpenAI models does the book use, and when should I choose each one?The book mainly uses gpt-4o for harder reasoning tasks like messy field extraction, and gpt-4o-mini for cheaper, high-volume tasks like ranking, classification, and triage. The general rule is to use the cheapest model that still does the job.
How do I get structured output instead of free-form text?Use openai.beta.chat.completions.parse() with a Pydantic model passed as response_format. The API validates the output against your schema and returns a parsed object instead of raw text.
Why does the book use Pydantic models for extraction tasks?Pydantic models define the exact shape of the data you want back, which makes outputs more reliable and easier to use in code. Field descriptions also help guide the model, reducing how much prompt text you need.
When should I make a field Optional in a structured output schema?Make a field optional when real-world data might be missing it. If you require a field that is often absent, the model may fail or invent a value.
How does token usage affect API cost?OpenAI charges by token for both input and output. Since cost adds up across large batches, estimating token use before a run is important for pipeline work.
How can I estimate input tokens before sending text to the API?You can use tiktoken and encoding_for_model() to count the tokens in your text. This helps you estimate cost and reduce oversized inputs before making API calls.
What are the best ways to reduce OpenAI API cost?The two biggest levers are sending less text and using a cheaper model when possible. Cleaning input aggressively and reserving expensive models for only the hardest step can significantly lower cost.
How should I handle API errors and retries?Catch openai.OpenAIError, retry only failures that are worth retrying, and use exponential backoff so you do not overwhelm a rate-limited endpoint. Do not retry requests that fail because the input itself is bad.

pro $24.99 per month

  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose one free eBook per month to keep
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime

lite $19.99 per month

  • access to all Manning books, including MEAPs!

team

5, 10 or 20 seats+ for your team - learn more


choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn AI Data Engineering ebook for free
choose your plan

team

monthly
annual
$49.99
$499.99
only $41.67 per month
  • five seats for your team
  • access to all Manning books, MEAPs, liveVideos, liveProjects, and audiobooks!
  • choose another free product every time you renew
  • choose twelve free products per year
  • exclusive 50% discount on all purchases
  • renews monthly, pause or cancel renewal anytime
  • renews annually, pause or cancel renewal anytime
  • Learn AI Data Engineering ebook for free