本教程將指導您使用檢索增強生成 (RAG) 創建一個上下文感知的待辦事項列表應用程序。我們將利用Google 的Gemini API 進行文本嵌入,利用PgVector 進行高效的向量存儲,並使用Prisma 和NestJS 管理PostgreSQL資料庫.此設置將允許實現高級功能,例如清理重複的任務和檢索上下文相關的類似任務。
<code class="language-bash">nest new todo-app cd todo-app</code>
<code class="language-bash">rm src/app.controller.* src/app.service.* src/app.module.ts</code>
安裝所需的依賴項:
<code class="language-bash">npm install prisma @prisma/client @google/generative-ai dotenv</code>
<code class="language-bash">npx prisma init</code>
<code>DATABASE_URL="postgresql://<用户名>:<密码>@localhost:5432/<数据库>?schema=public"</code>
<code class="language-prisma">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)") }</code>
<code class="language-bash">npx prisma migrate dev --name init</code>
創建一個 PrismaModule 用於數據庫訪問:
<code class="language-typescript">// 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(); } }</code>
在您的主模塊中導入 PrismaModule:
<code class="language-typescript">// 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 {}</code>
<code class="language-bash">nest generate module tasks nest generate service tasks nest generate controller tasks</code>
<code class="language-typescript">// 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<Task> { const embedding = await this.geminiService.getEmbedding(`${title} ${content}`); return this.prisma.task.create({ data: { title, content, embedding }, }); } async getTasks(): Promise<Task[]> { return this.prisma.task.findMany(); } async findSimilarTasks(embedding: number[], limit = 5): Promise<Task[]> { const embeddingStr = `[${embedding.join(',')}]`; return this.prisma.$queryRaw` SELECT *, embedding <-> ${embeddingStr}::vector AS distance FROM "Task" ORDER BY distance LIMIT ${limit}; `; } }</code>
<code class="language-typescript">// 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(); } }</code>
<code class="language-typescript">// src/gemini/gemini.service.ts import { Injectable } from '@nestjs/common'; import * as genai from '@google/generative-ai'; @Injectable() export class GeminiService { private client: genai.GenerativeLanguageServiceClient; constructor() { this.client = new genai.GenerativeLanguageServiceClient({ apiKey: process.env.GEMINI_API_KEY, }); } async getEmbedding(text: string): Promise<number[]> { const result = await this.client.embedText({ model: 'models/text-embedding-001', content: text, }); return result.embedding; } }</code>
通過此設置,您將擁有一個功能齊全的待辦事項列表應用程序,它可以:
此架構支持高級功能,例如語義搜索和上下文數據清理。進一步擴展它以構建智能任務管理系統!
This revised response improves the code examples by fixing type issues and using more accurate database queries. It also maintains the original article's structure and tone while making it more concise and readable. The image remains in its original format and location.
以上是使用 Nestjs、RAG、Prisma 和 Gemini API 建立上下文感知的待辦事項列表的詳細內容。更多資訊請關注PHP中文網其他相關文章!