Encountering "Incorrect API key provided" Error Using Jupyter Notebook

I have a website written in PHP that connects to the OpenAI Completions API, model “text-davinci-003” and have no problems getting a response back from the API with the requested completion.

I’m trying the same using Python in a Jupyter Notebook and encountering difficulty with authentication. I first tried using LangChain OpenAI LLM Library using the code below (substituted the actual API key):

from langchain.llms import OpenAI
import os

%env OPENAI_API_KEY = "sk-abcdef"

print(os.environ['OPENAI_API_KEY'])

llm = OpenAI(temperature=0.8, model_name="text-davinci-003")
s = llm("Tell me a joke")

I encountered the error "AuthenticationError: Incorrect API key provided: “sk-abc*****************************************def”. I thought the code might’ve been the culprit, so I tried using the same code from the OpenAI playground and encountered the same error.

import os
import openai

%env OPENAI_API_KEY = "sk-abcdef"

openai.api_key = os.getenv("OPENAI_API_KEY")

response = openai.Completion.create(
  model="text-davinci-003",
  prompt="Tell me a joke",
  temperature=0.7,
  max_tokens=3000,
  top_p=1,
  frequency_penalty=0,
  presence_penalty=0
)

I’m getting the same error using both methods. The Jupyter Notebook is a local install on a local web server accessible by “localhost.” I’m unsure how to solve this issue - what can I do? I have no issues accessing the API from my website, only when trying it locally. Any thoughts about resolving this?

I solved my problem! I was using “%env”, which appeared to set the environment variable, but I don’t think it was. In actuality, it was probably setting a different kind of environment variable - probably a virtual environment variable. Or, it was causing incompatibility somewhere else. When I tried “%env” in the command-line Python kernel, it didn’t recognize “%env”. From browsing a similar question in another forum posting, I discovered “os.environ” and set the environment variable using that method.

It worked!

Here’s the change I made:

os.environ["OPENAI_API_KEY"] = "sk-abcdef"

Sharing this just in case a future Python rookie makes the same mistake.

4 Likes

Welcome to the forum. Thanks for coming back to let us know.

Hope you stick around!