Search code examples
pythonartificial-intelligenceopenai-api

How do you convert json to python function arguments?


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.


Solution

  • 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