def create_connection(): try: global watsonAssistant watsonAssistant = AssistantV2(iam_apikey=ASSISTANT_APIKEY, version=ASSISTANT_VERSION, url=ASSISTANT_URL) print("Connected To IBM server") return watsonAssistant except WatsonApiException as ex: print("Method failed with status code " + str(ex.code) + ": " + ex.message) return "Service unavailable (connection)"
def loadAndInit(confFile=None): # Credentials are read from a file with open(confFile) as confFile: config = json.load(confFile) configWA = config['credentials'] global assistantService # Initialize the Watson Assistant client, use API V2 if 'username' in configWA: assistantService = AssistantV2( username=configWA['username'], password=configWA['password'], version=configWA['versionV2'], url=configWA['url']) elif 'apikey' in configWA: assistantService = AssistantV2( iam_apikey=configWA['apikey'], version=configWA['versionV2'], url=configWA['url']) else: print('Expected either username / password or apikey in credentials.') exit
def __init__(self, apikey, asst_id): self.assistant = AssistantV2(version="2019-02-16", iam_apikey=apikey) self.assistant_id = asst_id self.session = self.assistant.create_session( self.assistant_id).get_result() self.session_id = self.session["session_id"] self.pass_date = {} self.case = Case() self.context = None print("Watson assistant session details: {}".format( json.dumps(self.session))) return None
def __init__(self, name): super().__init__() self.name = name self.discovery = DiscoveryV1(version='2018-08-01', url='insert-watson-url', iam_apikey='insert-api-key') self.discovery_env_id = 'insert-env-id' self.discovery_col_id = 'insert-col-id' self.assistant_id = 'insert-assistant-id' self.assistant = AssistantV2(iam_apikey='insert-api-key', version='2018-11-08', url='insert-url') self.assistant_session_id = self.assistant.create_session( assistant_id=self.assistant_id).get_result()['session_id']
from __future__ import print_function import json from watson_developer_cloud import AssistantV2 ######################### # Credentials ######################### assistant = AssistantV2( version='2018-09-20', url='https://gateway-fra.watsonplatform.net/assistant/api', iam_apikey='AAAA') assistant_id = 'BBBB' ######################### # Sessions ######################### session = assistant.create_session(assistant_id).get_result() session_id = session["session_id"] #print("Dump session..." + json.dumps(session, indent=2)) ######################### # Message ######################### message = assistant.message( assistant_id, session_id, input={ 'text': 'What is Kodi?' }, ).get_result()
def assistant(): """End point dedicated to communicate with the user as assistant 'Yelp Voice'""" message = '' number = '' twilio_number = '' global sessionID assistant = AssistantV2(username=watson_username, password=watson_password, url=watson_url, version=watson_version) if request.values.get('SpeechResult'): print(message) message = request.values['SpeechResult'] if request.values.get('From'): number = request.values['From'] if request.values.get('To'): twilio_number = request.values['To'] twilio_response = VoiceResponse() gather = Gather(input='speech', action='/assistant', speechTimeout='auto') # print(sessionID) if sessionID == "": session = assistant.create_session(watson_assistanceID).get_result() sessionID = session['session_id'] print("message: {}".format(message)) if message != '': watson_call = assistant.message(watson_assistanceID, sessionID, options={'return_context': 'true'}, input={'text': message}) response_watson = watson_call.get_result() print(json.dumps(response_watson, indent=1)) if (len(response_watson['output']['generic']) > 0): for intern_response in response_watson['output']['generic']: if intern_response['response_type'] == 'text': print(intern_response['text']) flag_variable = "" flag_values = "" if len(intern_response['text'].split("::")) > 1: flag_variable = intern_response['text'].split( "::")[0].strip() flag_values = intern_response['text'].split( "::")[1].strip() if flag_variable == "{restaurant}": gather.say( 'sure, I will let you know about some restaurants nearby', voice='alice') gather.say(getRestaurantList(flag_values), voice='alice') elif (len(response_watson['output']['intents']) > 0): for intern_intent in response_watson['output'][ 'intents']: if intern_intent["intent"] == "No" or intern_intent[ "intent"] == "General_Ending": twilio_response.say(intern_response['text'], voice='alice') assistant.delete_session( watson_assistanceID, sessionID) sessionID = "" gather.pause(2) twilio_response.hangup() else: gather.say(intern_response['text'], voice='alice') else: gather.say(intern_response['text'], voice='alice') gather.pause(4) gather.say('Is there other question that I can answer?', voice='alice') else: response_watson = assistant.message(watson_assistanceID, sessionID, options={ 'return_context': 'true' }, input={ 'text': login(number) }).get_result() if (len(response_watson['output']['generic']) > 0): for intern_response in response_watson['output']['generic']: if intern_response['response_type'] == 'text': print(intern_response['text']) gather.say(intern_response['text'], voice='alice') gather.pause(3) gather.say( 'Remember, you can know what the people is thinking about some store or business. Just ask: Yelp, let me know about Thai Restaurants.', voice='alice') twilio_response.append(gather) return str(twilio_response)
def __init__(self, API_KEY, URL, enviornment_id, collection_id, NLU_API_KEY, NLU_URL, ASSISTANT_API_KEY, ASSISTANT_URL, ASSISSTANT_ID, S2T_KEY, S2T_URL, SMMRY_API_KEY): ''' Initialize a hindsight chatbot :param API_KEY: IBM Watson Discovery API Key :param URL: IBM Watson Discovery base url :param enviornment_id: IBM Enviornment id :param collection_id: IBM document collection id :return: ''' self.chat_states = {'add_mode': 1, 'ask_mode': 2} self.speech_mode_enabled = False self.intents = { 'show_notes': 1, 'summarize_notes': 2, 'sentiment_notes': 3 } self.state = self.chat_states['add_mode'] self.prompt = '>>> ' self.chatprompt = '\t~~~ ' self.state_prompt = 'Add a note: ' self.discovery = DiscoveryV1(version='2018-12-03', iam_apikey=API_KEY, url=URL) self.nlu = NaturalLanguageUnderstandingV1(version='2018-11-16', iam_apikey=NLU_API_KEY, url=NLU_URL) self.assistant = AssistantV2(version='2018-11-08', iam_apikey=ASSISTANT_API_KEY, url=ASSISTANT_URL) self.session_id = self.assistant.create_session( assistant_id=ASSISSTANT_ID).get_result()['session_id'] self.enviornment_id = enviornment_id self.collection_id = collection_id self.assistant_id = ASSISSTANT_ID self.ROOT_PATH = sys.path[0] self.METADATA_PATH = self.ROOT_PATH + '/notes_metadata' if not os.path.exists(self.METADATA_PATH): os.makedirs(self.METADATA_PATH) self.GLOBAL_ENTITIES = self.ROOT_PATH + '/notes_metadata/global_entities.p' if not os.path.exists(self.GLOBAL_ENTITIES): t = {'NULL': 0} pickle.dump(t, open(self.GLOBAL_ENTITIES, "wb")) self.GLOBAL_DOC_IDS = self.ROOT_PATH + '/notes_metadata/global_doc_ids.p' if not os.path.exists(self.GLOBAL_DOC_IDS): t = {'NULL': '/'} pickle.dump(t, open(self.GLOBAL_DOC_IDS, "wb")) self.NOTES_PATH = self.ROOT_PATH + '/notes.html' if not os.path.exists(self.NOTES_PATH): os.makedirs(self.NOTES_PATH) self.INTENT_LINES = [] if not os.path.exists(self.ROOT_PATH + '/intent_training_data.csv'): print('!!! ERROR: ./scripts/intent_training_data.csv required') quit() lines = open(self.ROOT_PATH + '/intent_training_data.csv').readlines() self.INTENT_LINES = [l.strip().split(',')[0] for l in lines] self.S2T_KEY = S2T_KEY self.S2T_URL = S2T_URL self.pyAudio = pyaudio.PyAudio() self.SMMRY_API_KEY = SMMRY_API_KEY
from __future__ import print_function import json from watson_developer_cloud import AssistantV2 # If service instance provides API key authentication # assistant = AssistantV2( # version='2017-04-21', # ## url is optional, and defaults to the URL below. Use the correct URL for your region. # url='https://gateway.watsonplatform.net/assistant/api', # iam_apikey='iam_apikey') assistant = AssistantV2( username='******', password='******', ## url is optional, and defaults to the URL below. Use the correct URL for your region. url='https://gateway.watsonplatform.net/assistant/api', version='2017-04-21') ######################### # Sessions ######################### session = assistant.create_session("<YOUR ASSISTANT ID>").get_result() print(json.dumps(session, indent=2)) assistant.delete_session("<YOUR ASSISTANT ID>", "<YOUR SESSION ID>").get_result() ######################### # Message #########################
from watson_developer_cloud import AssistantV2 import json service = AssistantV2( version='2018-11-08', iam_apikey='BtmOQOR6pEBs-wtg2HyeUdLw_4lVpPech-dJ7Yte_1Cr', url='https://gateway-wdc.watsonplatform.net/assistant/api') sessionID = service.create_session( assistant_id='d3bdd0a5-4f23-490b-98d4-1e258befb228').get_result() print( "Hello. Welcome to SecAware! What can I help you with? I can help you learn about various IT concepts." ) user_text = input("Respond, then press ENTER.") while (user_text != "exit" or user_text != "quit"): response = service.message( assistant_id='d3bdd0a5-4f23-490b-98d4-1e258befb228', session_id=sessionID["session_id"], input={ 'message_type': 'text', 'text': user_text }).get_result() text_response = json.dumps(response) text_response = response["output"]["generic"][0]["text"] print(text_response)
def load_user(uid): return User(uid, getUser(uid)) ############ ### CHAT ### ############ # Secret Key to use for session app.config.update(SECRET_KEY='aoun@ibm') ## Watson Assistant ## api, url = getService('assistant') authenticator = IAMAuthenticator(api) assistant = AssistantV2(version='2020-09-24', authenticator=authenticator) assistant.set_service_url(url) ASSISTANT_ID = "12345" ## Chat page ## @app.route('/chat') def chat(): ## Watson session context response = assistant.create_session(assistant_id=ASSISTANT_ID).get_result() session['session_id'] = response['session_id'] ## End Watson session context return render_template('chat.html')
def airecruiter(): """End point dedicated to communicate with the user as assistant""" # welcome_message = ['Wellcome to the AI Recruiter Tool...', # # 'How can I help you?', # 'You can ask for status of your licences, check the candidates growth in latest month, and even know the most used actions from recruiters.', # 'Just ask whenever you feel ready, saying Please let me know the candidates grow, for example...'] message = '' number = '' twilio_number = '' session = None assistant = AssistantV2(username=watson_username, password=watson_password, url=watson_url, version=watson_version) if request.values.get('SpeechResult'): message = request.values['SpeechResult'] if request.values.get('From'): number = request.values['From'] if request.values.get('To'): twilio_number = request.values['To'] twilio_response = VoiceResponse() gather = Gather(input='speech', action='/airecruiter', speechTimeout='auto') if session is None: session = assistant.create_session(watson_assistanceID).get_result() sessionID = session['session_id'] if message != '': print("message: {}".format(message)) message = assistant.message(watson_assistanceID, sessionID, input={ 'text': message }).get_result() if (len(message['output']['generic']) > 0): for intern_response in message['output']['generic']: if intern_response['response_type'] == 'text': print(intern_response['text']) if intern_response['text'] == "{userName}": messageApi = assistant.message(watson_assistanceID, sessionID, input={ 'text': login() }).get_result() if (len(messageApi['output']['generic']) > 0): for intern_api_response in messageApi['output'][ 'generic']: if intern_api_response[ 'response_type'] == 'text': print(intern_api_response['text']) gather.say(intern_api_response['text'], voice='alice') elif intern_response['text'] == "{growth}": gather.say( 'sure, I will let you know about the candidates growth in a second.', voice='alice') for idea_response in get_candidate_growth(): gather.say(idea_response, voice='alice') elif intern_response['text'] == "{resumeviewed}": gather.say( 'sure thing, I will let you know about the most recent resumes viewed.', voice='alice') for idea_response in most_viewed_resumes(): gather.say(idea_response, voice='alice') elif intern_response['text'] == "{actionused}": gather.say( 'hold on a second, I am collecting the data.', voice='alice') for idea_response in actions_used_by_recruiter(): gather.say(idea_response, voice='alice') elif (len(message['output']['intents']) > 0): for intern_intent in message['output']['intents']: if intern_intent["intent"] == "No" or intern_intent[ "intent"] == "General_Ending": twilio_response.say(intern_response['text'], voice='alice') gather.pause(2) twilio_response.hangup() else: gather.say(intern_response['text'], voice='alice') gather.pause(2) gather.say('Is there other question that I can answer?', voice='alice') else: message = assistant.message(watson_assistanceID, sessionID, input={ 'text': login() }).get_result() if (len(message['output']['generic']) > 0): for intern_response in message['output']['generic']: if intern_response['response_type'] == 'text': print(intern_response['text']) gather.say(intern_response['text'], voice='alice') gather.pause(2) gather.say( 'Remember, you can ask about the grow in candidates latest months. Just ask: "Alice, let me know the candidates grow."', voice='alice') twilio_response.append(gather) return str(twilio_response)