Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 343
codeweird Avatar asked Dec 12 '25 11:12

codeweird


2 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"]
like image 118
Max R Avatar answered Dec 15 '25 03:12

Max R


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.

like image 44
Random Davis Avatar answered Dec 15 '25 03:12

Random Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!