File size: 1,341 Bytes
84983c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
export type AnalysisRow = {
  icon?: string;
  left: string;
  right: string;
  right_style?: string;
};

export type Candidate = {
  commodity_code: number;
  path: string;
  reason?: string;
};

export type SelectedDetails = {
  commodity_code: number;
  path: string;
  segment_code?: number;
  family_code?: number;
  class_code?: number;
  commodity_title?: string;
  commodity_definition?: string;
};

export type ChatResponse = {
  status: "found" | "choose" | "not_found";
  summary: string;
  commodity_code: number | null;
  candidates: Candidate[];
  analysis_rows: AnalysisRow[];
  form_intro: string;
  selected_details?: SelectedDetails;
  error?: string;
};

const base = () =>
  (import.meta.env.VITE_API_BASE as string | undefined)?.replace(/\/$/, "") ?? "";

export async function chatApi(body: {
  message: string;
  selected_commodity_code?: number | null;
}): Promise<ChatResponse> {
  const url = `${base()}/api/chat`;
  const res = await fetch(url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({
      message: body.message ?? "",
      selected_commodity_code: body.selected_commodity_code ?? null,
    }),
  });
  if (!res.ok) {
    const t = await res.text();
    throw new Error(t || `HTTP ${res.status}`);
  }
  return res.json() as Promise<ChatResponse>;
}