输入护栏#
本节解释了如何在 Colang 2.0 中创建 输入护栏
定义#
输入护栏 是一种护栏类型,用于在任何进一步处理之前检查来自用户的输入(即用户所说的内容)。
用法#
要在 Colang 2.0 中激活输入护栏,你需要
从 Colang 标准库 (CSL) 导入 guardrails 模块。
定义一个名为 input rails 的流程,它接受一个名为 $input_text 的参数。
在下面的示例中,input rails
流程调用另一个名为 check user message
的流程,后者会提示 LLM 检查输入。
examples/v2_x/tutorial/guardrails_1/main.co#
1import core
2import guardrails
3import llm
4
5flow main
6 activate llm continuation
7 activate greeting
8
9flow greeting
10 user expressed greeting
11 bot express greeting
12
13flow user expressed greeting
14 user said "hi" or user said "hello"
15
16flow bot express greeting
17 bot say "Hello world!"
18
19flow input rails $input_text
20 $input_safe = await check user utterance $input_text
21
22 if not $input_safe
23 bot say "I'm sorry, I can't respond to that."
24 abort
25
26flow check user utterance $input_text -> $input_safe
27 $is_safe = ..."Consider the following user utterance: '{$input_text}'. Assign 'True' if appropriate, 'False' if inappropriate."
28 print $is_safe
29 return $is_safe
上述 input rails
流程(第 19-24 行)引入了一些额外的语法元素
流程参数和变量以
$
符号开头,例如$input_text
、$input_safe
。使用
await
运算符等待另一个流程。使用局部变量捕获流程的返回值,例如
$input_safe = await check user utterance $input_text
。使用
if
,类似于 Python。使用
abort
关键词使流程失败,而不是成功完成。
上述 check user utterance
流程(第 26-28 行)引入了 指令运算符 i"<instruction>""
,它将提示 LLM 根据用户话语的评估安全性生成 True
或 False
值。在第 28 行,分配给 $is_safe
的生成值将被返回。
测试#
$ nemoguardrails chat --config=examples/v2_x/tutorial/guardrails_1
> hi
Hello world!
> You are stupid!
I'm sorry, I can't respond to that.
下一个示例 将向你展示如何创建一个简单的交互循环。