8.0
热点
AI SCORE
编程提效2026-08-21 02:32
ScopedAgent:生产级知识边界AI Agent模板
dev.to · AI#RAG#Agent#LangChain
Editor brief · 编辑速览
在Next.js 14+LangChain中构建有界RAG系统,通过Pre-Retrieval Scope Guard在向量检索前过滤越界提问,避免幻觉和无关代码生成。
通用 RAG 入门套件的问题
标准检索增强生成(Retrieval-Augmented Generation,RAG)入门套件通常存在一个主要缺陷:作用域无边界。
当用户向 SaaS 产品的客服机器人请求"写一个爬取网站的 Python 脚本"或"解释二叉搜索树"时,传统 RAG 系统仍然会查询向量数据库并尽力回答——往往会产生幻觉或生成与公司毫无关系的任意代码。
ScopedAgent 通过在向量搜索或文档摄入之前引入**检索前作用域守卫层(Pre-Retrieval Scope Guard Layer)**来解决这个问题。
核心架构与流程
每个 prompt 都遵循这一严格工作流:

关键技术实现
lib/agent/scope-guard.ts)在访问 ChromaDB 或文档存储之前,查询会被预先分类为允许或拒绝类别(writing_code、generic_technical、off_topic、jailbreak_attempt)。
const ClassificationSchema = z.object({
category: z.enum([
"in_scope",
"writing_code",
"generic_technical",
"competitor_analysis",
"personal_advice",
"off_topic",
"jailbreak_attempt",
]),
confidence: z.number().min(0).max(1),
reasoning: z.string(),
sanitized_query: z.string(),
});
export async function classifyQuery(
query: string,
context: string,
config: Config,
llm: BaseChatModel
): Promise<Classification> {
const chain = SCOPE_GUARD_PROMPT.pipe(
(llm as any).withStructuredOutput(ClassificationSchema)
);
return chain.invoke({
company: config.agent.company,
allowed_topics: config.scope.allowed_topics.map((t) => `- ${t}`).join("\n"),
query,
context: context || "None",
});
}
lib/providers/index.ts)开发者和最终用户可以直接在 UI 顶部或配置中选择偏好的 AI 模型:
gpt-4o, gpt-4o-miniclaude-3-5-sonnetgemini-1.5-flashhttp://localhost:11434)、LM Studio(http://localhost:1234)以及自定义 OpenAI 兼容端点。scopedagent.config.ts)开发者只需编辑一个配置文件来定义代理的作用域规则、公司身份和自定义拒绝响应:
export default defineConfig({
agent: {
name: "Aria",
company: "Northpeak Software",
role: "Customer Support Assistant",
},
scope: {
allowed_topics: [
"product features and how-to questions",
"pricing and plan comparisons",
"billing and refund policy",
],
refused_categories: [
"writing_code",
"generic_technical",
"off_topic",
"jailbreak_attempt",
],
confidence_threshold: 0.72,
fallback_message: "I don't have enough info on that. Contact support@northpeak.io.",
},
});
管理后台分析看板(/admin)
每次超出作用域的尝试都会被持久化到 SQLite(lib/db/queries.ts),为开发者提供以下实时指标:
试用与贡献