Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Semantic Text UI] Handle the case when the model is not yet downloaded #182040

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,15 @@ import { act } from 'react-dom/test-utils';
const mlMock: any = {
mlApi: {
inferenceModels: {
createInferenceEndpoint: jest.fn(),
createInferenceEndpoint: jest.fn().mockResolvedValue({}),
},
trainedModels: {
startModelAllocation: jest.fn(),
startModelAllocation: jest.fn().mockResolvedValue({}),
getTrainedModels: jest.fn().mockResolvedValue([
{
fully_defined: true,
},
]),
},
},
};
Expand Down Expand Up @@ -93,6 +98,11 @@ describe('useSemanticText', () => {
result.current.handleSemanticText(mockFieldData);
});

expect(mlMock.mlApi.trainedModels.startModelAllocation).toHaveBeenCalledWith('.elser_model_2');
expect(mockDispatch).toHaveBeenCalledWith({
type: 'field.addSemanticText',
value: mockFieldData,
});
expect(mlMock.mlApi.inferenceModels.createInferenceEndpoint).toHaveBeenCalledWith(
'elser_model_2',
'text_embedding',
Expand All @@ -105,16 +115,58 @@ describe('useSemanticText', () => {
},
}
);
expect(mlMock.mlApi.trainedModels.startModelAllocation).toHaveBeenCalledWith('.elser_model_2');
expect(mockDispatch).toHaveBeenCalledWith({
type: 'field.addSemanticText',
value: mockFieldData,
});

it('should invoke the download api if the model does not exist', async () => {
const mlMockWithModelNotDownloaded: any = {
mlApi: {
inferenceModels: {
createInferenceEndpoint: jest.fn(),
},
trainedModels: {
startModelAllocation: jest.fn(),
getTrainedModels: jest.fn().mockResolvedValue([
{
fully_defined: false,
},
]),
installElasticTrainedModelConfig: jest.fn().mockResolvedValue({}),
},
},
};
const { result } = renderHook(() =>
useSemanticText({
form,
setErrorsInTrainedModelDeployment: jest.fn(),
ml: mlMockWithModelNotDownloaded,
})
);

await act(async () => {
result.current.handleSemanticText(mockFieldData);
});

expect(
mlMockWithModelNotDownloaded.mlApi.trainedModels.installElasticTrainedModelConfig
).toHaveBeenCalledWith('.elser_model_2');
expect(
mlMockWithModelNotDownloaded.mlApi.trainedModels.startModelAllocation
).toHaveBeenCalledWith('.elser_model_2');
expect(
mlMockWithModelNotDownloaded.mlApi.inferenceModels.createInferenceEndpoint
).toHaveBeenCalledWith('elser_model_2', 'text_embedding', {
service: 'elasticsearch',
service_settings: {
num_allocations: 1,
num_threads: 1,
model_id: '.elser_model_2',
},
});
});

it('handles errors correctly', async () => {
const mockError = new Error('Test error');
mlMock.mlApi.inferenceModels.createInferenceEndpoint.mockImplementationOnce(() => {
mlMock.mlApi?.trainedModels.startModelAllocation.mockImplementationOnce(() => {
throw mockError;
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
*/

import { i18n } from '@kbn/i18n';
import { MlPluginStart } from '@kbn/ml-plugin/public';
import { useCallback } from 'react';
import { MlPluginStart, TrainedModelConfigResponse } from '@kbn/ml-plugin/public';
import React, { useEffect, useState } from 'react';
import { useComponentTemplatesContext } from '../../../../../../component_templates/component_templates_context';
import { useDispatch, useMappingsState } from '../../../../../mappings_state_context';
Expand Down Expand Up @@ -64,20 +65,37 @@ export function useSemanticText(props: UseSemanticTextProps) {
}
}, [form, inferenceId, inferenceToModelIdMap]);

const handleSemanticText = (data: Field) => {
data.inferenceId = inferenceValue;
const isModelDownloaded = useCallback(
async (modelId: string) => {
try {
const response: TrainedModelConfigResponse[] | undefined =
await ml?.mlApi?.trainedModels.getTrainedModels(modelId, {
include: 'definition_status',
});
return !!response?.[0]?.fully_defined;
} catch (error) {
if (error.body.statusCode !== 404) {
throw error;
}
}
return false;
},
[ml?.mlApi?.trainedModels]
);

const createInferenceEndpoint = (
trainedModelId: string,
defaultInferenceEndpoint: boolean,
data: Field
) => {
if (data.inferenceId === undefined) {
return;
}

const inferenceData = inferenceToModelIdMap?.[data.inferenceId];

if (!inferenceData) {
return;
throw new Error(
i18n.translate('xpack.idxMgmt.mappingsEditor.createField.undefinedInferenceIdError', {
defaultMessage: 'InferenceId is undefined while creating the inference endpoint.',
})
);
}

const { trainedModelId, defaultInferenceEndpoint, isDeployed, isDeployable } = inferenceData;

if (trainedModelId && defaultInferenceEndpoint) {
const modelConfig = {
service: 'elasticsearch',
Expand All @@ -87,28 +105,45 @@ export function useSemanticText(props: UseSemanticTextProps) {
model_id: trainedModelId,
},
};
try {
ml?.mlApi?.inferenceModels?.createInferenceEndpoint(
data.inferenceId,
'text_embedding',
modelConfig
);
} catch (error) {
setErrorsInTrainedModelDeployment?.((prevItems) => [...prevItems, trainedModelId]);
toasts?.addError(error.body && error.body.message ? new Error(error.body.message) : error, {
title: i18n.translate(
'xpack.idxMgmt.mappingsEditor.createField.inferenceEndpointCreationErrorTitle',
{
defaultMessage: 'Inference endpoint creation failed',
}
),
});
}

ml?.mlApi?.inferenceModels?.createInferenceEndpoint(
data.inferenceId,
'text_embedding',
modelConfig
);
}
};

const handleSemanticText = async (data: Field) => {
data.inferenceId = inferenceValue;
if (data.inferenceId === undefined) {
return;
}

const inferenceData = inferenceToModelIdMap?.[data.inferenceId];

if (!inferenceData) {
return;
}

const { trainedModelId, defaultInferenceEndpoint, isDeployed, isDeployable } = inferenceData;

if (isDeployable && trainedModelId && !isDeployed) {
if (isDeployable && trainedModelId) {
try {
ml?.mlApi?.trainedModels.startModelAllocation(trainedModelId);
const modelDownloaded: boolean = await isModelDownloaded(trainedModelId);

if (isDeployed) {
createInferenceEndpoint(trainedModelId, defaultInferenceEndpoint, data);
} else if (modelDownloaded) {
ml?.mlApi?.trainedModels
.startModelAllocation(trainedModelId)
.then(() => createInferenceEndpoint(trainedModelId, defaultInferenceEndpoint, data));
} else {
ml?.mlApi?.trainedModels
.installElasticTrainedModelConfig(trainedModelId)
.then(() => ml?.mlApi?.trainedModels.startModelAllocation(trainedModelId))
.then(() => createInferenceEndpoint(trainedModelId, defaultInferenceEndpoint, data));
}
toasts?.addSuccess({
title: i18n.translate(
'xpack.idxMgmt.mappingsEditor.createField.modelDeploymentStartedNotification',
Expand Down
1 change: 1 addition & 0 deletions x-pack/plugins/ml/public/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export const plugin: PluginInitializer<
> = (initializerContext: PluginInitializerContext) => new MlPlugin(initializerContext);

export type { MlPluginSetup, MlPluginStart };
export type { TrainedModelConfigResponse } from '../common/types/trained_models';

export type { MlCapabilitiesResponse } from '../common/types/capabilities';
export type { MlSummaryJob } from '../common/types/anomaly_detection_jobs';
Expand Down