forge
Explore
Log in

Don't you dare go Hollow

hezarfen_frontend

Clone
★ 0

0 watching0 forksTypeScript5.5 MiBdcf123aBurak Boduroğlu2 months ago674 commits

rag-output-document.ts264 lines, 9.4 KiBHistoryRawDownload
1import type { RagOutput } from "@/api/client";
2
3const SUMMARY_KEYS = ["summary", "ozet", "özet", "content", "text", "answer"];
4const POINT_KEYS = ["keywords", "key_points", "topics", "questions", "highlights"];
5/** Payload entries the drawer renders on their own; the rest land in `fields`. */
6const RENDERED_KEYS: Record<string, true> = {
7 summary: true,
8 ozet: true,
9 "özet": true,
10 content: true,
11 text: true,
12 answer: true,
13 keywords: true,
14 key_points: true,
15 topics: true,
16 questions: true,
17 highlights: true,
18 files: true,
19 failed: true,
20 course_note: true,
21 passages: true,
22 passages_truncated: true,
23};
24
25function asRecord(value: unknown): Record<string, unknown> | null {
26 return value != null && typeof value === "object" && !Array.isArray(value)
27 ? value as Record<string, unknown>
28 : null;
29}
30
31/** The payload's own prose, whatever key the service used for it. */
32export function payloadText(payload: unknown): string {
33 if (typeof payload === "string") return payload.trim();
34 const record = asRecord(payload);
35 if (!record) return "";
36 for (const key of SUMMARY_KEYS) {
37 const value = record[key];
38 if (typeof value === "string" && value.trim()) return value.trim();
39 }
40 return "";
41}
42
43/** The payload's list-shaped highlights, whatever key the service used. */
44export function payloadPoints(payload: unknown): string[] {
45 const record = asRecord(payload);
46 if (!record) return [];
47 for (const key of POINT_KEYS) {
48 const value = record[key];
49 if (Array.isArray(value)) {
50 const rows = value.filter((item): item is string => typeof item === "string" && !!item.trim());
51 if (rows.length > 0) return rows;
52 }
53 }
54 return [];
55}
56
57/** Attachment id → name, for the ids the service recorded in `payload.files`. */
58export function payloadFileNames(payload: unknown): Map<string, string> {
59 const names = new Map<string, string>();
60 const files = asRecord(payload)?.files;
61 if (!Array.isArray(files)) return names;
62 for (const entry of files) {
63 const file = asRecord(entry);
64 const name = typeof file?.name === "string" && file.name.trim() ? file.name.trim() : null;
65 if (!name) continue;
66 for (const idKey of ["id", "doc_id"]) {
67 const id = file?.[idKey];
68 if (typeof id === "string" && id && !names.has(id)) names.set(id, name);
69 }
70 }
71 return names;
72}
73
74export type RagOutputDocument = {
75 /** The produced prose — the summary the service wrote. */
76 summary: string;
77 points: string[];
78 /** Attachment names in the order the output listed them; never raw ids. */
79 sourceNames: string[];
80 /** Stored attachment ids whose name the payload does not carry. */
81 unnamedSources: number;
82 failed: string[];
83 /** The indexed chunks the service handed back, in the order it wrote them. */
84 passages: RagOutputPassage[];
85 /** The service dropped passages above its response budget. */
86 passagesTruncated: boolean;
87 /** The payload's own `chunks` — the total it indexed — when it recorded one. */
88 chunksTotal: number | null;
89 /** Payload entries with no dedicated rendering, in payload order. */
90 fields: Array<{ key: string; value: unknown }>;
91 raw: unknown;
92};
93
94/** One indexed chunk as the service returned it — the extraction, readable. */
95export type RagOutputPassage = {
96 /** The attachment the passage came from, by name; null when unresolvable. */
97 sourceName: string | null;
98 /** The passage came from the note's own text, not from an attachment. */
99 fromNote: boolean;
100 /** The chunk's own text, verbatim. */
101 text: string;
102 pageStart: number | null;
103 pageEnd: number | null;
104};
105
106/** The note key the answer stamps its own body chunks with — the payload's own
107 * `course_note` first, the stored row's link as the fallback. */
108function payloadNoteKey(record: Record<string, unknown> | null, output: RagOutput): string {
109 if (typeof record?.course_note === "string" && record.course_note) return record.course_note;
110 return typeof output.course_note === "string" ? output.course_note : "";
111}
112
113/** The passages the service recorded, dropping entries with no readable text. */
114function payloadPassages(
115 record: Record<string, unknown> | null,
116 names: Map<string, string>,
117 noteId: string,
118): RagOutputPassage[] {
119 if (!Array.isArray(record?.passages)) return [];
120 const pages = (value: unknown) => (typeof value === "number" && Number.isInteger(value) ? value : null);
121 const passages: RagOutputPassage[] = [];
122 for (const entry of record.passages) {
123 const passage = asRecord(entry);
124 if (typeof passage?.text !== "string" || !passage.text.trim()) continue;
125 const docId = typeof passage.doc_id === "string" ? passage.doc_id : "";
126 passages.push({
127 sourceName: (docId ? names.get(docId) : undefined) ?? null,
128 // The service stamps the note's own chunks with the note key, not a file id.
129 fromNote: docId !== "" && docId === noteId,
130 text: passage.text,
131 pageStart: pages(passage.page_start),
132 pageEnd: pages(passage.page_end),
133 });
134 }
135 return passages;
136}
137
138/**
139 * Read one stored AI output into everything the drawer shows. The payload is
140 * the service's own object served unread, so every read here is defensive: a
141 * shape the service did not send degrades to an empty value, never a crash.
142 */
143export function readRagOutputDocument(output: RagOutput): RagOutputDocument {
144 const raw = output.payload;
145 const record = asRecord(raw);
146 const names = payloadFileNames(raw);
147 const storedSources = Array.isArray(output.sources) ? output.sources : [];
148
149 const sourceNames: string[] = [];
150 let unnamedSources = 0;
151 if (storedSources.length > 0) {
152 for (const id of storedSources) {
153 const name = names.get(id);
154 if (name) {
155 if (!sourceNames.includes(name)) sourceNames.push(name);
156 } else {
157 unnamedSources += 1;
158 }
159 }
160 } else {
161 // No stored id list — fall back to the names the payload itself recorded.
162 for (const name of new Set(names.values())) sourceNames.push(name);
163 }
164
165 const failed = Array.isArray(record?.failed)
166 ? record.failed.filter((item): item is string => typeof item === "string" && !!item.trim()).map((item) => item.trim())
167 : [];
168
169 return {
170 summary: payloadText(raw),
171 points: payloadPoints(raw),
172 sourceNames,
173 unnamedSources,
174 failed,
175 passages: payloadPassages(record, names, payloadNoteKey(record, output)),
176 passagesTruncated: record?.passages_truncated === true,
177 chunksTotal: typeof record?.chunks === "number" && Number.isFinite(record.chunks) ? record.chunks : null,
178 fields: record
179 ? Object.entries(record)
180 .filter(([key]) => !RENDERED_KEYS[key])
181 .map(([key, value]) => ({ key, value }))
182 : [],
183 raw,
184 };
185}
186
187export type RagOutputMarkdownLabels = {
188 date: string;
189 note: string;
190 sources: string;
191 failed: string;
192 otherFields: string;
193 /** Heading of the extracted-text section. */
194 passages: string;
195 /** One passage's heading: source name and page range, never a raw id. */
196 passageHeader: (passage: RagOutputPassage) => string;
197 /** Honest note when the service dropped passages; "" when it did not. */
198 passagesTruncated: string;
199};
200
201/**
202 * The downloadable document: title, date, note, sources, body — built from the
203 * same view the drawer renders, in plain Markdown a teacher can open anywhere.
204 */
205export function buildRagOutputMarkdown(input: {
206 title: string;
207 date: string;
208 noteTitle?: string;
209 document: RagOutputDocument;
210 labels: RagOutputMarkdownLabels;
211}): string {
212 const { document: doc, labels } = input;
213 const lines: string[] = [`# ${input.title}`, ""];
214 lines.push(`- **${labels.date}:** ${input.date}`);
215 if (input.noteTitle?.trim()) lines.push(`- **${labels.note}:** ${input.noteTitle.trim()}`);
216 if (doc.sourceNames.length > 0 || doc.unnamedSources > 0) {
217 const named = [...doc.sourceNames];
218 if (doc.unnamedSources > 0) named.push(`(${doc.unnamedSources})`);
219 lines.push(`- **${labels.sources}:** ${named.join(", ")}`);
220 }
221 lines.push("");
222 if (doc.summary) {
223 lines.push(doc.summary, "");
224 }
225 if (doc.points.length > 0) {
226 for (const point of doc.points) lines.push(`- ${point}`);
227 lines.push("");
228 }
229 if (doc.failed.length > 0) {
230 lines.push(`## ${labels.failed}`, "");
231 for (const name of doc.failed) lines.push(`- ${name}`);
232 lines.push("");
233 }
234 if (doc.passages.length > 0) {
235 lines.push(`## ${labels.passages}`, "");
236 for (const passage of doc.passages) {
237 lines.push(`**${labels.passageHeader(passage)}**`, "", passage.text, "");
238 }
239 if (doc.passagesTruncated && labels.passagesTruncated) lines.push(labels.passagesTruncated, "");
240 }
241 if (doc.fields.length > 0) {
242 lines.push(`## ${labels.otherFields}`, "");
243 for (const field of doc.fields) lines.push(`- **${field.key}:** ${fieldValueText(field.value)}`);
244 lines.push("");
245 }
246 return lines.join("\n");
247}
248
249/**
250 * One value → one line of text. Exported so the drawer's field list and the
251 * Markdown export render unknown payload values identically.
252 */
253export function fieldValueText(value: unknown): string {
254 if (typeof value === "string") return value;
255 if (typeof value === "number" || typeof value === "boolean") return String(value);
256 return JSON.stringify(value) ?? String(value);
257}
258
259/** Deterministic download name: `yz-cikti-YYYYMMDD-HHmm.md`. */
260export function ragOutputFileName(generatedAt: number): string {
261 const d = new Date(generatedAt);
262 const pad = (n: number) => String(n).padStart(2, "0");
263 return `yz-cikti-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}.md`;
264}