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.
langchain-openai-example.py
Copy
from langchain_openai import ChatOpenAIfrom langchain_core.prompts import ChatPromptTemplateimport osfrom dotenv import load_dotenv# Automatically load the .env file from the current directory or parent directoriesload_dotenv()# Access the API keysapi_key = os.getenv('OPENAI_API_KEY')# Model options include gpt3.5-turbo, gpt-4-turbo, gpt-4o. https://platform.openai.com/docs/modelsllm = 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)
Create a Python script named langchain-openai-example.py with the following content:
langchain-openai-example.py
Copy
from langchain_openai import ChatOpenAIfrom langchain_core.prompts import ChatPromptTemplateimport osfrom dotenv import load_dotenv# Automatically load the .env file from the current directory or parent directoriesload_dotenv()# Access the API keysapi_key = os.getenv('OPENAI_API_KEY')# Model options include gpt3.5-turbo, gpt-4-turbo, gpt-4o. https://platform.openai.com/docs/modelsllm = 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)
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.