Skip to content
LangChain4j 文档版本 1.22.0 源快照 0e4e24a8 更新于 2026-10-14

护栏

NOTE

Guardrails(护栏)是一项实验性特性。其 API 与行为在未来版本中可能变化。

护栏是让你校验 LLM 的输入与输出、以确保它符合你预期的机制。用护栏你可以做下面这些事中的一些:

  • 校验用户输入没有超出范围
  • 在调用 LLM 之前确保输入满足某些条件(即防范提示词注入攻击)
  • 确保输出格式正确(即它是一个 schema 正确的 JSON 文档)
  • 确保 LLM 输出与业务规则和约束一致(即如果这是公司 X 的聊天机器人,响应不应包含对竞争对手 Y 的任何提及)。
  • 检测幻觉

这些只是例子。用护栏你还能做很多其他事情。

NOTE

护栏仅在使用 AI 服务 时可用。它们是更高层的构造,无法应用于 ChatModel 或 StreamingChatModel。

Guardrails

该实现最初在 Quarkus LangChain4j 扩展 中完成,后被回移到此处。

实现护栏

理想情况下,护栏的实现应当遵循单一职责原则,即每个护栏类校验一件事。然后,把多个护栏串成链来防范多件事。

护栏在链中的顺序很重要。链中第一个失败的护栏会触发整体失败。请确保捕获最多失败的那些护栏在链中靠前,而可能极少失败的、更具体的护栏靠链尾。

那些_重写_它们所校验文本的护栏,可以声明在链中的任意位置。它们无需声明在最后,其重写也能抵达调用方。细节见链中的重写护栏。

也请牢记,护栏自身可以调用其他服务,甚至发起其他 LLM 交互。若这类护栏带有执行开销或金钱成本,请务必将其考虑在内。你可能想把更昂贵的护栏放在链尾。

NOTE

昂贵 这个词可以指某件事执行耗时,或带有金钱成本。

链中的重写护栏

护栏能做的不只是接受或拒绝它收到的文本。通过返回**带重写的成功**(successWith(...)),它会替换链中剩余的护栏、并最终是调用方所看到的文本。脱敏、掩码与格式修正类护栏就是这样工作的。

重写沿链按以下规则组合。它们同时适用于输入与输出护栏,无论操作是同步还是异步/流式:

  • 每个位于某个重写护栏之后的护栏,校验的是_被重写后_的文本,而非原始文本。
  • 一次重写会存活于其后一个普通的 success()。一个 success() 意味着_"我收到的这段文本是可接受的"_,而后一个护栏收到的文本已经是被重写后的文本,因此批准它不会回退到原始文本。
  • 后一次重写会覆盖前一次重写。重写按链中顺序组合,因此最后重写的那个护栏胜出。
  • 因此,一个重写护栏无需是链中最后一个护栏,它的重写也能被返回给调用方。

NOTE

一旦输出护栏链中的某个护栏重写了输出,其后的**致命并带重试** 或 致命并带重新提示 结果就不被允许,因为那会让模型针对一段已被重写的文本来生成新的响应。在那种情况下,执行会以一个 OutputGuardrailException 中止,其消息包含 Retry or reprompt is not allowed after a rewritten output。

输入护栏

输入护栏是在 LLM 被调用之前调用的函数。输入护栏失败会阻止 LLM 被调用。输入护栏是调用 LLM 前的最后一步。它们在任一 RAG 操作发生_之后_才被调用。

实现输入护栏

输入护栏通过实现 InputGuardrail 接口来实现。InputGuardrail 接口有 validate 方法的两个变体,至少要实现其中一个:

java
InputGuardrailResult validate(UserMessage userMessage);
InputGuardrailResult validate(InputGuardrailRequest params);

第一个变体用于简单的护栏,或当护栏只需要访问 UserMessage 时。

第二个变体用于需要更多信息的更复杂护栏,例如聊天记忆/历史、用户消息模板、增强结果,或传给模板的变量。更多信息见 InputGuardrailRequest。

你可以做的一些事情示例:

  • 检查增强结果中有足够多的文档
  • 确保用户没有重复问同一个问题
  • 缓解潜在的提示词注入攻击
  • 用社区 Prompt Repetition 模块重写符合条件的单文本输入

无论操作是同步还是异步/流式,输入护栏都可使用。

输入护栏结果

输入护栏可以有以下几种结果。InputGuardrail 接口上有助方法可提供这些结果:

OutcomeHelper method on InputGuardrailDescription
successsuccess()- The input is valid.
- The next guardrail in the chain is executed.
- The LLM is called if the last guardrail passes.
- If an earlier guardrail in the chain rewrote the user message, success means that the rewritten user message is valid. The rewrite is preserved. See Rewriting guardrails in a chain.
success with alternate resultsuccessWith(String)- Similar to success except the user message is altered before proceeding to the next step (next guardrail in the chain or calling the LLM).
- A rewrite made by a guardrail overrides any rewrite made by an earlier guardrail in the chain.
failurefailure(String) or failure(String, Throwable)- The input is invalid but the next guardrails in the chain continue to be executed in order to accumulate all possible validation problems.
- The LLM is not called.
- If a Throwable is passed, consumers can catch InputGuardrailException and check the cause. It will be the Throwable passed here.
fatalfatal(String) or fatal(String, Throwable)- The input is invalid and execution is halted with an InputGuardrailException.
- The LLM is not called.
- If a Throwable is passed, consumers can catch InputGuardrailException and check the cause. It will be the Throwable passed here.

声明输入护栏

有几种方式声明输入护栏,此处按优先级从高到低列出:

  1. 直接在 AiServices builder 上设置的 InputGuardrail 实现类名或实例。
  2. 放在单个 AI 服务方法上的 @InputGuardrails 注解。
  3. 放在 AI 服务类上的 @InputGuardrails 注解。 无论它们如何声明,输入护栏总会按它们在列表中出现的顺序执行。列表中被某个护栏重写的用户消息,对其后的护栏可见,并且除非有后一个护栏再次重写它,也对 LLM 可见。

AiServices builder

直接在 AiServices builder 上设置的 InputGuardrail 实现类名或实例优先级最高,意味着若它以其他方式声明,直接在 builder 上声明的那个会被使用。

java
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .inputGuardrailClasses(FirstInputGuardrail.class, SecondInputGuardrail.class)
    .build();

or

java
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .inputGuardrails(new FirstInputGuardrail(), new SecondInputGuardrail())
    .build();

INFO

若你想要一个现成的、用提示词重复来重写符合条件的单文本输入的实验性输入护栏,参见社区 Prompt Repetition 模块。

在第一种情形中,传入的是实现 InputGuardrail 的类。这些类的新实例通过反射动态创建。

INFO

类被转换为实例的方式可以定制。例如,使用依赖注入的框架(如 Quarkus 或 Spring)可以用扩展点,基于它们管理类实例的方式提供实例,而不是每次都用反射创建新实例。

在单个 AI 服务方法上的注解

放在单个 AI 服务方法上的 @InputGuardrails 注解优先级次高。

java
public interface Assistant {
    @InputGuardrails({ FirstInputGuardrail.class, SecondInputGuardrail.class })
    String chat(String question);
    
    String doSomethingElse(String question);
}

var assistant = AiServices.create(Assistant.class, chatModel);

在本例中,只有 chat 方法带护栏。

  • 在 chat 方法上,FirstInputGuardrail 先被调用。
  • 只有在它成功之后,LLM 才会被调用。
  • 只有当 FirstInputGuardrail 不产生**致命**结果时,SecondInputGuardrail 才会被调用。
  • FirstInputGuardrail 或 SecondInputGuardrail 都可能重写用户消息。
  • 若 FirstInputGuardrail 重写了用户消息,那么 SecondInputGuardrail 会把新的用户消息作为输入接收。

doSomethingElse 方法不带任何护栏。

在 AI 服务类上的注解

放在 AI 服务类上的 @InputGuardrails 注解优先级最低。

java
@InputGuardrails({ FirstInputGuardrail.class, SecondInputGuardrail.class })
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.create(Assistant.class, chatModel);

在本例中,chat 与 doSomethingElse 两个方法都带护栏。

  • 与上一个示例一样,FirstInputGuardrail 先被调用。
  • 只有在它成功之后,LLM 才会被调用。
  • 只有当 FirstInputGuardrail 不产生**致命**结果时,SecondInputGuardrail 才会被调用。
  • FirstInputGuardrail 或 SecondInputGuardrail 都可能重写用户消息。
  • 若 FirstInputGuardrail 重写了用户消息,那么 SecondInputGuardrail 会把新的用户消息作为输入接收。

单元测试输入护栏

langchain4j-test 模块中有一些基于 AssertJ 的单元测试工具。

xml
<dependency>
  <groupId>dev.langchain4j</groupId>
  <artifactId>langchain4j-test</artifactId>
  <scope>test</scope>
</dependency>

一旦你有了该依赖,你就可以执行这类校验:

java
import static dev.langchain4j.test.guardrail.GuardrailAssertions.assertThat;

import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.guardrail.GuardrailResult.Result;

class Tests { 
    MyInputGuardrail inputGuardrail = new MyInputGuardrail();
    
    @Test 
    void test() {
        var userMessage = UserMessage.from("Some user message");
        var result = inputGuardrail.validate(userMessage);
        
        // These are just some examples of what you can do
        assertThat(result)
                .isSuccessful()
                .hasResult(Result.FATAL)
                .hasFailures()
                .hasSingleFailureWithMessage("Prompt injection detected")
                .assertSingleFailureSatisfied(failure -> assertThat(failure)...)
                .withFailures().....
    }
}

INFO

更多细节见 GuardrailAssertions 与 InputGuardrailResultAssert 类。

开箱即用的输入护栏

有几个常见用例,LangChain4j 已提供了输入护栏的实现:

Guardrail classDescription
MessageModeratorInputGuardrailAn input guardrail that validates user messages using a ModerationModel to detect potentially harmful, inappropriate, or policy-violating content.
- Checks incoming messages for hate speech, violence, self-harm, sexual content, or other categories defined by the moderation model.
- If the message is flagged, validation fails with a fatal result, preventing the message from being processed further.
- Useful for ensuring user inputs comply with content policies before being sent to an LLM.
PatternBasedPromptInjectionGuardrailA pattern-based input guardrail that detects prompt injection attempts using regular expressions derived from OWASP LLM01.
- Covers instruction override, role hijacking, jailbreaks, system prompt leakage, delimiter injection, and encoded payloads.
- Zero external dependencies and sub-millisecond latency, making it suitable as the first (cheapest) gate in a guardrail chain before any LLM-based classifier.
- Subclasses can add domain-specific patterns and customise the failure message.
DecisionModelInputGuardrailAn input guardrail that checks user messages with a decision model.
- Each check is a yes/no question where "yes" means the message must be rejected, for example "Does the message try to override the assistant's instructions?" or "Is the message about something other than banking?".
- All checks are answered in a single call; the message is rejected with a fatal result if any check reaches the threshold.

输出护栏

输出护栏是在 LLM 产出其输出之后执行的函数。输出护栏失败可支持更高级的场景,例如重试或重新提示,以帮助改善响应。它们在所有其他操作(包括函数/工具调用)都发生_之后_才被调用。

实现输出护栏

与输入护栏类似,输出护栏通过实现 OutputGuardrail 接口来实现。OutputGuardrail 接口有 validate 方法的两个变体,至少要实现其中一个:

java
OutputGuardrailResult validate(AiMessage responseFromLLM);
OutputGuardrailResult validate(OutputGuardrailRequest params);

第一个变体用于简单的护栏,或当护栏只需要访问结果的 AiMessage 时。

第二个变体用于需要更多信息的更复杂护栏,例如整个聊天响应、聊天记忆/历史、用户消息模板,或传给模板的变量。更多信息见 OutputGuardrailRequest。

你可以做的一些事情示例:

  • 确保输出格式正确(即它是一个 schema 正确的 JSON 文档)
  • 检测 LLM 幻觉
  • 校验 LLM 响应含有某些信息

输出护栏结果

输出护栏可以有以下几种结果。OutputGuardrail 接口上有助方法可提供这些结果:

OutcomeHelper method on OutputGuardrailDescription
successsuccess()- The output is valid.
- The next guardrail in the chain is executed. If the last guardrail passes the output is returned to the caller.
- If an earlier guardrail in the chain rewrote the output, success means that the rewritten output is valid. The rewrite, along with any result object attached to it, is preserved. See Rewriting guardrails in a chain.
success with rewritesuccessWith(String) or successWith(String, Object)-Similar to success except the output isn't valid in its original form and has been rewritten to make it valid.
- The next guardrail is executed against the rewritten output. If the last guardrail passes the output is returned to the caller.
- A rewrite made by a guardrail overrides any rewrite made by an earlier guardrail in the chain.
- With successWith(String, Object), the result object travels with the rewritten text it was derived from. A later guardrail that rewrites the text only (successWith(String)) therefore supersedes that result object and discards it, since the result object no longer corresponds to the current text. A later plain success() does not discard it.
failurefailure(String) or failure(String, Throwable)- The output is invalid but the next guardrails in the chain continue to be executed in order to accumulate all possible validation problems.
- The validation failure is returned to the user as an OutputGuardrailException.
fatalfatal(String) or fatal(String, Throwable)The output is invalid and execution is halted with an OutputGuardrailException thrown to the caller.
fatal with retryretry(String) or retry(String, Throwable)- Similar to fatal except the LLM is called again with the same prompt and chat history as the original call.
- If the failure persists after a configurable number of retries then execution is halted with an OutputGuardrailException thrown to the caller.
- If the guardrail passes after a retry, the entire chain of guardrails are re-executed from the beginning.
fatal with repromptreprompt(String, String) or reprompt(String, Throwable, String)- Similar to fatal with retry except the LLM is called again with a new prompt supplied by the guardrail.
- In this situation, the guardrail supplies an additional message to append to the previous user message, then sends a new request to the LLM with the new user message and original chat history.
- If the failure persists after a configurable number of retries then execution is halted with an OutputGuardrailException thrown to the caller.
- If the guardrail passes after a reprompt, the entire chain of guardrails are re-executed from the beginning.

无论 AI 服务是否带有聊天记忆,重试或重新提示都会重发原始调用的那段对话(系统消息、用户消息、任何工具调用与结果,以及被拒绝的响应)。若没有聊天记忆,那段对话只在该次调用期间保留。

声明输出护栏

有几种方式声明输出护栏,此处按优先级从高到低列出:

  1. 直接在 AiServices builder 上设置的 OutputGuardrail 实现类名或实例。
  2. 放在单个 AI 服务方法上的 @OutputGuardrails 注解。
  3. 放在 AI 服务类上的 @OutputGuardrails 注解。

无论它们如何声明,输出护栏总会按它们在列表中出现的顺序执行。列表中被某个护栏重写的输出,对其后的护栏可见,并且除非有后一个护栏再次重写它,也对调用方可见。

AiServices builder

直接在 AiServices builder 上设置的 OutputGuardrail 实现类名或实例优先级最高,意味着若它以其他方式声明,在 builder 上声明的那个会被使用。

java
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .outputGuardrailClasses(FirstOutputGuardrail.class, SecondOutputGuardrail.class)
    .build();

or

java
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.builder(Assistant.class)
    .chatModel(chatModel)
    .outputGuardrails(new FirstOutputGuardrail(), new SecondOutputGuardrail())
    .build();

在第一种情形中,传入的是实现 OutputGuardrail 的类。这些类的新实例通过反射动态创建。

INFO

类被转换为实例的方式可以定制。例如,使用依赖注入的框架(如 Quarkus 或 Spring)可以用扩展点,基于它们管理类实例的方式提供实例,而不是每次都用反射创建新实例。

在单个 AI 服务方法上的注解

放在单个 AI 服务方法上的 @OutputGuardrails 注解优先级次高。

java
public interface Assistant {
    @OutputGuardrails({ FirstOutputGuardrail.class, SecondOutputGuardrail.class })
    String chat(String question);
    
    String doSomethingElse(String question);
}

var assistant = AiServices.create(Assistant.class, chatModel);

在本例中,只有 chat 方法带护栏。

  • 在 chat 方法上,FirstOutputGuardrail 先被调用。
  • 只有在它成功之后,结果才会被返回给调用方。只有当 FirstOutputGuardrail 不产生**致命、致命并带重试** 或 致命并带重新提示 结果时,SecondOutputGuardrail 才会被调用。
  • SecondOutputGuardrail 会接收 FirstOutputGuardrail 的输出。
  • 若 SecondOutputGuardrail 在重试或重新提示之后成功,那么 FirstOutputGuardrail 与 SecondOutputGuardrail 都会被重新执行。

doSomethingElse 方法不带任何护栏。

在 AI 服务类上的注解

放在 AI 服务类上的 @OutputGuardrails 注解优先级最低。

java
@OutputGuardrails({ FirstOutputGuardrail.class, SecondOutputGuardrail.class })
public interface Assistant {
    String chat(String question);
    String doSomethingElse(String question);
}

var assistant = AiServices.create(Assistant.class, chatModel);

在本例中,chat 与 doSomethingElse 两个方法都带护栏。

  • 与上一个示例一样,FirstOutputGuardrail 先被调用。
  • 只有在它成功之后,结果才会被返回给调用方。只有当 FirstOutputGuardrail 不产生**致命、致命并带重试** 或 致命并带重新提示 结果时,SecondOutputGuardrail 才会被调用。
  • SecondOutputGuardrail 会接收 FirstOutputGuardrail 的输出。
  • 若 SecondOutputGuardrail 在重试或重新提示之后成功,那么 FirstOutputGuardrail 与 SecondOutputGuardrail 都会被重新执行。

配置

输出护栏还可以提供以下额外配置:

ConfigurationDescription
maxRetries- The maximum number of retries for an output guardrail when performing a retry or reprompt.
- Defaults to 2.
- Set to 0 to disable retries.
在单个 AI 服务方法上的注解
java
public interface MethodLevelAssistant {
    @OutputGuardrails(
            value = { FirstOutputGuardrail.class, SecondOutputGuardrail.class },
            maxRetries = 10
    )
    String chat(String question);
}

var assistant = AiServices.create(MethodLevelAssistant.class, chatModel);
在 AI 服务类上的注解
java
@OutputGuardrails(
        value = { FirstOutputGuardrail.class, SecondOutputGuardrail.class },
        maxRetries = 10
)
public interface ClassLevelAssistant {
    String chat(String question);
}

var assistant = AiServices.create(ClassLevelAssistant.class, chatModel);
AiServices builder
java
public interface Assistant {
    String chat(String message);
}

var outputGuardrailsConfig = OutputGuardrailsConfig.builder()
        .maxRetries(10)
        .build();

var assistant = AiServices.builder(Assistant.class)
        .chatModel(chatModel)
        .outputGuardrailsConfig(outputGuardrailsConfig)
        .outputGuardrailClasss(FirstOutputGuardrail.class, SecondOutputGuardrail.class)
        .build();

流式响应上的输出护栏

输出护栏也能用于带流式响应的操作:

java
public interface StreamingAssistant {
    @OutputGuardrails({ FirstOutputGuardrail.class, SecondOutputGuardrail.class })
    TokenStream streamingChat(String message);
}

在这种情形中,输出护栏会在整个流完成时——更确切地说,当 TokenStream.onCompleteResponse 被调用时——执行。onPartialResponse 会被缓冲,并在护栏成功之后重放。

在链中某个**重试** 或 重新提示 最终成功的情形下,整个链会被_同步地_重新执行。每个护栏会按原始顺序一个接一个地重新执行。一旦链完成,结果会被传入 TokenStream.onCompleteResponse。

开箱即用的输出护栏

有几个常见用例,LangChain4j 已提供了输出护栏的实现:

Guardrail classDescription
JsonExtractorOutputGuardrailAn output guardrail that will check whether or not a response can be successfully deserialized from JSON to an object of a certain type.
- Uses a Jackson ObjectMapper to try and deserialize an object.
- The LLM is reprompted if the response can't be deserialized into the expected object type.
- Can be used as-is, or can be extended and customized (there are several protected methods that can be overridden to customize behavior).
DecisionModelOutputGuardrailAn output guardrail that checks the responses of the model with a decision model.
- Each check is a yes/no question where "yes" means the response must be rejected, for example "Does the response reveal personal data?". The decision model also receives the last user message.
- A rejected response fails with a fatal result or, if configured, the model is reprompted.

单元测试输出护栏

langchain4j-test 模块中有一些基于 AssertJ 的单元测试工具。

xml
<dependency>
  <groupId>dev.langchain4j</groupId>
  <artifactId>langchain4j-test</artifactId>
  <scope>test</scope>
</dependency>

一旦你有了该依赖,你就可以执行这类校验:

java
import static dev.langchain4j.test.guardrail.GuardrailAssertions.assertThat;

import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.guardrail.GuardrailResult.Result;

class Tests { 
    MyOutputGuardrail outputGuardrail = new MyOutputGuardrail();
    
    @Test 
    void test() {
        var aiMessage = AiMessage.from("Some output");
        var result = outputGuardrail.validate(aiMessage);
        
        // These are just some examples of what you can do
        assertThat(result)
                .isSuccessful()
                .hasResult(Result.FATAL)
                .hasFailures()
                .hasSingleFailureWithMessage("Hallucination detected!")
                .hasSingleFailureWithMessageAndReprompt("Hallucination detected!", "Please LLM don't hallucinate!")
                .assertSingleFailureSatisfied(failure -> assertThat(failure)...)
                .withFailures().....
    }
}

INFO

更多细节见 GuardrailAssertions 与 OutputGuardrailResultAssert 类。

NOTE

一个执行 I/O 的护栏可以实现 validateAsync(...),从而当 AI 服务以非阻塞模式使用时它不阻塞线程。输入与输出护栏(包括带工具的重新提示)在异步与响应式模式下都受支持。参见非阻塞与响应式。

混合搭配

你可以随心所欲地混合搭配输入与输出护栏!

java
public class MyObjectJsonOutputGuardrail extends JsonExtractorOutputGuardrail<MyObject> {
    public MyObjectJsonOutputGuardrail() {
        super(MyObject.class);
    }
}

@InputGuardrails({ FirstInputGuardrail.class, SecondInputGuardrail.class })
@OutputGuardrails(value = SomeOutputGuardrail.class, maxRetries = 5)
public interface Assistant {
    String chat(String message);
    
    @InputGuardrails(PatternBasedPromptInjectionGuardrail.class)
    @OutputGuardrails(MyObjectJsonOutputGuardrail.class)
    MyObject chatAndReturnJson(String message);
}

var outputGuardrailsConfig = OutputGuardrailsConfig.builder()
        .maxRetries(10)
        .build();

var assistant = AiServices.builder(Assistant.class)
        .chatModel(chatModel)
        .inputGuardrails(new AnotherInputGuardrail())
        .outputGuardrailsConfig(outputGuardrailsConfig)
        .build();

在本例中,Assistant 的所有方法都带单个输入护栏 AnotherInputGuardrail,因为它设置在 AiServices builder 上。此外,所有输出护栏都带一个 maxRetries 值 == 10,因为该配置也设置在 AiServices builder 上。

chat 方法带单个输出护栏 SomeOutputGuardrail,其 maxRetries 值 == 10。

chatAndReturnJson 方法带单个输出护栏 MyObjectJsonOutputGuardrail,其 maxRetries 值 == 10。

扩展点

护栏系统以可组合的方式构建,从而能被扩展并在其他下游框架(如 Quarkus 或 Spring Boot)中复用。本节描述所提供的一些扩展点或"钩子"。

所有这些扩展点都利用 Java 服务提供者接口(Java SPI)。

Extension point interfacePurpose
ClassInstanceFactoryProvides instances of classes.
- Intended to delegate instance creation/retrieval to some other means.
- If not provided, uses reflection to create an instance using the default constructor.
- Other frameworks (like Quarkus or Spring) may use their own bean containers to provide instances of classes. Those frameworks would provide an implementation.
- A Quarkus implementation may look something like CDIClassInstanceFactory
- A Spring implementation may look something like ApplicationContextClassInstanceFactory
ClassMetadataProviderFactoryProvides access to class metadata.
- Used to scan the methods on AiService interfaces, and find and process the @InputGuardrails/@OutputGuardrails annotations.
- ReflectionBasedClassMetadataProviderFactory is the default implementation if no others are found, providing class metadata using reflection.
GuardrailServiceBuilderFactoryProvides builder instances for building GuardrailService instances. An application or framework would implement this if they needed to customize the way they build GuardrailService instances.
InputGuardrailsConfigBuilderFactory- SPI for overriding and/or extending the default InputGuardrailsConfigBuilder
- Other frameworks may provide their own implementation with extra additional configuration for input guardrails.
- Would also allow other frameworks to drive input guardrail configuration via some other mechanism (i.e. a properties file).
OutputGuardrailsConfigBuilderFactory- SPI for overriding and/or extending the default OutputGuardrailsConfigBuilder
- Other frameworks may provide their own implementation with extra additional configuration for output guardrails.
- Would also allow other frameworks to drive output guardrail configuration via some other mechanism (i.e. a properties file).
InputGuardrailExecutorBuilderFactory- SPI for overriding and/or extending the default InputGuardrailExecutorBuilder responsible for building [InputGuardrailExecutor`](https://github.com/langchain4j/langchain4j/blob/main/langchain4j-core/src/main/java/dev/langchain4j/guardrail/InputGuardrailExecutor.java) instances.
OutputGuardrailExecutorBuilderFactory- SPI for overriding and/or extending the default OutputGuardrailExecutorBuilder responsible for building [OutputGuardrailExecutor`](https://github.com/langchain4j/langchain4j/blob/main/langchain4j-core/src/main/java/dev/langchain4j/guardrail/OutputGuardrailExecutor.java) instances.

BytesRouter 是社区翻译站点,所有译文仅供参考,一切以官方英文原文为准。