Python API#

在您的项目中使用 guardrails 的主要方式是

  1. 创建一个 RailsConfig 对象。

  2. 创建一个 LLMRails 实例,该实例提供了一个 LLM 接口,用于自动应用配置的 guardrails。

  3. 使用 LLMRails.generate(...)LLMRails.generate_async(...) 方法生成 LLM 响应。

基本用法#

from nemoguardrails import LLMRails, RailsConfig

config = RailsConfig.from_path("path/to/config")

app = LLMRails(config)
new_message = app.generate(messages=[{
    "role": "user",
    "content": "Hello! What can you do for me?"
}])

RailsConfig#

RailsConfig 类包含用于配置 guardrails 的关键信息

  • models:rails 配置使用的模型列表。

  • user_messages:应该用于 rails 的用户消息列表。

  • bot_messages:应该用于 rails 的 bot 消息列表。

  • flows:应该用于 rails 的 flows 列表。

  • instructions:自然语言指令列表(目前仅支持通用指令)。

  • docs:知识库中包含的文档列表。

  • sample_conversation:在 prompts 中使用的示例对话。

  • actions_server_url:要使用的 actions 服务器。如果指定,actions 将通过 actions 服务器执行。

消息生成#

要使用 guardrails 配置,您可以调用 LLMRails.generateLLMRails.generate_async 方法。

LLMRails.generate 方法接受 promptmessages 数组作为输入。当提供 prompt 时,guardrails 的应用方式类似于单轮对话。消息的结构如下

properties:
  role:
    type: "string"
    enum: ["user", "assistant", "context"]
  content:
    oneOf:
      - type: "string"
      - type: "object"

对话历史记录的示例如下

[
  {
    "role": "user",
    "content": "Hello!"
  },
  {
    "role": "assistant",
    "content": "Hello! How can I help you?"
  },
  {
    "role": "user",
    "content": "I want to know if my insurance covers certain expenses."
  }
]

以下示例也设置了初始上下文

[
  {
    "role": "context",
    "content": {
      "user_name": "John",
      "access_level": "admin"
    }
  },
  {
    "role": "user",
    "content": "Hello!"
  },
  {
    "role": "assistant",
    "content": "Hello! How can I help you?"
  },
  {
    "role": "user",
    "content": "I want to know if my insurance covers certain expenses."
  }
]

Actions#

Actions 是 Guardrails 工具包的关键组件。Actions 可以在 guardrails 内部执行 python 代码。

默认 Actions#

以下是工具包中包含的默认 actions

核心 actions

  • generate_user_intent:生成用户所说内容的规范形式。

  • generate_next_step:生成当前对话流程中的下一步。

  • generate_bot_message:根据所需的 bot 意图生成 bot 消息。

  • retrieve_relevant_chunks:从知识库中检索相关 chunks 并将其添加到上下文中。

Guardrail 特定 actions

  • self_check_facts:根据从知识库中提取的相关 chunks 检查上次 bot 响应的事实。

  • self_check_input:检查是否应允许用户输入。

  • self_check_output:检查是否应允许 bot 响应。

  • self_check_hallucination:检查上次 bot 响应是否是幻觉。

为了方便起见,此工具包还包括精选的 LangChain 工具,这些工具被包装为 actions

  • apifyApify 是一个网络抓取和网络自动化平台,使您能够构建自己的网络爬虫和网络抓取器。

  • bing_searchBing Web Search API 的包装器。

  • google_search:来自 Langchain 的 Google Search API 的包装器。

  • searx_searchSearx API 的包装器。Google/Bing Search 的替代方案。

  • google_serper:SerpApi Google Search API 的包装器。它可用于从 Google Search 添加答案框和知识图谱。

  • openweather_queryOpenWeatherMap’s API 的包装器,用于检索天气信息。

  • serp_api_querySerpAPI API 的包装器。它提供对搜索引擎的访问,并帮助回答有关时事的问题。

  • wikipedia_queryWikipedia API 的包装器。它使用 MediaWiki API 从 Wikipedia 检索信息。

  • wolfram_alpha_queryWolfram Alpha API 的包装器。它可用于回答数学和科学问题。

  • zapier_nla_queryZapier NLA API 的包装器。它提供对超过 5k 个应用程序和 20k 个 actions 的访问,以自动化您的工作流程。

Chains as Actions#

您可以使用 LLMRails.register_action 方法将 Langchain chain 注册为 action

app.register_action(some_chain, name="some_chain")

当 chain 作为 action 调用时,action 的参数对应于 chain 的输入键。对于返回值,如果 chain 的输出只有一个键,则将返回该值。如果 chain 有多个输出键,则返回输出键及其值的字典。有关更多详细信息,请参阅 LangChain 集成指南

自定义 Actions#

您可以使用 action 装饰器或使用 LLMRails(RailsConfig).register_action(action: callable, name: Optional[str]) 将任何 python 函数注册为自定义 action。

from nemoguardrails.actions import action

@action()
async def some_action():
    # Do some work

    return "some_result"

默认情况下,action 的名称设置为函数名称。但是,您可以通过指定不同的名称来更改它。

from nemoguardrails.actions import action

@action(name="some_action_name")
async def some_action():
    # Do some work

    return "some_result"

Actions 可以接受任意数量的参数。由于 actions 是从 Colang flows 调用的,因此参数的类型仅限于 stringintegerfloatbooleanlistdictionary

特殊参数#

以下参数是特殊的,如果它们出现在 action 的签名中,NeMo Guardrails 工具包会自动提供这些参数

  • events:到目前为止的事件历史记录;最后一个是触发 action 本身的事件;

  • context:action 可用的上下文数据;

  • llm:访问 LLM 实例(来自 LangChain 的 BaseLLM);

  • config:完整的 RailsConfig 实例。

这些参数仅供高级用例使用。

Action 参数#

以下是可在 actions 中使用的参数

参数

描述

类型

示例

events

到目前为止的事件历史记录;最后一个是触发 action 本身的事件。

List[dict]

[     {'type': 'UtteranceUserActionFinished', ...},     {'type': 'StartInternalSystemAction', 'action_name': 'generate_user_intent', ...},      {'type': 'InternalSystemActionFinished', 'action_name': 'generate_user_intent', ...} ]

context

action 可用的上下文数据。

dict

{ 'last_user_message': ...,  'last_bot_message': ..., 'retrieved_relevant_chunks': ... }

llm

访问 LLM 实例(来自 LangChain 的 BaseLLM)。

BaseLLM

OpenAI(model="gpt-3.5-turbo-instruct",...)