之前使用 Bash Shell 脚本来实现的 Rasa 长对话流程的测试(多轮对话,因为很多 bug 只有在多轮对话的特定流程之后才会复现)。 但是,Shell 变量太难搞了,特别是单引号及双引号混用的情况。
例如,下面这段脚本:
#!/bin/bash
set -e # or use "set -o errexit" to quit on error.
set -x # or use "set -o xtrace" to print the statement before you execute it.
# 定义一个变量,值为 test_user_ 加上时间戳
user="test_user_$(date +%s)"
# 打印变量的值
echo "user: $user"
curl --request POST \
--url http://localhost:5005/webhooks/some_channel/webhook \
--header 'Content-Type: application/json' \
--data '{
"sender": "$user",
"text": "hi",
"metadata": {"some_var":"some_value"}
}'
sleep 1
curl --request POST \
--url http://localhost:5005/webhooks/some_channel/webhook \
--header 'Content-Type: application/json' \
--data '{
"sender": "$user",
"text": "\/some_intent{\"some_entity\": \"some_value\"}",
"metadata": {"some_var":"some_value"}
}'
sleep 1
这里有几个问题:
- $user 在单引号中是无法展开的。让 DeepSeek 推荐了几个替代方案,但是各有各的问题
- 如果 data 中的字段 value 中使用了双引号,还得转义,手写麻烦
- 如果能做成循环就很方便,但是这么多年我都记不住 shell 的循环语法
- 接口返回的 json,不方便做格式化打印。平时中 shell 中,我也是基于 python 实现的格式化 json
而使用 Python 就能很轻松地解决上面的所有问题。特别是既然已经使用了 rasa,那么开发环境里就内置了 Python,连 requests 依赖都内置了。 就能直接使用了,环境搭建都省去了。
而且使用 VSCode 中的 Github Copilot AI 直接就能将 Bash Shell 转换为 Python,修修补补就能使用了。
Python 测试脚本
import time
import requests
import json
# 全局变量
URL = "http://localhost:5005/webhooks/some_channel/webhook"
HEADERS = {"Content-Type": "application/json"}
SENDER = "test_user_" + str(int(time.time()))
METADATA = {"some_var": "some_value"}
# 定义 text 参数的列表
texts = [
"hi",
'/some_intent{"some_entity": "some_value"}',
"bye",
]
# 循环发送请求
for text in texts:
payload = {
"sender": SENDER,
"text": text,
"metadata": METADATA
}
# 打印当前时间
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(f"-------- Current time: {current_time} --------")
print(f"Sending payload: {text}")
response = requests.post(URL, headers=HEADERS, json=payload)
print(f"Response status code: {response.status_code}")
# 将 response.text 的 json 数据格式化输出
try:
response_json = response.json()
formatted_json = json.dumps(response_json, indent=4, ensure_ascii=False)
print(f"Response JSON:\n{formatted_json}\n")
except ValueError:
# 如果无法解析为 JSON,则输出原始文本
print("Response is not in JSON format.")
print(f"Response text: {response.text}\n")
time.sleep(1)
为了节省高级模型的配额,我仅仅使用了 gpt4o 效果就非常理想了。
查看合集
微信关注我哦 👍
我是来自山东烟台的一名开发者,有感兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式