> For the complete documentation index, see [llms.txt](https://docs.genesisconductor.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.genesisconductor.io/documentation/guides/ask-ai-streaming-integration.md).

# Ask AI Streaming Integration

Stream real-time answers, reasoning steps, and citations from your published GitBook site using the official `@gitbook/api` TypeScript/JavaScript SDK.

## Overview

GitBook's Ask AI service can be queried programmatically via Server-Sent Events (SSE). The `@gitbook/api` client provides an async iterator interface that yields discrete events as the model retrieves information and generates its answer:

* `answer`: Incremental text chunks of the generated answer.
* `thought`: Internal reasoning steps and retrieval phases (optional/debug).
* `sources`: Pages and spaces cited to ground the generated response.
* `error`: Stream interruption or query errors.

## Installation & Setup

Install the official GitBook SDK:

```bash
npm install @gitbook/api
```

### Authentication

Create an API token in your GitBook account or organization settings. Initialize the client using your token:

```typescript
import { GitBookAPI } from '@gitbook/api';

const client = new GitBookAPI({
  authToken: process.env.GITBOOK_API_TOKEN,
});
```

## Discovered Site Architecture

This site (`site_xTtJm`) contains the following spaces available for Ask AI indexing:

| Route            | Space Title   | Space ID               |
| ---------------- | ------------- | ---------------------- |
| `/home`          | Home          | `t1FXPcSL1cEb8Okm7fMJ` |
| `/documentation` | Documentation | `qiqgCnL6rv0WmkpkT6al` |
| `/api-reference` | API Reference | `uUD4p10JZ1cqeF3TmukQ` |
| `/changelog`     | Changelog     | `NPMmjJ86Ayz3rVF7EYJE` |
| `/help-center`   | Help Center   | `3PxE7oNpnGL4IuAuuOBs` |

## Complete Implementation

Here is a reusable function supporting both full-site queries and space-scoped filtering:

```typescript
import { GitBookAPI } from '@gitbook/api';

const ORGANIZATION_ID = '7MiVIRVE66fpXEn3Mphn';
const SITE_ID = 'site_xTtJm';

const client = new GitBookAPI({
  authToken: process.env.GITBOOK_API_TOKEN,
});

export interface StreamAskOptions {
  /** Optional array of space IDs to restrict retrieval scope */
  spaceIds?: string[];
  /** Callback fired on each text token */
  onToken?: (token: string) => void;
  /** Callback fired for reasoning or thinking traces */
  onThought?: (thought: string) => void;
  /** Callback fired when citations are resolved */
  onSources?: (sources: unknown[]) => void;
}

export async function askInSite(query: string, options: StreamAskOptions = {}) {
  const scope = options.spaceIds && options.spaceIds.length > 0
    ? { mode: 'spaces' as const, spaces: options.spaceIds }
    : { mode: 'default' as const };

  const stream = await client.orgs.streamAskInSite(ORGANIZATION_ID, SITE_ID, {
    question: query,
    scope,
  });

  for await (const event of stream) {
    switch (event.type) {
      case 'answer':
        options.onToken?.(event.text ?? '');
        break;

      case 'thought':
        options.onThought?.(event.thought ?? '');
        break;

      case 'sources':
        options.onSources?.(event.sources ?? []);
        break;

      case 'error':
        throw new Error(`Stream error: ${event.error}`);

      default:
        break;
    }
  }
}
```

## Scoping Examples

### 1. Default (Full-Site Search)

When omitted or set to `default`, Ask AI queries across all published sections on the site:

```typescript
await askInSite('How do I get started?', {
  onToken: (token) => process.stdout.write(token),
  onSources: (sources) => console.log('\nSources:', sources),
});
```

### 2. Targeted Section Search

To isolate answers to specific spaces (such as Documentation and API Reference only):

```typescript
await askInSite('How do I configure webhook endpoints?', {
  spaceIds: [
    'qiqgCnL6rv0WmkpkT6al', // /documentation
    'uUD4p10JZ1cqeF3TmukQ', // /api-reference
  ],
  onToken: (token) => process.stdout.write(token),
  onSources: (sources) => console.log('\nSources:', sources),
});
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.genesisconductor.io/documentation/guides/ask-ai-streaming-integration.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
