You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将HTML标签属性传递至Rasa的Python Action文件?代码实现后返回None

问题描述

我已创建自定义Connector,使用jQuery调用Webhook API,尝试将HTML标签的属性传递到Rasa的Action文件中,但获取自定义数据时返回None。

相关代码片段

1. index.html

<html>
<body>
    <div id="rasa-chat-widget" api-key="E7paWtyYWZ0LmNvbV96QTVhOXc5UHBiQ9e" data-websocket-url="http://localhost:5005"></div>
    <script src="https://unpkg.com/@rasahq/rasa-chat@0.1.5/dist/widget.js" type="application/javascript"></script>
</body>

<script>
    $(document).ready(function() {
            
            var api_key   = $("#rasa-chat-widget").attr('api-key');
            console.log('API KEY...',api_key);
            var attributes = {
                "get_api_key": api_key,
            };
            $.ajax({
                url: "http://localhost:5055/webhook/",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify({
                    "sender": "user",
                    "message": 'userInput',
                    "attributes": attributes
                }),
                success: function(response) {
                    console.log("Message sent successfully:", response);
                },
                error: function(error) {
                    console.error("Error sending message:", error);
                }
            });
    });
</script>

2. 自定义Connector文件

from rasa.core.channels.channel import InputChannel, UserMessage, OutputChannel
from sanic import Blueprint, response

class MyCustomConnector(InputChannel):
    @classmethod
    def name(cls):
        return "my_custom_connector"

    def blueprint(self, on_new_message):
        custom_webhook = Blueprint("custom_webhook", __name__)

        @custom_webhook.route("/", methods=["GET"])
        async def health(request):
            return response.json({"status": "ok"})

        @custom_webhook.route("/webhook", methods=["POST"])
        async def receive(request):
            payload = request.json
            sender_id = payload.get("sender", None)
            text = payload.get("message", None)
            attributes = payload.get("attributes", {})
            print('ATTRIBUTES....',attributes)
            out_channel = self.get_output_channel()
            if text:
                await on_new_message(
                    UserMessage(text, out_channel, sender_id, input_channel=self.name(), metadata=attributes)
                )
            return response.json({"status": "message received"})

        return custom_webhook

    def get_output_channel(self) -> OutputChannel:
        return CollectingOutputChannel()

class CollectingOutputChannel(OutputChannel):
    @classmethod
    def name(cls):
        return "my_custom_connector_output"

    async def send_text_message(self, recipient_id, text, **kwargs):
        print(f"Sending message to {recipient_id}: {text}")

3. actions/action.py 代码片段

# Retrieve custom attributes
custom_attributes = tracker.latest_message.get('metadata', {})
print('CUSTOM ATTRIBUTES...',custom_attributes)
custom_attribute1 = custom_attributes.get("get_api_key")
print('CUSTOM ATTRIBUTES API...',custom_attribute1)

4. credentials.yml

socketio:
  user_message_evt: user_uttered
  bot_message_evt: bot_uttered
  session_persistence: true
  my_custom_connector.MyCustomConnector:

5. endpoints.yml

action_endpoint:
  url: "http://localhost:5055/webhook"
  cors: true

问题排查与修复方案

1. 核心错误:端口混淆

你混淆了Rasa Core和Action Server的端口用途:

  • http://localhost:5005 是Rasa Core服务端口,自定义Connector的Webhook路由挂载在此服务上
  • http://localhost:5055 是Action Server端口,仅用于Rasa Core调用自定义Action,不接收前端请求

修复: 修改jQuery中的请求URL:

url: "http://localhost:5005/webhook",

2. Credentials.yml 配置错误

自定义Connector被错误嵌套在socketio配置下,导致Rasa无法加载该通道。

修复后credentials.yml:

socketio:
  user_message_evt: user_uttered
  bot_message_evt: bot_uttered
  session_persistence: true

my_custom_connector.MyCustomConnector: {}

说明:自定义通道配置需与socketio同级,不能缩进嵌套。

3. 启动命令需指定自定义通道

启动Rasa Core时,必须显式指定加载自定义通道,否则服务不会启用该Connector:

rasa run --enable-api --cors "*" --credentials credentials.yml --endpoints endpoints.yml --channel my_custom_connector

4. 补全自定义Action结构

确保Action类正确继承并实现run方法,否则无法正常获取metadata:

from typing import Any, Text, Dict, List
from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher

class ActionGetApiKey(Action):
    def name(self) -> Text:
        return "action_get_api_key"

    def run(self, dispatcher: CollectingDispatcher,
            tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        
        # Retrieve custom attributes
        custom_attributes = tracker.latest_message.get('metadata', {})
        print('CUSTOM ATTRIBUTES...',custom_attributes)
        custom_attribute1 = custom_attributes.get("get_api_key")
        print('CUSTOM ATTRIBUTES API...',custom_attribute1)
        
        dispatcher.utter_message(text=f"API Key received: {custom_attribute1}")
        return []

验证步骤

  1. 按上述修改所有配置与代码
  2. 启动Rasa Core:执行上述指定通道的启动命令
  3. 启动Action Server:rasa run actions --port 5055
  4. 刷新前端页面,查看Rasa控制台是否打印ATTRIBUTES....日志
  5. 触发自定义Action,查看Action服务日志是否成功获取到get_api_key值

内容的提问来源于stack exchange,提问作者pratham rajdev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:53:15