Service Connector Interface

Connectors allow Intents Agent definitions to operate with real cloud services such as Dialogflow, Lex or Azure Bot Services. Currently, only one connector is provided with this library, and this is for Dialogflow ES: intents.connectors.dialogflow_es.connector.

Note

Details about the Connector interface are only useful if you need to develop your own Service Connector (please consider raising a pull request if this is the case). If you just need to use the included Dialogflow Connector you can jump to its documentation page right away: intents.connectors.dialogflow_es.connector

Connectors are used to operate with the cloud version of the Agent, and specifically to:

  • Export an intents.Agent in a format that is natively readable by the Service

  • Predict User messages on the Cloud Agent

  • Trigger Intents on the Cloud Agent

More details can be found in the Connector interface.

class Connector(agent_cls, default_session=None, default_language='en')[source]

Connect the given Agent to a Prediction Service.

Parameters
  • agent_cls (_AgentMetaclass) – The Agent to connect

  • default_session (Optional[str]) – A default session ID (conversation channel) for predictions

  • default_language (str) – A default language for predictions

abstract property entity_mappings

A Service Connector must know the Entity Mappings of its Prediction Service. They will be used to lookup entity names during export.

Return type

ServiceEntityMappings

abstract export(destination)[source]

Export the connected Agent in a format that can be read and imported natively by the Prediction service. For instance, the Dialogflow service will produce a ZIP export that can be imported from the Dialogflow console.

Note that you can also directly upload the Agent with upload().

Parameters

destination (str) – destination path of the exported Agent

abstract predict(message, session=None, language=None)[source]

Predict the given User message in the given session using the given language. When session or language are None, predict will use the default values that are specified in __init__().

predict will return an instance of Prediction, representing the service response.

>>> from intents.connectors import DialogflowEsConnector
>>> from example_agent import ExampleAgent
>>> df = DialogflowEsConnector('/path/to/service-account.json', ExampleAgent)
>>> prediction = df.predict("Hi, my name is Guido")
>>> prediction.intent
UserNameGive(user_name='Guido')
>>> prediction.intent.user_name
"Guido"
>>> prediction.fulfillment_text
"Hi Guido, I'm Bot"
>>> prediction.confidence
0.86
Parameters
  • message (str) – The User message to predict

  • session (Optional[str]) – Any string identifying a conversation

  • language (Optional[str]) – A ISO 639-1 language code (e.g. “en”)

Return type

Prediction

abstract trigger(intent, session=None, language=None)[source]

Trigger the given Intent in the given session using the given language. When session or language are None, predict will use the default values that are specified in __init__().

>>> from intents.connectors import DialogflowEsConnector
>>> from example_agent import ExampleAgent, smalltalk
>>> df = DialogflowEsConnector('/path/to/service-account.json', ExampleAgent)
>>> prediction = df.trigger(smalltalk.AgentNameGive(agent_name='Alice'))
>>> prediction.intent
AgentNameGive(agent_name='Alice')
>>> prediction.fulfillment_text
"Howdy Human, I'm Alice"
>>> prediction.confidence
1.0
Parameters
  • intent (Intent) – The Intent instance to trigger

  • session (Optional[str]) – Any string identifying a conversation

  • language (Optional[str]) – A ISO 639-1 language code (e.g. “en”)

Return type

Prediction

abstract upload()[source]

Upload the connected Agent to the Prediction Service.

class EntityMapping[source]

An Entity Mapping is a (de-)serializer for predicted Entities.

Most of the times a Mapping is not needed as the Entity can be mapped directly to its type (e.g. “3” -> Number(3)). However, prediction services such as Dialogflow may define system entities of structured types; a notable example is Dialogflow’s sys.person entity, which is returned as {“name”: “John”} and therefore needs custom logic to be mapped to Person(“John”). This is modelled in intents.connectors.dialogflow_es.entities.PersonEntityMapping.

Another notable scenario is Date/Time objects. A mapping can be used to convert time strings from the Service format to python objects. For Dialogflow ES, this is modelled in intents.connectors.dialogflow_es.entities.DateTimeEntityMapping.

abstract property entity_cls

This is the internal entity type that is being mapped.

>>> mapping = StringEntityMapping(Sys.Integer, 'sys.number-integer')
>>> mapping.entity_cls
Sys.Integer
Return type

_EntityMetaclass

abstract from_service(service_data)[source]

De-serialize the Service representation of an Entity (typically the value that is returned at prediction time) to an instance of one of the internal Entity classes in intents.model.entities

>>> date_mapping.from_service("2021-07-11")
Sys.Date(2021, 7, 11)
Parameters

service_data (Any) – A parameter value, as it is returned by the Service in a prediction/trigger response

Return type

SystemEntityMixin

Returns

the parameter value, modelled as one of the System Entity classes

abstract property service_name

This is the name of the Entity in the Prediction Service domain.

>>> mapping = StringEntityMapping(Sys.Integer, 'sys.number-integer')
>>> mapping.service_name
'sys.number-integer'
Return type

str

abstract to_service(entity)[source]

Serialize a System Entity instance into a Service representation (typically, to be sent as a parameter of a trigger request)

>>> date_mapping.to_service(Sys.Date(2021, 7, 11))
"2021-07-11"
Parameters

entity (SystemEntityMixin) – The System Entity to serialize

Return type

Any

Returns

The serialized Entity that can be sent to Service (e.g. in a trigger request)

class Prediction(intent, confidence, fulfillment_message_dict, fulfillment_text=None)[source]

One of the core uses of Service Connectors is to predict user utterances, or programmatically trigger intents. This class models the result of such predictions and triggers.

You will typically obtain Prediction objects from Connector methods predict() and trigger().

Parameters
  • intent (Intent) – An instance of the predicted Intent

  • confidence (float) – A confidence value on the service prediction

  • fulfillment_message_dict (Dict[IntentResponseGroup, List[IntentResponse]]) – A map of Intent Responses, as they were returned by the Service. Consider using Prediction.fulfillment_messages() for convenience

  • fulfillment_text (Optional[str]) – A plain-text version of the response

fulfillment_messages(response_group=<IntentResponseGroup.RICH: 'rich'>)[source]

Return a list of fulfillment messages that are suitable for the given Response Group. The following scenarios may happen:

  • language.IntentResponseGroup.DEFAULT is requested -> Message in the DEFAULT group will be returned

  • language.IntentResponseGroup.RICH is requested

    • RICH messages are defined -> RICH messages are returned

    • No RICH message is defined -> DEFAULT messages are returned

If present, messages in the “rich” group will be returned:

>>> prediction.fulfillment_messages()
[TextIntentResponse(choices=['I like travelling too! How can I help?']),
 QuickRepliesIntentResponse(replies=['Recommend a hotel', 'Send holiday photo', 'Where the station?'])]

Alternatively, I can ask for plain-text default messages:

>>> from intents.language import IntentResponseGroup
>>> prediction.fulfillment_messages(IntentResponseGroup.DEFAULT)
[TextIntentResponse(choices=['Nice, I can send you holiday pictures, or recommend an hotel'])]
Parameters

response_group (IntentResponseGroup) – The Response Group to fetch responses for

Return type

List[IntentResponse]

class ServiceEntityMappings[source]

Models a list of entity mappings, in the form of a dict where the key is a System entity class (inherits from SystemEntityMixin) and the value is a EntityMapping. In addition to a standard dict, these features are added:

  • Instantiate from a list of mappings with from_list()

  • Consistency check: a mapping list must cover all the entities defined in the framework (TODO)

  • Shortcut to define StringEntityMappings like (Sys.Integer, ‘sys.number-integer’) (TODO)

class StringEntityMapping(entity_cls, service_name)[source]

This is a basic EntityMapping that reads values as they are sent by the prediction service (e.g. “3” -> Sys.Integer(“3”)), and serializes by simple string conversion (e.g. Sys.Integer(3) -> “3”).

The System Entity to use must be defined when instantiating the mapping, for instance:

>>> StringEntityMapping(Sys.Integer, "sys.number-integer")
Parameters
  • entity_cls (_EntityMetaclass) –

  • service_name (str) –

from_service(service_data)[source]

De-serialize the Service representation of an Entity (typically the value that is returned at prediction time) to an instance of one of the internal Entity classes in intents.model.entities

>>> date_mapping.from_service("2021-07-11")
Sys.Date(2021, 7, 11)
Parameters

service_data (Any) – A parameter value, as it is returned by the Service in a prediction/trigger response

Return type

SystemEntityMixin

Returns

the parameter value, modelled as one of the System Entity classes

to_service(entity)[source]

Serialize a System Entity instance into a Service representation (typically, to be sent as a parameter of a trigger request)

>>> date_mapping.to_service(Sys.Date(2021, 7, 11))
"2021-07-11"
Parameters

entity (SystemEntityMixin) – The System Entity to serialize

Return type

Any

Returns

The serialized Entity that can be sent to Service (e.g. in a trigger request)

deserialize_intent_parameters(service_parameters, intent_cls, mappings)[source]

Cast parameters from Service format to Intents format according to the given schema. Typically this happens when a Connector has to turn prediction parameters into Intents entities.

Parameters
  • service_parameters (Dict[str, Any]) – The parameters dict, as it is returned by a Prediction Service

  • intent_cls (_IntentMetaclass) – The Intent parameters will be matched against

  • mappings (ServiceEntityMappings) – The Service Entity Mappings, to deserialize parameter values

Return type

Dict[str, EntityMixin]