Overview

5 Using the OpenAI API in Data Workflows

The chapter introduces a key shift in how AI is used in data engineering: rather than relying on an external coding assistant, the model is embedded directly inside the data workflow as a working component. Using a practical sentiment analysis example, it shows how AI can function like any other transformation step in a pipeline, enriching incoming text data and passing the results onward to tools such as pandas, machine learning workflows, databases, or dashboards. The main idea is that AI is no longer just a helper for writing code, but a native part of the data stack.

To build this workflow, the chapter walks through a simple end-to-end pipeline that starts with live article extraction from NewsAPI, then cleans and combines article fields into a usable text column, and finally sends that content to OpenAI’s Chat Completions API for sentiment analysis. It emphasizes secure API key handling with environment variables, explains the basic structure of OpenAI requests and responses, and demonstrates how prompt design affects the usefulness of the output. The first version returns verbose explanations, but the chapter quickly moves toward more practical prompting so the model produces concise sentiment labels suitable for downstream use.

As the workflow matures, the focus shifts to making AI output more reliable and pipeline-friendly. The chapter highlights the need to normalize responses into consistent categories such as positive, neutral, or negative, and to log results while processing multiple articles into an enriched DataFrame. It also cautions about cost management, model inconsistency, and the limits of sentiment analysis when dealing with sarcasm, nuance, or subjective interpretation. Overall, the chapter frames OpenAI as a composable data tool and encourages careful prompt engineering, structured outputs, and iterative testing to make AI practical in real-world data workflows.

In earlier chapters, the data engineer acted as a go-between—manually passing instructions between an AI coding companion and the coding environment. Now, the AI component is embedded directly within the workflow, alongside libraries like Requests and Pandas, enabling natural language tasks (like sentiment analysis) to execute as native steps within the Jupyter notebook
This diagram illustrates the full mental model for the use case. Articles are fetched from the NewsAPI using the requests library, then preprocessed into clean content blocks. The OpenAI API is embedded within the Python environment to analyze sentiment, returning structured labels. Finally, results are stored in a pandas DataFrame and logged—ready for downstream use in tools like scikit-learn, PostgreSQL, or Tableau.
This figure shows the results of the full AI-powered sentiment pipeline. The top portion displays logging output for each step, including API requests and processed sentiment labels. The bottom shows the final pandas DataFrame, where each article title is paired with a normalized sentiment category. Results will vary over time, as the input depends on live Tesla news retrieved from NewsAPI.
Example of what output by sentiment score should look like.
Example of what aggregation results may look like.

FAQ

What is the main goal of embedding the OpenAI API into a data workflow?To make AI a native part of the pipeline, so it can enrich, transform, and analyze data directly inside the workflow rather than only being used as an external assistant.
Why is sentiment analysis used as the example in this chapter?Sentiment analysis is a clear, practical example of how AI can classify text in a pipeline, and it has real-world use cases such as customer feedback analysis, social media monitoring, and market research.
What does NewsAPI do in this workflow?NewsAPI is used to fetch live news articles from many sources so the pipeline has fresh text data to preprocess and enrich with sentiment labels.
Which NewsAPI endpoint is used to retrieve articles, and why?The /v2/everything endpoint is used because it searches across a large archive of articles and supports filters like keywords, dates, language, and sort order.
Why should API keys be managed with environment variables instead of hardcoded in scripts?Using environment variables or a secrets manager keeps keys more secure and avoids exposing credentials directly in code.
What does the preprocessing step do before sending articles to OpenAI?It combines the article title, description, and content into a single clean text block and stores the result in a pandas DataFrame for analysis.
How is the OpenAI Chat Completions API used in this chapter?A prompt is sent along with system and user messages, and the model returns a response that can be used to analyze article sentiment programmatically.
Why is it important to normalize the sentiment output?Normalized outputs like “Positive,” “Neutral,” or “Negative” are easier to store, filter, analyze, and use in downstream systems than long free-form explanations.
How is the raw API response cleaned for use in the pipeline?The code extracts the model’s message content with response.choices[0].message.content.strip() so only the sentiment result is kept, not the extra metadata.
What should you watch out for when using AI for sentiment analysis at scale?AI sentiment can be inconsistent or misread sarcasm and nuance, and costs can add up quickly, so prompts should be precise and usage should be monitored carefully.

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