基于 CopilotKit 构建法律文档审查 Agent:AI 高亮、合规分析与修订建议的完整实践
基于 CopilotKit 构建法律文档审查 Agent:AI 高亮、合规分析与修订建议的完整实践
本篇技术指南围绕社区 Hacktoberfest 示例 Legal Document Reviewer(关联文档)展开:以 CopilotKit 为核心,结合 React、Next.js、Gemini、Shadcn-UI 与 Tailwind CSS,构建一个能够分析法律文档、高亮关键章节并给出合规与清晰度修订建议的 Agent 系统。阅读本文后,你将掌握 CopilotKit 前后端接入方式、前端 Action(工具)注册、Generative UI 渲染与人工确认(Human-in-the-Loop)等关键技术,具备独立复刻同类文档审查类 Agent 的实战能力。
一、功能目标:法律文档审查 Agent 要解决什么
原文档将该示例定位为 Hacktoberfest Demo,核心任务是:
Develop a system where AI agents analyze legal documents, highlight important sections, and suggest revisions to ensure compliance and clarity.
拆解开来,这个系统需要具备三项核心能力:
- 文档分析(Analyze):AI Agent 读取用户粘贴或上传的法律文本,识别其中的条款、义务、风险点与潜在不合规内容;
- 高亮重要章节(Highlight):对关键段落(如赔偿条款、终止条款、保密义务、违约责任)进行视觉化标记,便于用户快速定位;
- 建议修订(Suggest Revisions):针对表述含糊、可能存在合规风险的原文,生成改写建议,保证文本的合规性(compliance)与清晰度(clarity)。
这三项能力天然适配 CopilotKit 的 Generative UI 与 Human-in-the-Loop 模式:分析结果不是以纯文本形式丢给用户,而是以结构化的审查卡片、高亮面板渲染在聊天界面中;修订建议则可以在用户确认后再写入文档,形成"Agent 提议 → 用户审批 → 落地修改"的闭环。
二、技术选型与架构分层
原文档明确列出的技术栈如下:
| 技术 | 在本项目中的角色 |
|---|---|
| CopilotKit | 核心组件:连接前端 UI 与 AI Agent,提供聊天、工具调用、Generative UI 与状态同步 |
| React.js | 用户界面构建 |
| Next.js | React 框架,提供 App Router 路由与 API 路由(Serverless 后端部署) |
| Gemini | 驱动 CopilotKit 的底层大模型(Developer Tools 标注为 "CopilotKit powered with Gemini") |
| Shadcn-UI | 组件库,构建高亮卡片、审查面板等界面元素 |
| Tailwind CSS | 工具类优先的样式框架 |
| TypeScript | 类型安全,可选用 |
从仓库结构看,CopilotKit 官方正是以这套技术组合作为主推形态:examples/v2/react/ 目录下的 React 示例全部采用 Next.js App Router + TypeScript,前端通过 @copilotkit/react-core/v2 接入,后端通过 @copilotkit/runtime/v2 暴露 Agent 端点;Gemini 接入有独立示例(examples/canvas/gemini),且在官方 v2 示例中 Gemini 是被直接支持的模型后端之一。
整个系统的架构可以归纳为三层:
- 前端层:Next.js 页面内嵌入
CopilotChat组件,通过useFrontendTool(或 v1 的useCopilotAction)注册"分析文档""高亮条款""生成修订"等前端工具; - 协议层:CopilotKit 通过 AG-UI 协议将前端工具描述、Agent 消息、Generative UI 渲染指令在前后端之间流转(见 README.md 中关于 AG-UI 的说明);
- 后端层:Next.js API 路由内运行
CopilotRuntime,挂载内置 Agent 与语言模型,可额外注册后端 Action(如调用文档解析服务、合规知识库)。
三、后端接入:CopilotRuntime 与模型配置
后端是整个系统的大脑所在。在 Next.js App Router 中,标准的接入方式是创建 src/app/api/copilotkit/<a href="https://link.gitcode.com/i/27e25d1b978827ec9ad050558ba48643" target="_blank">[...slug]]/route.ts,实例化 CopilotRuntime 并通过 Hono 的 handle 导出 GET / POST。仓库中的官方 v2 示例([route.ts)给出了可直接参考的骨架:
import {
CopilotRuntime,
createCopilotEndpoint,
InMemoryAgentRunner,
BuiltInAgent,
} from "@copilotkit/runtime/v2";
import { handle } from "hono/vercel";
const builtInAgent = new BuiltInAgent({
model: determineModel(), // 依据环境变量选择模型
prompt: "You are a helpful AI assistant.",
});
const runtime = new CopilotRuntime({
agents: { default: builtInAgent },
runner: new InMemoryAgentRunner(),
});
const app = createCopilotEndpoint({
runtime,
basePath: "/api/copilotkit",
});
export const GET = handle(app);
export const POST = handle(app);
在本示例中,由于底层模型是 Gemini,determineModel 分支中可以直接返回 "google/gemini-3.8-flash"(该模型 ID 出现在官方示例的模型选择逻辑中,对应 GOOGLE_API_KEY 环境变量)。你也可以借鉴官方示例的做法,用一个 determineModel 函数按环境变量自动回退:
const determineModel = () => {
if (process.env.GOOGLE_API_KEY?.trim()) {
return "google/gemini-3.8-flash"; // 优先使用 Gemini
}
if (process.env.OPENAI_API_KEY?.trim()) {
return "openai/gpt-5.2";
}
return "openai/gpt-5.2"; // 兜底默认值
};
BuiltInAgent 的构造参数(来自 route.ts)说明如下:
- model:字符串模型 ID 或由 AI SDK Provider 工厂返回的模型实例,支持 OpenAI / Anthropic / Google / OpenRouter 等;
- prompt:系统提示词。对法律文档审查场景,可以在 prompt 中注入审查规则,例如"你是资深法律合规顾问,逐条识别潜在风险条款,输出修订建议";
- temperature:采样温度,法律审查类任务建议偏低(如 0.2~0.5),以控制输出稳定性与严谨性。
此外,CopilotRuntime 还支持注册 后端 Action:v1 风格的示例(route.ts)展示了在 CopilotRuntime 构造时通过 actions 数组声明工具的方式——每个 Action 包含 name、description、parameters(声明式参数描述)与 handler 异步函数。在 Legal Document Reviewer 中,你可以在后端注册诸如"调用合规法规检索 API""解析 PDF/文本文件"之类的 Action,将纯前端无法完成的外部能力挂载给 Agent。
四、前端接入:Provider、Chat 组件与文档输入
前端层面,页面需要包裹 CopilotKitProvider 并提供 runtimeUrl,指向上一节创建的 API 路由。官方 v2 示例(single/page.tsx)展示了完整写法:
"use client";
import {
CopilotChat,
CopilotKitProvider,
useFrontendTool,
defineToolCallRenderer,
} from "@copilotkit/react-core/v2";
export default function LegalReviewerPage() {
return (
<CopilotKitProvider runtimeUrl="/api/copilotkit">
<div style={{ height: "100vh", overflow: "hidden" }}>
<LegalReviewerChat />
</div>
</CopilotKitProvider>
);
}
要点:
- 使用
CopilotKitProvider必须将包含 Chat 的组件树包在其中,页面文件需声明"use client"; runtimeUrl指向后端端点(如/api/copilotkit),也可使用useSingleEndpoint开启单端点模式(见 route.ts 与 single/page.tsx 的配套用法);CopilotChat是可深度定制的预置聊天组件,用户在其中粘贴法律文档、向 Agent 提问,Agent 的审查结果以工具调用 + Generative UI 的形式回流到同一界面。
对于文档输入,实战上通常有两条路径:
- 直接粘贴文本:用户在
CopilotChat输入框中粘贴合同/协议正文,由 Agent 在对话上下文中分析; - 独立输入区:页面顶部提供一个受控的
<textarea>(可搭配 Shadcn-UI 的 Textarea 组件),用户粘贴文档后通过前端工具把文本注入 Agent 上下文。
五、注册审查工具:useCopilotAction 与 useFrontendTool
法律审查系统的灵魂在于把"分析""高亮""修订"注册为 Agent 可调用的前端工具。仓库中 useCopilotAction 的源码注释(use-copilot-action.ts)完整说明了其使用模型:
- 通过
name声明工具名; - 通过
parameters声明参数(支持string、number、boolean、object、数组以及enum枚举,可标记required); - 通过
handler接收参数并返回结果; - 通过
render渲染自定义 UI; - 通过
renderAndWaitForResponse实现需要用户确认的交互。
以下是为 Legal Document Reviewer 设计的三个前端工具(v1 风格,语义清晰;v2 中对应 useFrontendTool,参数改用 Zod schema 描述,见 use-frontend-tool.tsx):
// 1. 分析文档:让 Agent 提取条款结构并标注风险等级
useCopilotAction({
name: "analyzeDocument",
description: "Analyze the pasted legal document, identify clauses, obligations and compliance risks",
parameters: [
{ name: "documentText", type: "string", description: "Full text of the legal document", required: true },
{ name: "riskLevel", type: "string", enum: ["low", "medium", "high"], required: false },
],
handler: async ({ documentText }) => {
// 这里可以做本地预处理,例如保存原文、统计段落数
return { analyzed: true, length: documentText.length };
},
});
// 2. 高亮重要章节:渲染带定位的条款卡片
useCopilotAction({
name: "highlightSections",
description: "Highlight important sections and risky clauses in the document",
parameters: [
{ name: "clauses", type: "object[]", attributes: [
{ name: "title", type: "string" },
{ name: "text", type: "string" },
{ name: "risk", type: "string", enum: ["low", "medium", "high"] },
]},
],
render: ({ status, args }) => (
<ClauseHighlightPanel clauses={args.clauses} status={status} />
),
});
// 3. 生成修订建议:以卡片形式给出原文与改写对照
useCopilotAction({
name: "suggestRevision",
description: "Suggest a revised version of a clause to improve compliance and clarity",
parameters: [
{ name: "clauseId", type: "string", required: true },
{ name: "originalText", type: "string", required: true },
{ name: "suggestedText", type: "string", required: true },
{ name: "reason", type: "string", description: "Why this revision improves compliance or clarity", required: true },
],
render: ({ status, args }) => (
<RevisionCard
original={args.originalText}
suggested={args.suggestedText}
reason={args.reason}
status={status}
/>
),
});
从源码实现看,useCopilotAction 会根据配置自动分派到三条底层路径(use-copilot-action.ts):
- 提供
handler且无render时,走 frontend 路径(底层为useFrontendTool); - 仅提供
render时,走 render 路径(工具调用结果只渲染 UI); - 提供
renderAndWaitForResponse时,走 hitl(Human-in-the-Loop) 路径,Agent 会暂停等待用户通过respond给出确认或修改。
六、高亮与修订:Generative UI 的落地形态
"高亮重要章节"与"建议修订"是本示例最具代表性的 Generative UI 场景。所谓 Generative UI,是指 Agent 在运行时根据工具参数动态生成并渲染 React 组件(参见 README.md 对 Generative UI 的定义:"agents to dynamically render UI as part of their workflow")。
在 Legal Document Reviewer 中,render 函数返回的自定义组件可以直接使用 Shadcn-UI + Tailwind CSS 构建。例如 ClauseHighlightPanel 可以用 Card、Badge 等 Shadcn 组件实现风险分级高亮:
// components/ClauseHighlightPanel.tsx
import { Card, CardContent } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
const riskColor = { low: "bg-green-100", medium: "bg-yellow-100", high: "bg-red-100" };
export function ClauseHighlightPanel({ clauses, status }: {
clauses: { title: string; text: string; risk: "low" | "medium" | "high" }[];
status: string;
}) {
return (
<div className="space-y-2">
{clauses.map((clause, i) => (
<Card key={i} className={riskColor[clause.risk]}>
<CardContent>
<div className="flex items-center justify-between">
<h4 className="font-semibold">{clause.title}</h4>
<Badge variant="secondary">{clause.risk}</Badge>
</div>
<p className="text-sm mt-1">{clause.text}</p>
{status === "executing" && <p className="text-xs text-muted">analyzing...</p>}
</CardContent>
</Card>
))}
</div>
);
}
同理,RevisionCard 用左右对照布局呈现"原文 → 建议改写 → 修改理由",让用户一眼看清 Agent 的合规性/清晰度判断依据。
值得一提的是,工具调用状态 status(如 executing、completed、error)会随着执行过程实时更新传入 render,这允许你在 Agent 分析过程中展示加载态,在完成后展示最终结果——官方示例 single/page.tsx 中的 wildcard renderer 就展示了 status 与 args 的用法。
七、人工确认闭环:合规修订的 Human-in-the-Loop
法律文本修改属于高风险操作,直接由 Agent 静默改写并不稳妥。CopilotKit 的 Human-in-the-Loop 机制正好解决这个问题:Agent 提出修订后暂停执行,等待用户点击"接受/拒绝"再继续。仓库源码将其实现为 hitl 路径(use-copilot-action.ts),并提供了完整的交互示例(react-textarea README 中的邮件确认场景)。
把该模式迁移到法律审查场景:
useCopilotAction({
name: "approveRevision",
description: "Ask the user to approve or reject a suggested clause revision",
parameters: [
{ name: "clauseId", type: "string", required: true },
{ name: "suggestedText", type: "string", required: true },
],
renderAndWaitForResponse: ({ args, status, respond }) => {
return (
<RevisionApprovalDialog
clauseId={args.clauseId}
suggestedText={args.suggestedText}
isExecuting={status === "executing"}
onApprove={() => respond?.({ approved: true })}
onReject={() => respond?.({ approved: false })}
/>
);
},
});
关键点:
renderAndWaitForResponse渲染的组件必须通过respond把用户决策回传给 Agent,Agent 收到后才继续后续流程;- 这样既保留了 AI 的审查能力,又把"最终是否改写文档"的决定权交给用户,符合法律文档场景对严谨性的要求;
- v2 中该能力由
useHumanInTheLoop提供,useCopilotAction在检测到renderAndWaitForResponse时自动切换到该底层实现。
八、从零搭建:完整项目实践路径
参考原文档的技术栈与仓库中的官方示例,完整的搭建步骤如下:
- 初始化 Next.js + TypeScript 项目,并安装 Tailwind CSS 与 Shadcn-UI(执行
npx shadcn@latest init并添加card、badge、textarea、dialog等组件); - 安装 CopilotKit 依赖:
@copilotkit/react-core(前端)与@copilotkit/runtime(后端); - 搭建后端路由:按第三节创建
/api/copilotkit/[[...slug]]/route.ts,用BuiltInAgent配置 Gemini 模型,设置面向法律审查的系统提示词; - 搭建前端页面:按第四节在页面中包裹
CopilotKitProvider并渲染CopilotChat,提供法律文档粘贴输入; - 注册前端工具:按第五节注册
analyzeDocument、highlightSections、suggestRevision三个工具,并用 Shadcn-UI 组件实现render; - 加入人工确认:按第七节为修订落地增加
renderAndWaitForResponse审批对话框; - 本地运行验证:配置
GOOGLE_API_KEY环境变量,运行npm run dev,在聊天中粘贴一份合同文本,观察 Agent 是否依次执行分析 → 高亮 → 修订建议 → 等待审批。
若需要无后端 Agent 快速联调,可参考官方单端点模式(route.ts),它用 InMemoryAgentRunner 在本地直接运行内置 Agent,无需外部推理服务。
九、源码参考索引
本文涉及的关键实现均可在本仓库中继续深挖:
- useCopilotAction 定义与分派逻辑:工具注册、render / HITL / frontend 三条路径的判定源码;
- v2 useFrontendTool 实现:v2 时代前端工具注册与渲染器注册的底层逻辑;
- v2 Runtime 后端路由示例:
BuiltInAgent+CopilotRuntime的完整配置(含模型选择与 providerOptions); - v2 单端点示例:
CopilotKitProvider、useFrontendTool、defineToolCallRenderer的前端组合写法; - v1 后端 Actions 示例:声明式
parameters+handler的后端工具注册范式; - HITL 交互示例:
renderAndWaitForResponse+respond的确认闭环范式; - React 生态概览:CopilotKit 能力总览与 AG-UI 协议说明。
十、总结
Legal Document Reviewer 示例的价值在于展示了一条清晰可复制的路径:用 CopilotKit 的聊天 + 工具注册 + Generative UI + Human-in-the-Loop 四件套,把"文档分析 → 高亮 → 修订建议 → 人工审批"串成一个完整的 Agent 工作流。本文从后端 CopilotRuntime 配置、前端 CopilotKitProvider 接入,到 useCopilotAction / useFrontendTool 的工具注册、Shadcn-UI 渲染的审查卡片,再到 renderAndWaitForResponse 的人工确认闭环,逐一给出了可运行的实现方案,并标注了仓库中的对应源码位置。以此为基础,你不仅能复刻法律文档审查器,还能将同一套模式迁移到合同审核、政策解读、审计复核等任何"文本 + 合规"类 Agent 应用中。