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,用于检查作为输入提供的字符串是否包含某些关键字。

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 作为输入 rail 流程的一部分。为了实现这一点,您需要将 CheckKeywords 的实例注册为 action。在下面的代码片段中,我们将其注册为 check_keywords action。然后,我们可以在 check proprietary keywords 流程中使用此 action,该流程用作输入 rail。

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 配置,则返回的响应是“I’m sorry, I can’t respond to that”。

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

另一方面,不触发输入 rail 的消息将照常进行。

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 或向量存储的那些。