[Python] First time using API for a project been 3 days and can't get it to work

Discussão em 'Python' iniciado por Stack, Fevereiro 20, 2025.

  1. Stack

    Stack Membro Participativo

    I’m working on an application that uses both the ChatGPT and Genia APIs. After several days of trial and error and going through StackOverflow posts, my code still isn’t working.

    this some code i got off stackoverflow trying to modify it

    from os import environ
    from collections import deque
    from datetime import datetime
    from functools import lru_cache
    import openai
    from dotenv import load_dotenv

    load_dotenv()

    openai.api_key = environ["OPENAI_API_KEY"]

    CHAT_MODEL = "gpt-4"
    PROMPT = """Your name is Kim. A kind and friendly AI assistant that answers in a short and concise answer. Give short step-by-step reasoning if required."""

    class Chat:
    def __init__(self, converstion_limit: int = 8):

    self.messages_queue = deque(maxlen=converstion_limit)

    @lru_cache(maxsize=518)
    def chat(self, message: str) -> str:
    self.messages_queue.append({"role": "user", "content": message})

    try:
    prompty = {
    "role": "system",
    "content": f"{PROMPT} Today is {datetime.now(): %A %d %B %Y %H:%M}",
    }
    print(f"Sending request with prompt: {prompty}")
    response = openai.ChatCompletion.create(
    model=CHAT_MODEL, messages=[prompty, *self.messages_queue]
    )

    reply = response["choices"][0]["message"]["content"]
    print(f"Response from OpenAI: {reply}")

    self.messages_queue.append({"role": "assistant", "content": reply})
    except openai.error.OpenAIError as e:
    print(f"OpenAI error occurred: {e}")
    reply = "An error occurred. Please try again later."
    except Exception as e:
    print(f"Error: {e}")
    reply = "An unexpected error occurred."

    return reply


    if __name__ == "__main__":
    chat_instance = Chat()
    response = chat_instance.chat("Hello, Testing!")
    print(f"AI Response: {response}")```



    I am getting the following error:

    openai.lib._old_api.APIRemovedInV1:

    You tried to access openai.ChatCompletion, but this is no longer supported in openai>=1.0.0 - see the README at https://github.com/openai/openai-python for the API.

    You can run `openai migrate` to automatically upgrade your codebase to use the 1.0.0 interface.

    Alternatively, you can pin your installation to the old version, e.g. `pip install openai==0.28`

    A detailed migration guide is available here: https://github.com/openai/openai-python/discussions/742



    Traceback (most recent call last):
    File "/Users/farajaathanas/Documents/GitHub/Health_Ai_App/app.py", line 52, in <module>
    response = chat_instance.chat("Hello, AI!")
    File "/Users/farajaathanas/Documents/GitHub/Health_Ai_App/app.py", line 40, in chat
    except openai.error.OpenAIError as e:
    ^^^^^^^^^^^^
    AttributeError: module 'openai' has no attribute 'error'

    Continue reading...

Compartilhe esta Página