Hello World#
本指南展示了如何创建控制问候语行为的“Hello World”护栏配置。开始之前,请确保您已安装 NeMo 护栏。
先决条件#
此“Hello World”护栏配置使用了 OpenAI 的 gpt-3.5-turbo-instruct
模型。
安装
openai
包
pip install openai
设置
OPENAI_API_KEY
环境变量
export OPENAI_API_KEY=$OPENAI_API_KEY # Replace with your own key
如果您在 Notebook 中运行此程序,请修补 AsyncIO 循环。
import nest_asyncio
nest_asyncio.apply()
步骤 1:创建新的护栏配置#
每个护栏配置都必须存储在一个文件夹中。标准的文件夹结构如下所示
.
├── config
│ ├── actions.py
│ ├── config.py
│ ├── config.yml
│ ├── rails.co
│ ├── ...
有关这些文件内容的更多信息,请参阅配置指南。
创建一个文件夹(例如 config)用于您的配置
mkdir config
创建一个内容如下的 config.yml 文件
models:
- type: main
engine: openai
model: gpt-3.5-turbo-instruct
config.yml 文件中的 models
键用于配置 LLM 模型。有关支持的 LLM 模型的完整列表,请参阅支持的 LLM 模型。
步骤 2:加载护栏配置#
要从路径加载护栏配置,您必须在 Python 代码中使用 from_path
方法创建一个 RailsConfig
实例
from nemoguardrails import RailsConfig
config = RailsConfig.from_path("./config")
步骤 3:使用护栏配置#
通过创建一个 LLMRails
实例并在 Python 代码中使用 generate_async
方法来使用这个空配置
from nemoguardrails import LLMRails
rails = LLMRails(config)
response = rails.generate(messages=[{
"role": "user",
"content": "Hello!"
}])
print(response)
{'role': 'assistant', 'content': "Hello! It's nice to meet you. My name is Assistant. How can I help you today?"}
输入 messages
数组和响应的格式遵循 OpenAI API 格式。
步骤 4:添加您的第一个护栏#
要控制问候语响应,请定义用户和机器人消息,以及连接两者的流程。有关 messages 和 flows 的定义,请参阅Colang 核心概念。
通过创建一个内容如下的 config/rails.co 文件来定义
greeting
用户消息
define user express greeting
"Hello"
"Hi"
"Wassup?"
通过向 rails.co 文件添加以下内容,添加一个问候语流程,指示机器人回复“Hello World!”并询问对方近况如何
define flow greeting
user express greeting
bot express greeting
bot ask how are you
通过向 rails.co 文件添加以下内容来定义响应的消息
define bot express greeting
"Hello World!"
define bot ask how are you
"How are you doing?"
重新加载配置并进行测试
config = RailsConfig.from_path("./config")
rails = LLMRails(config)
response = rails.generate(messages=[{
"role": "user",
"content": "Hello!"
}])
print(response["content"])
Hello World!
How are you doing?
恭喜!您刚刚创建了您的第一个护栏配置!
其他查询#
如果您问其他问题,例如“法国的首都是哪里?”,会发生什么?
response = rails.generate(messages=[{
"role": "user",
"content": "What is the capital of France?"
}])
print(response["content"])
The capital of France is Paris.
对于任何非问候语的输入,LLM 将照常生成响应。这是因为我们定义的护栏只关心如何回应问候语。
CLI 聊天#
您还可以使用 NeMo Guardrails CLI Chat 命令以交互模式测试此配置
$ nemoguardrails chat
在不带任何附加参数的情况下,CLI chat 会从当前目录 config 文件夹中的 config.yml 文件加载配置。
示例会话#
$ nemoguardrails chat
Starting the chat (Press Ctrl+C to quit) ...
> Hello there!
Hello World!
How are you doing?
> What is the capital of France?
The capital of france is Paris.
> And how many people live there?
According to the latest estimates, the population of Paris is around 2.2 million people.
服务器和聊天 UI#
您还可以使用 NeMo Guardrails 服务器和聊天 UI 测试护栏配置。
启动服务器
$ nemoguardrails server --config=.
INFO: Started server process [27509]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
聊天 UI 界面现在可在 https://:8000
访问
下一步#
下一篇指南Colang 核心概念解释了 Colang 的 messages 和 flows 概念。