使用 Nestjs、RAG、Prisma 和 Gemini API 构建上下文感知的待办事项列表
2025-01-27 19:10:06
0浏览
收藏
最近发现不少小伙伴都对文章很感兴趣,所以今天继续给大家介绍文章相关的知识,本文《使用 Nestjs、RAG、Prisma 和 Gemini API 构建上下文感知的待办事项列表》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

本教程演示如何利用检索增强生成 (RAG) 技术构建一个具备上下文感知能力的待办事项列表应用。我们将结合Google Gemini API进行文本嵌入,借助pgvector高效管理向量数据,并使用Prisma和NestJS框架操作PostgreSQL数据库。此方案将实现诸如去重任务和基于上下文检索相似任务等高级功能。
前提条件
- 熟悉NestJS和Prisma框架。
- 已安装Node.js和npm。
- PostgreSQL数据库已安装并启用pgvector扩展。
- 拥有可访问Google Cloud的Gemini API密钥。
步骤一:搭建NestJS项目
- 创建新的NestJS项目:
nest new todo-app cd todo-app
- 删除默认生成的无用文件:
rm src/app.controller.* src/app.service.* src/app.module.ts
步骤二:安装依赖
安装所需依赖包:
npm install prisma @prisma/client @google/generative-ai dotenv pg
步骤三:使用pgvector配置Prisma
- 初始化Prisma:
npx prisma init
- 使用你的PostgreSQL数据库连接信息更新
.env文件:
DATABASE_URL="postgresql://<用户名>:<密码>@localhost:5432/<数据库名>?schema=public"
GEMINI_API_KEY="<你的Gemini API密钥>"
- 在
schema.prisma文件中启用pgvector:
generator client {
provider = "prisma-client-js"
previewFeatures = ["postgresqlextensions"]
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
extensions = ["pgvector"]
}
model Task {
id Int @id @default(autoincrement())
title String
content String
embedding Unsupported("vector(1536)")
}
- 执行数据库迁移:
npx prisma migrate dev --name init
步骤四:在NestJS中配置Prisma
创建Prisma模块用于数据库访问:
// src/prisma/prisma.module.ts
import { Module } from '@nestjs/common';
import { PrismaService } from './prisma.service';
@Module({
providers: [PrismaService],
exports: [PrismaService],
})
export class PrismaModule {}
// src/prisma/prisma.service.ts
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';
@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy {
async onModuleInit() {
await this.$connect();
}
async onModuleDestroy() {
await this.$disconnect();
}
}
在主模块中导入Prisma模块:
// src/app.module.ts
import { Module } from '@nestjs/common';
import { PrismaModule } from './prisma/prisma.module';
import { TasksModule } from './tasks/tasks.module';
@Module({
imports: [PrismaModule, TasksModule],
})
export class AppModule {}
步骤五:创建任务模块
- 生成任务模块:
nest generate module tasks nest generate service tasks nest generate controller tasks
- 实现
TasksService:
// src/tasks/tasks.service.ts
import { Injectable } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { Task } from '@prisma/client';
import { GeminiService } from '../gemini/gemini.service';
@Injectable()
export class TasksService {
constructor(private prisma: PrismaService, private geminiService: GeminiService) {}
async createTask(title: string, content: string): Promise {
const embedding = await this.geminiService.getEmbedding(`${title} ${content}`);
return this.prisma.task.create({
data: { title, content, embedding },
});
}
async getTasks(): Promise {
return this.prisma.task.findMany();
}
async findSimilarTasks(embedding: number[], limit = 5): Promise {
const embeddingStr = `[${embedding.join(',')}]`;
return this.prisma.$queryRaw`
SELECT *, embedding <-> ${embeddingStr}::vector AS distance
FROM "Task"
ORDER BY distance
LIMIT ${limit};
`;
}
}
- 实现
TasksController:
// src/tasks/tasks.controller.ts
import { Controller, Post, Get, Body } from '@nestjs/common';
import { TasksService } from './tasks.service';
@Controller('tasks')
export class TasksController {
constructor(private tasksService: TasksService) {}
@Post()
async createTask(@Body('title') title: string, @Body('content') content: string) {
return this.tasksService.createTask(title, content);
}
@Get()
async getTasks() {
return this.tasksService.getTasks();
}
}
步骤六:集成Gemini API生成嵌入向量
- 创建
GeminiService:
// src/gemini/gemini.service.ts
import { Injectable } from '@nestjs/common';
import { GenerativeLanguageServiceClient } from '@google/generative-ai';
@Injectable()
export class GeminiService {
private client: GenerativeLanguageServiceClient;
constructor() {
this.client = new GenerativeLanguageServiceClient({
apiKey: process.env.GEMINI_API_KEY,
});
}
async getEmbedding(text: string): Promise {
const result = await this.client.embedText({
model: 'models/text-embedding-001',
content: text,
});
return result.embedding;
}
}
总结
通过以上步骤,你将拥有一个功能完善的待办事项列表应用,具备以下能力:
- 使用Gemini API为任务内容生成嵌入向量。
- 使用pgvector将嵌入向量存储在PostgreSQL数据库中。
- 基于嵌入向量检索相似任务。
此架构支持语义搜索和上下文数据清理等高级功能,可进一步扩展以构建更智能的任务管理系统。
以上就是《使用 Nestjs、RAG、Prisma 和 Gemini API 构建上下文感知的待办事项列表》的详细内容,更多关于的资料请关注golang学习网公众号!
清华大学研究组首次在双重编码量子比特之间实现高保真度量子纠缠门
- 上一篇
- 清华大学研究组首次在双重编码量子比特之间实现高保真度量子纠缠门
- 下一篇
- AI软件市场规模2029年将达到2180亿美元
查看更多
最新文章
-
- 文章 · python教程 | 1小时前 | 数据校验 · python · Pydantic 部分更新 exclude_unset model_fields_set 显式空值 model_dump
- Pydantic 模型更新时区分未提供字段与显式空值
- 399浏览 收藏
-
- 文章 · python教程 | 3小时前 |
- pytest Fixture 作用域如何影响测试隔离与速度
- 341浏览 收藏
-
- 文章 · python教程 | 5小时前 | Python教程 · pathlib · 路径安全 Python pathlib Path.resolve 目录穿越 relative_to
- Pathlib 安全拼接用户路径:解析后再验证根目录
- 463浏览 收藏
-
- 文章 · python教程 | 7小时前 | 性能优化 · Python教程 · Python 进程间通信 pickle multiprocessing SharedMemory
- multiprocessing 传输大对象为何变慢,如何减少序列化
- 478浏览 收藏
-
- 文章 · python教程 | 1天前 | python · Python import很慢 -X importtime 模块级副作用 延迟导入 Python启动优化
- Python import 很慢怎么分析:模块级副作用与延迟导入
- 292浏览 收藏
-
- 文章 · python教程 | 1天前 | python · 异步编程 · Python asyncio contextvars request_id
- contextvars 在异步请求链中传递追踪信息
- 393浏览 收藏
-
- 文章 · python教程 | 1天前 | 并发 · 异常处理 · python · asyncio · CancelledError 结构化并发 ExceptionGroup Python asyncio TaskGroup asyncio gather
- asyncio TaskGroup 让并发任务在首错时一起收敛
- 246浏览 收藏
-
- 文章 · python教程 | 1天前 |
- Python 3.14 自由线程程序怎样显式保护共享状态
- 337浏览 收藏
-
- 文章 · python教程 | 1天前 | 标准库 · Python教程 · Python Traversable importlib.resources 包内资源
- Python importlib.resources Traversable 怎么读取包内目录
- 359浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 378次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 450次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 458次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 402次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 229次使用
查看更多
相关文章
-
- Python sqlite3 Connection serialize 怎么导出数据库快照:备份窗口、内存占用与恢复校验
- 2026-08-26 501浏览
-
- Python监控网页状态:requests异常处理实战
- 2026-05-29 501浏览
-
- TensorFlow模型部署为API的TF Serving方法
- 2026-05-26 501浏览
-
- Python字符串编码转换:encode与decode详解
- 2026-05-16 501浏览
-
- TensorFlow裁剪无用算子方法详解
- 2026-05-15 501浏览

