---
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: Angular
source: https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/angular
index: https://surveyjs.io/survey-creator/examples/overview.md
---

# AI-Powered Survey Design Chat (Angular)

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

### `src/app/components/creator.component.css`

```css
/* You can define custom CSS rules here */
```

### `src/app/components/creator.component.html`

```html
<div style="position: fixed; top: 0; bottom: 0; right: 0; left: 0;">
    <survey-creator [model]="model"></survey-creator>
</div>
```

### `src/app/components/ai-survey-chat.component.html`

```html
<div class="chat-container">
    <div class="messages">
        <div *ngFor="let msg of messages; let i = index" class="message" [ngClass]="msg.role">
            {{msg.text}}
        </div>
        <div *ngIf="isLoading" class="message ai loading">
            <div class="typing-indicator">
                <span></span>
                <span></span>
                <span></span>
                &nbsp;
            </div>
        </div>
    </div>
    <div class="ai-chat-input">
        <div class="spg-question__content spg-text__content">
            <div class="sd-formbox sd-text">
            <input
                id="ai-chat-input"
                name="ai-chat-input"
                class="sd-formbox__input"
                type="text"
                [(ngModel)]="input"
                (keypress)="onKeyPress($event)"
                [placeholder]="isLoading ? 'Sending message...' : 'Type message...'"
                [disabled]="isLoading"
            />
                <div class="sd-action-bar sd-action-bar--default-size sd-formbox__group">
                    <div class="sd-action-bar__item">
                        <div class="sd-action-bar__item-content">
                            <button
                                type="button"
                                class="sd-action sd-action--neutral sd-action--tertiary sd-action--small"
                                aria-label="Send"
                                title="Send"
                                (click)="sendMessage()"
                                [disabled]="isLoading || !input.trim()"
                            >
                                <svg class="sv-svg-icon sd-action__icon">
                                    <use xlink:href="#icon-arrowup-24x24"></use>
                                </svg>
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
```

### `src/app/components/ai-survey-chat.component.scss`

```
:host {
    display: block;
    width: 100%;
    height: 100%;
}

/* 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/app/components/ai-survey-chat.component.ts`

```ts
import { Component, Input, OnInit } from "@angular/core";
import { AngularComponentFactory, BaseAngular } from "survey-angular-ui";
import { PropertyGridViewModel } from "survey-creator-core";

import { ChatManager } from "./chat_manager";
import { CreatorManager } from "./creator_manager";

@Component({
    selector: "svc-custom-property-grid",
    templateUrl: "./custom-property-grid.component.html",
    styleUrls: ["./custom-property-grid.component.scss"]
})
export class CustomPropertyGridComponent extends BaseAngular implements OnInit {
    @Input() model!: PropertyGridViewModel;
    
    public messages: any[] = [];
    public _input: string = "";
    public isLoading: boolean = false;
    
    private chatManager: any;
    private creatorManager: any;

    public get input(): string {
        return this._input;
    }
    public set input(val: string) {
        this._input = val;
        this.update();
    }

    getModel() {
        return this.model;
    }

    ngOnInit() {
        this.chatManager = ChatManager.getInstance();
        this.creatorManager = new CreatorManager(this.model["creator"]);
        this.showMessages();
    }

    showMessages() {
        this.messages = this.chatManager.getDisplayMessages();
        this.isLoading = false;
        this.update();
    }

    async sendMessage() {
        if (!this.input.trim() || this.isLoading) return;
        
        const userMessage = this.input;
        this.input = '';
        
        const response = await this.chatManager.prepareMessage(
            userMessage, 
            this.creatorManager.getJSONString(), 
            this.creatorManager.getSelectedElementName()
        );
        this.isLoading = true;
        this.update();

        const result = await this.chatManager.sendMessage(response);

        if (result.success) {
            this.showMessages();
        }
        
        this.creatorManager.handleJSONResponse(result.response);
    }

    onKeyPress(event: KeyboardEvent) {
        if (event.key === 'Enter') {
            this.sendMessage();
        }
    }
}
AngularComponentFactory.Instance.registerComponent(
    "svc-property-grid",
    CustomPropertyGridComponent
);
```

### `src/app/components/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/app/components/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/app/components/creator.component.ts`

```ts
import { Component, OnInit } from "@angular/core";
import { SurveyCreatorModel } from "survey-creator-core";
import "survey-core/survey.i18n";
import "survey-creator-core/survey-creator-core.i18n";
import "survey-core/survey-core.css";
import "survey-creator-core/survey-creator-core.css";

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

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

@Component({
    // tslint:disable-next-line:component-selector
    selector: "component-survey-creator",
    templateUrl: "./creator.component.html",
    styleUrls: ["./creator.component.css"]
})
export class SurveyCreatorComponent implements OnInit {
    model: SurveyCreatorModel;
    ngOnInit() {
        const creator = new SurveyCreatorModel();
        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;
        this.model = creator;
    }
}
```

### `src/app/app.component.html`

```html
<component-survey-creator></component-survey-creator>
```

### `src/app/app.component.ts`

```ts
import { Component } from "@angular/core";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html"
})
export class AppComponent {
    title = "CodeSandbox";
}
```

### `src/app/app.module.ts`

```ts
import { BrowserModule } from "@angular/platform-browser";
import { NgModule } from "@angular/core";
import { AppComponent } from "./app.component";
import { SurveyCreatorModule } from "survey-creator-angular";
import { SurveyCreatorComponent } from "./components/creator.component";
import { CommonModule } from "@angular/common";
import { FormsModule } from "@angular/forms";
import { AISurveyChatComponent } from "./components/custom-property-grid.component";

@NgModule({
    declarations: [AppComponent, SurveyCreatorComponent, AISurveyChatComponent],
    imports: [BrowserModule, SurveyCreatorModule, CommonModule, FormsModule],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }
```

### `src/environments/environment.prod.ts`

```ts
export const environment = {
    production: true
};
```

### `src/environments/environment.ts`

```ts
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.

export const environment = {
    production: false
};
```

### `src/index.html`

```html
<app-root></app-root>
```

### `src/main.ts`

```ts
import { enableProdMode } from "@angular/core";
import { platformBrowserDynamic } from "@angular/platform-browser-dynamic";

import { AppModule } from "./app/app.module";
import { environment } from "./environments/environment";

if (environment.production) {
    enableProdMode();
}

platformBrowserDynamic()
    .bootstrapModule(AppModule)
    .catch(err => console.log(err));
```

### `src/polyfills.ts`

```ts
/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js';  // Run `npm install classlist.js`.

/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';

/** Evergreen browsers require these. **/
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
import "core-js/proposals/reflect-metadata";

/**
 * Required to support Web Animations `@angular/platform-browser/animations`.
 * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
 **/
// import 'web-animations-js';  // Run `npm install web-animations-js`.

/***************************************************************************************************
 * Zone JS is required by default for Angular itself.
 */
import "zone.js/dist/zone"; // Included with Angular CLI.

/***************************************************************************************************
 * APPLICATION IMPORTS
 */
```

### `src/styles.css`

```css
/* You can add global styles to this file and import other style files */
```

### `src/typings.d.ts`

```ts
/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
    id: string;
}
```

### `.angular-cli.json`

```json
{
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [ "assets", "favicon.ico" ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "prefix": "app",
      "styles": [ "styles.css"  ],
      "scripts": [  ],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ]
}
```

### `_tsconfig.json`

```json
{
  "compileOnSave": false,
  "compilerOptions": {
    "baseUrl": "./",
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "allowSyntheticDefaultImports": true,
    "downlevelIteration": true,
    "experimentalDecorators": true,
    "moduleResolution": "node",
    "importHelpers": true,
    "resolveJsonModule": true,
    "target": "es2015",
    "module": "es2020",
    "lib": [
      "es2018",
      "dom"
    ]
  }
}
```

### `package.json`

```json
{
  "name": "surveyjs-angular",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "14.1.1",
    "@angular/cdk": "14.1.1",
    "@angular/common": "14.1.1",
    "@angular/compiler": "14.1.1",
    "@angular/core": "14.1.1",
    "@angular/forms": "14.1.1",
    "@angular/platform-browser": "14.1.1",
    "@angular/platform-browser-dynamic": "14.1.1",
    "@angular/router": "14.1.1",
    "core-js": "3.6.4",
    "rxjs": "6.5.4",
    "survey-angular-ui": "latest",
    "survey-creator-core": "latest",
    "survey-core": "latest",
    "survey-creator-angular": "latest",
    "tslib": "1.13.0",
    "zone.js": "0.11.7"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.0",
    "@angular/cli": "~13.0.0",
    "@types/jasmine": "3.6.3",
    "@types/jasminewd2": "2.0.8",
    "@types/node": "14.14.28",
    "codelyzer": "6.0.1",
    "jasmine-core": "3.6.0",
    "jasmine-spec-reporter": "6.0.0",
    "karma": "6.1.1",
    "karma-chrome-launcher": "3.1.0",
    "karma-coverage-istanbul-reporter": "3.0.3",
    "karma-jasmine": "4.0.1",
    "karma-jasmine-html-reporter": "1.5.4",
    "protractor": "7.0.0",
    "ts-node": "9.1.1",
    "tslint": "~6.1.3",
    "typescript": "4.1.5"
  },
  "keywords": [ "angular", "surveyjs" ],
  "description": "SurveyJS-Angular example project"
}
```

## Other Frameworks

- [React](https://surveyjs.io/survey-creator/examples/ai-assisted-survey-design-chat/reactjs.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)
