---
title: "How to Use OpenAI’s API with LangChain: Setup, Environment Variables, and First Model Call"
description: "Set up the OpenAI API with LangChain: get your API key, use a .env file, load environment variables, and run your first model call in Python."
image: https://blog.rheinwerk-computing.com/hubfs/How%20to%20Use%20OpenAI%E2%80%99s%20API%20with%20LangChain_%20Setup%2c%20Environment%20Variables%2c%20and%20First%20Model%20Call.jpg
---

[![Rheinwerk Computing Logo](https://blog.rheinwerk-computing.com/hubfs/computing_logo-header.svg)](https://blog.rheinwerk-computing.com/) [Blog](https://blog.rheinwerk-computing.com)

- Books 
    - Get an overview of our wide selection of books on every relevant computing topic. 
          - [General Computing](https://www.sap-press.com/rheinwerk-computing/general-computing/)
          - [DevOps](https://www.sap-press.com/rheinwerk-computing/devops/)
          - [Programming Languages](https://www.sap-press.com/rheinwerk-computing/programming-languages/)
          - [Security](https://www.sap-press.com/rheinwerk-computing/security/)
          - [Software Development](https://www.sap-press.com/rheinwerk-computing/software-development/)
- Book Subscription 
    - Get unlimited access to all Rheinwerk Computing books! 
          - [Programming Subscription](https://sap-press.com/subscriptions/)

[Python](https://blog.rheinwerk-computing.com/tag/python)

# How to Use OpenAI’s API with LangChain: Setup, Environment Variables, and First Model Call

![Rheinwerk Computing](https://blog.rheinwerk-computing.com/hubfs/RW-logo-300x300.png)  by [Rheinwerk Computing](https://blog.rheinwerk-computing.com/author/rheinwerk-computing) on August 13, 2025

Want to integrate OpenAI’s powerful language models into your application? Whether you’re building with LangChain or experimenting with GPT-4o, the first step is securing and managing your API key.

 

This post walks you through how to get your OpenAI API key, store it securely using environment variables, and make your first model call in[ Python](https://learning.rheinwerk-computing.com/python)with LangChain. Let’s get your environment set up and your first prompt running in minutes.

 

## Getting Started with the OpenAI API

To use OpenAI you need to have an application programming interface (API) key. These models are not free, so you’ll be charged for your usage. Prices are dropping permanently over time, and you can [check the current pricing here](https://openai.com/api/pricing/)*.*

### What Is an API Key and Why Do You Need One?

First, you must set up an API key. To use a web service, you usually only need a username and password to access the service. To use a service programmatically, you require an API key, which makes an API key something like a combination of username and password.

### How to Get an OpenAI API Key

If you don’t have one yet, get an API key by following these steps:

1. Head over to [https://platform.openai.com/](https://platform.openai.com/).
2. Create an account.
3. Activate billing and load some money onto your account.
4. Navigate to API keys and create a new API key. The name you specify in the web frontend is irrelevant, you only need the key. Copy the key into the clipboard.
5. Paste this key into a file called the *.env*  The key should look like sk-proj...

### Best Practice: Use a .env File for Credentials

A best practice is to separate the code from the credentials. Thus, store the API key in a separate file. A common approach is to store this information in a file called *.env* and place it in the working folder. In that file, you could store the API key and possibly many more keys if needed. This listing shows what an environment file should look like.

 

`OPENAI_API_KEY = sk-proj...`

API keys are treated as *environment variables*, which are typically variables that are used by your operating system. Our variable has the name OPENAI\_API\_KEY and its value must be defined to the right of the equal sign. Make sure you use the same key name in the coding script.

 

Let’s now start coding. You can find the required material in the file *03\_LLMs/10\_model\_ chat.py* at [this webpage](https://www.sap-press.com/generative-ai-with-python_6057/) (click "Supplements list" to download). A best practice is to place all the required packages and functions at the beginning of the file. Let’s go through what we need next.

 

## Leading Environment Variables in Python

The os package is required for fetching and loading the environment variables. All major model providers offer packages for integration into LangChain. Thus, as shown in the listing below, use langchain\_openai. The package dotenv is required for working with the environment variables file. Its function load\_dotenv() loads the content of the *.env* file and provides the content as environment variables.

### Required Packages

These are the packages you’ll need:

 

`#%% packages`

`import os`

`from langchain_openai import ChatOpenAI`

`from dotenv import load_dotenv`

`load_dotenv('.env')`

### Loading the API Key from the .env File

Check that the API key is available by running os.getenv('OPENAI\_API\_KEY'). As a result, you should see the API key printed on the screen.

 

## Creating and Using a LangChain Model

Now we create an instance of the model we’ll use by using ChatOpenAI class. This requires a model name. We choose GPT 4o Mini here. Another important parameter is the temperature. This parameter controls the creativity of the model. And you need to pass the API key to authenticate and enabling OpenAI to charge you based on your usage.

 

`MODEL_NAME = 'gpt-4o-mini'`

`model = ChatOpenAI(model_name=MODEL_NAME,``                                                    temperature=0.5, # controls creativity`*                                                                          api\_key*=os.getenv('OPENAI\_API\_KEY'))

### Run a Model Prompt with invoke()

The model object’s invoke() method is particularly important, as shown in the listing below. This method allows you to run the model based on specified parameters. In our first example, we asked the model to provide information on “What is LangChain?” The result is stored in an object of type AIMessage. You can access the information received from the model call by looking at the output of its dict() method.

 

`res = model.invoke("What is a LangChain?")`

`res.dict()`

`{'content': 'LangChain is ...',`

`'additional_kwargs': {},`

`'response_metadata': {'token_usage': {'completion_tokens': 312,`

` 'prompt_tokens': 13,`

` 'total_tokens': 325},`

`'model_name': 'gpt-4o-mini-2024-07-18',`

`'system_fingerprint': 'fp_f33667828e',`

`'finish_reason': 'stop',`

`'logprobs': None},`

`'type': 'ai',`

`'name': None,`

`'id': 'run-929cb722-e48e-457b-859c-754a5d272c6d-0',`

`'example': False,`

`'tool_calls': [],`

`'invalid_tool_calls': [],`

`'usage_metadata': {'input_tokens': 13,`

` 'output_tokens': 312,`

` 'total_tokens': 325}}`

### Understanding the Response Object

Plenty of information is coming back from the model. Let’s start with the most important part: content. This property holds the actual model output prompt. Out of the other properties, we just want to mention response\_metadata, which holds information on token usage. You’re charged in terms of input tokens and output tokens. In this property, you can determine how many tokens were used in the request.

 

## Exploring the OpenAI Model Family

Familiarize yourself with the different models from OpenAI’s model family by studying the [model overview at this page](https://platform.openai.com/docs/models/overview). Some key features include the following:

- OpenAI created a model family ([https://platform.openai.com/docs/models](https://platform.openai.com/docs/models)) consisting of several models suitable for different tasks.
- Language models like the GPT family (e.g., GPT-4o) can process text, and some can also work with images.
- Text-to-image generation: DALL-E is a model that can generate and edit images.
- Text-to-speech (TTS): Several models can convert text to natural, spoken audio.
- Speech-to-text: With Whisper, you can convert audio recordings into text.
- Text embeddings: Embeddings are numerical representations of text. Such embeddings are the cornerstone of NLP.

You’re not limited to the OpenAI model family. You can work with many other LLMs such as Groq.

 

## Conclusion

Setting up and using the OpenAI API is straightforward once you understand the key steps: getting your API key, securing it with a .env file, and using libraries like LangChain to send prompts and receive structured results. As you begin exploring models like GPT-4o, DALL·E, and Whisper, you’ll discover a rich ecosystem of tools to integrate AI into your projects.

 

 Editor’s note: This post has been adapted from a section of the book [*Generative AI with Python: The Developer’s Guide to Pretrained LLMs, Vector Databases, Retrieval-Augmented Generation, and Agentic Systems*](https://www.amazon.com/Generative-Python-Developers-Pretrained-Generation/dp/1493226908?maas=maas_adg_65C1F2AB72EBBA6CEA13210F2B44DDD3_afap_abs&ref_=aa_maas&tag=maas) by [Bert Gollnick](https://www.linkedin.com/in/bertgollnick/). Bert is a senior data scientist who specializes in renewable energies. For many years, he has taught courses about data science and machine learning, and more recently, about generative AI and natural language processing. Bert studied aeronautics at the Technical University of Berlin and economics at the University of Hagen. His main areas of interest are machine learning and data science. 

 

This post was originally published 8/2025.

## Recommendation

[![Generative AI with Python](https://blog.rheinwerk-computing.com/hs-fs/hubfs/social-suggested-images/2690-3.jpg?width=170&name=2690-3.jpg)](https://www.amazon.com/Generative-Python-Developers-Pretrained-Generation/dp/1493226908?maas=maas_adg_65C1F2AB72EBBA6CEA13210F2B44DDD3_afap_abs&ref_=aa_maas&tag=maas)

**Develop Your Own Gen AI Applications with Python!**

Ready to build your own generative AI applications? This developer's guide walks you through working with pretrained LLMs, vector databases, and retrieval-augmented generation using Python — then takes it further with agentic systems built on frameworks like LangChain, CrewAI, and OpenAI Agents. It's a practical, code-first path from AI concepts to fully deployed applications.

[Learn More](https://www.amazon.com/Generative-Python-Developers-Pretrained-Generation/dp/1493226908?maas=maas_adg_65C1F2AB72EBBA6CEA13210F2B44DDD3_afap_abs&ref_=aa_maas&tag=maas)

![Rheinwerk Computing](https://blog.rheinwerk-computing.com/hubfs/RW-logo-300x300.png)

**by [Rheinwerk Computing](https://blog.rheinwerk-computing.com/author/rheinwerk-computing)**

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes books by leading experts in the fields of programming, administration, security, analytics, and more.

[Python](https://blog.rheinwerk-computing.com/tag/python) [Artificial Intelligence](https://blog.rheinwerk-computing.com/tag/artificial-intelligence) [How To](https://blog.rheinwerk-computing.com/tag/how-to)

[![Share on facebook](https://7528309.fs1.hubspotusercontent-na1.net/hub/7528309/hubfs/raw_assets/public/mV0_d-web-default-modules_hubspot/img/facebook-color.png?width=24&name=facebook-color.png)](https://www.facebook.com/share.php?u=https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Dfacebook) [![Share on linkedin](https://7528302.fs1.hubspotusercontent-na1.net/hub/7528302/hubfs/raw_assets/public/mV0_d-web-default-modules_hubspot/img/linkedin-color.png?width=24&name=linkedin-color.png)](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Dlinkedin) [![Share on twitter](https://7528304.fs1.hubspotusercontent-na1.net/hub/7528304/hubfs/raw_assets/public/mV0_d-web-default-modules_hubspot/img/twitter-color.png?width=24&name=twitter-color.png)](https://twitter.com/intent/tweet?original_referer=https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Dtwitter&url=https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Dtwitter&source=tweetbutton&text=) [![Share on email](https://7528311.fs1.hubspotusercontent-na1.net/hub/7528311/hubfs/raw_assets/public/mV0_d-web-default-modules_hubspot/img/email-color.png?width=24&name=email-color.png)](mailto:?subject=Check+out+https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Demail&body=Check+out+https%3A%2F%2Fblog.rheinwerk-computing.com%2Fhow-to-use-openais-api-with-langchain%3Futm_medium%3Dsocial%26utm_source%3Demail)

### Comments

### Latest Blog Posts

[![What Is the Difference Between Narrow AI and General AI?](https://blog.rheinwerk-computing.com/hs-fs/hubfs/What%20Is%20the%20Difference%20Between%20Narrow%20AI%20and%20General%20AI_.jpg?height=600&name=What%20Is%20the%20Difference%20Between%20Narrow%20AI%20and%20General%20AI_.jpg)](https://blog.rheinwerk-computing.com/what-is-the-difference-between-narrow-ai-and-general-ai)

[Artificial Intelligence](https://blog.rheinwerk-computing.com/tag/artificial-intelligence)

## [What Is the Difference Between Narrow AI and General AI?](https://blog.rheinwerk-computing.com/what-is-the-difference-between-narrow-ai-and-general-ai)

[Read More](https://blog.rheinwerk-computing.com/what-is-the-difference-between-narrow-ai-and-general-ai)

[![LLM Model Selection: Key Criteria for Generative AI Projects](https://blog.rheinwerk-computing.com/hs-fs/hubfs/LLM%20Model%20Selection_%20Key%20Criteria%20for%20Generative%20AI%20Projects.jpg?height=600&name=LLM%20Model%20Selection_%20Key%20Criteria%20for%20Generative%20AI%20Projects.jpg)](https://blog.rheinwerk-computing.com/llm-model-selection-key-criteria-for-generative-ai-projects)

[Featured](https://blog.rheinwerk-computing.com/tag/featured)

## [LLM Model Selection: Key Criteria for Generative AI Projects](https://blog.rheinwerk-computing.com/llm-model-selection-key-criteria-for-generative-ai-projects)

[Read More](https://blog.rheinwerk-computing.com/llm-model-selection-key-criteria-for-generative-ai-projects)

**Subscribe to our blog!**Get notified about future blog updates.

- <https://www.linkedin.com/showcase/rheinwerk-computing/>
- <https://www.youtube.com/channel/UChj-U-uWGM7qRlHXSFU93ew>
- <https://blog.rheinwerk-computing.com/rss.xml>

### The official Rheinwerk Computing Blog

Rheinwerk Computing is an imprint of Rheinwerk Publishing and publishes resources that will help you accelerate your computing journey. The Rheinwerk Computing Blog is designed to provide helpful, actionable information on a variety of topics, including programming, administration, security, and analytics!

### Blog Topics

- [All Topics](https://blog.rheinwerk-computing.com)
- [Programming Languages](https://blog.rheinwerk-computing.com/tag/programming-languages)
- [How To](https://blog.rheinwerk-computing.com/tag/how-to)
- [JavaScript](https://blog.rheinwerk-computing.com/tag/javascript)
- [DevOps](https://blog.rheinwerk-computing.com/tag/devops)
- [Web Development](https://blog.rheinwerk-computing.com/tag/web-development)
- [Python](https://blog.rheinwerk-computing.com/tag/python)
- [What Is?](https://blog.rheinwerk-computing.com/tag/what-is)
- [Cybersecurity](https://blog.rheinwerk-computing.com/tag/cybersecurity)
- [Software Development](https://blog.rheinwerk-computing.com/tag/software-development)
- [Java](https://blog.rheinwerk-computing.com/tag/java)

### Blog curated by

[![Rheinwerk Computing Logo](https://blog.rheinwerk-computing.com/hubfs/computing_logo-header.svg)](https://www.sap-press.com/rheinwerk-computing/) [Visit Rheinwerk Computing Store](https://www.sap-press.com/rheinwerk-computing/)

### About

- [Home](https://sap-press.com/)
- [About Us](https://sap-press.com/the-publisher/)
- [Contact](mailto:info@rheinwerk-publishing.com)
- [Legal Notes](https://sap-press.com/legal-notes/)
- [Privacy Policy](https://sap-press.com/privacy/)
- [Terms of Use](https://sap-press.com/terms/)

© 2026 Rheinwerk Publishing, Inc. | Change Privacy Options

```json
{
  "@context" : "https://schema.org",
  "@type" : "BlogPosting",
  "author" : {
    "@type" : "Person",
    "name" : "Rheinwerk Computing",
    "url" : "https://blog.rheinwerk-computing.com/author/rheinwerk-computing"
  },
  "dateModified" : "2026-03-13T15:44:33.491Z",
  "datePublished" : "2025-08-13T13:00:00.000Z",
  "headline" : "How to Use OpenAI’s API with LangChain: Setup, Environment Variables, and First Model Call",
  "image" : [ "https://blog.rheinwerk-computing.com/hubfs/How%20to%20Use%20OpenAI%E2%80%99s%20API%20with%20LangChain_%20Setup%2c%20Environment%20Variables%2c%20and%20First%20Model%20Call.jpg" ],
  "mainEntityOfPage" : {
    "@id" : "https://blog.rheinwerk-computing.com/how-to-use-openais-api-with-langchain",
    "@type" : "WebPage"
  },
  "publisher" : {
    "@type" : "Organization",
    "logo" : {
      "@type" : "ImageObject",
      "url" : "https://blog.rheinwerk-computing.com/hubfs/Logo-1.jpg"
    },
    "name" : "Rheinwerk Publishing, Inc."
  }
}
```