OpenAI API to Update Product Titles in Excel Using Python

I have access to the Free OpenAI API, and I want to use it to update the titles of my products in column B of an Excel CSV File. However, despite several attempts, I haven’t been able to achieve this using Python.

Welcome!

This doesn’t exist. Or do you mean you were given credits?

Check your billing.

If the code still doesn’t work, share the code, so we can take a look.

Good luck!

import pandas as pd
import openai
import os

Set your OpenAI API key

openai.api_key = ‘API_KEY_HERE’

def rephrase_title(title):
try:
response = openai.Completion.create(
model=“text-davinci-003”, # Adjust the model name as needed
prompt=f"Rephrase the following product title: {title}",
max_tokens=50
)

    new_title = response.choices[0].text.strip()
    print(f"Original title: {title}, New title: {new_title}")
    return new_title
except Exception as e:
    print(f"An error occurred: {e}")
    return title  # Return the original title in case of an error

Load your CSV file into a DataFrame

file_path = r"D:\Downloads\products_export_1 (9)\Sheet1.csv"
if not os.path.isfile(file_path):
print(f"Error: Input file ‘{file_path}’ does not exist.")
exit()

try:
df = pd.read_csv(file_path)
except Exception as e:
print(f"Error reading CSV file: {e}")
exit()

Print the column names to confirm the correct column for rephrasing

print(df.columns)

Choose the correct column name for rephrasing

correct_column_name = ‘Title’

Apply the rephrasing function to the selected column

df[correct_column_name] = df[correct_column_name].apply(lambda x: rephrase_title(x) if pd.notna(x) else x)

Specify a different output path for the CSV file

output_path = r"D:\Downloads\products_export_1 (9)\Sheet1_rephrased.csv"

try:

Save the modified DataFrame back to a CSV file

df.to_csv(output_path, index=False)
print(f"CSV file with rephrased titles saved to: {output_path}“)
except Exception as e:
print(f"Error saving CSV file: {e}”)

What error are you getting? Does the code run at all?

[Running] python -u “C:\Users\AHMEDN~1\AppData\Local\Temp\tempCodeRunnerFile.python”
Index([‘Handle’, ‘Title’, ‘Body (HTML)’, ‘Vendor’, ‘Product Category’, ‘Type’,
‘Tags’, ‘Published’, ‘Option1 Name’, ‘Option1 Value’, ‘Option2 Name’,
‘Option2 Value’, ‘Option3 Name’, ‘Option3 Value’, ‘Variant SKU’,
‘Variant Grams’, ‘Variant Inventory Tracker’,
‘Variant Inventory Policy’, ‘Variant Fulfillment Service’,
‘Variant Price’, ‘Variant Compare At Price’,
‘Variant Requires Shipping’, ‘Variant Taxable’, ‘Variant Barcode’,
‘Image Src’, ‘Image Position’, ‘Image Alt Text’, ‘Gift Card’,
‘SEO Title’, ‘SEO Description’,
‘Google Shopping / Google Product Category’, ‘Google Shopping / Gender’,
‘Google Shopping / Age Group’, ‘Google Shopping / MPN’,
‘Google Shopping / Condition’, ‘Google Shopping / Custom Product’,
‘Google Shopping / Custom Label 0’, ‘Google Shopping / Custom Label 1’,
‘Google Shopping / Custom Label 2’, ‘Google Shopping / Custom Label 3’,
‘Google Shopping / Custom Label 4’, ‘Variant Image’,
‘Variant Weight Unit’, ‘Variant Tax Code’, ‘Cost per item’,
‘Included / United States’, ‘Price / United States’,
‘Compare At Price / United States’, ‘Included / International’,
‘Price / International’, ‘Compare At Price / International’, ‘Status’],
dtype=‘object’)
An error occurred: Must provide an ‘engine’ parameter to create a <class ‘openai.api_resources.completion.Completion’>
An error occurred: Must provide an ‘engine’ parameter to create a <class ‘openai.api_resources.completion.Completion’>
C:\Users\Ahmed Nasar\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\blocks.py:2538: RuntimeWarning: invalid value encountered in cast
values = values.astype(str)
CSV file with rephrased titles saved to: D:\Downloads\products_export_1 (9)\Sheet1_rephrased.csv

[Done] exited with code=0 in 0.824 seconds

This model is no longer available. The only old-style Completion model is gpt-3.5-turbo-instruct…

Or you need to change your code for Chat Completion / ChatML…

Try swapping the model, though.

That’s what i don’t know to do it

model=“gpt-3.5-turbo-instruct”, # Adjust the model name as needed

The quickstart quide and API Docs (see left rail on this site) are very helpful to get you started…

Now the file is created but without any edit on column B cells:
[Running] python -u “C:\Users\AHMEDN~1\AppData\Local\Temp\tempCodeRunnerFile.python”
Index([‘Handle’, ‘Title’, ‘Body (HTML)’, ‘Vendor’, ‘Product Category’, ‘Type’,
‘Tags’, ‘Published’, ‘Option1 Name’, ‘Option1 Value’, ‘Option2 Name’,
‘Option2 Value’, ‘Option3 Name’, ‘Option3 Value’, ‘Variant SKU’,
‘Variant Grams’, ‘Variant Inventory Tracker’,
‘Variant Inventory Policy’, ‘Variant Fulfillment Service’,
‘Variant Price’, ‘Variant Compare At Price’,
‘Variant Requires Shipping’, ‘Variant Taxable’, ‘Variant Barcode’,
‘Image Src’, ‘Image Position’, ‘Image Alt Text’, ‘Gift Card’,
‘SEO Title’, ‘SEO Description’,
‘Google Shopping / Google Product Category’, ‘Google Shopping / Gender’,
‘Google Shopping / Age Group’, ‘Google Shopping / MPN’,
‘Google Shopping / Condition’, ‘Google Shopping / Custom Product’,
‘Google Shopping / Custom Label 0’, ‘Google Shopping / Custom Label 1’,
‘Google Shopping / Custom Label 2’, ‘Google Shopping / Custom Label 3’,
‘Google Shopping / Custom Label 4’, ‘Variant Image’,
‘Variant Weight Unit’, ‘Variant Tax Code’, ‘Cost per item’,
‘Included / United States’, ‘Price / United States’,
‘Compare At Price / United States’, ‘Included / International’,
‘Price / International’, ‘Compare At Price / International’, ‘Status’],
dtype=‘object’)
An error occurred: module ‘openai’ has no attribute ‘ChatCompletion’
An error occurred: module ‘openai’ has no attribute ‘ChatCompletion’
C:\Users\Ahmed Nasar\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\blocks.py:2538: RuntimeWarning: invalid value encountered in cast
values = values.astype(str)
CSV file with rephrased titles saved to: D:\Downloads\products_export_1 (9)\Sheet1_rephrased.csv

[Done] exited with code=0 in 0.852 seconds

Try updating you OpenAI library…

Where did you get the python code? Is it old? Might try asking ChatGPT to update it for you…

I got this code from ChatGPT

Ah, okay, that’s the problem. You likely didn’t tell it to use most modern libraries (and tell it which one), or maybe used a model that doesn’t yet have that info.

Prob better to find something on GitHub that does something similar.

What model were you using? What prompt did you give it?

[Running] python -u “C:\Users\AHMEDN~1\AppData\Local\Temp\tempCodeRunnerFile.python”
Index([‘Handle’, ‘Title’, ‘Body (HTML)’, ‘Vendor’, ‘Product Category’, ‘Type’,
‘Tags’, ‘Published’, ‘Option1 Name’, ‘Option1 Value’, ‘Option2 Name’,
‘Option2 Value’, ‘Option3 Name’, ‘Option3 Value’, ‘Variant SKU’,
‘Variant Grams’, ‘Variant Inventory Tracker’,
‘Variant Inventory Policy’, ‘Variant Fulfillment Service’,
‘Variant Price’, ‘Variant Compare At Price’,
‘Variant Requires Shipping’, ‘Variant Taxable’, ‘Variant Barcode’,
‘Image Src’, ‘Image Position’, ‘Image Alt Text’, ‘Gift Card’,
‘SEO Title’, ‘SEO Description’,
‘Google Shopping / Google Product Category’, ‘Google Shopping / Gender’,
‘Google Shopping / Age Group’, ‘Google Shopping / MPN’,
‘Google Shopping / Condition’, ‘Google Shopping / Custom Product’,
‘Google Shopping / Custom Label 0’, ‘Google Shopping / Custom Label 1’,
‘Google Shopping / Custom Label 2’, ‘Google Shopping / Custom Label 3’,
‘Google Shopping / Custom Label 4’, ‘Variant Image’,
‘Variant Weight Unit’, ‘Variant Tax Code’, ‘Cost per item’,
‘Included / United States’, ‘Price / United States’,
‘Compare At Price / United States’, ‘Included / International’,
‘Price / International’, ‘Compare At Price / International’, ‘Status’],
dtype=‘object’)
Processing title: Deer with Elven Design
An error occurred: You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: Collection of Astronauts
An error occurred: You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
Processing title: nan
C:\Users\Ahmed Nasar\AppData\Local\Programs\Python\Python311\Lib\site-packages\pandas\core\internals\blocks.py:2538: RuntimeWarning: invalid value encountered in cast
values = values.astype(str)
CSV file with rephrased titles saved to: D:\Downloads\products_export_1 (9)\Sheet1_rephrased.csv

[Done] exited with code=0 in 1.522 seconds

Latest error is here.

What would you recommend to solve this one?