Is there a better way to strip and get OpenAI responses?

Question:

I’m trying to get at least 1 response for each keyword that is looped to be included in the text prompt, however when I run the python code to generate responses I get the following error:

PS C:Users...DocumentsArticle-gen> & C:/Users/.../AppData/Local/Microsoft/WindowsApps/python3.11.exe c:/Users/.../Documents/Article-gen/createArticle.py
ChatGPT API replies for Amazon (AMZN) stock:

Traceback (most recent call last):
  File "C:Users...AppDataLocalPackagesPythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0LocalCachelocal-packagesPython311site-packagesopenaiopenai_object.py", line 59, in __getattr__
    return self[k]
           ~~~~^^^
KeyError: 'text'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:Users...DocumentsArticle-gencreateArticle.py", line 29, in <module>
    outputText = choice.text.strip()
                 ^^^^^^^^^^^
  File "C:Users...AppDataLocalPackagesPythonSoftwareFoundation.Python.3.11_qbz5n2kfra8p0LocalCachelocal-packagesPython311site-packagesopenaiopenai_object.py", line 61, in __getattr__
    raise AttributeError(*err.args)
AttributeError: text

How can I fix this so I can get at least 1 response back per keyword? Here’s the Python code I’m working with:

import openai
import os

# Set OpenAI API key
openai.api_key = ""

# Then, you can call the "gpt-3.5-turbo" model
modelEngine = "gpt-3.5-turbo"

# set your input text
inputText = "Write a 1,500 word that is highly speculative bullish article IN YOUR OWN WORDS on {} stock and why it went up, you must include how it could affect the stock price and future outcome of the business. Include subheadings in your own words and act like you know it all and be an authoritative expert on the topic. Now write."

# Array of keywords to generate article on
keywords = ["Nio (NIO)", "Apple (AAPL)", "Microsoft (MSFT)", "Tesla (TSLA)", "Meta (META)", "Amazon (AMZN)"]

# Switches and injects keywords into API request
for keyword in keywords:
    # set input text with the current keyword
    inputSent = inputText.format(keyword)

# Send an API request and get a response, note that the interface and parameters have changed compared to the old model
response = openai.ChatCompletion.create(
   model=modelEngine,
   messages=[{"role": "user", "content": inputSent }],
   n = 1
)
print("ChatGPT API replies for", keyword, "stock:n")
for choice in response.choices:
        outputText = choice.text.strip()
        print(outputText)
        print("------")
print("n")
Asked By: overdeveloping

||

Answers:

Here is code with two issues fixed:

  1. Set outputText = choice.message.content to get the text of the response.
  2. Indented response and print blocks to be within the for keyword... loop.

Note that I tweaked the prompt just a bit for brevity in my testing.

import openai
import os

# Set OpenAI API key
openai.api_key = ""

# Then, you can call the "gpt-3.5-turbo" model
modelEngine = "gpt-3.5-turbo"

# set your input text
# inputText = "Write a 1,500 word that is highly speculative bullish article IN YOUR OWN WORDS on {} stock and why it went up, you must include how it could affect the stock price and future outcome of the business. Include subheadings in your own words and act like you know it all and be an authoritative expert on the topic. Now write."
inputText = "Write a 100 word tweet is highly speculative bullish article IN YOUR OWN WORDS on {} stock and why it went up, you must include how it could affect the stock price and future outcome of the business. Include subheadings in your own words and act like you know it all and be an authoritative expert on the topic. Now write."

# Array of keywords to generate article on
keywords = ["Nio (NIO)", "Apple (AAPL)", "Microsoft (MSFT)", "Tesla (TSLA)", "Meta (META)", "Amazon (AMZN)"]

# Switches and injects keywords into API request
for keyword in keywords:
    # set input text with the current keyword
    inputSent = inputText.format(keyword)

    # Send an API request and get a response, note that the interface and parameters have changed compared to the old model
    response = openai.ChatCompletion.create(
    model=modelEngine,
    messages=[{"role": "user", "content": inputSent }],
    n = 1
    )
    print("ChatGPT API replies for", keyword, "stock:n")
    for choice in response.choices:
            #outputText = choice.text.strip()
            outputText = choice.message.content
            print(outputText)
            print("------")
    print("n")
Answered By: busse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.