2.2. State Transition
Create a dialogue flow using state transitions.
Dialogue Flow
Let us create a dictionary called transitions
and name its initial state as start
:
#1
:transitions
is a dictionary.
Add transitions to conduct a single-turn dialogue:
#3
: the system begins the dialogue by saying, "Hello. How are you?".#4
: the system matches the user input with'good'
.#5
: the system responds to the user with "Glad to hear that ..." and recognizes that it is the final stateend
.
All keys and values must be in the string type, where literals need to be surrounded by reversed primes (e.g., '`Hello. How are you?`'
).
There are two ways to create a string in Python, using single quotes (e.g., 'Hello'
) and double quotes (e.g., "Hello"
). When you use single quotes, any single quote inside the string needs to be escaped by a backslash (e.g., 'I\'m "good"!'
). Similarly, when you use double quotes, any double quote needs to be escaped (e.g., "I'm \"good\"!"
).
Create the dialogue flow df
that expects the initial state start
and the final state end
, which must match the names of the initial and final states in transitions
:
#1
: the import statement should be on top of the source code (see dialogue_graph.py).
Load the transitions to the dialogue flow df
:
Finally, run the dialogue flow:
Enter inputs such as "good", "Good", or "Good!" (separately) and see how the system responds. Does the system respond differently?
How does the system respond to inputs like "fantastic" or "bad"?
Branching
Let us add a transition such that it can also handle the input 'bad'
:
#7-9
: a new transition for the'bad'
condition.
When you load the new transitions and run the dialogue flow, it now gives proper responses to both 'good'
and 'bad'
:
Error Handling
Even with branching, it still throws errors for other inputs. Let us add an error transition to set the default statement for all the other inputs:
#10-12
: an error transition to generate the default response.
Make sure to put a default error statement for every branching; otherwise, it will throw an exception during runtime, which can be detrimental.
Code Snippet
#3
: although Python is a dynamically-typed language, it allows you to indicate the type of a variable or a function using typing (since Python 3.5).
Last updated