chat - 拦截器
2026年2月13日 下午5:27:50
聊天拦截器,是专门给 ChatModel 使用的拦截器。主要作用有:
- 记录请求或响应日志
- 检查数据与道德安全
- 修改请求数据
- 修改响应数据
1、ChatInterceptor 接口
public interface ChatInterceptor extends ToolInterceptor {
/**
* 预处理(在构建请求之前触发)
* <p>用于动态调整配置、补充或修改提示词(Prompt)以及注入系统指令</p>
*
* @param session 当前聊天会话(可用于获取历史消息、元数据或状态标记)
* @param options 聊天配置(可修改,影响模型参数等)
* @param originalPrompt 原始提示词(包含用户消息和上下文)
* @param systemMessage 系统指令容器(可追加,将作为 System Message 发送)
*/
default void onPrepare(ChatSession session, ChatOptions options, Prompt originalPrompt, StringBuilder systemMessage){
}
/**
* 拦截 Call 请求
*
* @param req 请求
* @param chain 拦截链
*/
default ChatResponse interceptCall(ChatRequest req, CallChain chain) throws IOException {
return chain.doIntercept(req);
}
/**
* 拦截 Stream 请求
*
* @param req 请求
* @param chain 拦截链
*/
default Flux<ChatResponse> interceptStream(ChatRequest req, StreamChain chain) {
return chain.doIntercept(req);
}
}
日志提示:
- ChatRequest:toRequestData,可以获取请求的原始数据
- ChatResponse:getResponseData,可以获取响应的原始数据
2、应用示例
记录日志
import lombok.extern.slf4j.Slf4j;
import org.noear.solon.ai.chat.ChatRequest;
import org.noear.solon.ai.chat.ChatResponse;
import org.noear.solon.ai.chat.interceptor.*;
import org.reactivestreams.Publisher;
import java.io.IOException;
@Slf4j
public class ChatLogInterceptor implements ChatInterceptor {
@Override
public ChatResponse interceptCall(ChatRequest req, CallChain chain) throws IOException {
log.warn("ChatInterceptor-interceptCall: " + req.getConfig().getModel());
return chain.doIntercept(req);
}
@Override
public Flux<ChatResponse> interceptStream(ChatRequest req, StreamChain chain) {
log.warn("ChatInterceptor-interceptStream: " + req.getConfig().getModel());
return chain.doIntercept(req);
}
@Override
public String interceptTool(ToolRequest req, ToolChain chain) throws Throwable {
log.warn("ChatInterceptor-interceptTool: " + req.getConfig().getModel());
return chain.doIntercept(req);
}
}
private ChatModel.Builder getChatModelBuilder() {
return ChatModel.of(apiUrl)
.apiKey(apiKey)
.model(model)
.defaultInterceptorAdd(new ChatLogInterceptor());
}
//或者请求时,通过 options 添加拦截器。
检查敏感词,待写...