英文:
How do you convert json to python function arguments?
问题
from flask import Flask, request
import openai, json
openai.api_key = API_KEY
app = Flask(__name__)
@app.route('/v1/chat/completions', methods=["POST"])
def index():
return openai.ChatCompletion.create(json.loads(request.get_json(force=True)))
app.run(debug=True, port=8080)
{'model': 'gpt-3.5-turbo', 'messages': [{'role': 'user', 'content': 'What is 2 + 2?'}], 'temperature': 0}
英文:
I'm trying to make a program that allows anyone to use the ChatGPT API using my API key using the Official OpenAI API. I am using a Flask server to listen to requests. Here is my code:
from flask import Flask, request
import openai, json
openai.api_key = API_KEY
app = Flask(__name__)
@app.route('/v1/chat/completions', methods=["POST"])
def index():
return openai.ChatCompletion.create(json.loads(request.get_json(force=True)))
app.run(debug=True, port=8080)
and here's my request body:
{'model': 'gpt-3.5-turbo', 'messages': [{'role': 'user', 'content': 'What is 2 + 2?'}], 'temperature': 0}
There seems to be a parsing error because it says: openai.error.InvalidRequestError: Must provide an 'engine' or 'model' parameter to create a <class 'openai.api_resources.chat_completion.ChatCompletion'>
even though in my requests I give it a model.
答案1
得分: 1
你不能将一个字符串转换为多个参数。另外,如评论中所述,你不需要使用 json.loads
,因为request.get_json()
应该会返回你想要的 - 一个字典。
如果你提供了一个具有匹配键的字典,你可以这样做:
payload = request.get_json()
return openai.ChatCompletion.create(**payload)
否则,手动解析每个键:
payload = request.get_json()
return openai.ChatCompletion.create(
model=payload["model"],
messages=payload["messages"]
)
另外,Flask 更喜欢你返回文本/渲染后的 HTML,而不是直接的 Python 对象。
英文:
You can't convert one string into multiple parameters. Plus, as mentioned in the comments, you don't need json.loads
as request.get_json()
should return what you want - a dictionary.
If you were providing a dictionary with matching keys you could do
payload = request.get_json()
return openai.ChatCompletion.create(**payload)
Otherwise, parse each key manually
payload = request.get_json()
return openai.ChatCompletion.create(
model=payload["model"],
messages=payload["messages"]
)
Also, Flask prefers you return text / rendered HTML, rather than a direct Python object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论