Struggling to get a simple API task working

Trying to send of a series of prompts, that once processed, the response is plugged into a .csv file back here… Here is the script:

import os
import requests
import csv
import shutil
import time

Function to copy prompt files to a destination directory

def copy_prompt_files(src_directory, dest_directory):
# Check if the destination directory exists and create it if not
if not os.path.exists(dest_directory):
print(f"Destination directory created: {dest_directory}")

files_copied = 0  # Counter for the number of files copied
# Walk through all subdirectories in the source directory
for root, dirs, files in os.walk(src_directory):
    for filename in files:
        # Check if the filename pattern matches
        if '_prompt.txt' in filename:
            src_file_path = os.path.join(root, filename)
            dest_file_path = os.path.join(dest_directory, filename)
            # Ensure there's no filename conflict in the destination directory
            if os.path.exists(dest_file_path):
                print(f"A file with the name '{filename}' already exists in the destination. Skipping.")
                    shutil.copy(src_file_path, dest_file_path)
                    print(f"Copied: {filename} to {dest_directory}")
                    files_copied += 1
                except Exception as e:
                    print(f"Failed to copy {filename}: {e}")

# If no files were copied, report it
if files_copied == 0:
    print(f"No files containing '_prompt.txt' were found in {src_directory}")

Use your actual source and destination directories

src_directory = ‘REDACTED’
dest_directory = ‘REDACTED’

Call the function to copy the files

copy_prompt_files(src_directory, dest_directory)

Your destination CSV file

csv_file = ‘REDACTED’

The directory where your _prompt.txt files are located

prompts_directory = ‘REDACTED’

API_URL = ‘REDACTED’ (but its bassically V1 completions)

Define your CSV headers here as per the structure you want

csv_headers = [
“variant_option_one_name”, “variant_option_one_value”,
“inventory_Main_Outlet”, “Name”, “supplier_name”,
“SKU”, “supply_price”, “retail_price”,
“RELEASE DATE”, “TAGS”, “description”,

Function to send prompt to the OpenAI API

def send_to_api(prompt):
headers = {
‘Content-Type’: ‘application/json’,
‘Authorization’: f’Bearer {API_KEY}’
data = {
‘model’: ‘gpt-3.5-turbo’, # Use the most suitable model
‘prompt’: prompt,
‘max_tokens’: 150,
‘temperature’: 0.7
response =, headers=headers, json=data)
if response.status_code == 200:
return response.json()
return None

Function to write a row to the CSV

def write_to_csv(row_data):
with open(csv_file, ‘a’, newline=‘’) as file:
writer = csv.writer(file)

Main function to process the files and handle the API interaction

def process_files():
for subdir, dirs, files in os.walk(prompts_directory):
for filename in files:
if filename.endswith(‘_prompt.txt’):
file_path = os.path.join(subdir, filename)
with open(file_path, ‘r’) as file:
prompt_content =

                print(f"Processing: {filename}")
                # Send the prompt to the API
                api_response = send_to_api(prompt_content)
                if api_response is not None:
                    # Extract the text from the API response
                    if 'choices' in api_response and api_response['choices']:
                        description = api_response['choices'][0]['text'].strip()
                        # Here we just put the description in the 'description' column
                        row_data = [""] * len(csv_headers)
                        description_index = csv_headers.index('description')
                        row_data[description_index] = description
                        # Write this row to the CSV file
                        print(f"Processed and added to CSV: {filename}")

                    # Print the API response for debugging
                    print(f"API Response for {filename}: {api_response}")

                    # Add a delay before processing the next file
                    time.sleep(5)  # Adjust the delay time as needed
            except Exception as e:
                print(f"An error occurred while processing {filename}: {e}")

Run the processing function


Ultimatly, its meant to send a prompt, receive the response, write the results to the .scv and send the next, so on and so forth… But try as I might (API key works), I get nothing other than

Processing: _Omni_prompt.txt
An error occurred while processing _Omni_prompt.txt: 404 Client Error: Not Found for url: ‘REDACTED’ (but its bassically V1 completions)

Im not a coder, just someone TRYING to expidite a mundane workflow… So some hand holding may be required (unless its an easy fix)