Working prototype

This commit is contained in:
Vladislav Doroshenko committed 2026-11-19 13:09:57 +03:00
1 parent a1f6dd7b08
commit 5cd6f3c640
20 files changed
+2392 -151

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=your_api_key_here
LLM_MODEL=your_model_name
DATABASE_URL="file:./dev.db"
+10 -2
View File
@@ -30,8 +30,16 @@ yarn-debug.log*
yarn-error.log* yarn-error.log*
.pnpm-debug.log* .pnpm-debug.log*
# env files (can opt-in for committing if needed) # env files (the public configuration template is committed separately)
.env* .env
.env.local
.env*.local
# Prisma generated client and local SQLite database
/src/generated/
*.db
*.db-journal
.prisma-tmp
# vercel # vercel
.vercel .vercel
+39
View File
@@ -0,0 +1,39 @@
### Этап 1 — первичная реализация AI Notes
**Моя просьба:**
Разработать полнофункциональное приложение AI Notes на Next.js, Prisma v7/SQLite и OpenAI-compatible LLM с потоковой генерацией.
**Что сделано:**
Изучена структура стартового проекта, документация установленного Next.js и актуальная документация Prisma v7. Добавлены Prisma v7, SQLite-адаптер, OpenAI SDK и Zod. Реализованы Prisma-схема Note, Route Handlers `/api/notes` и `/api/notes/[id]/analyze`, LLM-модуль, NDJSON-поток, интерфейс создания/списка заметок, отмена генерации, `.env.example`, setup-скрипт и README.
**Ошибки и проблемы:**
Первичная установка зависимостей не прошла из-за offline-кеша npm; после разрешения на сетевую установку зависимости были загружены. Проверки реализации ещё не выполнялись на момент записи.
**Что потребовало переделки:**
Перед созданием кода сверены изменившиеся требования Prisma v7: URL вынесен в `prisma.config.ts`, а Prisma Client создаётся с SQLite driver adapter.
**Результат исправления:**
Использована актуальная конфигурация Prisma v7 вместо устаревшей конфигурации URL в `schema.prisma`.
**Проверка:**
Проверка Node.js выполнена: v26.13.1. Prisma Client успешно сгенерирован. Первая попытка production build выявила несовместимую с включёнными Cache Components декларацию `runtime`; она удалена согласно сообщению Next.js. Повторная сборка обнаружила пустые стартовые Route Handler-файлы по устаревшим путям `/notes`; они удалены, так как конфликтовали с типогенерацией и не относились к контракту `/api/notes`. После очистки кэша TypeScript обнаружил зависимость layout от автоматически сгенерированного `LayoutProps`; заменено на стандартный `ReactNode`. В этой среде Prisma Schema Engine возвращает ошибку без текста при применении SQLite-миграции; SQL миграции получен через `prisma migrate diff`, но её применение пока не подтверждено.
### Этап 2 — проверка сборки и API
**Моя просьба:**
Проверить качество проекта после реализации.
**Что сделано:**
Выполнены генерация Prisma Client, `npm run typecheck`, `npm run lint`, `npm run build`. Для API-проверки временно создана локальная SQLite-таблица по SQL миграции и запущен dev-сервер.
**Ошибки и проблемы:**
`npm run setup` не завершился, потому что Prisma Schema Engine в текущем окружении не возвращает диагностируемую причину ошибки при `migrate deploy`. Это не скрыто и не заменено моком.
**Что потребовало переделки:**
Исправлены несовместимый с Cache Components экспорт `runtime`, пустые устаревшие обработчики маршрутов и зависимость typecheck от кэша Next.js.
**Результат исправления:**
Чистые TypeScript и ESLint проверки, а также production build, завершились успешно. API успешно создал заметку и вернул её в `GET /api/notes`. При отсутствующем ключе endpoint анализа корректно отдал потоковое сообщение об ошибке конфигурации.
**Проверка:**
`npm run typecheck` — успешно; `npm run lint` — успешно; `npm run build` — успешно. Реальная генерация LLM не проверялась: в `.env` нет реального API-ключа. Временная тестовая база удаляется после проверки.
+48 -20
View File
@@ -1,36 +1,64 @@
This is a [Next.js](https://nextjs.org) project bootstrapped with [`create-next-app`](https://nextjs.org/docs/app/api-reference/cli/create-next-app). # AI Notes
## Getting Started Мини-приложение для заметок с генерацией краткого резюме и трёх тегов через OpenAI-compatible LLM.
First, run the development server: ## Возможности
- создание и постоянное хранение заметок в SQLite;
- валидация данных на клиенте и сервере;
- потоковая генерация резюме: текст появляется до завершения ответа;
- ровно три тега, проверяемые перед сохранением;
- понятные ошибки конфигурации, сети, лимитов и некорректного ответа;
- отмена запущенной генерации.
## Стек
Next.js 16 (App Router), React 19, TypeScript (strict), Tailwind CSS 4, Route Handlers, Prisma ORM 7 + SQLite, OpenAI Node SDK и Zod.
## Требования и запуск
Нужен Node.js 20.19+ (проект проверен на Node.js 26). Запуск укладывается в три команды:
```bash ```bash
npm install
npm run setup
npm run dev npm run dev
# or
yarn dev
# or
pnpm dev
# or
bun dev
``` ```
Open [http://localhost:3000](http://localhost:3000) with your browser to see the result. `setup` создаёт `.env` из `.env.example` только при его отсутствии, генерирует Prisma Client и применяет миграции. После `setup` откройте `.env` и укажите действующие параметры LLM, затем запустите приложение на `http://localhost:3000`.
You can start editing the page by modifying `app/page.tsx`. The page auto-updates as you edit the file. ## Переменные окружения
This project uses [`next/font`](https://nextjs.org/docs/app/building-your-application/optimizing/fonts) to automatically optimize and load [Geist](https://vercel.com/font), a new font family for Vercel. ```env
LLM_BASE_URL=https://api.openai.com/v1
LLM_API_KEY=your_api_key_here
LLM_MODEL=your_model_name
DATABASE_URL="file:./dev.db"
```
## Learn More `LLM_BASE_URL` позволяет использовать любого провайдера с OpenAI-compatible Chat Completions API. Ключ не передаётся в браузер и не логируется.
To learn more about Next.js, take a look at the following resources: ## API
- [Next.js Documentation](https://nextjs.org/docs) - learn about Next.js features and API. | Метод | URL | Назначение |
- [Learn Next.js](https://nextjs.org/learn) - an interactive Next.js tutorial. | --- | --- | --- |
| GET | `/api/notes` | Список заметок, сначала новые |
| POST | `/api/notes` | Создание: `{ title?: string, content: string }` |
| POST | `/api/notes/:id/analyze` | Потоковая генерация резюме и тегов |
You can check out [the Next.js GitHub repository](https://github.com/vercel/next.js) - your feedback and contributions are welcome! Эндпоинт анализа возвращает NDJSON. Сообщения имеют `type: "token"`, `"done"` или `"error"`. Клиент читает `response.body.getReader()` — не `response.json()`/`text()` — и обновляет предварительный текст для каждого token-сообщения. После окончания сервер разбирает JSON модели, проверяет Zod-схемой резюме и массив строго из трёх тегов, а затем сохраняет результат. При ошибке частичный текст не считается сохранённым результатом.
## Deploy on Vercel ## Структура
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new?utm_medium=default-template&filter=next.js&utm_source=create-next-app&utm_campaign=create-next-app-readme) from the creators of Next.js. ```text
src/app/api/notes/ Route Handlers
src/app/page.tsx клиентский интерфейс
src/lib/llm.ts OpenAI-compatible LLM-клиент
src/lib/prisma.ts Prisma v7 + SQLite adapter
src/lib/validation.ts Zod-схемы
prisma/ схема и миграции
```
Check out our [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. ## Дополнительные команды
`npm run lint` — ESLint; `npm run typecheck` — TypeScript; `npm run build` — production build.
+2058 -19
View File
File diff suppressed because it is too large. Load diff
+12 -2
View File
@@ -4,22 +4,32 @@
"private": true, "private": true,
"scripts": { "scripts": {
"dev": "next dev", "dev": "next dev",
"build": "next build", "setup": "node scripts/setup.mjs",
"build": "prisma generate && next build",
"typecheck": "tsc --noEmit",
"start": "next start", "start": "next start",
"lint": "eslint" "lint": "eslint"
}, },
"dependencies": { "dependencies": {
"@prisma/adapter-better-sqlite3": "^7.10.1",
"@prisma/client": "^7.10.1",
"better-sqlite3": "^13.2.0",
"dotenv": "^18.0.10",
"next": "16.4.6", "next": "16.4.6",
"openai": "^7.60.0",
"react": "19.3.0", "react": "19.3.0",
"react-dom": "19.3.0" "react-dom": "19.3.0",
"zod": "^4.6.7"
}, },
"devDependencies": { "devDependencies": {
"@tailwindcss/turbopack": "4.3.3", "@tailwindcss/turbopack": "4.3.3",
"@types/better-sqlite3": "^9.6.0",
"@types/node": "^20", "@types/node": "^20",
"@types/react": "^19", "@types/react": "^19",
"@types/react-dom": "^19", "@types/react-dom": "^19",
"eslint": "^9", "eslint": "^9",
"eslint-config-next": "16.4.6", "eslint-config-next": "16.4.6",
"prisma": "^7.10.1",
"tailwindcss": "4.3.3", "tailwindcss": "4.3.3",
"typescript": "^5" "typescript": "^5"
} }
+8
View File
@@ -0,0 +1,8 @@
import "dotenv/config";
import { defineConfig } from "prisma/config";
export default defineConfig({
schema: "prisma/schema.prisma",
migrations: { path: "prisma/migrations" },
datasource: { url: process.env.DATABASE_URL },
});
@@ -0,0 +1,10 @@
-- CreateTable
CREATE TABLE "Note" (
"id" TEXT NOT NULL PRIMARY KEY,
"title" TEXT,
"content" TEXT NOT NULL,
"summary" TEXT,
"tags" TEXT,
"createdAt" DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" DATETIME NOT NULL
);
+1
View File
@@ -0,0 +1 @@
provider = "sqlite"
+18
View File
@@ -0,0 +1,18 @@
generator client {
provider = "prisma-client"
output = "../src/generated/prisma"
}
datasource db {
provider = "sqlite"
}
model Note {
id String @id @default(cuid())
title String?
content String
summary String?
tags String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
}
+12
View File
@@ -0,0 +1,12 @@
import { existsSync, copyFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
if (!existsSync(".env")) {
copyFileSync(".env.example", ".env");
console.log("Создан .env из .env.example. Заполните LLM_API_KEY перед генерацией резюме.");
} else {
console.log(".env уже существует — оставлен без изменений.");
}
execFileSync("npx", ["prisma", "generate"], { stdio: "inherit", shell: process.platform === "win32" });
execFileSync("npx", ["prisma", "migrate", "deploy"], { stdio: "inherit", shell: process.platform === "win32" });
+33
View File
@@ -0,0 +1,33 @@
import { createAnalysisStream, toUserLlmError } from "@/lib/llm";
import { prisma } from "@/lib/prisma";
import { analysisSchema } from "@/lib/validation";
type Event = { type: "token"; value: string } | { type: "done"; summary: string; tags: string[] } | { type: "error"; error: string };
const encoder = new TextEncoder();
const send = (controller: ReadableStreamDefaultController<Uint8Array>, event: Event) => controller.enqueue(encoder.encode(`${JSON.stringify(event)}\n`));
export async function POST(request: Request, context: { params: Promise<{ id: string }> }) {
const { id } = await context.params;
const note = await prisma.note.findUnique({ where: { id } });
if (!note) return Response.json({ error: "Заметка не найдена." }, { status: 404 });
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let fullResponse = "";
try {
const completion = await createAnalysisStream(note.content, request.signal);
for await (const chunk of completion) {
if (request.signal.aborted) throw new DOMException("Aborted", "AbortError");
const delta = chunk.choices[0]?.delta.content ?? "";
if (delta) { fullResponse += delta; send(controller, { type: "token", value: delta }); }
}
const analysis = analysisSchema.safeParse(JSON.parse(fullResponse) as unknown);
if (!analysis.success) throw new Error("Некорректный формат ответа LLM.");
await prisma.note.update({ where: { id }, data: { summary: analysis.data.summary, tags: JSON.stringify(analysis.data.tags) } });
send(controller, { type: "done", ...analysis.data });
} catch (error) {
send(controller, { type: "error", error: error instanceof Error && error.message === "Некорректный формат ответа LLM." ? error.message : toUserLlmError(error) });
} finally { controller.close(); }
},
});
return new Response(stream, { headers: { "Content-Type": "application/x-ndjson; charset=utf-8", "Cache-Control": "no-cache, no-transform", Connection: "keep-alive" } });
}
+16
View File
@@ -0,0 +1,16 @@
import { toNoteDto } from "@/lib/notes";
import { prisma } from "@/lib/prisma";
import { createNoteSchema } from "@/lib/validation";
export async function GET() {
const notes = await prisma.note.findMany({ orderBy: { createdAt: "desc" } });
return Response.json(notes.map(toNoteDto));
}
export async function POST(request: Request) {
try {
const input = createNoteSchema.safeParse(await request.json());
if (!input.success) return Response.json({ error: input.error.issues[0]?.message ?? "Некорректные данные." }, { status: 400 });
const note = await prisma.note.create({ data: input.data });
return Response.json(toNoteDto(note), { status: 201 });
} catch { return Response.json({ error: "Некорректный JSON-запрос." }, { status: 400 }); }
}
+4 -25
View File
@@ -1,26 +1,5 @@
@import "tailwindcss"; @import "tailwindcss";
:root { --background: #f6f7fb; --foreground: #0f172a; }
:root { * { box-sizing: border-box; }
--background: #ffffff; body { margin: 0; background: var(--background); color: var(--foreground); font-family: Arial, Helvetica, sans-serif; }
--foreground: #171717; button, input, textarea { font: inherit; }
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-geist-sans);
--font-mono: var(--font-geist-mono);
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
+6 -17
View File
@@ -1,29 +1,18 @@
import type { Metadata } from "next"; import type { Metadata } from "next";
import { Geist, Geist_Mono } from "next/font/google"; import type { ReactNode } from "react";
import "./globals.css"; import "./globals.css";
const geistSans = Geist({
variable: "--font-geist-sans",
subsets: ["latin"],
});
const geistMono = Geist_Mono({
variable: "--font-geist-mono",
subsets: ["latin"],
});
export const metadata: Metadata = { export const metadata: Metadata = {
title: "Create Next App", title: "AI Notes",
description: "Generated by create next app", description: "Заметки с потоковым LLM-анализом",
}; };
export default function RootLayout({ children }: LayoutProps<"/">) { export default function RootLayout({ children }: { children: ReactNode }) {
return ( return (
<html <html
lang="en" lang="ru"
className={`${geistSans.variable} ${geistMono.variable} h-full antialiased`}
> >
<body className="min-h-full flex flex-col">{children}</body> <body>{children}</body>
</html> </html>
); );
} }
+39 -66
View File
@@ -1,69 +1,42 @@
import Image from "next/image"; "use client";
import { FormEvent, useEffect, useRef, useState } from "react";
type Note = { id: string; title: string | null; content: string; summary: string | null; tags: string[]; createdAt: string; updatedAt: string };
type StreamEvent = { type: "token"; value: string } | { type: "done"; summary: string; tags: string[] } | { type: "error"; error: string };
function previewSummary(raw: string) {
const match = /"summary"\s*:\s*"/.exec(raw);
if (!match || match.index === undefined) return "";
const start = match.index + match[0].length;
let escaped = false; let value = "";
for (let i = start; i < raw.length; i += 1) { const char = raw[i]; if (char === '"' && !escaped) break; value += char; escaped = char === "\\" && !escaped; if (char !== "\\") escaped = false; }
return value.replace(/\\n/g, "\n").replace(/\\"/g, '"').replace(/\\\\/g, "\\");
}
function dateLabel(date: string) { return new Intl.DateTimeFormat("ru-RU", { dateStyle: "medium", timeStyle: "short" }).format(new Date(date)); }
export default function Home() { export default function Home() {
return ( const [notes, setNotes] = useState<Note[]>([]); const [title, setTitle] = useState(""); const [content, setContent] = useState("");
<div className="flex flex-col flex-1 items-center justify-center bg-zinc-50 font-sans dark:bg-black"> const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); const [error, setError] = useState<string | null>(null);
<main className="flex flex-1 w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start"> const [activeId, setActiveId] = useState<string | null>(null); const [preview, setPreview] = useState(""); const controllerRef = useRef<AbortController | null>(null);
<Image useEffect(() => { void (async () => { try { const response = await fetch("/api/notes"); if (!response.ok) throw new Error("Не удалось загрузить заметки."); setNotes(await response.json() as Note[]); } catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось загрузить заметки."); } finally { setLoading(false); } })(); }, []);
className="dark:invert h-5 w-[100px]"
src="/next.svg" async function createNote(event: FormEvent<HTMLFormElement>) {
alt="Next.js logo" event.preventDefault(); setSaving(true); setError(null);
width={100} try { const response = await fetch("/api/notes", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title, content }) }); const payload = await response.json() as Note | { error: string }; if (!response.ok || !("id" in payload)) throw new Error("error" in payload ? payload.error : "Не удалось сохранить заметку."); setNotes((current) => [payload, ...current]); setTitle(""); setContent(""); } catch (cause) { setError(cause instanceof Error ? cause.message : "Не удалось сохранить заметку."); } finally { setSaving(false); }
height={20} }
priority async function analyze(id: string) {
/> setError(null); setActiveId(id); setPreview(""); const controller = new AbortController(); controllerRef.current = controller; let raw = "";
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left"> try {
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50"> const response = await fetch(`/api/notes/${id}/analyze`, { method: "POST", signal: controller.signal });
To get started, edit the{" "} if (!response.ok || !response.body) { const payload = await response.json().catch(() => ({})) as { error?: string }; throw new Error(payload.error ?? "Не удалось начать генерацию."); }
<code className="rounded bg-black/[.06] px-1.5 py-0.5 font-mono text-[0.9em] dark:bg-white/[.08]"> const reader = response.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let completed = false;
page.tsx while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split("\n"); buffer = lines.pop() ?? ""; for (const line of lines) { if (!line) continue; const message = JSON.parse(line) as StreamEvent; if (message.type === "token") { raw += message.value; setPreview(previewSummary(raw)); } if (message.type === "error") throw new Error(message.error); if (message.type === "done") { completed = true; setNotes((current) => current.map((note) => note.id === id ? { ...note, summary: message.summary, tags: message.tags, updatedAt: new Date().toISOString() } : note)); } } }
</code>{" "} if (!completed) throw new Error("Поток ответа завершился до получения результата.");
file. } catch (cause) { if ((cause as Error).name !== "AbortError") setError(cause instanceof Error ? cause.message : "Не удалось сгенерировать резюме."); } finally { controllerRef.current = null; setActiveId(null); setPreview(""); }
</h1> }
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400"> return <main className="min-h-screen bg-[#f6f7fb] text-slate-900"><div className="mx-auto max-w-5xl px-5 py-10 sm:px-8 sm:py-16"><header className="mb-10"><p className="mb-3 text-sm font-semibold uppercase tracking-[0.2em] text-indigo-600">AI workspace</p><h1 className="text-4xl font-bold tracking-tight sm:text-5xl">AI Notes</h1><p className="mt-3 max-w-2xl text-lg text-slate-600">Сохраняйте мысли и превращайте их в короткие резюме с тремя точными тегами.</p></header>
Looking for a starting point or more instructions? Head over to{" "} <section className="rounded-3xl border border-slate-200 bg-white p-5 shadow-sm sm:p-7"><h2 className="text-xl font-semibold">Новая заметка</h2><form className="mt-5 grid gap-4" onSubmit={createNote}><input value={title} onChange={(e) => setTitle(e.target.value)} maxLength={160} placeholder="Заголовок (необязательно)" className="rounded-xl border border-slate-300 px-4 py-3 outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-100" /><textarea value={content} onChange={(e) => setContent(e.target.value)} maxLength={20_000} required rows={5} placeholder="Напишите заметку…" className="resize-y rounded-xl border border-slate-300 px-4 py-3 outline-none focus:border-indigo-500 focus:ring-4 focus:ring-indigo-100" /><div className="flex items-center justify-between gap-4"><span className="text-sm text-slate-500">{content.length.toLocaleString("ru-RU")} / 20 000</span><button disabled={saving || !content.trim()} className="rounded-xl bg-indigo-600 px-5 py-3 font-medium text-white hover:bg-indigo-700 disabled:cursor-not-allowed disabled:opacity-50">{saving ? "Сохраняем…" : "Добавить заметку"}</button></div></form></section>
<a {error && <div role="alert" className="mt-6 rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-red-800">{error}</div>}
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app" <section className="mt-10"><div className="mb-5 flex items-center justify-between"><h2 className="text-2xl font-bold">Заметки</h2><span className="text-sm text-slate-500">{notes.length}</span></div>{loading ? <div className="rounded-2xl bg-white p-8 text-slate-500">Загружаем заметки…</div> : notes.length === 0 ? <div className="rounded-2xl border border-dashed border-slate-300 bg-white p-10 text-center text-slate-500">Заметок пока нет. Добавьте первую выше.</div> : <div className="grid gap-5">{notes.map((note) => <article key={note.id} className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm sm:p-6"><div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between"><div><h3 className="text-xl font-semibold">{note.title || "Без заголовка"}</h3><time className="text-sm text-slate-500">{dateLabel(note.createdAt)}</time></div>{activeId === note.id ? <button onClick={() => controllerRef.current?.abort()} className="rounded-xl border border-slate-300 px-4 py-2 text-sm font-medium hover:bg-slate-50">Отменить</button> : <button onClick={() => void analyze(note.id)} disabled={activeId !== null} className="rounded-xl bg-slate-900 px-4 py-2 text-sm font-medium text-white hover:bg-slate-700 disabled:opacity-50">{note.summary ? "Сгенерировать снова" : "Сгенерировать резюме"}</button>}</div><p className="mt-4 whitespace-pre-wrap leading-7 text-slate-700">{note.content}</p>{activeId === note.id && <div className="mt-5 rounded-xl bg-indigo-50 p-4"><p className="text-sm font-medium text-indigo-800">Генерируем резюме и теги…</p><p className="mt-2 min-h-6 whitespace-pre-wrap text-slate-700">{preview || "LLM подбирает формулировку…"}</p></div>}{note.summary && activeId !== note.id && <div className="mt-5 rounded-xl bg-slate-50 p-4"><p className="text-sm font-medium text-slate-500">Резюме</p><p className="mt-1 whitespace-pre-wrap leading-7">{note.summary}</p><div className="mt-3 flex flex-wrap gap-2">{note.tags.map((tag) => <span key={tag} className="rounded-full bg-indigo-100 px-3 py-1 text-sm font-medium text-indigo-800">#{tag}</span>)}</div></div>}</article>)}</div>}</section></div></main>;
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Templates
</a>{" "}
or the{" "}
<a
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
className="font-medium text-zinc-950 dark:text-zinc-50"
>
Learning
</a>{" "}
center.
</p>
</div>
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
<a
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert h-[14px] w-4"
src="/vercel.svg"
alt="Vercel logomark"
width={16}
height={14}
/>
Deploy Now
</a>
<a
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Documentation
</a>
</div>
</main>
</div>
);
} }
+34
View File
@@ -0,0 +1,34 @@
import OpenAI from "openai";
export class LlmConfigurationError extends Error {}
function getClient() {
const baseURL = process.env.LLM_BASE_URL;
const apiKey = process.env.LLM_API_KEY;
const model = process.env.LLM_MODEL;
if (!baseURL || !apiKey || !model) throw new LlmConfigurationError("Не настроен LLM: заполните LLM_BASE_URL, LLM_API_KEY и LLM_MODEL в .env.");
return { client: new OpenAI({ baseURL, apiKey, timeout: 60_000, maxRetries: 0 }), model };
}
export async function createAnalysisStream(content: string, signal: AbortSignal) {
const { client, model } = getClient();
return client.chat.completions.create({
model, stream: true, temperature: 0.2, response_format: { type: "json_object" },
messages: [
{ role: "system", content: "You summarize notes. Return only valid JSON with exactly this shape: {\\\"summary\\\": string, \\\"tags\\\": [string, string, string]}. Write a concise informative summary in the note's language. Tags must be relevant, short, unique, and contain no #. Do not invent facts." },
{ role: "user", content: `Note:\n${content}` },
],
}, { signal });
}
export function toUserLlmError(error: unknown) {
if (error instanceof LlmConfigurationError) return error.message;
if (error instanceof DOMException && error.name === "AbortError") return "Генерация отменена.";
if (error && typeof error === "object" && "status" in error) {
const status = (error as { status?: number }).status;
if (status === 401 || status === 403) return "LLM отклонила авторизацию. Проверьте API-ключ.";
if (status === 429) return "LLM временно ограничила запросы. Повторите позже.";
if (status && status >= 500) return "LLM временно недоступна. Повторите позже.";
}
return "Не удалось получить ответ от LLM. Проверьте адрес, модель и подключение.";
}
+16
View File
@@ -0,0 +1,16 @@
import type { Note } from "@/generated/prisma/client";
export type NoteDto = Omit<Note, "tags"> & { tags: string[] };
export function toNoteDto(note: Note): NoteDto {
let tags: string[] = [];
if (note.tags) {
try {
const parsed: unknown = JSON.parse(note.tags);
if (Array.isArray(parsed) && parsed.every((tag) => typeof tag === "string")) tags = parsed;
} catch {
// A malformed legacy value must not break the whole notes list.
}
}
return { ...note, tags };
}
+10
View File
@@ -0,0 +1,10 @@
import { PrismaBetterSqlite3 } from "@prisma/adapter-better-sqlite3";
import { PrismaClient } from "@/generated/prisma/client";
const databaseUrl = process.env.DATABASE_URL ?? "file:./dev.db";
const adapter = new PrismaBetterSqlite3({ url: databaseUrl });
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
export const prisma = globalForPrisma.prisma ?? new PrismaClient({ adapter });
if (process.env.NODE_ENV !== "production") globalForPrisma.prisma = prisma;
+13
View File
@@ -0,0 +1,13 @@
import { z } from "zod";
export const createNoteSchema = z.object({
title: z.string().trim().max(160).optional().transform((value) => value || undefined),
content: z.string().trim().min(1, "Содержание заметки не может быть пустым.").max(20_000),
});
export const analysisSchema = z.object({
summary: z.string().trim().min(1).max(2_000),
tags: z.array(z.string().trim().min(1).max(40)).length(3),
});
export type Analysis = z.infer<typeof analysisSchema>;