Search code examples
pythonopenai-api

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.


Solution

  • 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.