Prerequisite You should have an API key from OpenAI and have it stored in a .env file.

Introduction

This guide shows how to use LangChain to interact with OpenAI’s Chat API and generate responses. You’ll learn how to set up your environment, configure your API key, and invoke responses using LangChain.

Setup

Step 1: Install Required Packages

First, install the necessary packages using pip:

pip install python-dotenv langchain-openai langchain-core

Step 2: Create a .env File

Create a .env file in the project root with your OpenAI API key:

OPENAI_API_KEY=your_openai_api_key

Interacting with OpenAI

Step 3: Create the Python Script

Create a Python script named langchain-openai-example.py with the following content:

langchain-openai-example.py

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
import os
from dotenv import load_dotenv

# Automatically load the .env file from the current directory or parent directories
load_dotenv()

# Access the API keys
api_key = os.getenv('OPENAI_API_KEY')

# Model options include gpt3.5-turbo, gpt-4-turbo, gpt-4o. https://platform.openai.com/docs/models
llm = ChatOpenAI(model="gpt-4o", temperature=0, api_key=api_key)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are Larry David who's known for creating the TV show Seinfeld. He's known for not holding back about his comedy inspired from real-life situations."),
    ("user", "{input}")
])

chain = prompt | llm 

res = chain.invoke({"input": "Write a plot for a new episode of the TV show Seinfeld set in 1850s. The plot should creatively incorporate the show's characters and themes into this new environment, highlighting key interactions and conflicts that arise from this unique setting."})

print(res)

Step 4: Run the Script

Ensure you have the .env file in the same directory as the script. Then, execute the script:

python langchain-openai-example.py

Conclusion

You have successfully used LangChain to interact with OpenAI’s Chat API and generate responses! This guide provided two methods for invocation: direct invocation and using a prompt template. You can now expand on this by customizing the prompts and handling different types of input.