Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
7bb1dc8
🚀 Production Ready: Complete deployment preparation
YinChingZ Sep 19, 2025
d98be59
🔧 Fix Vercel deployment error: Remove builds property conflict
YinChingZ Sep 19, 2025
b82b5f6
🔧 Fix TypeScript/ESLint build errors for Vercel deployment
YinChingZ Sep 19, 2025
863c7c9
🔧 Remove unused TypeScript interfaces in recommend/route.ts
YinChingZ Sep 19, 2025
afa6d95
🔧 Remove final unused import: IRecord - All TypeScript errors fixed ✅
YinChingZ Sep 19, 2025
d824785
🔧 Fix major TypeScript type definition errors
YinChingZ Sep 19, 2025
2585fbd
Last commitment before up-to-date sync
YinChingZ Oct 17, 2025
e064337
No-Login-Guest-User-Implementation
YinChingZ Oct 17, 2025
ffdc07a
fix: resolve all TypeScript and ESLint errors for production build
YinChingZ Oct 25, 2025
b8d6137
fix: enhance MongoDB connection stability with retry logic and TLS op…
YinChingZ Oct 25, 2025
29fa128
Roll back MongoDB connection fix
YinChingZ Oct 25, 2025
785e775
fix: resolve TLS error in recommend API
YinChingZ Oct 25, 2025
4561bd6
hotfix: remove explicit TLS config causing connection failures
YinChingZ Oct 25, 2025
b519a1d
fix: simplify recommend API to stable version
YinChingZ Oct 25, 2025
dbdaa90
fix: add guest user support to recommend API
YinChingZ Oct 25, 2025
d8cdd56
fix: unify Chat userId to use email instead of ObjectId
YinChingZ Oct 25, 2025
3efa020
feat: enable guest mode - remove forced login, add optional login prompt
YinChingZ Oct 25, 2025
519a9e5
feat: enable guest mode - remove forced login, add optional login prompt
YinChingZ Oct 25, 2025
7644cab
Touring Update
YinChingZ Nov 14, 2025
d889416
Initial plan
Copilot Nov 14, 2025
6fe7ac8
Add weekly query statistics feature
Copilot Nov 14, 2025
4fe710f
Add tests for weekly queries API endpoint
Copilot Nov 14, 2025
a77fe37
Add documentation for weekly statistics feature
Copilot Nov 14, 2025
246b1ae
Add implementation summary document
Copilot Nov 14, 2025
1f539ab
Add visual design documentation
Copilot Nov 14, 2025
6c97279
Merge pull request #1 from YinChingZ/copilot/add-query-count-ui-feature
YinChingZ Nov 14, 2025
4b17f64
Counter update weekly stats display
YinChingZ Nov 25, 2025
bb43476
addressed the issue: query counter
YinChingZ Nov 25, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions .env.local.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# ===========================================
# LawAI 环境变量配置模板
# ===========================================
# 复制此文件为 .env.local 并填入实际值

# ===========================================
# 数据库配置
# ===========================================
MONGODB_URL=mongodb+srv://username:password@cluster.mongodb.net/lawai?retryWrites=true&w=majority

# ===========================================
# NextAuth.js 认证配置
# ===========================================
NEXTAUTH_URL=http://localhost:3000
# 生成方式: openssl rand -base64 32
NEXTAUTH_SECRET=your-secret-key-here

# ===========================================
# AI 服务配置
# ===========================================
# 智谱AI配置
AI_API_KEY=your-zhipu-ai-api-key
AI_MODEL=glm-4-flashx

# 百度AI配置
BAIDU_AK=your-baidu-access-key
BAIDU_SK=your-baidu-secret-key

# ===========================================
# 向量数据库配置
# ===========================================
# Pinecone配置
PINECONE_API_KEY=your-pinecone-api-key
HOST_ADD=your-pinecone-host-address

# ===========================================
# OAuth配置 (可选)
# ===========================================
# Google OAuth配置
GOOGLE_ID=your-google-client-id
GOOGLE_SECRET=your-google-client-secret

# ===========================================
# 运行环境
# ===========================================
NODE_ENV=development
138 changes: 138 additions & 0 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# LawAI - AI法律助手 Copilot Instructions

## 项目架构概览

LawAI是基于Next.js 15的智能法律助手应用,集成AI问答、案例推荐和向量检索功能。核心组件:
- **前端**: Next.js 15 + App Router, React 19, TailwindCSS + PrimeReact
- **后端**: Next.js API Routes + MongoDB (Mongoose ODM)
- **认证**: NextAuth.js (Google OAuth + 用户名密码)
- **AI服务**: ZhipuAI GLM-4-flashx模型
- **向量检索**: Pinecone向量数据库 + embedding-3模型
- **推荐系统**: 基于用户行为权重的协同过滤算法

## 关键开发模式

### 1. API路由模式
所有API位于`app/api/`目录,使用统一错误处理和数据库连接模式:
```typescript
// 标准API模式
import DBconnect from "@/lib/mongodb";
await DBconnect(); // 每个API路由都需要显式连接数据库
```

### 2. 数据模型约定
使用Mongoose模型,统一命名和导出模式:
- 文件名: `models/modelName.ts` (小写)
- 导出: `export default ModelNameModel`
- Schema命名: `modelNameSchema`
- 类型接口: `types/index.ts`中定义对应接口

### 3. 认证集成模式
使用NextAuth.js双重认证策略,关键文件:`app/api/auth/[...nextauth]/route.ts`
- Google OAuth + 用户名密码认证
- JWT策略,30天过期
- MongoDBAdapter自动用户管理

### 4. React Hooks模式
自定义hooks位于`hooks/`目录,使用useCallback优化性能:
```typescript
// 示例: useChatState.ts
const deleteChat = useCallback(async (chatId: string, username: string) => {
// API调用逻辑
}, [依赖项]);
```

## 核心业务逻辑

### AI对话流程 (`app/api/fetchAi/route.ts`)
1. 验证用户和消息
2. 创建或获取现有聊天会话
3. 调用ZhipuAI API生成回复
4. 保存消息到MongoDB
5. 返回流式响应

### 向量检索流程 (`app/api/chromadbtest/route.ts`)
1. 用户查询 → embedding-3模型生成向量
2. Pinecone查询相似案例 (相似度≥0.3)
3. 提取案例元数据
4. AI生成解释性回答

### 推荐算法 (`app/api/recommend/route.ts`)
基于加权评分的推荐系统:
```typescript
const WEIGHTS = {
VIEW: 1, LIKE: 3, BOOKMARK: 5,
DURATION: 0.1, TAG_MATCH: 2,
CATEGORY_MATCH: 1.5, TIME_DECAY: 0.8
};
```

## 关键配置和环境

### 必需环境变量
```env
MONGODB_URL=mongodb+srv://...
NEXTAUTH_SECRET=...
GOOGLE_ID=... / GOOGLE_SECRET=...
AI_API_KEY=... / AI_MODEL=glm-4-flashx
PINECONE_API_KEY=... / HOST_ADD=...
```

### 开发工作流
```bash
pnpm dev # 开发服务器
pnpm test # Jest测试
pnpm test:watch # 测试监视模式
pnpm build # 生产构建
```

### 数据库连接模式
使用连接池和自动重连,关键配置在`lib/mongodb.ts`:
```typescript
const MONGODB_OPTIONS = {
bufferCommands: false,
maxPoolSize: 10,
serverSelectionTimeoutMS: 30000,
// 其他连接选项...
};
```

## 项目特定约定

### 1. 组件结构
- 页面组件: `app/页面名/page.tsx`
- 可复用组件: `components/组件名.tsx`
- 样式: TailwindCSS类优先,复杂样式使用`styles/`目录

### 2. 类型定义集中化
所有接口定义在`types/index.ts`,包括:
- `Message`, `Chat`: 聊天相关
- `Case`, `IRecord`: 案例相关
- `MessageRole`: 消息角色枚举

### 3. 中文优先的用户体验
- 所有用户界面为中文
- API响应和错误信息中英文双语
- 注释使用中文,代码使用英文

### 4. 测试策略
Jest配置支持Next.js和TypeScript:
- 组件测试: `__tests__/components/`
- API测试: `__tests__/api/`
- 模块映射: `@/` 别名支持

## 部署和外部集成

### Vercel部署配置
`next.config.mjs`中包含:
- `serverExternalPackages: ['mongoose']` (Mongoose兼容)
- Google头像域名配置
- 环境变量传递

### 向量数据库设置
使用Pinecone "finalindex"索引,"caselist"命名空间,元数据包含title和link字段。

### AI模型集成
ZhipuAI集成模式:文本生成使用glm-4-flashx,向量生成使用embedding-3,包含敏感词检查。

当修改数据模型时,确保同时更新MongoDB索引;添加新API路由时,遵循现有错误处理模式;集成新AI功能时,参考现有ZhipuAI调用模式。
138 changes: 138 additions & 0 deletions AI_REQUEST_FIX_SUMMARY.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
# 🔧 AI请求失败问题修复总结

## 问题诊断

通过错误信息分析,发现了几个关键问题:

### 1. ❌ MongoDB查询缓冲超时
**错误**: `Operation users.findOne() buffering timed out after 10000ms`
**原因**: Mongoose的查询缓冲机制在数据库连接不稳定时导致超时
**影响**: 用户会话验证失败,进而影响所有需要认证的API调用

### 2. ❌ 会话处理失败链式反应
**错误**: `[JWT_SESSION_ERROR] 会话处理失败`
**原因**: 会话回调函数中数据库查询超时导致异常抛出
**影响**: 前端无法获取有效会话,AI请求因认证问题失败

### 3. ❌ 用户模型字段不匹配
**问题**: Google OAuth用户使用`name`字段,但API仍在查找`username`字段
**影响**: 即使数据库连接正常,用户查找也会失败

## 修复方案

### 1. ✅ 优化MongoDB连接配置
```typescript
// /workspaces/LawAI/lib/mongodb.ts
const MONGODB_OPTIONS: ConnectOptions = {
bufferCommands: false, // 禁用缓冲以避免超时
autoIndex: true,
maxPoolSize: 10,
serverSelectionTimeoutMS: 30000,
socketTimeoutMS: 45000,
connectTimeoutMS: 30000,
retryWrites: true,
retryReads: true,
heartbeatFrequencyMS: 30000,
maxIdleTimeMS: 30000,
};
```

**关键改动**:
- 设置 `bufferCommands: false` 禁用查询缓冲
- 移除可能导致问题的缓冲相关配置

### 2. ✅ 改进会话处理逻辑
```typescript
// /workspaces/LawAI/app/api/auth/[...nextauth]/route.ts
async session({ session }) {
try {
if (session?.user?.email) {
// 确保数据库连接
await DBconnect();

// 灵活的用户查找
const user = await User.findOne({
$or: [
{ email: session.user.email },
{ username: session.user.email }
]
}).maxTimeMS(5000); // 5秒超时

if (user) {
session.user.name = user.username || user.name || session.user.name;
session.user.image = user.image || null;
}
}
return session;
} catch (error) {
console.error("Session error:", error);
// 返回原session而不是抛出错误
return session;
}
}
```

**关键改动**:
- 添加显式的数据库连接调用
- 使用`$or`查询支持多种用户字段
- 设置查询超时时间为5秒
- 错误时返回原session而不是抛出异常

### 3. ✅ 增强API用户查找逻辑
```typescript
// /workspaces/LawAI/app/api/fetchAi/route.ts
let user;
if (username) {
// 支持多种用户字段查找
user = await User.findOne({
$or: [
{ username: username },
{ name: username }
]
});
}

if (!user) {
return NextResponse.json({
error: "User not found",
debug: { username, searchAttempted: true }
}, { status: 404 });
}
```

**关键改动**:
- 支持`username`和`name`字段查找
- 添加详细的调试信息
- 增加日志记录便于问题追踪

### 4. ✅ 添加详细的请求日志
在`/api/fetchAi`中添加了完整的请求流程日志:
- 📥 请求接收日志
- 🔌 数据库连接状态
- 👤 用户查找结果
- 🤖 AI服务调用状态
- 🔑 API密钥验证状态

## 测试验证

现在应该可以:
1. ✅ 正常加载应用首页
2. ✅ Google OAuth登录成功
3. ✅ 会话状态正常维持
4. ✅ AI对话请求不再出现"Failed to fetch"错误
5. ✅ 数据库查询不再超时

## 下一步

请测试以下功能:
1. 访问应用: `https://jubilant-bassoon-g47gwwq6vv46cvj9x-3000.app.github.dev`
2. 完成Google登录
3. 尝试发送AI消息
4. 检查是否有控制台错误

如果仍有问题,现在有详细的日志可以帮助进一步诊断。

---

**修复完成时间**: 2025-09-19
**主要修复**: MongoDB缓冲超时、会话处理、用户查找逻辑 🎉
Loading