-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWatsonAssistantV2Utility.py
161 lines (123 loc) · 4.79 KB
/
WatsonAssistantV2Utility.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#!/usr/bin/env python3
"""
A Watson-Assistant Utility/Interface for the API v2.
Copyright (C) 2019 Peter Maar
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
"""
from watson_developer_cloud import AssistantV2, assistant_v2
from watson_developer_cloud.watson_service import WatsonApiException
from time import sleep
from Logger import log
DEBUG = True
# 0 Dallas, 1 Washington DC, 2 Frankfurt, 3 Sydney, 4 Tokyo, 5 London
LOCATION_NUMBER = 1
url_locations = ["", "-wdc", "-fra", "-syd", "-tok", "-lon"]
url_location = url_locations[LOCATION_NUMBER]
def timed_print(text):
for char in text:
log(char, end='')
if not DEBUG:
sleep(0.01)
def display_response(response_lines):
""" Displays the lines of the response """
for line in response_lines:
rt = line["response_type"]
# Bot gave text, so show it
if rt == "text":
timed_print(line['text'])
# Bot 'typing' or waiting, so wait for a moment
elif rt == "pause":
if line['typing']:
log('User is typing...')
# Sleep for typing duration (or just print it if debugging mode)
seconds = line['time'] / 1000 # Convert from ms to s
if DEBUG:
log(seconds, "second sleep")
else:
sleep(seconds)
elif rt == "option":
log(line['title'])
for o in line['options']:
log(o['label'], ": ", o['value']['input']['text'], sep="")
# Short pause between anything, even if no 'typing' (unless debugging mode)
if not DEBUG:
sleep(0.1)
log() # Newline
class WatsonAssistant:
def __init__(self, version, api_key, assistant_id):
self.version = version
self.api_key = api_key
self.assistant_id = assistant_id
self.assistant = None
self.session_id = None
self.connect()
def connect(self):
"""
Start the session
"""
# Create assistant object
self.assistant = AssistantV2(
version=self.version,
iam_apikey=self.api_key,
url='https://gateway' + url_location + '.watsonplatform.net/assistant/api'
)
# Start a session
self.session_id = self.assistant.create_session(
assistant_id=self.assistant_id
).get_result()["session_id"]
def disconnect(self):
"""
End the session
"""
try:
self.assistant.delete_session(self.assistant_id, self.session_id)
except WatsonApiException:
log("Problem with disconnecting an Assistant. Ignoring.")
log("Disconnected")
def message(self, text, context, loopAgain=True):
"""
Send a message from the user to the assistant, and get the response.
:param text: The text to send.
:param context: The context to send.
:return: The assistant's response and the context
"""
text = text.replace('\t', ' ').replace('\n', ' ').replace('\r', ' ')
if text.lower() == 'exit':
self.disconnect()
return
# Create InputData object for text to send
opt = assistant_v2.MessageInputOptions(return_context=True)
message_input = assistant_v2.MessageInput(text=text, options=opt)
try:
response = self.assistant.message(
assistant_id=self.assistant_id,
session_id=self.session_id,
input=message_input,
context=context
).get_result()
except WatsonApiException:
if loopAgain:
log("Exception occurred sending message to assistant, probably timed out. Reconnecting...")
self.connect()
log("Trying again...")
return self.message(text, context, loopAgain=False)
else:
return "", context
# Get just the array of the different lines (text, pause, etc)
lines = response["output"]["generic"]
# Get just the context dictionary
context = response['context']
if DEBUG:
log("------------------")
log(response)
log("------------------")
return lines, context