def respond(sender_id): request_params = request_parameters() if 'query' in request_params: message = request_params.pop('query') elif 'q' in request_params: message = request_params.pop('q') else: return error(400, "InvalidParameter", "Missing the message parameter.", { "parameter": "query", "in": "query" }) try: # Set the output channel out = CollectingOutputChannel() # Fetches the appropriate bot response in a json format responses = agent.handle_text(message, output_channel=out, sender_id=sender_id) return jsonify(responses) except Exception as e: logger.exception("Caught an exception during respond.") return error(500, "ActionException", "Server failure. Error: {}".format(e))
def log_message(sender_id): request_params = request.get_json(force=True) try: message = request_params["message"] except KeyError: message = request_params.get("text") sender = request_params.get("sender") parse_data = request_params.get("parse_data") verbosity = event_verbosity_parameter(EventVerbosity.AFTER_RESTART) # TODO: implement properly for agent / bot if sender != "user": return error( 500, "NotSupported", "Currently, only user messages can be passed " "to this endpoint. Messages of sender '{}' " "can not be handled. ".format(sender), { "parameter": "sender", "in": "body" }) try: usermsg = UserMessage(message, None, sender_id, parse_data) tracker = agent.log_message(usermsg) return jsonify(tracker.current_state(verbosity)) except Exception as e: logger.exception("Caught an exception while logging message.") return error(500, "MessageException", "Server failure. Error: {}".format(e))
def continue_training(): request.headers.get("Accept") epochs = request.args.get("epochs", 30) batch_size = request.args.get("batch_size", 5) request_params = request.get_json(force=True) sender_id = UserMessage.DEFAULT_SENDER_ID try: tracker = DialogueStateTracker.from_dict(sender_id, request_params, agent.domain.slots) except Exception as e: return error(400, "InvalidParameter", "Supplied events are not valid. {}".format(e), { "parameter": "", "in": "body" }) try: # Fetches the appropriate bot response in a json format agent.continue_training([tracker], epochs=epochs, batch_size=batch_size) return '', 204 except Exception as e: logger.exception("Caught an exception during prediction.") return error(500, "TrainingException", "Server failure. Error: {}".format(e))
def handle_actions(self, message, action_name): verbosity = self.event_verbosity_parameter( EventVerbosity.AFTER_RESTART) try: output_channel = CollectingOutputChannel() dispatcher = Dispatcher(message.sender_id, output_channel, self.agent.nlg) tracker = self.message_processor._get_tracker(message.sender_id) if tracker: #拿到action实例 action = self.ask_for_action( action_name, self.message_processor.action_endpoint, self.ask_for_action) # action = self._get_action(action_name) self.message_processor._run_action(action, tracker, dispatcher) # save tracker state to continue conversation from this state self.message_processor._save_tracker(tracker) # retrieve tracker and set to requested state tracker = self.agent.tracker_store.get_or_create_tracker( message.sender_id) state = tracker.current_state(verbosity) return jsonify({ "tracker": state, "messages": output_channel.messages }) except ValueError as e: return error(400, "ValueError", e) except Exception as e: return error(500, "ValueError", "Server failure. Error: {}".format(e))
def tracker_predict(): """ Given a list of events, predicts the next action""" sender_id = UserMessage.DEFAULT_SENDER_ID request_params = request.get_json(force=True) verbosity = event_verbosity_parameter(EventVerbosity.AFTER_RESTART) try: tracker = DialogueStateTracker.from_dict(sender_id, request_params, agent.domain.slots) except Exception as e: return error(400, "InvalidParameter", "Supplied events are not valid. {}".format(e), { "parameter": "", "in": "body" }) policy_ensemble = agent.policy_ensemble probabilities, policy = \ policy_ensemble.probabilities_using_best_policy(tracker, agent.domain) scores = [{ "action": a, "score": p } for a, p in zip(agent.domain.action_names, probabilities)] return jsonify({ "scores": scores, "policy": policy, "tracker": tracker.current_state(verbosity) })
def load_model(): """Loads a zipped model, replacing the existing one.""" if 'model' not in request.files: # model file is missing return error(400, "InvalidParameter", "You did not supply a model as part of your request.", { "parameter": "model", "in": "body" }) model_file = request.files['model'] logger.info("Received new model through REST interface.") zipped_path = tempfile.NamedTemporaryFile(delete=False, suffix=".zip") zipped_path.close() model_directory = tempfile.mkdtemp() model_file.save(zipped_path.name) logger.debug("Downloaded model to {}".format(zipped_path.name)) zip_ref = zipfile.ZipFile(zipped_path.name, 'r') zip_ref.extractall(model_directory) zip_ref.close() logger.debug("Unzipped model to {}".format( os.path.abspath(model_directory))) ensemble = PolicyEnsemble.load(model_directory) agent.policy_ensemble = ensemble logger.debug("Finished loading new agent.") return '', 204
def decorated(*args, **kwargs): if not agent.is_ready(): return error( 503, "NoAgent", "No agent loaded. To continue processing, a " "model of a trained agent needs to be loaded.", help_url=_docs("/server.html#running-the-http-server")) return f(*args, **kwargs)
def predict(sender_id): try: # Fetches the appropriate bot response in a json format responses = agent.predict_next(sender_id) return jsonify(responses) except Exception as e: logger.exception("Caught an exception during prediction.") return error(500, "PredictionException", "Server failure. Error: {}".format(e))
def execute_action(sender_id): request_params = request.get_json(force=True) action_to_execute = request_params.get("action", None) verbosity = event_verbosity_parameter(EventVerbosity.AFTER_RESTART) try: out = CollectingOutputChannel() agent.execute_action(sender_id, action_to_execute, out) # retrieve tracker and set to requested state tracker = agent.tracker_store.get_or_create_tracker(sender_id) state = tracker.current_state(verbosity) return jsonify({"tracker": state, "messages": out.messages}) except ValueError as e: return error(400, "ValueError", e) except Exception as e: logger.exception(e) return error(500, "ValueError", "Server failure. Error: {}".format(e))
def retrieve_tracker(sender_id): """Get a dump of a conversations tracker including its events.""" if not agent.tracker_store: return error( 503, "NoTrackerStore", "No tracker store available. Make sure to configure " "a tracker store when starting the server.") # parameters default_verbosity = EventVerbosity.AFTER_RESTART # this is for backwards compatibility if "ignore_restarts" in request.args: ignore_restarts = utils.bool_arg('ignore_restarts', default=False) if ignore_restarts: default_verbosity = EventVerbosity.ALL if "events" in request.args: include_events = utils.bool_arg('events', default=True) if not include_events: default_verbosity = EventVerbosity.NONE verbosity = event_verbosity_parameter(default_verbosity) until_time = request.args.get('until', None) # retrieve tracker and set to requested state tracker = agent.tracker_store.get_or_create_tracker(sender_id) if not tracker: return error( 503, "NoDomain", "Could not retrieve tracker. Most likely " "because there is no domain set on the agent.") if until_time is not None: tracker = tracker.travel_back_in_time(float(until_time)) # dump and return tracker state = tracker.current_state(verbosity) return jsonify(state)
def evaluate_stories(): """Evaluate stories against the currently loaded model.""" tmp_file = rasa_nlu.utils.create_temporary_file(request.get_data(), mode='w+b') use_e2e = utils.bool_arg('e2e', default=False) try: evaluation = run_story_evaluation(tmp_file, agent, use_e2e=use_e2e) return jsonify(evaluation) except ValueError as e: return error(400, "FailedEvaluation", "Evaluation could not be created. Error: {}" "".format(e))
def event_verbosity_parameter(default_verbosity): event_verbosity_str = request.args.get( 'include_events', default=default_verbosity.name).upper() try: return EventVerbosity[event_verbosity_str] except KeyError: enum_values = ", ".join([e.name for e in EventVerbosity]) abort( error( 404, "InvalidParameter", "Invalid parameter value for 'include_events'. " "Should be one of {}".format(enum_values), { "parameter": "include_events", "in": "query" }))
def get_domain(): """Get current domain in yaml or json format.""" accepts = request.headers.get("Accept", default="application/json") if accepts.endswith("json"): domain = agent.domain.as_dict() return jsonify(domain) elif accepts.endswith("yml"): domain_yaml = agent.domain.as_yaml() return Response(domain_yaml, status=200, content_type="application/x-yml") else: return error( 406, "InvalidHeader", """Invalid accept header. Domain can be provided as json ("Accept: application/json") or yml ("Accept: application/x-yml"). Make sure you've set the appropriate Accept header.""")
def append_event(sender_id): """Append a list of events to the state of a conversation""" request_params = request.get_json(force=True) evt = Event.from_parameters(request_params) tracker = agent.tracker_store.get_or_create_tracker(sender_id) verbosity = event_verbosity_parameter(EventVerbosity.AFTER_RESTART) if evt: tracker.update(evt) agent.tracker_store.save(tracker) return jsonify(tracker.current_state(verbosity)) else: logger.warning("robot_apiend event called, but could not extract a " "valid event. Request JSON: {}".format(request_params)) return error( 400, "InvalidParameter", "Couldn't extract a proper event from the request " "body.", { "parameter": "", "in": "body" })
def draw_main_menu(stdscr, window, menu, menu_bar): draw_background(stdscr) (win_h, win_w) = draw_window(stdscr, window, menu.title, menu_bar) x = 3 y = wrap_text(window, mainwindow_help_text, 1, x, win_w - 6) y = draw_legend(window, y, x, win_w - 6) menu_height = win_h - y - 3 lit_border(window, menu_height, win_w - 4, y, 2, raised=False) y += 1 menu_height -= 2 menu_bottom = menu_height + y menu_top = y x = 7 if menu.selection < menu.top: menu.top = menu.selection # Check if the menu could be scrolled up can_scroll_up = False for i in range(0, menu.top): if menu[i].can_enable() and menu[i].is_visible(): can_scroll_up = True break # Compute which menu items should be visible and scrolling menu_items = [] can_scroll_down = True for i in range(menu.top, len(menu.items)): if menu[i].can_enable() and menu[i].is_visible(): menu_items.append(i) if len(menu_items) >= menu_height: if menu.selection > i: menu_items = menu_items[1:] if len(menu_items) > 0: menu.top = menu_items[0] else: # Screen is too small to show any items raise _curses.error("Too small") can_scroll_up = True else: for j in range(i + 1, len(menu.items)): if menu[j].can_enable() and menu[i].is_visible(): break else: can_scroll_down = False break else: can_scroll_down = False cursor_y = 0 max_width = win_w - x - 3 if can_scroll_up: window.addstr(menu_top - 1, min(7, win_w - 3), " ^ ", attr["scroll"]) if can_scroll_down: window.addstr(menu_bottom, min(7, win_w - 3), " v ", attr["scroll"]) for menu_pos in menu_items: menu_option = menu[menu_pos] is_selected = False if menu.selection == menu_pos: cursor_y = y is_selected = True tmp_x = x remaining_width = max_width for part in menu[menu_pos].get_styled_text(is_selected, max_width): if len(part.text) > 0 and remaining_width > 0: window.addstr(y, tmp_x, part.text[:remaining_width], attr[part.style]) tmp_x += len(part.text) remaining_width -= len(part.text) y += 1 window.move(cursor_y, x + 1) return menu_height
def userptr(self): # XXX: This is probably wrong. obj = lib.panel_userptr(self._pan) if obj == ffi.NULL: raise error("no userptr set") return obj
def userptr(self): # XXX: This is probably wrong. obj = lib.panel_userptr(self._pan) if obj == ffi.NULL: raise error("no userptr set") return obj