An error has occurred ” line 3, in generate_100_word_summary AttributeError: type object ‘OpenAI’ has no attribute ‘client'”

I have a csv file with open source reports and news articles for infectious diseases and wanted to use ChatGPT to create epidemiological summaries using this text data for each infectious disease.

This is the code I am using :

from openai import OpenAI
import pandas as pd
client = OpenAI()

##Importing data
data = pd.read_csv("xxxx_signals.csv",encoding='unicode_escape')
#going to subset data, removing publications, filtering on xxxx entries logged in MONTH xxxx
subset = data[data["Incident or Publication"]== "Incident"] 
subset2 = subset[subset["xxxx"]== 1] 
## incident and list of xxxx

# Set your OpenAI API key here
OpenAI.api_key = "PRIVATE"

def generate_100_word_summary(prompt):
    # Using OpenAI API to generate response
    response = OpenAI.client.completions.create(
        engine="text-davinci-003",
        prompt=prompt,
        temperature=0.7,
        max_tokens=300
    )

    summary = response['choices'][0]['text']
    return summary

# Replace 'subset2' with your actual data structure
subset2 = {
    'Infection or Disease': ['Disease1', 'Disease2', 'Disease1', 'Disease3'],
    'Description of incident': [
        '10 cases reported on 2023-01-15',
        '5 cases on 2023-02-05',
        '15 cases on 2023-01-20',
        '8 cases on 2023-02-10'
    ],
    # Add more columns as needed
}

# Generate and print 100-word summaries for each infectious disease
for disease, description in zip(subset2['Infection or Disease'], subset2['Description of incident']):
    prompt = f"Epidemiological summary for {disease}:\nDescription: {description}\n"

    # Generate 100-word summary using GPT-3.5-turbo
    summary = generate_100_word_summary(prompt)

    # Print or use the generated summary as needed
    print(f"\nSummary for {disease}:\n{summary}")

I am receiving this error ” Traceback (most recent call last):
File “”, line 4, in
File “”, line 3, in generate_100_word_summary
AttributeError: type object ‘OpenAI’ has no attribute ‘client’

Please can someone help with this? Would be much appreciated.

I have tried changing the “OpenAI.client.completions.create” to “openai.client.Completion.create” and vice versa. Not sure if I am going about this the wrong way.

What stands out to me with a quick look-over is that you’ve already instantiated an OpenAI object called client with

client = OpenAI()

So change your response line to this:

    response = client.completions.create(

and give it a go. You see, ‘client’ is the name you’ve given to the OpenAI object that you’re trying to use, not an attribute of that class. 🙂

Continued

Your new errors make sense; I wondered if you might run in to an error like that after taking a closer look at your code. Here is a simple, working ‘chat’ client that I use. I’ve removed anything unique to my environment. If you supply your own API key, it should work and hopefully give you tips on getting yours to work correctly. It is a ‘chat completion’, so, slightly different than what your doing:

#!/usr/bin/env python3
# openai_chat.py
# OpenAI ChatGPT 3.5 chat client

import os
import sys
import openai
from openai import OpenAI

arg1 = sys.argv[1]
intro = "Answer the following query as 'Alice' the polite, helpful personal assistant: "
query = intro + arg1

client = OpenAI(api_key=YOUR_API_KEY)

try:
    chat_completion = client.chat.completions.create(
        messages=[
                  {
                   "role": "user",
                   "content": query,
                  }
                 ],
        model="gpt-3.5-turbo",
    )
except openai.APIConnectionError as e:
    print("The server could not be reached")
    print(e.__cause__)  # an underlying Exception, likely raised within httpx.
except openai.RateLimitError as e:
    print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
    print("Another non-200-range status code was received")
    print(e.status_code)
    print(e.response)

# Print out our results
print('You asked:\n', arg1, '\n')
print('Answer:')
print('',chat_completion.choices[0].message.content, '\n')

Please let me know if this works for you, and if it was helpful in trouble-shooting your own.

Continued #2

In the future, remember to include the version of Python you’re using and the version(s) of the modules that might be giving you problems. OS platform is good to know as well. 🙂

I’m testing this with
Python 3.9.18
openai 1.10.0 (latest)
and I’m on FreeBSD, for what it’s worth.

OK, so here is your code slightly altered, which raises an exception at line 8 where you read the .csv file, due to the fact that I don’t have the file or any reasonable facsimile. If I comment that section out, and allow generate_100_word_summary() to be called, I don’t get any exceptions from client.completions.create(), so hopefully this will work.

I’d love to see this work. If it’s at all possible to download an appropriate .csv file, I’d like to try it.

from openai import OpenAI
import pandas as pd


##Importing data
data = pd.read_csv("xxxx_signals.csv",encoding='unicode_escape')
#going to subset data, removing publications, filtering on xxxx entries logged in MONTH xxxx
subset = data[data["Incident or Publication"]== "Incident"] 
subset2 = subset[subset["xxxx"]== 1] 
## incident and list of xxxx

# Set your OpenAI API key here
#OpenAI.api_key = OPENAI_API_KEY
OPENAI_API_KEY = 'your_key'
client = OpenAI(api_key=OPENAI_API_KEY)


def generate_100_word_summary(prompt):
    # Using OpenAI API to generate response
    response = client.completions.create(
        ## New model to use:
        model="gpt-3.5-turbo-instruct",
        prompt=prompt,
        temperature=0.7,
        max_tokens=300
    )

    ## Change this:
    #summary = response['choices'][0]['text']
    ## to this:
    summary = response.choices[0].text
    return summary

# Replace 'subset2' with your actual data structure
subset2 = {
    'Infection or Disease': ['Disease1', 'Disease2', 'Disease1', 'Disease3'],
    'Description of incident': [
        '10 cases reported on 2023-01-15',
        '5 cases on 2023-02-05',
        '15 cases on 2023-01-20',
        '8 cases on 2023-02-10'
    ],
    # Add more columns as needed
}

# Generate and print 100-word summaries for each infectious disease
for disease, description in zip(subset2['Infection or Disease'], subset2['Description of incident']):
    prompt = f"Epidemiological summary for {disease}:\nDescription: {description}\n"

    # Generate 100-word summary using GPT-3.5-turbo
    summary = generate_100_word_summary(prompt)

    # Print or use the generated summary as needed
    print(f"\nSummary for {disease}:\n{summary}")

Leave a Comment