async def Get_LLM_Response(self):
from server_modules.text_web_ui import local_answer
while True:
if self.ImageInterpretation.value == False and self.Wispper.value == False and self.task_GenerateResponseProcess_started.value == True:
self.GenerateLLMResponse.value = True
request_id, message_content = await asyncio.get_event_loop().run_in_executor(None, self.input_queue.get)
response = await local_answer(message_content)
await asyncio.get_event_loop().run_in_executor(None, self.output_queue.put, (request_id, response))
self.GenerateLLMResponse.value = False
def _run(self):
asyncio.run(self.Get_LLM_Response())
Функция для обработки запросов
def process_request(request, input_queue, output_queue, request_queues):
request_id = str(uuid.uuid4())
response_queue = Manager().Queue() # Создаем очередь для ответа
request_queues[request_id] = response_queue
input_queue.put((request_id, request))
Ожидаем ответа
response = response_queue.get()
del request_queues[request_id] # Удаляем очередь после получения ответа
return {"response": response}
Функция для обработки ответов
def handle_responses(output_queue, request_queues):
while True:
request_id, response = output_queue.get()
if request_id in request_queues:
request_queues[request_id].put(response)
@app.post("/image_interpretation")
async def process_request_endpoint_2(request: Request):
global task_ImageInterpretationProcess_started
print("получил данные")
data = await request.json()
print(task_ImageInterpretationProcess_started.value) # Это покажет текущее значение
task_ImageInterpretationProcess_started.value = True # Исправлено на корректную запись
print(task_ImageInterpretationProcess_started.value) # Это покажет новое значение
print(task_ImageInterpretationProcess_started.value)
return process_request(data, input_queue_2, output_queue_2, request_queues_2)
@app.post("/generate_LLM_response")
async def process_request_endpoint_3(request: Request):
global task_GenerateResponseProcess_started
task_GenerateResponseProcess_started = True
data = await request.json()
return process_request(data, input_queue_3, output_queue_3, request_queues_3)
при обращении на эндпоинт /image_interpretation процесс Qwen_interpretation не запускает обработку из-за того, что в нём не обновляются значения переменных для условия. Вывод консоли выглядит в этот момент так:
получил данные
False
True
True
GenerateLLMResponse: False
Wispper: False
task_ImageInterpretationProcess_started: False
Как решить эту проблему и из-за чего она возникает?
The issue you're encountering stems from incorrectly passing shared variables to the ImageInterpretationProcess. Specifically, the ImageInterpretationProcess is inadvertently receiving the task_GenerateResponseProcess_started variable instead of the intended task_ImageInterpretationProcess_started variable. This mismatch prevents the condition in the Qwen_interpretation method from being met, as it's monitoring the wrong variable.
Problem:
The ImageInterpretationProcess is mistakenly receiving task_GenerateResponseProcess_started instead of task_ImageInterpretationProcess_started. This means it's monitoring the wrong flag, which remains False, preventing it from initiating the image interpretation process.
Endpoint Handling:
@app.post("/image_interpretation")
async def process_request_endpoint_2(request: Request):
global task_ImageInterpretationProcess_started
print("получил данные")
data = await request.json()
print(task_ImageInterpretationProcess_started.value) # Should print current value
task_ImageInterpretationProcess_started.value = True # Set to True
print(task_ImageInterpretationProcess_started.value) # Should print True
print(task_ImageInterpretationProcess_started.value)
return process_request(data, input_queue_2, output_queue_2, request_queues_2)
Observation:
This endpoint correctly sets task_ImageInterpretationProcess_started.value to True. However, since the ImageInterpretationProcess is monitoring task_GenerateResponseProcess_started, it doesn't recognize this change.
Solution
Correct the Variable Passing in Process Creation
Ensure that each process receives the correct shared variables. Specifically, pass task_ImageInterpretationProcess_started to the ImageInterpretationProcess instead of task_GenerateResponseProcess_started.
Updated Process Creation:
if __name__ == "__main__":
multiprocessing.freeze_support()
manager = Manager()
# Shared flags
ImageInterpretation = manager.Value('b', False)
TranscriptProcessor = manager.Value('b', False)
GenerateLLMResponse = manager.Value('b', False)
Wispper = manager.Value('b', False)
# Task-specific flags
task_GenerateResponseProcess_started = manager.Value('b', False)
task_ImageInterpretationProcess_started = manager.Value('b', False)
# Queues
input_queue_1 = manager.Queue()
input_queue_2 = manager.Queue()
input_queue_3 = manager.Queue()
input_queue_4 = manager.Queue()
output_queue_1 = manager.Queue()
output_queue_2 = manager.Queue()
output_queue_3 = manager.Queue()
output_queue_4 = manager.Queue()
request_queues_1 = manager.dict()
request_queues_2 = manager.dict()
request_queues_3 = manager.dict()
request_queues_4 = manager.dict()
# Creating and starting processes with correct variables
TPP = Process(target=TranscriptProcessorProcess(input_queue_1, output_queue_1, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper)._run)
# **Fixed:** Pass task_ImageInterpretationProcess_started to ImageInterpretationProcess
IIP = Process(target=ImageInterpretationProcess(input_queue_2, output_queue_2, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_ImageInterpretationProcess_started)._run)
GRP = Process(target=GenerateResponseProcess(input_queue_3, output_queue_3, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_GenerateResponseProcess_started)._run)
processes = [TPP, IIP, GRP]
# Start all processes
for process in processes:
process.start()
# Start response handler threads
threading.Thread(target=handle_responses, args=(output_queue_1, request_queues_1), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_2, request_queues_2), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_3, request_queues_3), daemon=True).start()
threading.Thread(target=handle_responses, args=(output_queue_4, request_queues_4), daemon=True).start()
# Run the FastAPI app
uvicorn.run(app, host="127.0.0.1", port=5100)
# Ensure all processes are joined (optional, as uvicorn.run is blocking)
for p in processes:
p.join()
Additional Recommendations
Use Keyword Arguments:
To prevent such issues in the future, consider using keyword arguments when initializing your process classes. This makes it clear which variable is being passed and reduces the risk of mixing them up.
Improve Logging:
Enhance your logging to include more detailed information about the state of shared variables and process actions. This can significantly aid in debugging.
Validate Shared Variables:
Implement checks to ensure that all shared variables are correctly initialized and passed to their respective processes.
Consider Using multiprocessing.Process Classes Directly:
Instead of embedding the logic within classes and then invoking a _run method, consider subclassing multiprocessing.Process directly. This can lead to clearer and more maintainable code.
from multiprocessing import Process
class ImageInterpretationProcess(Process):
def __init__(self, input_queue, output_queue, ImageInterpretation, TranscriptProcessor, GenerateLLMResponse, Wispper, task_ImageInterpretationProcess_started):
super().__init__()
self.input_queue = input_queue
self.output_queue = output_queue
# ... initialize other variables
def run(self):
asyncio.run(self.Qwen_interpretation())
By implementing the above correction and recommendations, the ImageInterpretationProcess should correctly recognize when task_ImageInterpretationProcess_started is set to True, thereby initiating the intended processing.
Summary:
Ensure that the ImageInterpretationProcess is initialized with task_ImageInterpretationProcess_started instead of task_GenerateResponseProcess_started. This alignment will allow the process to correctly detect when it should commence image interpretation.