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

# AI-Powered Survey Design Chat (Vue 3)

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
<div id="app" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0;"></div>
```

### `src/AISurveyChat.vue`

```html
<template>
  <div class="chat-container">
    <div class="messages">
      <div 
        v-for="(msg, i) in messages" 
        :key="i" 
        class="message" 
        :class="msg.role"
      >
        {{ msg.text }}
      </div>
      <div v-if="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"
          v-model="input"
          @keypress="onKeyPress"
          :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>
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue';

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

const props = defineProps<{ model: PropertyGridViewModel }>();

const messages = ref<any[]>([]);
const input = ref('');
const isLoading = ref(false);

let chatManager: any;
let creatorManager: any;

onMounted(() => {
  chatManager = ChatManager.getInstance();
  creatorManager = new CreatorManager(props.model.creator);
  showMessages();
});

function showMessages() {
  messages.value = chatManager.getDisplayMessages();
  isLoading.value = false;
}

async function sendMessage() {
  if (!input.value.trim() || isLoading.value) return;
  
  const userMessage = input.value;
  input.value = '';
  
  const response = await chatManager.prepareMessage(
    userMessage, 
    creatorManager.getJSONString(), 
    creatorManager.getSelectedElementName()
  );
  showMessages();
  isLoading.value = true;
  
  const result = await chatManager.sendMessage(response);
  
  if (result.success) {
    showMessages();
  }
  
  creatorManager.handleJSONResponse(result.response);
}

function onKeyPress(event: KeyboardEvent) {
  if (event.key === 'Enter') {
    sendMessage();
  }
}
</script>

<style scoped>
.chat-container {
  display: block;
  width: 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%;
}
</style>
  
```

### `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/App.vue`

```html
<template>
    <SurveyCreatorComponent :model="creator" />
</template>
<script setup lang="ts">
    import { SurveyCreatorModel } from "survey-creator-core";
    import { SurveyCreatorComponent } from "survey-creator-vue";
    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 "./index.css";
    import SurveyTheme from "survey-core/themes";
    import { registerCreatorTheme } from "survey-creator-core";

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

    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;
</script>
```

### `src/index.css`

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

### `src/main.ts`

```ts
import { createApp } from "vue";
import App from "./App.vue";
import AISurveyChat from "./AISurveyChat.vue";
import { ComponentFactory } from "survey-vue3-ui";

const app = createApp(App);
ComponentFactory.Instance.registerComponent(
    "svc-ai-chat",
    AISurveyChat
);
app.mount("#app");
```

### `src/shims-vue.d.ts`

```ts
/* eslint-disable */
declare module "*.vue" {
    import type { DefineComponent } from "vue"
    const component: DefineComponent<{}, {}, any>
    export default component
}
```

### `.eslintrc.js`

```js
module.exports = {
    root: true,
    env: {
        node: true
    },
    extends: [
        "plugin:vue/vue3-essential",
        "eslint:recommended",
        "@vue/typescript/recommended",
        "@vue/prettier",
        "@vue/prettier/@typescript-eslint"
    ],
    parserOptions: {
        ecmaVersion: 2020
    },
    rules: {
        "no-console": process.env.NODE_ENV === "production" ? "warn" : "off",
        "no-debugger": process.env.NODE_ENV === "production" ? "warn" : "off"
    },
    overrides: [
        {
            files: [
                "**/__tests__/*.{j,t}s?(x)",
                "**/tests/unit/**/*.spec.{j,t}s?(x)"
            ],
            env: {
                jest: true
            }
        }
    ]
};
```

### `babel.config.js`

```js
module.exports = {
  presets: ["@vue/cli-plugin-babel/preset"]
};
```

### `package.json`

```json
{
  "name": "surveyjs-library-vue3",
  "version": "0.1.0",
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "core-js": "^3.6.5",
    "tslib": "2.6.1",
    "vue": "^3.4.1",
    "survey-core": "latest",
    "survey-vue3-ui": "latest",
    "survey-creator-core": "latest",
    "survey-creator-vue": "latest",
    "vue-router": "^4.0.0-0",
    "vuex": "^4.0.0-0"
  },
  "devDependencies": {
    "@typescript-eslint/eslint-plugin": "^2.33.0",
    "@typescript-eslint/parser": "^2.33.0",
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-plugin-pwa": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-plugin-vuex": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "@vue/eslint-config-prettier": "^6.0.0",
    "@vue/eslint-config-typescript": "^5.0.2",
    "@vue/test-utils": "^2.0.0-0",
    "eslint": "^6.7.2",
    "eslint-plugin-prettier": "^3.1.3",
    "eslint-plugin-vue": "^7.0.0-0",
    "node-sass": "^4.12.0",
    "prettier": "^1.19.1",
    "sass-loader": "^8.0.2",
    "typescript": "~3.9.3"
  }
}
```

### `tsconfig.json`

```json
{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "types": [
      "webpack-env",
      "jest"
    ],
    "paths": {
      "@/*": [
        "src/*"
      ]
    },
    "lib": [
      "esnext",
      "dom",
      "dom.iterable",
      "scripthost"
    ]
  },
  "include": [
    "src/**/*.ts",
    "src/**/*.tsx",
    "src/**/*.vue",
    "tests/**/*.ts",
    "tests/**/*.tsx"
  ],
  "exclude": [
    "node_modules"
  ]
}
```

## Other Frameworks

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