Create function for `openai` and `ChatCompletion` in Python

Question:

I am trying to create a simple function that will take a message (string) and pass it through to openai.ChatCompletion.create(), but when I use an F-string, it returns an object error. Not super familiar with debugging Python, so I am a bit stuck here.

def get_response(message):
    
    response = openai.ChatCompletion.create(
        model = 'gpt-3.5-turbo',
        temperature = 1,
        messages = [
            f"{{'role': 'user', 'content': '{message}'}}"
        ]
    )
    return response.choices[0]["message"]["content"]

# get_response('What is 2 + 2?')

It returns:

InvalidRequestError: "{'role': 'user', 'content': 'What is 2 + 2?'}" is not of type 'object' - 'messages.0'

I guess that I might need to cast the string to some unique class that openai has created, but I’m not quite sure how. Looked through the source code but couldn’t find a reference to this class.

Asked By: xTrevi

||

Answers:

Your messages need to be objects, not strings (see here)

def get_response(message):
    
    response = openai.ChatCompletion.create(
        model = 'gpt-3.5-turbo',
        temperature = 1,
        messages = [
            {"role": "user", "content": message}
        ]
    )
    return response.choices[0]["message"]["content"]
Answered By: Violet Rosenzweig

Messages are actual object literals; you can’t replace the object literals with a string version. But you can replace the strings within the object literal with an f-string:

{"role": "user", "content": f"{message}"}

Or obviously in this example, an f-string is unnecessary so you can just put the name message right there:

{"role": "user", "content": message}

Again, to emphasize, it is not equivalent to send a string that has the same syntax as the object literal format, instead of sending an actual object literal.

Answered By: Random Davis

Not sure if it will help, see this solution

Answered By: Neil Russ
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.