0

Ask a question in a site

by
Published Oct 17, 2025

The response is streamed.

Script gitbook Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Gitbook = {
3
  token: string;
4
};
5
/**
6
 * Ask a question in a site
7
 * The response is streamed.
8
 */
9
export async function main(
10
  auth: Gitbook,
11
  organizationId: string,
12
  siteId: string,
13
  format: "document" | "markdown" | undefined,
14
  body: {
15
    question: string;
16
    context?: { siteSpaceId?: string };
17
    scope:
18
      | { mode: "default"; includedSiteSpaces?: string[] }
19
      | { mode: "specific"; siteSpaceIds: string[] }
20
      | { mode: "all" };
21
  },
22
) {
23
  const url = new URL(`https://api.gitbook.com/v1/orgs/${organizationId}/sites/${siteId}/ask`);
24
  for (const [k, v] of [["format", format]]) {
25
    if (v !== undefined && v !== "" && k !== undefined) {
26
      url.searchParams.append(k, v);
27
    }
28
  }
29
  const response = await fetch(url, {
30
    method: "POST",
31
    headers: {
32
      "Content-Type": "application/json",
33
      Authorization: "Bearer " + auth.token,
34
    },
35
    body: JSON.stringify(body),
36
  });
37
  if (!response.ok) {
38
    const text = await response.text();
39
    throw new Error(`${response.status} ${text}`);
40
  }
41
  return await response.text();
42
}
43