8000 Added 11.qnamaker (#429) · itsmokha/botbuilder-python@435e77b · GitHub
[go: up one dir, main page]

Skip to content

Commit 435e77b

Browse files
tracyboehreraxelsrz
authored andcommitted
Added 11.qnamaker (microsoft#429)
1 parent f7ae133 commit 435e77b

File tree

8 files changed

+459
-0
lines changed

8 files changed

+459
-0
lines changed

samples/11.qnamaker/README.md

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
# QnA Maker
2+
3+
Bot Framework v4 QnA Maker bot sample
4+
5+
This bot has been created using [Bot Framework](https://dev.botframework.com), it shows how to create a bot that uses the [QnA Maker Cognitive AI](https://www.qnamaker.ai) service.
6+
7+
The [QnA Maker Service](https://www.qnamaker.ai) enables you to build, train and publish a simple question and answer bot based on FAQ URLs, structured documents or editorial content in minutes. In this sample, we demonstrate how to use the QnA Maker service to answer questions based on a FAQ text file used as input.
8+
9+
## Prerequisites
10+
11+
This samples **requires** prerequisites in order to run.
12+
13+
### Overview
14+
15+
This bot uses [QnA Maker Service](https://www.qnamaker.ai), an AI based cognitive service, to implement simple Question and Answer conversational patterns.
16+
17+
### Create a QnAMaker Application to enable QnA Knowledge Bases
18+
19+
QnA knowledge base setup and application configuration steps can be found [here](https://aka.ms/qna-instructions).
20+
21+
## Running the sample
22+
- Clone the re 8000 pository
23+
```bash
24+
git clone https://github.com/Microsoft/botbuilder-python.git
25+
```
26+
- Activate your desired virtual environment
27+
- Bring up a terminal, navigate to `botbuilder-python\samples\11.qnamaker` folder
28+
- In the terminal, type `pip install -r requirements.txt`
29+
- Update `QNA_KNOWLEDGEBASE_ID`, `QNA_ENDPOINT_KEY`, and `QNA_ENDPOINT_HOST` in `config.py`
30+
- In the terminal, type `python app.py`
31+
32+
## Testing the bot using Bot Framework Emulator
33+
[Microsoft Bot Framework Emulator](https://github.com/microsoft/botframework-emulator) is a desktop application that allows bot developers to test and debug their bots on localhost or running remotely through a tunnel.
34+
35+
- Install the Bot Framework emulator from [here](https://github.com/Microsoft/BotFramework-Emulator/releases)
36+
37+
### Connect to bot using Bot Framework Emulator
38+
- Launch Bot Framework Emulator
39+
- File -> Open Bot
40+
- Paste this URL in the emulator window - http://localhost:3978/api/messages
41+
42+
## QnA Maker service
43+
44+
QnA Maker enables you to power a question and answer service from your semi-structured content.
45+
46+
One of the basic requirements in writing your own bot is to seed it with questions and answers. In many cases, the questions and answers already exist in content like FAQ URLs/documents, product manuals, etc. With QnA Maker, users can query your application in a natural, conversational manner. QnA Maker uses machine learning to extract relevant question-answer pairs from your content. It also uses powerful matching and ranking algorithms to provide the best possible match between the user query and the questions.
47+
48+
## Further reading
49+
50+
- [Bot Framework Documentation](https://docs.botframework.com)
51+
- [Bot Basics](https://docs.microsoft.com/azure/bot-service/bot-builder-basics?view=azure-bot-service-4.0)
52+
- [QnA Maker Documentation](https://docs.microsoft.com/en-us/azure/cognitive-services/qnamaker/overview/overview)
53+
- [Activity processing](https://docs.microsoft.com/en-us/azure/bot-service/bot-builder-concept-activity-processing?view=azure-bot-service-4.0)
54+
- [QnA Maker CLI](https://github.com/Microsoft/botbuilder-tools/tree/master/packages/QnAMaker)
55+
- [Channels and Bot Connector Service](https://docs.microsoft.com/en-us/azure/bot-service/bot-concepts?view=azure-bot-service-4.0)
56+
- [Azure Portal](https://portal.azure.com)

samples/11.qnamaker/app.py

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
import asyncio
5+
import sys
6+
from datetime import datetime
7+
8+
from flask import Flask, request, Response
9+
from botbuilder.core import BotFrameworkAdapterSettings, TurnContext, BotFrameworkAdapter
10+
from botbuilder.schema import Activity, ActivityTypes
11+
12+
from bots import QnABot
13+
14+
# Create the loop and Flask app
15+
LOOP = asyncio.get_event_loop()
16+
app = Flask(__name__, instance_relative_config=True)
17+
app.config.from_object("config.DefaultConfig")
18+
19+
# Create adapter.
20+
# See https://aka.ms/about-bot-adapter to learn more about how bots work.
21+
SETTINGS = BotFrameworkAdapterSettings(app.config["APP_ID"], app.config["APP_PASSWORD"])
22+
ADAPTER = BotFrameworkAdapter(SETTINGS)
23+
24+
25+
# Catch-all for errors.
26+
async def on_error(context: TurnContext, error: Exception):
27+
# This check writes out errors to console log .vs. app insights.
28+
# NOTE: In production environment, you should consider logging this to Azure
29+
# application insights.
30+
print(f"\n [on_turn_error] unhandled error: {error}", file=sys.stderr)
31+
32+
# Send a message to the user
33+
await context.send_activity("The bot encountered an error or bug.")
34+
await context.send_activity("To continue to run this bot, please fix the bot source code.")
35+
# Send a trace activity if we're talking to the Bot Framework Emulator
36+
if context.activity.channel_id == 'emulator':
37+
# Create a trace activity that contains the error object
38+
trace_activity = Activity(
39+
label="TurnError",
40+
name="on_turn_error Trace",
41+
timestamp=datetime.utcnow(),
42+
type=ActivityTypes.trace,
43+
value=f"{error}",
44+
value_type="https://www.botframework.com/schemas/error"
45+
)
46+
# Send a trace activity, which will be displayed in Bot Framework Emulator
47+
await context.send_activity(trace_activity)
48+
49+
ADAPTER.on_turn_error = on_error
50+
51+
# Create the Bot
52+
BOT = QnABot(app.config)
53+
54+
# Listen for incoming requests on /api/messages
55+
@app.route("/api/messages", methods=["POST"])
56+
def messages():
57+
# Main bot message handler.
58+
if "application/json" in request.headers["Content-Type"]:
59+
body = request.json
60+
else:
61+
return Response(status=415)
62+
63+
activity = Activity().deserialize(body)
64+
auth_header = (
65+
request.headers["Authorization"] if "Authorization" in request.headers else ""
66+
)
67+
68+
try:
69+
task = LOOP.create_task(
70+
ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
71+
)
72+
LOOP.run_until_complete(task)
73+
return Response(status=201)
74+
except Exception as exception:
75+
raise exception
76+
77+
78+
if __name__ == "__main__":
79+
try:
80+
app.run(debug=False, port=app.config["PORT"]) # nosec debug
81+
except Exception as exception:
82+
raise exception

samples/11.qnamaker/bots/__init__.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from .qna_bot import QnABot
5+
6+
__all__ = ["QnABot"]

samples/11.qnamaker/bots/qna_bot.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Copyright (c) Microsoft Corporation. All rights reserved.
2+
# Licensed under the MIT License.
3+
4+
from flask import Config
5+
6+
from botbuilder.ai.qna import QnAMaker, QnAMakerEndpoint
7+
from botbuilder.core import ActivityHandler, MessageFactory, TurnContext
8+
from botbuilder.schema import ChannelAccount
9+
10+
11+
class QnABot(ActivityHandler):
12+
def __init__(self, config: Config):
13+
self.qna_maker = QnAMaker(
14+
QnAMakerEndpoint(
15+
knowledge_base_id=config["QNA_KNOWLEDGEBASE_ID"],
16+
endpoint_key=config["QNA_ENDPOINT_KEY"],
17+
host=config["QNA_ENDPOINT_HOST"],
18+
)
19+
)
20+
21+
async def on_members_added_activity(
22+
self, members_added: [ChannelAccount], turn_context: TurnContext
23+
):
24+
for member in members_added:
25+
if member.id != turn_context.activity.recipient.id:
26+
await turn_context.send_activity(
27+
"Welcome to the QnA Maker sample! Ask me a question and I will try "
28+
"to answer it."
29+
)
30+
31+
async def on_message_activity(self, turn_context: TurnContext):
32+
# The actual call to the QnA Maker service.
33+
response = await self.qna_maker.get_answers(turn_context)
34+
if response and len(response) > 0:
35+
await turn_context.send_activity(MessageFactory.text(response[0].answer))
36+
else:
37+
await turn_context.send_activity("No QnA Maker answers were found.")
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
Question Answer Source Keywords
2+
Question Answer 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Source
3+
My Contoso smart light won't turn on. Check the connection to the wall outlet to make sure it's plugged in properly. 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
4+
Light won't turn on. Check the connection to the wall outlet to make sure it's plugged in properly. 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
5+
My smart light app stopped responding. Restart the app. If the problem persists, contact support. 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
6+
How do I contact support? Email us at service@contoso.com 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
7+
I need help. Email us at service@contoso.com 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
8+
I upgraded the app and it doesn't work anymore. When you upgrade, you need to disable Bluetooth, then re-enable it. After re-enable, re-pair your light with the app. 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
9+
Light doesn't work after upgrade. When you upgrade, you need to disable Bluetooth, then re-enable it. After re-enable, re-pair your light with the app. 96207418-4609-48df-9cbc-dd35a71e83f7-KB.tsv Editorial
10+
Question Answer 890b1efc-27ad-4dca-8dcb-b20d29d50e14-KB.tsv Source
11+
Who should I contact for customer service? Please direct all customer service questions to (202) 555-0164 \n 890b1efc-27ad-4dca-8dcb-b20d29d50e14-KB.tsv Editorial
12+
Why does the light not work? The simplest way to troubleshoot your smart light is to turn it off and on. \n 890b1efc-27ad-4dca-8dcb-b20d29d50e14-KB.tsv Editorial
13+
How long does the light's battery last for? The battery will last approximately 10 - 12 weeks with regular use. \n 890b1efc-27ad-4dca-8dcb-b20d29d50e14-KB.tsv Editorial
14+
What type of light bulb do I need? A 26-Watt compact fluorescent light bulb that features both energy savings and long-life performance. 890b1efc-27ad-4dca-8dcb-b20d29d50e14-KB.tsv Editorial
15+
Hi Hello Editorial

samples/11.qnamaker/config.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) Microsoft Corporation. All rights reserved.
3+
# Licensed under the MIT License.
4+
5+
import os
6+
7+
""" Bot Configuration """
8+
9+
10+
class DefaultConfig:
11+
""" Bot Configuration """
12+
13+
PORT = 3978
14+
APP_ID = os.environ.get("MicrosoftAppId", "")
15+
APP_PASSWORD = os.environ.get("MicrosoftAppPassword", "")
16+
QNA_KNOWLEDGEBASE_ID = os.environ.get("QnAKnowledgebaseId", "")
17+
QNA_ENDPOINT_KEY = os.environ.get("QnAEndpointKey", "")
18+
QNA_ENDPOINT_HOST = os.environ.get("QnAEndpointHostName", "")

0 commit comments

Comments
 (0)
0