ChatGPT Code not working

pls tell me what changes i should make

@nidhiranka You are experiencing issues due to a shortage of OpenAI key access or an incorrect API key.I had checked on replit it was working on myside means code is correct and just you need to API access .

what you have done mistake :
in you code you had not ask input for next question and that led to continuous replying of chatgpt and that hit your api access limit.So correct your code in last line add input to ask the next question.

from boltiotai import openai
import os
import sys

question = input("Q:Enter your question:\n ")

while True:
    openai.api_key = os.environ['OPENAI_API_KEY']
    if openai.api_key == "":
        sys.stderr.write("""
        You haven't set up your API key yet.

        If you don't have an API key yet, visit:

        https://platform.openai.com/signup

        1. Make an account or sign in
        2. Click "View API Keys" from the top right menu.
        3. Click "Create new secret key"

        Then, open the Secrets Tool and add OPENAI_API_KEY as a secret.
        """)
        exit(1)

    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "Who won the world series in 2020?"
            },
            {
                "role": "assistant",
                "content": "The Los Angeles Dodgers won the World Series in 2020."
            },
            {
                "role": "user",
                "content": question
            }
        ]
    )

    output = response['choices'][0]['message']['content']
    print("Ans: ", output, '\n')
    question = input("Q:Enter your next question:\n ")

I am open to discuss error furthur

This error is shown is called KeyError. This typically occurs in python when a dictionary key is not found. It is possible that the response dictionary does not contain a key called ‘choices’.

Hi @nidhiranka

Make sure that the secret key variable is matching with the key variable you have used in the code. According to your your the secret key variable should be “OPENAI_API_KEY”. Please do the changes and run the code again.

Do try this and let us know. If you still face any issue, please feel free to get back to us.

Give a try to this corrected code as it is working fine for me :

import openai
import os
import sys

question=input("Q: What is your question/instruction? \n")

while True:
  try:
    openai.api_key = os.environ['OPENAI_API_KEY']
    if openai.api_key == "":
      sys.stderr.write("""
  You haven't set up your API key yet.
  
  If you don't have an API key yet, visit:
  
  https://platform.openai.com/signup

  1. Make an account or sign in
  2. Click "View API Keys" from the top right menu.
  3. Click "Create new secret key"

  Then, open the Secrets Tool and add OPENAI_API_KEY as a secret.
  """)
      exit(1)
    response = openai.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[{
        "role": "system",
        "content": "You are a helpful assistant."}, 
#{"role": "user","content": "Who won the world series in 2020?"}, 
#{"role":"assistant","content":"The Los Angeles Dodgers won the World Seriesin 2020."}, 
    {"role": "user", "content": question}])
    output=response.choices[0].message.content
    print("Answer : ",output)
    
    question=input("Q: What is your next question/instruction? \n")
  except Exception as e:
    print(f"An error occurred: {e}")

Do ensure that the key variable passed by you in this line " openai.api_key = os.environ[‘OPENAI_API_KEY’] " matches with the name with which you have saved your api key in the secrets.

hii @nidhiranka
Problem Explanation

You are experiencing issues because you didn’t prompt for the next question, causing continuous responses from the chatbot and hitting the API access limit.

Solution

You need to ensure that after providing a response, the script asks for the next question before proceeding.

Here is the corrected and improved code:

from boltiotai import openai
import os
import sys

# Prompt the user for their initial question
question = input("Q: Enter your question:\n ")

while True:
    # Set the OpenAI API key from the environment variable
    openai.api_key = os.environ.get('OPENAI_API_KEY')

    # Check if the API key is not set
    if not openai.api_key:
        sys.stderr.write("""
        You haven't set up your API key yet.

        If you don't have an API key yet, visit:

        https://platform.openai.com/signup

        1. Make an account or sign in
        2. Click "View API Keys" from the top right menu.
        3. Click "Create new secret key"

        Then, open the Secrets Tool and add OPENAI_API_KEY as a secret.
        """)
        exit(1)

    # Create a chat completion request
    response = openai.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "Who won the world series in 2020?"},
            {"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
            {"role": "user", "content": question}
        ]
    )

    # Extract and print the response content
    output = response['choices'][0]['message']['content']
    print("Ans: ", output, '\n')

    # Prompt the user for the next question
    question = input("Q: Enter your next question:\n ")

Explanation

  • Environment Variable Check: The script checks if the OPENAI_API_KEY is set in the environment. If not, it prompts the user to set it up.
  • Loop for Continuous Interaction: After answering a question, the script asks for the next question, preventing continuous requests and conserving API usage.
  • User Input: The script takes the initial question input before the loop starts and continues to prompt for new questions after each response.

If you encounter any further issues or errors, feel free to ask for more assistance.