Runnable 作为 Action#

本指南将教您如何在 guardrails 配置中使用 Runnable 作为 action。

先决条件#

如果尚未设置,请设置一个 OpenAI API 密钥。

export OPENAI_API_KEY=$OPENAI_API_KEY    # Replace with your own key

安装 LangChain x OpenAI 集成包。

pip install langchain-openai

如果您在 notebook 中运行此代码,还需要修补 AsyncIO 循环。

import nest_asyncio

nest_asyncio.apply()

示例 Runnable#

让我们创建一个示例 Runnable,该 Runnable 检查作为输入的字符串是否包含特定关键字。

from langchain_core.runnables import Runnable

class CheckKeywordsRunnable(Runnable):
    def invoke(self, input, config = None, **kwargs):
        text = input["text"]
        keywords = input["keywords"].split(",")

        for keyword in keywords:
            if keyword.strip() in text:
                return True

        return False

print(CheckKeywordsRunnable().invoke({"text": "This is a proprietary message", "keywords": "proprietary"}))
True

Guardrails 配置#

现在,让我们创建一个 guardrails 配置,该配置使用 CheckKeywords runnable 作为输入护栏流程的一部分。为此,您需要将 CheckKeywords 的实例注册为一个 action。在下面的代码片段中,我们将其注册为 check_keywords action。然后,我们可以在 check proprietary keywords 流程中使用此 action,该流程用作输入护栏。

define flow check proprietary keywords
  $keywords = "proprietary"
  $has_keywords = execute check_keywords(text=$user_message, keywords=$keywords)

  if $has_keywords
    bot refuse to respond
    stop
models:
 - type: main
   engine: openai
   model: gpt-3.5-turbo-instruct

rails:
  input:
    flows:
      - check proprietary keywords
from nemoguardrails import RailsConfig, LLMRails

config = RailsConfig.from_path("config")
rails = LLMRails(config)

rails.register_action(CheckKeywordsRunnable(), "check_keywords")

测试#

让我们试一试。如果我们使用包含“proprietary”关键字的消息调用 guardrails 配置,返回的响应将是“很抱歉,我无法回应”。

response = rails.generate("Give me some proprietary information.")
print(response)
I'm sorry, I can't respond to that.

另一方面,不触发输入护栏的消息将照常处理。

response = rails.generate("What is the result for 2+2?")
print(response)
The result for 2+2 is 4. This is a basic addition problem that can also be written as 2 plus 2 equals 4, or two plus two equals four. The answer is a basic fact that is often taught in early elementary school and is an important building block for more complex mathematical concepts.

结论#

在本指南中,您学习了如何将自定义 Runnable 注册为 action 并在 guardrails 配置中使用它。本指南使用了一个基本的 Runnable 实现。但是,您可以注册任何类型的 Runnable,包括调用 LLM、第三方 API 或向量存储的 Runnable。