Search code examples
pythonopenai-apichatgpt-api

simple python beginner chatgpt bot program bombs on compatibility issues, cannot find workaround


I am trying to learn both Python and simple ChatGPT api programming. The code I came up with was suggested by gpt itself, and in researching the problem I'm having, every code example I can find on the web is basically doing the same thing as the code I'm trying (below).

I started with a "pip3 install openai" and have no errors from that. It's when I run what should be the simplest code I've ever seen that the errors occur.

The errors I'm receiving are essentially telling me that "openai.ChatCompletion.create" is deprecated, so I've tried the recommended alternative call, which is just "openai.Completion.create". That fails too. Both calls are deprecated according to the runtime warnings. Unfortunately, every piece of sample code I can find on Google uses one of these two methods.

I was given two suggestions by the runtime. One was run "openai migrate" which does nothing but give me some strange permissions error on my PICTURES folder of all things.

The more sensible suggestion was digging into the recommended openai api spec and it suggested using "openai.chat.completions.create". When I try that, I get a different error, this time suggesting I've sent too many requests to the API. This is UTTER NONSENSE -- I've made one and exactly one only call to the api to get the error message.

This should not be this hard. I'm running out of options. I've tried every suggested sample I can find; none work; the call I find in the latest api spec (unless I'm misinterpreting) also does not work.

Any ideas would be appreciated.

import openai

def chat_with_gpt(api_key):
    openai.api_key = api_key

    # Starting a new chat session
    session = openai.ChatCompletion.create(
        model="gpt-3.5-turbo",  # or another model of your choice
        messages=[{"role": "system", "content": "You are a helpful assistant."}]
    )

    while True:
        prompt = input("Prompt: ")
        if prompt == "/quit":
            break

        try:
            response = openai.ChatCompletion.create(
                model="gpt-3.5-turbo",
                session_id=session["id"],  # Using the same session for continuity
                messages=[{"role": "user", "content": prompt}]
            )
            print(response["choices"][0]["message"]["content"])
        except Exception as e:
            print(f"An error occurred: {e}")

if __name__ == "__main__":
    api_key = "mykey"  # I replace with my actual key
    chat_with_gpt(api_key)

Solution

  • I'm on the 'free tier' with OpenAI and use my assisant program multiple times daily, but have never seen a 429 error before. I realize that's not helping you figure out why you were|are getting them. I agree with @larsks that the Github OpenAI repo has good working code examples. Here is my assistant program that works well for my needs. I got much of the code from the OpenAI repo. Replace <botname> with a name for your assistant, if you like. :-)

    #!/usr/bin/env python3
    # OpenAI ChatGPT 3.5 chat client
    
    import os
    import sys
    import openai
    from openai import OpenAI
    
    
    intro = "You are '<botname>' my helpful personal assitant. Where possible, answer the following query with citations from a reference text."
    
    try:
        client = OpenAI(api_key=os.environ['OPENAI_API_KEY'])
    except Exception as e:
        print(e.__cause__)
        sys.exit(1)
    
    
    print('How can I help you <your name>?\n')
    while True:
        query = input("> ")
        if query == "Done":
            print('Bye! -<botname>')
            break
    
        try:
            chat_completion = client.chat.completions.create(
                    messages=[{"role": "user", "content": intro+'query:"""'+query+'"""',}],
                model="gpt-3.5-turbo",
                temperature=0.2,
                top_p=1,
                frequency_penalty=0,
                presence_penalty=0
            )
    
        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('<botname>:')
        print('',chat_completion.choices[0].message.content, '\n')