Skip to content

Commit

Permalink
Adding flyout to add inference endpoint from index management for sem…
Browse files Browse the repository at this point in the history
…antic_text field
  • Loading branch information
Samiul-TheSoccerFan committed Dec 26, 2024
1 parent 0f08159 commit 4a67b15
Show file tree
Hide file tree
Showing 11 changed files with 159 additions and 37 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0; you may not use this file except in compliance with the Elastic License
* 2.0.
*/

import type { Config, Secrets } from '@kbn/inference-endpoint-ui-common';

export interface InferenceEndpoint {
config: Config;
secrets: Secrets;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,9 @@ import React, { useCallback, useEffect, useState } from 'react';
import { InferenceProvider, InferenceServiceFormFields } from '@kbn/inference-endpoint-ui-common';
import { EuiButton, EuiFlexGroup, EuiFlexItem, EuiSpacer } from '@elastic/eui';

// import { useAddEndpoint } from '../../hooks/use_add_endpoint';
import { InferenceEndpoint } from '../../../../../../../../common/types/inference';
import { useProviders } from '../../../../../../hooks/use_providers';
import { useAddEndpoint } from '../../../../../../hooks/use_add_endpoint';
import { useLoadInferenceEndpoints } from '../../../../../../services';

interface InferenceFormProps {
onSubmitSuccess: () => void;
Expand Down Expand Up @@ -44,13 +42,8 @@ export const InferenceForm: React.FC<InferenceFormProps> = ({ onSubmitSuccess, r
const { isValid, data } = await form.submit();

if (isValid) {
console.log('form is valid', data);
// addEndpoint({
// inferenceEndpoint: data as InferenceEndpoint,
// });
addInferenceEndpoint(data as InferenceEndpoint);
} else {
console.log('form in not valid');
setIsLoading(false);
}
}, [addInferenceEndpoint, form]);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ import React, { useEffect, useState, useCallback, useMemo } from 'react';
import { SUPPORTED_PYTORCH_TASKS, TRAINED_MODEL_TYPE } from '@kbn/ml-trained-models-utils';
import { InferenceTaskType } from '@elastic/elasticsearch/lib/api/types';
import { ModelConfig } from '@kbn/inference_integration_flyout/types';
import { InferenceFlyoutWrapper } from '@kbn/inference_integration_flyout/components/inference_flyout_wrapper';
import { TrainedModelConfigResponse } from '@kbn/ml-plugin/common/types/trained_models';
import { getFieldConfig } from '../../../lib';
import { useAppContext } from '../../../../../app_context';
import { useLoadInferenceEndpoints } from '../../../../../services/api';
import { useMLModelNotificationToasts } from '../../../../../../hooks/use_ml_model_status_toasts';
import { CustomInferenceEndpointConfig } from '../../../types';
import { UseField } from '../../../shared_imports';
import { AddInferenceFlyoutWrapper } from './add_inference_flyout/add_inference_flyout_wrapper';

export interface SelectInferenceIdProps {
createInferenceEndpoint: (
Expand Down Expand Up @@ -234,8 +234,26 @@ const SelectInferenceIdContent: React.FC<SelectInferenceIdContentProps> = ({
panelPaddingSize="m"
closePopover={() => setIsInferencePopoverVisible(!isInferencePopoverVisible)}
>
{inferenceEndpointsPageLink && (
<EuiContextMenuPanel>
<EuiContextMenuPanel>
<EuiContextMenuItem
key="createInferenceEndpointButton"
icon="plusInCircle"
size="s"
data-test-subj="createInferenceEndpointButton"
onClick={(e) => {
e.preventDefault();
setIsInferenceFlyoutVisible(true);
setIsInferencePopoverVisible(!isInferencePopoverVisible);
}}
>
{i18n.translate(
'xpack.idxMgmt.mappingsEditor.parameters.inferenceId.popover.createInferenceEndpointButton',
{
defaultMessage: 'Add inference endpoint',
}
)}
</EuiContextMenuItem>
{inferenceEndpointsPageLink && (
<EuiContextMenuItem
key="manageInferenceEndpointButton"
icon="gear"
Expand All @@ -254,8 +272,8 @@ const SelectInferenceIdContent: React.FC<SelectInferenceIdContentProps> = ({
}
)}
</EuiContextMenuItem>
</EuiContextMenuPanel>
)}
)}
</EuiContextMenuPanel>
<EuiHorizontalRule margin="none" />
<EuiPanel color="transparent" paddingSize="s">
<EuiTitle size="xxxs">
Expand Down Expand Up @@ -327,22 +345,12 @@ const SelectInferenceIdContent: React.FC<SelectInferenceIdContentProps> = ({
<EuiFlexGroup data-test-subj="selectInferenceId">
<EuiFlexItem grow={false}>
{inferencePopover()}
{isInferenceFlyoutVisible && (
<InferenceFlyoutWrapper
elserv2documentationUrl={docLinks.links.ml.nlpElser}
e5documentationUrl={docLinks.links.ml.nlpE5}
onInferenceEndpointChange={onInferenceEndpointChange}
inferenceEndpointError={inferenceEndpointError}
trainedModels={trainedModels}
onSaveInferenceEndpoint={onSaveInferenceCallback}
{isInferenceFlyoutVisible ? (
<AddInferenceFlyoutWrapper
onFlyoutClose={onFlyoutClose}
isInferenceFlyoutVisible={isInferenceFlyoutVisible}
supportedNlpModels={docLinks.links.enterpriseSearch.supportedNlpModels}
nlpImportModel={docLinks.links.ml.nlpImportModel}
setInferenceEndpointError={setInferenceEndpointError}
isCreateInferenceApiLoading={isSaveInferenceLoading}
resendRequest={resendRequest}
/>
)}
) : null}
</EuiFlexItem>
<EuiFlexItem grow={true}>
<EuiCallOut
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@
*/

import { useCallback } from 'react';
import { i18n } from '@kbn/i18n';
import { KibanaServerError } from '@kbn/kibana-utils-plugin/common';
import { useKibana } from '..';
import { InferenceEndpoint } from '../../../common/types/inference';
import { useMLModelNotificationToasts } from '../../hooks/use_ml_model_status_toasts';
import { createInferenceEndpoint, useCreateInferenceEndpoint } from '../services';
import { createInferenceEndpoint } from '../services';

export const useAddEndpoint = (onSuccess?: () => void, onError?: () => void) => {
const { services } = useKibana();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import type { SerializedEnrichPolicy } from '@kbn/index-management-shared-types'
import { IndicesStatsResponse } from '@elastic/elasticsearch/lib/api/types';
import { InferenceAPIConfigResponse } from '@kbn/ml-trained-models-utils';
import { MappingTypeMapping } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { InferenceProvider } from '@kbn/inference-endpoint-ui-common';
import {
API_BASE_PATH,
INTERNAL_API_BASE_PATH,
Expand Down Expand Up @@ -47,8 +48,7 @@ import {
import { useRequest, sendRequest } from './use_request';
import { httpService } from './http';
import { UiMetricService } from './ui_metric';
import type { FieldFromIndicesRequest } from '../../../common';
import { Fields } from '../components/mappings_editor/types';
import type { FieldFromIndicesRequest, InferenceEndpoint } from '../../../common';

interface ReloadIndicesOptions {
asSystemRequest?: boolean;
Expand Down Expand Up @@ -473,6 +473,25 @@ export function getInferenceEndpoints() {
});
}

export function getInferenceServices() {
return sendRequest<InferenceProvider[]>({
path: `${API_BASE_PATH}/inference/services`,
method: 'get',
});
}

export function createInferenceEndpoint(
taskType: string,
inferenceId: string,
inferenceEndpoint: InferenceEndpoint
) {
return sendRequest<InferenceAPIConfigResponse>({
path: `${API_BASE_PATH}/inference/${taskType}/${inferenceId}`,
method: 'put',
body: JSON.stringify(inferenceEndpoint),
});
}

export function useLoadInferenceEndpoints() {
return useRequest<InferenceAPIConfigResponse[]>({
path: `${API_BASE_PATH}/inference/all`,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export {
useLoadIndexSettings,
createIndex,
useLoadInferenceEndpoints,
getInferenceServices,
createInferenceEndpoint,
} from './api';

export { sortTable } from './sort_table';
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,13 +43,26 @@ export function useMLModelNotificationToasts() {
}),
});
};
const showErrorToasts = (error: ErrorType) => {
const showErrorToasts = (error: ErrorType, errorTitle: string = 'Model deployment failed') => {
const errorObj = extractErrorProperties(error);
return toasts.addError(new MLRequestFailure(errorObj, error), {
title: i18n.translate('xpack.idxMgmt.mappingsEditor.createField.modelDeploymentErrorTitle', {
defaultMessage: 'Model deployment failed',
title: i18n.translate('xpack.idxMgmt.mappingsEditor.createField.inferenceErrorTitle', {
defaultMessage: errorTitle,
}),
});
};
return { showSuccessToasts, showErrorToasts, showSuccessfullyDeployedToast };

const showInferenceSuccessToast = () => {
return toasts.addSuccess({
title: i18n.translate('xpack.idxMgmt.mappingsEditor.createField.endpointAddedSuccess', {
defaultMessage: 'Endpoint added',
}),
});
};
return {
showSuccessToasts,
showErrorToasts,
showSuccessfullyDeployedToast,
showInferenceSuccessToast,
};
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import { ElasticsearchClient } from '@kbn/core/server';

import { InferenceTaskType } from '@elastic/elasticsearch/lib/api/typesWithBodyKey';
import { Config, Secrets } from '../../../../../packages/shared/kbn-inference-endpoint-ui-common';
import type { Config, Secrets } from '@kbn/inference-endpoint-ui-common';
import { unflattenObject } from '../services/unflatten_object';

export const addInferenceEndpoint = async (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

import { FieldType } from '@kbn/search-connectors/types';
import { InferenceProvider } from '../../../../../packages/shared/kbn-inference-endpoint-ui-common';
import type { InferenceProvider } from '@kbn/inference-endpoint-ui-common';

export const fetchInferenceServices = (): InferenceProvider[] => [
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,17 @@
*/

import { InferenceAPIConfigResponse } from '@kbn/ml-trained-models-utils';
import { schema } from '@kbn/config-schema';
import { KibanaServerError } from '@kbn/kibana-utils-plugin/common';
import { addBasePath } from '..';
import { RouteDependencies } from '../../../types';
import { fetchInferenceServices } from '../../../lib/fetch_inference_services';
import { InferenceEndpoint } from '../../../../common/types/inference';
import { addInferenceEndpoint } from '../../../lib/add_inference_endpoint';

function isKibanaServerError(error: any): error is KibanaServerError {
return error.statusCode && error.message;
}

export function registerGetAllRoute({ router, lib: { handleEsError } }: RouteDependencies) {
// Get all inference models
Expand Down Expand Up @@ -36,4 +45,69 @@ export function registerGetAllRoute({ router, lib: { handleEsError } }: RouteDep
}
}
);

router.get(
{
path: addBasePath('/inference/services'),
validate: {},
},
async (context, request, response) => {
try {
const providers = fetchInferenceServices();

return response.ok({
body: providers,
headers: { 'content-type': 'application/json' },
});
} catch (error) {
if (isKibanaServerError(error)) {
return response.customError({ statusCode: error.statusCode, body: error.message });
}
throw error;
}
}
);

router.put(
{
path: addBasePath(`/inference/{taskType}/{inferenceId}`),
validate: {
params: schema.object({
taskType: schema.string(),
inferenceId: schema.string(),
}),
body: schema.object({
config: schema.object({
inferenceId: schema.string(),
provider: schema.string(),
taskType: schema.string(),
providerConfig: schema.any(),
}),
secrets: schema.object({
providerSecrets: schema.any(),
}),
}),
},
},
async (context, request, response) => {
try {
const {
client: { asCurrentUser },
} = (await context.core).elasticsearch;

const { config, secrets }: InferenceEndpoint = request.body;
const result = await addInferenceEndpoint(asCurrentUser, config, secrets);

return response.ok({
body: result,
headers: { 'content-type': 'application/json' },
});
} catch (error) {
if (isKibanaServerError(error)) {
return response.customError({ statusCode: error.statusCode, body: error.message });
}
throw error;
}
}
);
}
2 changes: 2 additions & 0 deletions x-pack/platform/plugins/shared/index_management/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@
"@kbn/unsaved-changes-prompt",
"@kbn/shared-ux-table-persist",
"@kbn/core-application-browser",
"@kbn/inference-endpoint-ui-common",
"@kbn/safer-lodash-set"
],
"exclude": ["target/**/*"]
}

0 comments on commit 4a67b15

Please sign in to comment.