ostra / frontend /src /api /client.ts
sumandas's picture
Bypass multipart 1024KB limit on /api/projects/index-precomputed via raw binary framing
b1bc2dc verified
Raw History Blame Contribute Delete
21.6 kB
import type {
AtlasBinaryData,
BaselineCheckResponse,
BaselineContract,
BootstrapProbesResponse,
CalibrationExportSummary,
ChunkingExportSummary,
ChunkStrategyConfig,
CorpusHygieneRequest,
CorpusHygieneResponse,
CorpusQuickFindResponse,
CuratedModel,
CuratedReranker,
DocumentDetail,
ExportResponse,
FacetQueryRequest,
FacetQueryResponse,
FixFinderResponse,
FixStackExportSummary,
FixStackRequest,
FixStackResponse,
ForensicDiffResponse,
FunnelExportSummary,
HardwareInfo,
HFDatasetSearchResponse,
HFInspectResponse,
HFModelSearchResponse,
HygieneExportSummary,
IndexPrecomputedMetadata,
IndexRunRequest,
LabelPoolResponse,
LassoResponse,
PrepareSliceRequest,
PrepareSliceResponse,
QueryAblationResponse,
RegressionGatePolicy,
RerankExportSummary,
RootCauseCallout,
RoutingExportSummary,
RunCompareRequest,
RunCompareResponse,
RunManifest,
SampleQuestionItem,
SearchRequest,
SearchResponse,
StarterPreset,
StressTestResponse,
SuiteAutoTuneResponse,
SuiteCalibrateResponse,
SuiteChunkSimResponse,
SuiteEvaluateResponse,
SuiteFunnelResponse,
SuiteMetrics,
SuiteRerankRequest,
SuiteRerankResponse,
SuiteRoutingResponse,
SuiteTriageResponse,
SuiteVocabScanResponse,
SuiteVocabVerifyResponse,
TokenSaliencyResponse,
TriageExportSummary,
VocabExportSummary,
VocabRule,
WhatIfDocResponse,
} from "../types/ostra";
const API_BASE = "";
async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${url}`, {
...init,
headers: {
"Content-Type": "application/json",
...(init?.headers ?? {}),
},
});
if (!res.ok) {
let msg = `HTTP ${res.status}`;
const text = await res.text(); // a body can only be read once
try {
const err = JSON.parse(text);
msg = typeof err.detail === "string" ? err.detail : JSON.stringify(err.detail ?? err);
} catch {
if (text) msg = text;
}
throw new Error(msg);
}
return res.json() as Promise<T>;
}
export async function fetchHardwareBootstrap(): Promise<{
hardware: HardwareInfo;
models: CuratedModel[];
rerankers: CuratedReranker[];
presets: StarterPreset[];
}> {
return requestJson("/api/hardware");
}
export async function searchHFDatasets(
query: string,
limit = 12
): Promise<HFDatasetSearchResponse> {
const params = new URLSearchParams({
q: query.trim(),
limit: String(limit),
});
return requestJson(`/api/hf/datasets/search?${params.toString()}`);
}
export async function searchHFModels(
query: string,
task: "embedding" | "reranker",
limit = 15
): Promise<HFModelSearchResponse> {
const params = new URLSearchParams({
q: query.trim(),
task,
limit: String(limit),
});
return requestJson(`/api/hf/models/search?${params.toString()}`);
}
export async function inspectHFDataset(payload: {
dataset_id: string;
config?: string | null;
split?: string | null;
}): Promise<HFInspectResponse> {
return requestJson("/api/hf/inspect", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function listProjects(): Promise<RunManifest[]> {
return requestJson("/api/projects");
}
export async function deleteProject(runId: string): Promise<void> {
await requestJson(`/api/projects/${encodeURIComponent(runId)}`, {
method: "DELETE",
});
}
export async function fetchAtlasBinary(runId: string): Promise<AtlasBinaryData> {
const res = await fetch(
`${API_BASE}/api/projects/${encodeURIComponent(runId)}/atlas-binary`
);
if (!res.ok) {
throw new Error(`Failed to fetch atlas binary (${res.status})`);
}
const stride = Number(res.headers.get("X-Ostra-Stride-Floats") || "8");
const buf = await res.arrayBuffer();
const raw = new Float32Array(buf);
return {
count: Math.floor(raw.length / stride),
stride,
raw,
};
}
export async function fetchDocDetail(
runId: string,
docId: number
): Promise<DocumentDetail> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/docs/${docId}`);
}
export async function inspectLasso(
runId: string,
polygon: [number, number][]
): Promise<LassoResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/lasso`, {
method: "POST",
body: JSON.stringify({ polygon }),
});
}
export async function queryFacetsApi(
runId: string,
req: FacetQueryRequest
): Promise<FacetQueryResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/facets`, {
method: "POST",
body: JSON.stringify(req),
});
}
export interface IndexProgressEvent {
stage: string;
message: string;
percent: number;
done?: number;
total?: number;
docs_per_sec?: number;
truncated_count?: number;
device?: string;
backend?: string;
}
export async function streamIndexRun(
req: IndexRunRequest,
onProgress: (ev: IndexProgressEvent) => void
): Promise<RunManifest> {
const res = await fetch(`${API_BASE}/api/projects/index`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(req),
});
if (!res.ok || !res.body) {
throw new Error(`Indexing request failed (${res.status})`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let finalManifest: RunManifest | null = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const chunks = buffer.split("\n\n");
buffer = chunks.pop() || "";
for (const chunk of chunks) {
const lines = chunk.split("\n");
let eventType = "message";
let dataStr = "";
for (const line of lines) {
if (line.startsWith("event:")) {
eventType = line.slice(6).trim();
} else if (line.startsWith("data:")) {
dataStr += line.slice(5).trim();
}
}
if (!dataStr) continue;
const parsed = JSON.parse(dataStr);
if (eventType === "progress") {
onProgress(parsed as IndexProgressEvent);
} else if (eventType === "complete") {
finalManifest = parsed.manifest as RunManifest;
} else if (eventType === "error") {
throw new Error(parsed.message || "Indexing error");
}
}
}
if (!finalManifest) {
throw new Error("Indexing stream ended without completion event.");
}
return finalManifest;
}
export async function prepareHFSlice(
payload: PrepareSliceRequest
): Promise<PrepareSliceResponse> {
return requestJson("/api/projects/prepare-slice", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function streamIndexPrecomputedRun(
meta: IndexPrecomputedMetadata,
embeddings: Float32Array,
onProgress: (ev: IndexProgressEvent) => void
): Promise<RunManifest> {
// Pack as a single raw binary stream: [uint32_le metaLen][utf8 metaJSON][float32 embeddings].
// Completely bypasses multipart form parsers and Starlette's 1024KB part-size limits.
const metaBytes = new TextEncoder().encode(JSON.stringify(meta));
const embCopy = new Uint8Array(
embeddings.buffer,
embeddings.byteOffset,
embeddings.byteLength
).slice();
const header = new ArrayBuffer(4);
new DataView(header).setUint32(0, metaBytes.byteLength, true);
const payload = new Blob([header, metaBytes, embCopy], {
type: "application/octet-stream",
});
const res = await fetch(`${API_BASE}/api/projects/index-precomputed`, {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: payload,
});
if (!res.ok || !res.body) {
const text = await res.text();
throw new Error(text || `Precomputed indexing failed (${res.status})`);
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
let finalManifest: RunManifest | null = null;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const chunks = buffer.split("\n\n");
buffer = chunks.pop() || "";
for (const chunk of chunks) {
const lines = chunk.split("\n");
let eventType = "message";
let dataStr = "";
for (const line of lines) {
if (line.startsWith("event:")) {
eventType = line.slice(6).trim();
} else if (line.startsWith("data:")) {
dataStr += line.slice(5).trim();
}
}
if (!dataStr) continue;
const parsed = JSON.parse(dataStr);
if (eventType === "progress") {
onProgress(parsed as IndexProgressEvent);
} else if (eventType === "complete") {
finalManifest = parsed.manifest as RunManifest;
} else if (eventType === "error") {
throw new Error(parsed.message || "Indexing finalization error");
}
}
}
if (!finalManifest) {
throw new Error("Finalization stream ended without completion event.");
}
return finalManifest;
}
export async function runHybridSearchApi(
runId: string,
req: SearchRequest,
signal?: AbortSignal
): Promise<SearchResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/search`, {
method: "POST",
body: JSON.stringify(req),
signal,
});
}
export async function fetchForensicDiff(
runId: string,
search: SearchRequest,
docAId: number,
docBId: number
): Promise<ForensicDiffResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/forensic-diff`, {
method: "POST",
body: JSON.stringify({
search,
doc_a_id: docAId,
doc_b_id: docBId,
}),
});
}
export async function fetchTokenSaliency(
runId: string,
payload: {
query: string;
doc_id: number;
query_prefix_override?: string | null;
abtt_d?: number;
mean_center?: boolean;
}
): Promise<TokenSaliencyResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/token-saliency`,
{
method: "POST",
body: JSON.stringify(payload),
}
);
}
export async function runStressTest(
runId: string,
search: SearchRequest
): Promise<StressTestResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/stress-test`, {
method: "POST",
body: JSON.stringify({ search }),
});
}
export async function fetchSuite(runId: string): Promise<SampleQuestionItem[]> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/suite`);
}
export async function saveSuiteApi(
runId: string,
items: SampleQuestionItem[]
): Promise<SampleQuestionItem[]> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/suite`, {
method: "PUT",
body: JSON.stringify(items),
});
}
export async function bootstrapSuiteProbesApi(
runId: string,
count: number = 12,
existingQueries: string[] = []
): Promise<BootstrapProbesResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/bootstrap-probes`,
{
method: "POST",
body: JSON.stringify({
count,
existing_queries: existingQueries,
}),
}
);
}
export async function fetchLabelPoolApi(
runId: string,
params: {
query: string;
search: SearchRequest;
draft_source_doc_id?: number | null;
existing_expected_doc_ids?: number[];
max_candidates?: number;
}
): Promise<LabelPoolResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/label-pool`,
{
method: "POST",
body: JSON.stringify({
query: params.query,
search: params.search,
draft_source_doc_id: params.draft_source_doc_id ?? null,
existing_expected_doc_ids: params.existing_expected_doc_ids ?? [],
max_candidates: params.max_candidates ?? 8,
}),
}
);
}
export async function quickFindCorpusDocsApi(
runId: string,
params: {
query: string;
limit?: number;
exclude_doc_ids?: number[];
}
): Promise<CorpusQuickFindResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/corpus-find`,
{
method: "POST",
body: JSON.stringify({
query: params.query,
limit: params.limit ?? 6,
exclude_doc_ids: params.exclude_doc_ids ?? [],
}),
}
);
}
export async function evaluateSuiteApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest,
baselineSearch: SearchRequest | null
): Promise<SuiteEvaluateResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/evaluate`,
{
method: "POST",
body: JSON.stringify({
questions,
search,
baseline_search: baselineSearch,
}),
}
);
}
export async function triageSuiteApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest
): Promise<SuiteTriageResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/triage`,
{
method: "POST",
body: JSON.stringify({ questions, search }),
}
);
}
export async function analyzeSuiteFunnelApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest,
rerankK: number | null = null
): Promise<SuiteFunnelResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/funnel`,
{
method: "POST",
body: JSON.stringify({
questions,
search,
...(rerankK !== null ? { rerank_k: rerankK } : {}),
}),
}
);
}
export async function analyzeSuiteRoutingApi(
runId: string,
items: SampleQuestionItem[],
baseSearch: SearchRequest
): Promise<SuiteRoutingResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/routing-lab`,
{
method: "POST",
body: JSON.stringify({
items,
base_search: baseSearch,
}),
}
);
}
export async function simulateSuiteChunkingApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest,
customStrategy: ChunkStrategyConfig | null = null
): Promise<SuiteChunkSimResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/chunk-sim`,
{
method: "POST",
body: JSON.stringify({
questions,
search,
...(customStrategy !== null ? { custom_strategy: customStrategy } : {}),
}),
}
);
}
export async function getVocabRulesApi(runId: string): Promise<VocabRule[]> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/vocab-rules`);
}
export async function saveVocabRulesApi(
runId: string,
rules: VocabRule[]
): Promise<VocabRule[]> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/vocab-rules`, {
method: "PUT",
body: JSON.stringify(rules),
});
}
export async function scanSuiteVocabApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest,
rules: VocabRule[] = []
): Promise<SuiteVocabScanResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/vocab-scan`,
{
method: "POST",
body: JSON.stringify({ questions, search, rules }),
}
);
}
export async function verifySuiteVocabApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest,
rules: VocabRule[]
): Promise<SuiteVocabVerifyResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/vocab-verify`,
{
method: "POST",
body: JSON.stringify({ questions, search, rules }),
}
);
}
export async function calibrateSuiteApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest
): Promise<SuiteCalibrateResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/calibrate`,
{
method: "POST",
body: JSON.stringify({ questions, search }),
}
);
}
export async function compareRunsApi(
payload: RunCompareRequest
): Promise<RunCompareResponse> {
return requestJson("/api/projects/compare-runs", {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function analyzeCorpusHygieneApi(
runId: string,
payload: CorpusHygieneRequest
): Promise<CorpusHygieneResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/corpus-hygiene`,
{
method: "POST",
body: JSON.stringify(payload),
}
);
}
export async function compileFixStackApi(
runId: string,
payload: FixStackRequest
): Promise<FixStackResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/suite/fix-stack`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function analyzeSuiteRerankApi(
runId: string,
payload: SuiteRerankRequest
): Promise<SuiteRerankResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/suite/rerank-lab`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function exportRecipeApi(
runId: string,
search: SearchRequest,
suiteMetrics: SuiteMetrics | null,
callouts: RootCauseCallout[],
triageSummary: TriageExportSummary | null = null,
calibrationSummary: CalibrationExportSummary | null = null,
funnelSummary: FunnelExportSummary | null = null,
chunkingSummary: ChunkingExportSummary | null = null,
vocabSummary: VocabExportSummary | null = null,
routingSummary: RoutingExportSummary | null = null,
hygieneSummary: HygieneExportSummary | null = null,
fixStackSummary: FixStackExportSummary | null = null,
rerankSummary: RerankExportSummary | null = null
): Promise<ExportResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/export`, {
method: "POST",
body: JSON.stringify({
search,
suite_metrics: suiteMetrics,
callouts,
triage_summary: triageSummary,
calibration_summary: calibrationSummary,
funnel_summary: funnelSummary,
chunking_summary: chunkingSummary,
vocab_summary: vocabSummary,
routing_summary: routingSummary,
hygiene_summary: hygieneSummary,
fix_stack_summary: fixStackSummary,
rerank_summary: rerankSummary,
}),
});
}
export async function findCounterfactualFixesApi(
runId: string,
search: SearchRequest,
targetDocId: number,
suiteQuestions: SampleQuestionItem[] = []
): Promise<FixFinderResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/find-fixes`, {
method: "POST",
body: JSON.stringify({
search,
target_doc_id: targetDocId,
suite_questions: suiteQuestions,
}),
});
}
export async function fetchQueryAblationApi(
runId: string,
search: SearchRequest,
docId: number
): Promise<QueryAblationResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/query-ablation`,
{
method: "POST",
body: JSON.stringify({ search, doc_id: docId }),
}
);
}
export async function runWhatIfDocApi(
runId: string,
payload: {
search: SearchRequest;
doc_id: number;
edited_fields?: Record<string, string> | null;
edited_text?: string | null;
simulate_chunking?: boolean;
chunk_words?: number;
chunk_overlap?: number;
}
): Promise<WhatIfDocResponse> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/what-if-doc`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function autoTuneSuiteApi(
runId: string,
questions: SampleQuestionItem[],
search: SearchRequest
): Promise<SuiteAutoTuneResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/suite/auto-tune`,
{
method: "POST",
body: JSON.stringify({ questions, search }),
}
);
}
export type ClusterGranularity = "coarse" | "balanced" | "fine" | "pinpoint";
export async function reclusterRunApi(
runId: string,
payload: {
granularity: ClusterGranularity;
focus_cluster_id?: number | null;
sub_clusters?: number;
}
): Promise<RunManifest> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/recluster`, {
method: "POST",
body: JSON.stringify(payload),
});
}
export async function getBaselineApi(
runId: string
): Promise<BaselineContract | null> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/baseline`);
}
export async function pinBaselineApi(
runId: string,
payload: {
label?: string;
questions?: SampleQuestionItem[] | null;
search: SearchRequest;
policy?: RegressionGatePolicy | null;
}
): Promise<BaselineContract> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/baseline/pin`,
{
method: "POST",
body: JSON.stringify(payload),
}
);
}
export async function updateBaselinePolicyApi(
runId: string,
policy: RegressionGatePolicy
): Promise<BaselineContract> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/baseline/policy`,
{
method: "PUT",
body: JSON.stringify({ policy }),
}
);
}
export async function deleteBaselineApi(
runId: string
): Promise<{ ok: boolean }> {
return requestJson(`/api/projects/${encodeURIComponent(runId)}/baseline`, {
method: "DELETE",
});
}
export async function checkBaselineApi(
runId: string,
payload: {
search: SearchRequest;
contract?: BaselineContract | null;
policy_override?: RegressionGatePolicy | null;
current_suite_hash?: string | null;
}
): Promise<BaselineCheckResponse> {
return requestJson(
`/api/projects/${encodeURIComponent(runId)}/baseline/check`,
{
method: "POST",
body: JSON.stringify(payload),
}
);
}