-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.py
More file actions
866 lines (731 loc) · 30 KB
/
server.py
File metadata and controls
866 lines (731 loc) · 30 KB
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
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
import logging
import os
import tempfile
import traceback
from functools import wraps
from inspect import isawaitable
from typing import Any, Callable, List, Optional, Text, Union
from sanic import Sanic, response
from sanic.request import Request
from sanic_cors import CORS
from sanic_jwt import Initialize, exceptions
import rasa
import rasa.utils.common
import rasa.utils.endpoints
import rasa.utils.io
from rasa.core.domain import InvalidDomain
from rasa.utils.endpoints import EndpointConfig
from rasa.constants import (
MINIMUM_COMPATIBLE_VERSION,
DEFAULT_MODELS_PATH,
DEFAULT_DOMAIN_PATH,
DOCS_BASE_URL,
)
from rasa.core import broker
from rasa.core.agent import load_agent, Agent
from rasa.core.channels.channel import UserMessage, CollectingOutputChannel
from rasa.core.events import Event
from rasa.core.test import test
from rasa.core.trackers import DialogueStateTracker, EventVerbosity
from rasa.core.utils import dump_obj_as_str_to_file, AvailableEndpoints
from rasa.model import get_model_subdirectories, fingerprint_from_path
from rasa.nlu.emulators.no_emulator import NoEmulator
from rasa.nlu.test import run_evaluation
from rasa.core.tracker_store import TrackerStore
logger = logging.getLogger(__name__)
class ErrorResponse(Exception):
def __init__(self, status, reason, message, details=None, help_url=None):
self.error_info = {
"version": rasa.__version__,
"status": "failure",
"message": message,
"reason": reason,
"details": details or {},
"help": help_url,
"code": status,
}
self.status = status
def _docs(sub_url: Text) -> Text:
"""Create a url to a subpart of the docs."""
return DOCS_BASE_URL + sub_url
def ensure_loaded_agent(app: Sanic):
"""Wraps a request handler ensuring there is a loaded and usable agent."""
def decorator(f):
@wraps(f)
def decorated(*args, **kwargs):
if not app.agent or not app.agent.is_ready():
raise ErrorResponse(
409,
"Conflict",
"No agent loaded. To continue processing, a "
"model of a trained agent needs to be loaded.",
help_url=_docs("/user-guide/running-the-server/"),
)
return f(*args, **kwargs)
return decorated
return decorator
def requires_auth(app: Sanic, token: Optional[Text] = None) -> Callable[[Any], Any]:
"""Wraps a request handler with token authentication."""
def decorator(f: Callable[[Any, Any], Any]) -> Callable[[Any, Any], Any]:
def conversation_id_from_args(args: Any, kwargs: Any) -> Optional[Text]:
argnames = rasa.utils.common.arguments_of(f)
try:
sender_id_arg_idx = argnames.index("conversation_id")
if "conversation_id" in kwargs: # try to fetch from kwargs first
return kwargs["conversation_id"]
if sender_id_arg_idx < len(args):
return args[sender_id_arg_idx]
return None
except ValueError:
return None
def sufficient_scope(request, *args: Any, **kwargs: Any) -> Optional[bool]:
jwt_data = request.app.auth.extract_payload(request)
user = jwt_data.get("user", {})
username = user.get("username", None)
role = user.get("role", None)
if role == "admin":
return True
elif role == "user":
conversation_id = conversation_id_from_args(args, kwargs)
return conversation_id is not None and username == conversation_id
else:
return False
@wraps(f)
async def decorated(request: Request, *args: Any, **kwargs: Any) -> Any:
provided = request.args.get("token", None)
# noinspection PyProtectedMember
if token is not None and provided == token:
result = f(request, *args, **kwargs)
if isawaitable(result):
result = await result
return result
elif app.config.get("USE_JWT") and request.app.auth.is_authenticated(
request
):
if sufficient_scope(request, *args, **kwargs):
result = f(request, *args, **kwargs)
if isawaitable(result):
result = await result
return result
raise ErrorResponse(
403,
"NotAuthorized",
"User has insufficient permissions.",
help_url=_docs(
"/user-guide/running-the-server/#security-considerations"
),
)
elif token is None and app.config.get("USE_JWT") is None:
# authentication is disabled
result = f(request, *args, **kwargs)
if isawaitable(result):
result = await result
return result
raise ErrorResponse(
401,
"NotAuthenticated",
"User is not authenticated.",
help_url=_docs(
"/user-guide/running-the-server/#security-considerations"
),
)
return decorated
return decorator
def event_verbosity_parameter(
request: Request, default_verbosity: EventVerbosity
) -> EventVerbosity:
event_verbosity_str = request.args.get(
"include_events", default_verbosity.name
).upper()
try:
return EventVerbosity[event_verbosity_str]
except KeyError:
enum_values = ", ".join([e.name for e in EventVerbosity])
raise ErrorResponse(
400,
"BadRequest",
"Invalid parameter value for 'include_events'. "
"Should be one of {}".format(enum_values),
{"parameter": "include_events", "in": "query"},
)
def obtain_tracker_store(agent: "Agent", conversation_id: Text) -> DialogueStateTracker:
tracker = agent.tracker_store.get_or_create_tracker(conversation_id)
if not tracker:
raise ErrorResponse(
409,
"Conflict",
"Could not retrieve tracker with id '{}'. Most likely "
"because there is no domain set on the agent.".format(conversation_id),
)
return tracker
def validate_request_body(request: Request, error_message: Text):
if not request.body:
raise ErrorResponse(400, "BadRequest", error_message)
async def authenticate(request: Request):
raise exceptions.AuthenticationFailed(
"Direct JWT authentication not supported. You should already have "
"a valid JWT from an authentication provider, Rasa will just make "
"sure that the token is valid, but not issue new tokens."
)
def _create_emulator(mode: Optional[Text]) -> NoEmulator:
"""Create emulator for specified mode.
If no emulator is specified, we will use the Rasa NLU format."""
if mode is None:
return NoEmulator()
elif mode.lower() == "wit":
from rasa.nlu.emulators.wit import WitEmulator
return WitEmulator()
elif mode.lower() == "luis":
from rasa.nlu.emulators.luis import LUISEmulator
return LUISEmulator()
elif mode.lower() == "dialogflow":
from rasa.nlu.emulators.dialogflow import DialogflowEmulator
return DialogflowEmulator()
else:
raise ErrorResponse(
400,
"BadRequest",
"Invalid parameter value for 'emulation_mode'. "
"Should be one of 'WIT', 'LUIS', 'DIALOGFLOW'.",
{"parameter": "emulation_mode", "in": "query"},
)
async def _load_agent(
model_path: Optional[Text] = None,
model_server: Optional[EndpointConfig] = None,
remote_storage: Optional[Text] = None,
endpoints: Optional[AvailableEndpoints] = None,
) -> Agent:
try:
tracker_store = None
generator = None
action_endpoint = None
if endpoints:
_broker = broker.from_endpoint_config(endpoints.event_broker)
tracker_store = TrackerStore.find_tracker_store(
None, endpoints.tracker_store, _broker
)
generator = endpoints.nlg
action_endpoint = endpoints.action
loaded_agent = await load_agent(
model_path,
model_server,
remote_storage,
generator=generator,
tracker_store=tracker_store,
action_endpoint=action_endpoint,
)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500, "LoadingError", "An unexpected error occurred. Error: {}".format(e)
)
if not loaded_agent:
raise ErrorResponse(
400,
"BadRequest",
"Agent with name '{}' could not be loaded.".format(model_path),
{"parameter": "model", "in": "query"},
)
return loaded_agent
def create_app(
agent: Optional["Agent"] = None,
cors_origins: Union[Text, List[Text]] = "*",
auth_token: Optional[Text] = None,
jwt_secret: Optional[Text] = None,
jwt_method: Text = "HS256",
endpoints: Optional[AvailableEndpoints] = None,
):
"""Class representing a Rasa HTTP server."""
app = Sanic(__name__)
app.config.RESPONSE_TIMEOUT = 60 * 60
CORS(
app, resources={r"/*": {"origins": cors_origins or ""}}, automatic_options=True
)
# Setup the Sanic-JWT extension
if jwt_secret and jwt_method:
# since we only want to check signatures, we don't actually care
# about the JWT method and set the passed secret as either symmetric
# or asymmetric key. jwt lib will choose the right one based on method
app.config["USE_JWT"] = True
Initialize(
app,
secret=jwt_secret,
authenticate=authenticate,
algorithm=jwt_method,
user_id="username",
)
app.agent = agent
@app.exception(ErrorResponse)
async def handle_error_response(request: Request, exception: ErrorResponse):
return response.json(exception.error_info, status=exception.status)
@app.get("/")
async def hello(request: Request):
"""Check if the server is running and responds with the version."""
return response.text("Hello from Rasa: " + rasa.__version__)
@app.get("/version")
async def version(request: Request):
"""Respond with the version number of the installed Rasa."""
return response.json(
{
"version": rasa.__version__,
"minimum_compatible_version": MINIMUM_COMPATIBLE_VERSION,
}
)
@app.get("/status")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def status(request: Request):
"""Respond with the model name and the fingerprint of that model."""
return response.json(
{
"model_file": app.agent.model_directory,
"fingerprint": fingerprint_from_path(app.agent.model_directory),
}
)
@app.get("/conversations/<conversation_id>/tracker")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def retrieve_tracker(request: Request, conversation_id: Text):
"""Get a dump of a conversation's tracker including its events."""
if not app.agent.tracker_store:
raise ErrorResponse(
409,
"Conflict",
"No tracker store available. Make sure to "
"configure a tracker store when starting "
"the server.",
)
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
until_time = rasa.utils.endpoints.float_arg(request, "until")
tracker = obtain_tracker_store(app.agent, conversation_id)
try:
if until_time is not None:
tracker = tracker.travel_back_in_time(until_time)
state = tracker.current_state(verbosity)
return response.json(state)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.post("/conversations/<conversation_id>/tracker/events")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def append_events(request: Request, conversation_id: Text):
"""Append a list of events to the state of a conversation"""
validate_request_body(
request,
"You must provide events in the request body in order to append them"
"to the state of a conversation.",
)
events = request.json
if not isinstance(events, list):
events = [events]
events = [Event.from_parameters(event) for event in events]
events = [event for event in events if event]
if not events:
logger.warning(
"Append event called, but could not extract a valid event. "
"Request JSON: {}".format(request.json)
)
raise ErrorResponse(
400,
"BadRequest",
"Couldn't extract a proper event from the request body.",
{"parameter": "", "in": "body"},
)
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
tracker = obtain_tracker_store(app.agent, conversation_id)
try:
for event in events:
tracker.update(event, app.agent.domain)
app.agent.tracker_store.save(tracker)
return response.json(tracker.current_state(verbosity))
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.put("/conversations/<conversation_id>/tracker/events")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def replace_events(request: Request, conversation_id: Text):
"""Use a list of events to set a conversations tracker to a state."""
validate_request_body(
request,
"You must provide events in the request body to set the sate of the "
"conversation tracker.",
)
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
try:
tracker = DialogueStateTracker.from_dict(
conversation_id, request.json, app.agent.domain.slots
)
# will override an existing tracker with the same id!
app.agent.tracker_store.save(tracker)
return response.json(tracker.current_state(verbosity))
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.get("/conversations/<conversation_id>/story")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def retrieve_story(request: Request, conversation_id: Text):
"""Get an end-to-end story corresponding to this conversation."""
if not app.agent.tracker_store:
raise ErrorResponse(
409,
"Conflict",
"No tracker store available. Make sure to "
"configure a tracker store when starting "
"the server.",
)
# retrieve tracker and set to requested state
tracker = obtain_tracker_store(app.agent, conversation_id)
until_time = rasa.utils.endpoints.float_arg(request, "until")
try:
if until_time is not None:
tracker = tracker.travel_back_in_time(until_time)
# dump and return tracker
state = tracker.export_stories(e2e=True)
return response.text(state)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.post("/conversations/<conversation_id>/execute")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def execute_action(request: Request, conversation_id: Text):
request_params = request.json
action_to_execute = request_params.get("name", None)
if not action_to_execute:
raise ErrorResponse(
400,
"BadRequest",
"Name of the action not provided in request body.",
{"parameter": "name", "in": "body"},
)
policy = request_params.get("policy", None)
confidence = request_params.get("confidence", None)
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
try:
out = CollectingOutputChannel()
await app.agent.execute_action(
conversation_id, action_to_execute, out, policy, confidence
)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
tracker = obtain_tracker_store(app.agent, conversation_id)
state = tracker.current_state(verbosity)
return response.json({"tracker": state, "messages": out.messages})
@app.post("/conversations/<conversation_id>/predict")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def predict(request: Request, conversation_id: Text):
try:
# Fetches the appropriate bot response in a json format
responses = app.agent.predict_next(conversation_id)
responses["scores"] = sorted(
responses["scores"], key=lambda k: (-k["score"], k["action"])
)
return response.json(responses)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.post("/conversations/<conversation_id>/messages")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def add_message(request: Request, conversation_id: Text):
validate_request_body(
request,
"No message defined in request body. Add a message to the request body in "
"order to add it to the tracker.",
)
request_params = request.json
message = request_params.get("text")
sender = request_params.get("sender")
parse_data = request_params.get("parse_data")
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
# TODO: implement for agent / bot
if sender != "user":
raise ErrorResponse(
400,
"BadRequest",
"Currently, only user messages can be passed to this endpoint. "
"Messages of sender '{}' cannot be handled.".format(sender),
{"parameter": "sender", "in": "body"},
)
try:
user_message = UserMessage(message, None, conversation_id, parse_data)
tracker = await app.agent.log_message(user_message)
return response.json(tracker.current_state(verbosity))
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"ConversationError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.post("/model/train")
@requires_auth(app, auth_token)
async def train(request: Request):
"""Train a Rasa Model."""
from rasa.train import train_async
validate_request_body(
request,
"You must provide training data in the request body in order to "
"train your model.",
)
rjs = request.json
validate_request(rjs)
# create a temporary directory to store config, domain and
# training data
temp_dir = tempfile.mkdtemp()
config_path = os.path.join(temp_dir, "config.yml")
dump_obj_as_str_to_file(config_path, rjs["config"])
if "nlu" in rjs:
nlu_path = os.path.join(temp_dir, "nlu.md")
dump_obj_as_str_to_file(nlu_path, rjs["nlu"])
if "stories" in rjs:
stories_path = os.path.join(temp_dir, "stories.md")
dump_obj_as_str_to_file(stories_path, rjs["stories"])
domain_path = DEFAULT_DOMAIN_PATH
if "domain" in rjs:
domain_path = os.path.join(temp_dir, "domain.yml")
dump_obj_as_str_to_file(domain_path, rjs["domain"])
try:
model_path = await train_async(
domain=domain_path,
config=config_path,
training_files=temp_dir,
output_path=rjs.get("out", DEFAULT_MODELS_PATH),
force_training=rjs.get("force", False),
)
return await response.file(model_path)
except InvalidDomain as e:
raise ErrorResponse(
400,
"InvalidDomainError",
"Provided domain file is invalid. Error: {}".format(e),
)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"TrainingError",
"An unexpected error occurred during training. Error: {}".format(e),
)
def validate_request(rjs):
if "config" not in rjs:
raise ErrorResponse(
400,
"BadRequest",
"The training request is missing the required key `config`.",
{"parameter": "config", "in": "body"},
)
if "nlu" not in rjs and "stories" not in rjs:
raise ErrorResponse(
400,
"BadRequest",
"To train a Rasa model you need to specify at least one type of "
"training data. Add `nlu` and/or `stories` to the request.",
{"parameters": ["nlu", "stories"], "in": "body"},
)
if "stories" in rjs and "domain" not in rjs:
raise ErrorResponse(
400,
"BadRequest",
"To train a Rasa model with story training data, you also need to "
"specify the `domain`.",
{"parameter": "domain", "in": "body"},
)
@app.post("/model/test/stories")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def evaluate_stories(request: Request):
"""Evaluate stories against the currently loaded model."""
validate_request_body(
request,
"You must provide some stories in the request body in order to "
"evaluate your model.",
)
stories = rasa.utils.io.create_temporary_file(request.body, mode="w+b")
use_e2e = rasa.utils.endpoints.bool_arg(request, "e2e", default=False)
try:
evaluation = await test(stories, app.agent, e2e=use_e2e)
return response.json(evaluation)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"TestingError",
"An unexpected error occurred during evaluation. Error: {}".format(e),
)
@app.post("/model/test/intents")
@requires_auth(app, auth_token)
async def evaluate_intents(request: Request):
"""Evaluate intents against a Rasa model."""
validate_request_body(
request,
"You must provide some nlu data in the request body in order to "
"evaluate your model.",
)
eval_agent = app.agent
model_path = request.args.get("model", None)
if model_path:
model_server = app.agent.model_server
if model_server is not None:
model_server.url = model_path
eval_agent = await _load_agent(
model_path, model_server, app.agent.remote_storage
)
nlu_data = rasa.utils.io.create_temporary_file(request.body, mode="w+b")
data_path = os.path.abspath(nlu_data)
if not os.path.exists(eval_agent.model_directory):
raise ErrorResponse(409, "Conflict", "Loaded model file not found.")
model_directory = eval_agent.model_directory
_, nlu_model = get_model_subdirectories(model_directory)
try:
evaluation = run_evaluation(data_path, nlu_model)
return response.json(evaluation)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"TestingError",
"An unexpected error occurred during evaluation. Error: {}".format(e),
)
@app.post("/model/predict")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def tracker_predict(request: Request):
""" Given a list of events, predicts the next action"""
validate_request_body(
request,
"No events defined in request_body. Add events to request body in order to "
"predict the next action.",
)
sender_id = UserMessage.DEFAULT_SENDER_ID
verbosity = event_verbosity_parameter(request, EventVerbosity.AFTER_RESTART)
request_params = request.json
try:
tracker = DialogueStateTracker.from_dict(
sender_id, request_params, app.agent.domain.slots
)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
400,
"BadRequest",
"Supplied events are not valid. {}".format(e),
{"parameter": "", "in": "body"},
)
try:
policy_ensemble = app.agent.policy_ensemble
probabilities, policy = policy_ensemble.probabilities_using_best_policy(
tracker, app.agent.domain
)
scores = [
{"action": a, "score": p}
for a, p in zip(app.agent.domain.action_names, probabilities)
]
return response.json(
{
"scores": scores,
"policy": policy,
"tracker": tracker.current_state(verbosity),
}
)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500,
"PredictionError",
"An unexpected error occurred. Error: {}".format(e),
)
@app.post("/model/parse")
@requires_auth(app, auth_token)
async def parse(request: Request):
validate_request_body(
request,
"No text message defined in request_body. Add text message to request body "
"in order to obtain the intent and extracted entities.",
)
emulation_mode = request.args.get("emulation_mode")
emulator = _create_emulator(emulation_mode)
try:
data = emulator.normalise_request_json(request.json)
parse_data = await app.agent.interpreter.parse(data.get("text"))
response_data = emulator.normalise_response_json(parse_data)
return response.json(response_data)
except Exception as e:
logger.debug(traceback.format_exc())
raise ErrorResponse(
500, "ParsingError", "An unexpected error occurred. Error: {}".format(e)
)
@app.put("/model")
@requires_auth(app, auth_token)
async def load_model(request: Request):
validate_request_body(request, "No path to model file defined in request_body.")
model_path = request.json.get("model_file", None)
model_server = request.json.get("model_server", None)
remote_storage = request.json.get("remote_storage", None)
app.agent = await _load_agent(
model_path, model_server, remote_storage, endpoints
)
logger.debug("Successfully loaded model '{}'.".format(model_path))
return response.json(None, status=204)
@app.delete("/model")
@requires_auth(app, auth_token)
async def unload_model(request: Request):
model_file = app.agent.model_directory
app.agent = Agent()
logger.debug("Successfully unload model '{}'.".format(model_file))
return response.json(None, status=204)
@app.get("/domain")
@requires_auth(app, auth_token)
@ensure_loaded_agent(app)
async def get_domain(request: Request):
"""Get current domain in yaml or json format."""
accepts = request.headers.get("Accept", default="application/json")
if accepts.endswith("json"):
domain = app.agent.domain.as_dict()
return response.json(domain)
elif accepts.endswith("yml") or accepts.endswith("yaml"):
domain_yaml = app.agent.domain.as_yaml()
return response.text(
domain_yaml, status=200, content_type="application/x-yml"
)
else:
raise ErrorResponse(
406,
"NotAcceptable",
"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.",
)
return app