Please help me find the error in my code. I don’t understand what the problem might be anymore.
According to my guesses, the bug occurs on line 42 when ( tool_outputs = self.collect_tool_outputs(run))I try to add an answer to the assistant after processing a function call, but an error occurs due to which I do not receive a response from the assistant.
ERROR - Error while getting response from ChatGPT assistant: Run failed with unexpected error.
Here is my code
import os
import re
import logging
import json
from openai import OpenAI
from datetime import datetime
class ChatGPTAssistant:
def __init__(self):
self.api_key = os.getenv('OPENAI_API_KEY')
self.client = OpenAI(api_key=self.api_key, default_headers={"OpenAI-Beta": "assistants=v2"})
self.assistant_id = os.getenv('OPENAI_ASSISTANT_ID')
if not self.assistant_id:
raise ValueError("OPENAI_ASSISTANT_ID is not set in the environment variables.")
self.logger = logging.getLogger(__name__)
def create_thread(self, user_id: str):
self.logger.info(f"Creating new thread for user {user_id}")
thread = self.client.beta.threads.create()
return thread.id
async def get_response(self, user_message: str, thread_id: str) -> str:
try:
self.logger.info(f"Getting response for message: {user_message[:50]}...")
self.client.beta.threads.messages.create(
thread_id=thread_id,
role="user",
content=user_message
)
run = self.client.beta.threads.runs.create_and_poll(
thread_id=thread_id,
assistant_id=self.assistant_id
)
if run.status == "requires_action":
self.logger.info("Run requires action (tool calls)")
tool_outputs = self.collect_tool_outputs(run)
if tool_outputs:
run = self.client.beta.threads.runs.submit_tool_outputs_and_poll(
thread_id=thread_id,
run_id=run.id,
tool_outputs=tool_outputs
)
self.logger.info("Tool outputs submitted successfully.")
else:
self.logger.info("No tool outputs to submit.")
if run.status == "completed":
self.logger.info("Retrieving assistant message")
messages = self.client.beta.threads.messages.list(thread_id=thread_id)
assistant_message = next((msg for msg in messages.data if msg.role == "assistant"), None)
if assistant_message and assistant_message.content:
response = assistant_message.content[0].text.value
self.logger.info(f"Got response: {response[:50]}...")
return response
else:
raise ValueError("No assistant response found")
elif run.status == "failed":
raise ValueError(f"Run failed with unexpected error.")
else:
raise ValueError(f"Unexpected run status: {run.status}")
except Exception as e:
error_message = f"Error while getting response from ChatGPT assistant: {str(e)}"
self.logger.error(error_message)
raise Exception(error_message)
def collect_tool_outputs(self, run):
try:
tool_outputs = []
for tool in run.required_action.submit_tool_outputs.tool_calls:
if tool.function.name == "handle_client_contact":
arguments = json.loads(tool.function.arguments)
client_name = arguments.get("client_name")
phone_number = arguments.get("phone_number")
preferred_call_time = arguments.get("preferred_call_time")
self.logger.info(
f"Received client data: Name={client_name}, Phone={phone_number}, Call Time={preferred_call_time}")
self.save_client_data(client_name, phone_number, preferred_call_time)
tool_outputs.append({
"tool_call_id": tool.id,
"output": "Client contact details have been saved successfully."
})
return tool_outputs
except Exception as e:
error_message = f"Error while handling tool calls: {str(e)}"
self.logger.error(error_message)
raise Exception(error_message)
def save_client_data(self, client_name, phone_number, preferred_call_time):
# Функция для сохранения данных клиента в файл
try:
filename = "client_contacts.txt"
with open(filename, "a") as file:
file.write(f"Client Name: {client_name}\n")
file.write(f"Phone Number: {phone_number}\n")
file.write(f"Preferred Call Time: {preferred_call_time}\n")
file.write(f"Recorded At: {datetime.now()}\n")
file.write("=" * 40 + "\n")
self.logger.info(f"Client data saved to {filename}")
except Exception as e:
error_message = f"Error while saving client data: {str(e)}"
self.logger.error(error_message)
raise Exception(error_message)
This is the description of the function