import json from openai.types.chat import ChatCompletion def func_talk(response: ChatCompletion): function_call = response.choices[0].message.function_call if function_call: function_name = function_call.name if function_name == 'talk': function_arguments = function_call.arguments try: j = json.loads(function_arguments) return j.get('message') except json.decoder.JSONDecodeError: # Sometimes the AI doesn't do JSON. return function_arguments else: print('THE AI DID NOT CALL A FUNCTION IN TALK:', response)