如果用户等待很长时间并开始新的请求,我需要取消请求

I need to cancel request if user waiting to long and start new one

提问人:Bohdan Liutko 提问时间:11/16/2023 更新时间:11/16/2023 访问量:22

问:

我正在使用 aoigram 构建电报聊天机器人,所以一切都是异步的,我需要连接 openai 一旦用户发送 reuest 并等待很长时间或改变主意,我希望他能够取消它,并在需要时开始一个新的 所以它应该用 /start 取消 在这里我所拥有的


@dp.message_handler(Regexp(r'.*/start.*'), state='*')
async def start(message: types.Message, state: FSMContext):
    chat_id = message.chat.id
    global ongoing_tasks
    if chat_id in ongoing_tasks and not ongoing_tasks[chat_id].done():
        ongoing_tasks[chat_id].cancel()
        del ongoing_tasks[chat_id]
    current_state = await state.get_state()
    if current_state:
        await state.finish()

在这里,用户将发送请求

@dp.message_handler(state=TaskCreation.ImprovementDetails)
async def process_improvement_details(message: types.Message, state: FSMContext):
    improvement_details = message.text
    global running_tasks

    chat_id = message.chat.id
    start_time = time.time()
    await message.answer('Треба подумати кілька секунд)')

    user_data = await state.get_data()
    description = user_data.get("description")
    response_text = ""
    if improvement_details != "":
        response_text = ""

        # improvement_details = None  # or some default value
    if chat_id in ongoing_tasks and not ongoing_tasks[chat_id].done():
        ongoing_tasks[chat_id].cancel()
    task = asyncio.create_task(
        send_request("generate_response/", {"text": message.text, "chat_id": chat_id})
    )
    ongoing_tasks[chat_id] = task
    try:
        response = await task
        await wait_for_response(response, message) # here just igame that appear once waiting for responce
   except asyncio.CancelledError:
            await message.answer("Task was cancelled.")
            return
    finally:
        # Cleanup the task from the tracking dictionary
        if chat_id in ongoing_tasks:
            del ongoing_tasks[chat_id]

以及我如何发送请求

    url = urljoin(BACKEND_URL, endpoint)
    async with aiohttp.ClientSession() as session:
        try:
            async with session.post(url, json=data) as response:
                if response.status == 200:
                    return await response.json()
                else:
                    print(f"Error: Server responded with status code {response.status}")
                    return None
        except aiohttp.ClientError as e:
            print(f"Connection error: {e}")
            return None```



once I type /start to cancel it all during waiting for response here what I have


`Connection error: HTTPConnectionPool(host='46.101.4.220', port=32191): Max retries exceeded with url: /gen/ (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x000001FCCD269790>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it'))
`


please help 
python 服务器 请求 人工智能 aiohttp

评论

0赞 matszwecja 11/16/2023
docs.aiohttp.org/en/stable/client_quickstart.html#timeouts
0赞 Bohdan Liutko 11/17/2023
@matszwecja因此,如果用户改变主意,用户将发送响应和想法,这样他就可以键入/start,然后返回主菜单。因为现在我只收到连接错误错误:HTTPConnectionPool(host='', port=): Max retries exceeded with URL,因为一旦用户键入/start,它将重置它应该向服务器发送另一个请求的历史记录#

答: 暂无答案