Python ChatGPT 机器人在 openai.Completion 中的问题
我正在尝试写一个聊天机器人。结果出现了一个错误,提示“你试图访问 openai.Completion,但在 openai>=1.0.0 中这已经不再支持了。”
有人能帮我想办法把这个代码改写成可以在 openAI API 的 v1.0.0 版本中使用的吗?
import openai
# Replace 'your_api_key_here' with your actual OpenAI API key
openai.api_key = 'your_api_key_here'
def chat_with_gpt(prompt):
"""
Sends a prompt to GPT and returns the generated response.
:param prompt: The input text to send.
:return: The text of the generated response.
"""
try:
response = openai.Completion.create(
model="gpt-3.5-turbo", # Adjust with the appropriate model you have access to
prompt=prompt,
temperature=0.7,
max_tokens=150,
n=1,
stop=None
)
return response.choices[0].text.strip()
except Exception as e:
return f"An error occurred: {str(e)}"
def main():
print("GPT-3.5: Hello! How can I assist you today? Type 'quit' to exit.")
chat_history = [] # To store the conversation history
while True:
user_input = input("You: ")
if user_input.lower() == "quit":
print("GPT-3.5: Goodbye! Have a great day!")
break
# Concatenate the chat history with the new message for context
prompt = "\n".join(chat_history + [f"You: {user_input}", "GPT-3.5:"])
response = chat_with_gpt(prompt)
print(f"GPT-3.5: {response}")
# Update the chat history
chat_history.extend([f"You: {user_input}", f"GPT-3.5: {response}"])
# Optional: Limit the history size to the last few exchanges to manage token limits
chat_history = chat_history[-6:]
if __name__ == "__main__":
main()
我也试过 openai.ChatCompletion,但也遇到了类似的错误。
1 个回答
0
你不需要使用 openai.Completion.create()
这个方法,而是要先创建一个客户端对象,方法是用 client = openai.OpenAI()
。然后,你可以使用 client.chat.completions.create()
这个方法来生成内容。
下面是一个示例,展示了你可以怎么做(这个例子来自官方的 OpenAI 文档):
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": "You are a poetic assistant, skilled in explaining complex programming concepts with creative flair."},
{"role": "user", "content": "Compose a poem that explains the concept of recursion in programming."}
]
)
print(completion.choices[0].message)