8000 Timeout context manager should be used inside a task - botbuilder.ai.qna - qnaMaker.get_answers · Issue #1187 · microsoft/botbuilder-python · GitHub
[go: up one dir, main page]

Skip to content
Timeout context manager should be used inside a task - botbuilder.ai.qna - qnaMaker.get_answers #1187
@vijaysaimutyala

Description

@vijaysaimutyala

Version

botbuilder.ai 4.9

Describe the bug

Timeout context manager should be used inside a task when using QnAMaker.get_answers

To Reproduce

Steps to reproduce the behavior:
Below is my code. I check for the intent of a text from user and if it fails, I try to get the answer from QnA Maker. This is resulting in a timeout error.

from botbuilder.core import ActivityHandler, TurnContext, MessageFactory, IntentScore
from botbuilder.schema import ChannelAccount,Attachment
from botbuilder.ai.luis import LuisApplication,LuisPredictionOptions,LuisRecognizer
from botbuilder.ai.qna import QnAMakerEndpoint,QnAMakerOptions,QnAMaker
from typing import List
import os
import json
import os.path
from usecases import SimpleUseCase


class Bot(ActivityHandler):

    def __init__(self):
        luisApp = LuisApplication("","","")
        luisOptions = LuisPredictionOptions(include_all_intents=True,include_instance_data=True)
        self.LuisRecog = LuisRecognizer(luisApp,luisOptions)
        qna_endpoint = QnAMakerEndpoint("","","")
        qna_options = QnAMakerOptions(score_threshold=0.5)
        self.qnaMaker = QnAMaker(qna_endpoint)

    async def on_members_added_activity(
        self, members_added: List[ChannelAccount], turn_context: TurnContext
    ):
        for member in members_added:
            # Greet anyone that was not the target (recipient) of this message.
            # To learn more about Adaptive Cards, see https://aka.ms/msbot-adaptivecards for more details.
            if member.id != turn_context.activity.recipient.id:
                welcome_card = self.create_adaptive_card_attachment()
                response = MessageFactory.attachment(welcome_card)
                await turn_context.send_activity(response)

    # Load attachment from file.
    def create_adaptive_card_attachment(self):
        relative_path = os.path.abspath(os.path.dirname(__file__))
        path = os.path.join(relative_path, "cards/welcomeCard.json")
        with open(path) as in_file:
            card = json.load(in_file)

        return Attachment(
            content_type="application/vnd.microsoft.card.adaptive", content=card
        )

    async def greetings(self,turn_context):
        await turn_context.send_activity(MessageFactory.text("from inside greetings"))

    async def on_message_activity(self, turn_context: TurnContext):
        luisResult = await self.LuisRecog.recognize(turn_context) 
        print(luisResult.get_top_scoring_intent())
        intent = LuisRecognizer.top_intent(luisResult,min_score=0.40)

        if turn_context.activity.text.lower() == 'hi':
            await self.greetings(turn_context)
            await turn_context.send_activity(MessageFactory.text("message sent from send greetings.."))
        else:
            if intent != "None":
                response = await SimpleUseCase().someUseCase(turn_context)
                await turn_context.send_activity(response)
            else:
                await turn_context.send_activity(MessageFactory.text("Did not finda any use cases..checking QnA Maker..."))
                answers = await self.qnaMaker.get_answers(turn_context)
                print(answers)
                await turn_context.send_activity(MessageFactory.text(answers[0].answer))     
from quart import Quart, request, Response
from botbuilder.core import (
    BotFrameworkAdapterSettings,
    ConversationState,
    MemoryStorage,
    UserState,
)
from botbuilder.schema import Activity

from bot import Bot

from adapter_with_error_handler import AdapterWithErrorHandler

app = Quart(__name__, instance_relative_config=True)
app.config.from_object("config.DefaultConfig")

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
SETTINGS = BotFrameworkAdapterSettings(app.config["APP_ID"], app.config["APP_PASSWORD"])

# Create MemoryStorage, UserState and ConversationState
MEMORY = MemoryStorage()
USER_STATE = UserState(MEMORY)
CONVERSATION_STATE = ConversationState(MEMORY)

# Create adapter.
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
ADAPTER = AdapterWithErrorHandler(SETTINGS, CONVERSATION_STATE)

# Create dialogs and Bot
BOT = Bot()


# Listen for incoming requests on /api/messages
@app.route("/api/messages", methods=["POST"])
async def messages():
    # Main bot message handler.
    if "application/json" in request.headers["Content-Type"]:
        body = await request.json
    else:
        return Response("", status=415)

    activity = Activity().deserialize(body)
    auth_header = (
        request.headers["Authorization"] if "Authorization" in request.headers else ""
    )

    try:
        await ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
        return Response("", status=201)
    except Exception as exception:
        raise exception


@app.route("/", methods=["GET"])
async def homepage():
    try:
        return "Yes I'm working brother."
    except Exception as exception:
        raise exception
    
if __name__ == "__main__":
    try:
        app.run()  # nosec debug
    except Exception as exception:
        raise exception

Expected behavior

I should be receiving answer from QnAMaker. I've tried the QnAMaker component individually and it worked well without this issue

Screenshots

image

Additional context

I'm using the Quart samples to build the bot. I've tried using the REST API for QnAMaker with the requests module and it worked without any issues. Also, I ran this with Flask and asyncio and that too worked without any issues.

Metadata

Metadata

Assignees

Labels

Area: AI-QnAMakerThe issue is related to QnA MakerBot ServicesRequired for internal Azure reporting. Do not delete. Do not change color.backlogThe issue is out of scope for the current iteration but it will be evaluated in a future release.customer-replied-toIndicates that the team has replied to the issue reported by the customer. Do not delete.customer-reportedIssue is created by anyone that is not a collaborator in the repository.feature-requestA request for new functionality or an enhancement to an existing one.

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions

    0