---
title: AI-Powered Survey Design Chat
product: Survey Creator
description: Experience interactive survey design with AI-powered chat assistant. Ask questions, request modifications, and watch your survey evolve in real-time. The AI understands SurveyJS JSON format and maintains conversation context while automatically applying changes to your survey. JavaScript form builder demo.
framework: React
source: https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/reactjs
index: https://surveyjs.io/survey-creator/examples/overview.md
---

# AI-Powered Survey Design Chat (React)

AI assistants can simplify tasks like content creation, coding, and data generation. In surveys, they help authors configure questionnaires faster by turning plain text prompts into ready-to-use survey definitions. In this demo, Survey Creator integrates an AI assistant instead of the standard Property Grid. The assistant generates survey JSON schemas based on your input. Enter a description of your survey, click Send, and within seconds the schema will appear in the Survey Creator's JSON Editor tab.

## Implementation

This Survey Creator configuration consists of four main parts:

- Language Model        
Integration begins with deploying a language model and exposing an API for interaction. Refer to the documentation of the chosen model for setup instructions. This example uses the GPT-3.5 Turbo model deployed on the SurveyJS website.

- Chat Manager      
A static class that provides an API for sending prompts and parsing responses. Before the user can send a prompt, the chat manager sends system messages to establish context. Each user prompt is accompanied by the current JSON schema and instructions for the required response format. See the `chat_manager.js` file for details.

- Survey Creator Manager        
A static class that provides an API for retrieving, validating, and assigning survey JSON schemas from and to Survey Creator. See the `creator_manager.js` file for details.

- Custom AI Survey Chat Component     
A custom component that renders a chat interface in the sidebar. It is activated by the AI Chat toolbar item and displays the conversation history, an input field, and a Send button. The component integrates with the chat manager and Survey Creator manager APIs to process prompts and manage JSON schemas. To use this component, register it under the `svc-ai-chat` name with the appropriate factory: `ReactElementFactory` (React and vanilla JavaScript), `AngularComponentFactory` (Angular), or `ComponentFactory` (Vue 3). See the `AISurveyChat` component in the source code for implementation details.

## More AI-Powered Demos

[Generate Choice Options](/survey-creator/examples/ai-generated-choices/ (linkStyle))

[One-Click Survey Localization](/survey-creator/examples/ai-translation/ (linkStyle))

[Generate Survey from PDF Document](/survey-creator/examples/convert-pdf-to-web-survey-ai/ (linkStyle))

## Files

### `public/index.html`

```html
<!-- Uncomment the following lines to enable Ace Editor in the JSON Editor tab -->
<!-- 
<script src="https://unpkg.com/ace-builds/src-min-noconflict/ace.js"></script>
<script src="https://unpkg.com/ace-builds/src-min-noconflict/ext-searchbox.js"></script>
<script src="https://unpkg.com/ace-builds/src-min-noconflict/theme-clouds_midnight.js"></script>
-->

<div id="surveyCreatorContainer" style="position: absolute; height: 100%; width: 100%"></div>
```

### `src/chat_manager.js`

```js
import { Serializer } from "survey-core";

export class ChatManager {
    helloMessage = "We are developing a SurveyJS JSON schema. I will ask questions, and you will answer them and provide the full version of JSON in each response.";
    helloMessageResponse = "Hello! I'm your AI assistant, here to help you create and configure your survey. What kind of survey would you like to create?";
    formatMessage = "You should give all answers only in this format: [COMMENT]your comment[/COMMENT] [JSON]Generated valid SurveyJS JSON[/JSON].";
    schemaMessage = "Your generated JSON should correspond to this schema: ```" + JSON.stringify(Serializer.generateSchema()) +"```. Always check this schema. Do not add properties to your JSON if they do not exist in this schema.";
    constructor() {
        if (ChatManager.instance) {
            return ChatManager.instance;
        }
        
        this.messageHistory = [
            { role: "user", content: this.helloMessage + this.formatMessage },
            { role: "assistant", content: this.helloMessageResponse, text: this.helloMessageResponse },
            { role: "user", content: this.schemaMessage }
        ];
        ChatManager.instance = this;
    }
    
    static getInstance() {
        if (!ChatManager.instance) {
            ChatManager.instance = new ChatManager();
        }
        return ChatManager.instance;
    }

    prepareMessage(userMessage, currentCreatorJSON, currentlySelectedElement) {
        this.messageHistory.push(
            { role: 'user', content: "My current JSON is: " + currentCreatorJSON }
        );
        if (currentlySelectedElement) {
            this.messageHistory.push(
                { role: 'user', content: "Currently selected element: " + currentlySelectedElement }
            );
        }
        this.messageHistory.push(
            { role: 'user', content: this.formatMessage }
        );
        this.messageHistory.push(
            { text: userMessage, role: 'user', content: userMessage }
        );

        return {
            text: userMessage,
            messageHistory: this.messageHistory
        };
    }
    
    async sendMessage(requestData) {
        try {
            const response = await fetch('/api/ai/query', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(requestData)
            });
            
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            
            const result = await response.json();
            
            if (result.error) {
                throw new Error(result.error);
            }
            const parsed = this.parseResponse(result.text);
            this.messageHistory.push(
                { text: parsed.comment, role: 'assistant', content: result.text }
            );
          
            return {
                success: true,
                response: parsed.json,
                error: null
            };
            
        } catch (error) {
            console.error('Error calling AI API:', error);
            
            return {
                success: false,
                response: null,
                error: error.message
            };
        }
    }
    
    parseResponse(responseText) {
        const commentRegex = /\[COMMENT\](.*?)\[\/COMMENT\]/s;
        const jsonRegex = /\[JSON\](.*?)\[\/JSON\]/s;
        
        const commentMatch = responseText.match(commentRegex);
        const jsonMatch = responseText.match(jsonRegex);
        
        return {
            comment: commentMatch && commentMatch[1].trim() || jsonMatch && jsonMatch[1].trim() || responseText,
            json: jsonMatch ? jsonMatch[1].trim() : null
        };
    }
   
    getDisplayMessages() {
        return this.messageHistory.filter(msg => !!msg.text);
    }
}
```

### `src/creator_manager.js`

```js
export class CreatorManager {
    constructor(creator) {
        this.creator = creator;
    }

    getJSONString() {
        return JSON.stringify(this.creator.JSON);
    }

    getSelectedElementName() {
        return this.creator.selectedElement && this.creator.selectedElement.name;
    }

    handleJSONResponse(jsonString) {
        jsonString = jsonString && jsonString.trim();
        if (!jsonString) return;
        try {
            const jsonData = JSON.parse(jsonString);
            if (JSON.stringify(jsonData) == "{}") return;
            
            // Validate JSON using SurveyJS Model
            let isValid = true;
            try {
                const survey = new Survey.Model();
                survey.fromJSON(jsonData, { validatePropertyValues: true });
                isValid = !survey.jsonErrors;
            } catch {
                isValid = false;
            }
            
            if (isValid) {
                this.creator.JSON = jsonData;
            } else {
                this.creator.notify("Generated JSON schema contains errors. Please fix them manually.", "error");
                this.creator.activeTab = "json";
                setTimeout(() => { 
                    this.creator.getPlugin("json").model.text = jsonString; 
                }, 100);
            }
        } catch (error) {
            this.creator.notify("Error parsing JSON: " + error.message, "error");
            console.error('Error parsing JSON:', error);
        }
    }
}
```

### `src/SurveyCreatorComponent.jsx`

```js
import React from "react";
import { SurveyCreator, SurveyCreatorComponent } from "survey-creator-react";
import "survey-core/survey.i18n";
import "survey-creator-core/survey-creator-core.i18n";
import { ReactElementFactory } from "survey-react-ui";
import { Action, ComputedUpdater, SvgRegistry } from "survey-core";
import { getLocaleStrings } from "survey-creator-core";
import { ChatManager } from "./chat_manager";
import { CreatorManager } from "./creator_manager";
import { Component } from "react";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";
import "./index.css";

import SurveyTheme from "survey-core/themes";
import { registerCreatorTheme } from "survey-creator-core";

registerCreatorTheme(SurveyTheme); // Add predefined Survey Creator UI themes




const translations = getLocaleStrings("en");
translations.ed.aiChat = "AI Chat";

const iconAiChat = `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
    <path d="M6 5.5H18C18.55 5.5 19 5.95 19 6.5V13C19 13.55 18.55 14 18 14H13L9 18V14H6C5.45 14 5 13.55 5 13V6.5C5 5.95 5.45 5.5 6 5.5Z"/>
</svg>`;

SvgRegistry.registerIcon("icon-aichat", iconAiChat);

class AISurveyChat extends Component {
    constructor(props) {
        super(props);
        this.state = { 
            messages: [], 
            input: '', 
            isLoading: false 
        };
        this.chatManager = ChatManager.getInstance();
        this.creatorManager = new CreatorManager(this.props.model);
        this.sendMessage = this.sendMessage.bind(this);
        this.handleInput = this.handleInput.bind(this);
    }
    
    componentDidMount() {
        this.showMessages();
    }
    
    showMessages() {
        this.setState({
            messages: this.chatManager.getDisplayMessages(),
            isLoading: false
        });
    }

    async sendMessage() {
        if (!this.state.input.trim() || this.state.isLoading) return;
        
        const userMessage = this.state.input;
        this.setState({ input: '' });
        
        const response = this.chatManager.prepareMessage(userMessage, this.creatorManager.getJSONString(), this.creatorManager.getSelectedElementName());
        this.showMessages();
        this.setState({ isLoading: true });

        const result = await this.chatManager.sendMessage(response);
        if (result.success) {
            this.showMessages();
        }
        
        this.creatorManager.handleJSONResponse(result.response);
    }

    handleInput(e) {
        this.setState({ input: e.target.value });
    }

    render() {
        const model = this.props.model;
        if (!model) return null;

        return (
            <div className="chat-container">
                <div className="messages">
                    {this.state.messages.map((msg, i) => (
                        <div key={i} className={`message ${msg.role}`}>
                            {msg.text}
                        </div>
                    ))}
                    {this.state.isLoading && (
                        <div className="message ai loading">
                            <div className="typing-indicator">
                                <span></span>
                                <span></span>
                                <span></span>
                                &nbsp;
                            </div>
                        </div>
                    )}
                </div>
                <div className="ai-chat-input">
                    <div className="spg-question__content spg-text__content">
                        <div className="sd-formbox sd-text">
                        <input
                            id="ai-chat-input"
                            name="ai-chat-input"
                            className="sd-formbox__input"
                            type="text"
                            value={this.state.input}
                            onChange={this.handleInput}
                            onKeyDown={e => e.key === 'Enter' && this.sendMessage()}
                            placeholder={this.state.isLoading ? "Sending message..." : "Type message..."}
                            disabled={this.state.isLoading}
                        />
                            <div className="sd-action-bar sd-action-bar--default-size sd-formbox__group">
                                <div className="sd-action-bar__item">
                                    <div className="sd-action-bar__item-content">
                                        <button
                                            type="button"
                                            className="sd-action sd-action--neutral sd-action--tertiary sd-action--small"
                                            aria-label="Send"
                                            title="Send"
                                            onClick={this.sendMessage}
                                            disabled={this.state.isLoading || !this.state.input.trim()}
                                        >
                                            <svg className="sv-svg-icon sd-action__icon">
                                                <use xlinkHref="#icon-arrowup-24x24"></use>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        );
    }
}

ReactElementFactory.Instance.registerElement("svc-ai-chat", (props) => {
    return React.createElement(AISurveyChat, props);
});
function SurveyCreatorRenderComponent() {
    const creator = new SurveyCreator();
    creator.propertyGridNavigationMode = "accordion";
    
    const aiChatAction = new Action({
      id: "svd-toolbox",
      iconName: "icon-aichat",
      iconSize: "auto",
      needSeparator: true,
      action: () => {
        if (!creator.showSidebar) {
          creator.setShowSidebar(true, true);
        }
    
        const designerPlugin = creator.getPlugin("designer");
        designerPlugin.setActivePage("aichat");
      },
      active: new ComputedUpdater(
        () => creator.sidebar.activePage === "aichat"
      ),
      visible: new ComputedUpdater(
        () => creator.activeTab === "designer"
      ),
      locTitleName: "ed.aiChat",
      showTitle: false,
    });
    
    creator.toolbar.actions.push(aiChatAction);
    
    const settingsAction = creator.toolbar.getActionById("svd-settings");
    
    settingsAction.active = new ComputedUpdater(
      () => creator.sidebar.activePage === "propertyGrid"
    );
    
    const aiChatTab = creator.sidebar.addPage(
      "aichat",
      "svc-ai-chat",
      creator
    );
    
    aiChatTab.locTitleName = "ed.aiChat";
    
    creator.sidebar.activePage = "aichat";
    creator.showSidebar = true;
    return (<SurveyCreatorComponent creator={creator} />);
}

export default SurveyCreatorRenderComponent;
```

### `src/index.css`

```css
/* Chat container styles */
.chat-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
  background-color: #f9f9f9;
  gap: 12px;
}

.message {
  margin-bottom: 12px;
  padding: 8px 12px;
  border-radius: 12px;
  max-width: 80%;
  word-wrap: break-word;
}

.message.user {
  background-color: #19b3941a;
  margin-left: auto;
  text-align: right;
}

.message.assistant {
  background-color: white;
}

.message.loading {
  background-color: white;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* Typing indicator animation */
.typing-indicator {
  display: flex;
  align-items: center;
  gap: 4px;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #999;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.chat-container .ai-chat-input {
  box-sizing: border-box;
  padding: 16px;
  border-top: 1px solid #d4d4d4;
}

.chat-container .ai-chat-input .spg-question__content {
  width: 100%;
}
```

### `src/index.js`

```js
import React from "react";
import { createRoot } from "react-dom/client";
import SurveyCreatorRenderComponent from "./SurveyCreatorComponent";

const root = createRoot(document.getElementById("surveyCreatorContainer"));
root.render(<SurveyCreatorRenderComponent />);
```

### `package.json`

```json
{
  "dependencies": {
    "react": "latest",
    "react-dom": "latest",
    "babel": "latest",
    "survey-core": "latest",
    "survey-react-ui": "latest",
    "survey-creator-core": "latest",
    "survey-creator-react": "latest"
  },
  "devDependencies": {
    "react-scripts": "latest"
  }
}
```

## Other Frameworks

- [Angular](https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/angular.md)
- [Vue 3](https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/vue3js.md)
- [jQuery](https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/jquery.md)
- [Vanilla JS](https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/vanillajs.md)
