ai-generation-persistence

작성자: openai

AI 생성 지속성 패턴 — 모든 LLM 생성에 대한 고유 ID, 주소 지정 가능한 URL, 데이터베이스 저장소 및 비용 추적

npx skills add https://github.com/openai/plugins --skill ai-generation-persistence

AI Generation Persistence

AI generations are expensive, non-reproducible assets. Never discard them.

Every call to an LLM costs real money and produces unique output that cannot be exactly reproduced. Treat generations like database records — assign an ID, persist immediately, and make them retrievable.

Core Rules

  1. Generate an ID before the LLM call — use nanoid() or createId() from @paralleldrive/cuid2
  2. Persist every generation — text and metadata to database, images and files to Vercel Blob
  3. Make every generation addressable — URL pattern: /chat/[id], /generate/[id], /image/[id]
  4. Track metadata — model name, token usage, estimated cost, timestamp, user ID
  5. Never stream without saving — if the user refreshes, the generation must survive

Generate-Then-Redirect Pattern

The standard UX flow for AI features: create the resource first, then redirect to its page.

// app/api/chat/route.ts
import { nanoid } from "nanoid";
import { db } from "@/lib/db";
import { redirect } from "next/navigation";

export async function POST(req: Request) {
  const { prompt, model } = await req.json();
  const id = nanoid();

  // Create the record BEFORE generation starts
  await db.insert(generations).values({
    id,
    prompt,
    model,
    status: "pending",
    createdAt: new Date(),
  });

  // Redirect to the generation page — it handles streaming
  redirect(`/chat/${id}`);
}
// app/chat/[id]/page.tsx
import { db } from "@/lib/db";
import { notFound } from "next/navigation";

export default async function ChatPage({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const generation = await db.query.generations.findFirst({
    where: eq(generations.id, id),
  });
  if (!generation) notFound();

  // Render with streaming if still pending, or show saved result
  return <ChatView generation={generation} />;
}

This gives you: shareable URLs, back-button support, multi-tab sessions, and generation history for free.

Persistence Schema

// lib/db/schema.ts
import { pgTable, text, integer, timestamp, jsonb } from "drizzle-orm/pg-core";

export const generations = pgTable("generations", {
  id: text("id").primaryKey(),            // nanoid
  userId: text("user_id"),                // auth user
  model: text("model").notNull(),         // "openai/gpt-5.4"
  prompt: text("prompt"),                 // input text
  result: text("result"),                 // generated output
  imageUrls: jsonb("image_urls"),         // Blob URLs for generated images
  tokenUsage: jsonb("token_usage"),       // { promptTokens, completionTokens }
  estimatedCostCents: integer("estimated_cost_cents"),
  status: text("status").default("pending"), // pending | streaming | complete | error
  createdAt: timestamp("created_at").defaultNow(),
});

Storage Strategy

Data TypeStorageWhy
Text, metadata, historyNeon Postgres via DrizzleQueryable, relational, supports search
Generated images & filesVercel Blob (@vercel/blob)Permanent URLs, CDN-backed, no expiry
Prompt dedup cacheUpstash RedisFast lookup, TTL-based expiry

Image Persistence

Never serve generated images as ephemeral base64 or temporary URLs. Save to Blob immediately:

import { put } from "@vercel/blob";
import { generateText } from "ai";

const result = await generateText({ model, prompt });

// Save every generated image to permanent storage
const imageUrls: string[] = [];
for (const file of result.files ?? []) {
  if (file.mediaType?.startsWith("image/")) {
    const ext = file.mediaType.split("/")[1] || "png";
    const blob = await put(`generations/${generationId}.${ext}`, file.uint8Array, {
      access: "public",
      contentType: file.mediaType,
    });
    imageUrls.push(blob.url);
  }
}

// Update the generation record with permanent URLs
await db.update(generations)
  .set({ imageUrls, status: "complete" })
  .where(eq(generations.id, generationId));

Cost Tracking

Extract usage from every generation and store it. This enables billing, budgeting, and abuse detection:

const result = await generateText({ model, prompt });

const usage = result.usage; // { promptTokens, completionTokens, totalTokens }
const estimatedCostCents = estimateCost(model, usage);

await db.update(generations).set({
  result: result.text,
  tokenUsage: usage,
  estimatedCostCents,
  status: "complete",
}).where(eq(generations.id, generationId));

Prompt Dedup / Caching

Avoid paying for identical generations. Cache by content hash:

import { Redis } from "@upstash/redis";
import { createHash } from "crypto";

const redis = Redis.fromEnv();

function hashPrompt(model: string, prompt: string): string {
  return createHash("sha256").update(`${model}:${prompt}`).digest("hex");
}

// Check cache before generating
const cacheKey = `gen:${hashPrompt(model, prompt)}`;
const cached = await redis.get<string>(cacheKey);
if (cached) return cached; // Return cached generation ID

// After generation, cache the result
await redis.set(cacheKey, generationId, { ex: 3600 }); // 1hr TTL

Anti-Patterns

  • Streaming to client without saving — generation lost on page refresh. Always write to DB as tokens arrive or on completion.
  • Routes without [id] segments/api/chat with no ID means generations aren't addressable. Use /chat/[id].
  • Re-generating identical prompts — check cache first. Same prompt + same model = same cost for no new value.
  • Ephemeral base64 images — generated images served inline are lost when the component unmounts. Save to Vercel Blob.
  • Missing metadata — always store model name, token counts, and timestamp. You need this for cost tracking and debugging.
  • Client-only state — storing generations only in React state or localStorage. Use a database — generations must survive across devices and sessions.

openai의 다른 스킬

user-context
openai
데이터 분석 플러그인의 지속적인 소스 라우팅 기본 설정, 온보딩 로직, 설정 진행 상황 및 의미 계층 레지스트리를 로드하거나 관리합니다.
official
notion-research-documentation
openai
Notion 콘텐츠를 조사하고 인용문과 함께 구조화된 브리핑, 보고서 또는 비교 자료로 종합합니다. 대상 질의를 사용해 Notion 페이지를 검색하고 가져온 후, 인라인 출처 인용과 참고 문헌 섹션을 포함해 주제별로 결과를 정리합니다. 범위와 사용자 목표에 따라 네 가지 출력 형식(빠른 브리핑, 연구 요약, 비교, 종합 보고서) 중에서 선택합니다. 내장 템플릿을 사용해 Notion 페이지를 생성 및 업데이트하고, 새 정보가 도착하면 출처를 직접 연결하고 변경 사항을 추적합니다...
official
rcsb-pdb-skill
openai
핵심 메타데이터, Search API 쿼리 및 FASTA 다운로드를 위한 간결한 RCSB PDB 요청을 제출합니다. 사용자가 간결한 RCSB 요약을 원할 때 사용하며, 원시 JSON 또는…을 저장합니다.
official
pdf
openai
PDF 읽기, 생성 및 검증 기능을 제공하며, 시각적 렌더링과 프로그래매틱 생성을 지원합니다. Poppler(pdftoppm)를 사용하여 PDF 페이지를 PNG로 렌더링하여 레이아웃, 간격, 타이포그래피를 시각적으로 검사할 수 있습니다. reportlab을 사용하여 프로그래매틱 방식으로 PDF를 생성하여 안정적인 포맷을 보장하며, pdfplumber 또는 pypdf를 통해 텍스트와 메타데이터를 추출합니다. 품질 기준을 준수합니다: 잘린 텍스트, 겹치는 요소, 깨진 표, 렌더링 아티팩트가 없어야 하며, ASCII 하이픈만 사용하고 사람이 읽을 수 있는 인용을 사용합니다.
official
test-coverage-improver
openai
Improve test coverage in the OpenAI Agents JS monorepo: run `pnpm test:coverage`, inspect coverage artifacts, identify low-coverage files and branches, propose…
official
playwright
openai
터미널 기반 브라우저 자동화로 요소 스냅샷 및 대화형 UI 워크플로우 지원. playwright-cli 래퍼 스크립트를 통해 작동하며(npx 필요), 헤드리스 및 헤드 모드 모두 지원하여 시각적 디버깅 가능. 핵심 워크플로우: 페이지 열기, 안정적인 요소 참조를 위한 스냅샷 생성, 참조를 사용한 상호작용, 탐색 또는 DOM 변경 후 재스냅샷. 양식 작성, 클릭, 타이핑, 다중 탭 관리, 스크린샷/PDF 캡처, 흐름 디버깅을 위한 트레이스 기록 포함. 요소 참조(예: e3, e15)...
official
ukb-topmed-phewas-skill
openai
단일 변이에 대한 간결한 UKB-TOPMed PheWAS 요약을 가져오며, rsID, GRCh37 또는 GRCh38 입력을 받아 필요한 GRCh38 쿼리로 변환합니다. 다음과 같은 경우에 사용하세요…
official
code-review-context
openai
모델 가시 컨텍스트
official