Spaces:
Sleeping
Sleeping
File size: 8,145 Bytes
b5e46e4 30cd0c9 98ca5fc 30cd0c9 98ca5fc 30cd0c9 98ca5fc 30cd0c9 b5e46e4 30cd0c9 98ca5fc 30cd0c9 f18b03d 30cd0c9 e2da2f6 30cd0c9 b5e46e4 30cd0c9 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 | import type { Data, Layout } from "plotly.js";
import { getEnv } from "@/env";
const AGENTIC_BASE_URL = getEnv("VITE_AGENTIC_API_BASE_URL");
export class AgenticApiError extends Error {
status: number;
data: unknown;
constructor(message: string, status: number, data?: unknown) {
super(message);
this.name = "AgenticApiError";
this.status = status;
this.data = data;
}
}
export type AgentStreamEvent =
| { type: "sources"; data: unknown[] }
| { type: "status"; data: string }
| { type: "chunk"; data: string }
| { type: "done"; data: { message_id?: string; [key: string]: unknown } }
| { type: "error"; data: string };
export interface AgentChatRequest {
user_id: string;
analysis_id: string;
message: string;
}
export interface Tool {
command: "/help" | "/report" | string;
name: "help" | "report" | string;
type: "skill" | string;
description: string;
}
export interface ObservabilityPlanningStep {
step?: number;
stage?: string;
objective?: string;
}
export interface ObservabilityPlanning {
goal_restated?: string;
assumptions?: string[];
steps?: ObservabilityPlanningStep[];
}
export interface ObservabilityToolCall {
order?: number;
task_id?: string | null;
name: string;
summary?: string;
input?: unknown;
output?: unknown;
status?: string;
error?: string | null;
}
export interface ObservabilityDataUsedSource {
id: string;
name: string;
type: string;
}
export interface ObservabilityDataUsedTable {
id: string;
name: string;
role?: string;
}
export interface ObservabilityDataUsedColumn {
id: string;
name: string;
table?: string;
data_type?: string;
pii?: boolean;
roles?: string[];
}
export interface ObservabilityDataUsedOutputColumn {
name: string;
kind?: string;
from?: string;
formula?: string;
}
export interface ObservabilityDataUsed {
source: ObservabilityDataUsedSource;
tables?: ObservabilityDataUsedTable[];
joins?: unknown[];
columns_read?: ObservabilityDataUsedColumn[];
output_columns?: ObservabilityDataUsedOutputColumn[];
filters?: unknown[];
group_by?: string[];
order_by?: unknown[];
limit?: number | null;
rows_returned?: number;
query?: string;
}
export interface ChartSpec {
schema: string;
chart_type: string;
title?: string | null;
plotly: {
data: Data[];
layout?: Partial<Layout>;
};
}
export interface ChartItem {
chart_id: string;
chart_type: string;
title?: string | null;
spec: ChartSpec;
created_at: string;
}
export interface ChartsResponse {
status: "success" | "empty" | "not_found";
message: string;
count: number;
charts: ChartItem[];
}
export interface Observability {
analysis_id: string;
message_id: string;
intent?: string;
generated_at?: string;
planning: ObservabilityPlanning | null;
thinking: string | null;
tool_calls: ObservabilityToolCall[];
data_used?: ObservabilityDataUsed[];
sources: unknown[];
}
export interface ReportSummary {
report_id: string;
version: number;
generated_at: string;
record_count?: number;
}
export interface ReportFinding {
text: string;
record_ids?: string[];
supporting_data?: unknown;
}
export interface ReportDetail {
report_id: string;
analysis_id: string;
user_id: string;
version: number;
generated_at: string;
problem_statement?: {
objective?: string;
business_questions?: string[];
};
record_ids?: string[];
executive_summary?: string;
findings?: ReportFinding[];
caveats?: ReportFinding[];
open_questions?: ReportFinding[];
data_sources?: unknown[];
method_steps?: unknown[];
rendered_markdown?: string;
}
async function parseAgenticError(res: Response): Promise<AgenticApiError> {
const body = await res.json().catch(() => null);
const message =
(body && typeof body === "object" && "detail" in body && String((body as { detail?: string }).detail)) ||
(body && typeof body === "object" && "message" in body && String((body as { message?: string }).message)) ||
`HTTP ${res.status}`;
return new AgenticApiError(message, res.status, body);
}
async function agenticJson<T>(path: string, options: RequestInit = {}): Promise<T> {
const headers = new Headers(options.headers);
if (!headers.has("Content-Type")) headers.set("Content-Type", "application/json");
const res = await fetch(`${AGENTIC_BASE_URL}${path}`, {
...options,
headers,
});
if (!res.ok) throw await parseAgenticError(res);
return (await res.json()) as T;
}
function parseSseData(eventName: string, data: string): AgentStreamEvent {
if (eventName === "sources") {
try {
const parsed = JSON.parse(data);
return { type: "sources", data: Array.isArray(parsed) ? parsed : [] };
} catch {
return { type: "sources", data: [] };
}
}
if (eventName === "done") {
try {
return { type: "done", data: JSON.parse(data) };
} catch {
return { type: "done", data: {} };
}
}
if (eventName === "error") return { type: "error", data };
if (eventName === "status") return { type: "status", data };
return { type: "chunk", data };
}
async function readEventStream(res: Response, onEvent: (event: AgentStreamEvent) => void): Promise<void> {
if (!res.ok) throw await parseAgenticError(res);
if (!res.body) throw new AgenticApiError("Streaming is not supported by this browser", 0);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = "";
const emitBlock = (rawBlock: string) => {
const lines = rawBlock.split(/\r?\n/);
let eventName = "chunk";
const dataLines: string[] = [];
for (const line of lines) {
if (line.startsWith("event:")) eventName = line.slice(6).trim();
if (line.startsWith("data:")) {
const value = line.startsWith("data: ") ? line.slice(6) : line.slice(5);
dataLines.push(value);
}
}
if (dataLines.length === 0) return;
onEvent(parseSseData(eventName, dataLines.join("\n")));
};
while (true) {
const { value, done } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const parts = buffer.split(/\r?\n\r?\n/);
buffer = parts.pop() ?? "";
parts.forEach(emitBlock);
}
if (buffer.trim()) emitBlock(buffer);
}
export async function streamChat(request: AgentChatRequest, onEvent: (event: AgentStreamEvent) => void): Promise<void> {
const res = await fetch(`${AGENTIC_BASE_URL}/api/v2/chat/stream`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
await readEventStream(res, onEvent);
}
export async function streamHelp(
request: { user_id: string; analysis_id: string },
onEvent: (event: AgentStreamEvent) => void
): Promise<void> {
const res = await fetch(`${AGENTIC_BASE_URL}/api/v1/tools/help`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
await readEventStream(res, onEvent);
}
export const listTools = (): Promise<{ count: number; tools: Tool[] }> => agenticJson("/api/v1/tools/list");
export const getObservability = (analysisId: string, messageId: string): Promise<Observability> =>
agenticJson(
`/api/v1/traceability?analysis_id=${encodeURIComponent(analysisId)}&message_id=${encodeURIComponent(messageId)}`
);
export const getCharts = (messageId: string): Promise<ChartsResponse> =>
agenticJson(`/api/v1/charts?message_id=${encodeURIComponent(messageId)}`);
export const generateReport = (analysisId: string, userId: string): Promise<ReportDetail> =>
agenticJson(
`/api/v1/tools/report?analysis_id=${encodeURIComponent(analysisId)}&user_id=${encodeURIComponent(userId)}`,
{ method: "POST" }
);
export const listReportVersions = (analysisId: string): Promise<ReportSummary[]> =>
agenticJson(`/api/v1/tools/report/${encodeURIComponent(analysisId)}`);
export const getReportVersion = (analysisId: string, version: number): Promise<ReportDetail> =>
agenticJson(`/api/v1/tools/report/${encodeURIComponent(analysisId)}/${encodeURIComponent(String(version))}`);
|