Python issue : 401 Client Error: Unauthorized for url:

Hi, I get this error message when I run my Python script.

  • I checked my API key : it’s good, and well written (type : “OPENAI_API_KEY=sk-[redacted by moderator]”) on a .env file which is on same directory than my script.

  • I have token credits (10€)

Here is my script :

`import time
import pandas as pd
import os
import requests
from dotenv import load_dotenv


def call_gpt_3_5(title, body_html, prompt):
    api_key = "OPENAI_API_KEY"
    print(f"Debugging: API Key fetched is {api_key}")

    headers = {
        "Authorization": f"Bearer {api_key}"
    data = {
        "engine": "text-davinci-002",
        "prompt": prompt,
        "max_tokens": 300

    retry_count = 0
    while retry_count < 3:  # Maximum de 3 tentatives
            response ="", headers=headers, json=data)
            return response.json()["choices"][0]["text"].strip()
        except requests.exceptions.RequestException as e:
            print(f"Erreur d'API : {e}")
            if '429' in str(e):  # Si l'erreur est '429 Too Many Requests'
                print("Trop de requêtes. Attente de 60 secondes avant de réessayer.")
                retry_count += 1
                print("Une erreur s'est produite lors de la demande à l'API OpenAI.")
                print("Erreur détaillée :")
                return None  # Si c'est une autre erreur, on sort de la boucle

gpt_3_5_prompt = '''
prend comme base le contenu présent dans body-html, pour créer une fiche produit qui ne soit pas son duplicate.
Focalise bénéfices client. Boutique en ligne sympa, populaire. Sortie HTML sans doctype ni head ni body. Température : 1

csv_file_path = 'C:/Users/zizic/Downloads/SOMMELIER PRESTIGE_PRODUITS - TEST (1).csv'
df = pd.read_csv(csv_file_path)

for index, row in df.iterrows():
    title = row['Title']
    body_html = row['Body (HTML)']
    if pd.notna(title) and pd.notna(body_html):
        complete_prompt = f"Title: {title}\nBody HTML: {body_html}\n{gpt_3_5_prompt}"
        gpt_3_5_response = call_gpt_3_5(title, body_html, complete_prompt)
        if gpt_3_5_response:
            df.loc[index, 'RENDU'] = gpt_3_5_response
            df.to_csv(csv_file_path, index=False)
        user_input = input("Voulez-vous continuer ? (Oui/Non): ")
        if user_input.lower() != 'oui':
            print("Arrêt du script.")

df.to_csv(csv_file_path, index=False)


Someone can help me ? :slight_smile:


Don’t ask coding questions about things newer than ChatGPT’s model.
Loading a key from a file is usually not done, and takes setting a different library parameter. than the one you didn’t set. At least everything else is completely wrong also.

I’m actually impressed at the quality of extreme hallucination in that code.

Here’s a better quality failure from ChatGPT, I basically gave it the answer and it still can’t code.

This forum has a handy API reference on the left bar, with example usage.

1 Like

Ok thanks. I’m lost (not coder) : where can I find a coder who knows enough about Python and Open-Ai to build me the good script ?

On the forum. Here you go, chat away after editing in your API key:

import openai
import time
openai.api_key = "sk-123412341234"
sys = [{"role": "system", "content": "You are ChatMagic, an AI assistant."}]
user = [{"role": "user", "content": "Introduction to ChatMagic AI starts conversation."}]
chat = []
while not user[0]['content'] == "exit":
    st = time.time()
    ap = openai.ChatCompletion.create(
        messages = sys + chat[-10:] + user,
        model="gpt-3.5-turbo", temperature=0.1, stream=True)
    resp = ""; wc = 0
    for d in ap:
        if d and not d['choices'][0]['finish_reason']:
            w = d['choices'][0]['delta']['content']
            resp += w; wc +=1
            print(w, end ="")
    chat += user + [{"role": "assistant", "content": resp}]
    en = time.time() - st
    print(f"\nDone. {len(resp.split())} words/{wc} chunks in {en:.1f} seconds.")
    user = [{"role": "user", "content": input("Prompt: ")}]

Thanks. :slight_smile: How can I adapt that base to automate text production based on a csv containing an input colomn (source of the text, to inspire GPT) and an output one (to receive the result producted by GPT) ?

This is the AI developer forum, not the programming lesson forum.

You can see in the loop that never stops, you supply the AI input with your chat prompt. Instead, the loop is likely not required, you take the text that has been obtained from the file or other retrieval method, include it as a user role message, and write the system message with instructions of the type of processing to do, and get the resp variable that collects the AI answer.

Hello Michel, please be careful about sharing your private API key. If the key is leaked a user could use it to make requests in your name, charging you for their usage or potentially banning you depending on the type of requests they make. Since your key has been leaked please delete it and create a new one.

Best Wishes,


1 Like

Thanks for your answear my friend. Unfortunately, as I’m not programmer, I don’t understand it. :wink: Do you know where I can pay a programmer to write me the good Python script to do what I want ? Programmer knowing Python + Open-Ai.

Thanks a lot for the advise my friend. I did what you told. :wink:

1 Like