# AI Assistant

## Content

The SpreadJS AI add-on provides a framework that enhances AI interactions by supplying contextual spreadsheet data and parsing capabilities. This enables AI models to generate more accurate and spreadsheet-specific responses.

## Installation and Setup

### Adding the AI Add-on

To enable AI functionality in SpreadJS, you must include the AI add-on script in your project.

#### For Header Reference Implementation:

```javascript
<script src="gc.spread.sheets.ai.x.x.x.min.js"></script>
```

#### For Module Implementation

```auto
import '@mescius/spread-sheets-ai-addon';
```

### Contextual Intelligence

SpreadJS intelligently extracts and organizes worksheet data to provide AI models with relevant context, resulting in more precise outputs.
​**​Example Scenario​**​:

* *Without context*: AI guesses data ranges (`=SUM(A1:A10)`)
* *With context*: AI references named ranges (`=SUM(table1[sales])`

## AI Model Integration Methods

SpreadJS provides flexible approaches to connect with AI models. Below are the detailed implementation methods:

### 1\. Secure Backend Proxy

If you do not accept exposing the API key, you can choose to send the request to the server and return the response data.
*Most secure approach - keeps API keys server-side*

#### Frontend Implementation:

```auto
const serverCallback = async (requestBody) => {
    requestBody.model = 'your model name';

    let response = await fetch('/api/queryAI', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(requestBody)
    });
    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response;
}
workbook.injectAI(serverCallback);
```

#### Backend Implementation (Node.js):

```auto
import express from "express";
import { OpenAI } from "openai";
import dotenv from "dotenv";
dotenv.config();
const app = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.static("public"));
const openai = new OpenAI({
    apiKey: process.env.AI_API_KEY,
    baseURL: process.env.AI_SERVER_URL,
});
app.post("/api/queryAI", async (req, res) => {
    try {
        const response = await openai.chat.completions.create(req.body);
        if (req.body.stream) {
            await handleStreamResponse(response, res);
        } else {
            handleNonStreamResponse(response, res);
        }
    } catch (error) {
        handleError(error, res, req.body.stream);
    }
});
async function handleStreamResponse(response, res) {
    res.setHeader("Content-Type", "text/event-stream");
    res.setHeader("Cache-Control", "no-cache");
    res.setHeader("Connection", "keep-alive");
    try {
        for await (const chunk of response) {
            res.write(`data: ${JSON.stringify(chunk)}\n\n`);
        }
        res.write("data: [DONE]\n\n");
        res.end();
    } catch (error) {
        res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`);
        res.end();
    }
}
function handleNonStreamResponse(response, res) {
    console.log("Handling non-stream response...");
    res.setHeader("Content-Type", "application/json");
    res.setHeader("Cache-Control", "no-store");
    res.status(200).json(response);
}
function handleError(error, res, isStream) {
    console.error("Error:", error);
    if (isStream) {
        res.write(`data: ${JSON.stringify({ error: error.message })}\n\n`);
        res.end();
    } else {
        res.status(500).json({ error: error.message });
    }
}
app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});
```

### 2\. Direct API Configuration

If you don’t mind exposing the AI configuration in the HTTP request body (*publishing your API key is not recommended*), you can choose to inject the configuration as an environment variable.

```auto
// Initialize SpreadJS workbook
const workbook = new GC.Spread.Sheets.Workbook('ss');

// Directly configure AI service credentials
workbook.injectAI({
    model: 'gpt-4-turbo',  // Specify your AI model
    key: 'sk-your-api-key-here',  // Your API key
    basePath: 'https://api.openai.com/v1',  // API endpoint
});
```

### 3\. Custom Client\-Side Handler

If you don’t mind exposing the AI configuration in the HTTP request body (*publishing your API key is not recommended*) but want to check whether the request body contains sensitive data and perform data cleaning and other actions, you can do so.

```auto
const httpCallback = async (requestBody) => {
    requestBody.model = 'your model name';
    // do data cleaning
    const response = await fetch('your base path', {
        method: 'POST',
        headers: {
            'Authorization': `Bearer ${'your api key'}`,
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(requestBody)
    });

    if (!response.ok) {
        throw new Error(`HTTP error! status: ${response.status}`);
    }
    return response;
};
var workbook = GC.Spread.Sheets.findControl('ss');
workbook.injectAI(httpCallback);
```

## Language Localization

SpreadJS automatically requests AI responses in the workbook's current language:

```auto
let culture = GC.Spread.Common.CultureManager.culture(); // ja-jp
let language = GC.Spread.Common.CultureManager.getCultureInfo(culture).displayName // 'Japanese (Japan)'

// in prompts
// 'please return the answer by this language: ' + language;
```

## Security Best Practices

1. ​**​Data Protection​**​:
    * Always sanitize sensitive spreadsheet data
    * Consider field redaction in callbacks
2. ​**​Credential Security​**​:
    * Exposing API Keys directly in client-side code is NOT recommended.
    * Use server proxies in production
3. ​**​Validation​**​:
    * Verify all AI-generated formulas/content
    * Implement output sanitization

>type=note
> AI functionality is one of the SpreadJS Add-on features. For licensing details, please refer to:[ License for Add-on Features.](/spreadjs/docs/getstarted/trialSpreadJS#license-for-add-on-features)

> **AI-Generated Content Disclaimer**
> 
> **1\. Content Generation Risks**
> This service utilizes third-party AI models injected by users to generate outputs. Results may contain inaccuracies, omissions, or misleading content due to inherent limitations in model architectures and training data. While we implement **prompt engineering** and technical constraints to optimize outputs, we cannot eliminate all error risks stemming from fundamental model deficiencies.
> 
> **2\. User Verification Obligations**
> By using this service, you acknowledge and agree to:
>
> * Conduct manual verification of all generated content
> * Refrain from using unvalidated outputs in high-risk scenarios (legal, medical, financial, etc.)
> * Hold us harmless for any direct/indirect damages caused by reliance on generated content
>
> **3\. Technical Limitations**
> We disclaim responsibility for:
>
> * Output failures caused by third-party model defects or logic errors
> * Unsuccessful error recovery attempts through fault-tolerant procedures
> * Technical constraints inherent in current AI technologies
>
> **4\. Intellectual Property Compliance**
> You must ensure:
>
> * Injected models/content do not infringe third-party rights
> * No illegal/sensitive material is processed through the service
> * Compliance with model providers' IP agreements
>
> **5\. Agreement Updates**
> We reserve the right to modify these terms to align with:
>
> * Technological advancements (e.g. new AI safety protocols)
> * Regulatory changes (e.g. updated AI governance frameworks)
> * Service architecture improvements