Custom in Python GPT Completions Repeatedly calling itself

I have created the function below. Which is continuously running when getting error from the function.

I got stuck with that logic. It’s just went to infinite loop.

def chat():
   query = request.json.get('query')
   if 'messages' not in session:
       session['messages'] = []
   messages = session['messages']
   # Prepend user query to the front of messages
   messages.append({"role": "user", "content": query})
   response = get_gpt_response(messages)
   iteration = 0
   while response.choices[0].message.function_call:
       iteration += 1
       print("Iteration: ", iteration)
       function_name = response.choices[0].message.function_call.name
       arguments = response.choices[0].message.function_call.arguments
       # messages.append({
       #     "role": "assistant",
       #     "content": f"Function call detected: {function_name}"
       # })
       function_response = execute_function_call(function_name, arguments)
       # print("Executing {}, with Parameters {} ".format(
       # function_name, arguments))
       # print("Function Response: ", function_response)
       messages.append({
           "role": "assistant",
           "content": str(function_response)
       })
       print("Message for GPT: ", messages[-1])
       response = get_gpt_response(messages)
       print("GPT Response: ", response.choices[0].message)
       messages.pop(-1)
       # messages.pop(-1)
   response_content = response.choices[0].message.content
   messages.append({"role": "assistant", "content": response_content})
   session['messages'] = messages
   return jsonify({'response': response_content, 'conversation': messages})
response = get_gpt_response(messages)

this line starts running infinite time instead of appending the message and stop for the query.