import { mkdir, readdir, readFile, writeFile } from 'node:fs/promises' import { basename, join, relative } from 'node:path' import { parseArgs } from 'node:util' const OPENAI_API_URL = 'https://api.openai.com/v1' const VECTOR_STORE_IDLE_DAYS = 7 const RESULTS_PER_SEARCH = 10 const FILE_LIST_PAGE_SIZE = 200 const INGESTION_POLL_MS = 3_000 const INGESTION_TIMEOUT_MS = 30 * 60 * 1_000 const REQUEST_ATTEMPTS = 4 const RETRY_BASE_MS = 2_000 const RETRIED_STATUSES = new Set([429, 500, 502, 503, 504]) const { values: options } = parseArgs({ options: { questions: { type: 'string' }, files: { type: 'string' }, out: { type: 'string' }, project: { type: 'string' }, 'knowledge-base': { type: 'string' }, }, }) function requiredOption(name) { const value = options[name] if (value === undefined || value.length === 0) throw new Error(`Pass --${name}.`) return value } function requiredVariable(name) { const value = process.env[name] if (value === undefined || value.length === 0) throw new Error(`Set ${name}.`) return value } const questionsPath = requiredOption('questions') const filesRoot = requiredOption('files') const outRoot = requiredOption('out') const projectId = requiredOption('project') const knowledgeBaseId = requiredOption('knowledge-base') function pause(ms) { return new Promise(resolve => setTimeout(resolve, ms)) } async function withRetries(send) { for (let attempt = 1; ; attempt += 1) { const response = await send() if (response.ok || !RETRIED_STATUSES.has(response.status) || attempt === REQUEST_ATTEMPTS) return response await response.body?.cancel() await pause(RETRY_BASE_MS * 2 ** (attempt - 1)) } } function apiClient(baseUrl, key) { async function call(method, path, body) { const isForm = body instanceof FormData const response = await withRetries(() => fetch(`${baseUrl}${path}`, { method, headers: { accept: 'application/json', authorization: `Bearer ${key}`, ...(body === undefined || isForm ? {} : { 'content-type': 'application/json' }), }, ...(body === undefined ? {} : { body: isForm ? body : JSON.stringify(body) }), }), ) const payload = await response.json().catch(() => ({})) return { ok: response.ok, status: response.status, payload } } return { call } } async function filesUnder(root) { const entries = await readdir(root, { recursive: true, withFileTypes: true }) return entries .filter(entry => entry.isFile() && !entry.name.startsWith('.')) .map(entry => relative(root, join(entry.parentPath, entry.name))) .sort() } async function preparedVectorStore(openAi, paths) { const statePath = join(outRoot, 'openai-vector-store.json') const saved = await readFile(statePath, 'utf8').then(JSON.parse, () => null) if (saved !== null && saved.files.length === paths.length) return saved const store = await openAi.call('POST', '/vector_stores', { name: 'himring-search-comparison', expires_after: { anchor: 'last_active_at', days: VECTOR_STORE_IDLE_DAYS }, }) if (!store.ok) throw new Error(`OpenAI refused the vector store: ${JSON.stringify(store.payload)}`) const files = [] for (const path of paths) { const form = new FormData() form.append('purpose', 'assistants') form.append('file', new Blob([await readFile(join(filesRoot, path))]), basename(path)) const uploaded = await openAi.call('POST', '/files', form) if (!uploaded.ok) { files.push({ path, fileId: null, status: 'upload_refused', error: uploaded.payload.error?.message ?? null }) continue } const attached = await openAi.call('POST', `/vector_stores/${store.payload.id}/files`, { file_id: uploaded.payload.id, }) files.push({ path, fileId: uploaded.payload.id, status: attached.ok ? 'attached' : 'attach_refused', error: attached.ok ? null : (attached.payload.error?.message ?? null), }) } const started = Date.now() for (;;) { const listed = await openAi.call('GET', `/vector_stores/${store.payload.id}/files?limit=100`) if (!listed.ok) throw new Error(`OpenAI refused the file list: ${JSON.stringify(listed.payload)}`) const byId = new Map(listed.payload.data.map(entry => [entry.id, entry])) const pending = files.filter(file => file.status === 'attached' && byId.get(file.fileId)?.status === 'in_progress') if (pending.length === 0) { for (const file of files) { const entry = file.fileId === null ? undefined : byId.get(file.fileId) if (entry === undefined || file.status !== 'attached') continue file.status = entry.status file.error = entry.last_error?.message ?? null file.usageBytes = entry.usage_bytes } break } if (Date.now() - started > INGESTION_TIMEOUT_MS) throw new Error('OpenAI did not finish indexing the files.') await pause(INGESTION_POLL_MS) } const state = { vectorStoreId: store.payload.id, createdAt: new Date().toISOString(), files } await writeFile(statePath, `${JSON.stringify(state, null, 2)}\n`, { mode: 0o600 }) return state } async function openAiResults(openAi, store, question) { const pathOf = new Map(store.files.filter(file => file.fileId !== null).map(file => [file.fileId, file.path])) const searched = await openAi.call('POST', `/vector_stores/${store.vectorStoreId}/search`, { query: question.question, max_num_results: RESULTS_PER_SEARCH, }) if (!searched.ok) throw new Error(`OpenAI refused a search: ${JSON.stringify(searched.payload)}`) return searched.payload.data.map(result => ({ path: pathOf.get(result.file_id) ?? result.filename, text: result.content.map(part => part.text).join('\n'), })) } function knowledgeBasePath() { return `/v1/projects/${encodeURIComponent(projectId)}/knowledge-bases/${encodeURIComponent(knowledgeBaseId)}` } async function himringReadablePaths(himring) { const readable = new Set() for (let offset = 0; ; offset += FILE_LIST_PAGE_SIZE) { const listed = await himring.call( 'GET', `${knowledgeBasePath()}/files?limit=${FILE_LIST_PAGE_SIZE}&offset=${offset}`, ) if (!listed.ok) throw new Error(`Himring refused the file list: ${JSON.stringify(listed.payload)}`) const page = listed.payload.files for (const file of page) { if (file.current_version !== null) readable.add(file.path) } if (page.length === 0 || offset + page.length >= listed.payload.total_count) return readable } } async function himringResults(himring, question) { const searched = await himring.call('POST', `${knowledgeBasePath()}/search`, { question: question.question, limit: RESULTS_PER_SEARCH, }) if (!searched.ok) throw new Error(`Himring refused a search: ${JSON.stringify(searched.payload)}`) return searched.payload.passages.map(passage => ({ path: passage.file_path, text: passage.text })) } await mkdir(join(outRoot, 'sides'), { recursive: true }) const questions = (await readFile(questionsPath, 'utf8')) .split('\n') .filter(line => line.trim().length > 0) .map(line => JSON.parse(line)) const himring = apiClient(requiredVariable('HIMRING_API_URL').replace(/\/+$/, ''), requiredVariable('HIMRING_API_KEY')) const openAi = apiClient(OPENAI_API_URL, requiredVariable('OPENAI_API_KEY')) const paths = await filesUnder(filesRoot) const himringReadable = await himringReadablePaths(himring) const missingFromHimring = paths.filter(path => !himringReadable.has(path)) if (missingFromHimring.length > 0) throw new Error(`Himring lacks ${missingFromHimring.join(', ')}.`) const store = await preparedVectorStore(openAi, paths) const openAiReadable = new Set( store.files.filter(file => file.status === 'completed' && (file.usageBytes ?? 0) > 0).map(file => file.path), ) const openAiSide = [] const himringSide = [] for (const question of questions) { const [openAiFound, himringFound] = await Promise.all([ openAiResults(openAi, store, question), himringResults(himring, question), ]) openAiSide.push({ question: question.question, searchable: openAiReadable.has(question.file), results: openAiFound }) himringSide.push({ question: question.question, searchable: himringReadable.has(question.file), results: himringFound, }) process.stdout.write(`${openAiSide.length}/${questions.length}\n`) } await writeFile(join(outRoot, 'sides', 'openai.json'), JSON.stringify(openAiSide), { mode: 0o600 }) await writeFile(join(outRoot, 'sides', 'himring.json'), JSON.stringify(himringSide), { mode: 0o600 })