Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading