API Reference

Model

Agent

The Agent base class is the entry point of your project. You will subclass it when defining your own Agent, and will later Agent.register() Intent classes and other resources into it.

Once the Agent is defined, you will connect it to a cloud service with a Connector, to make prediction and trigger requests.

class intents.model.agent.Agent[source]

As the name suggests, Agent is the base class that models an Agent definition within the Intents framework.

Typically, you will define a single Agent class in your project, that could be as simple as this:

from intents import Agent

class MyAgent(Agent):
    """A little docstring for your Agent"""

You can optionally define the languages that you intend to support. Intents will look for language resources based on the language class variable:

class MyAgent(Agent):
    """A little docstring for your Agent"""
    languages = ["en", "it"]

Languages are values from intents.language.LanguageCode. If omitted, Intents will discover language resources by itself.

You won’t do much more with your Agent class, other than registering intents and resources with Agent.register(), or passing it to a Connector to make predictions.

classmethod register(resource: Union[intents.model.intent._IntentMetaclass, module])[source]

Register the given resource in Agent. The resource could be:

  • An Intent

  • A module. In this case, the module is scanned (non recursively) for Intents, and each Intent is added individually

This is how you register a single intent:

from intents import Agent, Intent

class MyAgent(Agent):
    pass

@dataclass
class my_test_intent(Intent):
    """A little docstring for my Intent..."""
    a_parameter: str
    another_parameter: str

MyAgent.register(my_test_intent)

Alternatively, you can register a whole module containing Intents. This is how you register all the intents that are defined in the smalltalk module of example_agent:

from example_agent import smalltalk

class MyAgent(Agent):
    pass

MyAgent.register(smalltalk)

Note that together with each Intent, the Agent will register all of its linked resources, such as Entities, Events and Contexts.

Parameters

resource – The resource to register (an Intent, or a module containing Intents)

Intent

An intent is a categorical representation of the User intention in a single conversation turn. For instance, utterances like “I want a pizza”, “I’d like to order a pizza” and such, could be mapped to a single order_pizza intent.

Your agent will typically define a number of intents, representing all the types of messages the Agent can understand and answer to. This is done by defining Intent sub-classes and their language resources (see intents.language), and registering them to an intents.Agent class with intents.Agent.register().

class intents.model.intent.Intent[source]

Represents a predicted intent. This is also used as a base class for the intent classes that model a Dialogflow Agent in Python code.

In its simplest form, an Intent can be defined as follows:

from intents import Intent

class user_says_hello(Intent):
    """A little docstring for my Intent"""

Intents will then look for language resources in the folder where your Agent class is defined, and specifically in language/<LANGUAGE-CODE>/user_says_hello.yaml. More details in intents.language.

Intents can be more complex than this, for instance:

from dataclasses import dataclass
from intents import Intent, Sys

@dataclass
class user_says_hello(Intent):
    """A little docstring for my Intent"""

    user_name: Sys.Person

    name = "hello_custom_name"
    input_contexts = [a_context]
    input_contexts = [a_context(2), another_context(1)]

This Intent has a custom name (i.e. will appear as “hello_custom_name” when exported to Dialogflow), will be predicted only when a_context is active, and will spawn a_context, lasting 2 conversation turns, and another_context lasting only 1 conversation turn.

Most importantly, this intent has a user_name parameter of type Sys.Person (check out intents.model.entity.Sys for available system entities). With adequate examples in its language file, it will be able to match utterances like “Hello, my name is John”, tagging “John” as an Entity. When a connector is instantiated, predictions will look like this:

>>> predicted = connector.predict("My name is John")
user_says_hello(user_name="John") predicted.user_name "John"
predicted.fulfillment_text "Hi John, I'm Agent"

Last, we notice the @dataclass decorator. This isn’t really needed for the Intent to work, but adding it will have your IDE recognize the Intent class as a dataclass: you want autocomplete and static type checking when working with hundreds of intents in the same project.

classmethod from_prediction(prediction: intents.Prediction)Intent[source]

Build an Intent class from a Prediction. In practice:

  1. Match parameters givent the Intent schema

  2. Instantiate the Intent

  3. Set the prediction field on the instantiated Intent.

Note that this method is mostly for internal use, connectors will call it for you.

fulfillment_messages(response_group: intents.language.intent_language.IntentResponseGroup = <IntentResponseGroup.RICH: 'rich'>)List[intents.language.intent_language.IntentResponse][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:

>>> result.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
>>> result.fulfillment_messages(IntentResponseGroup.DEFAULT)
[TextIntentResponse(choices=['Nice, I can send you holiday pictures, or recommend an hotel'])]
classmethod parameter_schema()Dict[str, intents.model.intent.IntentParameterMetadata][source]

Return a dict representing the Intent parameter definition. A key is a parameter name, a value is a IntentParameterMetadata object.

TODO: consider computing this in metaclass to cache value and check types

class intents.model.intent.IntentParameterMetadata(name: str, entity_cls: intents.model.entity._EntityMetaclass, is_list: bool, required: bool, default: Any)[source]

Entity

Entities are special chunks of text in the User utterances, that are recognized and extratcted as parameters during predictions. For instance, in an utterance like “My name is John” we most likely want to match “John” as a Person Entity.

Two types of Entities exist:

  • System entities are built-in types that most chatbot frameworks will recognize (names, cities, numbers, emails, …). These are modelled in Sys.

  • Custom entities are user-defined entity types, that typically consist in a list of possible values and their synonims. For instance, a PizzaType custom entity will have values like “margherita”, “marinara”, “diavola” and so on, and each of these may define some synonims; this way, in an utterance like “I want a pepperoni pizza”, the “pepperoni” chunk can be recognized as a PizzaType parameter, and mapped to its correct name, which is “diavola”. Custom entities are defined by extending the Entity base class.

class intents.model.entity.Entity[source]

Custom Entities are defined by users to match parameters that are specific to the Agent’s domain. This is done by extending this class:

from dataclasses import dataclass
from intents import Intent, Entity

class PizzaType(Entity):
    """One of the pizza types that a Customer can order""" 

@dataclass
class customer_orders_pizza(Intent):
    """A little docstring for my Intent"""

    pizza_type: PizzaType

Language resources are expected for the PizzaType Entity. Like Intents, these will be looked up from the folder where the Agent main class is defined, and specifically in language/<LANGUAGE-CODE>/ENTITY_PizzaType.yaml. More details in intents.language.

class Meta(regex_entity: bool = False, automated_expansion: bool = False, fuzzy_matching: bool = False)[source]

This class is used to set user-controlled Entity parameters.

NOTE: usage of Meta is experimental, it may be removed in upcoming releases.

class intents.model.entity.EntityMixin[source]

This is a mixin class for entities, that adds from_df_response(), to build the Entity object from the match data in Dialogflow Responses.

classmethod from_df_response(match: Any)[source]

Buid the Entity object from the match data from a Dialogflow Response. Specifically, match is the dict version of queryResult.parameters.<PARAMETER_NAME>.

class intents.model.entity.Sys[source]

This is a container class, that defines all the system entities that are supported in the Intents framework. You can use system entities just like this:

from dataclasses import dataclass
from intents import Intent, Sys

@dataclass
class user_says_name(Intent):
    """A little docstring for my Intent"""

    user_name: Sys.Person

NOTE: This class can be expanded to contain more sophisticated entities, such as time intervals, amounts with measurement units and such. These may not be natively supported on every prediction service: some attention is needed to ensure portability.

class Color[source]

Words describing colors

class Date[source]

Matches a date as a Python datetime.date object

static from_py_date(py_date: datetime.date)[source]

Clone the given datetime.date object into a Sys.Date object. This is mostly for internal use.

class Email[source]

Any standard email address

class Integer[source]

Matches integers only

class Language[source]

Language names

class MusicArtist[source]

Matches the name of a music artist

class MusicGenre[source]

Matches a music genre (rock, pop, reggae, …)

class Person[source]

Matches common given names, last names or their combinations.

Note that in Dialogflow this is returned as an Object (e.g. {“name”: “John”}), while here we define Person as a String. The Dialogflow module defines proper entity mappings to handle the conversion.

class PhoneNumber[source]

Any standard phone number

class Time[source]

Matches a time reference as a Python datetime.time object

static from_py_time(py_time: datetime.time)[source]

Clone the given datetime.time object into a Sys.Time object. This is mostly for internal use.

class Url[source]

Any standard URL

class intents.model.entity.SystemEntityMixin[source]

This is used to signal that the entity is one of the Dialogflow default entities and doesn’t need language resources.

Context

Contexts allow the Agent to interpret utterances differently depending on the conversation state. An example of their usage can be found in example_agent.rickroll.

class intents.model.context.Context(lifespan)[source]

Context subclasses are generated from the Dialogflow agent. The name of the class corresponds to the name of the context.

>>> c_greetings.name
'c_greetings'
>>> c_greetings().name
'c_greetings'

Language

Language resources are defined separately from intent classes. They are stored as plain YAML files in a language/ folder, aside Agent Python modules; this is to be flexible in the relationship with designers and translators, as well as to allow some degree of automation when downloading cloud changes back to the local Agent definition (this feature is currently not implemented).

Your language/ folder will contain one subfloder per language (i.e. language/en/, language/it/, …); each of these will contain

Tip

It may be useful to look at The Example Agent code and language resources (https://github.com/dariowho/intents/tree/master/example_agent/language) to get more insight on the format and naming conventions of language files.

Intent language files have the following structure:

examples:
  - an example utterance
  - another example utterance
  - an example utterance with $foo{42} as a numeric parameter

slot_filling_prompts:
  foo:
    - Tell me the value for "foo"

responses:
  default:
    - text:
      - A plain text response
      - An alternative response
      - Another alternative, referencing $foo as a paramneter
  rich:
    - text:
      - A text response for rich clients
    - quick_replies:
      - a reply chip
      - another reply chip

Let’s look at the sections of this file.

  • examples contain example utterances that will be used to predict the given intent. If your intent has a parameter, it can be referenced as $parameter_name{example value}. You can omit this section if your intent is not meant to be predicted (some intents are trigger-only)

  • slot_filling_prompt are used when your intent has a mandatory parameter, and this parameter could not be matched in the user message. These prompts will be used to ask the User about that parameter. You can omit this section if your intent has no mandatory parameters, or if you don’t want to define custom prompts.

  • responses contain messages that Agent will send to User in response to the Intent. Two response groups are available:

class intents.language.intent_language.CardIntentResponse(title: str, subtitle: Optional[str] = None, image: Optional[str] = None, link: Optional[str] = None)[source]

A simple content card that can be rendered on many platforms.

In the YAML, this is defined as

Or an object with the image URL and a title, as in

rich:
  - card:
      title: The card title
      subtitle: An optional subtitle
      image: https://example.com/image.jpeg
      link: https://example.com/
class intents.language.intent_language.CustomPayloadIntentResponse(name: str, payload: dict)[source]

Custom Payloads are objects with arbitrary fields, they are supported by Dialogflow in every response group, including “Default”. Currently they can only be defined in the YAML as free form payloads; support for marshalling or generation from code is expected in future developments.

classmethod from_yaml(data: Dict[str, dict])[source]

In the YAML definition a custom payload is defined as follows

rich:
  - custom:
      custom_location:
        latitude: 45.484907
        longitude: 9.203299
        name: Piazza Duca D'Aosta, Milano

NOTE: while not currently enforced, consistency is expected between payload names and their fields. Future versions of the library will marshal custom payloads against dataclass schemas.

class intents.language.intent_language.EntityUtteranceChunk(entity_cls: intents.model.entity._EntityMetaclass, parameter_name: str, parameter_value: str)[source]

An Utterance Chunk that is a matched entity

class intents.language.intent_language.ExampleUtterance(example: str, intent: intents.Intent)[source]

One of the example Utterances of a given Intent.

chunks()[source]

Return the Utterance as a sequence of UtteranceChunk. Each chunk is either a plain text string, or a mapped Entity.

>>> utterance = ExampleUtterance("My name is $user_name{Guido}!", intents.user_gives_name)
>>> utterance.chunks()
[
    TextUtteranceChunk(text="My name is "),
    EntityUtteranceChunk(entity_cls=Sys.Person, parameter_name="user_name", parameter_value="Guido"),
    TextUtteranceChunk(text="!")
]

TODO: handle escaping

class intents.language.intent_language.ImageIntentResponse(url: str, title: Optional[str] = None)[source]

A simple image, defined by its URL and an optional title

In the YAML definition an image response can either be a string with the image URL, as in

rich:
  - image: https://example.com/image.png

Or an object with the image URL and a title, as in

rich:
  - image:
      url: https://example.com/image.png
      title: An example image
classmethod from_yaml(data: Union[str, List[str]])[source]

Instantiate an IntentResponse from language data, as it’s found in its YAML file. Typically, IntentResponse is a dataclass and data is a dict of fields; however specific subclasses may override with custom parameters.

class intents.language.intent_language.IntentLanguageData(example_utterances: List[intents.language.intent_language.ExampleUtterance], slot_filling_prompts: Dict[str, List[str]], responses: Dict[intents.language.intent_language.IntentResponseGroup, List[intents.language.intent_language.IntentResponse]])[source]

Language data for an Intent consists of three resources:

  • Example Utterances

  • Slot Filling Prompts

  • Responses

Example Utterances are the messages that Agent will be trained on to recognize the Intent.

Responses, intuitively, are the Agent’s response messages that will be sent to User once the Intent is recognized. They are divided in groups: a IntentResponseGroup.DEFAULT group (mandatory) can only contain plain text responses. A IntentResponseGroup.RICH group can provide intent responses that include cards, images and quick replies.

Slot Filling Promps are used to solve parameters that couldn’t be tagged in the original message. For instance a order_pizza intent may have a pizza_type parameter. When User asks “I’d like a pizza” we want to fill the slot by asking “What type of pizza?”. slot_filling_prompts will map parameters to their prompts: {“pizza_type”: [“What type of pizza?”]}

class intents.language.intent_language.IntentResponse[source]

One of the Response Utterances of a given Intent.

classmethod from_yaml(data: dict)[source]

Instantiate an IntentResponse from language data, as it’s found in its YAML file. Typically, IntentResponse is a dataclass and data is a dict of fields; however specific subclasses may override with custom parameters.

class intents.language.intent_language.IntentResponseGroup(value)[source]

Intent responses are divided in groups. The same intent can be answered with a set of plain-text responses (IntentResponseGroup.DEFAULT), or with rich content (IntentResponseGroup.RICH) that includes cards, images and quick replies.

class intents.language.intent_language.QuickRepliesIntentResponse(replies: List[str])[source]

A set of Quick Replies that can be used to answer the Intent. Each reply must be shorter than 20 characters.

In the YAML definition a quick replies response can either be a string, as in

rich:
  - quick_replies: Order Pizza

Or a list of replies, that will be rendered as separate chips

rich:
  - quick_replies:
    - Order Pizza
    - Order Beer
classmethod from_yaml(data: Union[str, List[str]])[source]

Instantiate an IntentResponse from language data, as it’s found in its YAML file. Typically, IntentResponse is a dataclass and data is a dict of fields; however specific subclasses may override with custom parameters.

class intents.language.intent_language.TextIntentResponse(choices: List[str])[source]

A plain text response. The actual response is picked randomly from a pool of choices.

In the YAML definition a text response can either be a string, as in

responses:
  default:
    - text: This is a response

Or a list of choices (the output fulfillment message will be chosen randomly among the different options)

responses:
  default:
    - text:
      - This is a response
      - This is an alternative response
classmethod from_yaml(data: Union[str, List[str]])[source]

Instantiate an IntentResponse from language data, as it’s found in its YAML file. Typically, IntentResponse is a dataclass and data is a dict of fields; however specific subclasses may override with custom parameters.

class intents.language.intent_language.TextUtteranceChunk(text: str)[source]

An Utterance Chunk that is a static, plain text string.

class intents.language.intent_language.UtteranceChunk[source]

An Example Utterance can be seen as a sequence of Chunks, where each Chunk is either a mapped Entity, or a plain text string.

class intents.language.entity_language.EntityEntry(value: str, synonyms: List[str])[source]

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 intents.service_connector.Connector(agent_cls: intents.model.agent._AgentMetaclass, default_session: Optional[str] = None, default_language: str = 'en')[source]
abstract export(destination: str)[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 – destination path of the exported Agent

abstract predict(message: str, session: Optional[str] = None, language: Optional[str] = None)intents.model.intent.Intent[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 Intent, representing the intent as it was predicted by the service.

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

  • session – Any string identifying a conversation

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

Returns

An instance of the predicted Intent class

abstract trigger(intent: intents.model.intent.Intent, session: Optional[str] = None, language: Optional[str] = None)intents.model.intent.Intent[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)
>>> df_result = df.trigger(smalltalk.agent_name_give(agent_name='Alice'))
agent_name_give(agent_name='Alice')
>>> df_result.fulfillment_text
"Howdy Human, I'm Alice"
>>> df_result.confidence
1.0
Parameters
  • intent – The Intent instance to trigger

  • session – Any string identifying a conversation

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

Returns

An instance of the triggered Intent class

abstract upload()[source]

Upload the connected Agent to the Prediction Service.

class intents.service_connector.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
abstract from_service(service_data: Any)intents.model.entity.SystemEntityMixin[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

Parameters

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

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'
abstract to_service(entity: intents.model.entity.SystemEntityMixin)Any[source]

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

Parameters

entity – the System Entity to serialize

Returns

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

class intents.service_connector.Prediction(intent_name: str, confidence: str, contexts: dict, parameters_dict: dict, fulfillment_messages: Dict[intents.language.intent_language.IntentResponseGroup, List[intents.language.intent_language.IntentResponse]], fulfillment_text: Optional[str] = None)[source]

This class is meant to abstract prediction results from a generic Prediction Service. It uses names from Dialogflow, as it is currently the only supported service

abstract property entity_mappings

A Prediction subclass must know the Entity Mappings of its Prediction Service. parameters() will use such mappings to convert parameters in parameters_dict to their generic Sys.* type.

parameters(schema: Dict[str, intents.model.intent.IntentParameterMetadata])Dict[str, Any][source]

Cast parameters in Prediction.parameters_dict according to the given schema. This is necessary, because parameter types are not known at prediction time, and therefore they need to be determined by the corresponding Intent class.

class intents.service_connector.ServiceEntityMappings[source]

Models a list of entity mappings. In addition to a standard list, two things are added:

  • Dict-like access to retrieve a mapping given its internal type (e.g. mappings[Sys.Integer])

  • 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 intents.service_connector.StringEntityMapping(entity_cls: intents.model.entity._EntityMetaclass, service_name: str)[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")
from_service(service_data: Any)intents.model.entity.SystemEntityMixin[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

Parameters

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

Returns

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

to_service(entity: intents.model.entity.SystemEntityMixin)Any[source]

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

Parameters

entity – the System Entity to serialize

Returns

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

Dialogflow ES

Here we implement DialogflowEsConnector, an implementation of Connector that allows Agents to operate on Dialogflow.

class intents.connectors.dialogflow_es.connector.DialogflowEsConnector(google_credentials: Union[str, google.auth.credentials.Credentials], agent_cls: intents.model.agent._AgentMetaclass, default_session: Optional[str] = None, default_language: str = 'en', rich_platforms: Iterable[str] = ('telegram'), webhook_configuration: Optional[intents.connectors.commons.WebhookConfiguration] = None)[source]

This is an implementation of Connector that enables Agents to work as Dialogflow projects.

An Agent can be connected to Dialogflow by providing its Agent class and service account credentials for the the Google Cloud project that hosts the Dialogflow ES agent:

from example_agent import ExampleAgent
from intents.connectors import DialogflowEsConnector
df = DialogflowEsConnector('/path/to/your/service-account-credentials.json', ExampleAgent)

The Connector can now be used, mainly to

Parameters
  • google_credentials – Path to service account JSON credentials, or a Credentials object

  • agent_cls – The Agent to connect

  • default_session – An arbitrary string to identify the conversation during predictions. Will be generated randomly if None

  • dedefault_language – Default language to use during predictions

  • rich_platforms – Platforms to include when exporting Rich response messages

  • webhook_configuration – Webhook connection parameters

export(destination: str)[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 – destination path of the exported Agent

property gcp_project_id

Return the Google Cloud Project ID that is associated with the current Connection

predict(message: str, session: Optional[str] = None, language: Optional[str] = None)intents.model.intent.Intent[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 Intent, representing the intent as it was predicted by the service.

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

  • session – Any string identifying a conversation

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

Returns

An instance of the predicted Intent class

trigger(intent: intents.model.intent.Intent, session: Optional[str] = None, language: Optional[str] = None)intents.model.intent.Intent[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)
>>> df_result = df.trigger(smalltalk.agent_name_give(agent_name='Alice'))
agent_name_give(agent_name='Alice')
>>> df_result.fulfillment_text
"Howdy Human, I'm Alice"
>>> df_result.confidence
1.0
Parameters
  • intent – The Intent instance to trigger

  • session – Any string identifying a conversation

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

Returns

An instance of the triggered Intent class

upload()[source]

Upload the connected Agent to the Prediction Service.

class intents.connectors.dialogflow_es.connector.DialogflowPrediction(intent_name: str, confidence: str, contexts: dict, parameters_dict: dict, fulfillment_messages: Dict[intents.language.intent_language.IntentResponseGroup, List[intents.language.intent_language.IntentResponse]], fulfillment_text: Optional[str] = None, df_response: Optional[google.cloud.dialogflow_v2.types.session.DetectIntentResponse] = None)[source]

This is an implementation of Prediction that comes from Dialogflow.

DialogflowPredictions are produced internally by DialogflowEsConnector, and automatically used to instantiate Intents in DialogflowEsConnector.predict and DialogflowEsConnector.trigger. Probably you won’t need to manually operate with Predictions.