node和rasa交互之可通信
1.2 通过node和rasa交互
1.2.1 配置
更改 config.yml
# The config recipe.
# https://rasa.com/docs/rasa/model-configuration/
recipe: default.v1
# The assistant project unique identifier
# This default value must be replaced with a unique assistant name within your deployment
assistant_id: 20241120-170106-khaki-margarine
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: zh # 改为中文
pipeline:
- name: JiebaTokenizer # 使用支持中文的 Tokenizer
- name: CountVectorsFeaturizer
analyzer: "word" # 基于分词结果生成特征
min_ngram: 1
max_ngram: 2
- name: DIETClassifier
epochs: 100
- name: EntitySynonymMapper
# - name: ResponseSelector
# epochs: 100
# # No configuration for the NLU pipeline was provided. The following default pipeline was used to train your model.
# # If you'd like to customize it, uncomment and adjust the pipeline.
# # See https://rasa.com/docs/rasa/tuning-your-model for more information.
# - name: RegexFeaturizer
# - name: LexicalSyntacticFeaturizer
# - name: CountVectorsFeaturizer
# analyzer: char_wb
# min_ngram: 1
# max_ngram: 4
# constrain_similarities: true
# constrain_similarities: true
# - name: FallbackClassifier
# threshold: 0.3
# ambiguity_threshold: 0.1
# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
# policies:
# - name: TEDPolicy
# max_history: 5
# epochs: 100
# constrain_similarities: true
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.
# - name: MemoizationPolicy
# - name: RulePolicy
# - name: UnexpecTEDIntentPolicy
# max_history: 5
# epochs: 100
policies:
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.
# - name: MemoizationPolicy
# - name: RulePolicy
# - name: UnexpecTEDIntentPolicy
# max_history: 5
# epochs: 100
# - name: TEDPolicy
# max_history: 5
# epochs: 100
# constrain_similarities: true
注意:别忘了先进虚拟环境,因为 jieba-0.42.1
的兼容性问题,我还把 setuptools
降级了
pip install setuptools==67.6.1
1.2.2 训练模型
然后重新训练模型
rasa train
1.2.3 启动 rasa 服务器
rasa run -m models --enable-api --cors "*" --debug
1.2.4 apipost 测试及可用路由

启动成功后即可使用接口访问
可用的 Web 服务器路由有以下这些:
/conversations/<conversation_id:path>/messages POST add_message
/conversations/<conversation_id:path>/tracker/events POST append_events
/webhooks/rasa GET custom_webhook_RasaChatInput.health
/webhooks/rasa/webhook POST custom_webhook_RasaChatInput.receive
/webhooks/rest GET custom_webhook_RestInput.health
/webhooks/rest/webhook POST custom_webhook_RestInput.receive
/model/test/intents POST evaluate_intents
/model/test/stories POST evaluate_stories
/conversations/<conversation_id:path>/execute POST execute_action
/domain GET get_domain
/ GET hello
/model PUT load_model
/model/parse POST parse
/conversations/<conversation_id:path>/predict POST predict
/conversations/<conversation_id:path>/tracker/events PUT replace_events
/conversations/<conversation_id:path>/story GET retrieve_story
/conversations/<conversation_id:path>/tracker GET retrieve_tracker
/status GET status
/model/predict POST tracker_predict
/model/train POST train
/conversations/<conversation_id:path>/trigger_intent POST trigger_intent
/model DELETE unload_model
/version GET version
具体来说:
1./conversations/<conversation_id:path>/messages
-
方法:
POST
-
功能:向指定的对话会话发送一条消息。
-
用途:用户与机器人交互的主要端点,用于发送用户消息并触发 Rasa 的响应。
-
参数:
conversation_id
:对话会话的唯一标识符。- 请求体中需要提供用户消息。
-
示例:
{ "sender": "user_1", "message": "你好" }
2./conversations/<conversation_id:path>/tracker/events
-
方法:
POST
-
功能:手动向会话的 tracker(追踪器)中添加事件。
-
用途:用于模拟事件流,或在测试和调试时添加自定义事件。
-
示例:
{ "event": "user", "text": "Hello", "timestamp": 1625146462.123 }
3./webhooks/rasa
和 /webhooks/rasa/webhook
-
方法:
GET
(/webhooks/rasa
):用于检查 Rasa webhook 的健康状态。POST
(/webhooks/rasa/webhook
):用于通过 Rasa 自定义输入通道发送消息。
-
用途:这些端点与自定义的输入通道集成,例如,来自外部平台的消息。
-
示例:
{ "sender": "test_user", "message": "Hello Rasa" }
4./webhooks/rest
和 /webhooks/rest/webhook
-
方法:
GET
(/webhooks/rest
):检查 REST 输入通道的健康状态。POST
(/webhooks/rest/webhook
):通过 REST API 与 Rasa 交互,用于标准化的 REST 输入。
-
用途:适用于通过 REST 与 Rasa 进行消息传递的场景。
-
示例:
{ "sender": "test_user", "message": "你好" }
1.2.5 Node.js与rasa响应的交互
创建一个 index.js
node.js 代码如下:
需要注意的是,这里使用的是 127.0.0.1
,笔者试过 localhost
会失败,127.0.0.1
可以强制使用 ipv4
const express = require('express');
const axios = require('axios');
const bodyParser = require('body-parser');
const app = express();
const port = 6000;
// 中间件
app.use(bodyParser.json());
// 定义与 Rasa 交互的端点
app.post('/webhook', async (req, res) => {
const userMessage = req.body.message;
const senderId = req.body.sender || 'default';
if (!userMessage) {
return res.status(400).json({ error: "Message is required" });
}
try {
// 发送用户消息到 Rasa
const response = await axios.post('http://127.0.0.1:5005/webhooks/rest/webhook', {
sender: senderId,
message: userMessage
});
// 收集 Rasa 的响应
const rasaResponses = response.data.map(r => r.text).filter(text => text);
// 返回响应到客户端
res.json({ replies: rasaResponses });
} catch (error) {
console.error('Error communicating with Rasa:', error.message);
// 检查 Axios 错误并处理
if (error.response) {
// Rasa 服务返回了非 2xx 状态
res.status(error.response.status).json({ error: error.response.data });
} else if (error.request) {
// 没有收到 Rasa 的响应
res.status(500).json({ error: 'No response from Rasa server' });
} else {
// 请求配置错误
res.status(500).json({ error: 'Request error: ' + error.message });
}
}
});
// 启动服务器
app.listen(port, () => {
console.log(`Node.js server is running on http://localhost:${port}`);
});
good,good

END
本文主要实现node和rasa的交互,这样为后面node介入rasa奠定基础,目前实现的是node获取rasa响应后的结果,从接口访问rasa然后返回rasa的结果。涉及如何配置,训练模型,启动rasa服务器,打通路由,交互。
写博客是写给未来的自己,会看到自己思想的演变
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?