Successfully integrating the OpenAI API into Jupyter Notebook with the help of the provided sample code

After following a tutorial to set up the ChatGPT API with Python, utilizing the original documentation provided at , I successfully completed all the necessary steps outlined. Following the recommendation to 'Setup your API key for all projects,' I utilized setex to add the environment variable and duplicated it as a system variable in advanced system settings. Running the echo snippet in the command prompt confirmed that the key was stored correctly without any issues. It was mentioned that once this step is reached, there's no need to provide the API key within the code.

However, upon attempting to run some example code provided:

from openai import OpenAI
client = OpenAI()

completion = client.chat.completions.create(
  model="gpt-3.5-turbo",
  messages=[
    {"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
    {"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
  ]
)

print(completion. Choices[0].message)

An error was encountered:

---------------------------------------------------------------------------
OpenAIError                               Traceback (most recent call last)
Cell In[7], line 2
      1 from openai import OpenAI
----> 2 client = OpenAI()
      4 completion = client.chat.completions.create(
      5   model="gpt-3.5-turbo",
      6   messages=[
   (...)
      9   ]
     10 )
     12 print(completion.choices[0].message)

File ~\AppData\Local\Programs\Python\Python311\Lib\site-packages\openai\_client.py:93, in OpenAI.__init__(self, api_key, organization, base_url, timeout, max_retries, default_headers, default_query, http_client, _strict_response_validation)
     91     api_key = os.environ.get("OPENAI_API_KEY")
     92 if api_key is None:
---> 93     raise OpenAIError(
     94         "The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable"
     95     )
     96 self.api_key = api_key
     98 if organization is None:

OpenAIError: The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

Facing confusion and seeking assistance, I attempted adding the line openai.api_key = 'sk-xxxxx' to resolve the issue to no avail, resulting in the same error message persisting.

Answer №1

It is recommended to use the following code:

client = OpenAI(api_key='sk-XXXXXX')

By the way, it's not safe to reveal your api_key in this manner. It's best to deactivate it immediately and obtain a new one.

A better approach would be to define an environment variable like so (similar to Google's method):

OPENAI_API_KEY=sk-XXXXXX

The OpenAI() function automatically looks for the value of this environment variable. This practice helps protect your private api_key from exposure. You can find more detailed information on this topic from Google.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

An effective method for removing various stems from the end of a word is to utilize slicing techniques

While I am aware of tools like NLTK that can assist with this task, I am interested in learning how to efficiently extract multiple stems from a list. Let's consider the following list of words: list = ["another", "cats", "walrus", "relaxed", "annoy ...

Something went wrong while attempting to decode JSON in Python due to a missing comma delimiter

How can I send JSON data using sockets in Python? {"receiver": "2", "sender:": 1, "seq_num": 10, "data": "{"iv": "jdjhvwGriJ95kZwgDWlShw==", "ciphertext": "Fg7ugYYAn ...

Bug in Bubble Sort Algorithm

I made an attempt at writing a bubble sort program but unfortunately, it doesn't seem to be working as expected. n = raw_input("please enter the number of elements you wish to add into the array") print 'enter the elements for the array that ne ...

Python 2: Exploring the differences between a Unicode object and a string object

I came across this issue on StackOverflow, but I was unable to find a satisfactory solution: The problem I am facing involves comparing Unicode strings received from a server with hardcoded strings in my code. Even though I understand why a simple == comp ...

Changing the contents of NamedTemporaryFile in Python 3

I'm encountering a challenge when trying to modify the content of a NamedTemporaryFile after its initial creation. In my specific case, I am creating a NamedTemporaryFile from JSON data retrieved from a URL. My objective is to later open and edit th ...

simultaneous execution and writing to files in Python

I am faced with a challenge of handling extremely large datasets spread across 10 major clusters. The objective is to perform computations for each cluster and write the results line by line into separate files. Each file will contain the results corresp ...

Collect information using Python's request module

import requests from pprint import pprint headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36', } params = ( ('LeagueID', &ap ...

Combining Flask with Celery: Maximizing Efficiency with Parallel Processes

My Flask Celery app instantiates the celery instance. I'm aware that I can add a normal Flask route to the same .py file, but would need to run the code twice: To run the worker: % celery worker -A app.celery ... To run the code as a normal ...

Using Selenium for web scraping, certain instances involve scanning data, while others may not have this capability

Currently, I am developing a Python script utilizing the Selenium library to scrape hotel information from the e-dreams platform. The main purpose of this script is to gather specific data such as the title and current price, organize them into lists, and ...

Flask - Issue werkzeug.exceptions.BadRequestKeyError -

I've been encountering an issue while trying to run my first Flask app. After sending a POST request on Postman, I keep getting the following error: Error: werkzeug.exceptions.BadRequestKeyError: 400 Bad Request: The server couldn't understand t ...

Tips for setting up communication between servers and multiple clients?

In an effort to establish a two-way communication between a single server and multiple clients, I have developed the following Server code: Import subprocess, time, socket, fileinput s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host='' ...

In Python 3.4, my goal is to streamline the code so that a variable doesn't need to request input again

Hi there, I'm currently working on a programming project for my class and I've run into an issue that I can't quite figure out. I need to find a way to prompt the user for input just once and not multiple times in my program. The input gathe ...

Creating a matrix or table in Python to analyze overlapping data frames and count the intersections

Python seems to hold the key to a problem I encountered recently. dataframe 1 dataframe 2 dataframe 3 SID UID SID UID SID UID 123 dog 456 dog 789 monkey 123 cat 456 bat 789 ...

Guidelines for transferring Selenium WebDriver response to Scrapy's parse method

I am currently facing two challenges that I need to overcome: First: effectively locating and interacting with an element on a website using a driver. Second: passing the link generated from this interaction to a parse method or LinkExtractor. ad. 1. My ...

Issue with rendering in React Router

I've been having trouble with React Router in my code. I know that there have been changes from Switch to Routes in React Router Dom v6, but even after making the adjustment, my program just displays a blank screen. Can anyone help me resolve this iss ...

Using a Python loop to find the sum of numbers between two randomly generated values within the range of 1 to

Can someone assist me in creating a loop to generate two random integers between 1-10 and then calculate their sum within the range? import random total_sum = 0 from random import randrange num1 = (randrange(1,11)) num2 = (randrange(1,11)) count = tota ...

I am encountering a TypeError because the type being used is unhashable, specifically a 'list'. How do I go about inserting an image into a list while preserving

Within my views.py file, I have the following code: import os import cv2 from pathlib import Path path1 = Path(__file__).parent / "../test1" path2 = Path(__file__).parent / "../test2" index_list = [] for i in path1.iterdir(): i = str(i) if i.split(" ...

Transferring Access ids from .kv file to .py file in Kivy

. I am a beginner in Kivy and I am working on creating an Android app. I have almost completed the GUI, the front-end part, but I am facing a major issue. Despite searching extensively online, I have not found a solution to my problem. I am struggling with ...

PhantomJS occasionally fails to close (while using Python with Selenium)

Currently, I am utilizing selenium-python in combination with PhantomJS. The code structure is as follows: from selenium.webdriver import PhantomJS from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from se ...

Exploring the recursive challenges within the sudoku solving algorithm

I encountered an issue where I seem to have surpassed the maximum number of errors in my recuSolve method. The approach involves using recursion to determine the correct value for each sudoku box individually. import numpy as np grid = [[2, 5, 0, 0, 3, ...