Skip to content

Commit

Permalink
make adding TransitionRoutes and EventHandlers more user friendly
Browse files Browse the repository at this point in the history
  • Loading branch information
MRyderOC committed Oct 30, 2023
1 parent d738a78 commit c56a724
Show file tree
Hide file tree
Showing 4 changed files with 305 additions and 65 deletions.
7 changes: 0 additions & 7 deletions src/dfcx_scrapi/builders/builders_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@ def _check_proto_obj_attr_exist(self):
"\nPlease create or load the correct type to continue."
)


def load_proto_obj(self, obj, overwrite: bool = False):
"""Load an existing object to proto_obj for further uses.
Expand Down Expand Up @@ -185,7 +184,6 @@ def _match_transition_route(

return is_match


def _check_transition_route_with_target_route(
self,
transition_route: TransitionRoute,
Expand Down Expand Up @@ -214,7 +212,6 @@ def _check_transition_route_with_target_route(
return True
return False


def _check_transition_route_with_intent_and_condition(
self,
transition_route: TransitionRoute,
Expand Down Expand Up @@ -246,7 +243,6 @@ def _check_transition_route_with_intent_and_condition(
return True
return False


def _check_transition_route_with_intent(
self,
transition_route: TransitionRoute,
Expand All @@ -271,7 +267,6 @@ def _check_transition_route_with_intent(
return True
return False


def _check_transition_route_with_condition(
self,
transition_route: TransitionRoute,
Expand Down Expand Up @@ -325,7 +320,6 @@ def _find_unmatched_event_handlers(
if eh not in event_handlers
]


def _find_unmatched_event_handlers_by_name(
self, event_names: Union[str, List[str]]
) -> List[EventHandler]:
Expand Down Expand Up @@ -370,7 +364,6 @@ def to_dataframe(self, mode: str = "basic") -> pd.DataFrame:
return self._dataframe_instance.proto_to_dataframe(
obj=self.proto_obj, mode=mode)


def from_dataframe(self, df: pd.DataFrame, action: str):
"""Perform an `action` from the DataFrame `df` on proto_obj.
Expand Down
148 changes: 118 additions & 30 deletions src/dfcx_scrapi/builders/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,16 @@

import logging
from dataclasses import dataclass
from typing import List, Union
from typing import List, Dict, Union

import numpy as np
import pandas as pd
from google.cloud.dialogflowcx_v3beta1.types import Flow
from google.cloud.dialogflowcx_v3beta1.types import NluSettings
from google.cloud.dialogflowcx_v3beta1.types import Fulfillment
from google.cloud.dialogflowcx_v3beta1.types import TransitionRoute
from google.cloud.dialogflowcx_v3beta1.types import EventHandler

from dfcx_scrapi.builders.builders_common import BuildersCommon
from dfcx_scrapi.builders.routes import TransitionRouteBuilder
from dfcx_scrapi.builders.routes import EventHandlerBuilder
Expand Down Expand Up @@ -57,7 +59,6 @@ def __str__(self) -> str:
f"\n\n\nTransitoinRouteGroups:\n{'='*25}"
f"\n{self._show_transition_route_groups()}")


def _show_basic_info(self) -> str:
"""String representation for the basic information of proto_obj."""
self._check_proto_obj_attr_exist()
Expand All @@ -76,7 +77,6 @@ def _show_basic_info(self) -> str:
f"\nNLU settings:\n{nlu_settings_str}"
)


def _show_transition_routes(self) -> str:
"""String representation for the transition routes of proto_obj."""
self._check_proto_obj_attr_exist()
Expand All @@ -87,7 +87,6 @@ def _show_transition_routes(self) -> str:
for i, tr in enumerate(self.proto_obj.transition_routes)
])


def _show_event_handlers(self) -> str:
"""String representation for the event handlers of proto_obj."""
self._check_proto_obj_attr_exist()
Expand All @@ -97,7 +96,6 @@ def _show_event_handlers(self) -> str:
for i, eh in enumerate(self.proto_obj.event_handlers)
])


def _show_transition_route_groups(self) -> str:
"""String representation for the transition route groups of proto_obj"""
self._check_proto_obj_attr_exist()
Expand All @@ -107,7 +105,6 @@ def _show_transition_route_groups(self) -> str:
for i, trg_id in enumerate(self.proto_obj.transition_route_groups)
])


def show_flow_info(
self, mode: str = "whole"
) -> None:
Expand Down Expand Up @@ -144,7 +141,6 @@ def show_flow_info(
" 'events', 'event handlers']"
)


def show_stats(self) -> None:
"""Provide some stats about the Page."""
self._check_proto_obj_attr_exist()
Expand Down Expand Up @@ -266,63 +262,158 @@ def nlu_settings(

return self.proto_obj


def add_transition_route(
self,
transition_routes: Union[TransitionRoute, List[TransitionRoute]]
transition_routes: Union[TransitionRoute, List[TransitionRoute]] = None,
intent: str = None,
condition: str = None,
target_page: str = None,
target_flow: str = None,
trigger_fulfillment: Fulfillment = None,
agent_response: Union[str, List[str]] = None,
parameter_map: Dict[str, str] = None,
) -> Flow:
"""Add single or multiple TransitionRoutes to the Flow.
You can either pass TransitionRoute objects or create a TransitionRoute
on the fly by passing other parameters. Note that `transition_routes`
takes priority over other parameters.
Args:
transition_routes (TransitionRoute | List[TransitionRoute]):
A single or list of TransitionRoutes to add
to the Flow existing in proto_obj.
to the Flow existed in proto_obj.
intent (str):
Indicates that the transition can only happen when the given
intent is matched.
Format:
``projects/<Project ID>/locations/<Location ID>/
agents/<Agent ID>/intents/<Intent ID>``.
At least one of ``intent`` or ``condition`` must be specified.
When both ``intent`` and ``condition`` are specified,
the transition can only happen when both are fulfilled.
condition (str):
The condition to evaluate.
See the conditions reference:
https://cloud.google.com/dialogflow/cx/docs/reference/condition
At least one of ``intent`` or ``condition`` must be specified.
When both ``intent`` and ``condition`` are specified,
the transition can only happen when both are fulfilled.
target_page (str):
The target page to transition to. Format:
``projects/<Project ID>/locations/<Location ID>/
agents/<Agent ID>/flows/<Flow ID>/pages/<Page ID>``.
At most one of ``target_page`` and ``target_flow``
can be specified at the same time.
target_flow (str):
The target flow to transition to. Format:
``projects/<Project ID>/locations/<Location ID>/
agents/<Agent ID>/flows/<Flow ID>``.
At most one of ``target_page`` and ``target_flow``
can be specified at the same time.
trigger_fulfillment (Fulfillment):
The fulfillment to call when the condition is satisfied.
When ``trigger_fulfillment`` and ``target`` are defined,
``trigger_fulfillment`` is executed first.
agent_response (str | List[str]):
Agent's response message (Fulfillment). A single message as
a string or multiple messages as a list of strings.
parameter_map (Dict[str, str]):
A dictionary that represents parameters as keys
and the parameter values as it's values.
A `None` value clears the parameter.
Returns:
A Flow object stored in proto_obj.
"""
self._check_proto_obj_attr_exist()

# Type error checking
self._is_type_or_list_of_types(
transition_routes, TransitionRoute, "transition_routes"
)
if not transition_routes is None:
self._is_type_or_list_of_types(
transition_routes, TransitionRoute, "transition_routes")

if not isinstance(transition_routes, list):
transition_routes = [transition_routes]
self.proto_obj.transition_routes.extend(transition_routes)
if not isinstance(transition_routes, list):
transition_routes = [transition_routes]
else:
trb = TransitionRouteBuilder()
trb.create_new_proto_obj(
intent, condition, trigger_fulfillment,
target_page, target_flow)
if trigger_fulfillment is None:
trb.set_fulfillment(
message=agent_response, parameter_map=parameter_map)
transition_routes = [trb.proto_obj]

self.proto_obj.transition_routes.extend(transition_routes)
return self.proto_obj


def add_event_handler(
self,
event_handlers: Union[EventHandler, List[EventHandler]]
event_handlers: Union[EventHandler, List[EventHandler]] = None,
event: str = None,
target_page: str = None,
target_flow: str = None,
trigger_fulfillment: Fulfillment = None,
agent_response: Union[str, List[str]] = None,
parameter_map: Dict[str, str] = None,
) -> Flow:
"""Add single or multiple EventHandlers to the Flow.
You can either pass EventHandler objects or create a EventHandler
on the fly by passing other parameters. Note that `event_handlers`
takes priority over other parameters.
Args:
event_handlers (EventHandler | List[EventHandler]):
A single or list of EventHandler to add
to the Flow existing in proto_obj.
event (str):
The name of the event to handle.
target_page (str):
The target page to transition to. Format:
``projects/<Project ID>/locations/<Location ID>/
agents/<Agent ID>/flows/<Flow ID>/pages/<Page ID>``.
At most one of ``target_page`` and ``target_flow``
can be specified at the same time.
target_flow (str):
The target flow to transition to. Format:
``projects/<Project ID>/locations/<Location ID>/
agents/<Agent ID>/flows/<Flow ID>``.
At most one of ``target_page`` and ``target_flow``
can be specified at the same time.
trigger_fulfillment (Fulfillment):
The fulfillment to call when the condition is satisfied.
When ``trigger_fulfillment`` and ``target`` are defined,
``trigger_fulfillment`` is executed first.
agent_response (str | List[str]):
Agent's response message (Fulfillment). A single message as
a string or multiple messages as a list of strings.
parameter_map (Dict[str, str]):
A dictionary that represents parameters as keys
and the parameter values as it's values.
A `None` value clears the parameter.
Returns:
A Flow object stored in proto_obj.
"""
self._check_proto_obj_attr_exist()

# Type error checking
self._is_type_or_list_of_types(
event_handlers, EventHandler, "event_handlers"
)
if not event_handlers is None:
self._is_type_or_list_of_types(
event_handlers, EventHandler, "event_handlers")

if not isinstance(event_handlers, list):
event_handlers = [event_handlers]
self.proto_obj.event_handlers.extend(event_handlers)
if not isinstance(event_handlers, list):
event_handlers = [event_handlers]
else:
ehb = EventHandlerBuilder()
ehb.create_new_proto_obj(
event, trigger_fulfillment, target_page, target_flow)
if trigger_fulfillment is None:
ehb.set_fulfillment(
message=agent_response, parameter_map=parameter_map)
event_handlers = [ehb.proto_obj]

self.proto_obj.event_handlers.extend(event_handlers)
return self.proto_obj


def add_transition_route_group(
self,
transition_route_groups: Union[str, List[str]]
Expand Down Expand Up @@ -352,7 +443,6 @@ def add_transition_route_group(

return self.proto_obj


def remove_transition_route(
self,
transition_route: TransitionRoute = None,
Expand Down Expand Up @@ -389,7 +479,6 @@ def remove_transition_route(

return self.proto_obj


def remove_event_handler(
self,
event_handlers: Union[EventHandler, List[EventHandler]] = None,
Expand Down Expand Up @@ -433,7 +522,6 @@ def remove_event_handler(

return self.proto_obj


def remove_transition_route_group(
self,
transition_route_groups: Union[str, List[str]]
Expand Down
Loading

0 comments on commit c56a724

Please sign in to comment.