const DATA = window.AGENT_STATIC_DATA;
const $ = (id) => document.getElementById(id);
const state = {
page: "run-page",
resultTab: "summary",
promptTab: "analysis",
apiKey: "",
users: [],
activeUser: 0,
activePassage: 0,
workspaceVisible: false,
running: false,
executionMode: "all",
manualRun: null,
exchangeRate: null,
gptSettings: defaultGptSettings(),
prompts: null,
defaultPrompts: null,
lastRun: null,
};
function escapeHtml(value) {
return String(value ?? "").replace(/[&<>"']/g, (char) => ({
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
}[char]));
}
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function canonicalModelLabel(label) {
return DATA.modelAliases[label] || label || DATA.models[0].label;
}
function modelRow(label) {
const canonical = canonicalModelLabel(label);
return DATA.models.find((row) => row.label === canonical) || DATA.models[0];
}
function modelMaxOutputTokens(label) {
return clampInt(modelRow(label).max_output_tokens, DATA.maxOutputTokens, DATA.minOutputTokens, DATA.maxOutputTokens);
}
function clampOutputTokens(label, value) {
const maxTokens = modelMaxOutputTokens(label);
return clampInt(value, Math.min(DATA.defaultOutputTokens, maxTokens), DATA.minOutputTokens, maxTokens);
}
function defaultGptSettings() {
return {
analysis_model_label: DATA.models[0].label,
analysis_max_output_tokens: DATA.defaultOutputTokens,
generation_model_label: DATA.models[0].label,
generation_max_output_tokens: DATA.defaultOutputTokens,
inspection_model_label: DATA.models[0].label,
inspection_max_output_tokens: DATA.defaultOutputTokens,
};
}
function normalizeGptSettings(settings) {
const current = settings || defaultGptSettings();
const analysisModel = canonicalModelLabel(current.analysis_model_label);
const generationModel = canonicalModelLabel(current.generation_model_label);
const inspectionModel = canonicalModelLabel(current.inspection_model_label);
return {
analysis_model_label: analysisModel,
analysis_max_output_tokens: clampOutputTokens(analysisModel, current.analysis_max_output_tokens),
generation_model_label: generationModel,
generation_max_output_tokens: clampOutputTokens(generationModel, current.generation_max_output_tokens),
inspection_model_label: inspectionModel,
inspection_max_output_tokens: clampOutputTokens(inspectionModel, current.inspection_max_output_tokens),
};
}
function stageConfig(stageKey) {
const settings = normalizeGptSettings(state.gptSettings);
if (stageKey === "analysis") {
return {
model_label: settings.analysis_model_label,
max_output_tokens: settings.analysis_max_output_tokens,
};
}
if (stageKey === "generation") {
return {
model_label: settings.generation_model_label,
max_output_tokens: settings.generation_max_output_tokens,
};
}
return {
model_label: settings.inspection_model_label,
max_output_tokens: settings.inspection_max_output_tokens,
};
}
async function init() {
forceLightTheme();
state.prompts = await loadPrompts();
state.defaultPrompts = clone(state.prompts);
state.gptSettings = normalizeGptSettings(state.gptSettings);
buildModelControls();
buildPromptTypeSelect();
resizeWorkspace(1, 1);
bindEvents();
renderAll();
$("workspace").classList.add("hidden");
$("prompt-status").textContent = "프롬프트를 불러왔습니다.";
}
function forceLightTheme() {
try {
localStorage.setItem("theme", "light");
localStorage.setItem("__theme", "light");
} catch (_) {}
document.documentElement.classList.remove("dark");
document.documentElement.dataset.theme = "light";
}
async function loadPrompts() {
const generation = {};
const inspection = {};
for (const type of DATA.problemTypes) {
generation[type] = effectivePrompt(
await fetchText(DATA.promptFiles.generation[type], `${DATA.fallbackPrompts.generation}\n\n유형: ${type}`),
"generation",
);
inspection[type] = effectivePrompt(
await fetchText(DATA.promptFiles.inspection[type], `${DATA.fallbackPrompts.inspection}\n\n유형: ${type}`),
"inspection",
);
}
return {
generation_prompt_type: DATA.problemTypes[0],
inspection_prompt_type: DATA.problemTypes[0],
analysis_prompt: effectivePrompt(await fetchText(DATA.promptFiles.analysis, DATA.fallbackPrompts.analysis), "analysis"),
generation_prompts: generation,
inspection_prompts: inspection,
};
}
function normalizePrompts(prompts) {
const fallback = state.defaultPrompts || {
generation_prompt_type: DATA.problemTypes[0],
inspection_prompt_type: DATA.problemTypes[0],
analysis_prompt: "",
generation_prompts: {},
inspection_prompts: {},
};
const normalized = clone(fallback);
normalized.generation_prompt_type = DATA.problemTypes.includes(prompts?.generation_prompt_type)
? prompts.generation_prompt_type
: DATA.problemTypes[0];
normalized.inspection_prompt_type = DATA.problemTypes.includes(prompts?.inspection_prompt_type)
? prompts.inspection_prompt_type
: normalized.generation_prompt_type;
normalized.analysis_prompt = String(prompts?.analysis_prompt ?? normalized.analysis_prompt ?? "");
normalized.generation_prompts = {...normalized.generation_prompts};
normalized.inspection_prompts = {...normalized.inspection_prompts};
for (const type of DATA.problemTypes) {
normalized.generation_prompts[type] = String(
prompts?.generation_prompts?.[type] ?? normalized.generation_prompts[type] ?? "",
);
normalized.inspection_prompts[type] = String(
prompts?.inspection_prompts?.[type] ?? normalized.inspection_prompts[type] ?? "",
);
}
return normalized;
}
async function fetchText(path, fallback) {
try {
const response = await fetch(path, {cache: "no-store"});
if (!response.ok) throw new Error(String(response.status));
return await response.text();
} catch (_) {
return fallback;
}
}
function formatInstruction(stage) {
const allowed = DATA.problemTypes.join(", ");
if (stage === "analysis") {
return `
응답은 PassageTypeAnalysisResponse 구조로만 작성한다.
- 필드는 types 하나만 사용한다.
- types에는 다음 유형명만 넣는다: ${allowed}
- 코드명, 단계명, 이유, 근거, 주문서는 넣지 않는다.
- 만들 수 있는 유형이 없으면 빈 배열을 반환한다.
`;
}
if (stage === "generation") {
return `
응답은 ProblemGenerationResponse 구조로만 작성한다.
- 입력은 JSON이며 from_who, original_text, previous_generation, verification_result를 읽는다.
- from_who가 "analysis"이면 previous_generation과 verification_result는 null이며, original_text를 바탕으로 새 문항을 만든다.
- from_who가 "verification"이면 previous_generation과 verification_result를 반드시 반영해 기존 문항을 개선한다.
- verification_result.review_reasons와 scores에서 감점된 지점을 우선 수정한다.
- from_who가 "verification"일 때 문제 유형 type은 유지한다. 완전히 다른 유형으로 바꾸지 않는다.
- from_who가 "verification"일 때도 응답은 수정 완료된 전체 ProblemGenerationResponse 하나만 반환한다.
- type은 이 생성 에이전트의 유형명을 쓴다.
- status는 "생성 완료" 또는 "생성 불가"만 쓴다.
- question은 해당 문제 유형에 맞는 발문만 쓴다.
- question_text는 해당 문제 유형에 맞는 원문, 빈칸, 밑줄, 삽입 위치, 번호 문장, 도표 등 학생이 읽고 풀 실제 문항 본문만 쓴다.
- question_choice는 JSON 객체로 쓰고, 키는 반드시 "1", "2", "3", "4", "5" 다섯 개다. 값에는 선지 내용만 쓴다.
- answer는 객관식이면 "1"~"5" 문자열만 쓴다. 원문자 숫자는 절대 쓰지 않는다.
- reason은 정답 이유와 풀이 설명만 쓴다.
- 코드명이나 단계명은 어떤 필드에도 쓰지 않는다.
`;
}
return `
응답은 ProblemInspectionResponse 구조로만 작성한다.
- verification_count는 0으로 작성한다. 자동화 코드가 실제 검사 횟수로 덮어쓴다.
- total_score는 100점 만점 정수다.
- judgment는 90점 이상이면 "PASS", 90점 미만이면 "FAIL"이다.
- review_reasons는 검사 판단 이유를 짧고 구체적으로 쓴다.
- 코드명이나 단계명은 어떤 필드에도 쓰지 않는다.
`;
}
function effectivePrompt(basePrompt, stage) {
return `${String(basePrompt || "").trimEnd()}${formatInstruction(stage)}`;
}
function buildModelControls() {
for (const id of ["analysis-model", "generation-model", "inspection-model"]) {
$(id).innerHTML = DATA.models.map((row) => ``).join("");
}
$("model-table").innerHTML = `
| label | api_model | input_usd_1m | output_usd_1m | max_output_tokens |
${
DATA.models.map((row) => `| ${escapeHtml(row.label)} | ${escapeHtml(row.api_model)} | ${Number(row.input_usd_1m).toFixed(2)} | ${Number(row.output_usd_1m).toFixed(2)} | ${Number(row.max_output_tokens).toLocaleString()} |
`).join("")
}
`;
}
function buildPromptTypeSelect() {
$("prompt-type").innerHTML = DATA.problemTypes.map((type) => ``).join("");
}
function bindEvents() {
document.querySelectorAll(".top-tab").forEach((button) => {
button.addEventListener("click", () => {
state.page = button.dataset.page;
renderPage();
if (state.page === "settings-page") renderGptSettings();
if (state.page === "prompts-page") renderPromptEditor();
});
});
document.querySelectorAll(".sub-tab").forEach((button) => {
button.addEventListener("click", () => {
state.resultTab = button.dataset.resultTab;
renderResultTabs();
});
});
$("api-key").addEventListener("input", () => {
state.apiKey = $("api-key").value.trim();
});
$("apply-workspace").addEventListener("click", () => {
resizeWorkspace(
clampInt($("user-count").value, 1, 1, 100),
clampInt($("passage-count").value, 1, 1, 50),
);
state.workspaceVisible = true;
$("workspace").classList.remove("hidden");
renderWorkspace();
});
$("prev-user").addEventListener("click", () => moveUser(-1));
$("next-user").addEventListener("click", () => moveUser(1));
$("prev-passage").addEventListener("click", () => movePassage(-1));
$("next-passage").addEventListener("click", () => movePassage(1));
$("passage-input").addEventListener("input", () => {
currentPassage().text = $("passage-input").value;
});
document.querySelectorAll('input[name="run-mode"]').forEach((input) => {
input.addEventListener("change", () => {
state.executionMode = input.value === "step" ? "step" : "all";
state.manualRun = null;
$("download-panel").classList.add("hidden");
renderRunControls();
});
});
$("run-button").addEventListener("click", runWorkspace);
$("next-button").addEventListener("click", runManualStep);
bindStageSettings("analysis");
bindStageSettings("generation");
bindStageSettings("inspection");
$("save-gpt-settings").addEventListener("click", () => {
readGptSettingsFromUi();
$("gpt-settings-status").innerHTML = gptSettingsStatus("GPT 설정 저장 완료");
});
document.querySelectorAll(".prompt-tab").forEach((button) => {
button.addEventListener("click", () => {
saveVisiblePrompt();
state.promptTab = button.dataset.promptTab || "analysis";
renderPromptEditor();
});
});
$("prompt-type").addEventListener("change", () => {
saveVisiblePrompt();
const type = $("prompt-type").value || DATA.problemTypes[0];
state.prompts.generation_prompt_type = type;
state.prompts.inspection_prompt_type = type;
renderPromptEditor();
});
$("save-prompt").addEventListener("click", () => {
saveVisiblePrompt();
$("prompt-status").innerHTML = promptStatus("프롬프트 저장 완료");
});
$("download-prompts-csv").addEventListener("click", downloadPromptsSheet);
$("download-prompt-template").addEventListener("click", downloadPromptTemplateSheet);
$("import-prompts-file").addEventListener("click", showPromptUploadPicker);
$("upload-prompts-file").addEventListener("change", importPromptsFile);
$("download-txt").addEventListener("click", () => downloadExport("txt"));
$("download-json").addEventListener("click", () => downloadExport("json"));
$("download-system-csv").addEventListener("click", () => downloadExport("system-csv"));
$("download-zip").addEventListener("click", () => downloadExport("zip"));
}
function bindStageSettings(stage) {
const model = $(`${stage}-model`);
const range = $(`${stage}-tokens`);
const number = $(`${stage}-token-number`);
model.addEventListener("change", () => {
readGptSettingsFromUi();
renderGptSettings();
});
range.addEventListener("input", () => {
number.value = range.value;
readGptSettingsFromUi();
renderGptStatusOnly();
});
number.addEventListener("input", () => {
const label = model.value;
const value = clampOutputTokens(label, number.value);
range.value = value;
number.value = value;
readGptSettingsFromUi();
renderGptStatusOnly();
});
}
function renderAll() {
renderPage();
renderWorkspace();
renderRunControls();
renderGptSettings();
renderPromptEditor();
renderOutputs();
}
function renderRunControls() {
const stepMode = state.executionMode === "step";
$("run-button").classList.toggle("hidden", stepMode);
$("next-button").classList.toggle("hidden", !stepMode || isManualDone());
$("next-button").disabled = state.running || !stepMode || isManualDone();
$("next-button").textContent = manualNextButtonLabel();
document.querySelectorAll('input[name="run-mode"]').forEach((input) => {
input.checked = input.value === (stepMode ? "step" : "all");
});
}
function renderPage() {
document.querySelectorAll(".page").forEach((page) => page.classList.toggle("active", page.id === state.page));
document.querySelectorAll(".top-tab").forEach((button) => button.classList.toggle("active", button.dataset.page === state.page));
}
function resizeWorkspace(userCount, passageCount) {
const previous = state.users;
state.users = Array.from({length: userCount}, (_, userIndex) => {
const oldUser = previous[userIndex];
return {
name: `User ${userIndex + 1}`,
passages: Array.from({length: passageCount}, (_, passageIndex) => oldUser?.passages?.[passageIndex] || {
text: "",
result: emptyPassageResult(),
}),
};
});
state.activeUser = Math.min(state.activeUser, userCount - 1);
state.activePassage = Math.min(state.activePassage, passageCount - 1);
}
function emptyPassageResult() {
return {
status: "대기",
analysisTypes: [],
results: [],
runs: [],
error: "",
seconds: 0,
};
}
function currentUser() {
return state.users[state.activeUser];
}
function currentPassage() {
return currentUser().passages[state.activePassage];
}
function moveUser(delta) {
saveCurrentPassageText();
state.activeUser = wrapIndex(state.activeUser + delta, state.users.length);
state.activePassage = Math.min(state.activePassage, currentUser().passages.length - 1);
renderWorkspace();
}
function movePassage(delta) {
saveCurrentPassageText();
state.activePassage = wrapIndex(state.activePassage + delta, currentUser().passages.length);
renderWorkspace();
}
function saveCurrentPassageText() {
if (!state.workspaceVisible || !state.users.length) return;
currentPassage().text = $("passage-input").value;
}
function renderWorkspace() {
if (!state.users.length) return;
$("user-label").textContent = `사용자 ${state.activeUser + 1} / ${state.users.length}`;
$("passage-label").textContent = `지문 ${state.activePassage + 1} / ${currentUser().passages.length}`;
$("passage-input").value = currentPassage().text || "";
}
function readGptSettingsFromUi() {
const settings = {
analysis_model_label: $("analysis-model").value,
analysis_max_output_tokens: $("analysis-token-number").value || $("analysis-tokens").value,
generation_model_label: $("generation-model").value,
generation_max_output_tokens: $("generation-token-number").value || $("generation-tokens").value,
inspection_model_label: $("inspection-model").value,
inspection_max_output_tokens: $("inspection-token-number").value || $("inspection-tokens").value,
};
state.gptSettings = normalizeGptSettings(settings);
}
function renderGptSettings() {
state.gptSettings = normalizeGptSettings(state.gptSettings);
renderStageSetting("analysis", state.gptSettings.analysis_model_label, state.gptSettings.analysis_max_output_tokens);
renderStageSetting("generation", state.gptSettings.generation_model_label, state.gptSettings.generation_max_output_tokens);
renderStageSetting("inspection", state.gptSettings.inspection_model_label, state.gptSettings.inspection_max_output_tokens);
renderGptStatusOnly();
}
function renderStageSetting(stage, label, tokens) {
const maxTokens = modelMaxOutputTokens(label);
const value = clampOutputTokens(label, tokens);
$(`${stage}-model`).value = label;
$(`${stage}-tokens`).max = maxTokens;
$(`${stage}-tokens`).value = value;
$(`${stage}-token-number`).max = maxTokens;
$(`${stage}-token-number`).value = value;
}
function renderGptStatusOnly() {
$("gpt-settings-status").innerHTML = gptSettingsStatus("저장된 GPT 설정");
}
function gptSettingsStatus(prefix) {
const s = normalizeGptSettings(state.gptSettings);
return `${escapeHtml(prefix)}
지문분석: ${escapeHtml(s.analysis_model_label)} / ${Number(s.analysis_max_output_tokens).toLocaleString()} tokens
문제 생성: ${escapeHtml(s.generation_model_label)} / ${Number(s.generation_max_output_tokens).toLocaleString()} tokens
검증: ${escapeHtml(s.inspection_model_label)} / ${Number(s.inspection_max_output_tokens).toLocaleString()} tokens`;
}
function saveVisiblePrompt() {
if (!state.prompts) return;
if (state.promptTab === "analysis") {
state.prompts.analysis_prompt = $("system-prompt").value;
return;
}
const type = state.prompts.generation_prompt_type || DATA.problemTypes[0];
state.prompts.inspection_prompt_type = type;
state.prompts.generation_prompts[type] = $("generation-system-prompt").value;
state.prompts.inspection_prompts[type] = $("inspection-system-prompt").value;
}
function renderPromptEditor() {
if (!state.prompts) return;
document.querySelectorAll(".prompt-tab").forEach((button) => button.classList.toggle("active", button.dataset.promptTab === state.promptTab));
const pairMode = state.promptTab === "generation";
$("prompt-type-row").classList.toggle("hidden", !pairMode);
$("single-prompt-layout").classList.toggle("hidden", pairMode);
$("paired-prompt-layout").classList.toggle("hidden", !pairMode);
if (state.promptTab === "analysis") {
$("system-prompt").value = state.prompts.analysis_prompt;
$("input-shape").value = analysisInputTemplate();
$("output-shape").value = analysisOutputShape();
}
if (pairMode) {
const type = state.prompts.generation_prompt_type || DATA.problemTypes[0];
state.prompts.inspection_prompt_type = type;
$("prompt-type-label").textContent = "문제 유형";
$("prompt-type").value = type;
$("prompt-pair-title").textContent = `${type} 생성 AGENT + ${type} 검증 AGENT`;
$("generation-system-prompt").value = state.prompts.generation_prompts[type] || "";
$("inspection-system-prompt").value = state.prompts.inspection_prompts[type] || "";
$("generation-input-shape").value = generationInputTemplate(type);
$("generation-output-shape").value = generationOutputShape(type);
$("inspection-input-shape").value = inspectionInputTemplate();
$("inspection-output-shape").value = inspectionOutputShape(type);
}
$("prompt-status").innerHTML = promptStatus("저장된 프롬프트");
}
function promptStatus(prefix) {
const generationType = state.prompts?.generation_prompt_type || DATA.problemTypes[0];
const inspectionType = state.prompts?.inspection_prompt_type || generationType;
return `${escapeHtml(prefix)}
지문 분석: ${Number(state.prompts?.analysis_prompt?.length || 0).toLocaleString()}자
문제 생성: ${escapeHtml(generationType)} / ${Number(state.prompts?.generation_prompts?.[generationType]?.length || 0).toLocaleString()}자
검증: ${escapeHtml(inspectionType)} / ${Number(state.prompts?.inspection_prompts?.[inspectionType]?.length || 0).toLocaleString()}자`;
}
function inspectionPromptForType(questionType) {
const fallbackType = state.prompts?.inspection_prompt_type || DATA.problemTypes[0];
return state.prompts?.inspection_prompts?.[questionType]
|| state.prompts?.inspection_prompts?.[fallbackType]
|| effectivePrompt(DATA.fallbackPrompts.inspection, "inspection");
}
async function runWorkspace() {
saveCurrentPassageText();
readGptSettingsFromUi();
saveVisiblePrompt();
state.manualRun = null;
const jobs = workspaceJobs();
if (!jobs.length) {
state.lastRun = {startedAt: performance.now(), statusMessage: "지문을 입력해야 합니다.", jobs: [], batchResults: []};
renderOutputs();
return;
}
state.apiKey = $("api-key").value.trim();
if (!state.apiKey) {
state.page = "settings-page";
renderPage();
alert("OpenAI API 키를 입력해 주세요.");
return;
}
state.running = true;
renderRunControls();
$("run-modal").classList.remove("hidden");
$("download-panel").classList.add("hidden");
state.exchangeRate = await getExchangeRate();
state.lastRun = {
startedAt: performance.now(),
statusMessage: `사용자 ${new Set(jobs.map((job) => job.user_name)).size.toLocaleString()}명 · 지문 ${jobs.length.toLocaleString()}개 실행 중`,
jobs,
batchResults: [],
};
renderOutputs();
let completed = 0;
await Promise.all(jobs.map(async (job, index) => {
const result = await executePassageJob(job, index + 1);
state.lastRun.batchResults.push(result);
state.lastRun.batchResults.sort((a, b) => a.job_order - b.job_order);
completed += 1;
state.lastRun.statusMessage = `지문 처리 중 ${completed}/${jobs.length}`;
renderOutputs();
}));
state.lastRun.statusMessage = "완료";
state.running = false;
$("run-modal").classList.add("hidden");
renderRunControls();
renderOutputs();
}
function jobSignature(jobs) {
return JSON.stringify(jobs.map((job) => [job.user_name, job.passage_index, job.passage]));
}
function emptyTypeResult(questionType) {
return {
type: questionType,
status: "생성 대기",
verification_count: 0,
generation: null,
inspections: [],
runs: [],
review_seen: {},
};
}
function initialManualRun(jobs) {
const startedAt = performance.now();
return {
signature: jobSignature(jobs),
startedAt,
statusMessage: "따로 실행 대기",
jobs,
batchResults: jobs.map((job, index) => ({
job_order: index + 1,
user_name: job.user_name,
passage_index: job.passage_index,
passage: job.passage,
status: "지문 분석 대기",
analysis_types: [],
results: [],
runs: [],
seconds: 0,
error: "",
})),
nextStage: "analysis",
done: false,
};
}
function isManualDone() {
return !!(state.manualRun?.done || state.manualRun?.nextStage === "done");
}
function manualNextButtonLabel() {
const stage = state.manualRun?.nextStage || "analysis";
if (isManualDone()) return "완료";
if (stage === "generation") return "다음: 문제 생성";
if (stage === "inspection") return "다음: 검사";
return "다음: 지문 분석";
}
function nextManualStage(batchResults) {
if ((batchResults || []).some((item) => !(item.runs || []).length && !["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(item.status))) return "analysis";
if ((batchResults || []).some((item) => (item.results || []).some((result) => ["생성 대기", "재생성 대기"].includes(result.status)))) return "generation";
if ((batchResults || []).some((item) => (item.results || []).some((result) => result.status === "검사 대기"))) return "inspection";
return "done";
}
function refreshManualPassageStatuses(batchResults) {
for (const item of batchResults || []) {
if (item.error) continue;
const results = item.results || [];
if (!(item.runs || []).length) {
item.status = "지문 분석 대기";
continue;
}
if (!results.length) {
item.status = (item.analysis_types || []).length ? `${item.analysis_types.length}개 유형 생성 대기` : "생성 가능한 유형 없음";
continue;
}
const generationWait = results.filter((result) => ["생성 대기", "재생성 대기"].includes(result.status)).length;
const inspectionWait = results.filter((result) => result.status === "검사 대기").length;
if (generationWait) {
item.status = `${generationWait}개 유형 문제 생성 대기`;
continue;
}
if (inspectionWait) {
item.status = `${inspectionWait}개 유형 검사 대기`;
continue;
}
const passed = results.filter((result) => result.status === "통과").length;
const review = results.filter((result) => result.status === "사람 검토").length;
const failed = results.filter((result) => ["생성 실패", "생성 불가"].includes(result.status)).length;
item.status = `완료 · 통과 ${passed} · 사람 검토 ${review} · 생성 실패 ${failed}`;
}
}
async function runManualStep() {
saveCurrentPassageText();
readGptSettingsFromUi();
saveVisiblePrompt();
const jobs = workspaceJobs();
if (!jobs.length) {
state.manualRun = initialManualRun([]);
state.manualRun.done = true;
state.manualRun.statusMessage = "지문을 입력해야 합니다.";
state.lastRun = state.manualRun;
renderOutputs();
renderRunControls();
return;
}
state.apiKey = $("api-key").value.trim();
if (!state.apiKey) {
state.page = "settings-page";
renderPage();
alert("OpenAI API 키를 입력해 주세요.");
return;
}
if (!state.manualRun || state.manualRun.signature !== jobSignature(jobs) || state.manualRun.done) {
state.manualRun = initialManualRun(jobs);
}
state.lastRun = state.manualRun;
const stage = state.manualRun.nextStage || nextManualStage(state.manualRun.batchResults);
if (stage === "done") {
state.manualRun.done = true;
state.manualRun.statusMessage = "완료";
renderOutputs();
renderRunControls();
return;
}
const stageName = {analysis: "지문 분석", generation: "문제 생성", inspection: "검사"}[stage] || "다음 단계";
state.running = true;
state.manualRun.statusMessage = `${stageName} 실행 중`;
$("run-modal").classList.remove("hidden");
$("download-panel").classList.add("hidden");
renderOutputs();
renderRunControls();
state.exchangeRate = await getExchangeRate();
try {
if (stage === "analysis") await runManualAnalysisStep();
else if (stage === "generation") await runManualGenerationStep();
else if (stage === "inspection") await runManualInspectionStep();
} catch (error) {
state.manualRun.statusMessage = `오류: ${String(error?.message || error)}`;
}
refreshManualPassageStatuses(state.manualRun.batchResults);
state.manualRun.nextStage = nextManualStage(state.manualRun.batchResults);
state.manualRun.done = state.manualRun.nextStage === "done";
state.manualRun.statusMessage = state.manualRun.done ? "완료" : `${stageName} 완료`;
state.running = false;
$("run-modal").classList.add("hidden");
state.lastRun = state.manualRun;
renderOutputs();
renderRunControls();
}
async function runManualAnalysisStep() {
const run = state.manualRun;
await Promise.all(run.batchResults.map(async (item, index) => {
if ((item.runs || []).length || ["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(item.status)) return;
const job = run.jobs[index];
item.status = "지문 분석 실행 중";
const started = performance.now();
const analysisRun = await callAgent({
agent_id: "analysis_agent",
stage: "지문 분석",
agent_name: "지문 분석 에이전트",
question_type: "",
system_prompt: state.prompts.analysis_prompt,
}, analysisInput(job.passage), "analysis", "");
item.runs.push(analysisRun);
item.seconds = (performance.now() - started) / 1000;
if (analysisRun.status !== "OK" || !analysisRun.parsed) {
item.status = "지문 분석 실패";
item.error = analysisRun.error;
return;
}
item.analysis_types = uniqueTypes(analysisRun.parsed.types);
item.results = item.analysis_types.map(emptyTypeResult);
item.status = item.analysis_types.length ? `${item.analysis_types.length}개 유형 생성 대기` : "생성 가능한 유형 없음";
}));
}
async function runManualGenerationStep() {
const run = state.manualRun;
const tasks = [];
for (const item of run.batchResults) {
for (const result of item.results || []) {
if (!["생성 대기", "재생성 대기"].includes(result.status)) continue;
tasks.push((async () => {
const questionType = result.type;
const previousInspection = (result.inspections || []).length ? result.inspections[result.inspections.length - 1] : null;
const previousGeneration = previousInspection ? result.generation : null;
const fromWho = previousGeneration && previousInspection ? "verification" : "analysis";
result.status = "문제 생성 실행 중";
const generationRun = await callAgent({
agent_id: `generation_${DATA.typeSlugs[questionType] || questionType}`,
stage: "문제 생성",
agent_name: `${questionType} 생성 에이전트`,
question_type: questionType,
system_prompt: state.prompts.generation_prompts[questionType],
}, generationInput(item.passage, {
from_who: fromWho,
previous_generation: previousGeneration,
verification_result: previousInspection,
}), "generation", questionType);
result.runs.push(generationRun);
item.runs.push(generationRun);
if (generationRun.status !== "OK" || !generationRun.parsed) {
result.status = "생성 실패";
return;
}
result.generation = generationRun.parsed;
result.status = result.generation.status === "생성 불가" ? "생성 불가" : "검사 대기";
})());
}
}
await Promise.all(tasks);
}
async function runManualInspectionStep() {
const run = state.manualRun;
const tasks = [];
for (const item of run.batchResults) {
for (const result of item.results || []) {
if (result.status !== "검사 대기") continue;
tasks.push((async () => {
const questionType = result.type;
const verificationCount = (result.inspections || []).length + 1;
result.status = "검사 실행 중";
const inspectionRun = await callAgent({
agent_id: `inspection_${DATA.typeSlugs[questionType] || questionType}`,
stage: "검사",
agent_name: `${questionType} 검증 에이전트`,
question_type: questionType,
system_prompt: inspectionPromptForType(questionType),
}, inspectionInput(item.passage, result.generation), "inspection", questionType);
if (inspectionRun.parsed) {
inspectionRun.parsed.verification_count = verificationCount;
inspectionRun.output_text = renderInspection(inspectionRun.parsed);
inspectionRun.structured_json = JSON.stringify(inspectionRun.parsed, null, 2);
}
result.runs.push(inspectionRun);
item.runs.push(inspectionRun);
if (inspectionRun.status !== "OK" || !inspectionRun.parsed) {
result.status = "사람 검토";
return;
}
result.inspections.push(inspectionRun.parsed);
result.verification_count = result.inspections.length;
if (inspectionRun.parsed.judgment === "PASS") {
result.status = "통과";
return;
}
const signature = reviewSignature(inspectionRun.parsed);
if (signature) result.review_seen[signature] = (result.review_seen[signature] || 0) + 1;
if (verificationCount >= 3 || (signature && result.review_seen[signature] >= 2)) result.status = "사람 검토";
else result.status = "재생성 대기";
})());
}
}
await Promise.all(tasks);
}
function workspaceJobs() {
const jobs = [];
state.users.forEach((user, userIndex) => {
let passageNumber = 0;
user.passages.forEach((passage, passageIndex) => {
if (!String(passage.text || "").trim()) return;
passageNumber += 1;
jobs.push({
user_index: userIndex,
passage_index_zero: passageIndex,
user_name: `User ${userIndex + 1}`,
passage_index: passageNumber,
passage: passage.text,
});
});
});
return jobs;
}
async function executePassageJob(job, jobOrder) {
const started = performance.now();
const passageObject = state.users[job.user_index].passages[job.passage_index_zero];
const passageResult = emptyPassageResult();
passageResult.status = "지문 분석 실행 중";
passageObject.result = passageResult;
renderOutputs();
try {
const analysisRun = await callAgent({
agent_id: "analysis_agent",
stage: "지문 분석",
agent_name: "지문 분석 에이전트",
question_type: "",
system_prompt: state.prompts.analysis_prompt,
}, analysisInput(job.passage), "analysis", "");
passageResult.runs.push(analysisRun);
if (analysisRun.status !== "OK" || !analysisRun.parsed) {
passageResult.status = "지문 분석 실패";
passageResult.error = analysisRun.error;
return passageJobResult(job, jobOrder, passageResult, started);
}
passageResult.analysisTypes = uniqueTypes(analysisRun.parsed.types);
if (!passageResult.analysisTypes.length) {
passageResult.status = "생성 가능한 유형 없음";
return passageJobResult(job, jobOrder, passageResult, started);
}
passageResult.status = `${passageResult.analysisTypes.length}개 유형 생성·검사 실행 중`;
renderOutputs();
const typeResults = await Promise.all(passageResult.analysisTypes.map((type) => processType(job.passage, type, passageResult)));
const order = Object.fromEntries(passageResult.analysisTypes.map((type, index) => [type, index]));
passageResult.results = typeResults.sort((a, b) => (order[a.type] ?? 999) - (order[b.type] ?? 999));
const passed = passageResult.results.filter((item) => item.status === "통과").length;
const review = passageResult.results.filter((item) => item.status === "사람 검토").length;
const failed = passageResult.results.filter((item) => ["생성 실패", "생성 불가"].includes(item.status)).length;
passageResult.status = `완료 · 통과 ${passed} · 사람 검토 ${review} · 생성 실패 ${failed}`;
} catch (error) {
passageResult.status = "오류";
passageResult.error = String(error?.message || error);
}
return passageJobResult(job, jobOrder, passageResult, started);
}
function passageJobResult(job, jobOrder, passageResult, started) {
passageResult.seconds = (performance.now() - started) / 1000;
return {
job_order: jobOrder,
user_name: job.user_name,
passage_index: job.passage_index,
passage: job.passage,
status: passageResult.status,
analysis_types: passageResult.analysisTypes,
results: passageResult.results,
runs: passageResult.runs,
seconds: passageResult.seconds,
error: passageResult.error,
};
}
async function processType(originalText, questionType, passageResult) {
const item = {
type: questionType,
status: "생성 실패",
verification_count: 0,
generation: null,
inspections: [],
runs: [],
};
const reviewSeen = {};
let previousGeneration = null;
let previousInspection = null;
for (let verificationCount = 1; verificationCount <= 3; verificationCount += 1) {
const generationFromWho = previousGeneration && previousInspection ? "verification" : "analysis";
const generationRun = await callAgent({
agent_id: `generation_${DATA.typeSlugs[questionType] || questionType}`,
stage: "문제 생성",
agent_name: `${questionType} 생성 에이전트`,
question_type: questionType,
system_prompt: state.prompts.generation_prompts[questionType],
}, generationInput(originalText, {
from_who: generationFromWho,
previous_generation: previousGeneration,
verification_result: previousInspection,
}), "generation", questionType);
item.runs.push(generationRun);
passageResult.runs.push(generationRun);
if (generationRun.status !== "OK" || !generationRun.parsed) break;
item.generation = generationRun.parsed;
if (item.generation.status === "생성 불가") {
item.status = "생성 불가";
break;
}
const inspectionRun = await callAgent({
agent_id: `inspection_${DATA.typeSlugs[questionType] || questionType}`,
stage: "검사",
agent_name: `${questionType} 검증 에이전트`,
question_type: questionType,
system_prompt: inspectionPromptForType(questionType),
}, inspectionInput(originalText, item.generation), "inspection", questionType);
if (inspectionRun.parsed) {
inspectionRun.parsed.verification_count = verificationCount;
inspectionRun.output_text = renderInspection(inspectionRun.parsed);
inspectionRun.structured_json = JSON.stringify(inspectionRun.parsed, null, 2);
}
item.runs.push(inspectionRun);
passageResult.runs.push(inspectionRun);
if (inspectionRun.status !== "OK" || !inspectionRun.parsed) {
item.status = "사람 검토";
break;
}
item.inspections.push(inspectionRun.parsed);
item.verification_count = item.inspections.length;
if (inspectionRun.parsed.judgment === "PASS") {
item.status = "통과";
break;
}
const signature = reviewSignature(inspectionRun.parsed);
if (signature) reviewSeen[signature] = (reviewSeen[signature] || 0) + 1;
if (verificationCount === 3 || (signature && reviewSeen[signature] >= 2)) {
item.status = "사람 검토";
break;
}
previousGeneration = item.generation;
previousInspection = inspectionRun.parsed;
}
return item;
}
async function callAgent(spec, userInput, stageKey, questionType) {
const started = performance.now();
const config = stageConfig(stageKey);
const row = modelRow(config.model_label);
const {schemaName, schema} = schemaForStage(stageKey, questionType);
const request = {
model: row.api_model,
instructions: spec.system_prompt || "",
input: userInput,
max_output_tokens: config.max_output_tokens,
text: {
format: {
type: "json_schema",
name: schemaName,
schema,
strict: true,
},
},
};
try {
const response = await fetch("https://api.openai.com/v1/responses", {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${state.apiKey}`,
},
body: JSON.stringify(request),
});
const body = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(body?.error?.message || `OpenAI API 오류 ${response.status}`);
const rawText = extractOutputText(body);
const parsed = parseJsonLike(rawText);
const usage = body.usage || {};
const inputTokens = Number(usage.input_tokens || 0);
const outputTokens = Number(usage.output_tokens || 0);
const totalTokens = Number(usage.total_tokens || inputTokens + outputTokens);
const costUsd = computeCost(row, inputTokens, outputTokens);
const costKrw = state.exchangeRate?.rate ? costUsd * state.exchangeRate.rate : null;
const rendered = displayTextFromParsed(stageKey, parsed, rawText);
return agentResult(spec, stageKey, questionType, row, schemaName, request, parsed, rawText, rendered, inputTokens, outputTokens, totalTokens, costUsd, costKrw, started, "");
} catch (error) {
return agentResult(spec, stageKey, questionType, row, schemaName, request, null, "", `ERROR: ${String(error?.message || error)}`, 0, 0, 0, 0, null, started, String(error?.message || error), "ERROR");
}
}
function agentResult(spec, stageKey, questionType, row, schemaName, request, parsed, rawText, outputText, inputTokens, outputTokens, totalTokens, costUsd, costKrw, started, error, status = "OK") {
return {
agent_id: spec.agent_id,
stage: spec.stage,
stage_key: stageKey,
agent_name: spec.agent_name,
question_type: questionType || spec.question_type || "",
model_label: row.label,
api_model: row.api_model,
response_model: schemaName,
status,
output_text: outputText,
raw_text: rawText,
parsed,
structured_json: parsed ? JSON.stringify(parsed, null, 2) : "",
request_json: JSON.stringify(request, null, 2),
input_tokens: inputTokens,
output_tokens: outputTokens,
total_tokens: totalTokens,
seconds: (performance.now() - started) / 1000,
cost_usd: costUsd,
cost_krw: costKrw,
exchange_rate_krw: state.exchangeRate?.rate || null,
error,
};
}
function schemaForStage(stageKey, questionType = "") {
if (stageKey === "analysis") return {schemaName: "PassageTypeAnalysisResponse", schema: analysisSchema()};
if (stageKey === "generation") return {schemaName: "ProblemGenerationResponse", schema: generationSchema(questionType)};
return {schemaName: "ProblemInspectionResponse", schema: inspectionSchema(questionType)};
}
function analysisSchema() {
return {
type: "object",
additionalProperties: false,
properties: {
types: {type: "array", items: {type: "string", enum: DATA.problemTypes}},
},
required: ["types"],
};
}
function generationSchema(questionType = "") {
return {
type: "object",
additionalProperties: false,
properties: {
type: {type: "string", enum: questionType ? [questionType] : DATA.problemTypes},
status: {type: "string", enum: ["생성 완료", "생성 불가"]},
question: {type: "string"},
question_text: {type: "string"},
question_choice: questionChoiceSchema(),
answer: {type: "string"},
reason: {type: "string"},
},
required: ["type", "status", "question", "question_text", "question_choice", "answer", "reason"],
};
}
function questionChoiceSchema() {
return {
type: "object",
additionalProperties: false,
properties: {
"1": {type: "string"},
"2": {type: "string"},
"3": {type: "string"},
"4": {type: "string"},
"5": {type: "string"},
},
required: ["1", "2", "3", "4", "5"],
};
}
function inspectionSchema(questionType = "") {
return {
type: "object",
additionalProperties: false,
properties: {
type: {type: "string", enum: questionType ? [questionType] : DATA.problemTypes},
verification_count: {type: "integer", minimum: 0, maximum: 3},
scores: {
type: "array",
items: {
type: "object",
additionalProperties: false,
properties: {
area: {type: "string", enum: ["정답 유일성", "유형 핵심", "선지·자료", "형식"]},
score: {type: "integer", minimum: 0, maximum: 40},
max_score: {type: "integer", minimum: 1, maximum: 40},
reason: {type: "string"},
},
required: ["area", "score", "max_score", "reason"],
},
},
total_score: {type: "integer", minimum: 0, maximum: 100},
judgment: {type: "string", enum: ["PASS", "FAIL"]},
review_reasons: {type: "array", items: {type: "string"}},
},
required: ["type", "verification_count", "scores", "total_score", "judgment", "review_reasons"],
};
}
function analysisInput(passage) {
return `[지문]\n${String(passage || "").trim()}\n\n위 지문으로 실제 생성 가능한 문제 유형명만 types에 넣어라.`;
}
function generationInput(originalText, options = {}) {
const fromWho = options.from_who === "verification" ? "verification" : "analysis";
return JSON.stringify({
from_who: fromWho,
original_text: String(originalText || "").trim(),
previous_generation: fromWho === "verification" ? (options.previous_generation || null) : null,
verification_result: fromWho === "verification" ? (options.verification_result || null) : null,
}, null, 2);
}
function inspectionInput(originalText, generation) {
return JSON.stringify({original_text: String(originalText || "").trim(), exam_generation: generation}, null, 2);
}
function analysisInputTemplate() {
return "[지문]\n{original_text}\n\n위 지문으로 실제 생성 가능한 문제 유형명만 types에 넣어라.";
}
function generationInputTemplate(questionType) {
return JSON.stringify({
from_who: "analysis | verification",
original_text: "{original_text}",
previous_generation: {
"사용": "from_who가 verification일 때만 이전 ProblemGenerationResponse 전체",
type: questionType,
status: "생성 완료",
question: "{previous_question}",
question_text: "{previous_question_text}",
question_choice: {"1": "{previous_choice_1}", "2": "{previous_choice_2}", "3": "{previous_choice_3}", "4": "{previous_choice_4}", "5": "{previous_choice_5}"},
answer: "{previous_answer}",
reason: "{previous_reason}",
},
verification_result: {
"사용": "from_who가 verification일 때만 직전 ProblemInspectionResponse 전체",
type: questionType,
verification_count: 1,
scores: [],
total_score: 82,
judgment: "FAIL",
review_reasons: ["검사에서 감점된 이유"],
},
}, null, 2);
}
function inspectionInputTemplate() {
return JSON.stringify({
original_text: "{original_text}",
exam_generation: {
type: "{type}",
status: "생성 완료",
question: "{question}",
question_text: "{question_text}",
question_choice: {"1": "{choice_1}", "2": "{choice_2}", "3": "{choice_3}", "4": "{choice_4}", "5": "{choice_5}"},
answer: "{answer}",
reason: "{reason}",
},
}, null, 2);
}
function analysisOutputShape() {
return JSON.stringify({types: ["빈칸", "대의파악"]}, null, 2);
}
function generationOutputShape(type = "빈칸") {
return JSON.stringify({
type,
status: "생성 완료",
question: "다음 글의 빈칸에 들어갈 말로 가장 적절한 것을 고르시오.",
question_text: "문항 본문",
question_choice: {"1": "선지 1", "2": "선지 2", "3": "선지 3", "4": "선지 4", "5": "선지 5"},
answer: "3",
reason: "정답 이유",
}, null, 2);
}
function inspectionOutputShape(type = "빈칸") {
return JSON.stringify({
type,
verification_count: 1,
scores: [
{area: "정답 유일성", score: 40, max_score: 40, reason: "점수 판단 이유"},
{area: "유형 핵심", score: 25, max_score: 25, reason: "점수 판단 이유"},
{area: "선지·자료", score: 20, max_score: 20, reason: "점수 판단 이유"},
{area: "형식", score: 15, max_score: 15, reason: "점수 판단 이유"},
],
total_score: 100,
judgment: "PASS",
review_reasons: [],
}, null, 2);
}
function uniqueTypes(values) {
const selected = [];
for (const value of values || []) {
if (DATA.problemTypes.includes(value) && !selected.includes(value)) selected.push(value);
}
return selected;
}
function reviewSignature(parsed) {
return (parsed.review_reasons || []).map((item) => String(item || "").replace(/\s+/g, " ").trim()).filter(Boolean).sort().join(" | ");
}
function extractOutputText(responseBody) {
if (typeof responseBody.output_text === "string") return responseBody.output_text;
const chunks = [];
for (const item of responseBody.output || []) {
for (const content of item.content || []) {
if (typeof content.text === "string") chunks.push(content.text);
if (typeof content.output_text === "string") chunks.push(content.output_text);
}
}
return chunks.join("\n").trim();
}
function parseJsonLike(text) {
if (!text) return null;
const candidates = [text.trim(), (text.match(/```(?:json)?\s*([\s\S]*?)```/) || [])[1], (text.match(/\{[\s\S]*\}/) || [])[0]].filter(Boolean);
for (const candidate of candidates) {
try {
return JSON.parse(candidate);
} catch (_) {}
}
return null;
}
function displayTextFromParsed(stageKey, parsed, fallback) {
if (!parsed) return fallback || "";
if (stageKey === "analysis") return renderAnalysis(parsed);
if (stageKey === "generation") return renderGenerated(parsed);
if (stageKey === "inspection") return renderInspection(parsed);
return JSON.stringify(parsed, null, 2);
}
function renderAnalysis(parsed) {
const types = uniqueTypes(parsed.types);
return `문제 유형: ${types.length ? types.join(", ") : "없음"}`;
}
function renderGenerated(parsed) {
if (!parsed) return "생성 결과가 없습니다.";
if (parsed.status === "생성 불가") return `### ${parsed.type}\n\n생성 불가`;
const choices = ["1", "2", "3", "4", "5"].map((key) => `${key}. ${parsed.question_choice?.[key] || ""}`).join("\n");
return [`### ${parsed.type}`, parsed.question || "", parsed.question_text || "", choices, `#### 봉인\n정답: ${parsed.answer || "없음"}\n\n이유: ${parsed.reason || "없음"}`].filter(Boolean).join("\n\n");
}
function renderInspection(parsed) {
if (!parsed) return "검사 결과가 없습니다.";
const scores = (parsed.scores || []).map((score) => `- ${score.area}: ${score.score}/${score.max_score} - ${score.reason}`).join("\n") || "- 점수 없음";
const reasons = (parsed.review_reasons || []).map((item) => `- ${item}`).join("\n") || "- 없음";
return [`### ${parsed.type} · 검사 ${parsed.verification_count}/3`, `판정: ${parsed.judgment} · 총점: ${parsed.total_score}/100`, scores, `검사 이유:\n${reasons}`].join("\n\n");
}
function renderOutputs() {
const run = state.lastRun;
const jobs = run?.jobs || [];
const batchResults = run?.batchResults || [];
$("summary").innerHTML = batchSummaryHtml(jobs, batchResults, run?.startedAt || performance.now(), run?.statusMessage || "실행 전입니다.");
$("analysis-output").innerHTML = `${escapeHtml(batchAnalysisText(batchResults))}`;
$("generation-output").innerHTML = `${escapeHtml(batchGenerationText(batchResults))}`;
$("inspection-output").innerHTML = `${escapeHtml(batchInspectionText(batchResults))}`;
$("usage-output").innerHTML = usageTableHtml(allBatchRuns(batchResults));
$("details-output").textContent = JSON.stringify(detailPayload(jobs, batchResults), null, 2);
$("download-panel").classList.toggle("hidden", !canDownload(run));
renderResultTabs();
}
function renderResultTabs() {
document.querySelectorAll(".sub-tab").forEach((button) => button.classList.toggle("active", button.dataset.resultTab === state.resultTab));
const mapping = {
summary: "summary",
analysis: "analysis-output",
generation: "generation-output",
inspection: "inspection-output",
usage: "usage-output",
details: "details-output",
};
Object.entries(mapping).forEach(([tab, id]) => $(id).classList.toggle("active", tab === state.resultTab));
}
function batchSummaryHtml(jobs, batchResults, startedAt, statusMessage) {
const runs = allBatchRuns(batchResults);
const ok = runs.filter((run) => run.status === "OK").length;
const errors = runs.filter((run) => run.status !== "OK").length;
const passed = batchResults.flatMap((item) => item.results || []).filter((item) => item.status === "통과").length;
const review = batchResults.flatMap((item) => item.results || []).filter((item) => item.status === "사람 검토").length;
const failed = batchResults.flatMap((item) => item.results || []).filter((item) => ["생성 실패", "생성 불가"].includes(item.status)).length;
const users = new Set(jobs.map((job) => job.user_name)).size;
const completedPassages = batchResults.filter(passageTerminal).length;
const input = runs.reduce((sum, run) => sum + Number(run.input_tokens || 0), 0);
const output = runs.reduce((sum, run) => sum + Number(run.output_tokens || 0), 0);
const elapsed = (performance.now() - startedAt) / 1000;
return `진행 상태: ${statusBadge(statusMessage)}
요청 규모: 사용자 ${users.toLocaleString()}명 · 지문 ${jobs.length.toLocaleString()}개
완료 지문: ${completedPassages.toLocaleString()}/${jobs.length.toLocaleString()}개
호출 수: ${runs.length.toLocaleString()}회 · 성공 ${ok.toLocaleString()}회 · 오류 ${errors.toLocaleString()}회
문항 결과: 통과 ${passed.toLocaleString()}개 · 사람 검토 ${review.toLocaleString()}개 · 생성 실패 ${failed.toLocaleString()}개
토큰: 입력 ${input.toLocaleString()} / 출력 ${output.toLocaleString()} · 비용: ${costSummaryText(runs)}
시간: ${elapsed.toFixed(1)}초
`;
}
function passageTerminal(item) {
const status = String(item?.status || "");
if (status.startsWith("완료")) return true;
if (["생성 가능한 유형 없음", "지문 분석 실패", "오류"].includes(status)) return true;
const results = item?.results || [];
return !!results.length && results.every((result) => ["통과", "사람 검토", "생성 실패", "생성 불가"].includes(result.status));
}
function statusBadge(statusMessage) {
let text = escapeHtml(statusMessage || "");
for (const keyword of ["실행 중", "처리 중"]) {
if (text.includes(keyword)) text = text.replace(keyword, `${keyword}`);
}
return text;
}
function batchAnalysisText(batchResults) {
if (!batchResults.length) return "문제 유형: 없음";
return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n문제 유형: ${(item.analysis_types || []).join(", ") || "없음"}`).join("\n\n---\n\n");
}
function batchGenerationText(batchResults) {
if (!batchResults.length) return "생성된 문제가 없습니다.";
return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n${(item.results || []).map((result) => `### ${result.type} · ${result.status}\n\n${renderGenerated(result.generation)}`).join("\n\n---\n\n") || "생성된 문제가 없습니다."}`).join("\n\n====================\n\n");
}
function batchInspectionText(batchResults) {
if (!batchResults.length) return "검사 결과가 없습니다.";
return batchResults.map((item) => `## ${item.user_name} · 지문 ${item.passage_index}\n\n${(item.results || []).flatMap((result) => result.inspections || []).map(renderInspection).join("\n\n---\n\n") || "검사 결과가 없습니다."}`).join("\n\n====================\n\n");
}
function usageTableHtml(runs) {
if (!runs.length) return '호출 기록이 없습니다.
';
return `| 단계 | 에이전트 | 유형 | 모델 | 상태 | 입력 | 출력 | 비용(KRW) | 오류 |
${
runs.map((run) => `| ${escapeHtml(run.stage)} | ${escapeHtml(run.agent_name)} | ${escapeHtml(run.question_type || "-")} | ${escapeHtml(run.api_model)} | ${escapeHtml(run.status)} | ${Number(run.input_tokens || 0).toLocaleString()} | ${Number(run.output_tokens || 0).toLocaleString()} | ${run.cost_krw == null ? "" : Number(run.cost_krw).toFixed(2)} | ${escapeHtml(run.error || "")} |
`).join("")
}
`;
}
function allBatchRuns(batchResults) {
return batchResults.flatMap((item) => item.runs || []);
}
function canDownload(run) {
if (!run || run.statusMessage !== "완료") return false;
if (!allBatchRuns(run.batchResults || []).length) return false;
return !(run.batchResults || []).some((item) => item.error || item.status === "오류");
}
function detailPayload(jobs, batchResults) {
const users = {};
const calls = [];
for (const item of batchResults || []) {
const compactResults = (item.results || []).map((result) => ({
type: result.type,
status: result.status,
verification_count: result.verification_count,
generation: result.generation,
inspections: result.inspections,
}));
const itemCalls = (item.runs || []).map((run, index) => callForExport(run, index + 1, item));
calls.push(...itemCalls);
if (!users[item.user_name]) users[item.user_name] = [];
users[item.user_name].push({
passage_index: item.passage_index,
status: item.status,
analysis_types: item.analysis_types,
results: compactResults,
calls: itemCalls,
error: item.error,
});
}
return {
architecture: {
stages: ["지문 분석", "문제 생성", "검사"],
rule: "사용자별 N개 지문을 동시에 처리합니다. 각 지문은 분석 1회 뒤, 분석 types 전체를 자동 병렬 생성·유형별 검증합니다.",
},
requested_jobs: jobs.map((job) => ({user_name: job.user_name, passage_index: job.passage_index})),
users,
calls,
output_shapes: outputShapes(),
};
}
function callForExport(run, index, item = {}) {
const request = parseJsonLike(run.request_json) || null;
const response = parseJsonLike(run.structured_json) || null;
return {
index,
user_name: item.user_name || "",
passage_index: item.passage_index || "",
agent_id: run.agent_id,
stage: run.stage,
agent_name: run.agent_name,
type: run.question_type,
status: run.status,
model_label: run.model_label,
api_model: run.api_model,
response_model: run.response_model,
input_tokens: run.input_tokens,
output_tokens: run.output_tokens,
total_tokens: run.total_tokens,
seconds: Number(run.seconds || 0),
cost_usd: Number(run.cost_usd || 0),
cost_krw: run.cost_krw,
exchange_rate_krw: run.exchange_rate_krw,
request,
response,
raw_response: run.raw_text,
error: run.error,
};
}
function outputShapes() {
return {
PassageTypeAnalysisResponse: JSON.parse(analysisOutputShape()),
ProblemGenerationResponse: JSON.parse(generationOutputShape("빈칸")),
ProblemInspectionResponse: JSON.parse(inspectionOutputShape()),
};
}
async function downloadPromptsSheet() {
saveVisiblePrompt();
const rows = promptSettingsRows(state.prompts);
if (!window.JSZip) {
return downloadBlob("prompt_settings.csv", csvRows(rows), "text/csv;charset=utf-8");
}
const blob = await promptSettingsXlsxBlob(rows);
return downloadBlob("prompt_settings.xlsx", blob, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
async function downloadPromptTemplateSheet() {
const rows = promptSettingsRows(state.defaultPrompts || state.prompts);
if (!window.JSZip) {
return downloadBlob("prompt_upload_template.csv", csvRows(rows), "text/csv;charset=utf-8");
}
const blob = await promptSettingsXlsxBlob(rows);
$("prompt-status").innerHTML = "업로드 양식 생성 완료
System prompt만 수정해서 업로드할 수 있습니다.";
return downloadBlob("prompt_upload_template.xlsx", blob, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
function promptSettingsRows(prompts = state.prompts) {
const source = normalizePrompts(prompts);
const rows = [[
"단계",
"유형",
"에이전트",
"System prompt",
"input 형태",
"output 형태",
"response_model 형태",
]];
rows.push([
"지문 분석",
"",
"지문 분석 AGENT",
source.analysis_prompt || "",
analysisInputTemplate(),
analysisOutputShape(),
JSON.stringify(analysisSchema(), null, 2),
]);
for (const type of DATA.problemTypes) {
rows.push([
"문제 생성",
type,
`${type} 생성 AGENT`,
source.generation_prompts?.[type] || "",
generationInputTemplate(type),
generationOutputShape(type),
JSON.stringify(generationSchema(type), null, 2),
]);
rows.push([
"검증",
type,
`${type} 검증 AGENT`,
source.inspection_prompts?.[type] || "",
inspectionInputTemplate(),
inspectionOutputShape(type),
JSON.stringify(inspectionSchema(type), null, 2),
]);
}
return rows;
}
function promptSettingsXlsxBlob(rows) {
const zip = new JSZip();
zip.file("[Content_Types].xml", '');
zip.file("_rels/.rels", '');
zip.file("xl/workbook.xml", '');
zip.file("xl/_rels/workbook.xml.rels", '');
zip.file("xl/styles.xml", promptSettingsStylesXml());
zip.file("xl/worksheets/sheet1.xml", promptSettingsWorksheetXml(rows));
return zip.generateAsync({type: "blob", mimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
}
function promptSettingsWorksheetXml(rows) {
const sheetRows = rows.map((row, rowIndex) => {
const cells = row.map((value, columnIndex) => {
const columnName = rows[0][columnIndex] || "";
const styleIndex = columnName === "System prompt" ? 0 : 1;
const cellRef = `${xlsxColumnName(columnIndex + 1)}${rowIndex + 1}`;
return `${xlsxText(value)}`;
}).join("");
return `${cells}
`;
}).join("");
return ''
+ ''
+ ''
+ ''
+ `${sheetRows}`;
}
function promptSettingsStylesXml() {
return ''
+ ''
+ ''
+ ''
+ ''
+ ''
+ ''
+ ''
+ '';
}
function xlsxColumnName(index) {
let name = "";
while (index > 0) {
const remainder = (index - 1) % 26;
name = String.fromCharCode(65 + remainder) + name;
index = Math.floor((index - 1) / 26);
}
return name;
}
function xlsxText(value) {
return escapeHtml(String(value ?? "").replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g, ""));
}
async function importPromptsFile() {
saveVisiblePrompt();
const input = $("upload-prompts-file");
const file = input.files?.[0];
if (!file) {
$("prompt-status").innerHTML = promptUploadErrorStatus(["파일을 선택해 주세요."]);
return;
}
try {
const rows = await promptRowsFromUploadFile(file);
const errors = validatePromptUploadRows(rows);
if (errors.length) {
$("prompt-status").innerHTML = promptUploadErrorStatus(errors);
return;
}
applyPromptUploadRows(rows);
renderPromptEditor();
$("prompt-status").innerHTML = promptUploadSuccessStatus(rows);
$("upload-prompts-file-label").classList.add("hidden");
input.value = "";
} catch (error) {
$("prompt-status").innerHTML = promptUploadErrorStatus([error?.message || String(error)]);
}
}
function showPromptUploadPicker() {
const label = $("upload-prompts-file-label");
const input = $("upload-prompts-file");
label.classList.remove("hidden");
input.value = "";
$("prompt-status").innerHTML = "프롬프트 업로드
CSV 또는 XLSX 파일을 선택하면 양식 검증 후 System prompt만 반영합니다.";
input.click();
}
async function promptRowsFromUploadFile(file) {
const name = String(file.name || "").toLowerCase();
if (name.endsWith(".csv")) return parseCsvRows(await file.text());
if (name.endsWith(".xlsx")) return parseXlsxRows(await file.arrayBuffer());
throw new Error("CSV 또는 XLSX 파일만 업로드할 수 있습니다.");
}
function parseCsvRows(text) {
const rows = [];
let row = [];
let cell = "";
let quoted = false;
const source = String(text || "").replace(/^\uFEFF/, "");
for (let index = 0; index < source.length; index += 1) {
const char = source[index];
if (quoted) {
if (char === '"') {
if (source[index + 1] === '"') {
cell += '"';
index += 1;
} else {
quoted = false;
}
} else {
cell += char;
}
continue;
}
if (char === '"') {
quoted = true;
} else if (char === ",") {
row.push(cell);
cell = "";
} else if (char === "\n" || char === "\r") {
row.push(cell);
rows.push(row);
row = [];
cell = "";
if (char === "\r" && source[index + 1] === "\n") index += 1;
} else {
cell += char;
}
}
if (cell || row.length) {
row.push(cell);
rows.push(row);
}
return rows;
}
async function parseXlsxRows(arrayBuffer) {
if (!window.JSZip) throw new Error("XLSX 파일을 읽을 수 없습니다. CSV 파일로 업로드해 주세요.");
const zip = await JSZip.loadAsync(arrayBuffer);
const sheetFile = zip.file("xl/worksheets/sheet1.xml");
if (!sheetFile) throw new Error("첫 번째 워크시트를 찾을 수 없습니다.");
const parser = new DOMParser();
const sharedStrings = [];
const sharedFile = zip.file("xl/sharedStrings.xml");
if (sharedFile) {
const sharedXml = parser.parseFromString(await sharedFile.async("text"), "application/xml");
for (const item of elementsByLocalName(sharedXml, "si")) sharedStrings.push(item.textContent || "");
}
const sheetXml = parser.parseFromString(await sheetFile.async("text"), "application/xml");
const rowMap = new Map();
for (const [rowIndex, rowElement] of elementsByLocalName(sheetXml, "row").entries()) {
const rowNumber = Number(rowElement.getAttribute("r") || rowIndex + 1);
const row = [];
for (const cell of Array.from(rowElement.children).filter((child) => child.localName === "c")) {
const ref = cell.getAttribute("r") || `A${rowNumber}`;
const columnIndex = xlsxColumnIndex(ref);
while (row.length <= columnIndex) row.push("");
const type = cell.getAttribute("t");
if (type === "s") {
const value = firstChildText(cell, "v");
row[columnIndex] = sharedStrings[Number(value)] || "";
} else if (type === "inlineStr") {
const inline = Array.from(cell.children).find((child) => child.localName === "is");
row[columnIndex] = inline?.textContent || "";
} else {
row[columnIndex] = firstChildText(cell, "v");
}
}
rowMap.set(rowNumber, row);
}
const maxRow = Math.max(0, ...rowMap.keys());
return Array.from({length: maxRow}, (_, index) => rowMap.get(index + 1) || []);
}
function elementsByLocalName(root, localName) {
return Array.from(root.getElementsByTagName("*")).filter((element) => element.localName === localName);
}
function firstChildText(element, localName) {
const child = elementsByLocalName(element, localName)[0];
return child?.textContent || "";
}
function xlsxColumnIndex(cellRef) {
const letters = String(cellRef || "A").replace(/[^A-Za-z]/g, "").toUpperCase();
let index = 0;
for (const letter of letters) index = index * 26 + letter.charCodeAt(0) - 64;
return Math.max(index - 1, 0);
}
function validatePromptUploadRows(uploadRows) {
const rows = trimTrailingEmptyRows(uploadRows);
const expectedRows = promptSettingsRows();
const errors = [];
if (!rows.length) return ["1행 - 파일이 비어 있습니다."];
if (!sameRow(rows[0], expectedRows[0])) errors.push("1행 - 헤더가 기준 양식과 다릅니다.");
if (rows.length !== expectedRows.length) errors.push(`전체 행 수 - 기준은 ${expectedRows.length}행인데 업로드 파일은 ${rows.length}행입니다.`);
const lockedColumns = expectedRows[0].filter((column) => column !== "System prompt");
const rowCount = Math.min(rows.length, expectedRows.length);
for (let rowIndex = 1; rowIndex < rowCount; rowIndex += 1) {
const row = rows[rowIndex] || [];
if (row.length !== expectedRows[0].length) {
errors.push(`${rowIndex + 1}행 - 컬럼 수가 기준 양식과 다릅니다.`);
continue;
}
for (const column of lockedColumns) {
const columnIndex = expectedRows[0].indexOf(column);
if (normalizeLockedPromptValue(row[columnIndex]) !== normalizeLockedPromptValue(expectedRows[rowIndex][columnIndex])) {
errors.push(`${rowIndex + 1}행 - ${column}: 기준 양식과 다릅니다.`);
}
}
}
return errors;
}
function trimTrailingEmptyRows(rows) {
const trimmed = [...(rows || [])];
while (trimmed.length && trimmed[trimmed.length - 1].every((cell) => String(cell ?? "") === "")) trimmed.pop();
return trimmed;
}
function sameRow(left, right) {
if (!left || !right || left.length !== right.length) return false;
return left.every((value, index) => String(value ?? "") === String(right[index] ?? ""));
}
function normalizeLockedPromptValue(value) {
return String(value ?? "").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
}
function applyPromptUploadRows(uploadRows) {
const rows = trimTrailingEmptyRows(uploadRows);
const expectedRows = promptSettingsRows();
const systemIndex = expectedRows[0].indexOf("System prompt");
const imported = normalizePrompts(state.prompts);
for (let index = 1; index < rows.length; index += 1) {
const systemPrompt = String(rows[index][systemIndex] ?? "");
const [stage, type] = expectedRows[index];
if (stage === "지문 분석") imported.analysis_prompt = systemPrompt;
if (stage === "문제 생성" && DATA.problemTypes.includes(type)) imported.generation_prompts[type] = systemPrompt;
if (stage === "검증" && DATA.problemTypes.includes(type)) imported.inspection_prompts[type] = systemPrompt;
}
state.prompts = imported;
}
function promptUploadErrorStatus(errors) {
const shown = errors.slice(0, 30);
const more = errors.length - shown.length;
const lines = shown.map((error) => `- ${escapeHtml(error)}`).join("
");
const suffix = more > 0 ? `
- 그 외 ${more.toLocaleString()}개 오류가 더 있습니다.` : "";
return `프롬프트 업로드 실패
반영된 내용이 없습니다.
수정 가능한 컬럼은 System prompt뿐입니다.
${lines}${suffix}`;
}
function promptUploadSuccessStatus(rows) {
return "업로드가 완료 되었습니다.";
}
function costSummaryText(runs) {
const krwValues = runs.map((run) => run.cost_krw).filter((value) => value != null);
if (!runs.length || !krwValues.length) return "약 0원";
if (krwValues.length === runs.length) return `약 ${krwValues.reduce((sum, value) => sum + Number(value || 0), 0).toLocaleString(undefined, {maximumFractionDigits: 0})}원`;
return "원화 환산 불가";
}
function computeCost(row, inputTokens, outputTokens) {
return (inputTokens / 1_000_000) * Number(row.input_usd_1m || 0) + (outputTokens / 1_000_000) * Number(row.output_usd_1m || 0);
}
async function getExchangeRate() {
try {
const response = await fetch(DATA.exchangeRateUrl, {cache: "no-store"});
const data = await response.json();
const rate = Number(data?.rates?.KRW);
if (rate) return {rate, stale: false};
} catch (_) {}
return {rate: null, stale: true};
}
function downloadExport(kind) {
const payload = exportPayload();
if (kind === "json") return downloadBlob("results.json", JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
if (kind === "txt") return downloadBlob("results.txt", exportText(payload), "text/plain;charset=utf-8");
if (kind === "system-csv") return downloadBlob("system_run.csv", systemRunCsv(payload), "text/csv;charset=utf-8");
if (!window.JSZip) return downloadBlob("results.json", JSON.stringify(payload, null, 2), "application/json;charset=utf-8");
const zip = new JSZip();
zip.file("results.txt", exportText(payload));
zip.file("results.json", JSON.stringify(payload, null, 2));
zip.file("system_run.csv", systemRunCsv(payload));
zip.file("usage.csv", usageCsv(payload));
zip.generateAsync({type: "blob"}).then((blob) => downloadBlob("results.zip", blob, "application/zip"));
}
function exportPayload() {
return {
exported_at: new Date().toISOString(),
details: detailPayload(state.lastRun?.jobs || [], state.lastRun?.batchResults || []),
};
}
function exportText(payload) {
const users = payload.details.users || {};
return Object.entries(users).flatMap(([userName, passages]) => passages.map((item) => {
const generation = (item.results || []).map((result) => `### ${result.type} · ${result.status}\n\n${renderGenerated(result.generation)}`).join("\n\n---\n\n") || "생성된 문제가 없습니다.";
const inspection = (item.results || []).flatMap((result) => result.inspections || []).map(renderInspection).join("\n\n---\n\n") || "검사 결과가 없습니다.";
return [`# ${userName} · 지문 ${item.passage_index}`, `문제 유형: ${(item.analysis_types || []).join(", ") || "없음"}`, "## 문제 생성", generation, "## 검사", inspection].join("\n\n");
})).join("\n\n====================\n\n");
}
function systemRunCsv(payload) {
const details = payload.details || {};
const shapes = details.output_shapes || {};
const rows = [[
"순번", "사용자", "지문번호", "단계", "에이전트", "문제유형", "상태", "입력값", "적용프롬프트", "설정모델", "호출모델", "최대출력토큰", "소요초", "비용원", "비용USD", "환율", "입력토큰", "출력토큰", "총토큰", "결과", "raw_output", "response_model", "response_model구성", "오류",
]];
for (const call of details.calls || []) {
rows.push([
call.index,
call.user_name,
call.passage_index,
call.stage,
call.agent_name,
call.type,
call.status,
call.request?.input || "",
call.request?.instructions || "",
call.model_label,
call.api_model || call.request?.model || "",
call.request?.max_output_tokens || "",
call.seconds,
call.cost_krw ?? "",
call.cost_usd ?? "",
call.exchange_rate_krw ?? "",
call.input_tokens,
call.output_tokens,
call.total_tokens,
JSON.stringify(call.response || "", null, 2),
call.raw_response || "",
call.response_model,
JSON.stringify(shapes[call.response_model] || call.request?.text?.format?.schema || "", null, 2),
call.error,
]);
}
return csvRows(rows);
}
function usageCsv(payload) {
const rows = [["user", "passage", "stage", "agent_name", "type", "model", "status", "input_tokens", "output_tokens", "total_tokens", "seconds", "cost_krw", "error"]];
for (const call of payload.details.calls || []) rows.push([call.user_name, call.passage_index, call.stage, call.agent_name, call.type, call.api_model, call.status, call.input_tokens, call.output_tokens, call.total_tokens, call.seconds, call.cost_krw ?? "", call.error]);
return csvRows(rows);
}
function csvRows(rows) {
return rows.map((row) => row.map((cell) => `"${String(cell ?? "").replace(/"/g, '""')}"`).join(",")).join("\n");
}
function downloadBlob(filename, content, type) {
const blob = content instanceof Blob ? content : new Blob(["\ufeff", content], {type});
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
URL.revokeObjectURL(url);
}
function wrapIndex(index, length) {
if (!length) return 0;
return (index + length) % length;
}
function clampInt(value, fallback, min, max) {
const parsed = Number.parseInt(value, 10);
if (Number.isNaN(parsed)) return fallback;
return Math.max(min, Math.min(max, parsed));
}
init();