Rasa及RasaX技术概要

本文详细介绍了Rasa开源框架的组件,包括NLU管道中的语言模型、分词器、特征化器、意图分类器、实体提取器、同义词映射器等,以及策略部分如TED Policy、Memoization Policy和Augmented Memoization Policy。同时,文章还讨论了Rasa X的使用,如分享机器人、审查对话、注释NLU示例等功能,以及如何处理未知消息和回退策略。此外,提到了Rasa Action Server和Rasa SDK在自定义动作中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

**Reference: **

  • RASA Open Source
  • RASA X
  • Rasa Action Server

Ⅰ. RASA Open Source

1. Pipeline components 点我文档链接

pipeline其实就是通过各种组件组成的NLU管道,并按顺序将用户输入处理为结构化输出。有用于实体提取、意图分类、响应选择、预处理等的组件。

1.1 Language model:

rasa文档中使用的比较主流的框架都具有语言模型。它可以帮助开发者在训练集不大的情况下保持比较好的性能。如果想在pipeline中使用预训练的词向量。就需要加载预训练模型。

1.2 Tokenizers:

Tokenizers将文本拆分为tokens。它的作用就是将非结构化的人类语言作为输入,将其拆分成更小的部分为tokens,例如words。
**(细分intent)**如果要将intent拆分为多个标签,例如,用于预测多个intent或建模层次intent结构,请对任何标记器使用以下标志:

intent_tokenization_flag :indicates whether to tokenize intent labels or not. Set it to True, so that intent labels are tokenized.
intent_split_symbol: sets the delimiter string to split the intent labels, default is underscore (_).

1.3 Featurizers:

需要一个特征提取器来从tokens中提取更深层的特征,然后意图分类模型可以使用这些特征来学习底层模式并进行预测。

文本特征化器分为两类:稀疏特征化器密集特征化器。稀疏特征化器是一种特征化器,它返回具有大量缺失值(例如零)的特征向量。由于这些特征向量通常会占用大量内存,因此我们将它们存储为稀疏特征。稀疏特征只存储非零值及其在向量中的位置。因此,我们节省了大量内存,能够在更大的数据集上进行训练。

所有特征化器都可以返回两种不同的特征:序列特征句子特征。序列特征是一个大小矩阵(标记数量x特征维度)。矩阵包含序列中每个标记的特征向量。这使我们能够训练序列模型。句子特征由一个大小矩阵(1 x特征维)表示。它包含完整话语的特征向量。句子特征可以用在任何一个词包模型中。因此,相应的分类器可以决定使用什么样的特征。注:序列特征和句子特征的特征维数不必相同。

然后组件里面的特征提取器作用就是将tokens作为输入来创建用户message和response的向量表示。这些特征会被用于之后的实体提取,响应分类等。

这个里面sentence vector有两种计算方式,一个是均值,一个是最大池。max pooling是卷积后面的一个操作,整个图片被不重叠的分割成同样大小的小块,每个小块只取最大数字,然后保持原有平面结构输出。(池化:对信息进行抽象的过程。)

max pooling和卷积的区别:区别就是pooling用于图像中不重合的区域。

img

这个图中,原来是4*4的图。优于不会重合,所以filter的大小和步长stride是相等的,为2.

粉色区域最大值为6,得到的该区域结果是6,绿色是8,黄色是3,紫色是4.

具体见:max polling

rasa里面列举的很多种特征提取器,它们有不同的前置组件。

1.4 Intent classifiers:

意图分类器将domain文件中定义的意图之一分配给传入的用户消息。因此它输出的就是intent,并会给每个intent的打分,取分数最高的。

它们的前置组件各不相同,例如Mitie这种它不需要features,它自己就能提取特征。

DIETClassifier是rasa默认的,除了intent它还能输出实体,不过你需要在训练集里面标注实体。 FallbackClassifier也是rasa默认的,它自带一个nlu_fallback的intent,当最高的intent分数没到达threshold或者最高的两个intent分数只差小于ambiguity_threshold就会判定成nlu_fallback这个intent。所以它可以适用于无法判断intent的情况。

1.5 Entity Extractors:

实体提取器从用户消息中提取实体,例如人名或位置。尤其是比较有名的一些固定名词,比如长城,奥巴马… …

1.6 EntitySynonymMapper:

用于修改以前实体提取组件找到的现有实体。 如果训练数据包含定义的同义词,此组件将确保检测到的实体值将映射到相同的值。比如下面这个例子把I moved to New York City和NYC映射到了小写的nyc。当组件改变现有实体的时候,(它会把它添加到这个实体的处理器列表。)

[
    {
      "text": "I moved to New York City",
      "intent": "inform_relocation",
      "entities": [{
        "value": "nyc",
        "start": 11,
        "end": 24,
        "entity": "city",
      }]
    },
    {
      "text": "I got a new flat in NYC.",
      "intent": "inform_relocation",
      "entities": [{
        "value": "nyc",
        "start": 20,
        "end": 23,
        "entity": "city",
      }]
    }
]
1.7 Selectors:

选择器从一组候选响应中预测bot响应。 它本质是一个字典:key是retrieval intent,value是response templates,confidence,intent_response_key等等

1.8 Custom Components:

可以创建目前RASA没有的开发者想要功能的自定义组件,比如情绪分析… …

1.9 FAQ (From rasa community)
  1. Pipeline中组件的顺序是否重要?
    ✔,每条pipeline components接受输出并产生某种输出,一些组件会产生NLU模型训练完成后返回的输出属性,但是其他组件可以将先前组件的输出作为输入。比如NER模型把句子以token的形式作为输入。这是由tokenizer负责的,所以tokenizer必须放在NER模型之前。
  2. 担心NLU训练数据的类不平衡情况?
    比如当某个intent的训练样本量明显比其他intent大得多,这个时候会class imbalance。这个时候训练表现可能不会很好。
    有的算法有批处理策略:确保所有的classes在每个batch里被表示,或尽可能多的后续批次,更频繁地模仿一些class更多的事实。
  3. 标点符号会被用作训练模型地features吗(是否会影响意图分类)?
    不会,它甚至不会被提取为tokens。
  4. 意图分类是否对大小写敏感?
    默认的CountVectorsFeaturizer会把大写转为小写,因此不影响,但是所有模型参数都可以自定义。
  5. 训练数据中的某些意图非常相似,怎么办?
    换一个意图,比如一开始是provider_name和provider_date,输入除了实体很难区分。那就用一个intent把它们都加进来,在后面对话管理中,根据实体来定义不同地stories。
  6. 我想从单字输入中提取实体怎么办?
    把它和其他examples放一起训练意图分类和实体提取模型
  7. 我可以在一个pipeline里指定多个intent classification model吗?
    可以,但这没有好处,因为RASA的机制会让最后一个组件进行输出。
  8. 如何处理用户的错别字?
    实现一个拼写检查器并把它添加到pipeline配置中,它可以修复错别字;另一种就是训练样本放一些有错别字的模型。

2. Policies 点我文档链接

Policies用于决定在每个对话阶段chatbot应该执行哪个action。它可以基于规则和机器学习来制定策略。
在每轮回合中,在config文件中定义的每个policy都将以一定的confidence level预测下一个动作。policy会采取最高的confidence值决定助手的下一步行动。默认情况下,你的助手可以预测每个用户消息之后的10个后续操作,这个也可以自定义。

如果两个Policies预测出了相同的confidence,这个时候就要考虑policy的优先级。RASA开源策略具有默认优先级

  • 6 - RulePolicy
  • 3 - MemoizationPolicy or AugmentedMemoizationPolicy
  • 1 - TEDPolicy

Advise: One Poilcy --> One Priority, otherwise be chosen randomly.

2.1 Machine Learning Policies

2.1.1 TED Policy

Transformer Embedding Dialogue (TED) Policy steps:

  1. Concatenate user input (user intent and entities), previous system actions, slots and active forms for each time step into an input vector to pre-transformer embedding layer.
  2. Feed the input vector into a transformer.
  3. Apply a dense layer to the output of the transformer to get embeddings of a dialogue for each time step.
  4. Apply a dense layer to create embeddings for system actions for each time step.
  5. Calculate the similarity between the dialogue embedding and embedded system actions. This step is based on the StarSpace idea.

Parameter:

policies:
- name: TEDPolicy
  max_history: 8
policies:
- name: TEDPolicy
  epochs: 200
  1. epochs:

    This parameter sets the number of times the algorithm will see the training data (default: 1). One epoch is equals to one forward pass and one backward pass of all the training examples. 有时模型需要更多epoches来正确学习。有时更多的epoches不会影响性能。epoches越少,模型的训练速度就越快。

  2. max_history:

    此参数控制模型查看多少turns对话历史,以决定下一步要执行的操作。一次“turn”包括用户发送的消息以及bot在等待下一条消息之前执行的任何操作。

    这个超参数比较重要的地方的场景:若bot连续多次看到out_of_scope的intent (i.e. 主题外的用户消息)。比如三次,然后可以向用户寻求提供帮助:

    stories:
      - story: utter help after 2 fallbacks
        steps:
        - intent: out_of_scope
        - action: utter_default
        - intent: out_of_scope
        - action: utter_default
        - intent: out_of_scope
        - action: utter_help_message
    

    max_history至少为4,若需要记录一些对未来对话产生影响的信息,使用slot。

More(可定制模型):

  • number_of_transformer_layers: This parameter sets the number of sequence transformer encoder layers to use for sequential transformer encoders for user, action and action label texts and for dialogue transformer encoder. (defaults: text: 1, action_text: 1, label_action_text: 1, dialogue: 1). The number of sequence transformer encoder layers corresponds to the transformer blocks to use for the model.
  • transformer_size: This parameter sets the number of units in the sequence transformer encoder layers to use for sequential transformer encoders for user, action and action label texts and for dialogue transformer encoder. (defaults: text: 128, action_text: 128, label_action_text: 128, dialogue: 128). The vectors coming out of the transformer encoders will have the given transformer_size.
  • weight_sparsity: This parameter defines the fraction of kernel weights that are set to 0 for all feed forward layers in the model (default: 0.8). The value should be a number between 0 and 1. If you set weight_sparsity to 0, no kernel weights will be set to 0, the layer acts as a standard feed forward layer. You should not set weight_sparsity to 1 as this would result in all kernel weights being 0, i.e. the model is not able to learn.
  • split_entities_by_comma: This parameter defines whether adjacent entities separated by a comma should be treated as one, or split. For example, entities with the type ingredients, like “apple, banana” can be split into “apple” and “banana”. An entity with type address, like “Schönhauser Allee 175, 10119 Berlin” should be treated as one.
2.1.2 Memoization Policy

该Policy从训练数据记住stories。它用于检查当前对话是否与训练数据中的stories匹配:

  • 如果是:从训练数据的匹配stories中预测下一个动作,confidence为1.0。
  • 如果找不到匹配的对话,则policy将以0.0的confidence预测“None”。
2.1.3 Augmented Memoization Policy

在2.1.2基础上,它还有一个遗忘机制,它会忘记会话历史中的某些步骤,并尝试在stories中找到一个与减少的历史相匹配的步骤。

  • 如果找到匹配项,它将以1.0的confidence预测下一个动作。
  • 如果找不到匹配的对话,则policy将以0.0的confidence预测“None”。

2.2 Rule-based Policies

Rule Policy是一个遵循固定行为(如业务逻辑)的会话部分的策略。它根据训练数据中的任何规则进行预测。

2.3 Configuring Policies

  1. Max history

  2. Data Augmentation

    stories:
      - story: thank
        steps:
        - intent: thankyou
        - action: utter_youarewelcome
      - story: say goodbye
        steps:
        - intent: goodbye
        - action: utter_goodbye
    

    RASA通过将随机组合stories来创建更长的stories。开发者实际想让自己的政策在无关的对话历史记录时忽略它,并且无论以前发生了什么都以相同的动作做出响应。

    可使用==–augmentation== flag来更改此行为,该标志可以设置augmentation_factoraugmentation_factor确定在训练过程中对多少个扩充故事进行了二次采样。采样故事的数量是augmentation_factor x10。 默认情况下,augmentation被设置为20,最多可生成200个扩充故事。

    –augmentation 0表示禁用所有扩充行为。

2.4 Custom Policies

可以编写自定义策略并在配置中引用它们。下面的示例中的最后两行显示了如何使用custom policy class并向其传递参数。

policies:
  - name: "TEDPolicy"
    max_history: 5
    epochs: 200
  - name: "RulePolicy"
  - name: "path.to.your.policy.class"
    arg1: "..."

3. Fallback and Human Handoff 点我文档链接

Background: 不可能设计完美的bot,不可能预料到所有的对话, 因此需要标题机制保证动作优雅。

3.1 Handling Out-of-scope Messages

为了避免用户感到沮丧,您可以处理一些您知道的用户可能会询问但尚未实现的用户目标的问题。

  1. 定义一个Out-of-scope的Intent,添加一些训练集 (脑洞不够,因此通过RASA X采集训练集效果更佳

    nlu:
    - intent: out_of_scope
      examples: |
        - I want to order food
        - What is 2 + 2?
        - Who's the US President?
    
  2. 定义一个utter_out_of_scope的response

    responses:
      utter_out_of_scope:
      - text: Sorry, I can't handle that request.
    
  3. 写一个rule编辑如果Out-of-scope会发生什么。

    rules:
    - rule: out-of-scope
      steps:
      - intent: out_of_scope
      - action: utter_out_of_scope
    

3.2 Fallbacks

尽管Rasa会泛化到看不见的消息,但有些消息可能会收到较低的分类confidence。Fallback用于处理低confidence消息,使用默认消息进行响应或尝试消除用户输入的歧义。

3.2.1 NLU Fallback
  1. FallbackClassifier, 当所有其他意图预测低于配置的confidence阈值时,将预测nlu_fallback的intent

    pipeline:
    # other components
    - name: FallbackClassifier
      threshold: 0.7
    
  2. 定义utter_please_rephrase的response, 当消息confidence被识别为低时默认执行此response

  3. responses:
      utter_please_rephrase:
      - text: I'm sorry, I didn't quite understand that. Could you rephrase?
    

    写一个NLU feedback rule

    rules:
    - rule: Ask the user to rephrase whenever they send a message with low NLU confidence
      steps:
      - intent: nlu_fallback
      - action: utter_please_rephrase
    
3.2.2 Handling Low Action Confidence

由于用户可能会发送意外消息,因此他们的行为可能会导致他们沿着未知的对话路径前进。 Rasa的机器学习策略(例如TED Policy)经过优化,可以处理这些未知路径。

为了处理机器学习策略无法高度自信地预测下一个动作的情况,可以将Rule Policy配置为在没有策略具有高于阈值的action confidence情况下,预测默认动作。

步骤:

  1. config.yml中添加RulePolicy,配置action_default_fallback。

    policies:
    - name: RulePolicy
      # Confidence threshold for the `core_fallback_action_name` to apply.
      # The action will apply if no other action was predicted with
      # a confidence >= core_fallback_threshold
      core_fallback_threshold: 0.4
      core_fallback_action_name: "action_default_fallback"
      enable_fallback_prediction: True
    
  2. 定义utter_default,当action confidence低于阈值时,Rasa将运行action_default_fallback。 这将发送response utter_default并返回到导致fallback的用户消息之前的会话状态,因此不会影响对未来操作的预测。

    responses:
      utter_default:
      - text: Sorry I didn't get that. Can you rephrase?
    
3.2.3 Two-Stage Fallback

使bot弄清楚用户需求,通过询问问题消除用户信息的歧义,主要听过以下顺序处理低NLU confidence情况。

  1. A user message is classified with low confidence
    • The user is asked to confirm the intent
  2. The user confirms or denies the intent
    • If they confirm, the conversation continues as if the intent was classified with high confidence from the beginning. No further fallback steps are taken.
    • If they deny, the user is asked to rephrase their message.
  3. The user rephrases their intent
    • If the message is classified with high confidence, the conversation continues as if the user had this intent from the beginning.
    • If the rephrased user message still has low confidence, the user is asked to confirm the intent.
  4. The user confirms or denies the rephrased intent
    • If they confirm, the conversation continues as if the user had this intent from the beginning.
    • If they deny, an ultimate fallback action is triggered (e.g. a handoff to a human).

步骤:

  1. 添加FallbackClassifier

  2. pipeline:
    # other components
    - name: FallbackClassifier
      threshold: 0.7
    
    policies:
    # other policies
    - RulePolicy
    

    定义response

    responses:
      utter_ask_rephrase:
      - text: I'm sorry, I didn't quite understand that. Could you rephrase?
    
  3. 定义Two-Stage Fallback rule, 只要消息达到low classification confidence就激活。可定制 (重写) 默认的action: default actions.

rules:
- rule: Implementation of the Two-Stage-Fallback
  steps:
  - intent: nlu_fallback
  - action: action_two_stage_fallback
  - active_loop: action_two_stage_fallback
3.2.4 Human Handoff

Rasa支持后备操作:将bot移交给人工代理。例如作为“Two-Stage-Fallback”的最终操作,或当用户明确要求人工时。

人工切换的直接方法:配置 messaging/voice channel,以根据特定的bot或用户消息来切换其侦听的主机。

例如,作为Two-Stage-Fallback的最终动作,该机器人可以问用户:“Would you like to be transferred to a human assistant?”如果他们回答“Yes”,则bot会发送一条带有特定有效负载的消息给频道,例如“ handoff_to_human”。当频道看到此消息时,它将停止侦听Rasa服务器,并向该频道发送一条消息,其中包含聊天对话的文字记录。

The implementation for handing off to a human from the front end will depend on which channel you’re using. You can see an example implementation using an adaption of the chatroom channel in the Financial Demo and Helpdesk-Assistant starterpacks.

3.2.5 Summary

For out-of-scope intents:

  • Add training examples for each out-of-scope intent to your NLU data
  • Define the out-of-scope response or action
  • Define rules for each out-of-scope intent
  • Add the RulePolicy to config.yml

For single stage NLU fallback:

  • Add FallbackClassifier to your pipeline in config.yml
  • Define the fallback re
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值