#API GPT4 openai-python discord

1 messages · Page 1 of 1 (latest)

jolly plover
#

Hello,
I try to use openai 1.33.0 with gpt4 in free-plan on discord
I used openai_key in environment

pip show openai
Name: openai
Version: 1.33.0
Summary: The official Python library for the openai API

pip show discord.py
Name: discord.py
Version: 2.3.2

my script

@client.command()
async def ai(ctx, *, user_message):
    try:
        response = openai.Completion.create(
            engine="text-davinci-003",
            prompt=user_message,
            temperature=0.7,
            max_tokens=150
        )
        assistant_response = response.choices[0].text.strip()
        await ctx.send(assistant_response)
    except Exception as e:
        print(f"Une erreur s'est produite : {e}")
        await ctx.send("Une erreur s'est produite lors de la génération de la réponse.")

And the error message :
Une erreur s'est produite :

You tried to access openai.Completion, 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

I don't understand where is the problem.
Could you help me please ?

shrewd nacelleBOT
#

Hi @jolly plover. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

The error message you're seeing is due to the fact that the openai.Completion endpoint you're trying to access has been deprecated in the newer versions of the OpenAI Python library (version 1.0.0 and above). This is why you're seeing the error message when you try to use openai.Completion.create.

Instead, you should use the chat completions endpoint, which is the recommended way to interact with the GPT-4 model. This is mentioned in one of the forum posts (https://community.openai.com/t/735807) in the knowledge sources.

Here's how you can modify your script to use the chat completions endpoint:

@client.command()
async def ai(ctx, *, user_message):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful assistant."
                },
                {
                    "role": "user",
                    "content": user_message
                }
            ]
        )
        assistant_response = response['choices'][0]['message']['content']
        await ctx.send(assistant_response)
    except Exception as e:
        print(f"Une erreur s'est produite : {e}")
        await ctx.send("Une erreur s'est produite lors de la génération de la réponse.")

Please note that the model parameter has been changed to "gpt-4" as per the new API. Also, the messages parameter is an array of message objects. Each object has a role that can be "system", "user", or "assistant", and content which is the text of the message from the role.

#

Also, please note that the model text-davinci-003 you were trying to use has been deprecated. It is recommended to use gpt-3.5-turbo-instruct instead as mentioned in another forum post (https://community.openai.com/t/581120) in the knowledge sources.

Remember to replace "gpt-4" with "gpt-3.5-turbo-instruct" if you're using a model that's available in your plan.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@jolly plover kapa.ai is still learning and improving, please let us know how it did by reacting below

jolly plover
#

@shrewd nacelle
error message is the same

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

GitHub

The official Python library for the OpenAI API. Contribute to openai/openai-python development by creating an account on GitHub.

GitHub

We have released a new major version of our SDK, and we recommend upgrading promptly. It's a total rewrite of the library, so many things have changed, but we've made upgrading easy with a ...

shrewd nacelleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

I apologize for the confusion. The error message indicates that the openai.ChatCompletion endpoint is no longer supported in the OpenAI Python library version 1.0.0 and above.

The correct way to use the chat models in the new API is to use the openai.ChatCompletion.create method. However, it seems there's a misunderstanding here. The openai.ChatCompletion.create method is not available in the OpenAI Python library version 1.0.0 and above.

Instead, you should use the openai.ChatCompletion.create method from the openai API. Here's how you can modify your script:

@client.command()
async def ai(ctx, *, user_message):
    try:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[
                {
                    "role": "system",
                    "content": "You are a helpful assistant."
                },
                {
                    "role": "user",
                    "content": user_message
                }
            ]
        )
        assistant_response = response['choices'][0]['message']['content']
        await ctx.send(assistant_response)
    except Exception as e:
        print(f"Une erreur s'est produite : {e}")
        await ctx.send("Une erreur s'est produite lors de la génération de la réponse.")

Please note that the model parameter has been changed to "gpt-4" as per the new API. Also, the messages parameter is an array of message objects. Each object has a role that can be "system", "user", or "assistant", and content which is the text of the message from the role.

Also, please note that the model text-davinci-003 you were trying to use has been deprecated. It is recommended to use gpt-3.5-turbo-instruct instead as mentioned in another forum post (https://community.openai.com/t/581120) in the knowledge sources.

#

Remember to replace "gpt-4" with "gpt-3.5-turbo-instruct" if you're using a model that's available in your plan.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@jolly plover kapa.ai is still learning and improving, please let us know how it did by reacting below

jolly plover
#

@shrewd nacelle is the same issue

shrewd nacelleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

I'm sorry for the confusion, but without additional context, it's difficult to determine what specific issue you're referring to. Could you please provide more details or clarify your question?

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:

#

@jolly plover kapa.ai is still learning and improving, please let us know how it did by reacting below

jolly plover
#

@shrewd nacelle how i can use a script python gpt-4 in discord.py to interact with users ?
Give me all steps.

shrewd nacelleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

To use GPT-4 with discord.py to interact with users, you need to follow these steps:

  1. Install the necessary libraries: You need to have the discord.py and openai libraries installed. You can install them using pip:
pip install discord.py
pip install openai
  1. Set up your Discord bot: You need to create a bot on the Discord developer portal, get the bot token, and invite the bot to your server. You can follow the instructions in this guide (https://discordpy.readthedocs.io/en/stable/discord.html).

  2. Set up your OpenAI API key: You need to get your OpenAI API key from the OpenAI website and set it as an environment variable. You can do this in your script like this:

import os
os.environ["OPENAI_API_KEY"] = "your-api-key"
  1. Write your Discord bot script: Now you can write a script that uses the discord.py library to listen for commands and respond using GPT-4. Here's a basic example:
import os
import discord
import openai

# Set up OpenAI API key
os.environ["OPENAI_API_KEY"] = "your-api-key"

# Initialize the Discord client
client = discord.Client()

# Initialize the OpenAI client
openai_client = openai.OpenAI()

@client.event
async def on_ready():
    print(f'We have logged in as {client.user}')

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('$hello'):
        await message.channel.send('Hello!')
#

if message.content.startswith('$ai'):
user_message = message.content[4:]
response = openai_client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": user_message
}
]
)
assistant_response = response['choices'][0]['message']['content']
await message.channel.send(assistant_response)

client.run('your-bot-token')


In this script, the bot responds to two commands: `$hello` and `$ai`. The `$hello` command makes the bot respond with "Hello!". The `$ai` command makes the bot send the rest of the message to the GPT-4 model and respond with the model's output.

Please replace `"your-api-key"` and `"your-bot-token"` with your actual OpenAI API key and Discord bot token.

Please note that the GPT-4 model may not be available in your OpenAI API plan. You may need to replace `"gpt-4"` with the name of a model that is available in your plan, such as `"gpt-3.5-turbo"`.

Also, please note that this is a very basic example. You may want to add error handling, command parsing, and other features to your bot. You can find more information on how to do this in the **discord.py documentation** (<https://discordpy.readthedocs.io/en/stable/index.html>).
----------------------
Note: you can ask me a follow up question by @ mentioning me again :speech_balloon:
----------------------
#

@jolly plover kapa.ai is still learning and improving, please let us know how it did by reacting below

jolly plover
#

@shrewd nacelle
error message :
Traceback (most recent call last):
File "/home/Bot/env/lib/python3.11/site-packages/discord/client.py", line 441, in _run_event
await coro(*args, **kwargs)
File "/home/Bot/bot.py", line 982, in on_message
assistant_response = response['choices'][0]['message']['content']
~~~~~~~~^^^^^^^^^^^
TypeError: 'ChatCompletion' object is not subscriptable

shrewd nacelleBOT
#

Let me check the knowledge base for you. One moment! :books:

#

The error message you're seeing is due to the fact that the response object returned by openai.ChatCompletion.create is not a dictionary, but an instance of the ChatCompletion class. Therefore, it cannot be subscripted like a dictionary.

To access the content of the assistant's message, you should use the .choices attribute of the response object, which is a list of ChatCompletionChoice objects. Each ChatCompletionChoice object has a .message attribute, which is a ChatCompletionMessage object. The ChatCompletionMessage object has a .content attribute, which is the content of the message.

Here's how you can modify your code to access the content of the assistant's message:

assistant_response = response.choices[0].message.content

This issue was discussed in a GitHub issue (https://github.com/openai/openai-python/issues/774) in the knowledge sources.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: