如何将 JSON 转换为 Python 函数参数?

huangapple go评论62阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年5月7日 22:46:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76194617.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定