You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0

what kind of artificial intelligence is chatgpt? it doesn’t even know how to connect to its own API.

I made (with ChatGPT) a code to connect with API-KEY, and to correct all the html code mistakes in several html files, then save the corrected files in another folder. I install and reinstall and upgrade all kinds of version of openAi library, but I get the same error. Come on !

I tried 21 times to connect, I redid the code as many times, and ChatGPT still doesn’t work. How can you not know how to connect to your own system? This is the most important thing, knowing how to open the door to your house with the right key. You pay for the API, then ChatGPT gives you the key, but the door remains closed. How come this?

The error you are getting is caused by changes in the OpenAI API for versions newer than 1.0.0. In the new version, the way API requests are made has changed, and the ChatCompletion.create method must be called in a way compatible with the new interface.

Solution
We need to update the script to use the new OpenAI API methodology. Here is a patched version of the code that works with the current version of the OpenAI API:

Below is the attempt no. 21 to create the code with ChatGPT 4:

import os
import logging
import openai  # Folosim direct openai, nu OpenAI ca în exemplul anterior

# Configurare logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# Setează API key-ul OpenAI
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
    api_key = "YOUR-API-KEY"
    logging.warning("Using hardcoded API key. It's recommended to use environment variables for security.")

openai.api_key = api_key

def analyze_and_correct_html_file(file_path, output_dir):
    try:
        # Citim conținutul HTML
        with open(file_path, 'r', encoding='utf-8') as file:
            html_content = file.read()

        # Trimiterea cererii către ChatGPT pentru analiza și corectarea HTML-ului
        response = openai.ChatCompletion.create(
            model="gpt-3.5-turbo",
            messages=[
                {"role": "system", "content": "You are a helpful assistant that analyzes and corrects HTML files. Please review the provided HTML and fix any issues in the code or text."},
                {"role": "user", "content": f"Please correct this HTML file:\n\n{html_content}"}
            ]
        )

        # Extragem conținutul corectat de la ChatGPT
        corrected_html = response['choices'][0]['message']['content']

        # Salvăm fișierul corectat
        output_file_path = os.path.join(output_dir, os.path.basename(file_path))
        with open(output_file_path, 'w', encoding='utf-8') as file:
            file.write(corrected_html)

        return corrected_html, output_file_path
    except Exception as e:
        logging.error(f"Error processing {file_path}: {str(e)}")
        return f"Error processing file: {str(e)}", None

def process_directory(input_dir, output_dir):
    os.makedirs(output_dir, exist_ok=True)
    report_file = os.path.join(output_dir, 'html_analysis_report.txt')

    with open(report_file, 'w', encoding='utf-8') as report:
        for root, dirs, files in os.walk(input_dir):
            html_files = [f for f in files if f.endswith('.html')]
            for i, file in enumerate(html_files[:10]):  # Limitează la primele 10 fișiere
                file_path = os.path.join(root, file)
                logging.info(f"Analyzing and correcting {file_path}...")
                analysis, output_path = analyze_and_correct_html_file(file_path, output_dir)
                report_text = f"Analysis and corrections for {file}:\n{analysis}\n"
                if output_path:
                    report_text += f"Corrected file saved to: {output_path}\n"
                report_text += "\n"
                report.write(report_text)
                logging.info(report_text)

            if len(html_files) > 10:
                logging.warning(f"Only the first 10 HTML files were processed to avoid exceeding API limits.")
            break  # Procesează doar directorul principal, nu și subdirectoarele

    logging.info(f"Analysis and correction complete. Report saved to {report_file}")

# Specificați directoarele de intrare și ieșire
input_directory = 'd:\\77'
output_directory = 'd:\\77\\Output'

# Rulăm analiza și corectarea
logging.info("Starting HTML file analysis and correction...")
process_directory(input_directory, output_directory)

This is the error:

*** Remote Interpreter Reinitialized ***2024-09-11 18:45:14,733 - INFO - goodbye ('127.0.0.1', 62533)
2024-09-11 18:45:14,733 - INFO - listener closed
2024-09-11 18:45:14,733 - INFO - server has terminated
2024-09-11 18:45:16,653 - WARNING - Using hardcoded API key. It's recommended to use environment variables for security.
2024-09-11 18:45:16,653 - INFO - Starting HTML file analysis and correction...
2024-09-11 18:45:16,654 - INFO - Analyzing and correcting d:\77\test-de-personalitate-in-leadership.html...
2024-09-11 18:45:16,655 - ERROR - Error processing d:\77\test-de-personalitate-in-leadership.html: 

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742

2024-09-11 18:45:16,655 - INFO - Analysis and corrections for test-de-personalitate-in-leadership.html:
Error processing file: 

You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface. 

Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742



2024-09-11 18:45:16,655 - INFO - Analysis and correction complete. Report saved to d:\77\Output\html_analysis_report.txt
>>>

What kind? A “generative pretrained transformer”. Pretrained means its knowledge corpus is collected ahead of time, used for a lengthy costly training, and then set in stone.

The OpenAI API is in constant flux of features, like many others. You would have to use in-context training (documentation) to teach it.

Just minutes ago a gave a tutorial on how to make enhanced calls to a latest model using Python > 1.0. It is not unique, as there are many other examples on the forum, along with that sidebar link “Documentation”.

Giving an AI examples of proper use will also improve its coding.

1 Like