Как дождаться завершения работы объекта Future, полученного в результате вызова API?

Я пытаюсь дождаться результатов запроса к api моего чатбота gradio, но не знаю, как это сделать. Я имею в виду ожидание завершения работы объекта Future. Я думал, что .result() будет ждать результатов, но это не так. На самом деле, следующий код дает мне эту ошибку:

python3 test_questions.py
Loaded as API: http://0.0.0.0:7860/ ✔
Traceback (most recent call last):
  File "/home/project/dev/PROJECT/chatbot-rag/test_questions.py", line 33, in <module>
    data = response.result()
  File "/home/project/dev/PROJECT/chatbot-rag/.venv/lib/python3.10/site-packages/gradio_client/client.py", line 1456, in result
    return super().result(timeout=timeout)
  File "/usr/lib/python3.10/concurrent/futures/_base.py", line 458, in result
    return self.__get_result()
  File "/usr/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
    raise self._exception
  File "/usr/lib/python3.10/concurrent/futures/thread.py", line 58, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/project/dev/PROJECT/chatbot-rag/.venv/lib/python3.10/site-packages/gradio_client/client.py", line 869, in _inner
    predictions = _predict(*data)
  File "/home/project/dev/PROJECT/chatbot-rag/.venv/lib/python3.10/site-packages/gradio_client/client.py", line 896, in _predict
    raise ValueError(result["error"])
ValueError: None

вот код:

from gradio_client import Client
import json
import time
from datetime import datetime

client = Client("http://0.0.0.0:7860/")

# Загрузка вопросов из файла JSON
with open('/media/HELLO/SanDisk/Clef_rag/project/questions.json', 'r') as file:
    questions_data = json.load(file)

# Инициализация списка для хранения ответов
responses_data = []

# Générer le nom de fichier horodaté
current_time = datetime.now()
timestamp = current_time.strftime("%d_%m_%Y_%H:%M")
filename = f'/media/HELLO/SanDisk/Clef_rag/project/responses_{timestamp}.json'

# Разберитесь с каждым вопросом
for domain, questions in questions_data.items():
    if domain == 'QR_TI_technique':
        for question in questions:
            # Получить вопрос
            question_text = question["question"]

            # Время начала записи
            start_time = time.time()

            # Задать вопрос модели
            response = client.submit(question_text, api_name="/bot")
            # wait(response)
            data = response.result()
            
            # Сохранить время окончания
            end_time = time.time()

            # Рассчитать продолжительность
            duration = end_time - start_time

            # Хранение данных ответа
            response_data = {
                "domaine": domain,
                "question": question_text,
                "reponse_attendue": question["reponse_attendue"],
                "reponse_model": response.data,
                "heure_debut": start_time,
                "heure_fin": end_time,
                "duree": duration
            }

            # Добавить данные ответа в список
            responses_data.append(response_data)

            # Запись ответов после каждой итерации в файл с временной меткой
            with open(filename, 'a') as file:
                json.dump(response_data, file, indent=4)
                file.write('\n')  # Добавьте новую строку для каждого ответа

Является ли проблемой содержимое response.result()?


Ответы (0 шт):