-
Notifications
You must be signed in to change notification settings - Fork 6
/
6_context_serialization.py
89 lines (69 loc) · 1.92 KB
/
6_context_serialization.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
# %% [markdown]
"""
# Core: 6. Context serialization
This tutorial shows context serialization.
First of all, let's do all the necessary imports from DFF.
"""
# %pip install dff
# %%
import logging
from dff.script import TRANSITIONS, RESPONSE, Context, Message
import dff.script.conditions as cnd
from dff.pipeline import Pipeline
from dff.utils.testing.common import (
check_happy_path,
is_interactive_mode,
run_interactive_mode,
)
# %% [markdown]
"""
This function returns the user request number.
"""
# %%
def response_handler(ctx: Context, _: Pipeline) -> Message:
return Message(f"answer {len(ctx.requests)}")
# %%
# a dialog script
toy_script = {
"flow_start": {
"node_start": {
RESPONSE: response_handler,
TRANSITIONS: {("flow_start", "node_start"): cnd.true()},
}
}
}
# testing
happy_path = (
(Message("hi"), Message("answer 1")),
(Message("how are you?"), Message("answer 2")),
(Message("ok"), Message("answer 3")),
(Message("good"), Message("answer 4")),
)
# %% [markdown]
"""
Draft function that performs serialization.
"""
# %%
def process_response(ctx: Context):
ctx_json = ctx.model_dump_json()
if isinstance(ctx_json, str):
logging.info("context serialized to json str")
else:
raise Exception(f"ctx={ctx_json} has to be serialized to json string")
ctx_dict = ctx.model_dump()
if isinstance(ctx_dict, dict):
logging.info("context serialized to dict")
else:
raise Exception(f"ctx={ctx_dict} has to be serialized to dict")
if not isinstance(ctx, Context):
raise Exception(f"ctx={ctx} has to have Context type")
# %%
pipeline = Pipeline.from_script(
toy_script,
start_label=("flow_start", "node_start"),
post_services=[process_response],
)
if __name__ == "__main__":
check_happy_path(pipeline, happy_path)
if is_interactive_mode():
run_interactive_mode(pipeline)