Configuring the OpenAI API Key for LangChain Operations
When executing LangChain workflows that interface with OpenAI models, an error is raised if the OPENAI_API_KEY environment variable is not defined.
In-Code Environment Variible Assignment
A temporary key can be assigned within the script to bypass the initialization error. This is suitable for testing environments.
import os
# Assign a placeholder value for initial execution
os.environ["OPENAI_API_KEY"] = "temp_test_key"
Shell Environment Configuration
Define the key in the shell session before runing the script. For Unix-based systems:
export OPENAI_API_KEY="your_actual_secret_key"
Direct Parameter Injection
Pass the key directly when instantiating the language model client.
from langchain.llms import OpenAI
language_model = OpenAI(openai_api_key="your_actual_secret_key")
Using PromptLayer for Instrumentation
For enhanced tracking, use the PromptLayerOpenAI wrapper, wich requires both PromptLayer and OpenAI keys.
from getpass import getpass
import os
from langchain.llms import PromptLayerOpenAI
pl_api_key = getpass("Input PromptLayer API Key: ")
os.environ["PROMPTLAYER_API_KEY"] = pl_api_key
oai_api_key = getpass("Input OpenAI API Key: ")
os.environ["OPENAI_API_KEY"] = oai_api_key
tracked_model = PromptLayerOpenAI(pl_tags=["langchain_demo"])
result = tracked_model("Describe the principle of backpropagation.")
print(result)
Example Workflow Requiring an API Key
The following script demonstrates a common operasion that will fail without a valid key. It loads a webpage, creates a vector index, and queries it.
import os
os.environ["OPENAI_API_KEY"] = "sk-xxxxxxxxxxxxxxxxxxxxxxxx" # Replace with a real key
import sys
os.environ['http_proxy'] = 'http://127.0.0.1:8080'
from langchain.document_loaders import WebBaseLoader
from langchain.indexes import VectorstoreIndexCreator
page_loader = WebBaseLoader("https://www.example.com/machine-learning-intro")
index_builder = VectorstoreIndexCreator()
vector_index = index_builder.from_loaders([page_loader])
answer = vector_index.query("What is supervised learning?")
print(answer)