<template>
<DxDataGrid
:data-source="dataSource"
:show-borders="true"
:remote-operations="true"
:height="600"
@editor-preparing="onEditorPreparing"
>
<DxScrolling mode="virtual"/>
<DxSearchPanel :visible="true"/>
<DxToolbar>
<DxItem
location="before"
>
<template #default>
<div>
<div :style="{ display: 'flex', alignItems: 'center' }">
<span :style="{ marginRight: '8px' }">Similarity Factor:</span>
<DxNumberBox
:value="similarityFactor"
:min="0"
:max="1"
format="0.00"
:step="0.05"
:show-spin-buttons="true"
:input-attr="{ 'aria-label': 'Similarity Factor' }"
@value-changed="onSimilarityFactorChanged"
/>
</div>
</div>
</template>
</DxItem>
<DxItem
name="searchPanel"
/>
</DxToolbar>
<DxColumn
data-field="ID"
:width="50"
/>
<DxColumn data-field="Name"/>
<DxColumn data-field="Description"/>
</DxDataGrid>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import {
DxDataGrid,
DxColumn,
DxScrolling,
DxSearchPanel,
DxToolbar,
DxItem,
type DxDataGridTypes,
} from 'devextreme-vue/data-grid';
import DxNumberBox, { type DxNumberBoxTypes } from 'devextreme-vue/number-box';
import { DataSource } from 'devextreme-vue/common/data';
import { createStore } from 'devextreme-aspnet-data-nojquery';
const url = 'https://js.devexpress.com/Demos/NetCore/api/DataGridSemanticSearch';
const searchValue = ref('');
const similarityFactor = ref(0.31);
const dataSource = new DataSource({
store: createStore({
key: 'ID',
loadUrl: `${url}/Get`,
loadParams: {
searchValue: () => searchValue.value,
similarityFactor: () => similarityFactor.value,
},
onBeforeSend(method, ajaxOptions) {
ajaxOptions.xhrFields = { withCredentials: true };
},
}),
});
const onSimilarityFactorChanged = (e: DxNumberBoxTypes.ValueChangedEvent) => {
similarityFactor.value = e.value;
if (searchValue.value !== '') {
dataSource.reload();
}
};
const onEditorPreparing = (e: DxDataGridTypes.EditorPreparingEvent) => {
if (e.parentType === 'searchPanel') {
let searchTimeout: ReturnType<typeof setTimeout> | undefined;
e.editorOptions.onValueChanged = (args: { value: string }) => {
clearTimeout(searchTimeout);
searchTimeout = setTimeout(() => {
searchValue.value = args.value;
e.component.getDataSource().reload();
}, e.updateValueTimeout);
};
e.editorOptions.placeholder = 'Try: clothing';
}
};
</script>
window.exports = window.exports || {};
window.config = {
transpiler: false,
meta: {
'*.vue': {
loader: 'vue-loader',
},
'*.ts': {
loader: 'demo-ts-loader',
},
'*.svg': {
loader: 'svg-loader',
},
'typescript': {
'exports': 'ts',
},
'vue': {
format: 'global',
exports: 'Vue',
esModule: true,
},
'vuex': {
format: 'global',
exports: 'Vuex',
esModule: true,
},
'devextreme/time_zone_utils.js': {
'esModule': true,
},
'devextreme/localization.js': {
'esModule': true,
},
'devextreme/viz/palette.js': {
'esModule': true,
},
'devextreme-aspnet-data-nojquery': {
'esModule': true,
},
'openai': {
'esModule': true,
},
'zod': {
'esModule': true,
},
'zod-to-json-schema': {
'esModule': true,
},
'anti-forgery': {
loader: 'demo-ts-loader',
},
},
paths: {
'project:': '../../../../',
'npm:': 'https://cdn.jsdelivr.net/npm/',
'bundles:': '../../../../bundles/',
'externals:': '../../../../bundles/externals/',
'anti-forgery:': '../../../../shared/anti-forgery/',
'loaders:': '../../../../shared/loaders/',
},
map: {
'anti-forgery': 'anti-forgery:fetch-override.js',
'vue': 'npm:vue@3.5.32/dist/vue.global.js',
'@vue/shared': 'npm:@vue/shared@3.4.27/dist/shared.cjs.prod.js',
'dx-systemjs-vue-browser': 'npm:dx-systemjs-vue-browser@1.1.2/index.js',
'demo-ts-loader': 'loaders:demo-ts-loader.js',
'demo-ts-shared': 'loaders:demo-ts-shared.js',
'vue-loader': 'loaders:demo-vue-loader.js',
'typescript': 'npm:typescript@4.2.4/lib/typescript.js',
'jszip': 'npm:jszip@3.10.1/dist/jszip.min.js',
'svg-loader': 'project:utils/svg-loader.js',
'devextreme-aspnet-data-nojquery': 'npm:devextreme-aspnet-data-nojquery@5.1.0/index.js',
'mitt': 'npm:mitt/dist/mitt.umd.js',
'rrule': 'npm:rrule@2.6.4/dist/es5/rrule.js',
'luxon': 'npm:luxon@3.4.4/build/global/luxon.min.js',
'es6-object-assign': 'npm:es6-object-assign',
'devextreme': 'npm:devextreme@link:../../packages/devextreme/artifacts/npm/devextreme/cjs',
'devextreme-vue': 'npm:devextreme-vue@link:../../packages/devextreme-vue/npm/cjs',
'zod': 'externals:zod.bundle.js',
'zod-to-json-schema': 'externals:zod-to-json-schema.bundle.js',
'devextreme-quill': 'npm:devextreme-quill@1.7.10/dist/dx-quill.min.js',
'devexpress-diagram': 'npm:devexpress-diagram@2.2.29/dist/dx-diagram.js',
'devexpress-gantt': 'npm:devexpress-gantt@4.1.69/dist/dx-gantt.js',
'inferno': 'npm:inferno@8.2.3/dist/inferno.min.js',
'inferno-compat': 'npm:inferno-compat/dist/inferno-compat.min.js',
'inferno-create-element': 'npm:inferno-create-element@8.2.3/dist/inferno-create-element.min.js',
'inferno-dom': 'npm:inferno-dom/dist/inferno-dom.min.js',
'inferno-hydrate': 'npm:inferno-hydrate/dist/inferno-hydrate.min.js',
'inferno-clone-vnode': 'npm:inferno-clone-vnode/dist/inferno-clone-vnode.min.js',
'inferno-create-class': 'npm:inferno-create-class/dist/inferno-create-class.min.js',
'inferno-extras': 'npm:inferno-extras/dist/inferno-extras.min.js',
'@preact/signals-core': 'npm:@preact/signals-core@1.14.1/dist/signals-core.min.js',
// Prettier
'prettier/standalone': 'npm:prettier@2.8.8/standalone.js',
'prettier/parser-html': 'npm:prettier@2.8.8/parser-html.js',
},
packages: {
'devextreme-vue': {
main: 'index.js',
},
'devextreme-vue/common': {
main: 'index.js',
},
'devextreme': {
defaultExtension: 'js',
},
'devextreme/events/utils': {
main: 'index',
},
'devextreme/common/core/events/utils': {
main: 'index',
},
'devextreme/events': {
main: 'index',
},
'es6-object-assign': {
main: './index.js',
defaultExtension: 'js',
},
},
packageConfigPaths: [
'npm:@devextreme/*/package.json',
],
};
window.process = {
env: {
NODE_ENV: 'production',
},
};
System.config(window.config);
// eslint-disable-next-line
const useTgzInCSB = ['openai'];
let packagesInfo = {
"zod": {
"version": "3.24.4"
},
"zod-to-json-schema": {
"version": "3.24.6"
}
};
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
<!DOCTYPE html>
<html lang="en">
<head>
<title>DevExtreme Demo</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0" />
<link rel="stylesheet" type="text/css" href="https://cdn3.devexpress.com/jslib/26.1.3/css/dx.light.css" />
<script type="module">
import * as vueCompilerSFC from "https://cdn.jsdelivr.net/npm/@vue/compiler-sfc@3.4.27/dist/compiler-sfc.esm-browser.js";
window.vueCompilerSFC = vueCompilerSFC;
</script>
<script src="https://cdn.jsdelivr.net/npm/typescript@6.0.3/lib/typescript.js"></script>
<script src="https://cdn.jsdelivr.net/npm/core-js@2.6.12/client/shim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/systemjs@0.21.3/dist/system.js"></script>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript">
System.import("./index.ts");
</script>
</head>
<body class="dx-viewport">
<div class="demo-container">
<div id="app" />
</div>
</body>
</html>
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Numerics.Tensors;
using System.Threading.Tasks;
using Azure.AI.OpenAI;
using Microsoft.Extensions.AI;
namespace DevExtreme.MVC.Demos.DataProviders {
public class SmartFilterProvider {
readonly IEmbeddingGenerator<string, Embedding<float>> Embedder;
readonly static ConcurrentDictionary<string, Embedding<float>> cache = new ConcurrentDictionary<string, Embedding<float>>(StringComparer.OrdinalIgnoreCase);
public SmartFilterProvider(AzureOpenAIClient openAIClient) {
Embedder = openAIClient.GetEmbeddingClient("text-embedding-3-small").AsIEmbeddingGenerator();
}
public async Task FillCacheAsync(IEnumerable<string> words) {
try {
var nonCachedWords = words.Where(x => !cache.ContainsKey(x)).ToArray();
if(!nonCachedWords.Any())
return;
var embeddings = await Embedder.GenerateAsync(nonCachedWords);
foreach(var (word, embedding) in nonCachedWords.Zip(embeddings, (word, embedding) => (word, embedding))) {
cache[word] = embedding;
}
} catch {
}
}
public float GetSimilarity(string text, string searchText) {
var eFilter = cache[text];
var eText = cache[searchText];
var cosineSimilarity = TensorPrimitives.CosineSimilarity(eText.Vector.Span, eFilter.Vector.Span);
return cosineSimilarity;
}
}
}
using DevExtreme.AspNet.Data;
using DevExtreme.AspNet.Mvc;
using DevExtreme.MVC.Demos.DataProviders;
using DevExtreme.MVC.Demos.Models.DataGrid;
using DevExtreme.MVC.Demos.Models.SampleData;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Http;
namespace DevExtreme.MVC.Demos.Controllers.ApiControllers {
public class DataGridSemanticSearchController : ApiController {
SmartFilterProvider smartFilter;
public DataGridSemanticSearchController(SmartFilterProvider smartFilterProvider) {
smartFilter = smartFilterProvider;
}
[HttpGet]
public async Task<object> Get(string searchValue, float similarityFactor, DataSourceLoadOptions loadOptions) {
if(string.IsNullOrEmpty(searchValue)) {
return DataSourceLoader.Load(SampleData.DictionaryItems, loadOptions);
}
await smartFilter.FillCacheAsync(new[] { searchValue });
var result = Search(searchValue, similarityFactor);
return DataSourceLoader.Load(result, loadOptions);
}
IEnumerable<DictionaryItem> Search(string searchValue, float similarityFactor = 0.31f) {
return SampleData.DictionaryItems
.Select(item => new {
Entry = item,
Similarity = smartFilter.GetSimilarity(DictionaryItem.GetItemDescription(item), searchValue)
})
.OrderByDescending(x => x.Similarity)
.Where(x => x.Similarity > similarityFactor)
.Select(x => x.Entry);
}
}
}
using DevExtreme.MVC.Demos.DataProviders;
using DevExtreme.MVC.Demos.Models.DataGrid;
using DevExtreme.MVC.Demos.Models.SampleData;
using Microsoft.Extensions.Hosting;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace DevExtreme.MVC.Demos.Services {
public class EmbeddingsInitializerService : IHostedService {
readonly SmartFilterProvider smartFilter;
public EmbeddingsInitializerService(SmartFilterProvider smartFilterProvider) {
smartFilter = smartFilterProvider;
}
public Task StartAsync(CancellationToken cancellationToken) {
return smartFilter.FillCacheAsync(SampleData.DictionaryItems.Select(DictionaryItem.GetItemDescription));
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
namespace DevExtreme.MVC.Demos.Models.DataGrid {
public class DictionaryItem {
public DictionaryItem(int id, string name, string description) {
ID = id;
Name = name;
Description = description;
}
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public static string GetItemDescription(DictionaryItem item) {
return $"{item.Name} - {item.Description}";
}
}
}