我想开始使用openai的api。使用谷歌云函数和python脚本。
设置为python 3.11
我一开始安装openai“pip-installopenai”或“pip3-installopenai”,但它在运行这段代码时都有问题。我看到有时安装目录会引起问题,所以为了排除这种可能的情况,我尝试了几种方式卸载和重新安装openai pip和pip3。
在我尝试amazons版本运行脚本之前,我想让它在谷歌云功能中工作。我计划在其他系统上运行它,比如简单到rasp-pi的家庭服务器,但我认为从这里开始会很好。
这段代码通过并部署,但在手动测试前后出现错误也是很奇怪的。
我一定错过了什么。因此,为了显示我正在使用的错误和代码:
为了开始,入口点被设置为“generate_response”,它与我想在main.py中启动的函数相匹配。
requirements.txt具有
Flask==2.3.3
requests==2.26.0
openai
不确定是否需要“openai”。。
再次将python运行时环境设置为python 3.11
然而openai安装在python3.9的目录中
我在运行时python 3.9和3.11都有相同的问题,所以我不认为这是目录问题。但谁知道呢。我确信它可以是任何东西。
main.py有
import os
import requests
from flask import jsonify
def generate_response(request):
# Define the OpenAI endpoint and your API key
OPENAI_URL = "https://api.openai.com/v1/engines/davinci/completions"
HEADERS = {
"Authorization": f"Bearer {os.environ.get('REPLACE_WITH_YOUR_OWN_API')}",
"Content-Type": "application/json"
}
# Define your question:
prompt_text = "How are you?"
# Construct the data to send to the API
data = {
"prompt": prompt_text,
"max_tokens": 100
}
# Make the API call
response = requests.post(OPENAI_URL, headers=HEADERS, json=data)
# Extract text from the API response
openai_response = response.json()['choices'][0]['text'].strip()
#Display on terminal shell for debug:
print(openai_response)
return jsonify({"response": openai_response })
错误在它给我的url页面中。它部署和构建没有错误,但url显示:
“500内部服务器错误:服务器遇到内部错误,无法完成您的请求。服务器过载或应用程序出错。”
现在我关闭了身份验证,并将其设置为“允许未经身份验证的调用”,因为这只是初始测试。
在测试时,它似乎只是冻结并停止执行任何操作。云外壳,在GCF测试终端窗口中:说准备好测试了,当你点击运行测试时,curser只会闪烁,其他什么都没有。。。
此外,我在运行这段代码时遇到了同样的问题——与openai对话的想法完全相同,但在部署后仍然会出现同样的错误。这个版本只是去掉了在网页中查看所有结果的想法,而在终端或日志中查看结果的方式更为硬编码和静态。
import os
import openai
import requests
#entry point ask_openai
# Initialize OpenAI API
openai.api_key = os.environ.get('REPLACE_WITH_YOUR_OWN_API')
def ask_openai(request):
# Hardcoded question
question = "What is the capital of France?"
# Call OpenAI API
response = openai.Completion.create(
model="davinci",
prompt=question,
max_tokens=150
)
# Extracting answer from the response
answer = response.choices[0].text.strip()
# Print the question and its answer
print("Question:", question)
print("Answer:", answer)
return "Check the logs for the answer."