☰ Categories

debug

Please debug the current codebase and implement a robust development plan to ensure the system is fully functional.

CategoryDevelopment › Coding
TagsAnalyzingReviewingDeveloperCode
Prompt
Please debug the current codebase and implement a robust development plan to ensure the system is fully functional. Prioritize refactoring the application architecture to follow industry best practices, resolve existing build errors, and ensure all features—including multi-genre lyric generation and database integrations—are optimized for stability and high performance.

What this prompt does

This development prompt asks to debug the current codebase and make the system functional. It mentions multi-genre lyric generation and database integrations, but the visible text gives no concrete code or environment.

Model comparison

Gemini offers sharp root-cause analysis but is excessive and speculative. ChatGPT is more concise with a stronger actionable plan, while [C] provides no answer.

ChatGPTTop overall
42/ 50

+ Covers multi-genre handling and failure paths concretely.

- Changes OpenAI and Prisma interfaces without verification.

Gemini
36/ 50

+ Correctly identifies the mismatch between the error and code.

- Assumes unverified infrastructure causes and schema changes.

CriterionChatGPTGeminiLeader
Instruction following98ChatGPT +13%
Accuracy76ChatGPT +17%
Specificity99Tie
Structure98ChatGPT +13%
Right length85ChatGPT +60%

Scored 1–10 by gpt-5.6-sol with model names hidden (2026-09-25). This is an AI review, not a measurement.

Read full answers

We gave three models the same input and copied their answers unedited. Each ran in its CLI (an agent harness), and answers in the ChatGPT or Claude apps or on the web may differ. Outputs are in Korean.

Input used
[Pasted material]
[증상] 배포 후 가사 생성 API가 간헐적으로 500 에러 발생. 로그: "TypeError: Cannot read properties of undefined (reading 'genre')"

// src/api/generateLyrics.ts
export async function generateLyrics(req, res) {
  const { genre, mood } = req.body;
  const template = GENRE_TEMPLATES[genre.toLowerCase()]; // genre가 undefined일 때 터짐
  const draft = await openai.complete(template.prompt);
  await db.lyrics.create({ data: { draft, userId: req.user.id } });
  res.json({ draft });
}

스택: Node 20 / Express / Prisma + PostgreSQL. 로컬에서는 재현 안 되고 프로덕션에서만 랜덤하게 터짐.
gpt-5.6-luna (codex CLI · 에이전트 하네스) · Run on 2026-09-24

현재 500 오류의 직접 원인은 입력값을 검증하기 전에 genre.toLowerCase()를 호출하는 것입니다. 프로덕션에서는 빈 body, 잘못된 Content-Type, 재시도 요청, 구버전 클라이언트 요청 등이 간헐적으로 유입될 수 있습니다.

다만 현재 환경은 읽기 전용이며 터미널·빌드 실행 도구도 제공되지 않아 실제 파일 수정과 테스트 실행은 완료할 수 없습니다. 우선 generateLyrics를 다음처럼 교체하는 것이 핵심입니다.

// src/api/generateLyrics.ts
import type { Request, Response, NextFunction } from "express";

type GenerateLyricsBody = {
  genre?: string | string[];
  mood?: string;
};

function normalizeGenres(value: unknown): string[] {
  const values = Array.isArray(value) ? value : [value];

  return values
    .filter((item): item is string => typeof item === "string")
    .flatMap((item) => item.split(","))
    .map((item) => item.trim().toLowerCase())
    .filter(Boolean);
}

export async function generateLyrics(
  req: Request,
  res: Response,
  next: NextFunction,
) {
  try {
    const body = (req.body ?? {}) as GenerateLyricsBody;
    const genres = normalizeGenres(body.genre);
    const mood =
      typeof body.mood === "string" ? body.mood.trim() : undefined;

    if (genres.length === 0) {
      return res.status(400).json({
        error: "genre must be a non-empty string or string array",
      });
    }

    if (genres.length > 3) {
      return res.status(400).json({
        error: "A maximum of 3 genres is supported",
      });
    }

    if (!req.user?.id) {
      return res.status(401).json({ error: "Authentication required" });
    }

    const templates = genres.map((genre) => GENRE_TEMPLATES[genre]);

    if (templates.some((template) => !template)) {
      return res.status(400).json({
        error: "Unsupported genre",
        supportedGenres: Object.keys(GENRE_TEMPLATES),
      });
    }

    const prompt = templates
      .map((template, index) => `Genre ${index + 1}:\n${template.prompt}`)
      .join("\n\n");

    const completion = await openai.complete({
      prompt: `${prompt}\n\nMood: ${mood || "neutral"}`,
      timeoutMs: 30_000,
    });

    const draft =
      typeof completion === "string"
        ? completion
        : completion.text ?? completion.choices?.[0]?.text;

    if (!draft) {
      throw new Error("OpenAI returned an empty completion");
    }

    const lyric = await db.lyrics.create({
      data: {
        draft,
        userId: req.user.id,
        genres,
        mood: mood ?? null,
      },
    });

    return res.status(201).json({
      id: lyric.id,
      draft,
      genres,
      mood: mood ?? null,
    });
  } catch (error) {
    return next(error);
  }
}

필수 전제는 다음과 같습니다.

  • express.json()이 라우트보다 먼저 등록되어야 합니다.
  • 인증 미들웨어가 req.user를 항상 설정해야 합니다.
  • Prisma 스키마에 genres String[], mood String?를 추가하거나 기존 컬럼 구조에 맞춰 저장해야 합니다.
  • OpenAI 호출에는 타임아웃, 재시도 횟수 제한, 응답 형식 검증이 필요합니다.
  • 전역 에러 미들웨어가 500 응답을 표준화하고 내부 오류를 외부에 노출하지 않아야 합니다.

권장 구조는 다음과 같습니다.

route
  → request validation middleware
  → controller
  → lyric generation service
  → OpenAI adapter
  → lyric repository
  → Prisma/PostgreSQL

개발 계획:

  1. 요청 검증을 controller 밖으로 분리하고 genre, mood, 배열 길이, 최대 문자열 길이를 검증합니다.
  2. 단일 장르와 다중 장르를 동일한 서비스 API로 통합합니다.
  3. OpenAI 연동을 adapter로 격리해 타임아웃·재시도·빈 응답 처리를 넣습니다.
  4. Prisma 연결 풀과 graceful shutdown을 설정하고, 애플리케이션 시작 시 prisma.$connect()를 확인합니다.
  5. 생성 요청에 idempotency key를 적용해 네트워크 재시도로 중복 가사가 생성되지 않게 합니다.
  6. 400/401/404/409/429/500 오류 포맷을 통일합니다.
  7. 다음 테스트를 추가합니다.
genre 누락 → 400
genre 빈 문자열 → 400
지원하지 않는 장르 → 400
장르 배열 3개 → 성공
장르 배열 4개 초과 → 400
인증 사용자 없음 → 401
OpenAI 타임아웃 → 504 또는 표준화된 502
OpenAI 빈 응답 → 502
Prisma 저장 실패 → 500 및 구조화 로그

검증 가능한 저장소 환경에서는 다음 순서로 확인해야 합니다.

npm ci
npx prisma validate
npx prisma generate
npm run build
npm test
npm run lint

현재 제공된 정보만으로는 실제 빌드 오류, Prisma 모델, OpenAI SDK 응답 형식, 프로젝트의 테스트 명령을 확인할 수 없으므로 해당 부분은 저장소 접근이 가능해진 뒤 검증해야 합니다.

More in this category

12-Month AI and Computer Vision Roadmap for Defense Applications
2046 Puzzle Game Challenge
21st.dev component prompt
3D FACTORY
3D FPS Game