diff --git a/Makefile b/Makefile index 00dc2b5e7..d385de6bb 100644 --- a/Makefile +++ b/Makefile @@ -197,22 +197,29 @@ generate-client-go: @echo "Generating Go client from swagger.yaml" @mv ${CLIENT_GO_EXAMPLES_DIR} ${TEMP_CLIENT_GO_EXAMPLES_DIR} @rm -rf ${CLIENT_GO_OUTPUT_DIR} - @swagger-codegen generate -i swagger.yaml -l go -o ${TEMP_CLIENT_GO_OUTPUT_DIR} -DpackageName=client + @docker run --rm -v ${PWD}/:/local openapitools/openapi-generator-cli:v7.1.0 generate \ + --input-spec /local/swagger.yaml \ + --generator-name go \ + --output /local/api/client_tmp/. \ + --config /local/openapi-api-codegen.yaml \ + --openapi-normalizer KEEP_ONLY_FIRST_TAG_IN_OPERATION=true @mkdir ${CLIENT_GO_OUTPUT_DIR} @mv ${TEMP_CLIENT_GO_OUTPUT_DIR}/*.go ${CLIENT_GO_OUTPUT_DIR} @rm -rf ${TEMP_CLIENT_GO_OUTPUT_DIR} @mv ${TEMP_CLIENT_GO_EXAMPLES_DIR} ${CLIENT_GO_EXAMPLES_DIR} @goimports -w ${CLIENT_GO_OUTPUT_DIR} + CLIENT_PYTHON_OUTPUT_DIR = ./python/sdk/client TEMP_CLIENT_PYTHON_OUTPUT_DIR = ./python/sdk/client_tmp .PHONY: generate-client-python generate-client-python: - @echo "Generating Python client from swagger.yaml" - @rm -rf ${CLIENT_PYTHON_OUTPUT_DIR} - @swagger-codegen generate -i swagger.yaml -l python -o ${TEMP_CLIENT_PYTHON_OUTPUT_DIR} -DpackageName=client - @mv ${TEMP_CLIENT_PYTHON_OUTPUT_DIR}/client ${CLIENT_PYTHON_OUTPUT_DIR} - @rm -rf ${TEMP_CLIENT_PYTHON_OUTPUT_DIR} + rm -rf ${CLIENT_PYTHON_OUTPUT_DIR} + @docker run --rm -v ${PWD}/:/local openapitools/openapi-generator-cli:v7.1.0 generate \ + --input-spec /local/swagger.yaml \ + --generator-name python \ + --output /local/python/sdk/. \ + --config /local/openapi-sdk-codegen.yaml .PHONY: generate-proto diff --git a/api/api/model_schema_api.go b/api/api/model_schema_api.go new file mode 100644 index 000000000..53dcf5081 --- /dev/null +++ b/api/api/model_schema_api.go @@ -0,0 +1,69 @@ +package api + +import ( + "errors" + "fmt" + "net/http" + + "github.com/caraml-dev/merlin/models" + mErrors "github.com/caraml-dev/merlin/pkg/errors" +) + +type ModelSchemaController struct { + *AppContext +} + +func (m *ModelSchemaController) GetAllSchemas(r *http.Request, vars map[string]string, _ interface{}) *Response { + ctx := r.Context() + modelID, _ := models.ParseID(vars["model_id"]) + modelSchemas, err := m.ModelSchemaService.List(ctx, modelID) + if err != nil { + if errors.Is(err, mErrors.ErrNotFound) { + return NotFound(fmt.Sprintf("Model schemas not found: %v", err)) + } + return InternalServerError(fmt.Sprintf("Error get All schemas with model id: %d with error: %v", modelID, err)) + } + return Ok(modelSchemas) +} + +func (m *ModelSchemaController) GetSchema(r *http.Request, vars map[string]string, _ interface{}) *Response { + ctx := r.Context() + modelID, _ := models.ParseID(vars["model_id"]) + modelSchemaID, _ := models.ParseID(vars["schema_id"]) + modelSchema, err := m.ModelSchemaService.FindByID(ctx, modelSchemaID, modelID) + if err != nil { + if errors.Is(err, mErrors.ErrNotFound) { + return NotFound(fmt.Sprintf("Model schema with id: %d not found: %v", modelSchemaID, err)) + } + return InternalServerError(fmt.Sprintf("Error get schema with id: %d, model id: %d and error: %v", modelSchemaID, modelID, err)) + } + + return Ok(modelSchema) +} + +func (m *ModelSchemaController) CreateOrUpdateSchema(r *http.Request, vars map[string]string, body interface{}) *Response { + ctx := r.Context() + modelID, _ := models.ParseID(vars["model_id"]) + + modelSchema, ok := body.(*models.ModelSchema) + if !ok { + return BadRequest("Unable to parse request body") + } + modelSchema.ModelID = modelID + schema, err := m.ModelSchemaService.Save(ctx, modelSchema) + if err != nil { + return InternalServerError(fmt.Sprintf("Error save model schema: %v", err)) + } + return Ok(schema) +} + +func (m *ModelSchemaController) DeleteSchema(r *http.Request, vars map[string]string, _ interface{}) *Response { + ctx := r.Context() + modelID, _ := models.ParseID(vars["model_id"]) + modelSchemaID, _ := models.ParseID(vars["schema_id"]) + modelSchema := &models.ModelSchema{ID: modelSchemaID, ModelID: modelID} + if err := m.ModelSchemaService.Delete(ctx, modelSchema); err != nil { + return InternalServerError(fmt.Sprintf("Error delete model schema: %v", err)) + } + return NoContent() +} diff --git a/api/api/model_schema_api_test.go b/api/api/model_schema_api_test.go new file mode 100644 index 000000000..e5f883107 --- /dev/null +++ b/api/api/model_schema_api_test.go @@ -0,0 +1,706 @@ +package api + +import ( + "encoding/json" + "fmt" + "net/http" + "testing" + + "github.com/caraml-dev/merlin/models" + "github.com/caraml-dev/merlin/pkg/errors" + internalValidator "github.com/caraml-dev/merlin/pkg/validator" + "github.com/caraml-dev/merlin/service/mocks" + "github.com/stretchr/testify/mock" + "github.com/stretchr/testify/require" +) + +func TestModelSchemaController_GetAllSchemas(t *testing.T) { + tests := []struct { + desc string + vars map[string]string + modelSchemaService func() *mocks.ModelSchemaService + expected *Response + }{ + { + desc: "Should success get all schemas", + vars: map[string]string{ + "model_id": "1", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("List", mock.Anything, models.ID(1)).Return([]*models.ModelSchema{ + { + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + { + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, + }, nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusOK, + data: []*models.ModelSchema{ + { + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + { + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, + }, + }, + }, + { + desc: "No schemas found", + vars: map[string]string{ + "model_id": "1", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("List", mock.Anything, models.ID(1)).Return(nil, errors.NewNotFoundError("model schema with model id 1 is not found")) + return mockSvc + }, + expected: &Response{ + code: http.StatusNotFound, + data: Error{Message: "Model schemas not found: not found: model schema with model id 1 is not found"}, + }, + }, + { + desc: "Error fetching the schemas", + vars: map[string]string{ + "model_id": "1", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("List", mock.Anything, models.ID(1)).Return(nil, fmt.Errorf("peer connection reset")) + return mockSvc + }, + expected: &Response{ + code: http.StatusInternalServerError, + data: Error{Message: "Error get All schemas with model id: 1 with error: peer connection reset"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + ctrl := &ModelSchemaController{ + AppContext: &AppContext{ + ModelSchemaService: tt.modelSchemaService(), + }, + } + resp := ctrl.GetAllSchemas(&http.Request{}, tt.vars, nil) + assertEqualResponses(t, tt.expected, resp) + }) + } +} + +func TestModelSchemaController_GetSchema(t *testing.T) { + tests := []struct { + desc string + vars map[string]string + modelSchemaService func() *mocks.ModelSchemaService + expected *Response + }{ + { + desc: "Should success get schema", + vars: map[string]string{ + "model_id": "1", + "schema_id": "2", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("FindByID", mock.Anything, models.ID(2), models.ID(1)).Return(&models.ModelSchema{ + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusOK, + data: &models.ModelSchema{ + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + }, + { + desc: "No schemas found", + vars: map[string]string{ + "model_id": "1", + "schema_id": "2", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("FindByID", mock.Anything, models.ID(2), models.ID(1)).Return(nil, errors.NewNotFoundError("model schema with id 2 is not found")) + return mockSvc + }, + expected: &Response{ + code: http.StatusNotFound, + data: Error{Message: "Model schema with id: 2 not found: not found: model schema with id 2 is not found"}, + }, + }, + { + desc: "Error fetching the schemas", + vars: map[string]string{ + "model_id": "1", + "schema_id": "2", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("FindByID", mock.Anything, models.ID(2), models.ID(1)).Return(nil, fmt.Errorf("peer connection reset")) + return mockSvc + }, + expected: &Response{ + code: http.StatusInternalServerError, + data: Error{Message: "Error get schema with id: 2, model id: 1 and error: peer connection reset"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + ctrl := &ModelSchemaController{ + AppContext: &AppContext{ + ModelSchemaService: tt.modelSchemaService(), + }, + } + resp := ctrl.GetSchema(&http.Request{}, tt.vars, nil) + assertEqualResponses(t, tt.expected, resp) + }) + } +} + +func TestModelSchemaController_CreateOrUpdateSchema(t *testing.T) { + tests := []struct { + desc string + vars map[string]string + body []byte + modelSchemaService func() *mocks.ModelSchemaService + expected *Response + }{ + { + desc: "success create ranking schema", + vars: map[string]string{ + "model_id": "1", + }, + body: []byte(`{ + "spec": { + "prediction_id_column":"prediction_id", + "tag_columns": ["tags"], + "feature_types": { + "featureA": "float64", + "featureB": "int64", + "featureC": "boolean" + }, + "model_prediction_output": { + "prediction_group_id_column": "session_id", + "rank_score_column": "score", + "relevance_score": "relevance_score", + "output_class": "RankingOutput" + } + } + }`), + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }, + }, + }).Return(&models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }, + }, + }, nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusOK, + data: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }, + }, + }, + }, + }, + { + desc: "success create binary classification schema", + vars: map[string]string{ + "model_id": "1", + }, + body: []byte(`{ + "spec": { + "prediction_id_column":"prediction_id", + "tag_columns": ["tags"], + "feature_types": { + "featureA": "float64", + "featureB": "int64", + "featureC": "boolean" + }, + "model_prediction_output": { + "actual_label_column": "actual_label", + "negative_class_label": "negative", + "prediction_score_column": "prediction_score", + "prediction_label_column": "prediction_label", + "positive_class_label": "positive", + "output_class": "BinaryClassificationOutput" + } + } + }`), + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + PositiveClassLabel: "positive", + OutputClass: models.BinaryClassification, + }, + }, + }, + }).Return(&models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + PositiveClassLabel: "positive", + OutputClass: models.BinaryClassification, + }, + }, + }, + }, nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusOK, + data: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + PositiveClassLabel: "positive", + OutputClass: models.BinaryClassification, + }, + }, + }, + }, + }, + }, + { + desc: "success create regression schema", + vars: map[string]string{ + "model_id": "1", + }, + body: []byte(`{ + "spec": { + "prediction_id_column":"prediction_id", + "tag_columns": ["tags"], + "feature_types": { + "featureA": "float64", + "featureB": "int64", + "featureC": "boolean" + }, + "model_prediction_output": { + "prediction_score_column": "prediction_score", + "actual_score_column": "actual_score", + "output_class": "RegressionOutput" + } + } + }`), + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RegressionOutput: &models.RegressionOutput{ + PredictionScoreColumn: "prediction_score", + ActualScoreColumn: "actual_score", + OutputClass: models.Regression, + }, + }, + }, + }).Return(&models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RegressionOutput: &models.RegressionOutput{ + PredictionScoreColumn: "prediction_score", + ActualScoreColumn: "actual_score", + OutputClass: models.Regression, + }, + }, + }, + }, nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusOK, + data: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RegressionOutput: &models.RegressionOutput{ + PredictionScoreColumn: "prediction_score", + ActualScoreColumn: "actual_score", + OutputClass: models.Regression, + }, + }, + }, + }, + }, + }, + { + desc: "fail to save schema", + vars: map[string]string{ + "model_id": "1", + }, + body: []byte(`{ + "spec": { + "prediction_id_column":"prediction_id", + "tag_columns": ["tags"], + "feature_types": { + "featureA": "float64", + "featureB": "int64", + "featureC": "boolean" + }, + "model_prediction_output": { + "prediction_group_id_column": "session_id", + "rank_score_column": "score", + "relevance_score": "relevance_score", + "output_class": "RankingOutput" + } + } + }`), + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }, + }, + }).Return(nil, fmt.Errorf("peer connection is reset")) + return mockSvc + }, + expected: &Response{ + code: http.StatusInternalServerError, + data: Error{Message: "Error save model schema: peer connection is reset"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + ctrl := &ModelSchemaController{ + AppContext: &AppContext{ + ModelSchemaService: tt.modelSchemaService(), + }, + } + var modelSchema *models.ModelSchema + err := json.Unmarshal(tt.body, &modelSchema) + require.NoError(t, err) + + validate, _ := internalValidator.NewValidator() + err = validate.Struct(modelSchema) + require.NoError(t, err) + + resp := ctrl.CreateOrUpdateSchema(&http.Request{}, tt.vars, modelSchema) + assertEqualResponses(t, tt.expected, resp) + }) + } +} + +func Benchmark_Unmarshal(b *testing.B) { + data := []byte(` { + "prediction_id_column":"prediction_id", + "tag_columns": ["tags"], + "feature_types": { + "featureA": "float64", + "featureB": "int64", + "featureC": "boolean" + }, + "model_prediction_output": { + "actual_label_column": "actual_label", + "negative_class_label": "negative", + "prediction_score_column": "prediction_score", + "prediction_label_column": "prediction_label", + "positive_class_label": "positive", + "output_class": "BinaryClassificationOutput" + } + }`) + for i := 0; i < b.N; i++ { + var schemaSpec models.SchemaSpec + _ = json.Unmarshal(data, &schemaSpec) + } +} + +func TestModelSchemaController_DeleteSchema(t *testing.T) { + tests := []struct { + desc string + vars map[string]string + modelSchemaService func() *mocks.ModelSchemaService + expected *Response + }{ + { + desc: "Should success get schema", + vars: map[string]string{ + "model_id": "1", + "schema_id": "2", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Delete", mock.Anything, &models.ModelSchema{ID: models.ID(2), ModelID: models.ID(1)}).Return(nil) + return mockSvc + }, + expected: &Response{ + code: http.StatusNoContent, + }, + }, + { + desc: "Error deleting the schema", + vars: map[string]string{ + "model_id": "1", + "schema_id": "2", + }, + modelSchemaService: func() *mocks.ModelSchemaService { + mockSvc := &mocks.ModelSchemaService{} + mockSvc.On("Delete", mock.Anything, &models.ModelSchema{ID: models.ID(2), ModelID: models.ID(1)}).Return(fmt.Errorf("peer connection reset")) + return mockSvc + }, + expected: &Response{ + code: http.StatusInternalServerError, + data: Error{Message: "Error delete model schema: peer connection reset"}, + }, + }, + } + for _, tt := range tests { + t.Run(tt.desc, func(t *testing.T) { + ctrl := &ModelSchemaController{ + AppContext: &AppContext{ + ModelSchemaService: tt.modelSchemaService(), + }, + } + resp := ctrl.DeleteSchema(&http.Request{}, tt.vars, nil) + assertEqualResponses(t, tt.expected, resp) + }) + } +} diff --git a/api/api/router.go b/api/api/router.go index 45aad0f9d..86281c5a1 100644 --- a/api/api/router.go +++ b/api/api/router.go @@ -66,6 +66,7 @@ type AppContext struct { ModelEndpointAlertService service.ModelEndpointAlertService TransformerService service.TransformerService MlflowDeleteService mlflowDelete.Service + ModelSchemaService service.ModelSchemaService AuthorizationEnabled bool FeatureToggleConfig config.FeatureToggleConfig @@ -167,6 +168,7 @@ func NewRouter(appCtx AppContext) (*mux.Router, error) { secretController := SecretsController{&appCtx} alertsController := AlertsController{&appCtx} transformerController := TransformerController{&appCtx} + modelSchemaController := ModelSchemaController{&appCtx} routes := []Route{ // Environment API @@ -226,6 +228,12 @@ func NewRouter(appCtx AppContext) (*mux.Router, error) { // Standard Transformer Simulation API {http.MethodPost, "/standard_transformer/simulate", models.TransformerSimulation{}, transformerController.SimulateTransformer, "SimulateTransformer"}, + + // Model Schema API + {http.MethodGet, "/models/{model_id:[0-9]+}/schemas", models.ModelSchema{}, modelSchemaController.GetAllSchemas, "GetAllSchemas"}, + {http.MethodGet, "/models/{model_id:[0-9]+}/schemas/{schema_id:[0-9]+}", models.ModelSchema{}, modelSchemaController.GetSchema, "GetSchemaDetail"}, + {http.MethodPut, "/models/{model_id:[0-9]+}/schemas", models.ModelSchema{}, modelSchemaController.CreateOrUpdateSchema, "CreateOrUpdateSchema"}, + {http.MethodDelete, "/models/{model_id:[0-9]+}/schemas/{schema_id:[0-9]+}", models.ModelSchema{}, modelSchemaController.DeleteSchema, "DeleteSchema"}, } if appCtx.FeatureToggleConfig.ModelDeletionConfig.Enabled { diff --git a/api/api/version_endpoints_api.go b/api/api/version_endpoints_api.go index 10da316cf..84e0e57a3 100644 --- a/api/api/version_endpoints_api.go +++ b/api/api/version_endpoints_api.go @@ -171,7 +171,7 @@ func (c *EndpointsController) CreateEndpoint(r *http.Request, vars map[string]st endpoint, err := c.EndpointsService.DeployEndpoint(ctx, env, model, version, newEndpoint) if err != nil { - if errors.Is(err, merror.InvalidInputError) { + if errors.Is(err, merror.ErrInvalidInput) { return BadRequest(fmt.Sprintf("Unable to process model version input: %v", err)) } return InternalServerError(fmt.Sprintf("Unable to deploy model version: %v", err)) @@ -236,7 +236,7 @@ func (c *EndpointsController) UpdateEndpoint(r *http.Request, vars map[string]st endpoint, err = c.EndpointsService.DeployEndpoint(ctx, env, model, version, newEndpoint) if err != nil { - if errors.Is(err, merror.InvalidInputError) { + if errors.Is(err, merror.ErrInvalidInput) { return BadRequest(fmt.Sprintf("Unable to deploy model version: %v", err)) } diff --git a/api/client/api_alert.go b/api/client/api_alert.go deleted file mode 100644 index a502ad15a..000000000 --- a/api/client/api_alert.go +++ /dev/null @@ -1,512 +0,0 @@ -/* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ -package client - -import ( - "context" - "fmt" - "io/ioutil" - "net/http" - "net/url" - "strings" - - "github.com/antihax/optional" -) - -// Linger please -var ( - _ context.Context -) - -type AlertApiService service - -/* -AlertApiService Lists teams for alert notification channel. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - -@return []string -*/ -func (a *AlertApiService) AlertsTeamsGet(ctx context.Context) ([]string, *http.Response, error) { - var ( - localVarHttpMethod = strings.ToUpper("Get") - localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue []string - ) - - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/alerts/teams" - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHttpContentTypes := []string{} - - // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - - // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} - - // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - if ctx != nil { - // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key - } - localVarHeaderParams["Authorization"] = key - - } - } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() - if err != nil { - return localVarReturnValue, localVarHttpResponse, err - } - - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err - } - } - - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ - body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []string - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr - } - - return localVarReturnValue, localVarHttpResponse, nil -} - -/* -AlertApiService Lists alerts for given model. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - -@return []ModelEndpointAlert -*/ -func (a *AlertApiService) ModelsModelIdAlertsGet(ctx context.Context, modelId int32) ([]ModelEndpointAlert, *http.Response, error) { - var ( - localVarHttpMethod = strings.ToUpper("Get") - localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue []ModelEndpointAlert - ) - - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/alerts" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHttpContentTypes := []string{} - - // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - - // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} - - // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - if ctx != nil { - // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key - } - localVarHeaderParams["Authorization"] = key - - } - } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() - if err != nil { - return localVarReturnValue, localVarHttpResponse, err - } - - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err - } - } - - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ - body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []ModelEndpointAlert - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr - } - - return localVarReturnValue, localVarHttpResponse, nil -} - -/* -AlertApiService Gets alert for given model endpoint. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param modelEndpointId - -@return ModelEndpointAlert -*/ -func (a *AlertApiService) ModelsModelIdEndpointsModelEndpointIdAlertGet(ctx context.Context, modelId int32, modelEndpointId string) (ModelEndpointAlert, *http.Response, error) { - var ( - localVarHttpMethod = strings.ToUpper("Get") - localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue ModelEndpointAlert - ) - - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHttpContentTypes := []string{} - - // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - - // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} - - // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - if ctx != nil { - // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key - } - localVarHeaderParams["Authorization"] = key - - } - } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return localVarReturnValue, nil, err - } - - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() - if err != nil { - return localVarReturnValue, localVarHttpResponse, err - } - - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err - } - } - - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ - body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v ModelEndpointAlert - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr - } - - return localVarReturnValue, localVarHttpResponse, nil -} - -/* -AlertApiService Creates alert for given model endpoint. - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param modelEndpointId - * @param optional nil or *AlertApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of ModelEndpointAlert) - - -*/ - -type AlertApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts struct { - Body optional.Interface -} - -func (a *AlertApiService) ModelsModelIdEndpointsModelEndpointIdAlertPost(ctx context.Context, modelId int32, modelEndpointId string, localVarOptionals *AlertApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts) (*http.Response, error) { - var ( - localVarHttpMethod = strings.ToUpper("Post") - localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - ) - - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} - - // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - - // to determine the Accept header - localVarHttpHeaderAccepts := []string{} - - // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { - // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key - } - localVarHeaderParams["Authorization"] = key - - } - } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return nil, err - } - - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() - if err != nil { - return localVarHttpResponse, err - } - - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ - body: localVarBody, - error: localVarHttpResponse.Status, - } - return localVarHttpResponse, newErr - } - - return localVarHttpResponse, nil -} - -/* -AlertApiService Creates alert for given model endpoint. - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param modelEndpointId - * @param optional nil or *AlertApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts - Optional Parameters: - * @param "Body" (optional.Interface of ModelEndpointAlert) - - -*/ - -type AlertApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts struct { - Body optional.Interface -} - -func (a *AlertApiService) ModelsModelIdEndpointsModelEndpointIdAlertPut(ctx context.Context, modelId int32, modelEndpointId string, localVarOptionals *AlertApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts) (*http.Response, error) { - var ( - localVarHttpMethod = strings.ToUpper("Put") - localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - ) - - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) - - localVarHeaderParams := make(map[string]string) - localVarQueryParams := url.Values{} - localVarFormParams := url.Values{} - - // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} - - // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType - } - - // to determine the Accept header - localVarHttpHeaderAccepts := []string{} - - // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept - } - // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { - // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key - } - localVarHeaderParams["Authorization"] = key - - } - } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) - if err != nil { - return nil, err - } - - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err - } - - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() - if err != nil { - return localVarHttpResponse, err - } - - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ - body: localVarBody, - error: localVarHttpResponse.Status, - } - return localVarHttpResponse, newErr - } - - return localVarHttpResponse, nil -} diff --git a/api/client/api_endpoint.go b/api/client/api_endpoint.go index dc7c9f960..cf5a2ecd0 100644 --- a/api/client/api_endpoint.go +++ b/api/client/api_endpoint.go @@ -1,644 +1,763 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// EndpointAPIService EndpointAPI service +type EndpointAPIService service -type EndpointApiService service +type ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 + endpointId string +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest) Execute() (*Container, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetExecute(r) +} /* -EndpointApiService Get all container belong to a version endpoint - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param endpointId +ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGet Get all container belong to a version endpoint -@return Container + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param endpointId + @return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest */ -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGet(ctx context.Context, modelId int32, versionId int32, endpointId string) (Container, *http.Response, error) { +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGet(ctx context.Context, modelId int32, versionId int32, endpointId string) ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest { + return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + endpointId: endpointId, + } +} + +// Execute executes the request +// +// @return Container +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetExecute(r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGetRequest) (*Container, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Container + formFiles []formFile + localVarReturnValue *Container ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}/containers" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", fmt.Sprintf("%v", endpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointEndpointIdContainersGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}/containers" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", url.PathEscape(parameterValueToString(r.endpointId, "endpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v Container - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 + endpointId string +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteExecute(r) } /* -EndpointApiService Undeploy the specified model version deployment - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param endpointId +ModelsModelIdVersionsVersionIdEndpointEndpointIdDelete Undeploy the specified model version deployment + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param endpointId + @return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest */ -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointEndpointIdDelete(ctx context.Context, modelId int32, versionId int32, endpointId string) (*http.Response, error) { +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdDelete(ctx context.Context, modelId int32, versionId int32, endpointId string) ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest { + return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + endpointId: endpointId, + } +} + +// Execute executes the request +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteExecute(r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdDeleteRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Delete") + localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", fmt.Sprintf("%v", endpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointEndpointIdDelete") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", url.PathEscape(parameterValueToString(r.endpointId, "endpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 + endpointId string +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest) Execute() (*VersionEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointEndpointIdGetExecute(r) } /* -EndpointApiService Get version endpoint resource - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param endpointId +ModelsModelIdVersionsVersionIdEndpointEndpointIdGet Get version endpoint resource -@return VersionEndpoint + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param endpointId + @return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest */ -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointEndpointIdGet(ctx context.Context, modelId int32, versionId int32, endpointId string) (VersionEndpoint, *http.Response, error) { +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdGet(ctx context.Context, modelId int32, versionId int32, endpointId string) ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest { + return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + endpointId: endpointId, + } +} + +// Execute executes the request +// +// @return VersionEndpoint +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdGetExecute(r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdGetRequest) (*VersionEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue VersionEndpoint + formFiles []formFile + localVarReturnValue *VersionEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", fmt.Sprintf("%v", endpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointEndpointIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", url.PathEscape(parameterValueToString(r.endpointId, "endpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v VersionEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 + endpointId string + body *VersionEndpoint +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest) Body(body VersionEndpoint) ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest) Execute() (*VersionEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointEndpointIdPutExecute(r) } /* -EndpointApiService Modify version endpoint, this API will redeploy the associated deployment - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param versionId - * @param endpointId - * @param optional nil or *EndpointApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutOpts - Optional Parameters: - * @param "Body" (optional.Interface of VersionEndpoint) - -@return VersionEndpoint -*/ +ModelsModelIdVersionsVersionIdEndpointEndpointIdPut Modify version endpoint, this API will redeploy the associated deployment -type EndpointApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param endpointId + @return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest +*/ +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdPut(ctx context.Context, modelId int32, versionId int32, endpointId string) ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest { + return ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + endpointId: endpointId, + } } -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointEndpointIdPut(ctx context.Context, modelId int32, versionId int32, endpointId string, localVarOptionals *EndpointApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutOpts) (VersionEndpoint, *http.Response, error) { +// Execute executes the request +// +// @return VersionEndpoint +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointEndpointIdPutExecute(r ApiModelsModelIdVersionsVersionIdEndpointEndpointIdPutRequest) (*VersionEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Put") + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue VersionEndpoint + formFiles []formFile + localVarReturnValue *VersionEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", fmt.Sprintf("%v", endpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointEndpointIdPut") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"endpoint_id"+"}", url.PathEscape(parameterValueToString(r.endpointId, "endpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v VersionEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdEndpointGetRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointGetRequest) Execute() ([]VersionEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointGetExecute(r) } /* -EndpointApiService List all endpoint of a model version - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId +ModelsModelIdVersionsVersionIdEndpointGet List all endpoint of a model version -@return []VersionEndpoint + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdEndpointGetRequest */ -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointGet(ctx context.Context, modelId int32, versionId int32) ([]VersionEndpoint, *http.Response, error) { +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointGet(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdEndpointGetRequest { + return ApiModelsModelIdVersionsVersionIdEndpointGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } +} + +// Execute executes the request +// +// @return []VersionEndpoint +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointGetExecute(r ApiModelsModelIdVersionsVersionIdEndpointGetRequest) ([]VersionEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []VersionEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v []VersionEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdEndpointPostRequest struct { + ctx context.Context + ApiService *EndpointAPIService + modelId int32 + versionId int32 + body *VersionEndpoint +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointPostRequest) Body(body VersionEndpoint) ApiModelsModelIdVersionsVersionIdEndpointPostRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdVersionsVersionIdEndpointPostRequest) Execute() (*VersionEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdEndpointPostExecute(r) } /* -EndpointApiService Deploy specific version of the models - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param versionId - * @param optional nil or *EndpointApiModelsModelIdVersionsVersionIdEndpointPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of VersionEndpoint) - -@return VersionEndpoint -*/ +ModelsModelIdVersionsVersionIdEndpointPost Deploy specific version of the models -type EndpointApiModelsModelIdVersionsVersionIdEndpointPostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdEndpointPostRequest +*/ +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointPost(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdEndpointPostRequest { + return ApiModelsModelIdVersionsVersionIdEndpointPostRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } } -func (a *EndpointApiService) ModelsModelIdVersionsVersionIdEndpointPost(ctx context.Context, modelId int32, versionId int32, localVarOptionals *EndpointApiModelsModelIdVersionsVersionIdEndpointPostOpts) (VersionEndpoint, *http.Response, error) { +// Execute executes the request +// +// @return VersionEndpoint +func (a *EndpointAPIService) ModelsModelIdVersionsVersionIdEndpointPostExecute(r ApiModelsModelIdVersionsVersionIdEndpointPostRequest) (*VersionEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue VersionEndpoint + formFiles []formFile + localVarReturnValue *VersionEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/endpoint" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EndpointAPIService.ModelsModelIdVersionsVersionIdEndpointPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/endpoint" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 201 { - var v VersionEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_environment.go b/api/client/api_environment.go index 98183eee2..fee604679 100644 --- a/api/client/api_environment.go +++ b/api/client/api_environment.go @@ -1,133 +1,145 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "io/ioutil" + "io" "net/http" "net/url" - "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// EnvironmentAPIService EnvironmentAPI service +type EnvironmentAPIService service + +type ApiEnvironmentsGetRequest struct { + ctx context.Context + ApiService *EnvironmentAPIService + name *string +} -type EnvironmentApiService service +func (r ApiEnvironmentsGetRequest) Name(name string) ApiEnvironmentsGetRequest { + r.name = &name + return r +} + +func (r ApiEnvironmentsGetRequest) Execute() ([]Environment, *http.Response, error) { + return r.ApiService.EnvironmentsGetExecute(r) +} /* -EnvironmentApiService List available environment -Environment can be filtered by optional `name` parameter - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param optional nil or *EnvironmentApiEnvironmentsGetOpts - Optional Parameters: - * @param "Name" (optional.String) - -@return []Environment -*/ +EnvironmentsGet List available environment + +Environment can be filtered by optional `name` parameter -type EnvironmentApiEnvironmentsGetOpts struct { - Name optional.String + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiEnvironmentsGetRequest +*/ +func (a *EnvironmentAPIService) EnvironmentsGet(ctx context.Context) ApiEnvironmentsGetRequest { + return ApiEnvironmentsGetRequest{ + ApiService: a, + ctx: ctx, + } } -func (a *EnvironmentApiService) EnvironmentsGet(ctx context.Context, localVarOptionals *EnvironmentApiEnvironmentsGetOpts) ([]Environment, *http.Response, error) { +// Execute executes the request +// +// @return []Environment +func (a *EnvironmentAPIService) EnvironmentsGetExecute(r ApiEnvironmentsGetRequest) ([]Environment, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Environment ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/environments" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "EnvironmentAPIService.EnvironmentsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/environments" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Name.IsSet() { - localVarQueryParams.Add("name", parameterToString(localVarOptionals.Name.Value(), "")) + if r.name != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "name", r.name, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []Environment - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_log.go b/api/client/api_log.go index 4a07ebf66..4cc9adabe 100644 --- a/api/client/api_log.go +++ b/api/client/api_log.go @@ -1,184 +1,278 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "io/ioutil" + "io" "net/http" "net/url" - "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// LogAPIService LogAPI service +type LogAPIService service -type LogApiService service +type ApiLogsGetRequest struct { + ctx context.Context + ApiService *LogAPIService + cluster *string + namespace *string + componentType *string + projectName *string + modelId *string + modelName *string + versionId *string + predictionJobId *string + containerName *string + prefix *string + follow *string + previous *string + sinceSeconds *string + sinceTime *string + timestamps *string + tailLines *string + limitBytes *string +} + +func (r ApiLogsGetRequest) Cluster(cluster string) ApiLogsGetRequest { + r.cluster = &cluster + return r +} + +func (r ApiLogsGetRequest) Namespace(namespace string) ApiLogsGetRequest { + r.namespace = &namespace + return r +} + +func (r ApiLogsGetRequest) ComponentType(componentType string) ApiLogsGetRequest { + r.componentType = &componentType + return r +} + +func (r ApiLogsGetRequest) ProjectName(projectName string) ApiLogsGetRequest { + r.projectName = &projectName + return r +} + +func (r ApiLogsGetRequest) ModelId(modelId string) ApiLogsGetRequest { + r.modelId = &modelId + return r +} + +func (r ApiLogsGetRequest) ModelName(modelName string) ApiLogsGetRequest { + r.modelName = &modelName + return r +} + +func (r ApiLogsGetRequest) VersionId(versionId string) ApiLogsGetRequest { + r.versionId = &versionId + return r +} + +func (r ApiLogsGetRequest) PredictionJobId(predictionJobId string) ApiLogsGetRequest { + r.predictionJobId = &predictionJobId + return r +} + +func (r ApiLogsGetRequest) ContainerName(containerName string) ApiLogsGetRequest { + r.containerName = &containerName + return r +} + +func (r ApiLogsGetRequest) Prefix(prefix string) ApiLogsGetRequest { + r.prefix = &prefix + return r +} + +func (r ApiLogsGetRequest) Follow(follow string) ApiLogsGetRequest { + r.follow = &follow + return r +} + +func (r ApiLogsGetRequest) Previous(previous string) ApiLogsGetRequest { + r.previous = &previous + return r +} + +func (r ApiLogsGetRequest) SinceSeconds(sinceSeconds string) ApiLogsGetRequest { + r.sinceSeconds = &sinceSeconds + return r +} + +func (r ApiLogsGetRequest) SinceTime(sinceTime string) ApiLogsGetRequest { + r.sinceTime = &sinceTime + return r +} + +func (r ApiLogsGetRequest) Timestamps(timestamps string) ApiLogsGetRequest { + r.timestamps = ×tamps + return r +} + +func (r ApiLogsGetRequest) TailLines(tailLines string) ApiLogsGetRequest { + r.tailLines = &tailLines + return r +} + +func (r ApiLogsGetRequest) LimitBytes(limitBytes string) ApiLogsGetRequest { + r.limitBytes = &limitBytes + return r +} + +func (r ApiLogsGetRequest) Execute() (*http.Response, error) { + return r.ApiService.LogsGetExecute(r) +} /* -LogApiService Retrieve log from a container - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param cluster - * @param namespace - * @param componentType - * @param optional nil or *LogApiLogsGetOpts - Optional Parameters: - * @param "ProjectName" (optional.String) - - * @param "ModelId" (optional.String) - - * @param "ModelName" (optional.String) - - * @param "VersionId" (optional.String) - - * @param "PredictionJobId" (optional.String) - - * @param "ContainerName" (optional.String) - - * @param "Prefix" (optional.String) - - * @param "Follow" (optional.String) - - * @param "Previous" (optional.String) - - * @param "SinceSeconds" (optional.String) - - * @param "SinceTime" (optional.String) - - * @param "Timestamps" (optional.String) - - * @param "TailLines" (optional.String) - - * @param "LimitBytes" (optional.String) - +LogsGet Retrieve log from a container + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiLogsGetRequest */ +func (a *LogAPIService) LogsGet(ctx context.Context) ApiLogsGetRequest { + return ApiLogsGetRequest{ + ApiService: a, + ctx: ctx, + } +} -type LogApiLogsGetOpts struct { - ProjectName optional.String - ModelId optional.String - ModelName optional.String - VersionId optional.String - PredictionJobId optional.String - ContainerName optional.String - Prefix optional.String - Follow optional.String - Previous optional.String - SinceSeconds optional.String - SinceTime optional.String - Timestamps optional.String - TailLines optional.String - LimitBytes optional.String -} - -func (a *LogApiService) LogsGet(ctx context.Context, cluster string, namespace string, componentType string, localVarOptionals *LogApiLogsGetOpts) (*http.Response, error) { +// Execute executes the request +func (a *LogAPIService) LogsGetExecute(r ApiLogsGetRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/logs" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "LogAPIService.LogsGet") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/logs" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.cluster == nil { + return nil, reportError("cluster is required and must be specified") + } + if r.namespace == nil { + return nil, reportError("namespace is required and must be specified") + } + if r.componentType == nil { + return nil, reportError("componentType is required and must be specified") + } - if localVarOptionals != nil && localVarOptionals.ProjectName.IsSet() { - localVarQueryParams.Add("project_name", parameterToString(localVarOptionals.ProjectName.Value(), "")) + if r.projectName != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "project_name", r.projectName, "") } - if localVarOptionals != nil && localVarOptionals.ModelId.IsSet() { - localVarQueryParams.Add("model_id", parameterToString(localVarOptionals.ModelId.Value(), "")) + if r.modelId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "model_id", r.modelId, "") } - if localVarOptionals != nil && localVarOptionals.ModelName.IsSet() { - localVarQueryParams.Add("model_name", parameterToString(localVarOptionals.ModelName.Value(), "")) + if r.modelName != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "model_name", r.modelName, "") } - if localVarOptionals != nil && localVarOptionals.VersionId.IsSet() { - localVarQueryParams.Add("version_id", parameterToString(localVarOptionals.VersionId.Value(), "")) + if r.versionId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "version_id", r.versionId, "") } - if localVarOptionals != nil && localVarOptionals.PredictionJobId.IsSet() { - localVarQueryParams.Add("prediction_job_id", parameterToString(localVarOptionals.PredictionJobId.Value(), "")) + if r.predictionJobId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "prediction_job_id", r.predictionJobId, "") } - localVarQueryParams.Add("cluster", parameterToString(cluster, "")) - localVarQueryParams.Add("namespace", parameterToString(namespace, "")) - localVarQueryParams.Add("component_type", parameterToString(componentType, "")) - if localVarOptionals != nil && localVarOptionals.ContainerName.IsSet() { - localVarQueryParams.Add("container_name", parameterToString(localVarOptionals.ContainerName.Value(), "")) + parameterAddToHeaderOrQuery(localVarQueryParams, "cluster", r.cluster, "") + parameterAddToHeaderOrQuery(localVarQueryParams, "namespace", r.namespace, "") + parameterAddToHeaderOrQuery(localVarQueryParams, "component_type", r.componentType, "") + if r.containerName != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "container_name", r.containerName, "") } - if localVarOptionals != nil && localVarOptionals.Prefix.IsSet() { - localVarQueryParams.Add("prefix", parameterToString(localVarOptionals.Prefix.Value(), "")) + if r.prefix != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "prefix", r.prefix, "") } - if localVarOptionals != nil && localVarOptionals.Follow.IsSet() { - localVarQueryParams.Add("follow", parameterToString(localVarOptionals.Follow.Value(), "")) + if r.follow != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "follow", r.follow, "") } - if localVarOptionals != nil && localVarOptionals.Previous.IsSet() { - localVarQueryParams.Add("previous", parameterToString(localVarOptionals.Previous.Value(), "")) + if r.previous != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "previous", r.previous, "") } - if localVarOptionals != nil && localVarOptionals.SinceSeconds.IsSet() { - localVarQueryParams.Add("since_seconds", parameterToString(localVarOptionals.SinceSeconds.Value(), "")) + if r.sinceSeconds != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "since_seconds", r.sinceSeconds, "") } - if localVarOptionals != nil && localVarOptionals.SinceTime.IsSet() { - localVarQueryParams.Add("since_time", parameterToString(localVarOptionals.SinceTime.Value(), "")) + if r.sinceTime != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "since_time", r.sinceTime, "") } - if localVarOptionals != nil && localVarOptionals.Timestamps.IsSet() { - localVarQueryParams.Add("timestamps", parameterToString(localVarOptionals.Timestamps.Value(), "")) + if r.timestamps != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "timestamps", r.timestamps, "") } - if localVarOptionals != nil && localVarOptionals.TailLines.IsSet() { - localVarQueryParams.Add("tail_lines", parameterToString(localVarOptionals.TailLines.Value(), "")) + if r.tailLines != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "tail_lines", r.tailLines, "") } - if localVarOptionals != nil && localVarOptionals.LimitBytes.IsSet() { - localVarQueryParams.Add("limit_bytes", parameterToString(localVarOptionals.LimitBytes.Value(), "")) + if r.limitBytes != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "limit_bytes", r.limitBytes, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil } diff --git a/api/client/api_model_endpoints.go b/api/client/api_model_endpoints.go index 806d38b2d..5bbaeef17 100644 --- a/api/client/api_model_endpoints.go +++ b/api/client/api_model_endpoints.go @@ -1,630 +1,749 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// ModelEndpointsAPIService ModelEndpointsAPI service +type ModelEndpointsAPIService service -type ModelEndpointsApiService service +type ApiModelsModelIdEndpointsGetRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + modelId int32 +} + +func (r ApiModelsModelIdEndpointsGetRequest) Execute() ([]ModelEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsGetExecute(r) +} /* -ModelEndpointsApiService List model endpoint - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId +ModelsModelIdEndpointsGet List model endpoint -@return []ModelEndpoint + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdEndpointsGetRequest */ -func (a *ModelEndpointsApiService) ModelsModelIdEndpointsGet(ctx context.Context, modelId int32) ([]ModelEndpoint, *http.Response, error) { +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsGet(ctx context.Context, modelId int32) ApiModelsModelIdEndpointsGetRequest { + return ApiModelsModelIdEndpointsGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return []ModelEndpoint +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsGetExecute(r ApiModelsModelIdEndpointsGetRequest) ([]ModelEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []ModelEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ModelsModelIdEndpointsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v []ModelEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + modelId int32 + modelEndpointId int32 +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdDeleteExecute(r) } /* -ModelEndpointsApiService Stop serving traffic to the model endpoint, then delete it. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param modelEndpointId +ModelsModelIdEndpointsModelEndpointIdDelete Stop serving traffic to the model endpoint, then delete it. + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest */ -func (a *ModelEndpointsApiService) ModelsModelIdEndpointsModelEndpointIdDelete(ctx context.Context, modelId int32, modelEndpointId string) (*http.Response, error) { +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdDelete(ctx context.Context, modelId int32, modelEndpointId int32) ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest { + return ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } +} + +// Execute executes the request +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdDeleteExecute(r ApiModelsModelIdEndpointsModelEndpointIdDeleteRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Delete") + localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ModelsModelIdEndpointsModelEndpointIdDelete") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdGetRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + modelId int32 + modelEndpointId int32 +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdGetRequest) Execute() (*ModelEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdGetExecute(r) } /* -ModelEndpointsApiService Get a model endpoint - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param modelEndpointId +ModelsModelIdEndpointsModelEndpointIdGet Get a model endpoint -@return ModelEndpoint + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdGetRequest */ -func (a *ModelEndpointsApiService) ModelsModelIdEndpointsModelEndpointIdGet(ctx context.Context, modelId int32, modelEndpointId string) (ModelEndpoint, *http.Response, error) { +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdGet(ctx context.Context, modelId int32, modelEndpointId int32) ApiModelsModelIdEndpointsModelEndpointIdGetRequest { + return ApiModelsModelIdEndpointsModelEndpointIdGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } +} + +// Execute executes the request +// +// @return ModelEndpoint +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdGetExecute(r ApiModelsModelIdEndpointsModelEndpointIdGetRequest) (*ModelEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue ModelEndpoint + formFiles []formFile + localVarReturnValue *ModelEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ModelsModelIdEndpointsModelEndpointIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v ModelEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdPutRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + modelId int32 + modelEndpointId int32 + body *ModelEndpoint +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdPutRequest) Body(body ModelEndpoint) ApiModelsModelIdEndpointsModelEndpointIdPutRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdPutRequest) Execute() (*ModelEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdPutExecute(r) } /* -ModelEndpointsApiService Update model endpoint data. Mainly used to update its rule. - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param modelEndpointId - * @param optional nil or *ModelEndpointsApiModelsModelIdEndpointsModelEndpointIdPutOpts - Optional Parameters: - * @param "Body" (optional.Interface of ModelEndpoint) - -@return ModelEndpoint -*/ +ModelsModelIdEndpointsModelEndpointIdPut Update model endpoint data. Mainly used to update its rule. -type ModelEndpointsApiModelsModelIdEndpointsModelEndpointIdPutOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdPutRequest +*/ +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdPut(ctx context.Context, modelId int32, modelEndpointId int32) ApiModelsModelIdEndpointsModelEndpointIdPutRequest { + return ApiModelsModelIdEndpointsModelEndpointIdPutRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } } -func (a *ModelEndpointsApiService) ModelsModelIdEndpointsModelEndpointIdPut(ctx context.Context, modelId int32, modelEndpointId string, localVarOptionals *ModelEndpointsApiModelsModelIdEndpointsModelEndpointIdPutOpts) (ModelEndpoint, *http.Response, error) { +// Execute executes the request +// +// @return ModelEndpoint +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsModelEndpointIdPutExecute(r ApiModelsModelIdEndpointsModelEndpointIdPutRequest) (*ModelEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Put") + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue ModelEndpoint + formFiles []formFile + localVarReturnValue *ModelEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ModelsModelIdEndpointsModelEndpointIdPut") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v ModelEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsPostRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + modelId int32 + body *ModelEndpoint +} + +// Model endpoint object that has to be added +func (r ApiModelsModelIdEndpointsPostRequest) Body(body ModelEndpoint) ApiModelsModelIdEndpointsPostRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdEndpointsPostRequest) Execute() (*ModelEndpoint, *http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsPostExecute(r) } /* -ModelEndpointsApiService Create a model endpoint - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param body Model endpoint object that has to be added - - @param modelId +ModelsModelIdEndpointsPost Create a model endpoint -@return ModelEndpoint + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdEndpointsPostRequest */ -func (a *ModelEndpointsApiService) ModelsModelIdEndpointsPost(ctx context.Context, body ModelEndpoint, modelId int32) (ModelEndpoint, *http.Response, error) { +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsPost(ctx context.Context, modelId int32) ApiModelsModelIdEndpointsPostRequest { + return ApiModelsModelIdEndpointsPostRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return ModelEndpoint +func (a *ModelEndpointsAPIService) ModelsModelIdEndpointsPostExecute(r ApiModelsModelIdEndpointsPostRequest) (*ModelEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue ModelEndpoint + formFiles []formFile + localVarReturnValue *ModelEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ModelsModelIdEndpointsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.body == nil { + return localVarReturnValue, nil, reportError("body is required and must be specified") + } // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = &body - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v ModelEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdModelEndpointsGetRequest struct { + ctx context.Context + ApiService *ModelEndpointsAPIService + projectId int32 + region *string +} + +// Filter list of model endpoints by specific environment's `region` +func (r ApiProjectsProjectIdModelEndpointsGetRequest) Region(region string) ApiProjectsProjectIdModelEndpointsGetRequest { + r.region = ®ion + return r +} + +func (r ApiProjectsProjectIdModelEndpointsGetRequest) Execute() ([]ModelEndpoint, *http.Response, error) { + return r.ApiService.ProjectsProjectIdModelEndpointsGetExecute(r) } /* -ModelEndpointsApiService List existing model endpoints for all models in particular project - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId Filter list of model endpoints by specific `project_id` - * @param optional nil or *ModelEndpointsApiProjectsProjectIdModelEndpointsGetOpts - Optional Parameters: - * @param "Region" (optional.String) - Filter list of model endpoints by specific environment's `region` -@return []ModelEndpoint -*/ +ProjectsProjectIdModelEndpointsGet List existing model endpoints for all models in particular project -type ModelEndpointsApiProjectsProjectIdModelEndpointsGetOpts struct { - Region optional.String + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId Filter list of model endpoints by specific `project_id` + @return ApiProjectsProjectIdModelEndpointsGetRequest +*/ +func (a *ModelEndpointsAPIService) ProjectsProjectIdModelEndpointsGet(ctx context.Context, projectId int32) ApiProjectsProjectIdModelEndpointsGetRequest { + return ApiProjectsProjectIdModelEndpointsGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } } -func (a *ModelEndpointsApiService) ProjectsProjectIdModelEndpointsGet(ctx context.Context, projectId int32, localVarOptionals *ModelEndpointsApiProjectsProjectIdModelEndpointsGetOpts) ([]ModelEndpoint, *http.Response, error) { +// Execute executes the request +// +// @return []ModelEndpoint +func (a *ModelEndpointsAPIService) ProjectsProjectIdModelEndpointsGetExecute(r ApiProjectsProjectIdModelEndpointsGetRequest) ([]ModelEndpoint, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []ModelEndpoint ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/model_endpoints" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelEndpointsAPIService.ProjectsProjectIdModelEndpointsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/model_endpoints" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Region.IsSet() { - localVarQueryParams.Add("region", parameterToString(localVarOptionals.Region.Value(), "")) + if r.region != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "region", r.region, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []ModelEndpoint - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_model_schema.go b/api/client/api_model_schema.go new file mode 100644 index 000000000..f13e795c7 --- /dev/null +++ b/api/client/api_model_schema.go @@ -0,0 +1,491 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "bytes" + "context" + "io" + "net/http" + "net/url" + "strings" +) + +// ModelSchemaAPIService ModelSchemaAPI service +type ModelSchemaAPIService service + +type ApiModelsModelIdSchemasGetRequest struct { + ctx context.Context + ApiService *ModelSchemaAPIService + modelId int32 +} + +func (r ApiModelsModelIdSchemasGetRequest) Execute() ([]ModelSchema, *http.Response, error) { + return r.ApiService.ModelsModelIdSchemasGetExecute(r) +} + +/* +ModelsModelIdSchemasGet List all of the model schemas + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdSchemasGetRequest +*/ +func (a *ModelSchemaAPIService) ModelsModelIdSchemasGet(ctx context.Context, modelId int32) ApiModelsModelIdSchemasGetRequest { + return ApiModelsModelIdSchemasGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return []ModelSchema +func (a *ModelSchemaAPIService) ModelsModelIdSchemasGetExecute(r ApiModelsModelIdSchemasGetRequest) ([]ModelSchema, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue []ModelSchema + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelSchemaAPIService.ModelsModelIdSchemasGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/schemas" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"*/*"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key + } + } + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdSchemasPutRequest struct { + ctx context.Context + ApiService *ModelSchemaAPIService + modelId int32 + body *ModelSchema +} + +func (r ApiModelsModelIdSchemasPutRequest) Body(body ModelSchema) ApiModelsModelIdSchemasPutRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdSchemasPutRequest) Execute() (*ModelSchema, *http.Response, error) { + return r.ApiService.ModelsModelIdSchemasPutExecute(r) +} + +/* +ModelsModelIdSchemasPut Creating new schemas for a model + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdSchemasPutRequest +*/ +func (a *ModelSchemaAPIService) ModelsModelIdSchemasPut(ctx context.Context, modelId int32) ApiModelsModelIdSchemasPutRequest { + return ApiModelsModelIdSchemasPutRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return ModelSchema +func (a *ModelSchemaAPIService) ModelsModelIdSchemasPutExecute(r ApiModelsModelIdSchemasPutRequest) (*ModelSchema, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPut + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *ModelSchema + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelSchemaAPIService.ModelsModelIdSchemasPut") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/schemas" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"*/*"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.body + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key + } + } + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdSchemasSchemaIdDeleteRequest struct { + ctx context.Context + ApiService *ModelSchemaAPIService + modelId int32 + schemaId int32 +} + +func (r ApiModelsModelIdSchemasSchemaIdDeleteRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdSchemasSchemaIdDeleteExecute(r) +} + +/* +ModelsModelIdSchemasSchemaIdDelete Delete schema + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param schemaId + @return ApiModelsModelIdSchemasSchemaIdDeleteRequest +*/ +func (a *ModelSchemaAPIService) ModelsModelIdSchemasSchemaIdDelete(ctx context.Context, modelId int32, schemaId int32) ApiModelsModelIdSchemasSchemaIdDeleteRequest { + return ApiModelsModelIdSchemasSchemaIdDeleteRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + schemaId: schemaId, + } +} + +// Execute executes the request +func (a *ModelSchemaAPIService) ModelsModelIdSchemasSchemaIdDeleteExecute(r ApiModelsModelIdSchemasSchemaIdDeleteRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodDelete + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelSchemaAPIService.ModelsModelIdSchemasSchemaIdDelete") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/schemas/{schema_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"schema_id"+"}", url.PathEscape(parameterValueToString(r.schemaId, "schemaId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key + } + } + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + +type ApiModelsModelIdSchemasSchemaIdGetRequest struct { + ctx context.Context + ApiService *ModelSchemaAPIService + modelId int32 + schemaId int32 +} + +func (r ApiModelsModelIdSchemasSchemaIdGetRequest) Execute() (*ModelSchema, *http.Response, error) { + return r.ApiService.ModelsModelIdSchemasSchemaIdGetExecute(r) +} + +/* +ModelsModelIdSchemasSchemaIdGet Get detail of the schema + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param schemaId + @return ApiModelsModelIdSchemasSchemaIdGetRequest +*/ +func (a *ModelSchemaAPIService) ModelsModelIdSchemasSchemaIdGet(ctx context.Context, modelId int32, schemaId int32) ApiModelsModelIdSchemasSchemaIdGetRequest { + return ApiModelsModelIdSchemasSchemaIdGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + schemaId: schemaId, + } +} + +// Execute executes the request +// +// @return ModelSchema +func (a *ModelSchemaAPIService) ModelsModelIdSchemasSchemaIdGetExecute(r ApiModelsModelIdSchemasSchemaIdGetRequest) (*ModelSchema, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodGet + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *ModelSchema + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelSchemaAPIService.ModelsModelIdSchemasSchemaIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/schemas/{schema_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"schema_id"+"}", url.PathEscape(parameterValueToString(r.schemaId, "schemaId")), -1) + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"*/*"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + if r.ctx != nil { + // API Key Authentication + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key + } + } + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/api/client/api_models.go b/api/client/api_models.go index 4fdff2279..294e67b66 100644 --- a/api/client/api_models.go +++ b/api/client/api_models.go @@ -1,933 +1,1093 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// ModelsAPIService ModelsAPI service +type ModelsAPIService service -type ModelsApiService service +type ApiAlertsTeamsGetRequest struct { + ctx context.Context + ApiService *ModelsAPIService +} + +func (r ApiAlertsTeamsGetRequest) Execute() ([]string, *http.Response, error) { + return r.ApiService.AlertsTeamsGetExecute(r) +} /* -ModelsApiService Lists teams for alert notification channel. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). +AlertsTeamsGet Lists teams for alert notification channel. -@return []string + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiAlertsTeamsGetRequest */ -func (a *ModelsApiService) AlertsTeamsGet(ctx context.Context) ([]string, *http.Response, error) { +func (a *ModelsAPIService) AlertsTeamsGet(ctx context.Context) ApiAlertsTeamsGetRequest { + return ApiAlertsTeamsGetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return []string +func (a *ModelsAPIService) AlertsTeamsGetExecute(r ApiAlertsTeamsGetRequest) ([]string, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []string ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/alerts/teams" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.AlertsTeamsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/alerts/teams" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v []string - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdAlertsGetRequest struct { + ctx context.Context + ApiService *ModelsAPIService + modelId int32 +} + +func (r ApiModelsModelIdAlertsGetRequest) Execute() ([]ModelEndpointAlert, *http.Response, error) { + return r.ApiService.ModelsModelIdAlertsGetExecute(r) } /* -ModelsApiService Lists alerts for given model. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId +ModelsModelIdAlertsGet Lists alerts for given model. -@return []ModelEndpointAlert + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdAlertsGetRequest */ -func (a *ModelsApiService) ModelsModelIdAlertsGet(ctx context.Context, modelId int32) ([]ModelEndpointAlert, *http.Response, error) { +func (a *ModelsAPIService) ModelsModelIdAlertsGet(ctx context.Context, modelId int32) ApiModelsModelIdAlertsGetRequest { + return ApiModelsModelIdAlertsGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return []ModelEndpointAlert +func (a *ModelsAPIService) ModelsModelIdAlertsGetExecute(r ApiModelsModelIdAlertsGetRequest) ([]ModelEndpointAlert, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []ModelEndpointAlert ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/alerts" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ModelsModelIdAlertsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/alerts" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []ModelEndpointAlert - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest struct { + ctx context.Context + ApiService *ModelsAPIService + modelId int32 + modelEndpointId string +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest) Execute() (*ModelEndpointAlert, *http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdAlertGetExecute(r) } /* -ModelsApiService Gets alert for given model endpoint. - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param modelEndpointId +ModelsModelIdEndpointsModelEndpointIdAlertGet Gets alert for given model endpoint. -@return ModelEndpointAlert + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest */ -func (a *ModelsApiService) ModelsModelIdEndpointsModelEndpointIdAlertGet(ctx context.Context, modelId int32, modelEndpointId string) (ModelEndpointAlert, *http.Response, error) { +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertGet(ctx context.Context, modelId int32, modelEndpointId string) ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest { + return ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } +} + +// Execute executes the request +// +// @return ModelEndpointAlert +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertGetExecute(r ApiModelsModelIdEndpointsModelEndpointIdAlertGetRequest) (*ModelEndpointAlert, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue ModelEndpointAlert + formFiles []formFile + localVarReturnValue *ModelEndpointAlert ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ModelsModelIdEndpointsModelEndpointIdAlertGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v ModelEndpointAlert - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest struct { + ctx context.Context + ApiService *ModelsAPIService + modelId int32 + modelEndpointId string + body *ModelEndpointAlert +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest) Body(body ModelEndpointAlert) ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdAlertPostExecute(r) } /* -ModelsApiService Creates alert for given model endpoint. - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param modelEndpointId - * @param optional nil or *ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of ModelEndpointAlert) - +ModelsModelIdEndpointsModelEndpointIdAlertPost Creates alert for given model endpoint. + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest */ - -type ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts struct { - Body optional.Interface +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertPost(ctx context.Context, modelId int32, modelEndpointId string) ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest { + return ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } } -func (a *ModelsApiService) ModelsModelIdEndpointsModelEndpointIdAlertPost(ctx context.Context, modelId int32, modelEndpointId string, localVarOptionals *ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPostOpts) (*http.Response, error) { +// Execute executes the request +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertPostExecute(r ApiModelsModelIdEndpointsModelEndpointIdAlertPostRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ModelsModelIdEndpointsModelEndpointIdAlertPost") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest struct { + ctx context.Context + ApiService *ModelsAPIService + modelId int32 + modelEndpointId string + body *ModelEndpointAlert +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest) Body(body ModelEndpointAlert) ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdEndpointsModelEndpointIdAlertPutExecute(r) } /* -ModelsApiService Creates alert for given model endpoint. - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param modelEndpointId - * @param optional nil or *ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts - Optional Parameters: - * @param "Body" (optional.Interface of ModelEndpointAlert) - +ModelsModelIdEndpointsModelEndpointIdAlertPut Creates alert for given model endpoint. + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param modelEndpointId + @return ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest */ - -type ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts struct { - Body optional.Interface +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertPut(ctx context.Context, modelId int32, modelEndpointId string) ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest { + return ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + modelEndpointId: modelEndpointId, + } } -func (a *ModelsApiService) ModelsModelIdEndpointsModelEndpointIdAlertPut(ctx context.Context, modelId int32, modelEndpointId string, localVarOptionals *ModelsApiModelsModelIdEndpointsModelEndpointIdAlertPutOpts) (*http.Response, error) { +// Execute executes the request +func (a *ModelsAPIService) ModelsModelIdEndpointsModelEndpointIdAlertPutExecute(r ApiModelsModelIdEndpointsModelEndpointIdAlertPutRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Put") + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", fmt.Sprintf("%v", modelEndpointId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ModelsModelIdEndpointsModelEndpointIdAlertPut") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/endpoints/{model_endpoint_id}/alert" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_endpoint_id"+"}", url.PathEscape(parameterValueToString(r.modelEndpointId, "modelEndpointId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdModelsGetRequest struct { + ctx context.Context + ApiService *ModelsAPIService + projectId int32 + name *string +} + +// Filter list of models by specific models `name` +func (r ApiProjectsProjectIdModelsGetRequest) Name(name string) ApiProjectsProjectIdModelsGetRequest { + r.name = &name + return r +} + +func (r ApiProjectsProjectIdModelsGetRequest) Execute() ([]Model, *http.Response, error) { + return r.ApiService.ProjectsProjectIdModelsGetExecute(r) } /* -ModelsApiService List existing models - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId Filter list of models by specific `project_id` - * @param optional nil or *ModelsApiProjectsProjectIdModelsGetOpts - Optional Parameters: - * @param "Name" (optional.String) - Filter list of models by specific models `name` -@return []Model -*/ +ProjectsProjectIdModelsGet List existing models -type ModelsApiProjectsProjectIdModelsGetOpts struct { - Name optional.String + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId Filter list of models by specific `project_id` + @return ApiProjectsProjectIdModelsGetRequest +*/ +func (a *ModelsAPIService) ProjectsProjectIdModelsGet(ctx context.Context, projectId int32) ApiProjectsProjectIdModelsGetRequest { + return ApiProjectsProjectIdModelsGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } } -func (a *ModelsApiService) ProjectsProjectIdModelsGet(ctx context.Context, projectId int32, localVarOptionals *ModelsApiProjectsProjectIdModelsGetOpts) ([]Model, *http.Response, error) { +// Execute executes the request +// +// @return []Model +func (a *ModelsAPIService) ProjectsProjectIdModelsGetExecute(r ApiProjectsProjectIdModelsGetRequest) ([]Model, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Model ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/models" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ProjectsProjectIdModelsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/models" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Name.IsSet() { - localVarQueryParams.Add("name", parameterToString(localVarOptionals.Name.Value(), "")) + if r.name != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "name", r.name, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []Model - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdModelsModelIdDeleteRequest struct { + ctx context.Context + ApiService *ModelsAPIService + projectId int32 + modelId int32 +} + +func (r ApiProjectsProjectIdModelsModelIdDeleteRequest) Execute() (int32, *http.Response, error) { + return r.ApiService.ProjectsProjectIdModelsModelIdDeleteExecute(r) } /* -ModelsApiService Delete model - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param projectId project id of the project to be deleted - - @param modelId model id of the model to be deleted +ProjectsProjectIdModelsModelIdDelete Delete model -@return int32 + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId project id of the project to be deleted + @param modelId model id of the model to be deleted + @return ApiProjectsProjectIdModelsModelIdDeleteRequest */ -func (a *ModelsApiService) ProjectsProjectIdModelsModelIdDelete(ctx context.Context, projectId int32, modelId int32) (int32, *http.Response, error) { +func (a *ModelsAPIService) ProjectsProjectIdModelsModelIdDelete(ctx context.Context, projectId int32, modelId int32) ApiProjectsProjectIdModelsModelIdDeleteRequest { + return ApiProjectsProjectIdModelsModelIdDeleteRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return int32 +func (a *ModelsAPIService) ProjectsProjectIdModelsModelIdDeleteExecute(r ApiProjectsProjectIdModelsModelIdDeleteRequest) (int32, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Delete") + localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue int32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/models/{model_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ProjectsProjectIdModelsModelIdDelete") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/models/{model_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v int32 - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdModelsModelIdGetRequest struct { + ctx context.Context + ApiService *ModelsAPIService + projectId int32 + modelId int32 +} + +func (r ApiProjectsProjectIdModelsModelIdGetRequest) Execute() ([]Model, *http.Response, error) { + return r.ApiService.ProjectsProjectIdModelsModelIdGetExecute(r) } /* -ModelsApiService Get model - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param projectId project id of the project to be retrieved - - @param modelId model id of the model to be retrieved +ProjectsProjectIdModelsModelIdGet Get model -@return []Model + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId project id of the project to be retrieved + @param modelId model id of the model to be retrieved + @return ApiProjectsProjectIdModelsModelIdGetRequest */ -func (a *ModelsApiService) ProjectsProjectIdModelsModelIdGet(ctx context.Context, projectId int32, modelId int32) ([]Model, *http.Response, error) { +func (a *ModelsAPIService) ProjectsProjectIdModelsModelIdGet(ctx context.Context, projectId int32, modelId int32) ApiProjectsProjectIdModelsModelIdGetRequest { + return ApiProjectsProjectIdModelsModelIdGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + modelId: modelId, + } +} + +// Execute executes the request +// +// @return []Model +func (a *ModelsAPIService) ProjectsProjectIdModelsModelIdGetExecute(r ApiProjectsProjectIdModelsModelIdGetRequest) ([]Model, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Model ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/models/{model_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ProjectsProjectIdModelsModelIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/models/{model_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []Model - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdModelsPostRequest struct { + ctx context.Context + ApiService *ModelsAPIService + projectId int32 + body *Model +} + +func (r ApiProjectsProjectIdModelsPostRequest) Body(body Model) ApiProjectsProjectIdModelsPostRequest { + r.body = &body + return r +} + +func (r ApiProjectsProjectIdModelsPostRequest) Execute() (*Model, *http.Response, error) { + return r.ApiService.ProjectsProjectIdModelsPostExecute(r) } /* -ModelsApiService Register a new models - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId Create new model in a specific `project_id` - * @param optional nil or *ModelsApiProjectsProjectIdModelsPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of Model) - -@return Model -*/ +ProjectsProjectIdModelsPost Register a new models -type ModelsApiProjectsProjectIdModelsPostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId Create new model in a specific `project_id` + @return ApiProjectsProjectIdModelsPostRequest +*/ +func (a *ModelsAPIService) ProjectsProjectIdModelsPost(ctx context.Context, projectId int32) ApiProjectsProjectIdModelsPostRequest { + return ApiProjectsProjectIdModelsPostRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } } -func (a *ModelsApiService) ProjectsProjectIdModelsPost(ctx context.Context, projectId int32, localVarOptionals *ModelsApiProjectsProjectIdModelsPostOpts) (Model, *http.Response, error) { +// Execute executes the request +// +// @return Model +func (a *ModelsAPIService) ProjectsProjectIdModelsPostExecute(r ApiProjectsProjectIdModelsPostRequest) (*Model, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Model + formFiles []formFile + localVarReturnValue *Model ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/models" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ModelsAPIService.ProjectsProjectIdModelsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/models" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 201 { - var v Model - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_prediction_jobs.go b/api/client/api_prediction_jobs.go index 8412b0a27..a66a65fdb 100644 --- a/api/client/api_prediction_jobs.go +++ b/api/client/api_prediction_jobs.go @@ -1,662 +1,801 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// PredictionJobsAPIService PredictionJobsAPI service +type PredictionJobsAPIService service -type PredictionJobsApiService service +type ApiModelsModelIdVersionsVersionIdJobsGetRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + modelId int32 + versionId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdJobsGetRequest) Execute() ([]PredictionJob, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdJobsGetExecute(r) +} /* -PredictionJobsApiService List all prediction jobs of a model version - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId +ModelsModelIdVersionsVersionIdJobsGet List all prediction jobs of a model version -@return []PredictionJob + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdJobsGetRequest */ -func (a *PredictionJobsApiService) ModelsModelIdVersionsVersionIdJobsGet(ctx context.Context, modelId int32, versionId int32) ([]PredictionJob, *http.Response, error) { +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsGet(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdJobsGetRequest { + return ApiModelsModelIdVersionsVersionIdJobsGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } +} + +// Execute executes the request +// +// @return []PredictionJob +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsGetExecute(r ApiModelsModelIdVersionsVersionIdJobsGetRequest) ([]PredictionJob, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []PredictionJob ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/jobs" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ModelsModelIdVersionsVersionIdJobsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/jobs" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []PredictionJob - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + modelId int32 + versionId int32 + jobId string +} + +func (r ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest) Execute() (*Container, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdJobsJobIdContainersGetExecute(r) } /* -PredictionJobsApiService Get all container belong to a prediction job - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param jobId +ModelsModelIdVersionsVersionIdJobsJobIdContainersGet Get all container belong to a prediction job -@return Container + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param jobId + @return ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest */ -func (a *PredictionJobsApiService) ModelsModelIdVersionsVersionIdJobsJobIdContainersGet(ctx context.Context, modelId int32, versionId int32, jobId string) (Container, *http.Response, error) { +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdContainersGet(ctx context.Context, modelId int32, versionId int32, jobId string) ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest { + return ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + jobId: jobId, + } +} + +// Execute executes the request +// +// @return Container +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdContainersGetExecute(r ApiModelsModelIdVersionsVersionIdJobsJobIdContainersGetRequest) (*Container, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Container + formFiles []formFile + localVarReturnValue *Container ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}/containers" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", fmt.Sprintf("%v", jobId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ModelsModelIdVersionsVersionIdJobsJobIdContainersGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}/containers" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", url.PathEscape(parameterValueToString(r.jobId, "jobId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v Container - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + modelId int32 + versionId int32 + jobId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest) Execute() (*PredictionJob, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdJobsJobIdGetExecute(r) } /* -PredictionJobsApiService Get prediction jobs with given id - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param jobId +ModelsModelIdVersionsVersionIdJobsJobIdGet Get prediction jobs with given id -@return PredictionJob + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param jobId + @return ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest */ -func (a *PredictionJobsApiService) ModelsModelIdVersionsVersionIdJobsJobIdGet(ctx context.Context, modelId int32, versionId int32, jobId int32) (PredictionJob, *http.Response, error) { +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdGet(ctx context.Context, modelId int32, versionId int32, jobId int32) ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest { + return ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + jobId: jobId, + } +} + +// Execute executes the request +// +// @return PredictionJob +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdGetExecute(r ApiModelsModelIdVersionsVersionIdJobsJobIdGetRequest) (*PredictionJob, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue PredictionJob + formFiles []formFile + localVarReturnValue *PredictionJob ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", fmt.Sprintf("%v", jobId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ModelsModelIdVersionsVersionIdJobsJobIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", url.PathEscape(parameterValueToString(r.jobId, "jobId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v PredictionJob - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + modelId int32 + versionId int32 + jobId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdJobsJobIdStopPutExecute(r) } /* -PredictionJobsApiService Stop prediction jobs with given id - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId - - @param jobId +ModelsModelIdVersionsVersionIdJobsJobIdStopPut Stop prediction jobs with given id + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @param jobId + @return ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest */ -func (a *PredictionJobsApiService) ModelsModelIdVersionsVersionIdJobsJobIdStopPut(ctx context.Context, modelId int32, versionId int32, jobId int32) (*http.Response, error) { +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdStopPut(ctx context.Context, modelId int32, versionId int32, jobId int32) ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest { + return ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + jobId: jobId, + } +} + +// Execute executes the request +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsJobIdStopPutExecute(r ApiModelsModelIdVersionsVersionIdJobsJobIdStopPutRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Put") + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}/stop" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", fmt.Sprintf("%v", jobId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ModelsModelIdVersionsVersionIdJobsJobIdStopPut") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/jobs/{job_id}/stop" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"job_id"+"}", url.PathEscape(parameterValueToString(r.jobId, "jobId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdJobsPostRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + modelId int32 + versionId int32 + body *PredictionJob +} + +func (r ApiModelsModelIdVersionsVersionIdJobsPostRequest) Body(body PredictionJob) ApiModelsModelIdVersionsVersionIdJobsPostRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdVersionsVersionIdJobsPostRequest) Execute() (*PredictionJob, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdJobsPostExecute(r) } /* -PredictionJobsApiService Create a prediction job from the given model version - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param versionId - * @param optional nil or *PredictionJobsApiModelsModelIdVersionsVersionIdJobsPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of PredictionJob) - -@return PredictionJob -*/ +ModelsModelIdVersionsVersionIdJobsPost Create a prediction job from the given model version -type PredictionJobsApiModelsModelIdVersionsVersionIdJobsPostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdJobsPostRequest +*/ +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsPost(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdJobsPostRequest { + return ApiModelsModelIdVersionsVersionIdJobsPostRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } } -func (a *PredictionJobsApiService) ModelsModelIdVersionsVersionIdJobsPost(ctx context.Context, modelId int32, versionId int32, localVarOptionals *PredictionJobsApiModelsModelIdVersionsVersionIdJobsPostOpts) (PredictionJob, *http.Response, error) { +// Execute executes the request +// +// @return PredictionJob +func (a *PredictionJobsAPIService) ModelsModelIdVersionsVersionIdJobsPostExecute(r ApiModelsModelIdVersionsVersionIdJobsPostRequest) (*PredictionJob, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue PredictionJob + formFiles []formFile + localVarReturnValue *PredictionJob ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}/jobs" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ModelsModelIdVersionsVersionIdJobsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}/jobs" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 201 { - var v PredictionJob - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdJobsGetRequest struct { + ctx context.Context + ApiService *PredictionJobsAPIService + projectId int32 + id *int32 + name *string + modelId *int32 + versionId *int32 + status *string + error_ *string +} + +func (r ApiProjectsProjectIdJobsGetRequest) Id(id int32) ApiProjectsProjectIdJobsGetRequest { + r.id = &id + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) Name(name string) ApiProjectsProjectIdJobsGetRequest { + r.name = &name + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) ModelId(modelId int32) ApiProjectsProjectIdJobsGetRequest { + r.modelId = &modelId + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) VersionId(versionId int32) ApiProjectsProjectIdJobsGetRequest { + r.versionId = &versionId + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) Status(status string) ApiProjectsProjectIdJobsGetRequest { + r.status = &status + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) Error_(error_ string) ApiProjectsProjectIdJobsGetRequest { + r.error_ = &error_ + return r +} + +func (r ApiProjectsProjectIdJobsGetRequest) Execute() ([]PredictionJob, *http.Response, error) { + return r.ApiService.ProjectsProjectIdJobsGetExecute(r) } /* -PredictionJobsApiService List all prediction jobs created using the model - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId - * @param optional nil or *PredictionJobsApiProjectsProjectIdJobsGetOpts - Optional Parameters: - * @param "Id" (optional.Int32) - - * @param "Name" (optional.String) - - * @param "ModelId" (optional.Int32) - - * @param "VersionId" (optional.Int32) - - * @param "Status" (optional.String) - - * @param "Error_" (optional.String) - -@return []PredictionJob -*/ +ProjectsProjectIdJobsGet List all prediction jobs created using the model -type PredictionJobsApiProjectsProjectIdJobsGetOpts struct { - Id optional.Int32 - Name optional.String - ModelId optional.Int32 - VersionId optional.Int32 - Status optional.String - Error_ optional.String + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId + @return ApiProjectsProjectIdJobsGetRequest +*/ +func (a *PredictionJobsAPIService) ProjectsProjectIdJobsGet(ctx context.Context, projectId int32) ApiProjectsProjectIdJobsGetRequest { + return ApiProjectsProjectIdJobsGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } } -func (a *PredictionJobsApiService) ProjectsProjectIdJobsGet(ctx context.Context, projectId int32, localVarOptionals *PredictionJobsApiProjectsProjectIdJobsGetOpts) ([]PredictionJob, *http.Response, error) { +// Execute executes the request +// +// @return []PredictionJob +func (a *PredictionJobsAPIService) ProjectsProjectIdJobsGetExecute(r ApiProjectsProjectIdJobsGetRequest) ([]PredictionJob, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []PredictionJob ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/jobs" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PredictionJobsAPIService.ProjectsProjectIdJobsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/jobs" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Id.IsSet() { - localVarQueryParams.Add("id", parameterToString(localVarOptionals.Id.Value(), "")) + if r.id != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "id", r.id, "") } - if localVarOptionals != nil && localVarOptionals.Name.IsSet() { - localVarQueryParams.Add("name", parameterToString(localVarOptionals.Name.Value(), "")) + if r.name != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "name", r.name, "") } - if localVarOptionals != nil && localVarOptionals.ModelId.IsSet() { - localVarQueryParams.Add("model_id", parameterToString(localVarOptionals.ModelId.Value(), "")) + if r.modelId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "model_id", r.modelId, "") } - if localVarOptionals != nil && localVarOptionals.VersionId.IsSet() { - localVarQueryParams.Add("version_id", parameterToString(localVarOptionals.VersionId.Value(), "")) + if r.versionId != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "version_id", r.versionId, "") } - if localVarOptionals != nil && localVarOptionals.Status.IsSet() { - localVarQueryParams.Add("status", parameterToString(localVarOptionals.Status.Value(), "")) + if r.status != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "status", r.status, "") } - if localVarOptionals != nil && localVarOptionals.Error_.IsSet() { - localVarQueryParams.Add("error", parameterToString(localVarOptionals.Error_.Value(), "")) + if r.error_ != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "error", r.error_, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []PredictionJob - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_project.go b/api/client/api_project.go index 48a2a5d54..04f54b3da 100644 --- a/api/client/api_project.go +++ b/api/client/api_project.go @@ -1,435 +1,514 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// ProjectAPIService ProjectAPI service +type ProjectAPIService service -type ProjectApiService service +type ApiProjectsGetRequest struct { + ctx context.Context + ApiService *ProjectAPIService + name *string +} + +func (r ApiProjectsGetRequest) Name(name string) ApiProjectsGetRequest { + r.name = &name + return r +} + +func (r ApiProjectsGetRequest) Execute() ([]Project, *http.Response, error) { + return r.ApiService.ProjectsGetExecute(r) +} /* -ProjectApiService List existing projects -Projects can be filtered by optional `name` parameter - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param optional nil or *ProjectApiProjectsGetOpts - Optional Parameters: - * @param "Name" (optional.String) - -@return []Project -*/ +ProjectsGet List existing projects -type ProjectApiProjectsGetOpts struct { - Name optional.String +Projects can be filtered by optional `name` parameter + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiProjectsGetRequest +*/ +func (a *ProjectAPIService) ProjectsGet(ctx context.Context) ApiProjectsGetRequest { + return ApiProjectsGetRequest{ + ApiService: a, + ctx: ctx, + } } -func (a *ProjectApiService) ProjectsGet(ctx context.Context, localVarOptionals *ProjectApiProjectsGetOpts) ([]Project, *http.Response, error) { +// Execute executes the request +// +// @return []Project +func (a *ProjectAPIService) ProjectsGetExecute(r ApiProjectsGetRequest) ([]Project, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Project ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectAPIService.ProjectsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Name.IsSet() { - localVarQueryParams.Add("name", parameterToString(localVarOptionals.Name.Value(), "")) + if r.name != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "name", r.name, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []Project - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsPostRequest struct { + ctx context.Context + ApiService *ProjectAPIService + body *Project +} + +// Project object that has to be added +func (r ApiProjectsPostRequest) Body(body Project) ApiProjectsPostRequest { + r.body = &body + return r +} + +func (r ApiProjectsPostRequest) Execute() (*Project, *http.Response, error) { + return r.ApiService.ProjectsPostExecute(r) } /* -ProjectApiService Create new project - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param body Project object that has to be added +ProjectsPost Create new project -@return Project + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiProjectsPostRequest */ -func (a *ProjectApiService) ProjectsPost(ctx context.Context, body Project) (Project, *http.Response, error) { +func (a *ProjectAPIService) ProjectsPost(ctx context.Context) ApiProjectsPostRequest { + return ApiProjectsPostRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// +// @return Project +func (a *ProjectAPIService) ProjectsPostExecute(r ApiProjectsPostRequest) (*Project, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Project + formFiles []formFile + localVarReturnValue *Project ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectAPIService.ProjectsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.body == nil { + return localVarReturnValue, nil, reportError("body is required and must be specified") + } // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = &body - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 201 { - var v Project - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdGetRequest struct { + ctx context.Context + ApiService *ProjectAPIService + projectId int32 +} + +func (r ApiProjectsProjectIdGetRequest) Execute() (*Project, *http.Response, error) { + return r.ApiService.ProjectsProjectIdGetExecute(r) } /* -ProjectApiService Get project - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param projectId project id of the project to be retrieved +ProjectsProjectIdGet Get project -@return Project + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId project id of the project to be retrieved + @return ApiProjectsProjectIdGetRequest */ -func (a *ProjectApiService) ProjectsProjectIdGet(ctx context.Context, projectId int32) (Project, *http.Response, error) { +func (a *ProjectAPIService) ProjectsProjectIdGet(ctx context.Context, projectId int32) ApiProjectsProjectIdGetRequest { + return ApiProjectsProjectIdGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } +} + +// Execute executes the request +// +// @return Project +func (a *ProjectAPIService) ProjectsProjectIdGetExecute(r ApiProjectsProjectIdGetRequest) (*Project, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Project + formFiles []formFile + localVarReturnValue *Project ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectAPIService.ProjectsProjectIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v Project - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdPutRequest struct { + ctx context.Context + ApiService *ProjectAPIService + projectId int32 + body *Project +} + +// Project object that has to be updated +func (r ApiProjectsProjectIdPutRequest) Body(body Project) ApiProjectsProjectIdPutRequest { + r.body = &body + return r +} + +func (r ApiProjectsProjectIdPutRequest) Execute() (*Project, *http.Response, error) { + return r.ApiService.ProjectsProjectIdPutExecute(r) } /* -ProjectApiService Update project - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param body Project object that has to be updated - - @param projectId project id of the project to be updated +ProjectsProjectIdPut Update project -@return Project + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId project id of the project to be updated + @return ApiProjectsProjectIdPutRequest */ -func (a *ProjectApiService) ProjectsProjectIdPut(ctx context.Context, body Project, projectId int32) (Project, *http.Response, error) { +func (a *ProjectAPIService) ProjectsProjectIdPut(ctx context.Context, projectId int32) ApiProjectsProjectIdPutRequest { + return ApiProjectsProjectIdPutRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } +} + +// Execute executes the request +// +// @return Project +func (a *ProjectAPIService) ProjectsProjectIdPutExecute(r ApiProjectsProjectIdPutRequest) (*Project, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Put") + localVarHTTPMethod = http.MethodPut localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Project + formFiles []formFile + localVarReturnValue *Project ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "ProjectAPIService.ProjectsProjectIdPut") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} + if r.body == nil { + return localVarReturnValue, nil, reportError("body is required and must be specified") + } // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - localVarPostBody = &body - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v Project - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_secret.go b/api/client/api_secret.go index 84bd941d4..fb530f7ec 100644 --- a/api/client/api_secret.go +++ b/api/client/api_secret.go @@ -1,430 +1,499 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// SecretAPIService SecretAPI service +type SecretAPIService service + +type ApiProjectsProjectIdSecretsGetRequest struct { + ctx context.Context + ApiService *SecretAPIService + projectId int32 +} -type SecretApiService service +func (r ApiProjectsProjectIdSecretsGetRequest) Execute() ([]Secret, *http.Response, error) { + return r.ApiService.ProjectsProjectIdSecretsGetExecute(r) +} /* -SecretApiService List secret - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param projectId +ProjectsProjectIdSecretsGet List secret -@return []Secret + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId + @return ApiProjectsProjectIdSecretsGetRequest */ -func (a *SecretApiService) ProjectsProjectIdSecretsGet(ctx context.Context, projectId int32) ([]Secret, *http.Response, error) { +func (a *SecretAPIService) ProjectsProjectIdSecretsGet(ctx context.Context, projectId int32) ApiProjectsProjectIdSecretsGetRequest { + return ApiProjectsProjectIdSecretsGetRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } +} + +// Execute executes the request +// +// @return []Secret +func (a *SecretAPIService) ProjectsProjectIdSecretsGetExecute(r ApiProjectsProjectIdSecretsGetRequest) ([]Secret, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Secret ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/secrets" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SecretAPIService.ProjectsProjectIdSecretsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/secrets" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 201 { - var v []Secret - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdSecretsPostRequest struct { + ctx context.Context + ApiService *SecretAPIService + projectId int32 + body *Secret +} + +func (r ApiProjectsProjectIdSecretsPostRequest) Body(body Secret) ApiProjectsProjectIdSecretsPostRequest { + r.body = &body + return r +} + +func (r ApiProjectsProjectIdSecretsPostRequest) Execute() (*Secret, *http.Response, error) { + return r.ApiService.ProjectsProjectIdSecretsPostExecute(r) } /* -SecretApiService Create secret - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId - * @param optional nil or *SecretApiProjectsProjectIdSecretsPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of Secret) - -@return Secret -*/ +ProjectsProjectIdSecretsPost Create secret -type SecretApiProjectsProjectIdSecretsPostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId + @return ApiProjectsProjectIdSecretsPostRequest +*/ +func (a *SecretAPIService) ProjectsProjectIdSecretsPost(ctx context.Context, projectId int32) ApiProjectsProjectIdSecretsPostRequest { + return ApiProjectsProjectIdSecretsPostRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + } } -func (a *SecretApiService) ProjectsProjectIdSecretsPost(ctx context.Context, projectId int32, localVarOptionals *SecretApiProjectsProjectIdSecretsPostOpts) (Secret, *http.Response, error) { +// Execute executes the request +// +// @return Secret +func (a *SecretAPIService) ProjectsProjectIdSecretsPostExecute(r ApiProjectsProjectIdSecretsPostRequest) (*Secret, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Secret + formFiles []formFile + localVarReturnValue *Secret ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/secrets" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SecretAPIService.ProjectsProjectIdSecretsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/secrets" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 201 { - var v Secret - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdSecretsSecretIdDeleteRequest struct { + ctx context.Context + ApiService *SecretAPIService + projectId int32 + secretId int32 +} + +func (r ApiProjectsProjectIdSecretsSecretIdDeleteRequest) Execute() (*http.Response, error) { + return r.ApiService.ProjectsProjectIdSecretsSecretIdDeleteExecute(r) } /* -SecretApiService Delete secret - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param projectId - - @param secretId +ProjectsProjectIdSecretsSecretIdDelete Delete secret + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId + @param secretId + @return ApiProjectsProjectIdSecretsSecretIdDeleteRequest */ -func (a *SecretApiService) ProjectsProjectIdSecretsSecretIdDelete(ctx context.Context, projectId int32, secretId int32) (*http.Response, error) { +func (a *SecretAPIService) ProjectsProjectIdSecretsSecretIdDelete(ctx context.Context, projectId int32, secretId int32) ApiProjectsProjectIdSecretsSecretIdDeleteRequest { + return ApiProjectsProjectIdSecretsSecretIdDeleteRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + secretId: secretId, + } +} + +// Execute executes the request +func (a *SecretAPIService) ProjectsProjectIdSecretsSecretIdDeleteExecute(r ApiProjectsProjectIdSecretsSecretIdDeleteRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Delete") + localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/secrets/{secret_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"secret_id"+"}", fmt.Sprintf("%v", secretId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SecretAPIService.ProjectsProjectIdSecretsSecretIdDelete") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/secrets/{secret_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"secret_id"+"}", url.PathEscape(parameterValueToString(r.secretId, "secretId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil +} + +type ApiProjectsProjectIdSecretsSecretIdPatchRequest struct { + ctx context.Context + ApiService *SecretAPIService + projectId int32 + secretId int32 + body *Secret +} + +func (r ApiProjectsProjectIdSecretsSecretIdPatchRequest) Body(body Secret) ApiProjectsProjectIdSecretsSecretIdPatchRequest { + r.body = &body + return r +} + +func (r ApiProjectsProjectIdSecretsSecretIdPatchRequest) Execute() (*Secret, *http.Response, error) { + return r.ApiService.ProjectsProjectIdSecretsSecretIdPatchExecute(r) } /* -SecretApiService Update secret - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param projectId - * @param secretId - * @param optional nil or *SecretApiProjectsProjectIdSecretsSecretIdPatchOpts - Optional Parameters: - * @param "Body" (optional.Interface of Secret) - -@return Secret -*/ +ProjectsProjectIdSecretsSecretIdPatch Update secret -type SecretApiProjectsProjectIdSecretsSecretIdPatchOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param projectId + @param secretId + @return ApiProjectsProjectIdSecretsSecretIdPatchRequest +*/ +func (a *SecretAPIService) ProjectsProjectIdSecretsSecretIdPatch(ctx context.Context, projectId int32, secretId int32) ApiProjectsProjectIdSecretsSecretIdPatchRequest { + return ApiProjectsProjectIdSecretsSecretIdPatchRequest{ + ApiService: a, + ctx: ctx, + projectId: projectId, + secretId: secretId, + } } -func (a *SecretApiService) ProjectsProjectIdSecretsSecretIdPatch(ctx context.Context, projectId int32, secretId int32, localVarOptionals *SecretApiProjectsProjectIdSecretsSecretIdPatchOpts) (Secret, *http.Response, error) { +// Execute executes the request +// +// @return Secret +func (a *SecretAPIService) ProjectsProjectIdSecretsSecretIdPatchExecute(r ApiProjectsProjectIdSecretsSecretIdPatchRequest) (*Secret, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Patch") + localVarHTTPMethod = http.MethodPatch localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Secret + formFiles []formFile + localVarReturnValue *Secret ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/projects/{project_id}/secrets/{secret_id}" - localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", fmt.Sprintf("%v", projectId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"secret_id"+"}", fmt.Sprintf("%v", secretId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "SecretAPIService.ProjectsProjectIdSecretsSecretIdPatch") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/projects/{project_id}/secrets/{secret_id}" + localVarPath = strings.Replace(localVarPath, "{"+"project_id"+"}", url.PathEscape(parameterValueToString(r.projectId, "projectId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"secret_id"+"}", url.PathEscape(parameterValueToString(r.secretId, "secretId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v Secret - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_standard_transformer.go b/api/client/api_standard_transformer.go index 1e325a365..1e663fcc3 100644 --- a/api/client/api_standard_transformer.go +++ b/api/client/api_standard_transformer.go @@ -1,135 +1,142 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "io/ioutil" + "io" "net/http" "net/url" - "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// StandardTransformerAPIService StandardTransformerAPI service +type StandardTransformerAPIService service -type StandardTransformerApiService service +type ApiStandardTransformerSimulatePostRequest struct { + ctx context.Context + ApiService *StandardTransformerAPIService + body *StandardTransformerSimulationRequest +} + +func (r ApiStandardTransformerSimulatePostRequest) Body(body StandardTransformerSimulationRequest) ApiStandardTransformerSimulatePostRequest { + r.body = &body + return r +} + +func (r ApiStandardTransformerSimulatePostRequest) Execute() (*StandardTransformerSimulationResponse, *http.Response, error) { + return r.ApiService.StandardTransformerSimulatePostExecute(r) +} /* -StandardTransformerApiService Simulate standard transformer - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param optional nil or *StandardTransformerApiStandardTransformerSimulatePostOpts - Optional Parameters: - * @param "Body" (optional.Interface of StandardTransformerSimulationRequest) - -@return StandardTransformerSimulationResponse -*/ +StandardTransformerSimulatePost Simulate standard transformer -type StandardTransformerApiStandardTransformerSimulatePostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiStandardTransformerSimulatePostRequest +*/ +func (a *StandardTransformerAPIService) StandardTransformerSimulatePost(ctx context.Context) ApiStandardTransformerSimulatePostRequest { + return ApiStandardTransformerSimulatePostRequest{ + ApiService: a, + ctx: ctx, + } } -func (a *StandardTransformerApiService) StandardTransformerSimulatePost(ctx context.Context, localVarOptionals *StandardTransformerApiStandardTransformerSimulatePostOpts) (StandardTransformerSimulationResponse, *http.Response, error) { +// Execute executes the request +// +// @return StandardTransformerSimulationResponse +func (a *StandardTransformerAPIService) StandardTransformerSimulatePostExecute(r ApiStandardTransformerSimulatePostRequest) (*StandardTransformerSimulationResponse, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue StandardTransformerSimulationResponse + formFiles []formFile + localVarReturnValue *StandardTransformerSimulationResponse ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/standard_transformer/simulate" + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "StandardTransformerAPIService.StandardTransformerSimulatePost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/standard_transformer/simulate" localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v StandardTransformerSimulationResponse - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil } diff --git a/api/client/api_version.go b/api/client/api_version.go index 7b5deceea..a81c99ebd 100644 --- a/api/client/api_version.go +++ b/api/client/api_version.go @@ -1,552 +1,647 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "bytes" "context" - "fmt" - "io/ioutil" + "io" "net/http" "net/url" "strings" - - "github.com/antihax/optional" ) -// Linger please -var ( - _ context.Context -) +// VersionAPIService VersionAPI service +type VersionAPIService service + +type ApiModelsModelIdVersionsGetRequest struct { + ctx context.Context + ApiService *VersionAPIService + modelId int32 + limit *int32 + cursor *string + search *string +} -type VersionApiService service +func (r ApiModelsModelIdVersionsGetRequest) Limit(limit int32) ApiModelsModelIdVersionsGetRequest { + r.limit = &limit + return r +} + +func (r ApiModelsModelIdVersionsGetRequest) Cursor(cursor string) ApiModelsModelIdVersionsGetRequest { + r.cursor = &cursor + return r +} + +// Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` +func (r ApiModelsModelIdVersionsGetRequest) Search(search string) ApiModelsModelIdVersionsGetRequest { + r.search = &search + return r +} + +func (r ApiModelsModelIdVersionsGetRequest) Execute() ([]Version, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsGetExecute(r) +} /* -VersionApiService List versions of the models - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param optional nil or *VersionApiModelsModelIdVersionsGetOpts - Optional Parameters: - * @param "Limit" (optional.Int32) - - * @param "Cursor" (optional.String) - - * @param "Search" (optional.String) - Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` -@return []Version -*/ +ModelsModelIdVersionsGet List versions of the models -type VersionApiModelsModelIdVersionsGetOpts struct { - Limit optional.Int32 - Cursor optional.String - Search optional.String + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdVersionsGetRequest +*/ +func (a *VersionAPIService) ModelsModelIdVersionsGet(ctx context.Context, modelId int32) ApiModelsModelIdVersionsGetRequest { + return ApiModelsModelIdVersionsGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } } -func (a *VersionApiService) ModelsModelIdVersionsGet(ctx context.Context, modelId int32, localVarOptionals *VersionApiModelsModelIdVersionsGetOpts) ([]Version, *http.Response, error) { +// Execute executes the request +// +// @return []Version +func (a *VersionAPIService) ModelsModelIdVersionsGetExecute(r ApiModelsModelIdVersionsGetRequest) ([]Version, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue []Version ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "VersionAPIService.ModelsModelIdVersionsGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} - if localVarOptionals != nil && localVarOptionals.Limit.IsSet() { - localVarQueryParams.Add("limit", parameterToString(localVarOptionals.Limit.Value(), "")) + if r.limit != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "limit", r.limit, "") } - if localVarOptionals != nil && localVarOptionals.Cursor.IsSet() { - localVarQueryParams.Add("cursor", parameterToString(localVarOptionals.Cursor.Value(), "")) + if r.cursor != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "cursor", r.cursor, "") } - if localVarOptionals != nil && localVarOptionals.Search.IsSet() { - localVarQueryParams.Add("search", parameterToString(localVarOptionals.Search.Value(), "")) + if r.search != nil { + parameterAddToHeaderOrQuery(localVarQueryParams, "search", r.search, "") } // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v []Version - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsPostRequest struct { + ctx context.Context + ApiService *VersionAPIService + modelId int32 + body *Version +} + +func (r ApiModelsModelIdVersionsPostRequest) Body(body Version) ApiModelsModelIdVersionsPostRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdVersionsPostRequest) Execute() (*Version, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsPostExecute(r) } /* -VersionApiService Log a new version of the models - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param optional nil or *VersionApiModelsModelIdVersionsPostOpts - Optional Parameters: - * @param "Body" (optional.Interface of Version) - -@return Version -*/ +ModelsModelIdVersionsPost Log a new version of the models -type VersionApiModelsModelIdVersionsPostOpts struct { - Body optional.Interface + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @return ApiModelsModelIdVersionsPostRequest +*/ +func (a *VersionAPIService) ModelsModelIdVersionsPost(ctx context.Context, modelId int32) ApiModelsModelIdVersionsPostRequest { + return ApiModelsModelIdVersionsPostRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + } } -func (a *VersionApiService) ModelsModelIdVersionsPost(ctx context.Context, modelId int32, localVarOptionals *VersionApiModelsModelIdVersionsPostOpts) (Version, *http.Response, error) { +// Execute executes the request +// +// @return Version +func (a *VersionAPIService) ModelsModelIdVersionsPostExecute(r ApiModelsModelIdVersionsPostRequest) (*Version, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Post") + localVarHTTPMethod = http.MethodPost localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Version + formFiles []formFile + localVarReturnValue *Version ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "VersionAPIService.ModelsModelIdVersionsPost") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v Version - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdDeleteRequest struct { + ctx context.Context + ApiService *VersionAPIService + modelId int32 + versionId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdDeleteRequest) Execute() (int32, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdDeleteExecute(r) } /* -VersionApiService Delete version by ID from model - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId +ModelsModelIdVersionsVersionIdDelete Delete version by ID from model -@return int32 + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdDeleteRequest */ -func (a *VersionApiService) ModelsModelIdVersionsVersionIdDelete(ctx context.Context, modelId int32, versionId int32) (int32, *http.Response, error) { +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdDelete(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdDeleteRequest { + return ApiModelsModelIdVersionsVersionIdDeleteRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } +} + +// Execute executes the request +// +// @return int32 +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdDeleteExecute(r ApiModelsModelIdVersionsVersionIdDeleteRequest) (int32, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Delete") + localVarHTTPMethod = http.MethodDelete localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile localVarReturnValue int32 ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "VersionAPIService.ModelsModelIdVersionsVersionIdDelete") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, - } - if localVarHttpResponse.StatusCode == 200 { - var v int32 - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr + error: err.Error(), } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdGetRequest struct { + ctx context.Context + ApiService *VersionAPIService + modelId int32 + versionId int32 +} + +func (r ApiModelsModelIdVersionsVersionIdGetRequest) Execute() (*Version, *http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdGetExecute(r) } /* -VersionApiService Get version by ID from model - - @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - - @param modelId - - @param versionId +ModelsModelIdVersionsVersionIdGet Get version by ID from model -@return Version + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdGetRequest */ -func (a *VersionApiService) ModelsModelIdVersionsVersionIdGet(ctx context.Context, modelId int32, versionId int32) (Version, *http.Response, error) { +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdGet(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdGetRequest { + return ApiModelsModelIdVersionsVersionIdGetRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } +} + +// Execute executes the request +// +// @return Version +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdGetExecute(r ApiModelsModelIdVersionsVersionIdGetRequest) (*Version, *http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Get") + localVarHTTPMethod = http.MethodGet localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte - localVarReturnValue Version + formFiles []formFile + localVarReturnValue *Version ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "VersionAPIService.ModelsModelIdVersionsVersionIdGet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{"*/*"} + localVarHTTPHeaderAccepts := []string{"*/*"} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } - if ctx != nil { + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return localVarReturnValue, nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarReturnValue, localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarReturnValue, localVarHttpResponse, err + return localVarReturnValue, localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode < 300 { - // If we succeed, return the data, otherwise pass on to decode error. - err = a.client.decode(&localVarReturnValue, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err == nil { - return localVarReturnValue, localVarHttpResponse, err + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, } + return localVarReturnValue, localVarHTTPResponse, newErr } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: err.Error(), } - if localVarHttpResponse.StatusCode == 200 { - var v Version - err = a.client.decode(&v, localVarBody, localVarHttpResponse.Header.Get("Content-Type")) - if err != nil { - newErr.error = err.Error() - return localVarReturnValue, localVarHttpResponse, newErr - } - newErr.model = v - return localVarReturnValue, localVarHttpResponse, newErr - } - return localVarReturnValue, localVarHttpResponse, newErr + return localVarReturnValue, localVarHTTPResponse, newErr } - return localVarReturnValue, localVarHttpResponse, nil + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiModelsModelIdVersionsVersionIdPatchRequest struct { + ctx context.Context + ApiService *VersionAPIService + modelId int32 + versionId int32 + body *Version +} + +func (r ApiModelsModelIdVersionsVersionIdPatchRequest) Body(body Version) ApiModelsModelIdVersionsVersionIdPatchRequest { + r.body = &body + return r +} + +func (r ApiModelsModelIdVersionsVersionIdPatchRequest) Execute() (*http.Response, error) { + return r.ApiService.ModelsModelIdVersionsVersionIdPatchExecute(r) } /* -VersionApiService Patch the version - * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). - * @param modelId - * @param versionId - * @param optional nil or *VersionApiModelsModelIdVersionsVersionIdPatchOpts - Optional Parameters: - * @param "Body" (optional.Interface of Version) - +ModelsModelIdVersionsVersionIdPatch Patch the version + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @param modelId + @param versionId + @return ApiModelsModelIdVersionsVersionIdPatchRequest */ - -type VersionApiModelsModelIdVersionsVersionIdPatchOpts struct { - Body optional.Interface +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdPatch(ctx context.Context, modelId int32, versionId int32) ApiModelsModelIdVersionsVersionIdPatchRequest { + return ApiModelsModelIdVersionsVersionIdPatchRequest{ + ApiService: a, + ctx: ctx, + modelId: modelId, + versionId: versionId, + } } -func (a *VersionApiService) ModelsModelIdVersionsVersionIdPatch(ctx context.Context, modelId int32, versionId int32, localVarOptionals *VersionApiModelsModelIdVersionsVersionIdPatchOpts) (*http.Response, error) { +// Execute executes the request +func (a *VersionAPIService) ModelsModelIdVersionsVersionIdPatchExecute(r ApiModelsModelIdVersionsVersionIdPatchRequest) (*http.Response, error) { var ( - localVarHttpMethod = strings.ToUpper("Patch") + localVarHTTPMethod = http.MethodPatch localVarPostBody interface{} - localVarFileName string - localVarFileBytes []byte + formFiles []formFile ) - // create path and map variables - localVarPath := a.client.cfg.BasePath + "/models/{model_id}/versions/{version_id}" - localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", fmt.Sprintf("%v", modelId), -1) - localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", fmt.Sprintf("%v", versionId), -1) + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "VersionAPIService.ModelsModelIdVersionsVersionIdPatch") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/models/{model_id}/versions/{version_id}" + localVarPath = strings.Replace(localVarPath, "{"+"model_id"+"}", url.PathEscape(parameterValueToString(r.modelId, "modelId")), -1) + localVarPath = strings.Replace(localVarPath, "{"+"version_id"+"}", url.PathEscape(parameterValueToString(r.versionId, "versionId")), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} // to determine the Content-Type header - localVarHttpContentTypes := []string{"*/*"} + localVarHTTPContentTypes := []string{} // set Content-Type header - localVarHttpContentType := selectHeaderContentType(localVarHttpContentTypes) - if localVarHttpContentType != "" { - localVarHeaderParams["Content-Type"] = localVarHttpContentType + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType } // to determine the Accept header - localVarHttpHeaderAccepts := []string{} + localVarHTTPHeaderAccepts := []string{} // set Accept header - localVarHttpHeaderAccept := selectHeaderAccept(localVarHttpHeaderAccepts) - if localVarHttpHeaderAccept != "" { - localVarHeaderParams["Accept"] = localVarHttpHeaderAccept + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params - if localVarOptionals != nil && localVarOptionals.Body.IsSet() { - - localVarOptionalBody := localVarOptionals.Body.Value() - localVarPostBody = &localVarOptionalBody - } - if ctx != nil { + localVarPostBody = r.body + if r.ctx != nil { // API Key Authentication - if auth, ok := ctx.Value(ContextAPIKey).(APIKey); ok { - var key string - if auth.Prefix != "" { - key = auth.Prefix + " " + auth.Key - } else { - key = auth.Key + if auth, ok := r.ctx.Value(ContextAPIKeys).(map[string]APIKey); ok { + if apiKey, ok := auth["Bearer"]; ok { + var key string + if apiKey.Prefix != "" { + key = apiKey.Prefix + " " + apiKey.Key + } else { + key = apiKey.Key + } + localVarHeaderParams["Authorization"] = key } - localVarHeaderParams["Authorization"] = key - } } - r, err := a.client.prepareRequest(ctx, localVarPath, localVarHttpMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFileName, localVarFileBytes) + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { return nil, err } - localVarHttpResponse, err := a.client.callAPI(r) - if err != nil || localVarHttpResponse == nil { - return localVarHttpResponse, err + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err } - localVarBody, err := ioutil.ReadAll(localVarHttpResponse.Body) - localVarHttpResponse.Body.Close() + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) if err != nil { - return localVarHttpResponse, err + return localVarHTTPResponse, err } - if localVarHttpResponse.StatusCode >= 300 { - newErr := GenericSwaggerError{ + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ body: localVarBody, - error: localVarHttpResponse.Status, + error: localVarHTTPResponse.Status, } - return localVarHttpResponse, newErr + return localVarHTTPResponse, newErr } - return localVarHttpResponse, nil + return localVarHTTPResponse, nil } diff --git a/api/client/client.go b/api/client/client.go index 2cd231ed8..74ea0ed83 100644 --- a/api/client/client.go +++ b/api/client/client.go @@ -1,11 +1,13 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( @@ -16,8 +18,10 @@ import ( "errors" "fmt" "io" + "log" "mime/multipart" "net/http" + "net/http/httputil" "net/url" "os" "path/filepath" @@ -27,13 +31,13 @@ import ( "strings" "time" "unicode/utf8" - - "golang.org/x/oauth2" ) var ( - jsonCheck = regexp.MustCompile("(?i:[application|text]/json)") - xmlCheck = regexp.MustCompile("(?i:[application|text]/xml)") + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) + queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) + queryDescape = strings.NewReplacer("%5B", "[", "%5D", "]") ) // APIClient manages communication with the Merlin API v0.14.0 @@ -44,27 +48,27 @@ type APIClient struct { // API Services - AlertApi *AlertApiService + EndpointAPI *EndpointAPIService - EndpointApi *EndpointApiService + EnvironmentAPI *EnvironmentAPIService - EnvironmentApi *EnvironmentApiService + LogAPI *LogAPIService - LogApi *LogApiService + ModelEndpointsAPI *ModelEndpointsAPIService - ModelEndpointsApi *ModelEndpointsApiService + ModelSchemaAPI *ModelSchemaAPIService - ModelsApi *ModelsApiService + ModelsAPI *ModelsAPIService - PredictionJobsApi *PredictionJobsApiService + PredictionJobsAPI *PredictionJobsAPIService - ProjectApi *ProjectApiService + ProjectAPI *ProjectAPIService - SecretApi *SecretApiService + SecretAPI *SecretAPIService - StandardTransformerApi *StandardTransformerApiService + StandardTransformerAPI *StandardTransformerAPIService - VersionApi *VersionApiService + VersionAPI *VersionAPIService } type service struct { @@ -83,17 +87,17 @@ func NewAPIClient(cfg *Configuration) *APIClient { c.common.client = c // API Services - c.AlertApi = (*AlertApiService)(&c.common) - c.EndpointApi = (*EndpointApiService)(&c.common) - c.EnvironmentApi = (*EnvironmentApiService)(&c.common) - c.LogApi = (*LogApiService)(&c.common) - c.ModelEndpointsApi = (*ModelEndpointsApiService)(&c.common) - c.ModelsApi = (*ModelsApiService)(&c.common) - c.PredictionJobsApi = (*PredictionJobsApiService)(&c.common) - c.ProjectApi = (*ProjectApiService)(&c.common) - c.SecretApi = (*SecretApiService)(&c.common) - c.StandardTransformerApi = (*StandardTransformerApiService)(&c.common) - c.VersionApi = (*VersionApiService)(&c.common) + c.EndpointAPI = (*EndpointAPIService)(&c.common) + c.EnvironmentAPI = (*EnvironmentAPIService)(&c.common) + c.LogAPI = (*LogAPIService)(&c.common) + c.ModelEndpointsAPI = (*ModelEndpointsAPIService)(&c.common) + c.ModelSchemaAPI = (*ModelSchemaAPIService)(&c.common) + c.ModelsAPI = (*ModelsAPIService)(&c.common) + c.PredictionJobsAPI = (*PredictionJobsAPIService)(&c.common) + c.ProjectAPI = (*ProjectAPIService)(&c.common) + c.SecretAPI = (*SecretAPIService)(&c.common) + c.StandardTransformerAPI = (*StandardTransformerAPIService)(&c.common) + c.VersionAPI = (*VersionAPIService)(&c.common) return c } @@ -126,10 +130,10 @@ func selectHeaderAccept(accepts []string) string { return strings.Join(accepts, ",") } -// contains is a case insenstive match, finding needle in a haystack +// contains is a case insensitive match, finding needle in a haystack func contains(haystack []string, needle string) bool { for _, a := range haystack { - if strings.ToLower(a) == strings.ToLower(needle) { + if strings.EqualFold(a, needle) { return true } } @@ -145,41 +149,157 @@ func typeCheckParameter(obj interface{}, expected string, name string) error { // Check the type is as expected. if reflect.TypeOf(obj).String() != expected { - return fmt.Errorf("Expected %s to be of type %s but received %s.", name, expected, reflect.TypeOf(obj).String()) + return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String()) } return nil } -// parameterToString convert interface{} parameters to string, using a delimiter if format is provided. -func parameterToString(obj interface{}, collectionFormat string) string { - var delimiter string +func parameterValueToString(obj interface{}, key string) string { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + return fmt.Sprintf("%v", obj) + } + var param, ok = obj.(MappedNullable) + if !ok { + return "" + } + dataMap, err := param.ToMap() + if err != nil { + return "" + } + return fmt.Sprintf("%v", dataMap[key]) +} + +// parameterAddToHeaderOrQuery adds the provided object to the request header or url query +// supporting deep object syntax +func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, collectionType string) { + var v = reflect.ValueOf(obj) + var value = "" + if v == reflect.ValueOf(nil) { + value = "null" + } else { + switch v.Kind() { + case reflect.Invalid: + value = "invalid" + + case reflect.Struct: + if t, ok := obj.(MappedNullable); ok { + dataMap, err := t.ToMap() + if err != nil { + return + } + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, collectionType) + return + } + if t, ok := obj.(time.Time); ok { + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339), collectionType) + return + } + value = v.Type().String() + " value" + case reflect.Slice: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + var lenIndValue = indValue.Len() + for i := 0; i < lenIndValue; i++ { + var arrayValue = indValue.Index(i) + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, arrayValue.Interface(), collectionType) + } + return - switch collectionFormat { - case "pipes": - delimiter = "|" - case "ssv": - delimiter = " " - case "tsv": - delimiter = "\t" - case "csv": - delimiter = "," + case reflect.Map: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + iter := indValue.MapRange() + for iter.Next() { + k, v := iter.Key(), iter.Value() + parameterAddToHeaderOrQuery(headerOrQueryParams, fmt.Sprintf("%s[%s]", keyPrefix, k.String()), v.Interface(), collectionType) + } + return + + case reflect.Interface: + fallthrough + case reflect.Ptr: + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, v.Elem().Interface(), collectionType) + return + + case reflect.Int, reflect.Int8, reflect.Int16, + reflect.Int32, reflect.Int64: + value = strconv.FormatInt(v.Int(), 10) + case reflect.Uint, reflect.Uint8, reflect.Uint16, + reflect.Uint32, reflect.Uint64, reflect.Uintptr: + value = strconv.FormatUint(v.Uint(), 10) + case reflect.Float32, reflect.Float64: + value = strconv.FormatFloat(v.Float(), 'g', -1, 32) + case reflect.Bool: + value = strconv.FormatBool(v.Bool()) + case reflect.String: + value = v.String() + default: + value = v.Type().String() + " value" + } } - if reflect.TypeOf(obj).Kind() == reflect.Slice { - return strings.Trim(strings.Replace(fmt.Sprint(obj), " ", delimiter, -1), "[]") + switch valuesMap := headerOrQueryParams.(type) { + case url.Values: + if collectionType == "csv" && valuesMap.Get(keyPrefix) != "" { + valuesMap.Set(keyPrefix, valuesMap.Get(keyPrefix)+","+value) + } else { + valuesMap.Add(keyPrefix, value) + } + break + case map[string]string: + valuesMap[keyPrefix] = value + break } +} - return fmt.Sprintf("%v", obj) +// helper for converting interface{} parameters to json strings +func parameterToJson(obj interface{}) (string, error) { + jsonBuf, err := json.Marshal(obj) + if err != nil { + return "", err + } + return string(jsonBuf), err } // callAPI do the request. func (c *APIClient) callAPI(request *http.Request) (*http.Response, error) { - return c.cfg.HTTPClient.Do(request) + if c.cfg.Debug { + dump, err := httputil.DumpRequestOut(request, true) + if err != nil { + return nil, err + } + log.Printf("\n%s\n", string(dump)) + } + + resp, err := c.cfg.HTTPClient.Do(request) + if err != nil { + return resp, err + } + + if c.cfg.Debug { + dump, err := httputil.DumpResponse(resp, true) + if err != nil { + return resp, err + } + log.Printf("\n%s\n", string(dump)) + } + return resp, err +} + +// Allow modification of underlying config for alternate implementations and testing +// Caution: modifying the configuration while live can cause data races and potentially unwanted behavior +func (c *APIClient) GetConfig() *Configuration { + return c.cfg } -// Change base path to allow switching to mocks -func (c *APIClient) ChangeBasePath(path string) { - c.cfg.BasePath = path +type formFile struct { + fileBytes []byte + fileName string + formFileName string } // prepareRequest build the request @@ -190,8 +310,7 @@ func (c *APIClient) prepareRequest( headerParams map[string]string, queryParams url.Values, formParams url.Values, - fileName string, - fileBytes []byte) (localVarRequest *http.Request, err error) { + formFiles []formFile) (localVarRequest *http.Request, err error) { var body *bytes.Buffer @@ -210,7 +329,7 @@ func (c *APIClient) prepareRequest( } // add form parameters and file if available. - if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(fileBytes) > 0 && fileName != "") { + if strings.HasPrefix(headerParams["Content-Type"], "multipart/form-data") && len(formParams) > 0 || (len(formFiles) > 0) { if body != nil { return nil, errors.New("Cannot specify postBody and multipart form at the same time.") } @@ -229,21 +348,23 @@ func (c *APIClient) prepareRequest( } } } - if len(fileBytes) > 0 && fileName != "" { - w.Boundary() - //_, fileNm := filepath.Split(fileName) - part, err := w.CreateFormFile("file", filepath.Base(fileName)) - if err != nil { - return nil, err - } - _, err = part.Write(fileBytes) - if err != nil { - return nil, err + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } } - // Set the Boundary in the Content-Type - headerParams["Content-Type"] = w.FormDataContentType() } + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + // Set Content-Length headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) w.Close() @@ -265,6 +386,16 @@ func (c *APIClient) prepareRequest( return nil, err } + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + // Adding Query Param query := url.Query() for k, v := range queryParams { @@ -274,7 +405,11 @@ func (c *APIClient) prepareRequest( } // Encode the parameters. - url.RawQuery = query.Encode() + url.RawQuery = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string { + pieces := strings.Split(s, "=") + pieces[0] = queryDescape.Replace(pieces[0]) + return strings.Join(pieces, "=") + }) // Generate a new request if body != nil { @@ -290,16 +425,11 @@ func (c *APIClient) prepareRequest( if len(headerParams) > 0 { headers := http.Header{} for h, v := range headerParams { - headers.Set(h, v) + headers[h] = []string{v} } localVarRequest.Header = headers } - // Override request host, if applicable - if c.cfg.Host != "" { - localVarRequest.Host = c.cfg.Host - } - // Add the user agent to the request. localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) @@ -309,43 +439,62 @@ func (c *APIClient) prepareRequest( // Walk through any authentication. - // OAuth2 authentication - if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { - // We were able to grab an oauth2 token from the context - var latestToken *oauth2.Token - if latestToken, err = tok.Token(); err != nil { - return nil, err - } - - latestToken.SetAuthHeader(localVarRequest) - } - - // Basic HTTP Authentication - if auth, ok := ctx.Value(ContextBasicAuth).(BasicAuth); ok { - localVarRequest.SetBasicAuth(auth.UserName, auth.Password) - } - - // AccessToken Authentication - if auth, ok := ctx.Value(ContextAccessToken).(string); ok { - localVarRequest.Header.Add("Authorization", "Bearer "+auth) - } } for header, value := range c.cfg.DefaultHeader { localVarRequest.Header.Add(header, value) } - return localVarRequest, nil } func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { - if strings.Contains(contentType, "application/xml") { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if f, ok := v.(*os.File); ok { + f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = f.Write(b) + if err != nil { + return + } + _, err = f.Seek(0, io.SeekStart) + return + } + if f, ok := v.(**os.File); ok { + *f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil - } else if strings.Contains(contentType, "application/json") { - if err = json.Unmarshal(b, v); err != nil { + } + if JsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err != nil { + return err + } + } else { + return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model return err } return nil @@ -355,11 +504,14 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err // Add a file to the multipart request func addFile(w *multipart.Writer, fieldName, path string) error { - file, err := os.Open(path) + file, err := os.Open(filepath.Clean(path)) + if err != nil { + return err + } + err = file.Close() if err != nil { return err } - defer file.Close() part, err := w.CreateFormFile(fieldName, filepath.Base(path)) if err != nil { @@ -375,6 +527,13 @@ func reportError(format string, a ...interface{}) error { return fmt.Errorf(format, a...) } +// A wrapper for strict JSON decoding +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} + // Set request body from an interface{} func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { if bodyBuf == nil { @@ -383,16 +542,22 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e if reader, ok := body.(io.Reader); ok { _, err = bodyBuf.ReadFrom(reader) + } else if fp, ok := body.(*os.File); ok { + _, err = bodyBuf.ReadFrom(fp) } else if b, ok := body.([]byte); ok { _, err = bodyBuf.Write(b) } else if s, ok := body.(string); ok { _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { - xml.NewEncoder(bodyBuf).Encode(body) + } else if XmlCheck.MatchString(contentType) { + var bs []byte + bs, err = xml.Marshal(body) + if err == nil { + bodyBuf.Write(bs) + } } if err != nil { @@ -400,7 +565,7 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e } if bodyBuf.Len() == 0 { - err = fmt.Errorf("Invalid body type %s\n", contentType) + err = fmt.Errorf("invalid body type %s\n", contentType) return nil, err } return bodyBuf, nil @@ -462,8 +627,9 @@ func CacheExpires(r *http.Response) time.Time { lifetime, err := time.ParseDuration(maxAge + "s") if err != nil { expires = now + } else { + expires = now.Add(lifetime) } - expires = now.Add(lifetime) } else { expiresHeader := r.Header.Get("Expires") if expiresHeader != "" { @@ -480,24 +646,44 @@ func strlen(s string) int { return utf8.RuneCountInString(s) } -// GenericSwaggerError Provides access to the body, error and model on returned errors. -type GenericSwaggerError struct { +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { body []byte error string model interface{} } // Error returns non-empty string if there was an error. -func (e GenericSwaggerError) Error() string { +func (e GenericOpenAPIError) Error() string { return e.error } // Body returns the raw bytes of the response -func (e GenericSwaggerError) Body() []byte { +func (e GenericOpenAPIError) Body() []byte { return e.body } // Model returns the unpacked model of the error -func (e GenericSwaggerError) Model() interface{} { +func (e GenericOpenAPIError) Model() interface{} { return e.model } + +// format error message using title and detail when model implements rfc7807 +func formatErrorMessage(status string, v interface{}) string { + str := "" + metaValue := reflect.ValueOf(v).Elem() + + if metaValue.Kind() == reflect.Struct { + field := metaValue.FieldByName("Title") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s", field.Interface()) + } + + field = metaValue.FieldByName("Detail") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s (%s)", str, field.Interface()) + } + } + + return strings.TrimSpace(fmt.Sprintf("%s %s", status, str)) +} diff --git a/api/client/configuration.go b/api/client/configuration.go index 7689c0a78..ec7d9c38d 100644 --- a/api/client/configuration.go +++ b/api/client/configuration.go @@ -1,15 +1,20 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "context" + "fmt" "net/http" + "strings" ) // contextKeys are used to identify the type of value in the context. @@ -23,17 +28,20 @@ func (c contextKey) String() string { } var ( - // ContextOAuth2 takes a oauth2.TokenSource as authentication for the request. - ContextOAuth2 = contextKey("token") + // ContextAPIKeys takes a string apikey as authentication for the request + ContextAPIKeys = contextKey("apiKeys") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") - // ContextBasicAuth takes BasicAuth as authentication for the request. - ContextBasicAuth = contextKey("basic") + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") - // ContextAccessToken takes a string oauth2 access token as authentication for the request. - ContextAccessToken = contextKey("accesstoken") + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") - // ContextAPIKey takes an APIKey as authentication for the request - ContextAPIKey = contextKey("apikey") + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") ) // BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth @@ -48,24 +56,162 @@ type APIKey struct { Prefix string } +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client type Configuration struct { - BasePath string `json:"basePath,omitempty"` - Host string `json:"host,omitempty"` - Scheme string `json:"scheme,omitempty"` - DefaultHeader map[string]string `json:"defaultHeader,omitempty"` - UserAgent string `json:"userAgent,omitempty"` - HTTPClient *http.Client + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client } +// NewConfiguration returns a new Configuration object func NewConfiguration() *Configuration { cfg := &Configuration{ - BasePath: "http://localhost:8080/v1", DefaultHeader: make(map[string]string), - UserAgent: "Swagger-Codegen/1.0.0/go", + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://localhost:8080/v1", + Description: "No description provided", + }, + }, + OperationServers: map[string]ServerConfigurations{}, } return cfg } +// AddDefaultHeader adds a new HTTP header to the default header in the request func (c *Configuration) AddDefaultHeader(key string, value string) { c.DefaultHeader[key] = value } + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/api/client/model_alert_condition_metric_type.go b/api/client/model_alert_condition_metric_type.go index 38ba1adaf..f331e1c33 100644 --- a/api/client/model_alert_condition_metric_type.go +++ b/api/client/model_alert_condition_metric_type.go @@ -1,20 +1,116 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// AlertConditionMetricType the model 'AlertConditionMetricType' type AlertConditionMetricType string // List of AlertConditionMetricType const ( - THROUGHPUT_AlertConditionMetricType AlertConditionMetricType = "throughput" - LATENCY_AlertConditionMetricType AlertConditionMetricType = "latency" - ERROR_RATE_AlertConditionMetricType AlertConditionMetricType = "error_rate" - CPU_AlertConditionMetricType AlertConditionMetricType = "cpu" - MEMORY_AlertConditionMetricType AlertConditionMetricType = "memory" + ALERTCONDITIONMETRICTYPE_THROUGHPUT AlertConditionMetricType = "throughput" + ALERTCONDITIONMETRICTYPE_LATENCY AlertConditionMetricType = "latency" + ALERTCONDITIONMETRICTYPE_ERROR_RATE AlertConditionMetricType = "error_rate" + ALERTCONDITIONMETRICTYPE_CPU AlertConditionMetricType = "cpu" + ALERTCONDITIONMETRICTYPE_MEMORY AlertConditionMetricType = "memory" ) + +// All allowed values of AlertConditionMetricType enum +var AllowedAlertConditionMetricTypeEnumValues = []AlertConditionMetricType{ + "throughput", + "latency", + "error_rate", + "cpu", + "memory", +} + +func (v *AlertConditionMetricType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := AlertConditionMetricType(value) + for _, existing := range AllowedAlertConditionMetricTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid AlertConditionMetricType", value) +} + +// NewAlertConditionMetricTypeFromValue returns a pointer to a valid AlertConditionMetricType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewAlertConditionMetricTypeFromValue(v string) (*AlertConditionMetricType, error) { + ev := AlertConditionMetricType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for AlertConditionMetricType: valid values are %v", v, AllowedAlertConditionMetricTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v AlertConditionMetricType) IsValid() bool { + for _, existing := range AllowedAlertConditionMetricTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to AlertConditionMetricType value +func (v AlertConditionMetricType) Ptr() *AlertConditionMetricType { + return &v +} + +type NullableAlertConditionMetricType struct { + value *AlertConditionMetricType + isSet bool +} + +func (v NullableAlertConditionMetricType) Get() *AlertConditionMetricType { + return v.value +} + +func (v *NullableAlertConditionMetricType) Set(val *AlertConditionMetricType) { + v.value = val + v.isSet = true +} + +func (v NullableAlertConditionMetricType) IsSet() bool { + return v.isSet +} + +func (v *NullableAlertConditionMetricType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAlertConditionMetricType(val *AlertConditionMetricType) *NullableAlertConditionMetricType { + return &NullableAlertConditionMetricType{value: val, isSet: true} +} + +func (v NullableAlertConditionMetricType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAlertConditionMetricType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_alert_condition_severity.go b/api/client/model_alert_condition_severity.go index 10eb58b3d..c580fa5b7 100644 --- a/api/client/model_alert_condition_severity.go +++ b/api/client/model_alert_condition_severity.go @@ -1,17 +1,110 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// AlertConditionSeverity the model 'AlertConditionSeverity' type AlertConditionSeverity string // List of AlertConditionSeverity const ( - WARNING_AlertConditionSeverity AlertConditionSeverity = "WARNING" - CRITICAL_AlertConditionSeverity AlertConditionSeverity = "CRITICAL" + ALERTCONDITIONSEVERITY_WARNING AlertConditionSeverity = "WARNING" + ALERTCONDITIONSEVERITY_CRITICAL AlertConditionSeverity = "CRITICAL" ) + +// All allowed values of AlertConditionSeverity enum +var AllowedAlertConditionSeverityEnumValues = []AlertConditionSeverity{ + "WARNING", + "CRITICAL", +} + +func (v *AlertConditionSeverity) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := AlertConditionSeverity(value) + for _, existing := range AllowedAlertConditionSeverityEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid AlertConditionSeverity", value) +} + +// NewAlertConditionSeverityFromValue returns a pointer to a valid AlertConditionSeverity +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewAlertConditionSeverityFromValue(v string) (*AlertConditionSeverity, error) { + ev := AlertConditionSeverity(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for AlertConditionSeverity: valid values are %v", v, AllowedAlertConditionSeverityEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v AlertConditionSeverity) IsValid() bool { + for _, existing := range AllowedAlertConditionSeverityEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to AlertConditionSeverity value +func (v AlertConditionSeverity) Ptr() *AlertConditionSeverity { + return &v +} + +type NullableAlertConditionSeverity struct { + value *AlertConditionSeverity + isSet bool +} + +func (v NullableAlertConditionSeverity) Get() *AlertConditionSeverity { + return v.value +} + +func (v *NullableAlertConditionSeverity) Set(val *AlertConditionSeverity) { + v.value = val + v.isSet = true +} + +func (v NullableAlertConditionSeverity) IsSet() bool { + return v.isSet +} + +func (v *NullableAlertConditionSeverity) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAlertConditionSeverity(val *AlertConditionSeverity) *NullableAlertConditionSeverity { + return &NullableAlertConditionSeverity{value: val, isSet: true} +} + +func (v NullableAlertConditionSeverity) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAlertConditionSeverity) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_autoscaling_policy.go b/api/client/model_autoscaling_policy.go index 4c60c3ffd..d636c1217 100644 --- a/api/client/model_autoscaling_policy.go +++ b/api/client/model_autoscaling_policy.go @@ -1,14 +1,181 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// checks if the AutoscalingPolicy type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &AutoscalingPolicy{} + +// AutoscalingPolicy struct for AutoscalingPolicy type AutoscalingPolicy struct { - MetricsType *MetricsType `json:"metrics_type,omitempty"` - TargetValue float64 `json:"target_value,omitempty"` + MetricsType MetricsType `json:"metrics_type"` + TargetValue float32 `json:"target_value"` +} + +type _AutoscalingPolicy AutoscalingPolicy + +// NewAutoscalingPolicy instantiates a new AutoscalingPolicy object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewAutoscalingPolicy(metricsType MetricsType, targetValue float32) *AutoscalingPolicy { + this := AutoscalingPolicy{} + this.MetricsType = metricsType + this.TargetValue = targetValue + return &this +} + +// NewAutoscalingPolicyWithDefaults instantiates a new AutoscalingPolicy object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewAutoscalingPolicyWithDefaults() *AutoscalingPolicy { + this := AutoscalingPolicy{} + return &this +} + +// GetMetricsType returns the MetricsType field value +func (o *AutoscalingPolicy) GetMetricsType() MetricsType { + if o == nil { + var ret MetricsType + return ret + } + + return o.MetricsType +} + +// GetMetricsTypeOk returns a tuple with the MetricsType field value +// and a boolean to check if the value has been set. +func (o *AutoscalingPolicy) GetMetricsTypeOk() (*MetricsType, bool) { + if o == nil { + return nil, false + } + return &o.MetricsType, true +} + +// SetMetricsType sets field value +func (o *AutoscalingPolicy) SetMetricsType(v MetricsType) { + o.MetricsType = v +} + +// GetTargetValue returns the TargetValue field value +func (o *AutoscalingPolicy) GetTargetValue() float32 { + if o == nil { + var ret float32 + return ret + } + + return o.TargetValue +} + +// GetTargetValueOk returns a tuple with the TargetValue field value +// and a boolean to check if the value has been set. +func (o *AutoscalingPolicy) GetTargetValueOk() (*float32, bool) { + if o == nil { + return nil, false + } + return &o.TargetValue, true +} + +// SetTargetValue sets field value +func (o *AutoscalingPolicy) SetTargetValue(v float32) { + o.TargetValue = v +} + +func (o AutoscalingPolicy) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o AutoscalingPolicy) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["metrics_type"] = o.MetricsType + toSerialize["target_value"] = o.TargetValue + return toSerialize, nil +} + +func (o *AutoscalingPolicy) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "metrics_type", + "target_value", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varAutoscalingPolicy := _AutoscalingPolicy{} + + err = json.Unmarshal(bytes, &varAutoscalingPolicy) + + if err != nil { + return err + } + + *o = AutoscalingPolicy(varAutoscalingPolicy) + + return err +} + +type NullableAutoscalingPolicy struct { + value *AutoscalingPolicy + isSet bool +} + +func (v NullableAutoscalingPolicy) Get() *AutoscalingPolicy { + return v.value +} + +func (v *NullableAutoscalingPolicy) Set(val *AutoscalingPolicy) { + v.value = val + v.isSet = true +} + +func (v NullableAutoscalingPolicy) IsSet() bool { + return v.isSet +} + +func (v *NullableAutoscalingPolicy) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableAutoscalingPolicy(val *AutoscalingPolicy) *NullableAutoscalingPolicy { + return &NullableAutoscalingPolicy{value: val, isSet: true} +} + +func (v NullableAutoscalingPolicy) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableAutoscalingPolicy) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_binary_classification_output.go b/api/client/model_binary_classification_output.go new file mode 100644 index 000000000..a75023589 --- /dev/null +++ b/api/client/model_binary_classification_output.go @@ -0,0 +1,309 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// checks if the BinaryClassificationOutput type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &BinaryClassificationOutput{} + +// BinaryClassificationOutput struct for BinaryClassificationOutput +type BinaryClassificationOutput struct { + PredictionScoreColumn string `json:"prediction_score_column"` + ActualLabelColumn *string `json:"actual_label_column,omitempty"` + PositiveClassLabel string `json:"positive_class_label"` + NegativeClassLabel string `json:"negative_class_label"` + ScoreThreshold *float32 `json:"score_threshold,omitempty"` + OutputClass ModelPredictionOutputClass `json:"output_class"` +} + +type _BinaryClassificationOutput BinaryClassificationOutput + +// NewBinaryClassificationOutput instantiates a new BinaryClassificationOutput object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewBinaryClassificationOutput(predictionScoreColumn string, positiveClassLabel string, negativeClassLabel string, outputClass ModelPredictionOutputClass) *BinaryClassificationOutput { + this := BinaryClassificationOutput{} + this.PredictionScoreColumn = predictionScoreColumn + this.PositiveClassLabel = positiveClassLabel + this.NegativeClassLabel = negativeClassLabel + this.OutputClass = outputClass + return &this +} + +// NewBinaryClassificationOutputWithDefaults instantiates a new BinaryClassificationOutput object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewBinaryClassificationOutputWithDefaults() *BinaryClassificationOutput { + this := BinaryClassificationOutput{} + return &this +} + +// GetPredictionScoreColumn returns the PredictionScoreColumn field value +func (o *BinaryClassificationOutput) GetPredictionScoreColumn() string { + if o == nil { + var ret string + return ret + } + + return o.PredictionScoreColumn +} + +// GetPredictionScoreColumnOk returns a tuple with the PredictionScoreColumn field value +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetPredictionScoreColumnOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PredictionScoreColumn, true +} + +// SetPredictionScoreColumn sets field value +func (o *BinaryClassificationOutput) SetPredictionScoreColumn(v string) { + o.PredictionScoreColumn = v +} + +// GetActualLabelColumn returns the ActualLabelColumn field value if set, zero value otherwise. +func (o *BinaryClassificationOutput) GetActualLabelColumn() string { + if o == nil || IsNil(o.ActualLabelColumn) { + var ret string + return ret + } + return *o.ActualLabelColumn +} + +// GetActualLabelColumnOk returns a tuple with the ActualLabelColumn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetActualLabelColumnOk() (*string, bool) { + if o == nil || IsNil(o.ActualLabelColumn) { + return nil, false + } + return o.ActualLabelColumn, true +} + +// HasActualLabelColumn returns a boolean if a field has been set. +func (o *BinaryClassificationOutput) HasActualLabelColumn() bool { + if o != nil && !IsNil(o.ActualLabelColumn) { + return true + } + + return false +} + +// SetActualLabelColumn gets a reference to the given string and assigns it to the ActualLabelColumn field. +func (o *BinaryClassificationOutput) SetActualLabelColumn(v string) { + o.ActualLabelColumn = &v +} + +// GetPositiveClassLabel returns the PositiveClassLabel field value +func (o *BinaryClassificationOutput) GetPositiveClassLabel() string { + if o == nil { + var ret string + return ret + } + + return o.PositiveClassLabel +} + +// GetPositiveClassLabelOk returns a tuple with the PositiveClassLabel field value +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetPositiveClassLabelOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PositiveClassLabel, true +} + +// SetPositiveClassLabel sets field value +func (o *BinaryClassificationOutput) SetPositiveClassLabel(v string) { + o.PositiveClassLabel = v +} + +// GetNegativeClassLabel returns the NegativeClassLabel field value +func (o *BinaryClassificationOutput) GetNegativeClassLabel() string { + if o == nil { + var ret string + return ret + } + + return o.NegativeClassLabel +} + +// GetNegativeClassLabelOk returns a tuple with the NegativeClassLabel field value +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetNegativeClassLabelOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.NegativeClassLabel, true +} + +// SetNegativeClassLabel sets field value +func (o *BinaryClassificationOutput) SetNegativeClassLabel(v string) { + o.NegativeClassLabel = v +} + +// GetScoreThreshold returns the ScoreThreshold field value if set, zero value otherwise. +func (o *BinaryClassificationOutput) GetScoreThreshold() float32 { + if o == nil || IsNil(o.ScoreThreshold) { + var ret float32 + return ret + } + return *o.ScoreThreshold +} + +// GetScoreThresholdOk returns a tuple with the ScoreThreshold field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetScoreThresholdOk() (*float32, bool) { + if o == nil || IsNil(o.ScoreThreshold) { + return nil, false + } + return o.ScoreThreshold, true +} + +// HasScoreThreshold returns a boolean if a field has been set. +func (o *BinaryClassificationOutput) HasScoreThreshold() bool { + if o != nil && !IsNil(o.ScoreThreshold) { + return true + } + + return false +} + +// SetScoreThreshold gets a reference to the given float32 and assigns it to the ScoreThreshold field. +func (o *BinaryClassificationOutput) SetScoreThreshold(v float32) { + o.ScoreThreshold = &v +} + +// GetOutputClass returns the OutputClass field value +func (o *BinaryClassificationOutput) GetOutputClass() ModelPredictionOutputClass { + if o == nil { + var ret ModelPredictionOutputClass + return ret + } + + return o.OutputClass +} + +// GetOutputClassOk returns a tuple with the OutputClass field value +// and a boolean to check if the value has been set. +func (o *BinaryClassificationOutput) GetOutputClassOk() (*ModelPredictionOutputClass, bool) { + if o == nil { + return nil, false + } + return &o.OutputClass, true +} + +// SetOutputClass sets field value +func (o *BinaryClassificationOutput) SetOutputClass(v ModelPredictionOutputClass) { + o.OutputClass = v +} + +func (o BinaryClassificationOutput) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o BinaryClassificationOutput) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["prediction_score_column"] = o.PredictionScoreColumn + if !IsNil(o.ActualLabelColumn) { + toSerialize["actual_label_column"] = o.ActualLabelColumn + } + toSerialize["positive_class_label"] = o.PositiveClassLabel + toSerialize["negative_class_label"] = o.NegativeClassLabel + if !IsNil(o.ScoreThreshold) { + toSerialize["score_threshold"] = o.ScoreThreshold + } + toSerialize["output_class"] = o.OutputClass + return toSerialize, nil +} + +func (o *BinaryClassificationOutput) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "prediction_score_column", + "positive_class_label", + "negative_class_label", + "output_class", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varBinaryClassificationOutput := _BinaryClassificationOutput{} + + err = json.Unmarshal(bytes, &varBinaryClassificationOutput) + + if err != nil { + return err + } + + *o = BinaryClassificationOutput(varBinaryClassificationOutput) + + return err +} + +type NullableBinaryClassificationOutput struct { + value *BinaryClassificationOutput + isSet bool +} + +func (v NullableBinaryClassificationOutput) Get() *BinaryClassificationOutput { + return v.value +} + +func (v *NullableBinaryClassificationOutput) Set(val *BinaryClassificationOutput) { + v.value = val + v.isSet = true +} + +func (v NullableBinaryClassificationOutput) IsSet() bool { + return v.isSet +} + +func (v *NullableBinaryClassificationOutput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBinaryClassificationOutput(val *BinaryClassificationOutput) *NullableBinaryClassificationOutput { + return &NullableBinaryClassificationOutput{value: val, isSet: true} +} + +func (v NullableBinaryClassificationOutput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBinaryClassificationOutput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_config.go b/api/client/model_config.go index 5259f55e9..80107d9e3 100644 --- a/api/client/model_config.go +++ b/api/client/model_config.go @@ -1,18 +1,304 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the Config type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Config{} + +// Config struct for Config type Config struct { JobConfig *PredictionJobConfig `json:"job_config,omitempty"` - ImageRef string `json:"image_ref,omitempty"` - ServiceAccountName string `json:"service_account_name,omitempty"` + ImageRef *string `json:"image_ref,omitempty"` + ServiceAccountName *string `json:"service_account_name,omitempty"` ResourceRequest *PredictionJobResourceRequest `json:"resource_request,omitempty"` ImageBuilderResourceRequest *ResourceRequest `json:"image_builder_resource_request,omitempty"` EnvVars []EnvVar `json:"env_vars,omitempty"` } + +// NewConfig instantiates a new Config object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewConfig() *Config { + this := Config{} + return &this +} + +// NewConfigWithDefaults instantiates a new Config object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewConfigWithDefaults() *Config { + this := Config{} + return &this +} + +// GetJobConfig returns the JobConfig field value if set, zero value otherwise. +func (o *Config) GetJobConfig() PredictionJobConfig { + if o == nil || IsNil(o.JobConfig) { + var ret PredictionJobConfig + return ret + } + return *o.JobConfig +} + +// GetJobConfigOk returns a tuple with the JobConfig field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetJobConfigOk() (*PredictionJobConfig, bool) { + if o == nil || IsNil(o.JobConfig) { + return nil, false + } + return o.JobConfig, true +} + +// HasJobConfig returns a boolean if a field has been set. +func (o *Config) HasJobConfig() bool { + if o != nil && !IsNil(o.JobConfig) { + return true + } + + return false +} + +// SetJobConfig gets a reference to the given PredictionJobConfig and assigns it to the JobConfig field. +func (o *Config) SetJobConfig(v PredictionJobConfig) { + o.JobConfig = &v +} + +// GetImageRef returns the ImageRef field value if set, zero value otherwise. +func (o *Config) GetImageRef() string { + if o == nil || IsNil(o.ImageRef) { + var ret string + return ret + } + return *o.ImageRef +} + +// GetImageRefOk returns a tuple with the ImageRef field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetImageRefOk() (*string, bool) { + if o == nil || IsNil(o.ImageRef) { + return nil, false + } + return o.ImageRef, true +} + +// HasImageRef returns a boolean if a field has been set. +func (o *Config) HasImageRef() bool { + if o != nil && !IsNil(o.ImageRef) { + return true + } + + return false +} + +// SetImageRef gets a reference to the given string and assigns it to the ImageRef field. +func (o *Config) SetImageRef(v string) { + o.ImageRef = &v +} + +// GetServiceAccountName returns the ServiceAccountName field value if set, zero value otherwise. +func (o *Config) GetServiceAccountName() string { + if o == nil || IsNil(o.ServiceAccountName) { + var ret string + return ret + } + return *o.ServiceAccountName +} + +// GetServiceAccountNameOk returns a tuple with the ServiceAccountName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetServiceAccountNameOk() (*string, bool) { + if o == nil || IsNil(o.ServiceAccountName) { + return nil, false + } + return o.ServiceAccountName, true +} + +// HasServiceAccountName returns a boolean if a field has been set. +func (o *Config) HasServiceAccountName() bool { + if o != nil && !IsNil(o.ServiceAccountName) { + return true + } + + return false +} + +// SetServiceAccountName gets a reference to the given string and assigns it to the ServiceAccountName field. +func (o *Config) SetServiceAccountName(v string) { + o.ServiceAccountName = &v +} + +// GetResourceRequest returns the ResourceRequest field value if set, zero value otherwise. +func (o *Config) GetResourceRequest() PredictionJobResourceRequest { + if o == nil || IsNil(o.ResourceRequest) { + var ret PredictionJobResourceRequest + return ret + } + return *o.ResourceRequest +} + +// GetResourceRequestOk returns a tuple with the ResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetResourceRequestOk() (*PredictionJobResourceRequest, bool) { + if o == nil || IsNil(o.ResourceRequest) { + return nil, false + } + return o.ResourceRequest, true +} + +// HasResourceRequest returns a boolean if a field has been set. +func (o *Config) HasResourceRequest() bool { + if o != nil && !IsNil(o.ResourceRequest) { + return true + } + + return false +} + +// SetResourceRequest gets a reference to the given PredictionJobResourceRequest and assigns it to the ResourceRequest field. +func (o *Config) SetResourceRequest(v PredictionJobResourceRequest) { + o.ResourceRequest = &v +} + +// GetImageBuilderResourceRequest returns the ImageBuilderResourceRequest field value if set, zero value otherwise. +func (o *Config) GetImageBuilderResourceRequest() ResourceRequest { + if o == nil || IsNil(o.ImageBuilderResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.ImageBuilderResourceRequest +} + +// GetImageBuilderResourceRequestOk returns a tuple with the ImageBuilderResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetImageBuilderResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.ImageBuilderResourceRequest) { + return nil, false + } + return o.ImageBuilderResourceRequest, true +} + +// HasImageBuilderResourceRequest returns a boolean if a field has been set. +func (o *Config) HasImageBuilderResourceRequest() bool { + if o != nil && !IsNil(o.ImageBuilderResourceRequest) { + return true + } + + return false +} + +// SetImageBuilderResourceRequest gets a reference to the given ResourceRequest and assigns it to the ImageBuilderResourceRequest field. +func (o *Config) SetImageBuilderResourceRequest(v ResourceRequest) { + o.ImageBuilderResourceRequest = &v +} + +// GetEnvVars returns the EnvVars field value if set, zero value otherwise. +func (o *Config) GetEnvVars() []EnvVar { + if o == nil || IsNil(o.EnvVars) { + var ret []EnvVar + return ret + } + return o.EnvVars +} + +// GetEnvVarsOk returns a tuple with the EnvVars field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Config) GetEnvVarsOk() ([]EnvVar, bool) { + if o == nil || IsNil(o.EnvVars) { + return nil, false + } + return o.EnvVars, true +} + +// HasEnvVars returns a boolean if a field has been set. +func (o *Config) HasEnvVars() bool { + if o != nil && !IsNil(o.EnvVars) { + return true + } + + return false +} + +// SetEnvVars gets a reference to the given []EnvVar and assigns it to the EnvVars field. +func (o *Config) SetEnvVars(v []EnvVar) { + o.EnvVars = v +} + +func (o Config) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Config) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.JobConfig) { + toSerialize["job_config"] = o.JobConfig + } + if !IsNil(o.ImageRef) { + toSerialize["image_ref"] = o.ImageRef + } + if !IsNil(o.ServiceAccountName) { + toSerialize["service_account_name"] = o.ServiceAccountName + } + if !IsNil(o.ResourceRequest) { + toSerialize["resource_request"] = o.ResourceRequest + } + if !IsNil(o.ImageBuilderResourceRequest) { + toSerialize["image_builder_resource_request"] = o.ImageBuilderResourceRequest + } + if !IsNil(o.EnvVars) { + toSerialize["env_vars"] = o.EnvVars + } + return toSerialize, nil +} + +type NullableConfig struct { + value *Config + isSet bool +} + +func (v NullableConfig) Get() *Config { + return v.value +} + +func (v *NullableConfig) Set(val *Config) { + v.value = val + v.isSet = true +} + +func (v NullableConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableConfig(val *Config) *NullableConfig { + return &NullableConfig{value: val, isSet: true} +} + +func (v NullableConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_container.go b/api/client/model_container.go index a80a9cbed..cfd9adda8 100644 --- a/api/client/model_container.go +++ b/api/client/model_container.go @@ -1,19 +1,340 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the Container type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Container{} + +// Container struct for Container type Container struct { - Name string `json:"name,omitempty"` - PodName string `json:"pod_name,omitempty"` - ComponentType string `json:"component_type,omitempty"` - Namespace string `json:"namespace,omitempty"` - Cluster string `json:"cluster,omitempty"` - GcpProject string `json:"gcp_project,omitempty"` - VersionEndpointId int32 `json:"version_endpoint_id,omitempty"` + Name *string `json:"name,omitempty"` + PodName *string `json:"pod_name,omitempty"` + ComponentType *string `json:"component_type,omitempty"` + Namespace *string `json:"namespace,omitempty"` + Cluster *string `json:"cluster,omitempty"` + GcpProject *string `json:"gcp_project,omitempty"` + VersionEndpointId *int32 `json:"version_endpoint_id,omitempty"` +} + +// NewContainer instantiates a new Container object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewContainer() *Container { + this := Container{} + return &this +} + +// NewContainerWithDefaults instantiates a new Container object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewContainerWithDefaults() *Container { + this := Container{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Container) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Container) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Container) SetName(v string) { + o.Name = &v +} + +// GetPodName returns the PodName field value if set, zero value otherwise. +func (o *Container) GetPodName() string { + if o == nil || IsNil(o.PodName) { + var ret string + return ret + } + return *o.PodName +} + +// GetPodNameOk returns a tuple with the PodName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetPodNameOk() (*string, bool) { + if o == nil || IsNil(o.PodName) { + return nil, false + } + return o.PodName, true +} + +// HasPodName returns a boolean if a field has been set. +func (o *Container) HasPodName() bool { + if o != nil && !IsNil(o.PodName) { + return true + } + + return false +} + +// SetPodName gets a reference to the given string and assigns it to the PodName field. +func (o *Container) SetPodName(v string) { + o.PodName = &v +} + +// GetComponentType returns the ComponentType field value if set, zero value otherwise. +func (o *Container) GetComponentType() string { + if o == nil || IsNil(o.ComponentType) { + var ret string + return ret + } + return *o.ComponentType +} + +// GetComponentTypeOk returns a tuple with the ComponentType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetComponentTypeOk() (*string, bool) { + if o == nil || IsNil(o.ComponentType) { + return nil, false + } + return o.ComponentType, true +} + +// HasComponentType returns a boolean if a field has been set. +func (o *Container) HasComponentType() bool { + if o != nil && !IsNil(o.ComponentType) { + return true + } + + return false +} + +// SetComponentType gets a reference to the given string and assigns it to the ComponentType field. +func (o *Container) SetComponentType(v string) { + o.ComponentType = &v +} + +// GetNamespace returns the Namespace field value if set, zero value otherwise. +func (o *Container) GetNamespace() string { + if o == nil || IsNil(o.Namespace) { + var ret string + return ret + } + return *o.Namespace +} + +// GetNamespaceOk returns a tuple with the Namespace field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetNamespaceOk() (*string, bool) { + if o == nil || IsNil(o.Namespace) { + return nil, false + } + return o.Namespace, true +} + +// HasNamespace returns a boolean if a field has been set. +func (o *Container) HasNamespace() bool { + if o != nil && !IsNil(o.Namespace) { + return true + } + + return false +} + +// SetNamespace gets a reference to the given string and assigns it to the Namespace field. +func (o *Container) SetNamespace(v string) { + o.Namespace = &v +} + +// GetCluster returns the Cluster field value if set, zero value otherwise. +func (o *Container) GetCluster() string { + if o == nil || IsNil(o.Cluster) { + var ret string + return ret + } + return *o.Cluster +} + +// GetClusterOk returns a tuple with the Cluster field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetClusterOk() (*string, bool) { + if o == nil || IsNil(o.Cluster) { + return nil, false + } + return o.Cluster, true +} + +// HasCluster returns a boolean if a field has been set. +func (o *Container) HasCluster() bool { + if o != nil && !IsNil(o.Cluster) { + return true + } + + return false +} + +// SetCluster gets a reference to the given string and assigns it to the Cluster field. +func (o *Container) SetCluster(v string) { + o.Cluster = &v +} + +// GetGcpProject returns the GcpProject field value if set, zero value otherwise. +func (o *Container) GetGcpProject() string { + if o == nil || IsNil(o.GcpProject) { + var ret string + return ret + } + return *o.GcpProject +} + +// GetGcpProjectOk returns a tuple with the GcpProject field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetGcpProjectOk() (*string, bool) { + if o == nil || IsNil(o.GcpProject) { + return nil, false + } + return o.GcpProject, true +} + +// HasGcpProject returns a boolean if a field has been set. +func (o *Container) HasGcpProject() bool { + if o != nil && !IsNil(o.GcpProject) { + return true + } + + return false +} + +// SetGcpProject gets a reference to the given string and assigns it to the GcpProject field. +func (o *Container) SetGcpProject(v string) { + o.GcpProject = &v +} + +// GetVersionEndpointId returns the VersionEndpointId field value if set, zero value otherwise. +func (o *Container) GetVersionEndpointId() int32 { + if o == nil || IsNil(o.VersionEndpointId) { + var ret int32 + return ret + } + return *o.VersionEndpointId +} + +// GetVersionEndpointIdOk returns a tuple with the VersionEndpointId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Container) GetVersionEndpointIdOk() (*int32, bool) { + if o == nil || IsNil(o.VersionEndpointId) { + return nil, false + } + return o.VersionEndpointId, true +} + +// HasVersionEndpointId returns a boolean if a field has been set. +func (o *Container) HasVersionEndpointId() bool { + if o != nil && !IsNil(o.VersionEndpointId) { + return true + } + + return false +} + +// SetVersionEndpointId gets a reference to the given int32 and assigns it to the VersionEndpointId field. +func (o *Container) SetVersionEndpointId(v int32) { + o.VersionEndpointId = &v +} + +func (o Container) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Container) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.PodName) { + toSerialize["pod_name"] = o.PodName + } + if !IsNil(o.ComponentType) { + toSerialize["component_type"] = o.ComponentType + } + if !IsNil(o.Namespace) { + toSerialize["namespace"] = o.Namespace + } + if !IsNil(o.Cluster) { + toSerialize["cluster"] = o.Cluster + } + if !IsNil(o.GcpProject) { + toSerialize["gcp_project"] = o.GcpProject + } + if !IsNil(o.VersionEndpointId) { + toSerialize["version_endpoint_id"] = o.VersionEndpointId + } + return toSerialize, nil +} + +type NullableContainer struct { + value *Container + isSet bool +} + +func (v NullableContainer) Get() *Container { + return v.value +} + +func (v *NullableContainer) Set(val *Container) { + v.value = val + v.isSet = true +} + +func (v NullableContainer) IsSet() bool { + return v.isSet +} + +func (v *NullableContainer) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableContainer(val *Container) *NullableContainer { + return &NullableContainer{value: val, isSet: true} +} + +func (v NullableContainer) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableContainer) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_custom_predictor.go b/api/client/model_custom_predictor.go index 6aea8cdf0..3cc4130f8 100644 --- a/api/client/model_custom_predictor.go +++ b/api/client/model_custom_predictor.go @@ -1,15 +1,196 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the CustomPredictor type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &CustomPredictor{} + +// CustomPredictor struct for CustomPredictor type CustomPredictor struct { - Image string `json:"image,omitempty"` - Command string `json:"command,omitempty"` - Args string `json:"args,omitempty"` + Image *string `json:"image,omitempty"` + Command *string `json:"command,omitempty"` + Args *string `json:"args,omitempty"` +} + +// NewCustomPredictor instantiates a new CustomPredictor object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewCustomPredictor() *CustomPredictor { + this := CustomPredictor{} + return &this +} + +// NewCustomPredictorWithDefaults instantiates a new CustomPredictor object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewCustomPredictorWithDefaults() *CustomPredictor { + this := CustomPredictor{} + return &this +} + +// GetImage returns the Image field value if set, zero value otherwise. +func (o *CustomPredictor) GetImage() string { + if o == nil || IsNil(o.Image) { + var ret string + return ret + } + return *o.Image +} + +// GetImageOk returns a tuple with the Image field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *CustomPredictor) GetImageOk() (*string, bool) { + if o == nil || IsNil(o.Image) { + return nil, false + } + return o.Image, true +} + +// HasImage returns a boolean if a field has been set. +func (o *CustomPredictor) HasImage() bool { + if o != nil && !IsNil(o.Image) { + return true + } + + return false +} + +// SetImage gets a reference to the given string and assigns it to the Image field. +func (o *CustomPredictor) SetImage(v string) { + o.Image = &v +} + +// GetCommand returns the Command field value if set, zero value otherwise. +func (o *CustomPredictor) GetCommand() string { + if o == nil || IsNil(o.Command) { + var ret string + return ret + } + return *o.Command +} + +// GetCommandOk returns a tuple with the Command field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *CustomPredictor) GetCommandOk() (*string, bool) { + if o == nil || IsNil(o.Command) { + return nil, false + } + return o.Command, true +} + +// HasCommand returns a boolean if a field has been set. +func (o *CustomPredictor) HasCommand() bool { + if o != nil && !IsNil(o.Command) { + return true + } + + return false +} + +// SetCommand gets a reference to the given string and assigns it to the Command field. +func (o *CustomPredictor) SetCommand(v string) { + o.Command = &v +} + +// GetArgs returns the Args field value if set, zero value otherwise. +func (o *CustomPredictor) GetArgs() string { + if o == nil || IsNil(o.Args) { + var ret string + return ret + } + return *o.Args +} + +// GetArgsOk returns a tuple with the Args field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *CustomPredictor) GetArgsOk() (*string, bool) { + if o == nil || IsNil(o.Args) { + return nil, false + } + return o.Args, true +} + +// HasArgs returns a boolean if a field has been set. +func (o *CustomPredictor) HasArgs() bool { + if o != nil && !IsNil(o.Args) { + return true + } + + return false +} + +// SetArgs gets a reference to the given string and assigns it to the Args field. +func (o *CustomPredictor) SetArgs(v string) { + o.Args = &v +} + +func (o CustomPredictor) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o CustomPredictor) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Image) { + toSerialize["image"] = o.Image + } + if !IsNil(o.Command) { + toSerialize["command"] = o.Command + } + if !IsNil(o.Args) { + toSerialize["args"] = o.Args + } + return toSerialize, nil +} + +type NullableCustomPredictor struct { + value *CustomPredictor + isSet bool +} + +func (v NullableCustomPredictor) Get() *CustomPredictor { + return v.value +} + +func (v *NullableCustomPredictor) Set(val *CustomPredictor) { + v.value = val + v.isSet = true +} + +func (v NullableCustomPredictor) IsSet() bool { + return v.isSet +} + +func (v *NullableCustomPredictor) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableCustomPredictor(val *CustomPredictor) *NullableCustomPredictor { + return &NullableCustomPredictor{value: val, isSet: true} +} + +func (v NullableCustomPredictor) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableCustomPredictor) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_deployment_mode.go b/api/client/model_deployment_mode.go index de821d8a4..40677aba5 100644 --- a/api/client/model_deployment_mode.go +++ b/api/client/model_deployment_mode.go @@ -1,17 +1,110 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// DeploymentMode the model 'DeploymentMode' type DeploymentMode string // List of DeploymentMode const ( - SERVERLESS_DeploymentMode DeploymentMode = "serverless" - RAW_DEPLOYMENT_DeploymentMode DeploymentMode = "raw_deployment" + DEPLOYMENTMODE_SERVERLESS DeploymentMode = "serverless" + DEPLOYMENTMODE_RAW_DEPLOYMENT DeploymentMode = "raw_deployment" ) + +// All allowed values of DeploymentMode enum +var AllowedDeploymentModeEnumValues = []DeploymentMode{ + "serverless", + "raw_deployment", +} + +func (v *DeploymentMode) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := DeploymentMode(value) + for _, existing := range AllowedDeploymentModeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid DeploymentMode", value) +} + +// NewDeploymentModeFromValue returns a pointer to a valid DeploymentMode +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewDeploymentModeFromValue(v string) (*DeploymentMode, error) { + ev := DeploymentMode(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for DeploymentMode: valid values are %v", v, AllowedDeploymentModeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v DeploymentMode) IsValid() bool { + for _, existing := range AllowedDeploymentModeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to DeploymentMode value +func (v DeploymentMode) Ptr() *DeploymentMode { + return &v +} + +type NullableDeploymentMode struct { + value *DeploymentMode + isSet bool +} + +func (v NullableDeploymentMode) Get() *DeploymentMode { + return v.value +} + +func (v *NullableDeploymentMode) Set(val *DeploymentMode) { + v.value = val + v.isSet = true +} + +func (v NullableDeploymentMode) IsSet() bool { + return v.isSet +} + +func (v *NullableDeploymentMode) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableDeploymentMode(val *DeploymentMode) *NullableDeploymentMode { + return &NullableDeploymentMode{value: val, isSet: true} +} + +func (v NullableDeploymentMode) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableDeploymentMode) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_endpoint_status.go b/api/client/model_endpoint_status.go index 00535bb8c..673bcfec7 100644 --- a/api/client/model_endpoint_status.go +++ b/api/client/model_endpoint_status.go @@ -1,20 +1,116 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// EndpointStatus the model 'EndpointStatus' type EndpointStatus string // List of EndpointStatus const ( - PENDING_EndpointStatus EndpointStatus = "pending" - RUNNING_EndpointStatus EndpointStatus = "running" - SERVING_EndpointStatus EndpointStatus = "serving" - FAILED_EndpointStatus EndpointStatus = "failed" - TERMINATED_EndpointStatus EndpointStatus = "terminated" + ENDPOINTSTATUS_PENDING EndpointStatus = "pending" + ENDPOINTSTATUS_RUNNING EndpointStatus = "running" + ENDPOINTSTATUS_SERVING EndpointStatus = "serving" + ENDPOINTSTATUS_FAILED EndpointStatus = "failed" + ENDPOINTSTATUS_TERMINATED EndpointStatus = "terminated" ) + +// All allowed values of EndpointStatus enum +var AllowedEndpointStatusEnumValues = []EndpointStatus{ + "pending", + "running", + "serving", + "failed", + "terminated", +} + +func (v *EndpointStatus) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := EndpointStatus(value) + for _, existing := range AllowedEndpointStatusEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid EndpointStatus", value) +} + +// NewEndpointStatusFromValue returns a pointer to a valid EndpointStatus +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewEndpointStatusFromValue(v string) (*EndpointStatus, error) { + ev := EndpointStatus(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for EndpointStatus: valid values are %v", v, AllowedEndpointStatusEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v EndpointStatus) IsValid() bool { + for _, existing := range AllowedEndpointStatusEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to EndpointStatus value +func (v EndpointStatus) Ptr() *EndpointStatus { + return &v +} + +type NullableEndpointStatus struct { + value *EndpointStatus + isSet bool +} + +func (v NullableEndpointStatus) Get() *EndpointStatus { + return v.value +} + +func (v *NullableEndpointStatus) Set(val *EndpointStatus) { + v.value = val + v.isSet = true +} + +func (v NullableEndpointStatus) IsSet() bool { + return v.isSet +} + +func (v *NullableEndpointStatus) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEndpointStatus(val *EndpointStatus) *NullableEndpointStatus { + return &NullableEndpointStatus{value: val, isSet: true} +} + +func (v NullableEndpointStatus) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEndpointStatus) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_env_var.go b/api/client/model_env_var.go index 1ef42518e..da8659af7 100644 --- a/api/client/model_env_var.go +++ b/api/client/model_env_var.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the EnvVar type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &EnvVar{} + +// EnvVar struct for EnvVar type EnvVar struct { - Name string `json:"name,omitempty"` - Value string `json:"value,omitempty"` + Name *string `json:"name,omitempty"` + Value *string `json:"value,omitempty"` +} + +// NewEnvVar instantiates a new EnvVar object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvVar() *EnvVar { + this := EnvVar{} + return &this +} + +// NewEnvVarWithDefaults instantiates a new EnvVar object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvVarWithDefaults() *EnvVar { + this := EnvVar{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *EnvVar) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvVar) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *EnvVar) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *EnvVar) SetName(v string) { + o.Name = &v +} + +// GetValue returns the Value field value if set, zero value otherwise. +func (o *EnvVar) GetValue() string { + if o == nil || IsNil(o.Value) { + var ret string + return ret + } + return *o.Value +} + +// GetValueOk returns a tuple with the Value field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *EnvVar) GetValueOk() (*string, bool) { + if o == nil || IsNil(o.Value) { + return nil, false + } + return o.Value, true +} + +// HasValue returns a boolean if a field has been set. +func (o *EnvVar) HasValue() bool { + if o != nil && !IsNil(o.Value) { + return true + } + + return false +} + +// SetValue gets a reference to the given string and assigns it to the Value field. +func (o *EnvVar) SetValue(v string) { + o.Value = &v +} + +func (o EnvVar) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o EnvVar) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Value) { + toSerialize["value"] = o.Value + } + return toSerialize, nil +} + +type NullableEnvVar struct { + value *EnvVar + isSet bool +} + +func (v NullableEnvVar) Get() *EnvVar { + return v.value +} + +func (v *NullableEnvVar) Set(val *EnvVar) { + v.value = val + v.isSet = true +} + +func (v NullableEnvVar) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvVar) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvVar(val *EnvVar) *NullableEnvVar { + return &NullableEnvVar{value: val, isSet: true} +} + +func (v NullableEnvVar) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvVar) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_environment.go b/api/client/model_environment.go index 1159a31f0..5589468df 100644 --- a/api/client/model_environment.go +++ b/api/client/model_environment.go @@ -1,28 +1,542 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" + "fmt" "time" ) +// checks if the Environment type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Environment{} + +// Environment struct for Environment type Environment struct { - Id int32 `json:"id,omitempty"` + Id *int32 `json:"id,omitempty"` Name string `json:"name"` - Cluster string `json:"cluster,omitempty"` - IsDefault bool `json:"is_default,omitempty"` - Region string `json:"region,omitempty"` - GcpProject string `json:"gcp_project,omitempty"` + Cluster string `json:"cluster"` + IsDefault *bool `json:"is_default,omitempty"` + Region *string `json:"region,omitempty"` + GcpProject *string `json:"gcp_project,omitempty"` DefaultResourceRequest *ResourceRequest `json:"default_resource_request,omitempty"` DefaultTransformerResourceRequest *ResourceRequest `json:"default_transformer_resource_request,omitempty"` DefaultPredictionJobResourceRequest *PredictionJobResourceRequest `json:"default_prediction_job_resource_request,omitempty"` - Gpus []GpuConfig `json:"gpus,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + Gpus []GPUConfig `json:"gpus,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +type _Environment Environment + +// NewEnvironment instantiates a new Environment object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewEnvironment(name string, cluster string) *Environment { + this := Environment{} + this.Name = name + this.Cluster = cluster + return &this +} + +// NewEnvironmentWithDefaults instantiates a new Environment object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewEnvironmentWithDefaults() *Environment { + this := Environment{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Environment) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Environment) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *Environment) SetId(v int32) { + o.Id = &v +} + +// GetName returns the Name field value +func (o *Environment) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *Environment) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *Environment) SetName(v string) { + o.Name = v +} + +// GetCluster returns the Cluster field value +func (o *Environment) GetCluster() string { + if o == nil { + var ret string + return ret + } + + return o.Cluster +} + +// GetClusterOk returns a tuple with the Cluster field value +// and a boolean to check if the value has been set. +func (o *Environment) GetClusterOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Cluster, true +} + +// SetCluster sets field value +func (o *Environment) SetCluster(v string) { + o.Cluster = v +} + +// GetIsDefault returns the IsDefault field value if set, zero value otherwise. +func (o *Environment) GetIsDefault() bool { + if o == nil || IsNil(o.IsDefault) { + var ret bool + return ret + } + return *o.IsDefault +} + +// GetIsDefaultOk returns a tuple with the IsDefault field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetIsDefaultOk() (*bool, bool) { + if o == nil || IsNil(o.IsDefault) { + return nil, false + } + return o.IsDefault, true +} + +// HasIsDefault returns a boolean if a field has been set. +func (o *Environment) HasIsDefault() bool { + if o != nil && !IsNil(o.IsDefault) { + return true + } + + return false +} + +// SetIsDefault gets a reference to the given bool and assigns it to the IsDefault field. +func (o *Environment) SetIsDefault(v bool) { + o.IsDefault = &v +} + +// GetRegion returns the Region field value if set, zero value otherwise. +func (o *Environment) GetRegion() string { + if o == nil || IsNil(o.Region) { + var ret string + return ret + } + return *o.Region +} + +// GetRegionOk returns a tuple with the Region field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetRegionOk() (*string, bool) { + if o == nil || IsNil(o.Region) { + return nil, false + } + return o.Region, true +} + +// HasRegion returns a boolean if a field has been set. +func (o *Environment) HasRegion() bool { + if o != nil && !IsNil(o.Region) { + return true + } + + return false +} + +// SetRegion gets a reference to the given string and assigns it to the Region field. +func (o *Environment) SetRegion(v string) { + o.Region = &v +} + +// GetGcpProject returns the GcpProject field value if set, zero value otherwise. +func (o *Environment) GetGcpProject() string { + if o == nil || IsNil(o.GcpProject) { + var ret string + return ret + } + return *o.GcpProject +} + +// GetGcpProjectOk returns a tuple with the GcpProject field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetGcpProjectOk() (*string, bool) { + if o == nil || IsNil(o.GcpProject) { + return nil, false + } + return o.GcpProject, true +} + +// HasGcpProject returns a boolean if a field has been set. +func (o *Environment) HasGcpProject() bool { + if o != nil && !IsNil(o.GcpProject) { + return true + } + + return false +} + +// SetGcpProject gets a reference to the given string and assigns it to the GcpProject field. +func (o *Environment) SetGcpProject(v string) { + o.GcpProject = &v +} + +// GetDefaultResourceRequest returns the DefaultResourceRequest field value if set, zero value otherwise. +func (o *Environment) GetDefaultResourceRequest() ResourceRequest { + if o == nil || IsNil(o.DefaultResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.DefaultResourceRequest +} + +// GetDefaultResourceRequestOk returns a tuple with the DefaultResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetDefaultResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.DefaultResourceRequest) { + return nil, false + } + return o.DefaultResourceRequest, true +} + +// HasDefaultResourceRequest returns a boolean if a field has been set. +func (o *Environment) HasDefaultResourceRequest() bool { + if o != nil && !IsNil(o.DefaultResourceRequest) { + return true + } + + return false +} + +// SetDefaultResourceRequest gets a reference to the given ResourceRequest and assigns it to the DefaultResourceRequest field. +func (o *Environment) SetDefaultResourceRequest(v ResourceRequest) { + o.DefaultResourceRequest = &v +} + +// GetDefaultTransformerResourceRequest returns the DefaultTransformerResourceRequest field value if set, zero value otherwise. +func (o *Environment) GetDefaultTransformerResourceRequest() ResourceRequest { + if o == nil || IsNil(o.DefaultTransformerResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.DefaultTransformerResourceRequest +} + +// GetDefaultTransformerResourceRequestOk returns a tuple with the DefaultTransformerResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetDefaultTransformerResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.DefaultTransformerResourceRequest) { + return nil, false + } + return o.DefaultTransformerResourceRequest, true +} + +// HasDefaultTransformerResourceRequest returns a boolean if a field has been set. +func (o *Environment) HasDefaultTransformerResourceRequest() bool { + if o != nil && !IsNil(o.DefaultTransformerResourceRequest) { + return true + } + + return false +} + +// SetDefaultTransformerResourceRequest gets a reference to the given ResourceRequest and assigns it to the DefaultTransformerResourceRequest field. +func (o *Environment) SetDefaultTransformerResourceRequest(v ResourceRequest) { + o.DefaultTransformerResourceRequest = &v +} + +// GetDefaultPredictionJobResourceRequest returns the DefaultPredictionJobResourceRequest field value if set, zero value otherwise. +func (o *Environment) GetDefaultPredictionJobResourceRequest() PredictionJobResourceRequest { + if o == nil || IsNil(o.DefaultPredictionJobResourceRequest) { + var ret PredictionJobResourceRequest + return ret + } + return *o.DefaultPredictionJobResourceRequest +} + +// GetDefaultPredictionJobResourceRequestOk returns a tuple with the DefaultPredictionJobResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetDefaultPredictionJobResourceRequestOk() (*PredictionJobResourceRequest, bool) { + if o == nil || IsNil(o.DefaultPredictionJobResourceRequest) { + return nil, false + } + return o.DefaultPredictionJobResourceRequest, true +} + +// HasDefaultPredictionJobResourceRequest returns a boolean if a field has been set. +func (o *Environment) HasDefaultPredictionJobResourceRequest() bool { + if o != nil && !IsNil(o.DefaultPredictionJobResourceRequest) { + return true + } + + return false +} + +// SetDefaultPredictionJobResourceRequest gets a reference to the given PredictionJobResourceRequest and assigns it to the DefaultPredictionJobResourceRequest field. +func (o *Environment) SetDefaultPredictionJobResourceRequest(v PredictionJobResourceRequest) { + o.DefaultPredictionJobResourceRequest = &v +} + +// GetGpus returns the Gpus field value if set, zero value otherwise. +func (o *Environment) GetGpus() []GPUConfig { + if o == nil || IsNil(o.Gpus) { + var ret []GPUConfig + return ret + } + return o.Gpus +} + +// GetGpusOk returns a tuple with the Gpus field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetGpusOk() ([]GPUConfig, bool) { + if o == nil || IsNil(o.Gpus) { + return nil, false + } + return o.Gpus, true +} + +// HasGpus returns a boolean if a field has been set. +func (o *Environment) HasGpus() bool { + if o != nil && !IsNil(o.Gpus) { + return true + } + + return false +} + +// SetGpus gets a reference to the given []GPUConfig and assigns it to the Gpus field. +func (o *Environment) SetGpus(v []GPUConfig) { + o.Gpus = v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *Environment) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *Environment) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *Environment) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *Environment) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Environment) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *Environment) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *Environment) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o Environment) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Environment) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + toSerialize["name"] = o.Name + toSerialize["cluster"] = o.Cluster + if !IsNil(o.IsDefault) { + toSerialize["is_default"] = o.IsDefault + } + if !IsNil(o.Region) { + toSerialize["region"] = o.Region + } + if !IsNil(o.GcpProject) { + toSerialize["gcp_project"] = o.GcpProject + } + if !IsNil(o.DefaultResourceRequest) { + toSerialize["default_resource_request"] = o.DefaultResourceRequest + } + if !IsNil(o.DefaultTransformerResourceRequest) { + toSerialize["default_transformer_resource_request"] = o.DefaultTransformerResourceRequest + } + if !IsNil(o.DefaultPredictionJobResourceRequest) { + toSerialize["default_prediction_job_resource_request"] = o.DefaultPredictionJobResourceRequest + } + if !IsNil(o.Gpus) { + toSerialize["gpus"] = o.Gpus + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +func (o *Environment) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + "cluster", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varEnvironment := _Environment{} + + err = json.Unmarshal(bytes, &varEnvironment) + + if err != nil { + return err + } + + *o = Environment(varEnvironment) + + return err +} + +type NullableEnvironment struct { + value *Environment + isSet bool +} + +func (v NullableEnvironment) Get() *Environment { + return v.value +} + +func (v *NullableEnvironment) Set(val *Environment) { + v.value = val + v.isSet = true +} + +func (v NullableEnvironment) IsSet() bool { + return v.isSet +} + +func (v *NullableEnvironment) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableEnvironment(val *Environment) *NullableEnvironment { + return &NullableEnvironment{value: val, isSet: true} +} + +func (v NullableEnvironment) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableEnvironment) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_file_format.go b/api/client/model_file_format.go index b2861e83c..5dea9e1cc 100644 --- a/api/client/model_file_format.go +++ b/api/client/model_file_format.go @@ -1,20 +1,116 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// FileFormat the model 'FileFormat' type FileFormat string // List of FileFormat const ( - INVALID_FILE_FORMAT_FileFormat FileFormat = "INVALID_FILE_FORMAT" - CSV_FileFormat FileFormat = "CSV" - PARQUET_FileFormat FileFormat = "PARQUET" - AVRO_FileFormat FileFormat = "AVRO" - JSON_FileFormat FileFormat = "JSON" + FILEFORMAT_INVALID_FILE_FORMAT FileFormat = "INVALID_FILE_FORMAT" + FILEFORMAT_CSV FileFormat = "CSV" + FILEFORMAT_PARQUET FileFormat = "PARQUET" + FILEFORMAT_AVRO FileFormat = "AVRO" + FILEFORMAT_JSON FileFormat = "JSON" ) + +// All allowed values of FileFormat enum +var AllowedFileFormatEnumValues = []FileFormat{ + "INVALID_FILE_FORMAT", + "CSV", + "PARQUET", + "AVRO", + "JSON", +} + +func (v *FileFormat) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := FileFormat(value) + for _, existing := range AllowedFileFormatEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid FileFormat", value) +} + +// NewFileFormatFromValue returns a pointer to a valid FileFormat +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewFileFormatFromValue(v string) (*FileFormat, error) { + ev := FileFormat(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for FileFormat: valid values are %v", v, AllowedFileFormatEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v FileFormat) IsValid() bool { + for _, existing := range AllowedFileFormatEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to FileFormat value +func (v FileFormat) Ptr() *FileFormat { + return &v +} + +type NullableFileFormat struct { + value *FileFormat + isSet bool +} + +func (v NullableFileFormat) Get() *FileFormat { + return v.value +} + +func (v *NullableFileFormat) Set(val *FileFormat) { + v.value = val + v.isSet = true +} + +func (v NullableFileFormat) IsSet() bool { + return v.isSet +} + +func (v *NullableFileFormat) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFileFormat(val *FileFormat) *NullableFileFormat { + return &NullableFileFormat{value: val, isSet: true} +} + +func (v NullableFileFormat) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFileFormat) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_gpu_config.go b/api/client/model_gpu_config.go index 0e74d1dfa..176be8e57 100644 --- a/api/client/model_gpu_config.go +++ b/api/client/model_gpu_config.go @@ -1,19 +1,340 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client -type GpuConfig struct { - Name string `json:"name,omitempty"` - Values []string `json:"values,omitempty"` - ResourceType string `json:"resource_type,omitempty"` - NodeSelector map[string]string `json:"node_selector,omitempty"` - Tolerations []GpuToleration `json:"tolerations,omitempty"` - MinMonthlyCostPerGpu float64 `json:"min_monthly_cost_per_gpu,omitempty"` - MaxMonthlyCostPerGpu float64 `json:"max_monthly_cost_per_gpu,omitempty"` +import ( + "encoding/json" +) + +// checks if the GPUConfig type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &GPUConfig{} + +// GPUConfig struct for GPUConfig +type GPUConfig struct { + Name *string `json:"name,omitempty"` + Values []string `json:"values,omitempty"` + ResourceType *string `json:"resource_type,omitempty"` + NodeSelector *map[string]string `json:"node_selector,omitempty"` + Tolerations []GPUToleration `json:"tolerations,omitempty"` + MinMonthlyCostPerGpu *float32 `json:"min_monthly_cost_per_gpu,omitempty"` + MaxMonthlyCostPerGpu *float32 `json:"max_monthly_cost_per_gpu,omitempty"` +} + +// NewGPUConfig instantiates a new GPUConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewGPUConfig() *GPUConfig { + this := GPUConfig{} + return &this +} + +// NewGPUConfigWithDefaults instantiates a new GPUConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewGPUConfigWithDefaults() *GPUConfig { + this := GPUConfig{} + return &this +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *GPUConfig) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *GPUConfig) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *GPUConfig) SetName(v string) { + o.Name = &v +} + +// GetValues returns the Values field value if set, zero value otherwise. +func (o *GPUConfig) GetValues() []string { + if o == nil || IsNil(o.Values) { + var ret []string + return ret + } + return o.Values +} + +// GetValuesOk returns a tuple with the Values field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetValuesOk() ([]string, bool) { + if o == nil || IsNil(o.Values) { + return nil, false + } + return o.Values, true +} + +// HasValues returns a boolean if a field has been set. +func (o *GPUConfig) HasValues() bool { + if o != nil && !IsNil(o.Values) { + return true + } + + return false +} + +// SetValues gets a reference to the given []string and assigns it to the Values field. +func (o *GPUConfig) SetValues(v []string) { + o.Values = v +} + +// GetResourceType returns the ResourceType field value if set, zero value otherwise. +func (o *GPUConfig) GetResourceType() string { + if o == nil || IsNil(o.ResourceType) { + var ret string + return ret + } + return *o.ResourceType +} + +// GetResourceTypeOk returns a tuple with the ResourceType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetResourceTypeOk() (*string, bool) { + if o == nil || IsNil(o.ResourceType) { + return nil, false + } + return o.ResourceType, true +} + +// HasResourceType returns a boolean if a field has been set. +func (o *GPUConfig) HasResourceType() bool { + if o != nil && !IsNil(o.ResourceType) { + return true + } + + return false +} + +// SetResourceType gets a reference to the given string and assigns it to the ResourceType field. +func (o *GPUConfig) SetResourceType(v string) { + o.ResourceType = &v +} + +// GetNodeSelector returns the NodeSelector field value if set, zero value otherwise. +func (o *GPUConfig) GetNodeSelector() map[string]string { + if o == nil || IsNil(o.NodeSelector) { + var ret map[string]string + return ret + } + return *o.NodeSelector +} + +// GetNodeSelectorOk returns a tuple with the NodeSelector field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetNodeSelectorOk() (*map[string]string, bool) { + if o == nil || IsNil(o.NodeSelector) { + return nil, false + } + return o.NodeSelector, true +} + +// HasNodeSelector returns a boolean if a field has been set. +func (o *GPUConfig) HasNodeSelector() bool { + if o != nil && !IsNil(o.NodeSelector) { + return true + } + + return false +} + +// SetNodeSelector gets a reference to the given map[string]string and assigns it to the NodeSelector field. +func (o *GPUConfig) SetNodeSelector(v map[string]string) { + o.NodeSelector = &v +} + +// GetTolerations returns the Tolerations field value if set, zero value otherwise. +func (o *GPUConfig) GetTolerations() []GPUToleration { + if o == nil || IsNil(o.Tolerations) { + var ret []GPUToleration + return ret + } + return o.Tolerations +} + +// GetTolerationsOk returns a tuple with the Tolerations field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetTolerationsOk() ([]GPUToleration, bool) { + if o == nil || IsNil(o.Tolerations) { + return nil, false + } + return o.Tolerations, true +} + +// HasTolerations returns a boolean if a field has been set. +func (o *GPUConfig) HasTolerations() bool { + if o != nil && !IsNil(o.Tolerations) { + return true + } + + return false +} + +// SetTolerations gets a reference to the given []GPUToleration and assigns it to the Tolerations field. +func (o *GPUConfig) SetTolerations(v []GPUToleration) { + o.Tolerations = v +} + +// GetMinMonthlyCostPerGpu returns the MinMonthlyCostPerGpu field value if set, zero value otherwise. +func (o *GPUConfig) GetMinMonthlyCostPerGpu() float32 { + if o == nil || IsNil(o.MinMonthlyCostPerGpu) { + var ret float32 + return ret + } + return *o.MinMonthlyCostPerGpu +} + +// GetMinMonthlyCostPerGpuOk returns a tuple with the MinMonthlyCostPerGpu field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetMinMonthlyCostPerGpuOk() (*float32, bool) { + if o == nil || IsNil(o.MinMonthlyCostPerGpu) { + return nil, false + } + return o.MinMonthlyCostPerGpu, true +} + +// HasMinMonthlyCostPerGpu returns a boolean if a field has been set. +func (o *GPUConfig) HasMinMonthlyCostPerGpu() bool { + if o != nil && !IsNil(o.MinMonthlyCostPerGpu) { + return true + } + + return false +} + +// SetMinMonthlyCostPerGpu gets a reference to the given float32 and assigns it to the MinMonthlyCostPerGpu field. +func (o *GPUConfig) SetMinMonthlyCostPerGpu(v float32) { + o.MinMonthlyCostPerGpu = &v +} + +// GetMaxMonthlyCostPerGpu returns the MaxMonthlyCostPerGpu field value if set, zero value otherwise. +func (o *GPUConfig) GetMaxMonthlyCostPerGpu() float32 { + if o == nil || IsNil(o.MaxMonthlyCostPerGpu) { + var ret float32 + return ret + } + return *o.MaxMonthlyCostPerGpu +} + +// GetMaxMonthlyCostPerGpuOk returns a tuple with the MaxMonthlyCostPerGpu field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUConfig) GetMaxMonthlyCostPerGpuOk() (*float32, bool) { + if o == nil || IsNil(o.MaxMonthlyCostPerGpu) { + return nil, false + } + return o.MaxMonthlyCostPerGpu, true +} + +// HasMaxMonthlyCostPerGpu returns a boolean if a field has been set. +func (o *GPUConfig) HasMaxMonthlyCostPerGpu() bool { + if o != nil && !IsNil(o.MaxMonthlyCostPerGpu) { + return true + } + + return false +} + +// SetMaxMonthlyCostPerGpu gets a reference to the given float32 and assigns it to the MaxMonthlyCostPerGpu field. +func (o *GPUConfig) SetMaxMonthlyCostPerGpu(v float32) { + o.MaxMonthlyCostPerGpu = &v +} + +func (o GPUConfig) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o GPUConfig) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Values) { + toSerialize["values"] = o.Values + } + if !IsNil(o.ResourceType) { + toSerialize["resource_type"] = o.ResourceType + } + if !IsNil(o.NodeSelector) { + toSerialize["node_selector"] = o.NodeSelector + } + if !IsNil(o.Tolerations) { + toSerialize["tolerations"] = o.Tolerations + } + if !IsNil(o.MinMonthlyCostPerGpu) { + toSerialize["min_monthly_cost_per_gpu"] = o.MinMonthlyCostPerGpu + } + if !IsNil(o.MaxMonthlyCostPerGpu) { + toSerialize["max_monthly_cost_per_gpu"] = o.MaxMonthlyCostPerGpu + } + return toSerialize, nil +} + +type NullableGPUConfig struct { + value *GPUConfig + isSet bool +} + +func (v NullableGPUConfig) Get() *GPUConfig { + return v.value +} + +func (v *NullableGPUConfig) Set(val *GPUConfig) { + v.value = val + v.isSet = true +} + +func (v NullableGPUConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableGPUConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableGPUConfig(val *GPUConfig) *NullableGPUConfig { + return &NullableGPUConfig{value: val, isSet: true} +} + +func (v NullableGPUConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableGPUConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_gpu_toleration.go b/api/client/model_gpu_toleration.go index c0c7a9c29..9d587b8a7 100644 --- a/api/client/model_gpu_toleration.go +++ b/api/client/model_gpu_toleration.go @@ -1,17 +1,268 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client -type GpuToleration struct { - Key string `json:"key,omitempty"` - Operator string `json:"operator,omitempty"` - Value string `json:"value,omitempty"` - Effect string `json:"effect,omitempty"` - TolerationSeconds int64 `json:"toleration_seconds,omitempty"` +import ( + "encoding/json" +) + +// checks if the GPUToleration type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &GPUToleration{} + +// GPUToleration struct for GPUToleration +type GPUToleration struct { + Key *string `json:"key,omitempty"` + Operator *string `json:"operator,omitempty"` + Value *string `json:"value,omitempty"` + Effect *string `json:"effect,omitempty"` + TolerationSeconds *int64 `json:"toleration_seconds,omitempty"` +} + +// NewGPUToleration instantiates a new GPUToleration object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewGPUToleration() *GPUToleration { + this := GPUToleration{} + return &this +} + +// NewGPUTolerationWithDefaults instantiates a new GPUToleration object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewGPUTolerationWithDefaults() *GPUToleration { + this := GPUToleration{} + return &this +} + +// GetKey returns the Key field value if set, zero value otherwise. +func (o *GPUToleration) GetKey() string { + if o == nil || IsNil(o.Key) { + var ret string + return ret + } + return *o.Key +} + +// GetKeyOk returns a tuple with the Key field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUToleration) GetKeyOk() (*string, bool) { + if o == nil || IsNil(o.Key) { + return nil, false + } + return o.Key, true +} + +// HasKey returns a boolean if a field has been set. +func (o *GPUToleration) HasKey() bool { + if o != nil && !IsNil(o.Key) { + return true + } + + return false +} + +// SetKey gets a reference to the given string and assigns it to the Key field. +func (o *GPUToleration) SetKey(v string) { + o.Key = &v +} + +// GetOperator returns the Operator field value if set, zero value otherwise. +func (o *GPUToleration) GetOperator() string { + if o == nil || IsNil(o.Operator) { + var ret string + return ret + } + return *o.Operator +} + +// GetOperatorOk returns a tuple with the Operator field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUToleration) GetOperatorOk() (*string, bool) { + if o == nil || IsNil(o.Operator) { + return nil, false + } + return o.Operator, true +} + +// HasOperator returns a boolean if a field has been set. +func (o *GPUToleration) HasOperator() bool { + if o != nil && !IsNil(o.Operator) { + return true + } + + return false +} + +// SetOperator gets a reference to the given string and assigns it to the Operator field. +func (o *GPUToleration) SetOperator(v string) { + o.Operator = &v +} + +// GetValue returns the Value field value if set, zero value otherwise. +func (o *GPUToleration) GetValue() string { + if o == nil || IsNil(o.Value) { + var ret string + return ret + } + return *o.Value +} + +// GetValueOk returns a tuple with the Value field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUToleration) GetValueOk() (*string, bool) { + if o == nil || IsNil(o.Value) { + return nil, false + } + return o.Value, true +} + +// HasValue returns a boolean if a field has been set. +func (o *GPUToleration) HasValue() bool { + if o != nil && !IsNil(o.Value) { + return true + } + + return false +} + +// SetValue gets a reference to the given string and assigns it to the Value field. +func (o *GPUToleration) SetValue(v string) { + o.Value = &v +} + +// GetEffect returns the Effect field value if set, zero value otherwise. +func (o *GPUToleration) GetEffect() string { + if o == nil || IsNil(o.Effect) { + var ret string + return ret + } + return *o.Effect +} + +// GetEffectOk returns a tuple with the Effect field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUToleration) GetEffectOk() (*string, bool) { + if o == nil || IsNil(o.Effect) { + return nil, false + } + return o.Effect, true +} + +// HasEffect returns a boolean if a field has been set. +func (o *GPUToleration) HasEffect() bool { + if o != nil && !IsNil(o.Effect) { + return true + } + + return false +} + +// SetEffect gets a reference to the given string and assigns it to the Effect field. +func (o *GPUToleration) SetEffect(v string) { + o.Effect = &v +} + +// GetTolerationSeconds returns the TolerationSeconds field value if set, zero value otherwise. +func (o *GPUToleration) GetTolerationSeconds() int64 { + if o == nil || IsNil(o.TolerationSeconds) { + var ret int64 + return ret + } + return *o.TolerationSeconds +} + +// GetTolerationSecondsOk returns a tuple with the TolerationSeconds field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *GPUToleration) GetTolerationSecondsOk() (*int64, bool) { + if o == nil || IsNil(o.TolerationSeconds) { + return nil, false + } + return o.TolerationSeconds, true +} + +// HasTolerationSeconds returns a boolean if a field has been set. +func (o *GPUToleration) HasTolerationSeconds() bool { + if o != nil && !IsNil(o.TolerationSeconds) { + return true + } + + return false +} + +// SetTolerationSeconds gets a reference to the given int64 and assigns it to the TolerationSeconds field. +func (o *GPUToleration) SetTolerationSeconds(v int64) { + o.TolerationSeconds = &v +} + +func (o GPUToleration) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o GPUToleration) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Key) { + toSerialize["key"] = o.Key + } + if !IsNil(o.Operator) { + toSerialize["operator"] = o.Operator + } + if !IsNil(o.Value) { + toSerialize["value"] = o.Value + } + if !IsNil(o.Effect) { + toSerialize["effect"] = o.Effect + } + if !IsNil(o.TolerationSeconds) { + toSerialize["toleration_seconds"] = o.TolerationSeconds + } + return toSerialize, nil +} + +type NullableGPUToleration struct { + value *GPUToleration + isSet bool +} + +func (v NullableGPUToleration) Get() *GPUToleration { + return v.value +} + +func (v *NullableGPUToleration) Set(val *GPUToleration) { + v.value = val + v.isSet = true +} + +func (v NullableGPUToleration) IsSet() bool { + return v.isSet +} + +func (v *NullableGPUToleration) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableGPUToleration(val *GPUToleration) *NullableGPUToleration { + return &NullableGPUToleration{value: val, isSet: true} +} + +func (v NullableGPUToleration) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableGPUToleration) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_label.go b/api/client/model_label.go index cdceed032..e9b46e486 100644 --- a/api/client/model_label.go +++ b/api/client/model_label.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the Label type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Label{} + +// Label struct for Label type Label struct { - Key string `json:"key,omitempty"` - Value string `json:"value,omitempty"` + Key *string `json:"key,omitempty"` + Value *string `json:"value,omitempty"` +} + +// NewLabel instantiates a new Label object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLabel() *Label { + this := Label{} + return &this +} + +// NewLabelWithDefaults instantiates a new Label object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLabelWithDefaults() *Label { + this := Label{} + return &this +} + +// GetKey returns the Key field value if set, zero value otherwise. +func (o *Label) GetKey() string { + if o == nil || IsNil(o.Key) { + var ret string + return ret + } + return *o.Key +} + +// GetKeyOk returns a tuple with the Key field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Label) GetKeyOk() (*string, bool) { + if o == nil || IsNil(o.Key) { + return nil, false + } + return o.Key, true +} + +// HasKey returns a boolean if a field has been set. +func (o *Label) HasKey() bool { + if o != nil && !IsNil(o.Key) { + return true + } + + return false +} + +// SetKey gets a reference to the given string and assigns it to the Key field. +func (o *Label) SetKey(v string) { + o.Key = &v +} + +// GetValue returns the Value field value if set, zero value otherwise. +func (o *Label) GetValue() string { + if o == nil || IsNil(o.Value) { + var ret string + return ret + } + return *o.Value +} + +// GetValueOk returns a tuple with the Value field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Label) GetValueOk() (*string, bool) { + if o == nil || IsNil(o.Value) { + return nil, false + } + return o.Value, true +} + +// HasValue returns a boolean if a field has been set. +func (o *Label) HasValue() bool { + if o != nil && !IsNil(o.Value) { + return true + } + + return false +} + +// SetValue gets a reference to the given string and assigns it to the Value field. +func (o *Label) SetValue(v string) { + o.Value = &v +} + +func (o Label) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Label) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Key) { + toSerialize["key"] = o.Key + } + if !IsNil(o.Value) { + toSerialize["value"] = o.Value + } + return toSerialize, nil +} + +type NullableLabel struct { + value *Label + isSet bool +} + +func (v NullableLabel) Get() *Label { + return v.value +} + +func (v *NullableLabel) Set(val *Label) { + v.value = val + v.isSet = true +} + +func (v NullableLabel) IsSet() bool { + return v.isSet +} + +func (v *NullableLabel) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLabel(val *Label) *NullableLabel { + return &NullableLabel{value: val, isSet: true} +} + +func (v NullableLabel) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLabel) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_logger.go b/api/client/model_logger.go index 6c07a1973..6df98c61a 100644 --- a/api/client/model_logger.go +++ b/api/client/model_logger.go @@ -1,15 +1,196 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the Logger type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Logger{} + +// Logger struct for Logger type Logger struct { Model *LoggerConfig `json:"model,omitempty"` Transformer *LoggerConfig `json:"transformer,omitempty"` Prediction *PredictionLoggerConfig `json:"prediction,omitempty"` } + +// NewLogger instantiates a new Logger object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLogger() *Logger { + this := Logger{} + return &this +} + +// NewLoggerWithDefaults instantiates a new Logger object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLoggerWithDefaults() *Logger { + this := Logger{} + return &this +} + +// GetModel returns the Model field value if set, zero value otherwise. +func (o *Logger) GetModel() LoggerConfig { + if o == nil || IsNil(o.Model) { + var ret LoggerConfig + return ret + } + return *o.Model +} + +// GetModelOk returns a tuple with the Model field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Logger) GetModelOk() (*LoggerConfig, bool) { + if o == nil || IsNil(o.Model) { + return nil, false + } + return o.Model, true +} + +// HasModel returns a boolean if a field has been set. +func (o *Logger) HasModel() bool { + if o != nil && !IsNil(o.Model) { + return true + } + + return false +} + +// SetModel gets a reference to the given LoggerConfig and assigns it to the Model field. +func (o *Logger) SetModel(v LoggerConfig) { + o.Model = &v +} + +// GetTransformer returns the Transformer field value if set, zero value otherwise. +func (o *Logger) GetTransformer() LoggerConfig { + if o == nil || IsNil(o.Transformer) { + var ret LoggerConfig + return ret + } + return *o.Transformer +} + +// GetTransformerOk returns a tuple with the Transformer field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Logger) GetTransformerOk() (*LoggerConfig, bool) { + if o == nil || IsNil(o.Transformer) { + return nil, false + } + return o.Transformer, true +} + +// HasTransformer returns a boolean if a field has been set. +func (o *Logger) HasTransformer() bool { + if o != nil && !IsNil(o.Transformer) { + return true + } + + return false +} + +// SetTransformer gets a reference to the given LoggerConfig and assigns it to the Transformer field. +func (o *Logger) SetTransformer(v LoggerConfig) { + o.Transformer = &v +} + +// GetPrediction returns the Prediction field value if set, zero value otherwise. +func (o *Logger) GetPrediction() PredictionLoggerConfig { + if o == nil || IsNil(o.Prediction) { + var ret PredictionLoggerConfig + return ret + } + return *o.Prediction +} + +// GetPredictionOk returns a tuple with the Prediction field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Logger) GetPredictionOk() (*PredictionLoggerConfig, bool) { + if o == nil || IsNil(o.Prediction) { + return nil, false + } + return o.Prediction, true +} + +// HasPrediction returns a boolean if a field has been set. +func (o *Logger) HasPrediction() bool { + if o != nil && !IsNil(o.Prediction) { + return true + } + + return false +} + +// SetPrediction gets a reference to the given PredictionLoggerConfig and assigns it to the Prediction field. +func (o *Logger) SetPrediction(v PredictionLoggerConfig) { + o.Prediction = &v +} + +func (o Logger) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Logger) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Model) { + toSerialize["model"] = o.Model + } + if !IsNil(o.Transformer) { + toSerialize["transformer"] = o.Transformer + } + if !IsNil(o.Prediction) { + toSerialize["prediction"] = o.Prediction + } + return toSerialize, nil +} + +type NullableLogger struct { + value *Logger + isSet bool +} + +func (v NullableLogger) Get() *Logger { + return v.value +} + +func (v *NullableLogger) Set(val *Logger) { + v.value = val + v.isSet = true +} + +func (v NullableLogger) IsSet() bool { + return v.isSet +} + +func (v *NullableLogger) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLogger(val *Logger) *NullableLogger { + return &NullableLogger{value: val, isSet: true} +} + +func (v NullableLogger) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLogger) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_logger_config.go b/api/client/model_logger_config.go index 5cf715ff1..7d567e303 100644 --- a/api/client/model_logger_config.go +++ b/api/client/model_logger_config.go @@ -1,14 +1,181 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// checks if the LoggerConfig type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &LoggerConfig{} + +// LoggerConfig struct for LoggerConfig type LoggerConfig struct { - Enabled bool `json:"enabled,omitempty"` - Mode *LoggerMode `json:"mode,omitempty"` + Enabled bool `json:"enabled"` + Mode LoggerMode `json:"mode"` +} + +type _LoggerConfig LoggerConfig + +// NewLoggerConfig instantiates a new LoggerConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewLoggerConfig(enabled bool, mode LoggerMode) *LoggerConfig { + this := LoggerConfig{} + this.Enabled = enabled + this.Mode = mode + return &this +} + +// NewLoggerConfigWithDefaults instantiates a new LoggerConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewLoggerConfigWithDefaults() *LoggerConfig { + this := LoggerConfig{} + return &this +} + +// GetEnabled returns the Enabled field value +func (o *LoggerConfig) GetEnabled() bool { + if o == nil { + var ret bool + return ret + } + + return o.Enabled +} + +// GetEnabledOk returns a tuple with the Enabled field value +// and a boolean to check if the value has been set. +func (o *LoggerConfig) GetEnabledOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.Enabled, true +} + +// SetEnabled sets field value +func (o *LoggerConfig) SetEnabled(v bool) { + o.Enabled = v +} + +// GetMode returns the Mode field value +func (o *LoggerConfig) GetMode() LoggerMode { + if o == nil { + var ret LoggerMode + return ret + } + + return o.Mode +} + +// GetModeOk returns a tuple with the Mode field value +// and a boolean to check if the value has been set. +func (o *LoggerConfig) GetModeOk() (*LoggerMode, bool) { + if o == nil { + return nil, false + } + return &o.Mode, true +} + +// SetMode sets field value +func (o *LoggerConfig) SetMode(v LoggerMode) { + o.Mode = v +} + +func (o LoggerConfig) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o LoggerConfig) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["enabled"] = o.Enabled + toSerialize["mode"] = o.Mode + return toSerialize, nil +} + +func (o *LoggerConfig) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "enabled", + "mode", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varLoggerConfig := _LoggerConfig{} + + err = json.Unmarshal(bytes, &varLoggerConfig) + + if err != nil { + return err + } + + *o = LoggerConfig(varLoggerConfig) + + return err +} + +type NullableLoggerConfig struct { + value *LoggerConfig + isSet bool +} + +func (v NullableLoggerConfig) Get() *LoggerConfig { + return v.value +} + +func (v *NullableLoggerConfig) Set(val *LoggerConfig) { + v.value = val + v.isSet = true +} + +func (v NullableLoggerConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableLoggerConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLoggerConfig(val *LoggerConfig) *NullableLoggerConfig { + return &NullableLoggerConfig{value: val, isSet: true} +} + +func (v NullableLoggerConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLoggerConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_logger_mode.go b/api/client/model_logger_mode.go index 5315a925f..cc6422021 100644 --- a/api/client/model_logger_mode.go +++ b/api/client/model_logger_mode.go @@ -1,18 +1,112 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// LoggerMode the model 'LoggerMode' type LoggerMode string // List of LoggerMode const ( - ALL_LoggerMode LoggerMode = "all" - REQUEST_LoggerMode LoggerMode = "request" - RESPONSE_LoggerMode LoggerMode = "response" + LOGGERMODE_ALL LoggerMode = "all" + LOGGERMODE_REQUEST LoggerMode = "request" + LOGGERMODE_RESPONSE LoggerMode = "response" ) + +// All allowed values of LoggerMode enum +var AllowedLoggerModeEnumValues = []LoggerMode{ + "all", + "request", + "response", +} + +func (v *LoggerMode) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := LoggerMode(value) + for _, existing := range AllowedLoggerModeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid LoggerMode", value) +} + +// NewLoggerModeFromValue returns a pointer to a valid LoggerMode +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewLoggerModeFromValue(v string) (*LoggerMode, error) { + ev := LoggerMode(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for LoggerMode: valid values are %v", v, AllowedLoggerModeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v LoggerMode) IsValid() bool { + for _, existing := range AllowedLoggerModeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to LoggerMode value +func (v LoggerMode) Ptr() *LoggerMode { + return &v +} + +type NullableLoggerMode struct { + value *LoggerMode + isSet bool +} + +func (v NullableLoggerMode) Get() *LoggerMode { + return v.value +} + +func (v *NullableLoggerMode) Set(val *LoggerMode) { + v.value = val + v.isSet = true +} + +func (v NullableLoggerMode) IsSet() bool { + return v.isSet +} + +func (v *NullableLoggerMode) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableLoggerMode(val *LoggerMode) *NullableLoggerMode { + return &NullableLoggerMode{value: val, isSet: true} +} + +func (v NullableLoggerMode) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableLoggerMode) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_metrics_type.go b/api/client/model_metrics_type.go index f4ce50115..f902cc13d 100644 --- a/api/client/model_metrics_type.go +++ b/api/client/model_metrics_type.go @@ -1,19 +1,114 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// MetricsType the model 'MetricsType' type MetricsType string // List of MetricsType const ( - CONCURRENCY_MetricsType MetricsType = "concurrency" - CPU_UTILIZATION_MetricsType MetricsType = "cpu_utilization" - MEMORY_UTILIZATION_MetricsType MetricsType = "memory_utilization" - RPS_MetricsType MetricsType = "rps" + METRICSTYPE_CONCURRENCY MetricsType = "concurrency" + METRICSTYPE_CPU_UTILIZATION MetricsType = "cpu_utilization" + METRICSTYPE_MEMORY_UTILIZATION MetricsType = "memory_utilization" + METRICSTYPE_RPS MetricsType = "rps" ) + +// All allowed values of MetricsType enum +var AllowedMetricsTypeEnumValues = []MetricsType{ + "concurrency", + "cpu_utilization", + "memory_utilization", + "rps", +} + +func (v *MetricsType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := MetricsType(value) + for _, existing := range AllowedMetricsTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid MetricsType", value) +} + +// NewMetricsTypeFromValue returns a pointer to a valid MetricsType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewMetricsTypeFromValue(v string) (*MetricsType, error) { + ev := MetricsType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for MetricsType: valid values are %v", v, AllowedMetricsTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v MetricsType) IsValid() bool { + for _, existing := range AllowedMetricsTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to MetricsType value +func (v MetricsType) Ptr() *MetricsType { + return &v +} + +type NullableMetricsType struct { + value *MetricsType + isSet bool +} + +func (v NullableMetricsType) Get() *MetricsType { + return v.value +} + +func (v *NullableMetricsType) Set(val *MetricsType) { + v.value = val + v.isSet = true +} + +func (v NullableMetricsType) IsSet() bool { + return v.isSet +} + +func (v *NullableMetricsType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMetricsType(val *MetricsType) *NullableMetricsType { + return &NullableMetricsType{value: val, isSet: true} +} + +func (v NullableMetricsType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMetricsType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_mock_response.go b/api/client/model_mock_response.go index 31df19c26..af71ac90e 100644 --- a/api/client/model_mock_response.go +++ b/api/client/model_mock_response.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the MockResponse type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &MockResponse{} + +// MockResponse struct for MockResponse type MockResponse struct { - Body *ModelMap `json:"body,omitempty"` - Headers *ModelMap `json:"headers,omitempty"` + Body map[string]interface{} `json:"body,omitempty"` + Headers map[string]interface{} `json:"headers,omitempty"` +} + +// NewMockResponse instantiates a new MockResponse object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewMockResponse() *MockResponse { + this := MockResponse{} + return &this +} + +// NewMockResponseWithDefaults instantiates a new MockResponse object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewMockResponseWithDefaults() *MockResponse { + this := MockResponse{} + return &this +} + +// GetBody returns the Body field value if set, zero value otherwise. +func (o *MockResponse) GetBody() map[string]interface{} { + if o == nil || IsNil(o.Body) { + var ret map[string]interface{} + return ret + } + return o.Body +} + +// GetBodyOk returns a tuple with the Body field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MockResponse) GetBodyOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Body) { + return map[string]interface{}{}, false + } + return o.Body, true +} + +// HasBody returns a boolean if a field has been set. +func (o *MockResponse) HasBody() bool { + if o != nil && !IsNil(o.Body) { + return true + } + + return false +} + +// SetBody gets a reference to the given map[string]interface{} and assigns it to the Body field. +func (o *MockResponse) SetBody(v map[string]interface{}) { + o.Body = v +} + +// GetHeaders returns the Headers field value if set, zero value otherwise. +func (o *MockResponse) GetHeaders() map[string]interface{} { + if o == nil || IsNil(o.Headers) { + var ret map[string]interface{} + return ret + } + return o.Headers +} + +// GetHeadersOk returns a tuple with the Headers field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *MockResponse) GetHeadersOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Headers) { + return map[string]interface{}{}, false + } + return o.Headers, true +} + +// HasHeaders returns a boolean if a field has been set. +func (o *MockResponse) HasHeaders() bool { + if o != nil && !IsNil(o.Headers) { + return true + } + + return false +} + +// SetHeaders gets a reference to the given map[string]interface{} and assigns it to the Headers field. +func (o *MockResponse) SetHeaders(v map[string]interface{}) { + o.Headers = v +} + +func (o MockResponse) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o MockResponse) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Body) { + toSerialize["body"] = o.Body + } + if !IsNil(o.Headers) { + toSerialize["headers"] = o.Headers + } + return toSerialize, nil +} + +type NullableMockResponse struct { + value *MockResponse + isSet bool +} + +func (v NullableMockResponse) Get() *MockResponse { + return v.value +} + +func (v *NullableMockResponse) Set(val *MockResponse) { + v.value = val + v.isSet = true +} + +func (v NullableMockResponse) IsSet() bool { + return v.isSet +} + +func (v *NullableMockResponse) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableMockResponse(val *MockResponse) *NullableMockResponse { + return &NullableMockResponse{value: val, isSet: true} +} + +func (v NullableMockResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableMockResponse) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_model.go b/api/client/model_model.go index d28eba86b..179aff7d2 100644 --- a/api/client/model_model.go +++ b/api/client/model_model.go @@ -1,26 +1,443 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" + "fmt" "time" ) +// checks if the Model type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Model{} + +// Model struct for Model type Model struct { - Id int32 `json:"id,omitempty"` - ProjectId int32 `json:"project_id,omitempty"` - MlflowExperimentId int32 `json:"mlflow_experiment_id,omitempty"` - Name string `json:"name,omitempty"` + Id *int32 `json:"id,omitempty"` + ProjectId *int32 `json:"project_id,omitempty"` + MlflowExperimentId *int32 `json:"mlflow_experiment_id,omitempty"` + Name string `json:"name"` // Model type - Type_ string `json:"type,omitempty"` - MlflowUrl string `json:"mlflow_url,omitempty"` + Type *string `json:"type,omitempty"` + MlflowUrl *string `json:"mlflow_url,omitempty"` Endpoints []ModelEndpoint `json:"endpoints,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +type _Model Model + +// NewModel instantiates a new Model object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModel(name string) *Model { + this := Model{} + this.Name = name + return &this +} + +// NewModelWithDefaults instantiates a new Model object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelWithDefaults() *Model { + this := Model{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Model) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Model) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *Model) SetId(v int32) { + o.Id = &v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *Model) GetProjectId() int32 { + if o == nil || IsNil(o.ProjectId) { + var ret int32 + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetProjectIdOk() (*int32, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *Model) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given int32 and assigns it to the ProjectId field. +func (o *Model) SetProjectId(v int32) { + o.ProjectId = &v +} + +// GetMlflowExperimentId returns the MlflowExperimentId field value if set, zero value otherwise. +func (o *Model) GetMlflowExperimentId() int32 { + if o == nil || IsNil(o.MlflowExperimentId) { + var ret int32 + return ret + } + return *o.MlflowExperimentId +} + +// GetMlflowExperimentIdOk returns a tuple with the MlflowExperimentId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetMlflowExperimentIdOk() (*int32, bool) { + if o == nil || IsNil(o.MlflowExperimentId) { + return nil, false + } + return o.MlflowExperimentId, true +} + +// HasMlflowExperimentId returns a boolean if a field has been set. +func (o *Model) HasMlflowExperimentId() bool { + if o != nil && !IsNil(o.MlflowExperimentId) { + return true + } + + return false +} + +// SetMlflowExperimentId gets a reference to the given int32 and assigns it to the MlflowExperimentId field. +func (o *Model) SetMlflowExperimentId(v int32) { + o.MlflowExperimentId = &v +} + +// GetName returns the Name field value +func (o *Model) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *Model) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *Model) SetName(v string) { + o.Name = v +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *Model) GetType() string { + if o == nil || IsNil(o.Type) { + var ret string + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetTypeOk() (*string, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *Model) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given string and assigns it to the Type field. +func (o *Model) SetType(v string) { + o.Type = &v +} + +// GetMlflowUrl returns the MlflowUrl field value if set, zero value otherwise. +func (o *Model) GetMlflowUrl() string { + if o == nil || IsNil(o.MlflowUrl) { + var ret string + return ret + } + return *o.MlflowUrl +} + +// GetMlflowUrlOk returns a tuple with the MlflowUrl field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetMlflowUrlOk() (*string, bool) { + if o == nil || IsNil(o.MlflowUrl) { + return nil, false + } + return o.MlflowUrl, true +} + +// HasMlflowUrl returns a boolean if a field has been set. +func (o *Model) HasMlflowUrl() bool { + if o != nil && !IsNil(o.MlflowUrl) { + return true + } + + return false +} + +// SetMlflowUrl gets a reference to the given string and assigns it to the MlflowUrl field. +func (o *Model) SetMlflowUrl(v string) { + o.MlflowUrl = &v +} + +// GetEndpoints returns the Endpoints field value if set, zero value otherwise. +func (o *Model) GetEndpoints() []ModelEndpoint { + if o == nil || IsNil(o.Endpoints) { + var ret []ModelEndpoint + return ret + } + return o.Endpoints +} + +// GetEndpointsOk returns a tuple with the Endpoints field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetEndpointsOk() ([]ModelEndpoint, bool) { + if o == nil || IsNil(o.Endpoints) { + return nil, false + } + return o.Endpoints, true +} + +// HasEndpoints returns a boolean if a field has been set. +func (o *Model) HasEndpoints() bool { + if o != nil && !IsNil(o.Endpoints) { + return true + } + + return false +} + +// SetEndpoints gets a reference to the given []ModelEndpoint and assigns it to the Endpoints field. +func (o *Model) SetEndpoints(v []ModelEndpoint) { + o.Endpoints = v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *Model) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *Model) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *Model) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *Model) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Model) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *Model) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *Model) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o Model) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Model) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.MlflowExperimentId) { + toSerialize["mlflow_experiment_id"] = o.MlflowExperimentId + } + toSerialize["name"] = o.Name + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.MlflowUrl) { + toSerialize["mlflow_url"] = o.MlflowUrl + } + if !IsNil(o.Endpoints) { + toSerialize["endpoints"] = o.Endpoints + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +func (o *Model) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varModel := _Model{} + + err = json.Unmarshal(bytes, &varModel) + + if err != nil { + return err + } + + *o = Model(varModel) + + return err +} + +type NullableModel struct { + value *Model + isSet bool +} + +func (v NullableModel) Get() *Model { + return v.value +} + +func (v *NullableModel) Set(val *Model) { + v.value = val + v.isSet = true +} + +func (v NullableModel) IsSet() bool { + return v.isSet +} + +func (v *NullableModel) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModel(val *Model) *NullableModel { + return &NullableModel{value: val, isSet: true} +} + +func (v NullableModel) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModel) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_model_endpoint.go b/api/client/model_model_endpoint.go index fff29a130..215edb591 100644 --- a/api/client/model_model_endpoint.go +++ b/api/client/model_model_endpoint.go @@ -1,27 +1,485 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" "time" ) +// checks if the ModelEndpoint type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelEndpoint{} + +// ModelEndpoint struct for ModelEndpoint type ModelEndpoint struct { - Id int32 `json:"id,omitempty"` - ModelId int32 `json:"model_id,omitempty"` + Id *int32 `json:"id,omitempty"` + ModelId *int32 `json:"model_id,omitempty"` Model *Model `json:"model,omitempty"` Status *EndpointStatus `json:"status,omitempty"` - Url string `json:"url,omitempty"` + Url *string `json:"url,omitempty"` Rule *ModelEndpointRule `json:"rule,omitempty"` - EnvironmentName string `json:"environment_name,omitempty"` + EnvironmentName *string `json:"environment_name,omitempty"` Environment *Environment `json:"environment,omitempty"` Protocol *Protocol `json:"protocol,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// NewModelEndpoint instantiates a new ModelEndpoint object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelEndpoint() *ModelEndpoint { + this := ModelEndpoint{} + return &this +} + +// NewModelEndpointWithDefaults instantiates a new ModelEndpoint object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelEndpointWithDefaults() *ModelEndpoint { + this := ModelEndpoint{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *ModelEndpoint) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *ModelEndpoint) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *ModelEndpoint) SetId(v int32) { + o.Id = &v +} + +// GetModelId returns the ModelId field value if set, zero value otherwise. +func (o *ModelEndpoint) GetModelId() int32 { + if o == nil || IsNil(o.ModelId) { + var ret int32 + return ret + } + return *o.ModelId +} + +// GetModelIdOk returns a tuple with the ModelId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetModelIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelId) { + return nil, false + } + return o.ModelId, true +} + +// HasModelId returns a boolean if a field has been set. +func (o *ModelEndpoint) HasModelId() bool { + if o != nil && !IsNil(o.ModelId) { + return true + } + + return false +} + +// SetModelId gets a reference to the given int32 and assigns it to the ModelId field. +func (o *ModelEndpoint) SetModelId(v int32) { + o.ModelId = &v +} + +// GetModel returns the Model field value if set, zero value otherwise. +func (o *ModelEndpoint) GetModel() Model { + if o == nil || IsNil(o.Model) { + var ret Model + return ret + } + return *o.Model +} + +// GetModelOk returns a tuple with the Model field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetModelOk() (*Model, bool) { + if o == nil || IsNil(o.Model) { + return nil, false + } + return o.Model, true +} + +// HasModel returns a boolean if a field has been set. +func (o *ModelEndpoint) HasModel() bool { + if o != nil && !IsNil(o.Model) { + return true + } + + return false +} + +// SetModel gets a reference to the given Model and assigns it to the Model field. +func (o *ModelEndpoint) SetModel(v Model) { + o.Model = &v +} + +// GetStatus returns the Status field value if set, zero value otherwise. +func (o *ModelEndpoint) GetStatus() EndpointStatus { + if o == nil || IsNil(o.Status) { + var ret EndpointStatus + return ret + } + return *o.Status +} + +// GetStatusOk returns a tuple with the Status field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetStatusOk() (*EndpointStatus, bool) { + if o == nil || IsNil(o.Status) { + return nil, false + } + return o.Status, true +} + +// HasStatus returns a boolean if a field has been set. +func (o *ModelEndpoint) HasStatus() bool { + if o != nil && !IsNil(o.Status) { + return true + } + + return false +} + +// SetStatus gets a reference to the given EndpointStatus and assigns it to the Status field. +func (o *ModelEndpoint) SetStatus(v EndpointStatus) { + o.Status = &v +} + +// GetUrl returns the Url field value if set, zero value otherwise. +func (o *ModelEndpoint) GetUrl() string { + if o == nil || IsNil(o.Url) { + var ret string + return ret + } + return *o.Url +} + +// GetUrlOk returns a tuple with the Url field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetUrlOk() (*string, bool) { + if o == nil || IsNil(o.Url) { + return nil, false + } + return o.Url, true +} + +// HasUrl returns a boolean if a field has been set. +func (o *ModelEndpoint) HasUrl() bool { + if o != nil && !IsNil(o.Url) { + return true + } + + return false +} + +// SetUrl gets a reference to the given string and assigns it to the Url field. +func (o *ModelEndpoint) SetUrl(v string) { + o.Url = &v +} + +// GetRule returns the Rule field value if set, zero value otherwise. +func (o *ModelEndpoint) GetRule() ModelEndpointRule { + if o == nil || IsNil(o.Rule) { + var ret ModelEndpointRule + return ret + } + return *o.Rule +} + +// GetRuleOk returns a tuple with the Rule field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetRuleOk() (*ModelEndpointRule, bool) { + if o == nil || IsNil(o.Rule) { + return nil, false + } + return o.Rule, true +} + +// HasRule returns a boolean if a field has been set. +func (o *ModelEndpoint) HasRule() bool { + if o != nil && !IsNil(o.Rule) { + return true + } + + return false +} + +// SetRule gets a reference to the given ModelEndpointRule and assigns it to the Rule field. +func (o *ModelEndpoint) SetRule(v ModelEndpointRule) { + o.Rule = &v +} + +// GetEnvironmentName returns the EnvironmentName field value if set, zero value otherwise. +func (o *ModelEndpoint) GetEnvironmentName() string { + if o == nil || IsNil(o.EnvironmentName) { + var ret string + return ret + } + return *o.EnvironmentName +} + +// GetEnvironmentNameOk returns a tuple with the EnvironmentName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetEnvironmentNameOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentName) { + return nil, false + } + return o.EnvironmentName, true +} + +// HasEnvironmentName returns a boolean if a field has been set. +func (o *ModelEndpoint) HasEnvironmentName() bool { + if o != nil && !IsNil(o.EnvironmentName) { + return true + } + + return false +} + +// SetEnvironmentName gets a reference to the given string and assigns it to the EnvironmentName field. +func (o *ModelEndpoint) SetEnvironmentName(v string) { + o.EnvironmentName = &v +} + +// GetEnvironment returns the Environment field value if set, zero value otherwise. +func (o *ModelEndpoint) GetEnvironment() Environment { + if o == nil || IsNil(o.Environment) { + var ret Environment + return ret + } + return *o.Environment +} + +// GetEnvironmentOk returns a tuple with the Environment field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetEnvironmentOk() (*Environment, bool) { + if o == nil || IsNil(o.Environment) { + return nil, false + } + return o.Environment, true +} + +// HasEnvironment returns a boolean if a field has been set. +func (o *ModelEndpoint) HasEnvironment() bool { + if o != nil && !IsNil(o.Environment) { + return true + } + + return false +} + +// SetEnvironment gets a reference to the given Environment and assigns it to the Environment field. +func (o *ModelEndpoint) SetEnvironment(v Environment) { + o.Environment = &v +} + +// GetProtocol returns the Protocol field value if set, zero value otherwise. +func (o *ModelEndpoint) GetProtocol() Protocol { + if o == nil || IsNil(o.Protocol) { + var ret Protocol + return ret + } + return *o.Protocol +} + +// GetProtocolOk returns a tuple with the Protocol field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetProtocolOk() (*Protocol, bool) { + if o == nil || IsNil(o.Protocol) { + return nil, false + } + return o.Protocol, true +} + +// HasProtocol returns a boolean if a field has been set. +func (o *ModelEndpoint) HasProtocol() bool { + if o != nil && !IsNil(o.Protocol) { + return true + } + + return false +} + +// SetProtocol gets a reference to the given Protocol and assigns it to the Protocol field. +func (o *ModelEndpoint) SetProtocol(v Protocol) { + o.Protocol = &v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *ModelEndpoint) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *ModelEndpoint) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *ModelEndpoint) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *ModelEndpoint) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpoint) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *ModelEndpoint) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *ModelEndpoint) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o ModelEndpoint) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelEndpoint) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.ModelId) { + toSerialize["model_id"] = o.ModelId + } + if !IsNil(o.Model) { + toSerialize["model"] = o.Model + } + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + if !IsNil(o.Url) { + toSerialize["url"] = o.Url + } + if !IsNil(o.Rule) { + toSerialize["rule"] = o.Rule + } + if !IsNil(o.EnvironmentName) { + toSerialize["environment_name"] = o.EnvironmentName + } + if !IsNil(o.Environment) { + toSerialize["environment"] = o.Environment + } + if !IsNil(o.Protocol) { + toSerialize["protocol"] = o.Protocol + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +type NullableModelEndpoint struct { + value *ModelEndpoint + isSet bool +} + +func (v NullableModelEndpoint) Get() *ModelEndpoint { + return v.value +} + +func (v *NullableModelEndpoint) Set(val *ModelEndpoint) { + v.value = val + v.isSet = true +} + +func (v NullableModelEndpoint) IsSet() bool { + return v.isSet +} + +func (v *NullableModelEndpoint) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelEndpoint(val *ModelEndpoint) *NullableModelEndpoint { + return &NullableModelEndpoint{value: val, isSet: true} +} + +func (v NullableModelEndpoint) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelEndpoint) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_model_endpoint_alert.go b/api/client/model_model_endpoint_alert.go index 27c6ded83..ed17e0d1a 100644 --- a/api/client/model_model_endpoint_alert.go +++ b/api/client/model_model_endpoint_alert.go @@ -1,17 +1,268 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ModelEndpointAlert type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelEndpointAlert{} + +// ModelEndpointAlert struct for ModelEndpointAlert type ModelEndpointAlert struct { - ModelId int32 `json:"model_id,omitempty"` - ModelEndpointId int32 `json:"model_endpoint_id,omitempty"` - EnvironmentName string `json:"environment_name,omitempty"` - TeamName string `json:"team_name,omitempty"` + ModelId *int32 `json:"model_id,omitempty"` + ModelEndpointId *int32 `json:"model_endpoint_id,omitempty"` + EnvironmentName *string `json:"environment_name,omitempty"` + TeamName *string `json:"team_name,omitempty"` AlertConditions []ModelEndpointAlertCondition `json:"alert_conditions,omitempty"` } + +// NewModelEndpointAlert instantiates a new ModelEndpointAlert object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelEndpointAlert() *ModelEndpointAlert { + this := ModelEndpointAlert{} + return &this +} + +// NewModelEndpointAlertWithDefaults instantiates a new ModelEndpointAlert object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelEndpointAlertWithDefaults() *ModelEndpointAlert { + this := ModelEndpointAlert{} + return &this +} + +// GetModelId returns the ModelId field value if set, zero value otherwise. +func (o *ModelEndpointAlert) GetModelId() int32 { + if o == nil || IsNil(o.ModelId) { + var ret int32 + return ret + } + return *o.ModelId +} + +// GetModelIdOk returns a tuple with the ModelId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlert) GetModelIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelId) { + return nil, false + } + return o.ModelId, true +} + +// HasModelId returns a boolean if a field has been set. +func (o *ModelEndpointAlert) HasModelId() bool { + if o != nil && !IsNil(o.ModelId) { + return true + } + + return false +} + +// SetModelId gets a reference to the given int32 and assigns it to the ModelId field. +func (o *ModelEndpointAlert) SetModelId(v int32) { + o.ModelId = &v +} + +// GetModelEndpointId returns the ModelEndpointId field value if set, zero value otherwise. +func (o *ModelEndpointAlert) GetModelEndpointId() int32 { + if o == nil || IsNil(o.ModelEndpointId) { + var ret int32 + return ret + } + return *o.ModelEndpointId +} + +// GetModelEndpointIdOk returns a tuple with the ModelEndpointId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlert) GetModelEndpointIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelEndpointId) { + return nil, false + } + return o.ModelEndpointId, true +} + +// HasModelEndpointId returns a boolean if a field has been set. +func (o *ModelEndpointAlert) HasModelEndpointId() bool { + if o != nil && !IsNil(o.ModelEndpointId) { + return true + } + + return false +} + +// SetModelEndpointId gets a reference to the given int32 and assigns it to the ModelEndpointId field. +func (o *ModelEndpointAlert) SetModelEndpointId(v int32) { + o.ModelEndpointId = &v +} + +// GetEnvironmentName returns the EnvironmentName field value if set, zero value otherwise. +func (o *ModelEndpointAlert) GetEnvironmentName() string { + if o == nil || IsNil(o.EnvironmentName) { + var ret string + return ret + } + return *o.EnvironmentName +} + +// GetEnvironmentNameOk returns a tuple with the EnvironmentName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlert) GetEnvironmentNameOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentName) { + return nil, false + } + return o.EnvironmentName, true +} + +// HasEnvironmentName returns a boolean if a field has been set. +func (o *ModelEndpointAlert) HasEnvironmentName() bool { + if o != nil && !IsNil(o.EnvironmentName) { + return true + } + + return false +} + +// SetEnvironmentName gets a reference to the given string and assigns it to the EnvironmentName field. +func (o *ModelEndpointAlert) SetEnvironmentName(v string) { + o.EnvironmentName = &v +} + +// GetTeamName returns the TeamName field value if set, zero value otherwise. +func (o *ModelEndpointAlert) GetTeamName() string { + if o == nil || IsNil(o.TeamName) { + var ret string + return ret + } + return *o.TeamName +} + +// GetTeamNameOk returns a tuple with the TeamName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlert) GetTeamNameOk() (*string, bool) { + if o == nil || IsNil(o.TeamName) { + return nil, false + } + return o.TeamName, true +} + +// HasTeamName returns a boolean if a field has been set. +func (o *ModelEndpointAlert) HasTeamName() bool { + if o != nil && !IsNil(o.TeamName) { + return true + } + + return false +} + +// SetTeamName gets a reference to the given string and assigns it to the TeamName field. +func (o *ModelEndpointAlert) SetTeamName(v string) { + o.TeamName = &v +} + +// GetAlertConditions returns the AlertConditions field value if set, zero value otherwise. +func (o *ModelEndpointAlert) GetAlertConditions() []ModelEndpointAlertCondition { + if o == nil || IsNil(o.AlertConditions) { + var ret []ModelEndpointAlertCondition + return ret + } + return o.AlertConditions +} + +// GetAlertConditionsOk returns a tuple with the AlertConditions field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlert) GetAlertConditionsOk() ([]ModelEndpointAlertCondition, bool) { + if o == nil || IsNil(o.AlertConditions) { + return nil, false + } + return o.AlertConditions, true +} + +// HasAlertConditions returns a boolean if a field has been set. +func (o *ModelEndpointAlert) HasAlertConditions() bool { + if o != nil && !IsNil(o.AlertConditions) { + return true + } + + return false +} + +// SetAlertConditions gets a reference to the given []ModelEndpointAlertCondition and assigns it to the AlertConditions field. +func (o *ModelEndpointAlert) SetAlertConditions(v []ModelEndpointAlertCondition) { + o.AlertConditions = v +} + +func (o ModelEndpointAlert) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelEndpointAlert) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.ModelId) { + toSerialize["model_id"] = o.ModelId + } + if !IsNil(o.ModelEndpointId) { + toSerialize["model_endpoint_id"] = o.ModelEndpointId + } + if !IsNil(o.EnvironmentName) { + toSerialize["environment_name"] = o.EnvironmentName + } + if !IsNil(o.TeamName) { + toSerialize["team_name"] = o.TeamName + } + if !IsNil(o.AlertConditions) { + toSerialize["alert_conditions"] = o.AlertConditions + } + return toSerialize, nil +} + +type NullableModelEndpointAlert struct { + value *ModelEndpointAlert + isSet bool +} + +func (v NullableModelEndpointAlert) Get() *ModelEndpointAlert { + return v.value +} + +func (v *NullableModelEndpointAlert) Set(val *ModelEndpointAlert) { + v.value = val + v.isSet = true +} + +func (v NullableModelEndpointAlert) IsSet() bool { + return v.isSet +} + +func (v *NullableModelEndpointAlert) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelEndpointAlert(val *ModelEndpointAlert) *NullableModelEndpointAlert { + return &NullableModelEndpointAlert{value: val, isSet: true} +} + +func (v NullableModelEndpointAlert) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelEndpointAlert) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_model_endpoint_alert_condition.go b/api/client/model_model_endpoint_alert_condition.go index 64b739979..fcea98f41 100644 --- a/api/client/model_model_endpoint_alert_condition.go +++ b/api/client/model_model_endpoint_alert_condition.go @@ -1,18 +1,304 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ModelEndpointAlertCondition type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelEndpointAlertCondition{} + +// ModelEndpointAlertCondition struct for ModelEndpointAlertCondition type ModelEndpointAlertCondition struct { - Enabled bool `json:"enabled,omitempty"` + Enabled *bool `json:"enabled,omitempty"` MetricType *AlertConditionMetricType `json:"metric_type,omitempty"` Severity *AlertConditionSeverity `json:"severity,omitempty"` - Target float64 `json:"target,omitempty"` - Percentile float64 `json:"percentile,omitempty"` - Unit string `json:"unit,omitempty"` + Target *float32 `json:"target,omitempty"` + Percentile *float32 `json:"percentile,omitempty"` + Unit *string `json:"unit,omitempty"` +} + +// NewModelEndpointAlertCondition instantiates a new ModelEndpointAlertCondition object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelEndpointAlertCondition() *ModelEndpointAlertCondition { + this := ModelEndpointAlertCondition{} + return &this +} + +// NewModelEndpointAlertConditionWithDefaults instantiates a new ModelEndpointAlertCondition object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelEndpointAlertConditionWithDefaults() *ModelEndpointAlertCondition { + this := ModelEndpointAlertCondition{} + return &this +} + +// GetEnabled returns the Enabled field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetEnabled() bool { + if o == nil || IsNil(o.Enabled) { + var ret bool + return ret + } + return *o.Enabled +} + +// GetEnabledOk returns a tuple with the Enabled field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetEnabledOk() (*bool, bool) { + if o == nil || IsNil(o.Enabled) { + return nil, false + } + return o.Enabled, true +} + +// HasEnabled returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasEnabled() bool { + if o != nil && !IsNil(o.Enabled) { + return true + } + + return false +} + +// SetEnabled gets a reference to the given bool and assigns it to the Enabled field. +func (o *ModelEndpointAlertCondition) SetEnabled(v bool) { + o.Enabled = &v +} + +// GetMetricType returns the MetricType field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetMetricType() AlertConditionMetricType { + if o == nil || IsNil(o.MetricType) { + var ret AlertConditionMetricType + return ret + } + return *o.MetricType +} + +// GetMetricTypeOk returns a tuple with the MetricType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetMetricTypeOk() (*AlertConditionMetricType, bool) { + if o == nil || IsNil(o.MetricType) { + return nil, false + } + return o.MetricType, true +} + +// HasMetricType returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasMetricType() bool { + if o != nil && !IsNil(o.MetricType) { + return true + } + + return false +} + +// SetMetricType gets a reference to the given AlertConditionMetricType and assigns it to the MetricType field. +func (o *ModelEndpointAlertCondition) SetMetricType(v AlertConditionMetricType) { + o.MetricType = &v +} + +// GetSeverity returns the Severity field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetSeverity() AlertConditionSeverity { + if o == nil || IsNil(o.Severity) { + var ret AlertConditionSeverity + return ret + } + return *o.Severity +} + +// GetSeverityOk returns a tuple with the Severity field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetSeverityOk() (*AlertConditionSeverity, bool) { + if o == nil || IsNil(o.Severity) { + return nil, false + } + return o.Severity, true +} + +// HasSeverity returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasSeverity() bool { + if o != nil && !IsNil(o.Severity) { + return true + } + + return false +} + +// SetSeverity gets a reference to the given AlertConditionSeverity and assigns it to the Severity field. +func (o *ModelEndpointAlertCondition) SetSeverity(v AlertConditionSeverity) { + o.Severity = &v +} + +// GetTarget returns the Target field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetTarget() float32 { + if o == nil || IsNil(o.Target) { + var ret float32 + return ret + } + return *o.Target +} + +// GetTargetOk returns a tuple with the Target field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetTargetOk() (*float32, bool) { + if o == nil || IsNil(o.Target) { + return nil, false + } + return o.Target, true +} + +// HasTarget returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasTarget() bool { + if o != nil && !IsNil(o.Target) { + return true + } + + return false +} + +// SetTarget gets a reference to the given float32 and assigns it to the Target field. +func (o *ModelEndpointAlertCondition) SetTarget(v float32) { + o.Target = &v +} + +// GetPercentile returns the Percentile field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetPercentile() float32 { + if o == nil || IsNil(o.Percentile) { + var ret float32 + return ret + } + return *o.Percentile +} + +// GetPercentileOk returns a tuple with the Percentile field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetPercentileOk() (*float32, bool) { + if o == nil || IsNil(o.Percentile) { + return nil, false + } + return o.Percentile, true +} + +// HasPercentile returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasPercentile() bool { + if o != nil && !IsNil(o.Percentile) { + return true + } + + return false +} + +// SetPercentile gets a reference to the given float32 and assigns it to the Percentile field. +func (o *ModelEndpointAlertCondition) SetPercentile(v float32) { + o.Percentile = &v +} + +// GetUnit returns the Unit field value if set, zero value otherwise. +func (o *ModelEndpointAlertCondition) GetUnit() string { + if o == nil || IsNil(o.Unit) { + var ret string + return ret + } + return *o.Unit +} + +// GetUnitOk returns a tuple with the Unit field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointAlertCondition) GetUnitOk() (*string, bool) { + if o == nil || IsNil(o.Unit) { + return nil, false + } + return o.Unit, true +} + +// HasUnit returns a boolean if a field has been set. +func (o *ModelEndpointAlertCondition) HasUnit() bool { + if o != nil && !IsNil(o.Unit) { + return true + } + + return false +} + +// SetUnit gets a reference to the given string and assigns it to the Unit field. +func (o *ModelEndpointAlertCondition) SetUnit(v string) { + o.Unit = &v +} + +func (o ModelEndpointAlertCondition) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelEndpointAlertCondition) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Enabled) { + toSerialize["enabled"] = o.Enabled + } + if !IsNil(o.MetricType) { + toSerialize["metric_type"] = o.MetricType + } + if !IsNil(o.Severity) { + toSerialize["severity"] = o.Severity + } + if !IsNil(o.Target) { + toSerialize["target"] = o.Target + } + if !IsNil(o.Percentile) { + toSerialize["percentile"] = o.Percentile + } + if !IsNil(o.Unit) { + toSerialize["unit"] = o.Unit + } + return toSerialize, nil +} + +type NullableModelEndpointAlertCondition struct { + value *ModelEndpointAlertCondition + isSet bool +} + +func (v NullableModelEndpointAlertCondition) Get() *ModelEndpointAlertCondition { + return v.value +} + +func (v *NullableModelEndpointAlertCondition) Set(val *ModelEndpointAlertCondition) { + v.value = val + v.isSet = true +} + +func (v NullableModelEndpointAlertCondition) IsSet() bool { + return v.isSet +} + +func (v *NullableModelEndpointAlertCondition) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelEndpointAlertCondition(val *ModelEndpointAlertCondition) *NullableModelEndpointAlertCondition { + return &NullableModelEndpointAlertCondition{value: val, isSet: true} +} + +func (v NullableModelEndpointAlertCondition) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelEndpointAlertCondition) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_model_endpoint_rule.go b/api/client/model_model_endpoint_rule.go index dd076f8fc..504002355 100644 --- a/api/client/model_model_endpoint_rule.go +++ b/api/client/model_model_endpoint_rule.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ModelEndpointRule type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelEndpointRule{} + +// ModelEndpointRule struct for ModelEndpointRule type ModelEndpointRule struct { Destinations []ModelEndpointRuleDestination `json:"destinations,omitempty"` Mirror *VersionEndpoint `json:"mirror,omitempty"` } + +// NewModelEndpointRule instantiates a new ModelEndpointRule object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelEndpointRule() *ModelEndpointRule { + this := ModelEndpointRule{} + return &this +} + +// NewModelEndpointRuleWithDefaults instantiates a new ModelEndpointRule object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelEndpointRuleWithDefaults() *ModelEndpointRule { + this := ModelEndpointRule{} + return &this +} + +// GetDestinations returns the Destinations field value if set, zero value otherwise. +func (o *ModelEndpointRule) GetDestinations() []ModelEndpointRuleDestination { + if o == nil || IsNil(o.Destinations) { + var ret []ModelEndpointRuleDestination + return ret + } + return o.Destinations +} + +// GetDestinationsOk returns a tuple with the Destinations field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointRule) GetDestinationsOk() ([]ModelEndpointRuleDestination, bool) { + if o == nil || IsNil(o.Destinations) { + return nil, false + } + return o.Destinations, true +} + +// HasDestinations returns a boolean if a field has been set. +func (o *ModelEndpointRule) HasDestinations() bool { + if o != nil && !IsNil(o.Destinations) { + return true + } + + return false +} + +// SetDestinations gets a reference to the given []ModelEndpointRuleDestination and assigns it to the Destinations field. +func (o *ModelEndpointRule) SetDestinations(v []ModelEndpointRuleDestination) { + o.Destinations = v +} + +// GetMirror returns the Mirror field value if set, zero value otherwise. +func (o *ModelEndpointRule) GetMirror() VersionEndpoint { + if o == nil || IsNil(o.Mirror) { + var ret VersionEndpoint + return ret + } + return *o.Mirror +} + +// GetMirrorOk returns a tuple with the Mirror field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointRule) GetMirrorOk() (*VersionEndpoint, bool) { + if o == nil || IsNil(o.Mirror) { + return nil, false + } + return o.Mirror, true +} + +// HasMirror returns a boolean if a field has been set. +func (o *ModelEndpointRule) HasMirror() bool { + if o != nil && !IsNil(o.Mirror) { + return true + } + + return false +} + +// SetMirror gets a reference to the given VersionEndpoint and assigns it to the Mirror field. +func (o *ModelEndpointRule) SetMirror(v VersionEndpoint) { + o.Mirror = &v +} + +func (o ModelEndpointRule) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelEndpointRule) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Destinations) { + toSerialize["destinations"] = o.Destinations + } + if !IsNil(o.Mirror) { + toSerialize["mirror"] = o.Mirror + } + return toSerialize, nil +} + +type NullableModelEndpointRule struct { + value *ModelEndpointRule + isSet bool +} + +func (v NullableModelEndpointRule) Get() *ModelEndpointRule { + return v.value +} + +func (v *NullableModelEndpointRule) Set(val *ModelEndpointRule) { + v.value = val + v.isSet = true +} + +func (v NullableModelEndpointRule) IsSet() bool { + return v.isSet +} + +func (v *NullableModelEndpointRule) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelEndpointRule(val *ModelEndpointRule) *NullableModelEndpointRule { + return &NullableModelEndpointRule{value: val, isSet: true} +} + +func (v NullableModelEndpointRule) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelEndpointRule) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_model_endpoint_rule_destination.go b/api/client/model_model_endpoint_rule_destination.go index 671dd7494..861621149 100644 --- a/api/client/model_model_endpoint_rule_destination.go +++ b/api/client/model_model_endpoint_rule_destination.go @@ -1,15 +1,196 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ModelEndpointRuleDestination type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelEndpointRuleDestination{} + +// ModelEndpointRuleDestination struct for ModelEndpointRuleDestination type ModelEndpointRuleDestination struct { - VersionEndpointId string `json:"version_endpoint_id,omitempty"` + VersionEndpointId *string `json:"version_endpoint_id,omitempty"` VersionEndpoint *VersionEndpoint `json:"version_endpoint,omitempty"` - Weight int32 `json:"weight,omitempty"` + Weight *int32 `json:"weight,omitempty"` +} + +// NewModelEndpointRuleDestination instantiates a new ModelEndpointRuleDestination object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelEndpointRuleDestination() *ModelEndpointRuleDestination { + this := ModelEndpointRuleDestination{} + return &this +} + +// NewModelEndpointRuleDestinationWithDefaults instantiates a new ModelEndpointRuleDestination object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelEndpointRuleDestinationWithDefaults() *ModelEndpointRuleDestination { + this := ModelEndpointRuleDestination{} + return &this +} + +// GetVersionEndpointId returns the VersionEndpointId field value if set, zero value otherwise. +func (o *ModelEndpointRuleDestination) GetVersionEndpointId() string { + if o == nil || IsNil(o.VersionEndpointId) { + var ret string + return ret + } + return *o.VersionEndpointId +} + +// GetVersionEndpointIdOk returns a tuple with the VersionEndpointId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointRuleDestination) GetVersionEndpointIdOk() (*string, bool) { + if o == nil || IsNil(o.VersionEndpointId) { + return nil, false + } + return o.VersionEndpointId, true +} + +// HasVersionEndpointId returns a boolean if a field has been set. +func (o *ModelEndpointRuleDestination) HasVersionEndpointId() bool { + if o != nil && !IsNil(o.VersionEndpointId) { + return true + } + + return false +} + +// SetVersionEndpointId gets a reference to the given string and assigns it to the VersionEndpointId field. +func (o *ModelEndpointRuleDestination) SetVersionEndpointId(v string) { + o.VersionEndpointId = &v +} + +// GetVersionEndpoint returns the VersionEndpoint field value if set, zero value otherwise. +func (o *ModelEndpointRuleDestination) GetVersionEndpoint() VersionEndpoint { + if o == nil || IsNil(o.VersionEndpoint) { + var ret VersionEndpoint + return ret + } + return *o.VersionEndpoint +} + +// GetVersionEndpointOk returns a tuple with the VersionEndpoint field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointRuleDestination) GetVersionEndpointOk() (*VersionEndpoint, bool) { + if o == nil || IsNil(o.VersionEndpoint) { + return nil, false + } + return o.VersionEndpoint, true +} + +// HasVersionEndpoint returns a boolean if a field has been set. +func (o *ModelEndpointRuleDestination) HasVersionEndpoint() bool { + if o != nil && !IsNil(o.VersionEndpoint) { + return true + } + + return false +} + +// SetVersionEndpoint gets a reference to the given VersionEndpoint and assigns it to the VersionEndpoint field. +func (o *ModelEndpointRuleDestination) SetVersionEndpoint(v VersionEndpoint) { + o.VersionEndpoint = &v +} + +// GetWeight returns the Weight field value if set, zero value otherwise. +func (o *ModelEndpointRuleDestination) GetWeight() int32 { + if o == nil || IsNil(o.Weight) { + var ret int32 + return ret + } + return *o.Weight +} + +// GetWeightOk returns a tuple with the Weight field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelEndpointRuleDestination) GetWeightOk() (*int32, bool) { + if o == nil || IsNil(o.Weight) { + return nil, false + } + return o.Weight, true +} + +// HasWeight returns a boolean if a field has been set. +func (o *ModelEndpointRuleDestination) HasWeight() bool { + if o != nil && !IsNil(o.Weight) { + return true + } + + return false +} + +// SetWeight gets a reference to the given int32 and assigns it to the Weight field. +func (o *ModelEndpointRuleDestination) SetWeight(v int32) { + o.Weight = &v +} + +func (o ModelEndpointRuleDestination) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelEndpointRuleDestination) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.VersionEndpointId) { + toSerialize["version_endpoint_id"] = o.VersionEndpointId + } + if !IsNil(o.VersionEndpoint) { + toSerialize["version_endpoint"] = o.VersionEndpoint + } + if !IsNil(o.Weight) { + toSerialize["weight"] = o.Weight + } + return toSerialize, nil +} + +type NullableModelEndpointRuleDestination struct { + value *ModelEndpointRuleDestination + isSet bool +} + +func (v NullableModelEndpointRuleDestination) Get() *ModelEndpointRuleDestination { + return v.value +} + +func (v *NullableModelEndpointRuleDestination) Set(val *ModelEndpointRuleDestination) { + v.value = val + v.isSet = true +} + +func (v NullableModelEndpointRuleDestination) IsSet() bool { + return v.isSet +} + +func (v *NullableModelEndpointRuleDestination) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelEndpointRuleDestination(val *ModelEndpointRuleDestination) *NullableModelEndpointRuleDestination { + return &NullableModelEndpointRuleDestination{value: val, isSet: true} +} + +func (v NullableModelEndpointRuleDestination) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelEndpointRuleDestination) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_model_prediction_config.go b/api/client/model_model_prediction_config.go index 77ac71fe8..09de8c399 100644 --- a/api/client/model_model_prediction_config.go +++ b/api/client/model_model_prediction_config.go @@ -1,13 +1,124 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ModelPredictionConfig type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelPredictionConfig{} + +// ModelPredictionConfig struct for ModelPredictionConfig type ModelPredictionConfig struct { MockResponse *MockResponse `json:"mock_response,omitempty"` } + +// NewModelPredictionConfig instantiates a new ModelPredictionConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelPredictionConfig() *ModelPredictionConfig { + this := ModelPredictionConfig{} + return &this +} + +// NewModelPredictionConfigWithDefaults instantiates a new ModelPredictionConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelPredictionConfigWithDefaults() *ModelPredictionConfig { + this := ModelPredictionConfig{} + return &this +} + +// GetMockResponse returns the MockResponse field value if set, zero value otherwise. +func (o *ModelPredictionConfig) GetMockResponse() MockResponse { + if o == nil || IsNil(o.MockResponse) { + var ret MockResponse + return ret + } + return *o.MockResponse +} + +// GetMockResponseOk returns a tuple with the MockResponse field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelPredictionConfig) GetMockResponseOk() (*MockResponse, bool) { + if o == nil || IsNil(o.MockResponse) { + return nil, false + } + return o.MockResponse, true +} + +// HasMockResponse returns a boolean if a field has been set. +func (o *ModelPredictionConfig) HasMockResponse() bool { + if o != nil && !IsNil(o.MockResponse) { + return true + } + + return false +} + +// SetMockResponse gets a reference to the given MockResponse and assigns it to the MockResponse field. +func (o *ModelPredictionConfig) SetMockResponse(v MockResponse) { + o.MockResponse = &v +} + +func (o ModelPredictionConfig) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelPredictionConfig) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.MockResponse) { + toSerialize["mock_response"] = o.MockResponse + } + return toSerialize, nil +} + +type NullableModelPredictionConfig struct { + value *ModelPredictionConfig + isSet bool +} + +func (v NullableModelPredictionConfig) Get() *ModelPredictionConfig { + return v.value +} + +func (v *NullableModelPredictionConfig) Set(val *ModelPredictionConfig) { + v.value = val + v.isSet = true +} + +func (v NullableModelPredictionConfig) IsSet() bool { + return v.isSet +} + +func (v *NullableModelPredictionConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelPredictionConfig(val *ModelPredictionConfig) *NullableModelPredictionConfig { + return &NullableModelPredictionConfig{value: val, isSet: true} +} + +func (v NullableModelPredictionConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelPredictionConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_model_prediction_output.go b/api/client/model_model_prediction_output.go new file mode 100644 index 000000000..3e0d72e8b --- /dev/null +++ b/api/client/model_model_prediction_output.go @@ -0,0 +1,175 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// ModelPredictionOutput - struct for ModelPredictionOutput +type ModelPredictionOutput struct { + BinaryClassificationOutput *BinaryClassificationOutput + RankingOutput *RankingOutput + RegressionOutput *RegressionOutput +} + +// BinaryClassificationOutputAsModelPredictionOutput is a convenience function that returns BinaryClassificationOutput wrapped in ModelPredictionOutput +func BinaryClassificationOutputAsModelPredictionOutput(v *BinaryClassificationOutput) ModelPredictionOutput { + return ModelPredictionOutput{ + BinaryClassificationOutput: v, + } +} + +// RankingOutputAsModelPredictionOutput is a convenience function that returns RankingOutput wrapped in ModelPredictionOutput +func RankingOutputAsModelPredictionOutput(v *RankingOutput) ModelPredictionOutput { + return ModelPredictionOutput{ + RankingOutput: v, + } +} + +// RegressionOutputAsModelPredictionOutput is a convenience function that returns RegressionOutput wrapped in ModelPredictionOutput +func RegressionOutputAsModelPredictionOutput(v *RegressionOutput) ModelPredictionOutput { + return ModelPredictionOutput{ + RegressionOutput: v, + } +} + +// Unmarshal JSON data into one of the pointers in the struct +func (dst *ModelPredictionOutput) UnmarshalJSON(data []byte) error { + var err error + match := 0 + // try to unmarshal data into BinaryClassificationOutput + err = newStrictDecoder(data).Decode(&dst.BinaryClassificationOutput) + if err == nil { + jsonBinaryClassificationOutput, _ := json.Marshal(dst.BinaryClassificationOutput) + if string(jsonBinaryClassificationOutput) == "{}" { // empty struct + dst.BinaryClassificationOutput = nil + } else { + match++ + } + } else { + dst.BinaryClassificationOutput = nil + } + + // try to unmarshal data into RankingOutput + err = newStrictDecoder(data).Decode(&dst.RankingOutput) + if err == nil { + jsonRankingOutput, _ := json.Marshal(dst.RankingOutput) + if string(jsonRankingOutput) == "{}" { // empty struct + dst.RankingOutput = nil + } else { + match++ + } + } else { + dst.RankingOutput = nil + } + + // try to unmarshal data into RegressionOutput + err = newStrictDecoder(data).Decode(&dst.RegressionOutput) + if err == nil { + jsonRegressionOutput, _ := json.Marshal(dst.RegressionOutput) + if string(jsonRegressionOutput) == "{}" { // empty struct + dst.RegressionOutput = nil + } else { + match++ + } + } else { + dst.RegressionOutput = nil + } + + if match > 1 { // more than 1 match + // reset to nil + dst.BinaryClassificationOutput = nil + dst.RankingOutput = nil + dst.RegressionOutput = nil + + return fmt.Errorf("data matches more than one schema in oneOf(ModelPredictionOutput)") + } else if match == 1 { + return nil // exactly one match + } else { // no match + return fmt.Errorf("data failed to match schemas in oneOf(ModelPredictionOutput)") + } +} + +// Marshal data from the first non-nil pointers in the struct to JSON +func (src ModelPredictionOutput) MarshalJSON() ([]byte, error) { + if src.BinaryClassificationOutput != nil { + return json.Marshal(&src.BinaryClassificationOutput) + } + + if src.RankingOutput != nil { + return json.Marshal(&src.RankingOutput) + } + + if src.RegressionOutput != nil { + return json.Marshal(&src.RegressionOutput) + } + + return nil, nil // no data in oneOf schemas +} + +// Get the actual instance +func (obj *ModelPredictionOutput) GetActualInstance() interface{} { + if obj == nil { + return nil + } + if obj.BinaryClassificationOutput != nil { + return obj.BinaryClassificationOutput + } + + if obj.RankingOutput != nil { + return obj.RankingOutput + } + + if obj.RegressionOutput != nil { + return obj.RegressionOutput + } + + // all schemas are nil + return nil +} + +type NullableModelPredictionOutput struct { + value *ModelPredictionOutput + isSet bool +} + +func (v NullableModelPredictionOutput) Get() *ModelPredictionOutput { + return v.value +} + +func (v *NullableModelPredictionOutput) Set(val *ModelPredictionOutput) { + v.value = val + v.isSet = true +} + +func (v NullableModelPredictionOutput) IsSet() bool { + return v.isSet +} + +func (v *NullableModelPredictionOutput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelPredictionOutput(val *ModelPredictionOutput) *NullableModelPredictionOutput { + return &NullableModelPredictionOutput{value: val, isSet: true} +} + +func (v NullableModelPredictionOutput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelPredictionOutput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_model_prediction_output_class.go b/api/client/model_model_prediction_output_class.go new file mode 100644 index 000000000..56ca67f11 --- /dev/null +++ b/api/client/model_model_prediction_output_class.go @@ -0,0 +1,112 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// ModelPredictionOutputClass the model 'ModelPredictionOutputClass' +type ModelPredictionOutputClass string + +// List of ModelPredictionOutputClass +const ( + MODELPREDICTIONOUTPUTCLASS_BINARY_CLASSIFICATION_OUTPUT ModelPredictionOutputClass = "BinaryClassificationOutput" + MODELPREDICTIONOUTPUTCLASS_RANKING_OUTPUT ModelPredictionOutputClass = "RankingOutput" + MODELPREDICTIONOUTPUTCLASS_REGRESSION_OUTPUT ModelPredictionOutputClass = "RegressionOutput" +) + +// All allowed values of ModelPredictionOutputClass enum +var AllowedModelPredictionOutputClassEnumValues = []ModelPredictionOutputClass{ + "BinaryClassificationOutput", + "RankingOutput", + "RegressionOutput", +} + +func (v *ModelPredictionOutputClass) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ModelPredictionOutputClass(value) + for _, existing := range AllowedModelPredictionOutputClassEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ModelPredictionOutputClass", value) +} + +// NewModelPredictionOutputClassFromValue returns a pointer to a valid ModelPredictionOutputClass +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewModelPredictionOutputClassFromValue(v string) (*ModelPredictionOutputClass, error) { + ev := ModelPredictionOutputClass(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ModelPredictionOutputClass: valid values are %v", v, AllowedModelPredictionOutputClassEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ModelPredictionOutputClass) IsValid() bool { + for _, existing := range AllowedModelPredictionOutputClassEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ModelPredictionOutputClass value +func (v ModelPredictionOutputClass) Ptr() *ModelPredictionOutputClass { + return &v +} + +type NullableModelPredictionOutputClass struct { + value *ModelPredictionOutputClass + isSet bool +} + +func (v NullableModelPredictionOutputClass) Get() *ModelPredictionOutputClass { + return v.value +} + +func (v *NullableModelPredictionOutputClass) Set(val *ModelPredictionOutputClass) { + v.value = val + v.isSet = true +} + +func (v NullableModelPredictionOutputClass) IsSet() bool { + return v.isSet +} + +func (v *NullableModelPredictionOutputClass) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelPredictionOutputClass(val *ModelPredictionOutputClass) *NullableModelPredictionOutputClass { + return &NullableModelPredictionOutputClass{value: val, isSet: true} +} + +func (v NullableModelPredictionOutputClass) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelPredictionOutputClass) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_model_schema.go b/api/client/model_model_schema.go new file mode 100644 index 000000000..4402fe03c --- /dev/null +++ b/api/client/model_model_schema.go @@ -0,0 +1,225 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// checks if the ModelSchema type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ModelSchema{} + +// ModelSchema struct for ModelSchema +type ModelSchema struct { + Id *int32 `json:"id,omitempty"` + ModelId *int32 `json:"model_id,omitempty"` + Spec SchemaSpec `json:"spec"` +} + +type _ModelSchema ModelSchema + +// NewModelSchema instantiates a new ModelSchema object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewModelSchema(spec SchemaSpec) *ModelSchema { + this := ModelSchema{} + this.Spec = spec + return &this +} + +// NewModelSchemaWithDefaults instantiates a new ModelSchema object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewModelSchemaWithDefaults() *ModelSchema { + this := ModelSchema{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *ModelSchema) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelSchema) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *ModelSchema) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *ModelSchema) SetId(v int32) { + o.Id = &v +} + +// GetModelId returns the ModelId field value if set, zero value otherwise. +func (o *ModelSchema) GetModelId() int32 { + if o == nil || IsNil(o.ModelId) { + var ret int32 + return ret + } + return *o.ModelId +} + +// GetModelIdOk returns a tuple with the ModelId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ModelSchema) GetModelIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelId) { + return nil, false + } + return o.ModelId, true +} + +// HasModelId returns a boolean if a field has been set. +func (o *ModelSchema) HasModelId() bool { + if o != nil && !IsNil(o.ModelId) { + return true + } + + return false +} + +// SetModelId gets a reference to the given int32 and assigns it to the ModelId field. +func (o *ModelSchema) SetModelId(v int32) { + o.ModelId = &v +} + +// GetSpec returns the Spec field value +func (o *ModelSchema) GetSpec() SchemaSpec { + if o == nil { + var ret SchemaSpec + return ret + } + + return o.Spec +} + +// GetSpecOk returns a tuple with the Spec field value +// and a boolean to check if the value has been set. +func (o *ModelSchema) GetSpecOk() (*SchemaSpec, bool) { + if o == nil { + return nil, false + } + return &o.Spec, true +} + +// SetSpec sets field value +func (o *ModelSchema) SetSpec(v SchemaSpec) { + o.Spec = v +} + +func (o ModelSchema) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ModelSchema) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.ModelId) { + toSerialize["model_id"] = o.ModelId + } + toSerialize["spec"] = o.Spec + return toSerialize, nil +} + +func (o *ModelSchema) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "spec", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varModelSchema := _ModelSchema{} + + err = json.Unmarshal(bytes, &varModelSchema) + + if err != nil { + return err + } + + *o = ModelSchema(varModelSchema) + + return err +} + +type NullableModelSchema struct { + value *ModelSchema + isSet bool +} + +func (v NullableModelSchema) Get() *ModelSchema { + return v.value +} + +func (v *NullableModelSchema) Set(val *ModelSchema) { + v.value = val + v.isSet = true +} + +func (v NullableModelSchema) IsSet() bool { + return v.isSet +} + +func (v *NullableModelSchema) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableModelSchema(val *ModelSchema) *NullableModelSchema { + return &NullableModelSchema{value: val, isSet: true} +} + +func (v NullableModelSchema) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableModelSchema) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_operation_tracing.go b/api/client/model_operation_tracing.go index 708b63ae0..c7cabf6f7 100644 --- a/api/client/model_operation_tracing.go +++ b/api/client/model_operation_tracing.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the OperationTracing type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &OperationTracing{} + +// OperationTracing struct for OperationTracing type OperationTracing struct { - Preprocess *[]PipelineTracingInner `json:"preprocess,omitempty"` - Postprocess *[]PipelineTracingInner `json:"postprocess,omitempty"` + Preprocess []PipelineTracing `json:"preprocess,omitempty"` + Postprocess []PipelineTracing `json:"postprocess,omitempty"` +} + +// NewOperationTracing instantiates a new OperationTracing object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewOperationTracing() *OperationTracing { + this := OperationTracing{} + return &this +} + +// NewOperationTracingWithDefaults instantiates a new OperationTracing object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewOperationTracingWithDefaults() *OperationTracing { + this := OperationTracing{} + return &this +} + +// GetPreprocess returns the Preprocess field value if set, zero value otherwise. +func (o *OperationTracing) GetPreprocess() []PipelineTracing { + if o == nil || IsNil(o.Preprocess) { + var ret []PipelineTracing + return ret + } + return o.Preprocess +} + +// GetPreprocessOk returns a tuple with the Preprocess field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OperationTracing) GetPreprocessOk() ([]PipelineTracing, bool) { + if o == nil || IsNil(o.Preprocess) { + return nil, false + } + return o.Preprocess, true +} + +// HasPreprocess returns a boolean if a field has been set. +func (o *OperationTracing) HasPreprocess() bool { + if o != nil && !IsNil(o.Preprocess) { + return true + } + + return false +} + +// SetPreprocess gets a reference to the given []PipelineTracing and assigns it to the Preprocess field. +func (o *OperationTracing) SetPreprocess(v []PipelineTracing) { + o.Preprocess = v +} + +// GetPostprocess returns the Postprocess field value if set, zero value otherwise. +func (o *OperationTracing) GetPostprocess() []PipelineTracing { + if o == nil || IsNil(o.Postprocess) { + var ret []PipelineTracing + return ret + } + return o.Postprocess +} + +// GetPostprocessOk returns a tuple with the Postprocess field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *OperationTracing) GetPostprocessOk() ([]PipelineTracing, bool) { + if o == nil || IsNil(o.Postprocess) { + return nil, false + } + return o.Postprocess, true +} + +// HasPostprocess returns a boolean if a field has been set. +func (o *OperationTracing) HasPostprocess() bool { + if o != nil && !IsNil(o.Postprocess) { + return true + } + + return false +} + +// SetPostprocess gets a reference to the given []PipelineTracing and assigns it to the Postprocess field. +func (o *OperationTracing) SetPostprocess(v []PipelineTracing) { + o.Postprocess = v +} + +func (o OperationTracing) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o OperationTracing) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Preprocess) { + toSerialize["preprocess"] = o.Preprocess + } + if !IsNil(o.Postprocess) { + toSerialize["postprocess"] = o.Postprocess + } + return toSerialize, nil +} + +type NullableOperationTracing struct { + value *OperationTracing + isSet bool +} + +func (v NullableOperationTracing) Get() *OperationTracing { + return v.value +} + +func (v *NullableOperationTracing) Set(val *OperationTracing) { + v.value = val + v.isSet = true +} + +func (v NullableOperationTracing) IsSet() bool { + return v.isSet +} + +func (v *NullableOperationTracing) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableOperationTracing(val *OperationTracing) *NullableOperationTracing { + return &NullableOperationTracing{value: val, isSet: true} +} + +func (v NullableOperationTracing) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableOperationTracing) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_pipeline_tracing.go b/api/client/model_pipeline_tracing.go new file mode 100644 index 000000000..5d6feba58 --- /dev/null +++ b/api/client/model_pipeline_tracing.go @@ -0,0 +1,232 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" +) + +// checks if the PipelineTracing type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PipelineTracing{} + +// PipelineTracing struct for PipelineTracing +type PipelineTracing struct { + OperationType *string `json:"operation_type,omitempty"` + Spec map[string]interface{} `json:"spec,omitempty"` + Input map[string]interface{} `json:"input,omitempty"` + Output map[string]interface{} `json:"output,omitempty"` +} + +// NewPipelineTracing instantiates a new PipelineTracing object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPipelineTracing() *PipelineTracing { + this := PipelineTracing{} + return &this +} + +// NewPipelineTracingWithDefaults instantiates a new PipelineTracing object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPipelineTracingWithDefaults() *PipelineTracing { + this := PipelineTracing{} + return &this +} + +// GetOperationType returns the OperationType field value if set, zero value otherwise. +func (o *PipelineTracing) GetOperationType() string { + if o == nil || IsNil(o.OperationType) { + var ret string + return ret + } + return *o.OperationType +} + +// GetOperationTypeOk returns a tuple with the OperationType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PipelineTracing) GetOperationTypeOk() (*string, bool) { + if o == nil || IsNil(o.OperationType) { + return nil, false + } + return o.OperationType, true +} + +// HasOperationType returns a boolean if a field has been set. +func (o *PipelineTracing) HasOperationType() bool { + if o != nil && !IsNil(o.OperationType) { + return true + } + + return false +} + +// SetOperationType gets a reference to the given string and assigns it to the OperationType field. +func (o *PipelineTracing) SetOperationType(v string) { + o.OperationType = &v +} + +// GetSpec returns the Spec field value if set, zero value otherwise. +func (o *PipelineTracing) GetSpec() map[string]interface{} { + if o == nil || IsNil(o.Spec) { + var ret map[string]interface{} + return ret + } + return o.Spec +} + +// GetSpecOk returns a tuple with the Spec field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PipelineTracing) GetSpecOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Spec) { + return map[string]interface{}{}, false + } + return o.Spec, true +} + +// HasSpec returns a boolean if a field has been set. +func (o *PipelineTracing) HasSpec() bool { + if o != nil && !IsNil(o.Spec) { + return true + } + + return false +} + +// SetSpec gets a reference to the given map[string]interface{} and assigns it to the Spec field. +func (o *PipelineTracing) SetSpec(v map[string]interface{}) { + o.Spec = v +} + +// GetInput returns the Input field value if set, zero value otherwise. +func (o *PipelineTracing) GetInput() map[string]interface{} { + if o == nil || IsNil(o.Input) { + var ret map[string]interface{} + return ret + } + return o.Input +} + +// GetInputOk returns a tuple with the Input field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PipelineTracing) GetInputOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Input) { + return map[string]interface{}{}, false + } + return o.Input, true +} + +// HasInput returns a boolean if a field has been set. +func (o *PipelineTracing) HasInput() bool { + if o != nil && !IsNil(o.Input) { + return true + } + + return false +} + +// SetInput gets a reference to the given map[string]interface{} and assigns it to the Input field. +func (o *PipelineTracing) SetInput(v map[string]interface{}) { + o.Input = v +} + +// GetOutput returns the Output field value if set, zero value otherwise. +func (o *PipelineTracing) GetOutput() map[string]interface{} { + if o == nil || IsNil(o.Output) { + var ret map[string]interface{} + return ret + } + return o.Output +} + +// GetOutputOk returns a tuple with the Output field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PipelineTracing) GetOutputOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Output) { + return map[string]interface{}{}, false + } + return o.Output, true +} + +// HasOutput returns a boolean if a field has been set. +func (o *PipelineTracing) HasOutput() bool { + if o != nil && !IsNil(o.Output) { + return true + } + + return false +} + +// SetOutput gets a reference to the given map[string]interface{} and assigns it to the Output field. +func (o *PipelineTracing) SetOutput(v map[string]interface{}) { + o.Output = v +} + +func (o PipelineTracing) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PipelineTracing) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.OperationType) { + toSerialize["operation_type"] = o.OperationType + } + if !IsNil(o.Spec) { + toSerialize["spec"] = o.Spec + } + if !IsNil(o.Input) { + toSerialize["input"] = o.Input + } + if !IsNil(o.Output) { + toSerialize["output"] = o.Output + } + return toSerialize, nil +} + +type NullablePipelineTracing struct { + value *PipelineTracing + isSet bool +} + +func (v NullablePipelineTracing) Get() *PipelineTracing { + return v.value +} + +func (v *NullablePipelineTracing) Set(val *PipelineTracing) { + v.value = val + v.isSet = true +} + +func (v NullablePipelineTracing) IsSet() bool { + return v.isSet +} + +func (v *NullablePipelineTracing) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePipelineTracing(val *PipelineTracing) *NullablePipelineTracing { + return &NullablePipelineTracing{value: val, isSet: true} +} + +func (v NullablePipelineTracing) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePipelineTracing) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_pipeline_tracing_inner.go b/api/client/model_pipeline_tracing_inner.go deleted file mode 100644 index d5023a5d9..000000000 --- a/api/client/model_pipeline_tracing_inner.go +++ /dev/null @@ -1,16 +0,0 @@ -/* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ -package client - -type PipelineTracingInner struct { - OperationType string `json:"operation_type,omitempty"` - Specs *ModelMap `json:"specs,omitempty"` - Inputs *ModelMap `json:"inputs,omitempty"` - Outputs *ModelMap `json:"outputs,omitempty"` -} diff --git a/api/client/model_prediction_job.go b/api/client/model_prediction_job.go index 0b76d4c0f..b14298f08 100644 --- a/api/client/model_prediction_job.go +++ b/api/client/model_prediction_job.go @@ -1,28 +1,521 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" "time" ) +// checks if the PredictionJob type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJob{} + +// PredictionJob struct for PredictionJob type PredictionJob struct { - Id int32 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - VersionId int32 `json:"version_id,omitempty"` - ModelId int32 `json:"model_id,omitempty"` - ProjectId int32 `json:"project_id,omitempty"` - EnvironmentName string `json:"environment_name,omitempty"` + Id *int32 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + VersionId *int32 `json:"version_id,omitempty"` + ModelId *int32 `json:"model_id,omitempty"` + ProjectId *int32 `json:"project_id,omitempty"` + EnvironmentName *string `json:"environment_name,omitempty"` Environment *Environment `json:"environment,omitempty"` Config *Config `json:"config,omitempty"` - Status string `json:"status,omitempty"` - Error_ string `json:"error,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + Status *string `json:"status,omitempty"` + Error *string `json:"error,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// NewPredictionJob instantiates a new PredictionJob object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJob() *PredictionJob { + this := PredictionJob{} + return &this +} + +// NewPredictionJobWithDefaults instantiates a new PredictionJob object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobWithDefaults() *PredictionJob { + this := PredictionJob{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *PredictionJob) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *PredictionJob) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *PredictionJob) SetId(v int32) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *PredictionJob) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *PredictionJob) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *PredictionJob) SetName(v string) { + o.Name = &v +} + +// GetVersionId returns the VersionId field value if set, zero value otherwise. +func (o *PredictionJob) GetVersionId() int32 { + if o == nil || IsNil(o.VersionId) { + var ret int32 + return ret + } + return *o.VersionId +} + +// GetVersionIdOk returns a tuple with the VersionId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetVersionIdOk() (*int32, bool) { + if o == nil || IsNil(o.VersionId) { + return nil, false + } + return o.VersionId, true +} + +// HasVersionId returns a boolean if a field has been set. +func (o *PredictionJob) HasVersionId() bool { + if o != nil && !IsNil(o.VersionId) { + return true + } + + return false +} + +// SetVersionId gets a reference to the given int32 and assigns it to the VersionId field. +func (o *PredictionJob) SetVersionId(v int32) { + o.VersionId = &v +} + +// GetModelId returns the ModelId field value if set, zero value otherwise. +func (o *PredictionJob) GetModelId() int32 { + if o == nil || IsNil(o.ModelId) { + var ret int32 + return ret + } + return *o.ModelId +} + +// GetModelIdOk returns a tuple with the ModelId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetModelIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelId) { + return nil, false + } + return o.ModelId, true +} + +// HasModelId returns a boolean if a field has been set. +func (o *PredictionJob) HasModelId() bool { + if o != nil && !IsNil(o.ModelId) { + return true + } + + return false +} + +// SetModelId gets a reference to the given int32 and assigns it to the ModelId field. +func (o *PredictionJob) SetModelId(v int32) { + o.ModelId = &v +} + +// GetProjectId returns the ProjectId field value if set, zero value otherwise. +func (o *PredictionJob) GetProjectId() int32 { + if o == nil || IsNil(o.ProjectId) { + var ret int32 + return ret + } + return *o.ProjectId +} + +// GetProjectIdOk returns a tuple with the ProjectId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetProjectIdOk() (*int32, bool) { + if o == nil || IsNil(o.ProjectId) { + return nil, false + } + return o.ProjectId, true +} + +// HasProjectId returns a boolean if a field has been set. +func (o *PredictionJob) HasProjectId() bool { + if o != nil && !IsNil(o.ProjectId) { + return true + } + + return false +} + +// SetProjectId gets a reference to the given int32 and assigns it to the ProjectId field. +func (o *PredictionJob) SetProjectId(v int32) { + o.ProjectId = &v +} + +// GetEnvironmentName returns the EnvironmentName field value if set, zero value otherwise. +func (o *PredictionJob) GetEnvironmentName() string { + if o == nil || IsNil(o.EnvironmentName) { + var ret string + return ret + } + return *o.EnvironmentName +} + +// GetEnvironmentNameOk returns a tuple with the EnvironmentName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetEnvironmentNameOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentName) { + return nil, false + } + return o.EnvironmentName, true +} + +// HasEnvironmentName returns a boolean if a field has been set. +func (o *PredictionJob) HasEnvironmentName() bool { + if o != nil && !IsNil(o.EnvironmentName) { + return true + } + + return false +} + +// SetEnvironmentName gets a reference to the given string and assigns it to the EnvironmentName field. +func (o *PredictionJob) SetEnvironmentName(v string) { + o.EnvironmentName = &v +} + +// GetEnvironment returns the Environment field value if set, zero value otherwise. +func (o *PredictionJob) GetEnvironment() Environment { + if o == nil || IsNil(o.Environment) { + var ret Environment + return ret + } + return *o.Environment +} + +// GetEnvironmentOk returns a tuple with the Environment field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetEnvironmentOk() (*Environment, bool) { + if o == nil || IsNil(o.Environment) { + return nil, false + } + return o.Environment, true +} + +// HasEnvironment returns a boolean if a field has been set. +func (o *PredictionJob) HasEnvironment() bool { + if o != nil && !IsNil(o.Environment) { + return true + } + + return false +} + +// SetEnvironment gets a reference to the given Environment and assigns it to the Environment field. +func (o *PredictionJob) SetEnvironment(v Environment) { + o.Environment = &v +} + +// GetConfig returns the Config field value if set, zero value otherwise. +func (o *PredictionJob) GetConfig() Config { + if o == nil || IsNil(o.Config) { + var ret Config + return ret + } + return *o.Config +} + +// GetConfigOk returns a tuple with the Config field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetConfigOk() (*Config, bool) { + if o == nil || IsNil(o.Config) { + return nil, false + } + return o.Config, true +} + +// HasConfig returns a boolean if a field has been set. +func (o *PredictionJob) HasConfig() bool { + if o != nil && !IsNil(o.Config) { + return true + } + + return false +} + +// SetConfig gets a reference to the given Config and assigns it to the Config field. +func (o *PredictionJob) SetConfig(v Config) { + o.Config = &v +} + +// GetStatus returns the Status field value if set, zero value otherwise. +func (o *PredictionJob) GetStatus() string { + if o == nil || IsNil(o.Status) { + var ret string + return ret + } + return *o.Status +} + +// GetStatusOk returns a tuple with the Status field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetStatusOk() (*string, bool) { + if o == nil || IsNil(o.Status) { + return nil, false + } + return o.Status, true +} + +// HasStatus returns a boolean if a field has been set. +func (o *PredictionJob) HasStatus() bool { + if o != nil && !IsNil(o.Status) { + return true + } + + return false +} + +// SetStatus gets a reference to the given string and assigns it to the Status field. +func (o *PredictionJob) SetStatus(v string) { + o.Status = &v +} + +// GetError returns the Error field value if set, zero value otherwise. +func (o *PredictionJob) GetError() string { + if o == nil || IsNil(o.Error) { + var ret string + return ret + } + return *o.Error +} + +// GetErrorOk returns a tuple with the Error field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetErrorOk() (*string, bool) { + if o == nil || IsNil(o.Error) { + return nil, false + } + return o.Error, true +} + +// HasError returns a boolean if a field has been set. +func (o *PredictionJob) HasError() bool { + if o != nil && !IsNil(o.Error) { + return true + } + + return false +} + +// SetError gets a reference to the given string and assigns it to the Error field. +func (o *PredictionJob) SetError(v string) { + o.Error = &v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *PredictionJob) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *PredictionJob) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *PredictionJob) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *PredictionJob) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJob) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *PredictionJob) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *PredictionJob) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o PredictionJob) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJob) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.VersionId) { + toSerialize["version_id"] = o.VersionId + } + if !IsNil(o.ModelId) { + toSerialize["model_id"] = o.ModelId + } + if !IsNil(o.ProjectId) { + toSerialize["project_id"] = o.ProjectId + } + if !IsNil(o.EnvironmentName) { + toSerialize["environment_name"] = o.EnvironmentName + } + if !IsNil(o.Environment) { + toSerialize["environment"] = o.Environment + } + if !IsNil(o.Config) { + toSerialize["config"] = o.Config + } + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + if !IsNil(o.Error) { + toSerialize["error"] = o.Error + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +type NullablePredictionJob struct { + value *PredictionJob + isSet bool +} + +func (v NullablePredictionJob) Get() *PredictionJob { + return v.value +} + +func (v *NullablePredictionJob) Set(val *PredictionJob) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJob) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJob) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJob(val *PredictionJob) *NullablePredictionJob { + return &NullablePredictionJob{value: val, isSet: true} +} + +func (v NullablePredictionJob) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJob) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config.go b/api/client/model_prediction_job_config.go index 60c2a9455..6f715e31e 100644 --- a/api/client/model_prediction_job_config.go +++ b/api/client/model_prediction_job_config.go @@ -1,20 +1,376 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfig type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfig{} + +// PredictionJobConfig struct for PredictionJobConfig type PredictionJobConfig struct { - Version string `json:"version,omitempty"` - Kind string `json:"kind,omitempty"` - Name string `json:"name,omitempty"` + Version *string `json:"version,omitempty"` + Kind *string `json:"kind,omitempty"` + Name *string `json:"name,omitempty"` BigquerySource *PredictionJobConfigBigquerySource `json:"bigquery_source,omitempty"` GcsSource *PredictionJobConfigGcsSource `json:"gcs_source,omitempty"` Model *PredictionJobConfigModel `json:"model,omitempty"` BigquerySink *PredictionJobConfigBigquerySink `json:"bigquery_sink,omitempty"` GcsSink *PredictionJobConfigGcsSink `json:"gcs_sink,omitempty"` } + +// NewPredictionJobConfig instantiates a new PredictionJobConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfig() *PredictionJobConfig { + this := PredictionJobConfig{} + return &this +} + +// NewPredictionJobConfigWithDefaults instantiates a new PredictionJobConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigWithDefaults() *PredictionJobConfig { + this := PredictionJobConfig{} + return &this +} + +// GetVersion returns the Version field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetVersion() string { + if o == nil || IsNil(o.Version) { + var ret string + return ret + } + return *o.Version +} + +// GetVersionOk returns a tuple with the Version field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetVersionOk() (*string, bool) { + if o == nil || IsNil(o.Version) { + return nil, false + } + return o.Version, true +} + +// HasVersion returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasVersion() bool { + if o != nil && !IsNil(o.Version) { + return true + } + + return false +} + +// SetVersion gets a reference to the given string and assigns it to the Version field. +func (o *PredictionJobConfig) SetVersion(v string) { + o.Version = &v +} + +// GetKind returns the Kind field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetKind() string { + if o == nil || IsNil(o.Kind) { + var ret string + return ret + } + return *o.Kind +} + +// GetKindOk returns a tuple with the Kind field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetKindOk() (*string, bool) { + if o == nil || IsNil(o.Kind) { + return nil, false + } + return o.Kind, true +} + +// HasKind returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasKind() bool { + if o != nil && !IsNil(o.Kind) { + return true + } + + return false +} + +// SetKind gets a reference to the given string and assigns it to the Kind field. +func (o *PredictionJobConfig) SetKind(v string) { + o.Kind = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *PredictionJobConfig) SetName(v string) { + o.Name = &v +} + +// GetBigquerySource returns the BigquerySource field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetBigquerySource() PredictionJobConfigBigquerySource { + if o == nil || IsNil(o.BigquerySource) { + var ret PredictionJobConfigBigquerySource + return ret + } + return *o.BigquerySource +} + +// GetBigquerySourceOk returns a tuple with the BigquerySource field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetBigquerySourceOk() (*PredictionJobConfigBigquerySource, bool) { + if o == nil || IsNil(o.BigquerySource) { + return nil, false + } + return o.BigquerySource, true +} + +// HasBigquerySource returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasBigquerySource() bool { + if o != nil && !IsNil(o.BigquerySource) { + return true + } + + return false +} + +// SetBigquerySource gets a reference to the given PredictionJobConfigBigquerySource and assigns it to the BigquerySource field. +func (o *PredictionJobConfig) SetBigquerySource(v PredictionJobConfigBigquerySource) { + o.BigquerySource = &v +} + +// GetGcsSource returns the GcsSource field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetGcsSource() PredictionJobConfigGcsSource { + if o == nil || IsNil(o.GcsSource) { + var ret PredictionJobConfigGcsSource + return ret + } + return *o.GcsSource +} + +// GetGcsSourceOk returns a tuple with the GcsSource field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetGcsSourceOk() (*PredictionJobConfigGcsSource, bool) { + if o == nil || IsNil(o.GcsSource) { + return nil, false + } + return o.GcsSource, true +} + +// HasGcsSource returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasGcsSource() bool { + if o != nil && !IsNil(o.GcsSource) { + return true + } + + return false +} + +// SetGcsSource gets a reference to the given PredictionJobConfigGcsSource and assigns it to the GcsSource field. +func (o *PredictionJobConfig) SetGcsSource(v PredictionJobConfigGcsSource) { + o.GcsSource = &v +} + +// GetModel returns the Model field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetModel() PredictionJobConfigModel { + if o == nil || IsNil(o.Model) { + var ret PredictionJobConfigModel + return ret + } + return *o.Model +} + +// GetModelOk returns a tuple with the Model field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetModelOk() (*PredictionJobConfigModel, bool) { + if o == nil || IsNil(o.Model) { + return nil, false + } + return o.Model, true +} + +// HasModel returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasModel() bool { + if o != nil && !IsNil(o.Model) { + return true + } + + return false +} + +// SetModel gets a reference to the given PredictionJobConfigModel and assigns it to the Model field. +func (o *PredictionJobConfig) SetModel(v PredictionJobConfigModel) { + o.Model = &v +} + +// GetBigquerySink returns the BigquerySink field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetBigquerySink() PredictionJobConfigBigquerySink { + if o == nil || IsNil(o.BigquerySink) { + var ret PredictionJobConfigBigquerySink + return ret + } + return *o.BigquerySink +} + +// GetBigquerySinkOk returns a tuple with the BigquerySink field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetBigquerySinkOk() (*PredictionJobConfigBigquerySink, bool) { + if o == nil || IsNil(o.BigquerySink) { + return nil, false + } + return o.BigquerySink, true +} + +// HasBigquerySink returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasBigquerySink() bool { + if o != nil && !IsNil(o.BigquerySink) { + return true + } + + return false +} + +// SetBigquerySink gets a reference to the given PredictionJobConfigBigquerySink and assigns it to the BigquerySink field. +func (o *PredictionJobConfig) SetBigquerySink(v PredictionJobConfigBigquerySink) { + o.BigquerySink = &v +} + +// GetGcsSink returns the GcsSink field value if set, zero value otherwise. +func (o *PredictionJobConfig) GetGcsSink() PredictionJobConfigGcsSink { + if o == nil || IsNil(o.GcsSink) { + var ret PredictionJobConfigGcsSink + return ret + } + return *o.GcsSink +} + +// GetGcsSinkOk returns a tuple with the GcsSink field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfig) GetGcsSinkOk() (*PredictionJobConfigGcsSink, bool) { + if o == nil || IsNil(o.GcsSink) { + return nil, false + } + return o.GcsSink, true +} + +// HasGcsSink returns a boolean if a field has been set. +func (o *PredictionJobConfig) HasGcsSink() bool { + if o != nil && !IsNil(o.GcsSink) { + return true + } + + return false +} + +// SetGcsSink gets a reference to the given PredictionJobConfigGcsSink and assigns it to the GcsSink field. +func (o *PredictionJobConfig) SetGcsSink(v PredictionJobConfigGcsSink) { + o.GcsSink = &v +} + +func (o PredictionJobConfig) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfig) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Version) { + toSerialize["version"] = o.Version + } + if !IsNil(o.Kind) { + toSerialize["kind"] = o.Kind + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.BigquerySource) { + toSerialize["bigquery_source"] = o.BigquerySource + } + if !IsNil(o.GcsSource) { + toSerialize["gcs_source"] = o.GcsSource + } + if !IsNil(o.Model) { + toSerialize["model"] = o.Model + } + if !IsNil(o.BigquerySink) { + toSerialize["bigquery_sink"] = o.BigquerySink + } + if !IsNil(o.GcsSink) { + toSerialize["gcs_sink"] = o.GcsSink + } + return toSerialize, nil +} + +type NullablePredictionJobConfig struct { + value *PredictionJobConfig + isSet bool +} + +func (v NullablePredictionJobConfig) Get() *PredictionJobConfig { + return v.value +} + +func (v *NullablePredictionJobConfig) Set(val *PredictionJobConfig) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfig) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfig(val *PredictionJobConfig) *NullablePredictionJobConfig { + return &NullablePredictionJobConfig{value: val, isSet: true} +} + +func (v NullablePredictionJobConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_prediction_job_config_bigquery_sink.go b/api/client/model_prediction_job_config_bigquery_sink.go index dcf211e50..d02461dd1 100644 --- a/api/client/model_prediction_job_config_bigquery_sink.go +++ b/api/client/model_prediction_job_config_bigquery_sink.go @@ -1,17 +1,268 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigBigquerySink type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigBigquerySink{} + +// PredictionJobConfigBigquerySink struct for PredictionJobConfigBigquerySink type PredictionJobConfigBigquerySink struct { - Table string `json:"table,omitempty"` - StagingBucket string `json:"staging_bucket,omitempty"` - ResultColumn string `json:"result_column,omitempty"` - SaveMode *SaveMode `json:"save_mode,omitempty"` - Options map[string]string `json:"options,omitempty"` + Table *string `json:"table,omitempty"` + StagingBucket *string `json:"staging_bucket,omitempty"` + ResultColumn *string `json:"result_column,omitempty"` + SaveMode *SaveMode `json:"save_mode,omitempty"` + Options *map[string]string `json:"options,omitempty"` +} + +// NewPredictionJobConfigBigquerySink instantiates a new PredictionJobConfigBigquerySink object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigBigquerySink() *PredictionJobConfigBigquerySink { + this := PredictionJobConfigBigquerySink{} + return &this +} + +// NewPredictionJobConfigBigquerySinkWithDefaults instantiates a new PredictionJobConfigBigquerySink object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigBigquerySinkWithDefaults() *PredictionJobConfigBigquerySink { + this := PredictionJobConfigBigquerySink{} + return &this +} + +// GetTable returns the Table field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySink) GetTable() string { + if o == nil || IsNil(o.Table) { + var ret string + return ret + } + return *o.Table +} + +// GetTableOk returns a tuple with the Table field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySink) GetTableOk() (*string, bool) { + if o == nil || IsNil(o.Table) { + return nil, false + } + return o.Table, true +} + +// HasTable returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySink) HasTable() bool { + if o != nil && !IsNil(o.Table) { + return true + } + + return false +} + +// SetTable gets a reference to the given string and assigns it to the Table field. +func (o *PredictionJobConfigBigquerySink) SetTable(v string) { + o.Table = &v +} + +// GetStagingBucket returns the StagingBucket field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySink) GetStagingBucket() string { + if o == nil || IsNil(o.StagingBucket) { + var ret string + return ret + } + return *o.StagingBucket +} + +// GetStagingBucketOk returns a tuple with the StagingBucket field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySink) GetStagingBucketOk() (*string, bool) { + if o == nil || IsNil(o.StagingBucket) { + return nil, false + } + return o.StagingBucket, true +} + +// HasStagingBucket returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySink) HasStagingBucket() bool { + if o != nil && !IsNil(o.StagingBucket) { + return true + } + + return false +} + +// SetStagingBucket gets a reference to the given string and assigns it to the StagingBucket field. +func (o *PredictionJobConfigBigquerySink) SetStagingBucket(v string) { + o.StagingBucket = &v +} + +// GetResultColumn returns the ResultColumn field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySink) GetResultColumn() string { + if o == nil || IsNil(o.ResultColumn) { + var ret string + return ret + } + return *o.ResultColumn +} + +// GetResultColumnOk returns a tuple with the ResultColumn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySink) GetResultColumnOk() (*string, bool) { + if o == nil || IsNil(o.ResultColumn) { + return nil, false + } + return o.ResultColumn, true +} + +// HasResultColumn returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySink) HasResultColumn() bool { + if o != nil && !IsNil(o.ResultColumn) { + return true + } + + return false +} + +// SetResultColumn gets a reference to the given string and assigns it to the ResultColumn field. +func (o *PredictionJobConfigBigquerySink) SetResultColumn(v string) { + o.ResultColumn = &v +} + +// GetSaveMode returns the SaveMode field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySink) GetSaveMode() SaveMode { + if o == nil || IsNil(o.SaveMode) { + var ret SaveMode + return ret + } + return *o.SaveMode +} + +// GetSaveModeOk returns a tuple with the SaveMode field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySink) GetSaveModeOk() (*SaveMode, bool) { + if o == nil || IsNil(o.SaveMode) { + return nil, false + } + return o.SaveMode, true +} + +// HasSaveMode returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySink) HasSaveMode() bool { + if o != nil && !IsNil(o.SaveMode) { + return true + } + + return false +} + +// SetSaveMode gets a reference to the given SaveMode and assigns it to the SaveMode field. +func (o *PredictionJobConfigBigquerySink) SetSaveMode(v SaveMode) { + o.SaveMode = &v +} + +// GetOptions returns the Options field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySink) GetOptions() map[string]string { + if o == nil || IsNil(o.Options) { + var ret map[string]string + return ret + } + return *o.Options +} + +// GetOptionsOk returns a tuple with the Options field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySink) GetOptionsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Options) { + return nil, false + } + return o.Options, true +} + +// HasOptions returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySink) HasOptions() bool { + if o != nil && !IsNil(o.Options) { + return true + } + + return false +} + +// SetOptions gets a reference to the given map[string]string and assigns it to the Options field. +func (o *PredictionJobConfigBigquerySink) SetOptions(v map[string]string) { + o.Options = &v +} + +func (o PredictionJobConfigBigquerySink) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigBigquerySink) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Table) { + toSerialize["table"] = o.Table + } + if !IsNil(o.StagingBucket) { + toSerialize["staging_bucket"] = o.StagingBucket + } + if !IsNil(o.ResultColumn) { + toSerialize["result_column"] = o.ResultColumn + } + if !IsNil(o.SaveMode) { + toSerialize["save_mode"] = o.SaveMode + } + if !IsNil(o.Options) { + toSerialize["options"] = o.Options + } + return toSerialize, nil +} + +type NullablePredictionJobConfigBigquerySink struct { + value *PredictionJobConfigBigquerySink + isSet bool +} + +func (v NullablePredictionJobConfigBigquerySink) Get() *PredictionJobConfigBigquerySink { + return v.value +} + +func (v *NullablePredictionJobConfigBigquerySink) Set(val *PredictionJobConfigBigquerySink) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigBigquerySink) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigBigquerySink) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigBigquerySink(val *PredictionJobConfigBigquerySink) *NullablePredictionJobConfigBigquerySink { + return &NullablePredictionJobConfigBigquerySink{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigBigquerySink) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigBigquerySink) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config_bigquery_source.go b/api/client/model_prediction_job_config_bigquery_source.go index 363b90d2f..ba00f4db8 100644 --- a/api/client/model_prediction_job_config_bigquery_source.go +++ b/api/client/model_prediction_job_config_bigquery_source.go @@ -1,15 +1,196 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigBigquerySource type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigBigquerySource{} + +// PredictionJobConfigBigquerySource struct for PredictionJobConfigBigquerySource type PredictionJobConfigBigquerySource struct { - Table string `json:"table,omitempty"` - Features []string `json:"features,omitempty"` - Options map[string]string `json:"options,omitempty"` + Table *string `json:"table,omitempty"` + Features []string `json:"features,omitempty"` + Options *map[string]string `json:"options,omitempty"` +} + +// NewPredictionJobConfigBigquerySource instantiates a new PredictionJobConfigBigquerySource object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigBigquerySource() *PredictionJobConfigBigquerySource { + this := PredictionJobConfigBigquerySource{} + return &this +} + +// NewPredictionJobConfigBigquerySourceWithDefaults instantiates a new PredictionJobConfigBigquerySource object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigBigquerySourceWithDefaults() *PredictionJobConfigBigquerySource { + this := PredictionJobConfigBigquerySource{} + return &this +} + +// GetTable returns the Table field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySource) GetTable() string { + if o == nil || IsNil(o.Table) { + var ret string + return ret + } + return *o.Table +} + +// GetTableOk returns a tuple with the Table field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySource) GetTableOk() (*string, bool) { + if o == nil || IsNil(o.Table) { + return nil, false + } + return o.Table, true +} + +// HasTable returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySource) HasTable() bool { + if o != nil && !IsNil(o.Table) { + return true + } + + return false +} + +// SetTable gets a reference to the given string and assigns it to the Table field. +func (o *PredictionJobConfigBigquerySource) SetTable(v string) { + o.Table = &v +} + +// GetFeatures returns the Features field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySource) GetFeatures() []string { + if o == nil || IsNil(o.Features) { + var ret []string + return ret + } + return o.Features +} + +// GetFeaturesOk returns a tuple with the Features field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySource) GetFeaturesOk() ([]string, bool) { + if o == nil || IsNil(o.Features) { + return nil, false + } + return o.Features, true +} + +// HasFeatures returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySource) HasFeatures() bool { + if o != nil && !IsNil(o.Features) { + return true + } + + return false +} + +// SetFeatures gets a reference to the given []string and assigns it to the Features field. +func (o *PredictionJobConfigBigquerySource) SetFeatures(v []string) { + o.Features = v +} + +// GetOptions returns the Options field value if set, zero value otherwise. +func (o *PredictionJobConfigBigquerySource) GetOptions() map[string]string { + if o == nil || IsNil(o.Options) { + var ret map[string]string + return ret + } + return *o.Options +} + +// GetOptionsOk returns a tuple with the Options field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigBigquerySource) GetOptionsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Options) { + return nil, false + } + return o.Options, true +} + +// HasOptions returns a boolean if a field has been set. +func (o *PredictionJobConfigBigquerySource) HasOptions() bool { + if o != nil && !IsNil(o.Options) { + return true + } + + return false +} + +// SetOptions gets a reference to the given map[string]string and assigns it to the Options field. +func (o *PredictionJobConfigBigquerySource) SetOptions(v map[string]string) { + o.Options = &v +} + +func (o PredictionJobConfigBigquerySource) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigBigquerySource) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Table) { + toSerialize["table"] = o.Table + } + if !IsNil(o.Features) { + toSerialize["features"] = o.Features + } + if !IsNil(o.Options) { + toSerialize["options"] = o.Options + } + return toSerialize, nil +} + +type NullablePredictionJobConfigBigquerySource struct { + value *PredictionJobConfigBigquerySource + isSet bool +} + +func (v NullablePredictionJobConfigBigquerySource) Get() *PredictionJobConfigBigquerySource { + return v.value +} + +func (v *NullablePredictionJobConfigBigquerySource) Set(val *PredictionJobConfigBigquerySource) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigBigquerySource) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigBigquerySource) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigBigquerySource(val *PredictionJobConfigBigquerySource) *NullablePredictionJobConfigBigquerySource { + return &NullablePredictionJobConfigBigquerySource{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigBigquerySource) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigBigquerySource) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config_gcs_sink.go b/api/client/model_prediction_job_config_gcs_sink.go index f946fd875..b36e85bfd 100644 --- a/api/client/model_prediction_job_config_gcs_sink.go +++ b/api/client/model_prediction_job_config_gcs_sink.go @@ -1,17 +1,272 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigGcsSink type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigGcsSink{} + +// PredictionJobConfigGcsSink struct for PredictionJobConfigGcsSink type PredictionJobConfigGcsSink struct { - Format *FileFormat `json:"format,omitempty"` - Uri string `json:"uri,omitempty"` - ResultColumn string `json:"result_column,omitempty"` - SaveMode *SaveMode `json:"save_mode,omitempty"` - Options map[string]string `json:"options,omitempty"` + Format *FileFormat `json:"format,omitempty"` + Uri *string `json:"uri,omitempty"` + ResultColumn *string `json:"result_column,omitempty"` + SaveMode *SaveMode `json:"save_mode,omitempty"` + Options *map[string]string `json:"options,omitempty"` +} + +// NewPredictionJobConfigGcsSink instantiates a new PredictionJobConfigGcsSink object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigGcsSink() *PredictionJobConfigGcsSink { + this := PredictionJobConfigGcsSink{} + var format FileFormat = FILEFORMAT_INVALID_FILE_FORMAT + this.Format = &format + return &this +} + +// NewPredictionJobConfigGcsSinkWithDefaults instantiates a new PredictionJobConfigGcsSink object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigGcsSinkWithDefaults() *PredictionJobConfigGcsSink { + this := PredictionJobConfigGcsSink{} + var format FileFormat = FILEFORMAT_INVALID_FILE_FORMAT + this.Format = &format + return &this +} + +// GetFormat returns the Format field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSink) GetFormat() FileFormat { + if o == nil || IsNil(o.Format) { + var ret FileFormat + return ret + } + return *o.Format +} + +// GetFormatOk returns a tuple with the Format field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSink) GetFormatOk() (*FileFormat, bool) { + if o == nil || IsNil(o.Format) { + return nil, false + } + return o.Format, true +} + +// HasFormat returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSink) HasFormat() bool { + if o != nil && !IsNil(o.Format) { + return true + } + + return false +} + +// SetFormat gets a reference to the given FileFormat and assigns it to the Format field. +func (o *PredictionJobConfigGcsSink) SetFormat(v FileFormat) { + o.Format = &v +} + +// GetUri returns the Uri field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSink) GetUri() string { + if o == nil || IsNil(o.Uri) { + var ret string + return ret + } + return *o.Uri +} + +// GetUriOk returns a tuple with the Uri field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSink) GetUriOk() (*string, bool) { + if o == nil || IsNil(o.Uri) { + return nil, false + } + return o.Uri, true +} + +// HasUri returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSink) HasUri() bool { + if o != nil && !IsNil(o.Uri) { + return true + } + + return false +} + +// SetUri gets a reference to the given string and assigns it to the Uri field. +func (o *PredictionJobConfigGcsSink) SetUri(v string) { + o.Uri = &v +} + +// GetResultColumn returns the ResultColumn field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSink) GetResultColumn() string { + if o == nil || IsNil(o.ResultColumn) { + var ret string + return ret + } + return *o.ResultColumn +} + +// GetResultColumnOk returns a tuple with the ResultColumn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSink) GetResultColumnOk() (*string, bool) { + if o == nil || IsNil(o.ResultColumn) { + return nil, false + } + return o.ResultColumn, true +} + +// HasResultColumn returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSink) HasResultColumn() bool { + if o != nil && !IsNil(o.ResultColumn) { + return true + } + + return false +} + +// SetResultColumn gets a reference to the given string and assigns it to the ResultColumn field. +func (o *PredictionJobConfigGcsSink) SetResultColumn(v string) { + o.ResultColumn = &v +} + +// GetSaveMode returns the SaveMode field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSink) GetSaveMode() SaveMode { + if o == nil || IsNil(o.SaveMode) { + var ret SaveMode + return ret + } + return *o.SaveMode +} + +// GetSaveModeOk returns a tuple with the SaveMode field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSink) GetSaveModeOk() (*SaveMode, bool) { + if o == nil || IsNil(o.SaveMode) { + return nil, false + } + return o.SaveMode, true +} + +// HasSaveMode returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSink) HasSaveMode() bool { + if o != nil && !IsNil(o.SaveMode) { + return true + } + + return false +} + +// SetSaveMode gets a reference to the given SaveMode and assigns it to the SaveMode field. +func (o *PredictionJobConfigGcsSink) SetSaveMode(v SaveMode) { + o.SaveMode = &v +} + +// GetOptions returns the Options field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSink) GetOptions() map[string]string { + if o == nil || IsNil(o.Options) { + var ret map[string]string + return ret + } + return *o.Options +} + +// GetOptionsOk returns a tuple with the Options field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSink) GetOptionsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Options) { + return nil, false + } + return o.Options, true +} + +// HasOptions returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSink) HasOptions() bool { + if o != nil && !IsNil(o.Options) { + return true + } + + return false +} + +// SetOptions gets a reference to the given map[string]string and assigns it to the Options field. +func (o *PredictionJobConfigGcsSink) SetOptions(v map[string]string) { + o.Options = &v +} + +func (o PredictionJobConfigGcsSink) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigGcsSink) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Format) { + toSerialize["format"] = o.Format + } + if !IsNil(o.Uri) { + toSerialize["uri"] = o.Uri + } + if !IsNil(o.ResultColumn) { + toSerialize["result_column"] = o.ResultColumn + } + if !IsNil(o.SaveMode) { + toSerialize["save_mode"] = o.SaveMode + } + if !IsNil(o.Options) { + toSerialize["options"] = o.Options + } + return toSerialize, nil +} + +type NullablePredictionJobConfigGcsSink struct { + value *PredictionJobConfigGcsSink + isSet bool +} + +func (v NullablePredictionJobConfigGcsSink) Get() *PredictionJobConfigGcsSink { + return v.value +} + +func (v *NullablePredictionJobConfigGcsSink) Set(val *PredictionJobConfigGcsSink) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigGcsSink) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigGcsSink) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigGcsSink(val *PredictionJobConfigGcsSink) *NullablePredictionJobConfigGcsSink { + return &NullablePredictionJobConfigGcsSink{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigGcsSink) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigGcsSink) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config_gcs_source.go b/api/client/model_prediction_job_config_gcs_source.go index 5e970ad16..87c5e5614 100644 --- a/api/client/model_prediction_job_config_gcs_source.go +++ b/api/client/model_prediction_job_config_gcs_source.go @@ -1,16 +1,236 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigGcsSource type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigGcsSource{} + +// PredictionJobConfigGcsSource struct for PredictionJobConfigGcsSource type PredictionJobConfigGcsSource struct { - Format *FileFormat `json:"format,omitempty"` - Uri string `json:"uri,omitempty"` - Features []string `json:"features,omitempty"` - Options map[string]string `json:"options,omitempty"` + Format *FileFormat `json:"format,omitempty"` + Uri *string `json:"uri,omitempty"` + Features []string `json:"features,omitempty"` + Options *map[string]string `json:"options,omitempty"` +} + +// NewPredictionJobConfigGcsSource instantiates a new PredictionJobConfigGcsSource object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigGcsSource() *PredictionJobConfigGcsSource { + this := PredictionJobConfigGcsSource{} + var format FileFormat = FILEFORMAT_INVALID_FILE_FORMAT + this.Format = &format + return &this +} + +// NewPredictionJobConfigGcsSourceWithDefaults instantiates a new PredictionJobConfigGcsSource object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigGcsSourceWithDefaults() *PredictionJobConfigGcsSource { + this := PredictionJobConfigGcsSource{} + var format FileFormat = FILEFORMAT_INVALID_FILE_FORMAT + this.Format = &format + return &this +} + +// GetFormat returns the Format field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSource) GetFormat() FileFormat { + if o == nil || IsNil(o.Format) { + var ret FileFormat + return ret + } + return *o.Format +} + +// GetFormatOk returns a tuple with the Format field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSource) GetFormatOk() (*FileFormat, bool) { + if o == nil || IsNil(o.Format) { + return nil, false + } + return o.Format, true +} + +// HasFormat returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSource) HasFormat() bool { + if o != nil && !IsNil(o.Format) { + return true + } + + return false +} + +// SetFormat gets a reference to the given FileFormat and assigns it to the Format field. +func (o *PredictionJobConfigGcsSource) SetFormat(v FileFormat) { + o.Format = &v +} + +// GetUri returns the Uri field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSource) GetUri() string { + if o == nil || IsNil(o.Uri) { + var ret string + return ret + } + return *o.Uri +} + +// GetUriOk returns a tuple with the Uri field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSource) GetUriOk() (*string, bool) { + if o == nil || IsNil(o.Uri) { + return nil, false + } + return o.Uri, true +} + +// HasUri returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSource) HasUri() bool { + if o != nil && !IsNil(o.Uri) { + return true + } + + return false +} + +// SetUri gets a reference to the given string and assigns it to the Uri field. +func (o *PredictionJobConfigGcsSource) SetUri(v string) { + o.Uri = &v +} + +// GetFeatures returns the Features field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSource) GetFeatures() []string { + if o == nil || IsNil(o.Features) { + var ret []string + return ret + } + return o.Features +} + +// GetFeaturesOk returns a tuple with the Features field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSource) GetFeaturesOk() ([]string, bool) { + if o == nil || IsNil(o.Features) { + return nil, false + } + return o.Features, true +} + +// HasFeatures returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSource) HasFeatures() bool { + if o != nil && !IsNil(o.Features) { + return true + } + + return false +} + +// SetFeatures gets a reference to the given []string and assigns it to the Features field. +func (o *PredictionJobConfigGcsSource) SetFeatures(v []string) { + o.Features = v +} + +// GetOptions returns the Options field value if set, zero value otherwise. +func (o *PredictionJobConfigGcsSource) GetOptions() map[string]string { + if o == nil || IsNil(o.Options) { + var ret map[string]string + return ret + } + return *o.Options +} + +// GetOptionsOk returns a tuple with the Options field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigGcsSource) GetOptionsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Options) { + return nil, false + } + return o.Options, true +} + +// HasOptions returns a boolean if a field has been set. +func (o *PredictionJobConfigGcsSource) HasOptions() bool { + if o != nil && !IsNil(o.Options) { + return true + } + + return false +} + +// SetOptions gets a reference to the given map[string]string and assigns it to the Options field. +func (o *PredictionJobConfigGcsSource) SetOptions(v map[string]string) { + o.Options = &v +} + +func (o PredictionJobConfigGcsSource) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigGcsSource) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Format) { + toSerialize["format"] = o.Format + } + if !IsNil(o.Uri) { + toSerialize["uri"] = o.Uri + } + if !IsNil(o.Features) { + toSerialize["features"] = o.Features + } + if !IsNil(o.Options) { + toSerialize["options"] = o.Options + } + return toSerialize, nil +} + +type NullablePredictionJobConfigGcsSource struct { + value *PredictionJobConfigGcsSource + isSet bool +} + +func (v NullablePredictionJobConfigGcsSource) Get() *PredictionJobConfigGcsSource { + return v.value +} + +func (v *NullablePredictionJobConfigGcsSource) Set(val *PredictionJobConfigGcsSource) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigGcsSource) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigGcsSource) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigGcsSource(val *PredictionJobConfigGcsSource) *NullablePredictionJobConfigGcsSource { + return &NullablePredictionJobConfigGcsSource{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigGcsSource) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigGcsSource) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config_model.go b/api/client/model_prediction_job_config_model.go index c8bcfec56..4d1a63e06 100644 --- a/api/client/model_prediction_job_config_model.go +++ b/api/client/model_prediction_job_config_model.go @@ -1,16 +1,236 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigModel type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigModel{} + +// PredictionJobConfigModel struct for PredictionJobConfigModel type PredictionJobConfigModel struct { - Type_ string `json:"type,omitempty"` - Uri string `json:"uri,omitempty"` + Type *string `json:"type,omitempty"` + Uri *string `json:"uri,omitempty"` Result *PredictionJobConfigModelResult `json:"result,omitempty"` - Options map[string]string `json:"options,omitempty"` + Options *map[string]string `json:"options,omitempty"` +} + +// NewPredictionJobConfigModel instantiates a new PredictionJobConfigModel object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigModel() *PredictionJobConfigModel { + this := PredictionJobConfigModel{} + var type_ string = "INVALID_MODEL_TYPE" + this.Type = &type_ + return &this +} + +// NewPredictionJobConfigModelWithDefaults instantiates a new PredictionJobConfigModel object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigModelWithDefaults() *PredictionJobConfigModel { + this := PredictionJobConfigModel{} + var type_ string = "INVALID_MODEL_TYPE" + this.Type = &type_ + return &this +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *PredictionJobConfigModel) GetType() string { + if o == nil || IsNil(o.Type) { + var ret string + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModel) GetTypeOk() (*string, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *PredictionJobConfigModel) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given string and assigns it to the Type field. +func (o *PredictionJobConfigModel) SetType(v string) { + o.Type = &v +} + +// GetUri returns the Uri field value if set, zero value otherwise. +func (o *PredictionJobConfigModel) GetUri() string { + if o == nil || IsNil(o.Uri) { + var ret string + return ret + } + return *o.Uri +} + +// GetUriOk returns a tuple with the Uri field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModel) GetUriOk() (*string, bool) { + if o == nil || IsNil(o.Uri) { + return nil, false + } + return o.Uri, true +} + +// HasUri returns a boolean if a field has been set. +func (o *PredictionJobConfigModel) HasUri() bool { + if o != nil && !IsNil(o.Uri) { + return true + } + + return false +} + +// SetUri gets a reference to the given string and assigns it to the Uri field. +func (o *PredictionJobConfigModel) SetUri(v string) { + o.Uri = &v +} + +// GetResult returns the Result field value if set, zero value otherwise. +func (o *PredictionJobConfigModel) GetResult() PredictionJobConfigModelResult { + if o == nil || IsNil(o.Result) { + var ret PredictionJobConfigModelResult + return ret + } + return *o.Result +} + +// GetResultOk returns a tuple with the Result field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModel) GetResultOk() (*PredictionJobConfigModelResult, bool) { + if o == nil || IsNil(o.Result) { + return nil, false + } + return o.Result, true +} + +// HasResult returns a boolean if a field has been set. +func (o *PredictionJobConfigModel) HasResult() bool { + if o != nil && !IsNil(o.Result) { + return true + } + + return false +} + +// SetResult gets a reference to the given PredictionJobConfigModelResult and assigns it to the Result field. +func (o *PredictionJobConfigModel) SetResult(v PredictionJobConfigModelResult) { + o.Result = &v +} + +// GetOptions returns the Options field value if set, zero value otherwise. +func (o *PredictionJobConfigModel) GetOptions() map[string]string { + if o == nil || IsNil(o.Options) { + var ret map[string]string + return ret + } + return *o.Options +} + +// GetOptionsOk returns a tuple with the Options field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModel) GetOptionsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Options) { + return nil, false + } + return o.Options, true +} + +// HasOptions returns a boolean if a field has been set. +func (o *PredictionJobConfigModel) HasOptions() bool { + if o != nil && !IsNil(o.Options) { + return true + } + + return false +} + +// SetOptions gets a reference to the given map[string]string and assigns it to the Options field. +func (o *PredictionJobConfigModel) SetOptions(v map[string]string) { + o.Options = &v +} + +func (o PredictionJobConfigModel) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigModel) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.Uri) { + toSerialize["uri"] = o.Uri + } + if !IsNil(o.Result) { + toSerialize["result"] = o.Result + } + if !IsNil(o.Options) { + toSerialize["options"] = o.Options + } + return toSerialize, nil +} + +type NullablePredictionJobConfigModel struct { + value *PredictionJobConfigModel + isSet bool +} + +func (v NullablePredictionJobConfigModel) Get() *PredictionJobConfigModel { + return v.value +} + +func (v *NullablePredictionJobConfigModel) Set(val *PredictionJobConfigModel) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigModel) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigModel) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigModel(val *PredictionJobConfigModel) *NullablePredictionJobConfigModel { + return &NullablePredictionJobConfigModel{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigModel) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigModel) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_job_config_model_result.go b/api/client/model_prediction_job_config_model_result.go index f68eaf3b0..5c305044a 100644 --- a/api/client/model_prediction_job_config_model_result.go +++ b/api/client/model_prediction_job_config_model_result.go @@ -1,14 +1,168 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobConfigModelResult type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobConfigModelResult{} + +// PredictionJobConfigModelResult struct for PredictionJobConfigModelResult type PredictionJobConfigModelResult struct { - Type_ *ResultType `json:"type,omitempty"` + Type *ResultType `json:"type,omitempty"` ItemType *ResultType `json:"item_type,omitempty"` } + +// NewPredictionJobConfigModelResult instantiates a new PredictionJobConfigModelResult object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobConfigModelResult() *PredictionJobConfigModelResult { + this := PredictionJobConfigModelResult{} + var type_ ResultType = RESULTTYPE_DOUBLE + this.Type = &type_ + var itemType ResultType = RESULTTYPE_DOUBLE + this.ItemType = &itemType + return &this +} + +// NewPredictionJobConfigModelResultWithDefaults instantiates a new PredictionJobConfigModelResult object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobConfigModelResultWithDefaults() *PredictionJobConfigModelResult { + this := PredictionJobConfigModelResult{} + var type_ ResultType = RESULTTYPE_DOUBLE + this.Type = &type_ + var itemType ResultType = RESULTTYPE_DOUBLE + this.ItemType = &itemType + return &this +} + +// GetType returns the Type field value if set, zero value otherwise. +func (o *PredictionJobConfigModelResult) GetType() ResultType { + if o == nil || IsNil(o.Type) { + var ret ResultType + return ret + } + return *o.Type +} + +// GetTypeOk returns a tuple with the Type field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModelResult) GetTypeOk() (*ResultType, bool) { + if o == nil || IsNil(o.Type) { + return nil, false + } + return o.Type, true +} + +// HasType returns a boolean if a field has been set. +func (o *PredictionJobConfigModelResult) HasType() bool { + if o != nil && !IsNil(o.Type) { + return true + } + + return false +} + +// SetType gets a reference to the given ResultType and assigns it to the Type field. +func (o *PredictionJobConfigModelResult) SetType(v ResultType) { + o.Type = &v +} + +// GetItemType returns the ItemType field value if set, zero value otherwise. +func (o *PredictionJobConfigModelResult) GetItemType() ResultType { + if o == nil || IsNil(o.ItemType) { + var ret ResultType + return ret + } + return *o.ItemType +} + +// GetItemTypeOk returns a tuple with the ItemType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobConfigModelResult) GetItemTypeOk() (*ResultType, bool) { + if o == nil || IsNil(o.ItemType) { + return nil, false + } + return o.ItemType, true +} + +// HasItemType returns a boolean if a field has been set. +func (o *PredictionJobConfigModelResult) HasItemType() bool { + if o != nil && !IsNil(o.ItemType) { + return true + } + + return false +} + +// SetItemType gets a reference to the given ResultType and assigns it to the ItemType field. +func (o *PredictionJobConfigModelResult) SetItemType(v ResultType) { + o.ItemType = &v +} + +func (o PredictionJobConfigModelResult) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobConfigModelResult) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Type) { + toSerialize["type"] = o.Type + } + if !IsNil(o.ItemType) { + toSerialize["item_type"] = o.ItemType + } + return toSerialize, nil +} + +type NullablePredictionJobConfigModelResult struct { + value *PredictionJobConfigModelResult + isSet bool +} + +func (v NullablePredictionJobConfigModelResult) Get() *PredictionJobConfigModelResult { + return v.value +} + +func (v *NullablePredictionJobConfigModelResult) Set(val *PredictionJobConfigModelResult) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobConfigModelResult) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobConfigModelResult) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobConfigModelResult(val *PredictionJobConfigModelResult) *NullablePredictionJobConfigModelResult { + return &NullablePredictionJobConfigModelResult{value: val, isSet: true} +} + +func (v NullablePredictionJobConfigModelResult) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobConfigModelResult) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_prediction_job_resource_request.go b/api/client/model_prediction_job_resource_request.go index 133aedb5f..a986993f3 100644 --- a/api/client/model_prediction_job_resource_request.go +++ b/api/client/model_prediction_job_resource_request.go @@ -1,17 +1,268 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the PredictionJobResourceRequest type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionJobResourceRequest{} + +// PredictionJobResourceRequest struct for PredictionJobResourceRequest type PredictionJobResourceRequest struct { - DriverCpuRequest string `json:"driver_cpu_request,omitempty"` - DriverMemoryRequest string `json:"driver_memory_request,omitempty"` - ExecutorCpuRequest string `json:"executor_cpu_request,omitempty"` - ExecutorMemoryRequest string `json:"executor_memory_request,omitempty"` - ExecutorReplica int32 `json:"executor_replica,omitempty"` + DriverCpuRequest *string `json:"driver_cpu_request,omitempty"` + DriverMemoryRequest *string `json:"driver_memory_request,omitempty"` + ExecutorCpuRequest *string `json:"executor_cpu_request,omitempty"` + ExecutorMemoryRequest *string `json:"executor_memory_request,omitempty"` + ExecutorReplica *int32 `json:"executor_replica,omitempty"` +} + +// NewPredictionJobResourceRequest instantiates a new PredictionJobResourceRequest object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionJobResourceRequest() *PredictionJobResourceRequest { + this := PredictionJobResourceRequest{} + return &this +} + +// NewPredictionJobResourceRequestWithDefaults instantiates a new PredictionJobResourceRequest object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionJobResourceRequestWithDefaults() *PredictionJobResourceRequest { + this := PredictionJobResourceRequest{} + return &this +} + +// GetDriverCpuRequest returns the DriverCpuRequest field value if set, zero value otherwise. +func (o *PredictionJobResourceRequest) GetDriverCpuRequest() string { + if o == nil || IsNil(o.DriverCpuRequest) { + var ret string + return ret + } + return *o.DriverCpuRequest +} + +// GetDriverCpuRequestOk returns a tuple with the DriverCpuRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobResourceRequest) GetDriverCpuRequestOk() (*string, bool) { + if o == nil || IsNil(o.DriverCpuRequest) { + return nil, false + } + return o.DriverCpuRequest, true +} + +// HasDriverCpuRequest returns a boolean if a field has been set. +func (o *PredictionJobResourceRequest) HasDriverCpuRequest() bool { + if o != nil && !IsNil(o.DriverCpuRequest) { + return true + } + + return false +} + +// SetDriverCpuRequest gets a reference to the given string and assigns it to the DriverCpuRequest field. +func (o *PredictionJobResourceRequest) SetDriverCpuRequest(v string) { + o.DriverCpuRequest = &v +} + +// GetDriverMemoryRequest returns the DriverMemoryRequest field value if set, zero value otherwise. +func (o *PredictionJobResourceRequest) GetDriverMemoryRequest() string { + if o == nil || IsNil(o.DriverMemoryRequest) { + var ret string + return ret + } + return *o.DriverMemoryRequest +} + +// GetDriverMemoryRequestOk returns a tuple with the DriverMemoryRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobResourceRequest) GetDriverMemoryRequestOk() (*string, bool) { + if o == nil || IsNil(o.DriverMemoryRequest) { + return nil, false + } + return o.DriverMemoryRequest, true +} + +// HasDriverMemoryRequest returns a boolean if a field has been set. +func (o *PredictionJobResourceRequest) HasDriverMemoryRequest() bool { + if o != nil && !IsNil(o.DriverMemoryRequest) { + return true + } + + return false +} + +// SetDriverMemoryRequest gets a reference to the given string and assigns it to the DriverMemoryRequest field. +func (o *PredictionJobResourceRequest) SetDriverMemoryRequest(v string) { + o.DriverMemoryRequest = &v +} + +// GetExecutorCpuRequest returns the ExecutorCpuRequest field value if set, zero value otherwise. +func (o *PredictionJobResourceRequest) GetExecutorCpuRequest() string { + if o == nil || IsNil(o.ExecutorCpuRequest) { + var ret string + return ret + } + return *o.ExecutorCpuRequest +} + +// GetExecutorCpuRequestOk returns a tuple with the ExecutorCpuRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobResourceRequest) GetExecutorCpuRequestOk() (*string, bool) { + if o == nil || IsNil(o.ExecutorCpuRequest) { + return nil, false + } + return o.ExecutorCpuRequest, true +} + +// HasExecutorCpuRequest returns a boolean if a field has been set. +func (o *PredictionJobResourceRequest) HasExecutorCpuRequest() bool { + if o != nil && !IsNil(o.ExecutorCpuRequest) { + return true + } + + return false +} + +// SetExecutorCpuRequest gets a reference to the given string and assigns it to the ExecutorCpuRequest field. +func (o *PredictionJobResourceRequest) SetExecutorCpuRequest(v string) { + o.ExecutorCpuRequest = &v +} + +// GetExecutorMemoryRequest returns the ExecutorMemoryRequest field value if set, zero value otherwise. +func (o *PredictionJobResourceRequest) GetExecutorMemoryRequest() string { + if o == nil || IsNil(o.ExecutorMemoryRequest) { + var ret string + return ret + } + return *o.ExecutorMemoryRequest +} + +// GetExecutorMemoryRequestOk returns a tuple with the ExecutorMemoryRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobResourceRequest) GetExecutorMemoryRequestOk() (*string, bool) { + if o == nil || IsNil(o.ExecutorMemoryRequest) { + return nil, false + } + return o.ExecutorMemoryRequest, true +} + +// HasExecutorMemoryRequest returns a boolean if a field has been set. +func (o *PredictionJobResourceRequest) HasExecutorMemoryRequest() bool { + if o != nil && !IsNil(o.ExecutorMemoryRequest) { + return true + } + + return false +} + +// SetExecutorMemoryRequest gets a reference to the given string and assigns it to the ExecutorMemoryRequest field. +func (o *PredictionJobResourceRequest) SetExecutorMemoryRequest(v string) { + o.ExecutorMemoryRequest = &v +} + +// GetExecutorReplica returns the ExecutorReplica field value if set, zero value otherwise. +func (o *PredictionJobResourceRequest) GetExecutorReplica() int32 { + if o == nil || IsNil(o.ExecutorReplica) { + var ret int32 + return ret + } + return *o.ExecutorReplica +} + +// GetExecutorReplicaOk returns a tuple with the ExecutorReplica field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionJobResourceRequest) GetExecutorReplicaOk() (*int32, bool) { + if o == nil || IsNil(o.ExecutorReplica) { + return nil, false + } + return o.ExecutorReplica, true +} + +// HasExecutorReplica returns a boolean if a field has been set. +func (o *PredictionJobResourceRequest) HasExecutorReplica() bool { + if o != nil && !IsNil(o.ExecutorReplica) { + return true + } + + return false +} + +// SetExecutorReplica gets a reference to the given int32 and assigns it to the ExecutorReplica field. +func (o *PredictionJobResourceRequest) SetExecutorReplica(v int32) { + o.ExecutorReplica = &v +} + +func (o PredictionJobResourceRequest) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionJobResourceRequest) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.DriverCpuRequest) { + toSerialize["driver_cpu_request"] = o.DriverCpuRequest + } + if !IsNil(o.DriverMemoryRequest) { + toSerialize["driver_memory_request"] = o.DriverMemoryRequest + } + if !IsNil(o.ExecutorCpuRequest) { + toSerialize["executor_cpu_request"] = o.ExecutorCpuRequest + } + if !IsNil(o.ExecutorMemoryRequest) { + toSerialize["executor_memory_request"] = o.ExecutorMemoryRequest + } + if !IsNil(o.ExecutorReplica) { + toSerialize["executor_replica"] = o.ExecutorReplica + } + return toSerialize, nil +} + +type NullablePredictionJobResourceRequest struct { + value *PredictionJobResourceRequest + isSet bool +} + +func (v NullablePredictionJobResourceRequest) Get() *PredictionJobResourceRequest { + return v.value +} + +func (v *NullablePredictionJobResourceRequest) Set(val *PredictionJobResourceRequest) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionJobResourceRequest) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionJobResourceRequest) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionJobResourceRequest(val *PredictionJobResourceRequest) *NullablePredictionJobResourceRequest { + return &NullablePredictionJobResourceRequest{value: val, isSet: true} +} + +func (v NullablePredictionJobResourceRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionJobResourceRequest) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_prediction_logger_config.go b/api/client/model_prediction_logger_config.go index fb3763144..26219db29 100644 --- a/api/client/model_prediction_logger_config.go +++ b/api/client/model_prediction_logger_config.go @@ -1,15 +1,225 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// checks if the PredictionLoggerConfig type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &PredictionLoggerConfig{} + +// PredictionLoggerConfig struct for PredictionLoggerConfig type PredictionLoggerConfig struct { - Enabled bool `json:"enabled,omitempty"` - RawFeaturesTable string `json:"raw_features_table,omitempty"` - EntitiesTable string `json:"entities_table,omitempty"` + Enabled bool `json:"enabled"` + RawFeaturesTable *string `json:"raw_features_table,omitempty"` + EntitiesTable *string `json:"entities_table,omitempty"` +} + +type _PredictionLoggerConfig PredictionLoggerConfig + +// NewPredictionLoggerConfig instantiates a new PredictionLoggerConfig object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPredictionLoggerConfig(enabled bool) *PredictionLoggerConfig { + this := PredictionLoggerConfig{} + this.Enabled = enabled + return &this +} + +// NewPredictionLoggerConfigWithDefaults instantiates a new PredictionLoggerConfig object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPredictionLoggerConfigWithDefaults() *PredictionLoggerConfig { + this := PredictionLoggerConfig{} + return &this +} + +// GetEnabled returns the Enabled field value +func (o *PredictionLoggerConfig) GetEnabled() bool { + if o == nil { + var ret bool + return ret + } + + return o.Enabled +} + +// GetEnabledOk returns a tuple with the Enabled field value +// and a boolean to check if the value has been set. +func (o *PredictionLoggerConfig) GetEnabledOk() (*bool, bool) { + if o == nil { + return nil, false + } + return &o.Enabled, true +} + +// SetEnabled sets field value +func (o *PredictionLoggerConfig) SetEnabled(v bool) { + o.Enabled = v +} + +// GetRawFeaturesTable returns the RawFeaturesTable field value if set, zero value otherwise. +func (o *PredictionLoggerConfig) GetRawFeaturesTable() string { + if o == nil || IsNil(o.RawFeaturesTable) { + var ret string + return ret + } + return *o.RawFeaturesTable +} + +// GetRawFeaturesTableOk returns a tuple with the RawFeaturesTable field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionLoggerConfig) GetRawFeaturesTableOk() (*string, bool) { + if o == nil || IsNil(o.RawFeaturesTable) { + return nil, false + } + return o.RawFeaturesTable, true +} + +// HasRawFeaturesTable returns a boolean if a field has been set. +func (o *PredictionLoggerConfig) HasRawFeaturesTable() bool { + if o != nil && !IsNil(o.RawFeaturesTable) { + return true + } + + return false +} + +// SetRawFeaturesTable gets a reference to the given string and assigns it to the RawFeaturesTable field. +func (o *PredictionLoggerConfig) SetRawFeaturesTable(v string) { + o.RawFeaturesTable = &v +} + +// GetEntitiesTable returns the EntitiesTable field value if set, zero value otherwise. +func (o *PredictionLoggerConfig) GetEntitiesTable() string { + if o == nil || IsNil(o.EntitiesTable) { + var ret string + return ret + } + return *o.EntitiesTable +} + +// GetEntitiesTableOk returns a tuple with the EntitiesTable field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *PredictionLoggerConfig) GetEntitiesTableOk() (*string, bool) { + if o == nil || IsNil(o.EntitiesTable) { + return nil, false + } + return o.EntitiesTable, true +} + +// HasEntitiesTable returns a boolean if a field has been set. +func (o *PredictionLoggerConfig) HasEntitiesTable() bool { + if o != nil && !IsNil(o.EntitiesTable) { + return true + } + + return false +} + +// SetEntitiesTable gets a reference to the given string and assigns it to the EntitiesTable field. +func (o *PredictionLoggerConfig) SetEntitiesTable(v string) { + o.EntitiesTable = &v +} + +func (o PredictionLoggerConfig) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o PredictionLoggerConfig) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["enabled"] = o.Enabled + if !IsNil(o.RawFeaturesTable) { + toSerialize["raw_features_table"] = o.RawFeaturesTable + } + if !IsNil(o.EntitiesTable) { + toSerialize["entities_table"] = o.EntitiesTable + } + return toSerialize, nil +} + +func (o *PredictionLoggerConfig) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "enabled", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varPredictionLoggerConfig := _PredictionLoggerConfig{} + + err = json.Unmarshal(bytes, &varPredictionLoggerConfig) + + if err != nil { + return err + } + + *o = PredictionLoggerConfig(varPredictionLoggerConfig) + + return err +} + +type NullablePredictionLoggerConfig struct { + value *PredictionLoggerConfig + isSet bool +} + +func (v NullablePredictionLoggerConfig) Get() *PredictionLoggerConfig { + return v.value +} + +func (v *NullablePredictionLoggerConfig) Set(val *PredictionLoggerConfig) { + v.value = val + v.isSet = true +} + +func (v NullablePredictionLoggerConfig) IsSet() bool { + return v.isSet +} + +func (v *NullablePredictionLoggerConfig) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePredictionLoggerConfig(val *PredictionLoggerConfig) *NullablePredictionLoggerConfig { + return &NullablePredictionLoggerConfig{value: val, isSet: true} +} + +func (v NullablePredictionLoggerConfig) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePredictionLoggerConfig) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_project.go b/api/client/model_project.go index a7bb64082..77f866c1d 100644 --- a/api/client/model_project.go +++ b/api/client/model_project.go @@ -1,26 +1,470 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" + "fmt" "time" ) +// checks if the Project type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Project{} + +// Project struct for Project type Project struct { - Id int32 `json:"id,omitempty"` - Name string `json:"name"` - MlflowTrackingUrl string `json:"mlflow_tracking_url,omitempty"` - Administrators []string `json:"administrators,omitempty"` - Readers []string `json:"readers,omitempty"` - Team string `json:"team,omitempty"` - Stream string `json:"stream,omitempty"` - Labels []Label `json:"labels,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + Id int32 `json:"id"` + Name string `json:"name"` + MlflowTrackingUrl *string `json:"mlflow_tracking_url,omitempty"` + Administrators []string `json:"administrators,omitempty"` + Readers []string `json:"readers,omitempty"` + Team *string `json:"team,omitempty"` + Stream *string `json:"stream,omitempty"` + Labels []Label `json:"labels,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +type _Project Project + +// NewProject instantiates a new Project object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewProject(id int32, name string) *Project { + this := Project{} + this.Id = id + this.Name = name + return &this +} + +// NewProjectWithDefaults instantiates a new Project object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewProjectWithDefaults() *Project { + this := Project{} + return &this +} + +// GetId returns the Id field value +func (o *Project) GetId() int32 { + if o == nil { + var ret int32 + return ret + } + + return o.Id +} + +// GetIdOk returns a tuple with the Id field value +// and a boolean to check if the value has been set. +func (o *Project) GetIdOk() (*int32, bool) { + if o == nil { + return nil, false + } + return &o.Id, true +} + +// SetId sets field value +func (o *Project) SetId(v int32) { + o.Id = v +} + +// GetName returns the Name field value +func (o *Project) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *Project) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *Project) SetName(v string) { + o.Name = v +} + +// GetMlflowTrackingUrl returns the MlflowTrackingUrl field value if set, zero value otherwise. +func (o *Project) GetMlflowTrackingUrl() string { + if o == nil || IsNil(o.MlflowTrackingUrl) { + var ret string + return ret + } + return *o.MlflowTrackingUrl +} + +// GetMlflowTrackingUrlOk returns a tuple with the MlflowTrackingUrl field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetMlflowTrackingUrlOk() (*string, bool) { + if o == nil || IsNil(o.MlflowTrackingUrl) { + return nil, false + } + return o.MlflowTrackingUrl, true +} + +// HasMlflowTrackingUrl returns a boolean if a field has been set. +func (o *Project) HasMlflowTrackingUrl() bool { + if o != nil && !IsNil(o.MlflowTrackingUrl) { + return true + } + + return false +} + +// SetMlflowTrackingUrl gets a reference to the given string and assigns it to the MlflowTrackingUrl field. +func (o *Project) SetMlflowTrackingUrl(v string) { + o.MlflowTrackingUrl = &v +} + +// GetAdministrators returns the Administrators field value if set, zero value otherwise. +func (o *Project) GetAdministrators() []string { + if o == nil || IsNil(o.Administrators) { + var ret []string + return ret + } + return o.Administrators +} + +// GetAdministratorsOk returns a tuple with the Administrators field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetAdministratorsOk() ([]string, bool) { + if o == nil || IsNil(o.Administrators) { + return nil, false + } + return o.Administrators, true +} + +// HasAdministrators returns a boolean if a field has been set. +func (o *Project) HasAdministrators() bool { + if o != nil && !IsNil(o.Administrators) { + return true + } + + return false +} + +// SetAdministrators gets a reference to the given []string and assigns it to the Administrators field. +func (o *Project) SetAdministrators(v []string) { + o.Administrators = v +} + +// GetReaders returns the Readers field value if set, zero value otherwise. +func (o *Project) GetReaders() []string { + if o == nil || IsNil(o.Readers) { + var ret []string + return ret + } + return o.Readers +} + +// GetReadersOk returns a tuple with the Readers field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetReadersOk() ([]string, bool) { + if o == nil || IsNil(o.Readers) { + return nil, false + } + return o.Readers, true +} + +// HasReaders returns a boolean if a field has been set. +func (o *Project) HasReaders() bool { + if o != nil && !IsNil(o.Readers) { + return true + } + + return false +} + +// SetReaders gets a reference to the given []string and assigns it to the Readers field. +func (o *Project) SetReaders(v []string) { + o.Readers = v +} + +// GetTeam returns the Team field value if set, zero value otherwise. +func (o *Project) GetTeam() string { + if o == nil || IsNil(o.Team) { + var ret string + return ret + } + return *o.Team +} + +// GetTeamOk returns a tuple with the Team field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetTeamOk() (*string, bool) { + if o == nil || IsNil(o.Team) { + return nil, false + } + return o.Team, true +} + +// HasTeam returns a boolean if a field has been set. +func (o *Project) HasTeam() bool { + if o != nil && !IsNil(o.Team) { + return true + } + + return false +} + +// SetTeam gets a reference to the given string and assigns it to the Team field. +func (o *Project) SetTeam(v string) { + o.Team = &v +} + +// GetStream returns the Stream field value if set, zero value otherwise. +func (o *Project) GetStream() string { + if o == nil || IsNil(o.Stream) { + var ret string + return ret + } + return *o.Stream +} + +// GetStreamOk returns a tuple with the Stream field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetStreamOk() (*string, bool) { + if o == nil || IsNil(o.Stream) { + return nil, false + } + return o.Stream, true +} + +// HasStream returns a boolean if a field has been set. +func (o *Project) HasStream() bool { + if o != nil && !IsNil(o.Stream) { + return true + } + + return false +} + +// SetStream gets a reference to the given string and assigns it to the Stream field. +func (o *Project) SetStream(v string) { + o.Stream = &v +} + +// GetLabels returns the Labels field value if set, zero value otherwise. +func (o *Project) GetLabels() []Label { + if o == nil || IsNil(o.Labels) { + var ret []Label + return ret + } + return o.Labels +} + +// GetLabelsOk returns a tuple with the Labels field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetLabelsOk() ([]Label, bool) { + if o == nil || IsNil(o.Labels) { + return nil, false + } + return o.Labels, true +} + +// HasLabels returns a boolean if a field has been set. +func (o *Project) HasLabels() bool { + if o != nil && !IsNil(o.Labels) { + return true + } + + return false +} + +// SetLabels gets a reference to the given []Label and assigns it to the Labels field. +func (o *Project) SetLabels(v []Label) { + o.Labels = v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *Project) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *Project) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *Project) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *Project) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Project) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *Project) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *Project) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o Project) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Project) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["id"] = o.Id + toSerialize["name"] = o.Name + if !IsNil(o.MlflowTrackingUrl) { + toSerialize["mlflow_tracking_url"] = o.MlflowTrackingUrl + } + if !IsNil(o.Administrators) { + toSerialize["administrators"] = o.Administrators + } + if !IsNil(o.Readers) { + toSerialize["readers"] = o.Readers + } + if !IsNil(o.Team) { + toSerialize["team"] = o.Team + } + if !IsNil(o.Stream) { + toSerialize["stream"] = o.Stream + } + if !IsNil(o.Labels) { + toSerialize["labels"] = o.Labels + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +func (o *Project) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "id", + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varProject := _Project{} + + err = json.Unmarshal(bytes, &varProject) + + if err != nil { + return err + } + + *o = Project(varProject) + + return err +} + +type NullableProject struct { + value *Project + isSet bool +} + +func (v NullableProject) Get() *Project { + return v.value +} + +func (v *NullableProject) Set(val *Project) { + v.value = val + v.isSet = true +} + +func (v NullableProject) IsSet() bool { + return v.isSet +} + +func (v *NullableProject) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProject(val *Project) *NullableProject { + return &NullableProject{value: val, isSet: true} +} + +func (v NullableProject) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProject) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_protocol.go b/api/client/model_protocol.go index 46b867580..94aa01586 100644 --- a/api/client/model_protocol.go +++ b/api/client/model_protocol.go @@ -1,17 +1,110 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// Protocol the model 'Protocol' type Protocol string // List of Protocol const ( - HTTP_JSON_Protocol Protocol = "HTTP_JSON" - UPI_V1_Protocol Protocol = "UPI_V1" + PROTOCOL_HTTP_JSON Protocol = "HTTP_JSON" + PROTOCOL_UPI_V1 Protocol = "UPI_V1" ) + +// All allowed values of Protocol enum +var AllowedProtocolEnumValues = []Protocol{ + "HTTP_JSON", + "UPI_V1", +} + +func (v *Protocol) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := Protocol(value) + for _, existing := range AllowedProtocolEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid Protocol", value) +} + +// NewProtocolFromValue returns a pointer to a valid Protocol +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewProtocolFromValue(v string) (*Protocol, error) { + ev := Protocol(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for Protocol: valid values are %v", v, AllowedProtocolEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Protocol) IsValid() bool { + for _, existing := range AllowedProtocolEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to Protocol value +func (v Protocol) Ptr() *Protocol { + return &v +} + +type NullableProtocol struct { + value *Protocol + isSet bool +} + +func (v NullableProtocol) Get() *Protocol { + return v.value +} + +func (v *NullableProtocol) Set(val *Protocol) { + v.value = val + v.isSet = true +} + +func (v NullableProtocol) IsSet() bool { + return v.isSet +} + +func (v *NullableProtocol) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableProtocol(val *Protocol) *NullableProtocol { + return &NullableProtocol{value: val, isSet: true} +} + +func (v NullableProtocol) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableProtocol) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_ranking_output.go b/api/client/model_ranking_output.go new file mode 100644 index 000000000..93b947066 --- /dev/null +++ b/api/client/model_ranking_output.go @@ -0,0 +1,245 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// checks if the RankingOutput type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RankingOutput{} + +// RankingOutput struct for RankingOutput +type RankingOutput struct { + RankScoreColumn string `json:"rank_score_column"` + PredictionGroupIdColumn string `json:"prediction_group_id_column"` + RelevanceScoreColumn *string `json:"relevance_score_column,omitempty"` + OutputClass ModelPredictionOutputClass `json:"output_class"` +} + +type _RankingOutput RankingOutput + +// NewRankingOutput instantiates a new RankingOutput object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRankingOutput(rankScoreColumn string, predictionGroupIdColumn string, outputClass ModelPredictionOutputClass) *RankingOutput { + this := RankingOutput{} + this.RankScoreColumn = rankScoreColumn + this.PredictionGroupIdColumn = predictionGroupIdColumn + this.OutputClass = outputClass + return &this +} + +// NewRankingOutputWithDefaults instantiates a new RankingOutput object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRankingOutputWithDefaults() *RankingOutput { + this := RankingOutput{} + return &this +} + +// GetRankScoreColumn returns the RankScoreColumn field value +func (o *RankingOutput) GetRankScoreColumn() string { + if o == nil { + var ret string + return ret + } + + return o.RankScoreColumn +} + +// GetRankScoreColumnOk returns a tuple with the RankScoreColumn field value +// and a boolean to check if the value has been set. +func (o *RankingOutput) GetRankScoreColumnOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.RankScoreColumn, true +} + +// SetRankScoreColumn sets field value +func (o *RankingOutput) SetRankScoreColumn(v string) { + o.RankScoreColumn = v +} + +// GetPredictionGroupIdColumn returns the PredictionGroupIdColumn field value +func (o *RankingOutput) GetPredictionGroupIdColumn() string { + if o == nil { + var ret string + return ret + } + + return o.PredictionGroupIdColumn +} + +// GetPredictionGroupIdColumnOk returns a tuple with the PredictionGroupIdColumn field value +// and a boolean to check if the value has been set. +func (o *RankingOutput) GetPredictionGroupIdColumnOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PredictionGroupIdColumn, true +} + +// SetPredictionGroupIdColumn sets field value +func (o *RankingOutput) SetPredictionGroupIdColumn(v string) { + o.PredictionGroupIdColumn = v +} + +// GetRelevanceScoreColumn returns the RelevanceScoreColumn field value if set, zero value otherwise. +func (o *RankingOutput) GetRelevanceScoreColumn() string { + if o == nil || IsNil(o.RelevanceScoreColumn) { + var ret string + return ret + } + return *o.RelevanceScoreColumn +} + +// GetRelevanceScoreColumnOk returns a tuple with the RelevanceScoreColumn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RankingOutput) GetRelevanceScoreColumnOk() (*string, bool) { + if o == nil || IsNil(o.RelevanceScoreColumn) { + return nil, false + } + return o.RelevanceScoreColumn, true +} + +// HasRelevanceScoreColumn returns a boolean if a field has been set. +func (o *RankingOutput) HasRelevanceScoreColumn() bool { + if o != nil && !IsNil(o.RelevanceScoreColumn) { + return true + } + + return false +} + +// SetRelevanceScoreColumn gets a reference to the given string and assigns it to the RelevanceScoreColumn field. +func (o *RankingOutput) SetRelevanceScoreColumn(v string) { + o.RelevanceScoreColumn = &v +} + +// GetOutputClass returns the OutputClass field value +func (o *RankingOutput) GetOutputClass() ModelPredictionOutputClass { + if o == nil { + var ret ModelPredictionOutputClass + return ret + } + + return o.OutputClass +} + +// GetOutputClassOk returns a tuple with the OutputClass field value +// and a boolean to check if the value has been set. +func (o *RankingOutput) GetOutputClassOk() (*ModelPredictionOutputClass, bool) { + if o == nil { + return nil, false + } + return &o.OutputClass, true +} + +// SetOutputClass sets field value +func (o *RankingOutput) SetOutputClass(v ModelPredictionOutputClass) { + o.OutputClass = v +} + +func (o RankingOutput) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RankingOutput) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["rank_score_column"] = o.RankScoreColumn + toSerialize["prediction_group_id_column"] = o.PredictionGroupIdColumn + if !IsNil(o.RelevanceScoreColumn) { + toSerialize["relevance_score_column"] = o.RelevanceScoreColumn + } + toSerialize["output_class"] = o.OutputClass + return toSerialize, nil +} + +func (o *RankingOutput) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "rank_score_column", + "prediction_group_id_column", + "output_class", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRankingOutput := _RankingOutput{} + + err = json.Unmarshal(bytes, &varRankingOutput) + + if err != nil { + return err + } + + *o = RankingOutput(varRankingOutput) + + return err +} + +type NullableRankingOutput struct { + value *RankingOutput + isSet bool +} + +func (v NullableRankingOutput) Get() *RankingOutput { + return v.value +} + +func (v *NullableRankingOutput) Set(val *RankingOutput) { + v.value = val + v.isSet = true +} + +func (v NullableRankingOutput) IsSet() bool { + return v.isSet +} + +func (v *NullableRankingOutput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRankingOutput(val *RankingOutput) *NullableRankingOutput { + return &NullableRankingOutput{value: val, isSet: true} +} + +func (v NullableRankingOutput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRankingOutput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_regression_output.go b/api/client/model_regression_output.go new file mode 100644 index 000000000..f1fa72d6b --- /dev/null +++ b/api/client/model_regression_output.go @@ -0,0 +1,217 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// checks if the RegressionOutput type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &RegressionOutput{} + +// RegressionOutput struct for RegressionOutput +type RegressionOutput struct { + PredictionScoreColumn string `json:"prediction_score_column"` + ActualScoreColumn *string `json:"actual_score_column,omitempty"` + OutputClass ModelPredictionOutputClass `json:"output_class"` +} + +type _RegressionOutput RegressionOutput + +// NewRegressionOutput instantiates a new RegressionOutput object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewRegressionOutput(predictionScoreColumn string, outputClass ModelPredictionOutputClass) *RegressionOutput { + this := RegressionOutput{} + this.PredictionScoreColumn = predictionScoreColumn + this.OutputClass = outputClass + return &this +} + +// NewRegressionOutputWithDefaults instantiates a new RegressionOutput object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewRegressionOutputWithDefaults() *RegressionOutput { + this := RegressionOutput{} + return &this +} + +// GetPredictionScoreColumn returns the PredictionScoreColumn field value +func (o *RegressionOutput) GetPredictionScoreColumn() string { + if o == nil { + var ret string + return ret + } + + return o.PredictionScoreColumn +} + +// GetPredictionScoreColumnOk returns a tuple with the PredictionScoreColumn field value +// and a boolean to check if the value has been set. +func (o *RegressionOutput) GetPredictionScoreColumnOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PredictionScoreColumn, true +} + +// SetPredictionScoreColumn sets field value +func (o *RegressionOutput) SetPredictionScoreColumn(v string) { + o.PredictionScoreColumn = v +} + +// GetActualScoreColumn returns the ActualScoreColumn field value if set, zero value otherwise. +func (o *RegressionOutput) GetActualScoreColumn() string { + if o == nil || IsNil(o.ActualScoreColumn) { + var ret string + return ret + } + return *o.ActualScoreColumn +} + +// GetActualScoreColumnOk returns a tuple with the ActualScoreColumn field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *RegressionOutput) GetActualScoreColumnOk() (*string, bool) { + if o == nil || IsNil(o.ActualScoreColumn) { + return nil, false + } + return o.ActualScoreColumn, true +} + +// HasActualScoreColumn returns a boolean if a field has been set. +func (o *RegressionOutput) HasActualScoreColumn() bool { + if o != nil && !IsNil(o.ActualScoreColumn) { + return true + } + + return false +} + +// SetActualScoreColumn gets a reference to the given string and assigns it to the ActualScoreColumn field. +func (o *RegressionOutput) SetActualScoreColumn(v string) { + o.ActualScoreColumn = &v +} + +// GetOutputClass returns the OutputClass field value +func (o *RegressionOutput) GetOutputClass() ModelPredictionOutputClass { + if o == nil { + var ret ModelPredictionOutputClass + return ret + } + + return o.OutputClass +} + +// GetOutputClassOk returns a tuple with the OutputClass field value +// and a boolean to check if the value has been set. +func (o *RegressionOutput) GetOutputClassOk() (*ModelPredictionOutputClass, bool) { + if o == nil { + return nil, false + } + return &o.OutputClass, true +} + +// SetOutputClass sets field value +func (o *RegressionOutput) SetOutputClass(v ModelPredictionOutputClass) { + o.OutputClass = v +} + +func (o RegressionOutput) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o RegressionOutput) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["prediction_score_column"] = o.PredictionScoreColumn + if !IsNil(o.ActualScoreColumn) { + toSerialize["actual_score_column"] = o.ActualScoreColumn + } + toSerialize["output_class"] = o.OutputClass + return toSerialize, nil +} + +func (o *RegressionOutput) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "prediction_score_column", + "output_class", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varRegressionOutput := _RegressionOutput{} + + err = json.Unmarshal(bytes, &varRegressionOutput) + + if err != nil { + return err + } + + *o = RegressionOutput(varRegressionOutput) + + return err +} + +type NullableRegressionOutput struct { + value *RegressionOutput + isSet bool +} + +func (v NullableRegressionOutput) Get() *RegressionOutput { + return v.value +} + +func (v *NullableRegressionOutput) Set(val *RegressionOutput) { + v.value = val + v.isSet = true +} + +func (v NullableRegressionOutput) IsSet() bool { + return v.isSet +} + +func (v *NullableRegressionOutput) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableRegressionOutput(val *RegressionOutput) *NullableRegressionOutput { + return &NullableRegressionOutput{value: val, isSet: true} +} + +func (v NullableRegressionOutput) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableRegressionOutput) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_resource_request.go b/api/client/model_resource_request.go index 5c9383b9a..05a3e75a2 100644 --- a/api/client/model_resource_request.go +++ b/api/client/model_resource_request.go @@ -1,18 +1,304 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the ResourceRequest type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &ResourceRequest{} + +// ResourceRequest struct for ResourceRequest type ResourceRequest struct { - MinReplica int32 `json:"min_replica,omitempty"` - MaxReplica int32 `json:"max_replica,omitempty"` - CpuRequest string `json:"cpu_request,omitempty"` - MemoryRequest string `json:"memory_request,omitempty"` - GpuName string `json:"gpu_name,omitempty"` - GpuRequest string `json:"gpu_request,omitempty"` + MinReplica *int32 `json:"min_replica,omitempty"` + MaxReplica *int32 `json:"max_replica,omitempty"` + CpuRequest *string `json:"cpu_request,omitempty"` + MemoryRequest *string `json:"memory_request,omitempty"` + GpuName *string `json:"gpu_name,omitempty"` + GpuRequest *string `json:"gpu_request,omitempty"` +} + +// NewResourceRequest instantiates a new ResourceRequest object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewResourceRequest() *ResourceRequest { + this := ResourceRequest{} + return &this +} + +// NewResourceRequestWithDefaults instantiates a new ResourceRequest object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewResourceRequestWithDefaults() *ResourceRequest { + this := ResourceRequest{} + return &this +} + +// GetMinReplica returns the MinReplica field value if set, zero value otherwise. +func (o *ResourceRequest) GetMinReplica() int32 { + if o == nil || IsNil(o.MinReplica) { + var ret int32 + return ret + } + return *o.MinReplica +} + +// GetMinReplicaOk returns a tuple with the MinReplica field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetMinReplicaOk() (*int32, bool) { + if o == nil || IsNil(o.MinReplica) { + return nil, false + } + return o.MinReplica, true +} + +// HasMinReplica returns a boolean if a field has been set. +func (o *ResourceRequest) HasMinReplica() bool { + if o != nil && !IsNil(o.MinReplica) { + return true + } + + return false +} + +// SetMinReplica gets a reference to the given int32 and assigns it to the MinReplica field. +func (o *ResourceRequest) SetMinReplica(v int32) { + o.MinReplica = &v +} + +// GetMaxReplica returns the MaxReplica field value if set, zero value otherwise. +func (o *ResourceRequest) GetMaxReplica() int32 { + if o == nil || IsNil(o.MaxReplica) { + var ret int32 + return ret + } + return *o.MaxReplica +} + +// GetMaxReplicaOk returns a tuple with the MaxReplica field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetMaxReplicaOk() (*int32, bool) { + if o == nil || IsNil(o.MaxReplica) { + return nil, false + } + return o.MaxReplica, true +} + +// HasMaxReplica returns a boolean if a field has been set. +func (o *ResourceRequest) HasMaxReplica() bool { + if o != nil && !IsNil(o.MaxReplica) { + return true + } + + return false +} + +// SetMaxReplica gets a reference to the given int32 and assigns it to the MaxReplica field. +func (o *ResourceRequest) SetMaxReplica(v int32) { + o.MaxReplica = &v +} + +// GetCpuRequest returns the CpuRequest field value if set, zero value otherwise. +func (o *ResourceRequest) GetCpuRequest() string { + if o == nil || IsNil(o.CpuRequest) { + var ret string + return ret + } + return *o.CpuRequest +} + +// GetCpuRequestOk returns a tuple with the CpuRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetCpuRequestOk() (*string, bool) { + if o == nil || IsNil(o.CpuRequest) { + return nil, false + } + return o.CpuRequest, true +} + +// HasCpuRequest returns a boolean if a field has been set. +func (o *ResourceRequest) HasCpuRequest() bool { + if o != nil && !IsNil(o.CpuRequest) { + return true + } + + return false +} + +// SetCpuRequest gets a reference to the given string and assigns it to the CpuRequest field. +func (o *ResourceRequest) SetCpuRequest(v string) { + o.CpuRequest = &v +} + +// GetMemoryRequest returns the MemoryRequest field value if set, zero value otherwise. +func (o *ResourceRequest) GetMemoryRequest() string { + if o == nil || IsNil(o.MemoryRequest) { + var ret string + return ret + } + return *o.MemoryRequest +} + +// GetMemoryRequestOk returns a tuple with the MemoryRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetMemoryRequestOk() (*string, bool) { + if o == nil || IsNil(o.MemoryRequest) { + return nil, false + } + return o.MemoryRequest, true +} + +// HasMemoryRequest returns a boolean if a field has been set. +func (o *ResourceRequest) HasMemoryRequest() bool { + if o != nil && !IsNil(o.MemoryRequest) { + return true + } + + return false +} + +// SetMemoryRequest gets a reference to the given string and assigns it to the MemoryRequest field. +func (o *ResourceRequest) SetMemoryRequest(v string) { + o.MemoryRequest = &v +} + +// GetGpuName returns the GpuName field value if set, zero value otherwise. +func (o *ResourceRequest) GetGpuName() string { + if o == nil || IsNil(o.GpuName) { + var ret string + return ret + } + return *o.GpuName +} + +// GetGpuNameOk returns a tuple with the GpuName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetGpuNameOk() (*string, bool) { + if o == nil || IsNil(o.GpuName) { + return nil, false + } + return o.GpuName, true +} + +// HasGpuName returns a boolean if a field has been set. +func (o *ResourceRequest) HasGpuName() bool { + if o != nil && !IsNil(o.GpuName) { + return true + } + + return false +} + +// SetGpuName gets a reference to the given string and assigns it to the GpuName field. +func (o *ResourceRequest) SetGpuName(v string) { + o.GpuName = &v +} + +// GetGpuRequest returns the GpuRequest field value if set, zero value otherwise. +func (o *ResourceRequest) GetGpuRequest() string { + if o == nil || IsNil(o.GpuRequest) { + var ret string + return ret + } + return *o.GpuRequest +} + +// GetGpuRequestOk returns a tuple with the GpuRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *ResourceRequest) GetGpuRequestOk() (*string, bool) { + if o == nil || IsNil(o.GpuRequest) { + return nil, false + } + return o.GpuRequest, true +} + +// HasGpuRequest returns a boolean if a field has been set. +func (o *ResourceRequest) HasGpuRequest() bool { + if o != nil && !IsNil(o.GpuRequest) { + return true + } + + return false +} + +// SetGpuRequest gets a reference to the given string and assigns it to the GpuRequest field. +func (o *ResourceRequest) SetGpuRequest(v string) { + o.GpuRequest = &v +} + +func (o ResourceRequest) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o ResourceRequest) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.MinReplica) { + toSerialize["min_replica"] = o.MinReplica + } + if !IsNil(o.MaxReplica) { + toSerialize["max_replica"] = o.MaxReplica + } + if !IsNil(o.CpuRequest) { + toSerialize["cpu_request"] = o.CpuRequest + } + if !IsNil(o.MemoryRequest) { + toSerialize["memory_request"] = o.MemoryRequest + } + if !IsNil(o.GpuName) { + toSerialize["gpu_name"] = o.GpuName + } + if !IsNil(o.GpuRequest) { + toSerialize["gpu_request"] = o.GpuRequest + } + return toSerialize, nil +} + +type NullableResourceRequest struct { + value *ResourceRequest + isSet bool +} + +func (v NullableResourceRequest) Get() *ResourceRequest { + return v.value +} + +func (v *NullableResourceRequest) Set(val *ResourceRequest) { + v.value = val + v.isSet = true +} + +func (v NullableResourceRequest) IsSet() bool { + return v.isSet +} + +func (v *NullableResourceRequest) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResourceRequest(val *ResourceRequest) *NullableResourceRequest { + return &NullableResourceRequest{value: val, isSet: true} +} + +func (v NullableResourceRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResourceRequest) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_result_type.go b/api/client/model_result_type.go index 74603cf6d..314a29540 100644 --- a/api/client/model_result_type.go +++ b/api/client/model_result_type.go @@ -1,21 +1,118 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" + "fmt" +) + +// ResultType the model 'ResultType' type ResultType string // List of ResultType const ( - DOUBLE_ResultType ResultType = "DOUBLE" - FLOAT_ResultType ResultType = "FLOAT" - INTEGER_ResultType ResultType = "INTEGER" - LONG_ResultType ResultType = "LONG" - STRING__ResultType ResultType = "STRING" - ARRAY_ResultType ResultType = "ARRAY" + RESULTTYPE_DOUBLE ResultType = "DOUBLE" + RESULTTYPE_FLOAT ResultType = "FLOAT" + RESULTTYPE_INTEGER ResultType = "INTEGER" + RESULTTYPE_LONG ResultType = "LONG" + RESULTTYPE_STRING ResultType = "STRING" + RESULTTYPE_ARRAY ResultType = "ARRAY" ) + +// All allowed values of ResultType enum +var AllowedResultTypeEnumValues = []ResultType{ + "DOUBLE", + "FLOAT", + "INTEGER", + "LONG", + "STRING", + "ARRAY", +} + +func (v *ResultType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ResultType(value) + for _, existing := range AllowedResultTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ResultType", value) +} + +// NewResultTypeFromValue returns a pointer to a valid ResultType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewResultTypeFromValue(v string) (*ResultType, error) { + ev := ResultType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ResultType: valid values are %v", v, AllowedResultTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ResultType) IsValid() bool { + for _, existing := range AllowedResultTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ResultType value +func (v ResultType) Ptr() *ResultType { + return &v +} + +type NullableResultType struct { + value *ResultType + isSet bool +} + +func (v NullableResultType) Get() *ResultType { + return v.value +} + +func (v *NullableResultType) Set(val *ResultType) { + v.value = val + v.isSet = true +} + +func (v NullableResultType) IsSet() bool { + return v.isSet +} + +func (v *NullableResultType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableResultType(val *ResultType) *NullableResultType { + return &NullableResultType{value: val, isSet: true} +} + +func (v NullableResultType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableResultType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_save_mode.go b/api/client/model_save_mode.go index 2793655cf..2e630e9c4 100644 --- a/api/client/model_save_mode.go +++ b/api/client/model_save_mode.go @@ -1,20 +1,116 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client -type SaveMode string +import ( + "encoding/json" + "fmt" +) + +// SaveMode the model 'SaveMode' +type SaveMode int32 // List of SaveMode const ( - ERRORIFEXISTS_SaveMode SaveMode = "ERRORIFEXISTS" - OVERWRITE_SaveMode SaveMode = "OVERWRITE" - APPEND_SaveMode SaveMode = "APPEND" - IGNORE_SaveMode SaveMode = "IGNORE" - ERROR__SaveMode SaveMode = "ERROR" + SAVEMODE__0 SaveMode = 0 + SAVEMODE__1 SaveMode = 1 + SAVEMODE__2 SaveMode = 2 + SAVEMODE__3 SaveMode = 3 + SAVEMODE__4 SaveMode = 4 ) + +// All allowed values of SaveMode enum +var AllowedSaveModeEnumValues = []SaveMode{ + 0, + 1, + 2, + 3, + 4, +} + +func (v *SaveMode) UnmarshalJSON(src []byte) error { + var value int32 + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := SaveMode(value) + for _, existing := range AllowedSaveModeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid SaveMode", value) +} + +// NewSaveModeFromValue returns a pointer to a valid SaveMode +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewSaveModeFromValue(v int32) (*SaveMode, error) { + ev := SaveMode(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for SaveMode: valid values are %v", v, AllowedSaveModeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v SaveMode) IsValid() bool { + for _, existing := range AllowedSaveModeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to SaveMode value +func (v SaveMode) Ptr() *SaveMode { + return &v +} + +type NullableSaveMode struct { + value *SaveMode + isSet bool +} + +func (v NullableSaveMode) Get() *SaveMode { + return v.value +} + +func (v *NullableSaveMode) Set(val *SaveMode) { + v.value = val + v.isSet = true +} + +func (v NullableSaveMode) IsSet() bool { + return v.isSet +} + +func (v *NullableSaveMode) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableSaveMode(val *SaveMode) *NullableSaveMode { + return &NullableSaveMode{value: val, isSet: true} +} + +func (v NullableSaveMode) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableSaveMode) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_schema_spec.go b/api/client/model_schema_spec.go new file mode 100644 index 000000000..ec474cb10 --- /dev/null +++ b/api/client/model_schema_spec.go @@ -0,0 +1,245 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// checks if the SchemaSpec type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &SchemaSpec{} + +// SchemaSpec struct for SchemaSpec +type SchemaSpec struct { + PredictionIdColumn string `json:"prediction_id_column"` + ModelPredictionOutput ModelPredictionOutput `json:"model_prediction_output"` + TagColumns []string `json:"tag_columns,omitempty"` + FeatureTypes map[string]ValueType `json:"feature_types"` +} + +type _SchemaSpec SchemaSpec + +// NewSchemaSpec instantiates a new SchemaSpec object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewSchemaSpec(predictionIdColumn string, modelPredictionOutput ModelPredictionOutput, featureTypes map[string]ValueType) *SchemaSpec { + this := SchemaSpec{} + this.PredictionIdColumn = predictionIdColumn + this.ModelPredictionOutput = modelPredictionOutput + this.FeatureTypes = featureTypes + return &this +} + +// NewSchemaSpecWithDefaults instantiates a new SchemaSpec object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewSchemaSpecWithDefaults() *SchemaSpec { + this := SchemaSpec{} + return &this +} + +// GetPredictionIdColumn returns the PredictionIdColumn field value +func (o *SchemaSpec) GetPredictionIdColumn() string { + if o == nil { + var ret string + return ret + } + + return o.PredictionIdColumn +} + +// GetPredictionIdColumnOk returns a tuple with the PredictionIdColumn field value +// and a boolean to check if the value has been set. +func (o *SchemaSpec) GetPredictionIdColumnOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.PredictionIdColumn, true +} + +// SetPredictionIdColumn sets field value +func (o *SchemaSpec) SetPredictionIdColumn(v string) { + o.PredictionIdColumn = v +} + +// GetModelPredictionOutput returns the ModelPredictionOutput field value +func (o *SchemaSpec) GetModelPredictionOutput() ModelPredictionOutput { + if o == nil { + var ret ModelPredictionOutput + return ret + } + + return o.ModelPredictionOutput +} + +// GetModelPredictionOutputOk returns a tuple with the ModelPredictionOutput field value +// and a boolean to check if the value has been set. +func (o *SchemaSpec) GetModelPredictionOutputOk() (*ModelPredictionOutput, bool) { + if o == nil { + return nil, false + } + return &o.ModelPredictionOutput, true +} + +// SetModelPredictionOutput sets field value +func (o *SchemaSpec) SetModelPredictionOutput(v ModelPredictionOutput) { + o.ModelPredictionOutput = v +} + +// GetTagColumns returns the TagColumns field value if set, zero value otherwise. +func (o *SchemaSpec) GetTagColumns() []string { + if o == nil || IsNil(o.TagColumns) { + var ret []string + return ret + } + return o.TagColumns +} + +// GetTagColumnsOk returns a tuple with the TagColumns field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *SchemaSpec) GetTagColumnsOk() ([]string, bool) { + if o == nil || IsNil(o.TagColumns) { + return nil, false + } + return o.TagColumns, true +} + +// HasTagColumns returns a boolean if a field has been set. +func (o *SchemaSpec) HasTagColumns() bool { + if o != nil && !IsNil(o.TagColumns) { + return true + } + + return false +} + +// SetTagColumns gets a reference to the given []string and assigns it to the TagColumns field. +func (o *SchemaSpec) SetTagColumns(v []string) { + o.TagColumns = v +} + +// GetFeatureTypes returns the FeatureTypes field value +func (o *SchemaSpec) GetFeatureTypes() map[string]ValueType { + if o == nil { + var ret map[string]ValueType + return ret + } + + return o.FeatureTypes +} + +// GetFeatureTypesOk returns a tuple with the FeatureTypes field value +// and a boolean to check if the value has been set. +func (o *SchemaSpec) GetFeatureTypesOk() (*map[string]ValueType, bool) { + if o == nil { + return nil, false + } + return &o.FeatureTypes, true +} + +// SetFeatureTypes sets field value +func (o *SchemaSpec) SetFeatureTypes(v map[string]ValueType) { + o.FeatureTypes = v +} + +func (o SchemaSpec) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o SchemaSpec) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + toSerialize["prediction_id_column"] = o.PredictionIdColumn + toSerialize["model_prediction_output"] = o.ModelPredictionOutput + if !IsNil(o.TagColumns) { + toSerialize["tag_columns"] = o.TagColumns + } + toSerialize["feature_types"] = o.FeatureTypes + return toSerialize, nil +} + +func (o *SchemaSpec) UnmarshalJSON(bytes []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "prediction_id_column", + "model_prediction_output", + "feature_types", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(bytes, &allProperties) + + if err != nil { + return err + } + + for _, requiredProperty := range requiredProperties { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varSchemaSpec := _SchemaSpec{} + + err = json.Unmarshal(bytes, &varSchemaSpec) + + if err != nil { + return err + } + + *o = SchemaSpec(varSchemaSpec) + + return err +} + +type NullableSchemaSpec struct { + value *SchemaSpec + isSet bool +} + +func (v NullableSchemaSpec) Get() *SchemaSpec { + return v.value +} + +func (v *NullableSchemaSpec) Set(val *SchemaSpec) { + v.value = val + v.isSet = true +} + +func (v NullableSchemaSpec) IsSet() bool { + return v.isSet +} + +func (v *NullableSchemaSpec) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableSchemaSpec(val *SchemaSpec) *NullableSchemaSpec { + return &NullableSchemaSpec{value: val, isSet: true} +} + +func (v NullableSchemaSpec) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableSchemaSpec) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_secret.go b/api/client/model_secret.go index 48f15e1d0..6655f21ae 100644 --- a/api/client/model_secret.go +++ b/api/client/model_secret.go @@ -1,15 +1,196 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the Secret type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Secret{} + +// Secret struct for Secret type Secret struct { - Id int32 `json:"id,omitempty"` - Name string `json:"name,omitempty"` - Data string `json:"data,omitempty"` + Id *int32 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + Data *string `json:"data,omitempty"` +} + +// NewSecret instantiates a new Secret object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewSecret() *Secret { + this := Secret{} + return &this +} + +// NewSecretWithDefaults instantiates a new Secret object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewSecretWithDefaults() *Secret { + this := Secret{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Secret) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Secret) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Secret) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *Secret) SetId(v int32) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Secret) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Secret) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Secret) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Secret) SetName(v string) { + o.Name = &v +} + +// GetData returns the Data field value if set, zero value otherwise. +func (o *Secret) GetData() string { + if o == nil || IsNil(o.Data) { + var ret string + return ret + } + return *o.Data +} + +// GetDataOk returns a tuple with the Data field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Secret) GetDataOk() (*string, bool) { + if o == nil || IsNil(o.Data) { + return nil, false + } + return o.Data, true +} + +// HasData returns a boolean if a field has been set. +func (o *Secret) HasData() bool { + if o != nil && !IsNil(o.Data) { + return true + } + + return false +} + +// SetData gets a reference to the given string and assigns it to the Data field. +func (o *Secret) SetData(v string) { + o.Data = &v +} + +func (o Secret) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Secret) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + if !IsNil(o.Data) { + toSerialize["data"] = o.Data + } + return toSerialize, nil +} + +type NullableSecret struct { + value *Secret + isSet bool +} + +func (v NullableSecret) Get() *Secret { + return v.value +} + +func (v *NullableSecret) Set(val *Secret) { + v.value = val + v.isSet = true +} + +func (v NullableSecret) IsSet() bool { + return v.isSet +} + +func (v *NullableSecret) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableSecret(val *Secret) *NullableSecret { + return &NullableSecret{value: val, isSet: true} +} + +func (v NullableSecret) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableSecret) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_standard_transformer_simulation_request.go b/api/client/model_standard_transformer_simulation_request.go index 824a2c8d5..4cc8eae39 100644 --- a/api/client/model_standard_transformer_simulation_request.go +++ b/api/client/model_standard_transformer_simulation_request.go @@ -1,17 +1,268 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the StandardTransformerSimulationRequest type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &StandardTransformerSimulationRequest{} + +// StandardTransformerSimulationRequest struct for StandardTransformerSimulationRequest type StandardTransformerSimulationRequest struct { - Payload *ModelMap `json:"payload,omitempty"` - Headers *ModelMap `json:"headers,omitempty"` - Config *ModelMap `json:"config,omitempty"` + Payload map[string]interface{} `json:"payload,omitempty"` + Headers map[string]interface{} `json:"headers,omitempty"` + Config map[string]interface{} `json:"config,omitempty"` ModelPredictionConfig *ModelPredictionConfig `json:"model_prediction_config,omitempty"` Protocol *Protocol `json:"protocol,omitempty"` } + +// NewStandardTransformerSimulationRequest instantiates a new StandardTransformerSimulationRequest object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewStandardTransformerSimulationRequest() *StandardTransformerSimulationRequest { + this := StandardTransformerSimulationRequest{} + return &this +} + +// NewStandardTransformerSimulationRequestWithDefaults instantiates a new StandardTransformerSimulationRequest object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewStandardTransformerSimulationRequestWithDefaults() *StandardTransformerSimulationRequest { + this := StandardTransformerSimulationRequest{} + return &this +} + +// GetPayload returns the Payload field value if set, zero value otherwise. +func (o *StandardTransformerSimulationRequest) GetPayload() map[string]interface{} { + if o == nil || IsNil(o.Payload) { + var ret map[string]interface{} + return ret + } + return o.Payload +} + +// GetPayloadOk returns a tuple with the Payload field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationRequest) GetPayloadOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Payload) { + return map[string]interface{}{}, false + } + return o.Payload, true +} + +// HasPayload returns a boolean if a field has been set. +func (o *StandardTransformerSimulationRequest) HasPayload() bool { + if o != nil && !IsNil(o.Payload) { + return true + } + + return false +} + +// SetPayload gets a reference to the given map[string]interface{} and assigns it to the Payload field. +func (o *StandardTransformerSimulationRequest) SetPayload(v map[string]interface{}) { + o.Payload = v +} + +// GetHeaders returns the Headers field value if set, zero value otherwise. +func (o *StandardTransformerSimulationRequest) GetHeaders() map[string]interface{} { + if o == nil || IsNil(o.Headers) { + var ret map[string]interface{} + return ret + } + return o.Headers +} + +// GetHeadersOk returns a tuple with the Headers field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationRequest) GetHeadersOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Headers) { + return map[string]interface{}{}, false + } + return o.Headers, true +} + +// HasHeaders returns a boolean if a field has been set. +func (o *StandardTransformerSimulationRequest) HasHeaders() bool { + if o != nil && !IsNil(o.Headers) { + return true + } + + return false +} + +// SetHeaders gets a reference to the given map[string]interface{} and assigns it to the Headers field. +func (o *StandardTransformerSimulationRequest) SetHeaders(v map[string]interface{}) { + o.Headers = v +} + +// GetConfig returns the Config field value if set, zero value otherwise. +func (o *StandardTransformerSimulationRequest) GetConfig() map[string]interface{} { + if o == nil || IsNil(o.Config) { + var ret map[string]interface{} + return ret + } + return o.Config +} + +// GetConfigOk returns a tuple with the Config field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationRequest) GetConfigOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Config) { + return map[string]interface{}{}, false + } + return o.Config, true +} + +// HasConfig returns a boolean if a field has been set. +func (o *StandardTransformerSimulationRequest) HasConfig() bool { + if o != nil && !IsNil(o.Config) { + return true + } + + return false +} + +// SetConfig gets a reference to the given map[string]interface{} and assigns it to the Config field. +func (o *StandardTransformerSimulationRequest) SetConfig(v map[string]interface{}) { + o.Config = v +} + +// GetModelPredictionConfig returns the ModelPredictionConfig field value if set, zero value otherwise. +func (o *StandardTransformerSimulationRequest) GetModelPredictionConfig() ModelPredictionConfig { + if o == nil || IsNil(o.ModelPredictionConfig) { + var ret ModelPredictionConfig + return ret + } + return *o.ModelPredictionConfig +} + +// GetModelPredictionConfigOk returns a tuple with the ModelPredictionConfig field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationRequest) GetModelPredictionConfigOk() (*ModelPredictionConfig, bool) { + if o == nil || IsNil(o.ModelPredictionConfig) { + return nil, false + } + return o.ModelPredictionConfig, true +} + +// HasModelPredictionConfig returns a boolean if a field has been set. +func (o *StandardTransformerSimulationRequest) HasModelPredictionConfig() bool { + if o != nil && !IsNil(o.ModelPredictionConfig) { + return true + } + + return false +} + +// SetModelPredictionConfig gets a reference to the given ModelPredictionConfig and assigns it to the ModelPredictionConfig field. +func (o *StandardTransformerSimulationRequest) SetModelPredictionConfig(v ModelPredictionConfig) { + o.ModelPredictionConfig = &v +} + +// GetProtocol returns the Protocol field value if set, zero value otherwise. +func (o *StandardTransformerSimulationRequest) GetProtocol() Protocol { + if o == nil || IsNil(o.Protocol) { + var ret Protocol + return ret + } + return *o.Protocol +} + +// GetProtocolOk returns a tuple with the Protocol field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationRequest) GetProtocolOk() (*Protocol, bool) { + if o == nil || IsNil(o.Protocol) { + return nil, false + } + return o.Protocol, true +} + +// HasProtocol returns a boolean if a field has been set. +func (o *StandardTransformerSimulationRequest) HasProtocol() bool { + if o != nil && !IsNil(o.Protocol) { + return true + } + + return false +} + +// SetProtocol gets a reference to the given Protocol and assigns it to the Protocol field. +func (o *StandardTransformerSimulationRequest) SetProtocol(v Protocol) { + o.Protocol = &v +} + +func (o StandardTransformerSimulationRequest) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o StandardTransformerSimulationRequest) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Payload) { + toSerialize["payload"] = o.Payload + } + if !IsNil(o.Headers) { + toSerialize["headers"] = o.Headers + } + if !IsNil(o.Config) { + toSerialize["config"] = o.Config + } + if !IsNil(o.ModelPredictionConfig) { + toSerialize["model_prediction_config"] = o.ModelPredictionConfig + } + if !IsNil(o.Protocol) { + toSerialize["protocol"] = o.Protocol + } + return toSerialize, nil +} + +type NullableStandardTransformerSimulationRequest struct { + value *StandardTransformerSimulationRequest + isSet bool +} + +func (v NullableStandardTransformerSimulationRequest) Get() *StandardTransformerSimulationRequest { + return v.value +} + +func (v *NullableStandardTransformerSimulationRequest) Set(val *StandardTransformerSimulationRequest) { + v.value = val + v.isSet = true +} + +func (v NullableStandardTransformerSimulationRequest) IsSet() bool { + return v.isSet +} + +func (v *NullableStandardTransformerSimulationRequest) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableStandardTransformerSimulationRequest(val *StandardTransformerSimulationRequest) *NullableStandardTransformerSimulationRequest { + return &NullableStandardTransformerSimulationRequest{value: val, isSet: true} +} + +func (v NullableStandardTransformerSimulationRequest) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableStandardTransformerSimulationRequest) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_standard_transformer_simulation_response.go b/api/client/model_standard_transformer_simulation_response.go index 97b7db5ad..d6d46cc89 100644 --- a/api/client/model_standard_transformer_simulation_response.go +++ b/api/client/model_standard_transformer_simulation_response.go @@ -1,14 +1,160 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client +import ( + "encoding/json" +) + +// checks if the StandardTransformerSimulationResponse type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &StandardTransformerSimulationResponse{} + +// StandardTransformerSimulationResponse struct for StandardTransformerSimulationResponse type StandardTransformerSimulationResponse struct { - Response *ModelMap `json:"response,omitempty"` - OperationTracing *OperationTracing `json:"operation_tracing,omitempty"` + Response map[string]interface{} `json:"response,omitempty"` + OperationTracing *OperationTracing `json:"operation_tracing,omitempty"` +} + +// NewStandardTransformerSimulationResponse instantiates a new StandardTransformerSimulationResponse object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewStandardTransformerSimulationResponse() *StandardTransformerSimulationResponse { + this := StandardTransformerSimulationResponse{} + return &this +} + +// NewStandardTransformerSimulationResponseWithDefaults instantiates a new StandardTransformerSimulationResponse object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewStandardTransformerSimulationResponseWithDefaults() *StandardTransformerSimulationResponse { + this := StandardTransformerSimulationResponse{} + return &this +} + +// GetResponse returns the Response field value if set, zero value otherwise. +func (o *StandardTransformerSimulationResponse) GetResponse() map[string]interface{} { + if o == nil || IsNil(o.Response) { + var ret map[string]interface{} + return ret + } + return o.Response +} + +// GetResponseOk returns a tuple with the Response field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationResponse) GetResponseOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Response) { + return map[string]interface{}{}, false + } + return o.Response, true +} + +// HasResponse returns a boolean if a field has been set. +func (o *StandardTransformerSimulationResponse) HasResponse() bool { + if o != nil && !IsNil(o.Response) { + return true + } + + return false +} + +// SetResponse gets a reference to the given map[string]interface{} and assigns it to the Response field. +func (o *StandardTransformerSimulationResponse) SetResponse(v map[string]interface{}) { + o.Response = v +} + +// GetOperationTracing returns the OperationTracing field value if set, zero value otherwise. +func (o *StandardTransformerSimulationResponse) GetOperationTracing() OperationTracing { + if o == nil || IsNil(o.OperationTracing) { + var ret OperationTracing + return ret + } + return *o.OperationTracing +} + +// GetOperationTracingOk returns a tuple with the OperationTracing field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *StandardTransformerSimulationResponse) GetOperationTracingOk() (*OperationTracing, bool) { + if o == nil || IsNil(o.OperationTracing) { + return nil, false + } + return o.OperationTracing, true +} + +// HasOperationTracing returns a boolean if a field has been set. +func (o *StandardTransformerSimulationResponse) HasOperationTracing() bool { + if o != nil && !IsNil(o.OperationTracing) { + return true + } + + return false +} + +// SetOperationTracing gets a reference to the given OperationTracing and assigns it to the OperationTracing field. +func (o *StandardTransformerSimulationResponse) SetOperationTracing(v OperationTracing) { + o.OperationTracing = &v +} + +func (o StandardTransformerSimulationResponse) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o StandardTransformerSimulationResponse) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Response) { + toSerialize["response"] = o.Response + } + if !IsNil(o.OperationTracing) { + toSerialize["operation_tracing"] = o.OperationTracing + } + return toSerialize, nil +} + +type NullableStandardTransformerSimulationResponse struct { + value *StandardTransformerSimulationResponse + isSet bool +} + +func (v NullableStandardTransformerSimulationResponse) Get() *StandardTransformerSimulationResponse { + return v.value +} + +func (v *NullableStandardTransformerSimulationResponse) Set(val *StandardTransformerSimulationResponse) { + v.value = val + v.isSet = true +} + +func (v NullableStandardTransformerSimulationResponse) IsSet() bool { + return v.isSet +} + +func (v *NullableStandardTransformerSimulationResponse) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableStandardTransformerSimulationResponse(val *StandardTransformerSimulationResponse) *NullableStandardTransformerSimulationResponse { + return &NullableStandardTransformerSimulationResponse{value: val, isSet: true} +} + +func (v NullableStandardTransformerSimulationResponse) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableStandardTransformerSimulationResponse) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_transformer.go b/api/client/model_transformer.go index 9aec9069f..5690bbf1f 100644 --- a/api/client/model_transformer.go +++ b/api/client/model_transformer.go @@ -1,26 +1,449 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" "time" ) +// checks if the Transformer type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Transformer{} + +// Transformer struct for Transformer type Transformer struct { - Id string `json:"id,omitempty"` - Enabled bool `json:"enabled,omitempty"` - TransformerType string `json:"transformer_type,omitempty"` - Image string `json:"image,omitempty"` - Command string `json:"command,omitempty"` - Args string `json:"args,omitempty"` + Id *string `json:"id,omitempty"` + Enabled *bool `json:"enabled,omitempty"` + TransformerType *string `json:"transformer_type,omitempty"` + Image *string `json:"image,omitempty"` + Command *string `json:"command,omitempty"` + Args *string `json:"args,omitempty"` ResourceRequest *ResourceRequest `json:"resource_request,omitempty"` EnvVars []EnvVar `json:"env_vars,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// NewTransformer instantiates a new Transformer object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTransformer() *Transformer { + this := Transformer{} + return &this +} + +// NewTransformerWithDefaults instantiates a new Transformer object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTransformerWithDefaults() *Transformer { + this := Transformer{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Transformer) GetId() string { + if o == nil || IsNil(o.Id) { + var ret string + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetIdOk() (*string, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Transformer) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given string and assigns it to the Id field. +func (o *Transformer) SetId(v string) { + o.Id = &v +} + +// GetEnabled returns the Enabled field value if set, zero value otherwise. +func (o *Transformer) GetEnabled() bool { + if o == nil || IsNil(o.Enabled) { + var ret bool + return ret + } + return *o.Enabled +} + +// GetEnabledOk returns a tuple with the Enabled field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetEnabledOk() (*bool, bool) { + if o == nil || IsNil(o.Enabled) { + return nil, false + } + return o.Enabled, true +} + +// HasEnabled returns a boolean if a field has been set. +func (o *Transformer) HasEnabled() bool { + if o != nil && !IsNil(o.Enabled) { + return true + } + + return false +} + +// SetEnabled gets a reference to the given bool and assigns it to the Enabled field. +func (o *Transformer) SetEnabled(v bool) { + o.Enabled = &v +} + +// GetTransformerType returns the TransformerType field value if set, zero value otherwise. +func (o *Transformer) GetTransformerType() string { + if o == nil || IsNil(o.TransformerType) { + var ret string + return ret + } + return *o.TransformerType +} + +// GetTransformerTypeOk returns a tuple with the TransformerType field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetTransformerTypeOk() (*string, bool) { + if o == nil || IsNil(o.TransformerType) { + return nil, false + } + return o.TransformerType, true +} + +// HasTransformerType returns a boolean if a field has been set. +func (o *Transformer) HasTransformerType() bool { + if o != nil && !IsNil(o.TransformerType) { + return true + } + + return false +} + +// SetTransformerType gets a reference to the given string and assigns it to the TransformerType field. +func (o *Transformer) SetTransformerType(v string) { + o.TransformerType = &v +} + +// GetImage returns the Image field value if set, zero value otherwise. +func (o *Transformer) GetImage() string { + if o == nil || IsNil(o.Image) { + var ret string + return ret + } + return *o.Image +} + +// GetImageOk returns a tuple with the Image field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetImageOk() (*string, bool) { + if o == nil || IsNil(o.Image) { + return nil, false + } + return o.Image, true +} + +// HasImage returns a boolean if a field has been set. +func (o *Transformer) HasImage() bool { + if o != nil && !IsNil(o.Image) { + return true + } + + return false +} + +// SetImage gets a reference to the given string and assigns it to the Image field. +func (o *Transformer) SetImage(v string) { + o.Image = &v +} + +// GetCommand returns the Command field value if set, zero value otherwise. +func (o *Transformer) GetCommand() string { + if o == nil || IsNil(o.Command) { + var ret string + return ret + } + return *o.Command +} + +// GetCommandOk returns a tuple with the Command field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetCommandOk() (*string, bool) { + if o == nil || IsNil(o.Command) { + return nil, false + } + return o.Command, true +} + +// HasCommand returns a boolean if a field has been set. +func (o *Transformer) HasCommand() bool { + if o != nil && !IsNil(o.Command) { + return true + } + + return false +} + +// SetCommand gets a reference to the given string and assigns it to the Command field. +func (o *Transformer) SetCommand(v string) { + o.Command = &v +} + +// GetArgs returns the Args field value if set, zero value otherwise. +func (o *Transformer) GetArgs() string { + if o == nil || IsNil(o.Args) { + var ret string + return ret + } + return *o.Args +} + +// GetArgsOk returns a tuple with the Args field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetArgsOk() (*string, bool) { + if o == nil || IsNil(o.Args) { + return nil, false + } + return o.Args, true +} + +// HasArgs returns a boolean if a field has been set. +func (o *Transformer) HasArgs() bool { + if o != nil && !IsNil(o.Args) { + return true + } + + return false +} + +// SetArgs gets a reference to the given string and assigns it to the Args field. +func (o *Transformer) SetArgs(v string) { + o.Args = &v +} + +// GetResourceRequest returns the ResourceRequest field value if set, zero value otherwise. +func (o *Transformer) GetResourceRequest() ResourceRequest { + if o == nil || IsNil(o.ResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.ResourceRequest +} + +// GetResourceRequestOk returns a tuple with the ResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.ResourceRequest) { + return nil, false + } + return o.ResourceRequest, true +} + +// HasResourceRequest returns a boolean if a field has been set. +func (o *Transformer) HasResourceRequest() bool { + if o != nil && !IsNil(o.ResourceRequest) { + return true + } + + return false +} + +// SetResourceRequest gets a reference to the given ResourceRequest and assigns it to the ResourceRequest field. +func (o *Transformer) SetResourceRequest(v ResourceRequest) { + o.ResourceRequest = &v +} + +// GetEnvVars returns the EnvVars field value if set, zero value otherwise. +func (o *Transformer) GetEnvVars() []EnvVar { + if o == nil || IsNil(o.EnvVars) { + var ret []EnvVar + return ret + } + return o.EnvVars +} + +// GetEnvVarsOk returns a tuple with the EnvVars field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetEnvVarsOk() ([]EnvVar, bool) { + if o == nil || IsNil(o.EnvVars) { + return nil, false + } + return o.EnvVars, true +} + +// HasEnvVars returns a boolean if a field has been set. +func (o *Transformer) HasEnvVars() bool { + if o != nil && !IsNil(o.EnvVars) { + return true + } + + return false +} + +// SetEnvVars gets a reference to the given []EnvVar and assigns it to the EnvVars field. +func (o *Transformer) SetEnvVars(v []EnvVar) { + o.EnvVars = v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *Transformer) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *Transformer) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *Transformer) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *Transformer) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Transformer) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *Transformer) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *Transformer) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o Transformer) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Transformer) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Enabled) { + toSerialize["enabled"] = o.Enabled + } + if !IsNil(o.TransformerType) { + toSerialize["transformer_type"] = o.TransformerType + } + if !IsNil(o.Image) { + toSerialize["image"] = o.Image + } + if !IsNil(o.Command) { + toSerialize["command"] = o.Command + } + if !IsNil(o.Args) { + toSerialize["args"] = o.Args + } + if !IsNil(o.ResourceRequest) { + toSerialize["resource_request"] = o.ResourceRequest + } + if !IsNil(o.EnvVars) { + toSerialize["env_vars"] = o.EnvVars + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +type NullableTransformer struct { + value *Transformer + isSet bool +} + +func (v NullableTransformer) Get() *Transformer { + return v.value +} + +func (v *NullableTransformer) Set(val *Transformer) { + v.value = val + v.isSet = true +} + +func (v NullableTransformer) IsSet() bool { + return v.isSet +} + +func (v *NullableTransformer) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTransformer(val *Transformer) *NullableTransformer { + return &NullableTransformer{value: val, isSet: true} +} + +func (v NullableTransformer) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTransformer) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_value_type.go b/api/client/model_value_type.go new file mode 100644 index 000000000..19c3594c7 --- /dev/null +++ b/api/client/model_value_type.go @@ -0,0 +1,114 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "fmt" +) + +// ValueType the model 'ValueType' +type ValueType string + +// List of ValueType +const ( + VALUETYPE_FLOAT64 ValueType = "float64" + VALUETYPE_INT64 ValueType = "int64" + VALUETYPE_BOOLEAN ValueType = "boolean" + VALUETYPE_STRING ValueType = "string" +) + +// All allowed values of ValueType enum +var AllowedValueTypeEnumValues = []ValueType{ + "float64", + "int64", + "boolean", + "string", +} + +func (v *ValueType) UnmarshalJSON(src []byte) error { + var value string + err := json.Unmarshal(src, &value) + if err != nil { + return err + } + enumTypeValue := ValueType(value) + for _, existing := range AllowedValueTypeEnumValues { + if existing == enumTypeValue { + *v = enumTypeValue + return nil + } + } + + return fmt.Errorf("%+v is not a valid ValueType", value) +} + +// NewValueTypeFromValue returns a pointer to a valid ValueType +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewValueTypeFromValue(v string) (*ValueType, error) { + ev := ValueType(v) + if ev.IsValid() { + return &ev, nil + } else { + return nil, fmt.Errorf("invalid value '%v' for ValueType: valid values are %v", v, AllowedValueTypeEnumValues) + } +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v ValueType) IsValid() bool { + for _, existing := range AllowedValueTypeEnumValues { + if existing == v { + return true + } + } + return false +} + +// Ptr returns reference to ValueType value +func (v ValueType) Ptr() *ValueType { + return &v +} + +type NullableValueType struct { + value *ValueType + isSet bool +} + +func (v NullableValueType) Get() *ValueType { + return v.value +} + +func (v *NullableValueType) Set(val *ValueType) { + v.value = val + v.isSet = true +} + +func (v NullableValueType) IsSet() bool { + return v.isSet +} + +func (v *NullableValueType) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableValueType(val *ValueType) *NullableValueType { + return &NullableValueType{value: val, isSet: true} +} + +func (v NullableValueType) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableValueType) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} diff --git a/api/client/model_version.go b/api/client/model_version.go index ec0f391b6..ebfd1be45 100644 --- a/api/client/model_version.go +++ b/api/client/model_version.go @@ -1,28 +1,557 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" "time" ) +// checks if the Version type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Version{} + +// Version struct for Version type Version struct { - Id int32 `json:"id,omitempty"` - ModelId int32 `json:"model_id,omitempty"` - MlflowRunId string `json:"mlflow_run_id,omitempty"` - MlflowUrl string `json:"mlflow_url,omitempty"` - ArtifactUri string `json:"artifact_uri,omitempty"` - Endpoints []VersionEndpoint `json:"endpoints,omitempty"` - Properties *interface{} `json:"properties,omitempty"` - Labels map[string]string `json:"labels,omitempty"` - CustomPredictor *CustomPredictor `json:"custom_predictor,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` - PythonVersion string `json:"python_version,omitempty"` + Id *int32 `json:"id,omitempty"` + ModelId *int32 `json:"model_id,omitempty"` + MlflowRunId *string `json:"mlflow_run_id,omitempty"` + MlflowUrl *string `json:"mlflow_url,omitempty"` + ArtifactUri *string `json:"artifact_uri,omitempty"` + Endpoints []VersionEndpoint `json:"endpoints,omitempty"` + Properties map[string]interface{} `json:"properties,omitempty"` + Labels *map[string]string `json:"labels,omitempty"` + CustomPredictor *CustomPredictor `json:"custom_predictor,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` + PythonVersion *string `json:"python_version,omitempty"` + ModelSchema *ModelSchema `json:"model_schema,omitempty"` +} + +// NewVersion instantiates a new Version object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewVersion() *Version { + this := Version{} + return &this +} + +// NewVersionWithDefaults instantiates a new Version object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewVersionWithDefaults() *Version { + this := Version{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Version) GetId() int32 { + if o == nil || IsNil(o.Id) { + var ret int32 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetIdOk() (*int32, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Version) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int32 and assigns it to the Id field. +func (o *Version) SetId(v int32) { + o.Id = &v +} + +// GetModelId returns the ModelId field value if set, zero value otherwise. +func (o *Version) GetModelId() int32 { + if o == nil || IsNil(o.ModelId) { + var ret int32 + return ret + } + return *o.ModelId +} + +// GetModelIdOk returns a tuple with the ModelId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetModelIdOk() (*int32, bool) { + if o == nil || IsNil(o.ModelId) { + return nil, false + } + return o.ModelId, true +} + +// HasModelId returns a boolean if a field has been set. +func (o *Version) HasModelId() bool { + if o != nil && !IsNil(o.ModelId) { + return true + } + + return false +} + +// SetModelId gets a reference to the given int32 and assigns it to the ModelId field. +func (o *Version) SetModelId(v int32) { + o.ModelId = &v +} + +// GetMlflowRunId returns the MlflowRunId field value if set, zero value otherwise. +func (o *Version) GetMlflowRunId() string { + if o == nil || IsNil(o.MlflowRunId) { + var ret string + return ret + } + return *o.MlflowRunId +} + +// GetMlflowRunIdOk returns a tuple with the MlflowRunId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetMlflowRunIdOk() (*string, bool) { + if o == nil || IsNil(o.MlflowRunId) { + return nil, false + } + return o.MlflowRunId, true +} + +// HasMlflowRunId returns a boolean if a field has been set. +func (o *Version) HasMlflowRunId() bool { + if o != nil && !IsNil(o.MlflowRunId) { + return true + } + + return false +} + +// SetMlflowRunId gets a reference to the given string and assigns it to the MlflowRunId field. +func (o *Version) SetMlflowRunId(v string) { + o.MlflowRunId = &v +} + +// GetMlflowUrl returns the MlflowUrl field value if set, zero value otherwise. +func (o *Version) GetMlflowUrl() string { + if o == nil || IsNil(o.MlflowUrl) { + var ret string + return ret + } + return *o.MlflowUrl +} + +// GetMlflowUrlOk returns a tuple with the MlflowUrl field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetMlflowUrlOk() (*string, bool) { + if o == nil || IsNil(o.MlflowUrl) { + return nil, false + } + return o.MlflowUrl, true +} + +// HasMlflowUrl returns a boolean if a field has been set. +func (o *Version) HasMlflowUrl() bool { + if o != nil && !IsNil(o.MlflowUrl) { + return true + } + + return false +} + +// SetMlflowUrl gets a reference to the given string and assigns it to the MlflowUrl field. +func (o *Version) SetMlflowUrl(v string) { + o.MlflowUrl = &v +} + +// GetArtifactUri returns the ArtifactUri field value if set, zero value otherwise. +func (o *Version) GetArtifactUri() string { + if o == nil || IsNil(o.ArtifactUri) { + var ret string + return ret + } + return *o.ArtifactUri +} + +// GetArtifactUriOk returns a tuple with the ArtifactUri field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetArtifactUriOk() (*string, bool) { + if o == nil || IsNil(o.ArtifactUri) { + return nil, false + } + return o.ArtifactUri, true +} + +// HasArtifactUri returns a boolean if a field has been set. +func (o *Version) HasArtifactUri() bool { + if o != nil && !IsNil(o.ArtifactUri) { + return true + } + + return false +} + +// SetArtifactUri gets a reference to the given string and assigns it to the ArtifactUri field. +func (o *Version) SetArtifactUri(v string) { + o.ArtifactUri = &v +} + +// GetEndpoints returns the Endpoints field value if set, zero value otherwise. +func (o *Version) GetEndpoints() []VersionEndpoint { + if o == nil || IsNil(o.Endpoints) { + var ret []VersionEndpoint + return ret + } + return o.Endpoints +} + +// GetEndpointsOk returns a tuple with the Endpoints field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetEndpointsOk() ([]VersionEndpoint, bool) { + if o == nil || IsNil(o.Endpoints) { + return nil, false + } + return o.Endpoints, true +} + +// HasEndpoints returns a boolean if a field has been set. +func (o *Version) HasEndpoints() bool { + if o != nil && !IsNil(o.Endpoints) { + return true + } + + return false +} + +// SetEndpoints gets a reference to the given []VersionEndpoint and assigns it to the Endpoints field. +func (o *Version) SetEndpoints(v []VersionEndpoint) { + o.Endpoints = v +} + +// GetProperties returns the Properties field value if set, zero value otherwise. +func (o *Version) GetProperties() map[string]interface{} { + if o == nil || IsNil(o.Properties) { + var ret map[string]interface{} + return ret + } + return o.Properties +} + +// GetPropertiesOk returns a tuple with the Properties field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetPropertiesOk() (map[string]interface{}, bool) { + if o == nil || IsNil(o.Properties) { + return map[string]interface{}{}, false + } + return o.Properties, true +} + +// HasProperties returns a boolean if a field has been set. +func (o *Version) HasProperties() bool { + if o != nil && !IsNil(o.Properties) { + return true + } + + return false +} + +// SetProperties gets a reference to the given map[string]interface{} and assigns it to the Properties field. +func (o *Version) SetProperties(v map[string]interface{}) { + o.Properties = v +} + +// GetLabels returns the Labels field value if set, zero value otherwise. +func (o *Version) GetLabels() map[string]string { + if o == nil || IsNil(o.Labels) { + var ret map[string]string + return ret + } + return *o.Labels +} + +// GetLabelsOk returns a tuple with the Labels field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetLabelsOk() (*map[string]string, bool) { + if o == nil || IsNil(o.Labels) { + return nil, false + } + return o.Labels, true +} + +// HasLabels returns a boolean if a field has been set. +func (o *Version) HasLabels() bool { + if o != nil && !IsNil(o.Labels) { + return true + } + + return false +} + +// SetLabels gets a reference to the given map[string]string and assigns it to the Labels field. +func (o *Version) SetLabels(v map[string]string) { + o.Labels = &v +} + +// GetCustomPredictor returns the CustomPredictor field value if set, zero value otherwise. +func (o *Version) GetCustomPredictor() CustomPredictor { + if o == nil || IsNil(o.CustomPredictor) { + var ret CustomPredictor + return ret + } + return *o.CustomPredictor +} + +// GetCustomPredictorOk returns a tuple with the CustomPredictor field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetCustomPredictorOk() (*CustomPredictor, bool) { + if o == nil || IsNil(o.CustomPredictor) { + return nil, false + } + return o.CustomPredictor, true +} + +// HasCustomPredictor returns a boolean if a field has been set. +func (o *Version) HasCustomPredictor() bool { + if o != nil && !IsNil(o.CustomPredictor) { + return true + } + + return false +} + +// SetCustomPredictor gets a reference to the given CustomPredictor and assigns it to the CustomPredictor field. +func (o *Version) SetCustomPredictor(v CustomPredictor) { + o.CustomPredictor = &v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *Version) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *Version) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *Version) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *Version) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *Version) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *Version) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +// GetPythonVersion returns the PythonVersion field value if set, zero value otherwise. +func (o *Version) GetPythonVersion() string { + if o == nil || IsNil(o.PythonVersion) { + var ret string + return ret + } + return *o.PythonVersion +} + +// GetPythonVersionOk returns a tuple with the PythonVersion field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetPythonVersionOk() (*string, bool) { + if o == nil || IsNil(o.PythonVersion) { + return nil, false + } + return o.PythonVersion, true +} + +// HasPythonVersion returns a boolean if a field has been set. +func (o *Version) HasPythonVersion() bool { + if o != nil && !IsNil(o.PythonVersion) { + return true + } + + return false +} + +// SetPythonVersion gets a reference to the given string and assigns it to the PythonVersion field. +func (o *Version) SetPythonVersion(v string) { + o.PythonVersion = &v +} + +// GetModelSchema returns the ModelSchema field value if set, zero value otherwise. +func (o *Version) GetModelSchema() ModelSchema { + if o == nil || IsNil(o.ModelSchema) { + var ret ModelSchema + return ret + } + return *o.ModelSchema +} + +// GetModelSchemaOk returns a tuple with the ModelSchema field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Version) GetModelSchemaOk() (*ModelSchema, bool) { + if o == nil || IsNil(o.ModelSchema) { + return nil, false + } + return o.ModelSchema, true +} + +// HasModelSchema returns a boolean if a field has been set. +func (o *Version) HasModelSchema() bool { + if o != nil && !IsNil(o.ModelSchema) { + return true + } + + return false +} + +// SetModelSchema gets a reference to the given ModelSchema and assigns it to the ModelSchema field. +func (o *Version) SetModelSchema(v ModelSchema) { + o.ModelSchema = &v +} + +func (o Version) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o Version) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.ModelId) { + toSerialize["model_id"] = o.ModelId + } + if !IsNil(o.MlflowRunId) { + toSerialize["mlflow_run_id"] = o.MlflowRunId + } + if !IsNil(o.MlflowUrl) { + toSerialize["mlflow_url"] = o.MlflowUrl + } + if !IsNil(o.ArtifactUri) { + toSerialize["artifact_uri"] = o.ArtifactUri + } + if !IsNil(o.Endpoints) { + toSerialize["endpoints"] = o.Endpoints + } + if !IsNil(o.Properties) { + toSerialize["properties"] = o.Properties + } + if !IsNil(o.Labels) { + toSerialize["labels"] = o.Labels + } + if !IsNil(o.CustomPredictor) { + toSerialize["custom_predictor"] = o.CustomPredictor + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + if !IsNil(o.PythonVersion) { + toSerialize["python_version"] = o.PythonVersion + } + if !IsNil(o.ModelSchema) { + toSerialize["model_schema"] = o.ModelSchema + } + return toSerialize, nil +} + +type NullableVersion struct { + value *Version + isSet bool +} + +func (v NullableVersion) Get() *Version { + return v.value +} + +func (v *NullableVersion) Set(val *Version) { + v.value = val + v.isSet = true +} + +func (v NullableVersion) IsSet() bool { + return v.isSet +} + +func (v *NullableVersion) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableVersion(val *Version) *NullableVersion { + return &NullableVersion{value: val, isSet: true} +} + +func (v NullableVersion) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableVersion) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/model_version_endpoint.go b/api/client/model_version_endpoint.go index f56713226..fc4acd8fd 100644 --- a/api/client/model_version_endpoint.go +++ b/api/client/model_version_endpoint.go @@ -1,27 +1,34 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( + "encoding/json" "time" ) +// checks if the VersionEndpoint type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &VersionEndpoint{} + +// VersionEndpoint struct for VersionEndpoint type VersionEndpoint struct { - Id string `json:"id,omitempty"` - VersionId int32 `json:"version_id,omitempty"` + Id *string `json:"id,omitempty"` + VersionId *int32 `json:"version_id,omitempty"` Status *EndpointStatus `json:"status,omitempty"` - Url string `json:"url,omitempty"` - ServiceName string `json:"service_name,omitempty"` - EnvironmentName string `json:"environment_name,omitempty"` + Url *string `json:"url,omitempty"` + ServiceName *string `json:"service_name,omitempty"` + EnvironmentName *string `json:"environment_name,omitempty"` Environment *Environment `json:"environment,omitempty"` - MonitoringUrl string `json:"monitoring_url,omitempty"` - Message string `json:"message,omitempty"` + MonitoringUrl *string `json:"monitoring_url,omitempty"` + Message *string `json:"message,omitempty"` ResourceRequest *ResourceRequest `json:"resource_request,omitempty"` ImageBuilderResourceRequest *ResourceRequest `json:"image_builder_resource_request,omitempty"` EnvVars []EnvVar `json:"env_vars,omitempty"` @@ -30,7 +37,777 @@ type VersionEndpoint struct { DeploymentMode *DeploymentMode `json:"deployment_mode,omitempty"` AutoscalingPolicy *AutoscalingPolicy `json:"autoscaling_policy,omitempty"` Protocol *Protocol `json:"protocol,omitempty"` - EnableModelObservability bool `json:"enable_model_observability,omitempty"` - CreatedAt time.Time `json:"created_at,omitempty"` - UpdatedAt time.Time `json:"updated_at,omitempty"` + EnableModelObservability *bool `json:"enable_model_observability,omitempty"` + CreatedAt *time.Time `json:"created_at,omitempty"` + UpdatedAt *time.Time `json:"updated_at,omitempty"` +} + +// NewVersionEndpoint instantiates a new VersionEndpoint object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewVersionEndpoint() *VersionEndpoint { + this := VersionEndpoint{} + var deploymentMode DeploymentMode = DEPLOYMENTMODE_SERVERLESS + this.DeploymentMode = &deploymentMode + return &this +} + +// NewVersionEndpointWithDefaults instantiates a new VersionEndpoint object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewVersionEndpointWithDefaults() *VersionEndpoint { + this := VersionEndpoint{} + var deploymentMode DeploymentMode = DEPLOYMENTMODE_SERVERLESS + this.DeploymentMode = &deploymentMode + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *VersionEndpoint) GetId() string { + if o == nil || IsNil(o.Id) { + var ret string + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetIdOk() (*string, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *VersionEndpoint) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given string and assigns it to the Id field. +func (o *VersionEndpoint) SetId(v string) { + o.Id = &v +} + +// GetVersionId returns the VersionId field value if set, zero value otherwise. +func (o *VersionEndpoint) GetVersionId() int32 { + if o == nil || IsNil(o.VersionId) { + var ret int32 + return ret + } + return *o.VersionId +} + +// GetVersionIdOk returns a tuple with the VersionId field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetVersionIdOk() (*int32, bool) { + if o == nil || IsNil(o.VersionId) { + return nil, false + } + return o.VersionId, true +} + +// HasVersionId returns a boolean if a field has been set. +func (o *VersionEndpoint) HasVersionId() bool { + if o != nil && !IsNil(o.VersionId) { + return true + } + + return false +} + +// SetVersionId gets a reference to the given int32 and assigns it to the VersionId field. +func (o *VersionEndpoint) SetVersionId(v int32) { + o.VersionId = &v +} + +// GetStatus returns the Status field value if set, zero value otherwise. +func (o *VersionEndpoint) GetStatus() EndpointStatus { + if o == nil || IsNil(o.Status) { + var ret EndpointStatus + return ret + } + return *o.Status +} + +// GetStatusOk returns a tuple with the Status field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetStatusOk() (*EndpointStatus, bool) { + if o == nil || IsNil(o.Status) { + return nil, false + } + return o.Status, true +} + +// HasStatus returns a boolean if a field has been set. +func (o *VersionEndpoint) HasStatus() bool { + if o != nil && !IsNil(o.Status) { + return true + } + + return false +} + +// SetStatus gets a reference to the given EndpointStatus and assigns it to the Status field. +func (o *VersionEndpoint) SetStatus(v EndpointStatus) { + o.Status = &v +} + +// GetUrl returns the Url field value if set, zero value otherwise. +func (o *VersionEndpoint) GetUrl() string { + if o == nil || IsNil(o.Url) { + var ret string + return ret + } + return *o.Url +} + +// GetUrlOk returns a tuple with the Url field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetUrlOk() (*string, bool) { + if o == nil || IsNil(o.Url) { + return nil, false + } + return o.Url, true +} + +// HasUrl returns a boolean if a field has been set. +func (o *VersionEndpoint) HasUrl() bool { + if o != nil && !IsNil(o.Url) { + return true + } + + return false +} + +// SetUrl gets a reference to the given string and assigns it to the Url field. +func (o *VersionEndpoint) SetUrl(v string) { + o.Url = &v +} + +// GetServiceName returns the ServiceName field value if set, zero value otherwise. +func (o *VersionEndpoint) GetServiceName() string { + if o == nil || IsNil(o.ServiceName) { + var ret string + return ret + } + return *o.ServiceName +} + +// GetServiceNameOk returns a tuple with the ServiceName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetServiceNameOk() (*string, bool) { + if o == nil || IsNil(o.ServiceName) { + return nil, false + } + return o.ServiceName, true +} + +// HasServiceName returns a boolean if a field has been set. +func (o *VersionEndpoint) HasServiceName() bool { + if o != nil && !IsNil(o.ServiceName) { + return true + } + + return false +} + +// SetServiceName gets a reference to the given string and assigns it to the ServiceName field. +func (o *VersionEndpoint) SetServiceName(v string) { + o.ServiceName = &v +} + +// GetEnvironmentName returns the EnvironmentName field value if set, zero value otherwise. +func (o *VersionEndpoint) GetEnvironmentName() string { + if o == nil || IsNil(o.EnvironmentName) { + var ret string + return ret + } + return *o.EnvironmentName +} + +// GetEnvironmentNameOk returns a tuple with the EnvironmentName field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetEnvironmentNameOk() (*string, bool) { + if o == nil || IsNil(o.EnvironmentName) { + return nil, false + } + return o.EnvironmentName, true +} + +// HasEnvironmentName returns a boolean if a field has been set. +func (o *VersionEndpoint) HasEnvironmentName() bool { + if o != nil && !IsNil(o.EnvironmentName) { + return true + } + + return false +} + +// SetEnvironmentName gets a reference to the given string and assigns it to the EnvironmentName field. +func (o *VersionEndpoint) SetEnvironmentName(v string) { + o.EnvironmentName = &v +} + +// GetEnvironment returns the Environment field value if set, zero value otherwise. +func (o *VersionEndpoint) GetEnvironment() Environment { + if o == nil || IsNil(o.Environment) { + var ret Environment + return ret + } + return *o.Environment +} + +// GetEnvironmentOk returns a tuple with the Environment field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetEnvironmentOk() (*Environment, bool) { + if o == nil || IsNil(o.Environment) { + return nil, false + } + return o.Environment, true +} + +// HasEnvironment returns a boolean if a field has been set. +func (o *VersionEndpoint) HasEnvironment() bool { + if o != nil && !IsNil(o.Environment) { + return true + } + + return false +} + +// SetEnvironment gets a reference to the given Environment and assigns it to the Environment field. +func (o *VersionEndpoint) SetEnvironment(v Environment) { + o.Environment = &v +} + +// GetMonitoringUrl returns the MonitoringUrl field value if set, zero value otherwise. +func (o *VersionEndpoint) GetMonitoringUrl() string { + if o == nil || IsNil(o.MonitoringUrl) { + var ret string + return ret + } + return *o.MonitoringUrl +} + +// GetMonitoringUrlOk returns a tuple with the MonitoringUrl field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetMonitoringUrlOk() (*string, bool) { + if o == nil || IsNil(o.MonitoringUrl) { + return nil, false + } + return o.MonitoringUrl, true +} + +// HasMonitoringUrl returns a boolean if a field has been set. +func (o *VersionEndpoint) HasMonitoringUrl() bool { + if o != nil && !IsNil(o.MonitoringUrl) { + return true + } + + return false +} + +// SetMonitoringUrl gets a reference to the given string and assigns it to the MonitoringUrl field. +func (o *VersionEndpoint) SetMonitoringUrl(v string) { + o.MonitoringUrl = &v +} + +// GetMessage returns the Message field value if set, zero value otherwise. +func (o *VersionEndpoint) GetMessage() string { + if o == nil || IsNil(o.Message) { + var ret string + return ret + } + return *o.Message +} + +// GetMessageOk returns a tuple with the Message field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetMessageOk() (*string, bool) { + if o == nil || IsNil(o.Message) { + return nil, false + } + return o.Message, true +} + +// HasMessage returns a boolean if a field has been set. +func (o *VersionEndpoint) HasMessage() bool { + if o != nil && !IsNil(o.Message) { + return true + } + + return false +} + +// SetMessage gets a reference to the given string and assigns it to the Message field. +func (o *VersionEndpoint) SetMessage(v string) { + o.Message = &v +} + +// GetResourceRequest returns the ResourceRequest field value if set, zero value otherwise. +func (o *VersionEndpoint) GetResourceRequest() ResourceRequest { + if o == nil || IsNil(o.ResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.ResourceRequest +} + +// GetResourceRequestOk returns a tuple with the ResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.ResourceRequest) { + return nil, false + } + return o.ResourceRequest, true +} + +// HasResourceRequest returns a boolean if a field has been set. +func (o *VersionEndpoint) HasResourceRequest() bool { + if o != nil && !IsNil(o.ResourceRequest) { + return true + } + + return false +} + +// SetResourceRequest gets a reference to the given ResourceRequest and assigns it to the ResourceRequest field. +func (o *VersionEndpoint) SetResourceRequest(v ResourceRequest) { + o.ResourceRequest = &v +} + +// GetImageBuilderResourceRequest returns the ImageBuilderResourceRequest field value if set, zero value otherwise. +func (o *VersionEndpoint) GetImageBuilderResourceRequest() ResourceRequest { + if o == nil || IsNil(o.ImageBuilderResourceRequest) { + var ret ResourceRequest + return ret + } + return *o.ImageBuilderResourceRequest +} + +// GetImageBuilderResourceRequestOk returns a tuple with the ImageBuilderResourceRequest field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetImageBuilderResourceRequestOk() (*ResourceRequest, bool) { + if o == nil || IsNil(o.ImageBuilderResourceRequest) { + return nil, false + } + return o.ImageBuilderResourceRequest, true +} + +// HasImageBuilderResourceRequest returns a boolean if a field has been set. +func (o *VersionEndpoint) HasImageBuilderResourceRequest() bool { + if o != nil && !IsNil(o.ImageBuilderResourceRequest) { + return true + } + + return false +} + +// SetImageBuilderResourceRequest gets a reference to the given ResourceRequest and assigns it to the ImageBuilderResourceRequest field. +func (o *VersionEndpoint) SetImageBuilderResourceRequest(v ResourceRequest) { + o.ImageBuilderResourceRequest = &v +} + +// GetEnvVars returns the EnvVars field value if set, zero value otherwise. +func (o *VersionEndpoint) GetEnvVars() []EnvVar { + if o == nil || IsNil(o.EnvVars) { + var ret []EnvVar + return ret + } + return o.EnvVars +} + +// GetEnvVarsOk returns a tuple with the EnvVars field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetEnvVarsOk() ([]EnvVar, bool) { + if o == nil || IsNil(o.EnvVars) { + return nil, false + } + return o.EnvVars, true +} + +// HasEnvVars returns a boolean if a field has been set. +func (o *VersionEndpoint) HasEnvVars() bool { + if o != nil && !IsNil(o.EnvVars) { + return true + } + + return false +} + +// SetEnvVars gets a reference to the given []EnvVar and assigns it to the EnvVars field. +func (o *VersionEndpoint) SetEnvVars(v []EnvVar) { + o.EnvVars = v +} + +// GetTransformer returns the Transformer field value if set, zero value otherwise. +func (o *VersionEndpoint) GetTransformer() Transformer { + if o == nil || IsNil(o.Transformer) { + var ret Transformer + return ret + } + return *o.Transformer +} + +// GetTransformerOk returns a tuple with the Transformer field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetTransformerOk() (*Transformer, bool) { + if o == nil || IsNil(o.Transformer) { + return nil, false + } + return o.Transformer, true +} + +// HasTransformer returns a boolean if a field has been set. +func (o *VersionEndpoint) HasTransformer() bool { + if o != nil && !IsNil(o.Transformer) { + return true + } + + return false +} + +// SetTransformer gets a reference to the given Transformer and assigns it to the Transformer field. +func (o *VersionEndpoint) SetTransformer(v Transformer) { + o.Transformer = &v +} + +// GetLogger returns the Logger field value if set, zero value otherwise. +func (o *VersionEndpoint) GetLogger() Logger { + if o == nil || IsNil(o.Logger) { + var ret Logger + return ret + } + return *o.Logger +} + +// GetLoggerOk returns a tuple with the Logger field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetLoggerOk() (*Logger, bool) { + if o == nil || IsNil(o.Logger) { + return nil, false + } + return o.Logger, true +} + +// HasLogger returns a boolean if a field has been set. +func (o *VersionEndpoint) HasLogger() bool { + if o != nil && !IsNil(o.Logger) { + return true + } + + return false +} + +// SetLogger gets a reference to the given Logger and assigns it to the Logger field. +func (o *VersionEndpoint) SetLogger(v Logger) { + o.Logger = &v +} + +// GetDeploymentMode returns the DeploymentMode field value if set, zero value otherwise. +func (o *VersionEndpoint) GetDeploymentMode() DeploymentMode { + if o == nil || IsNil(o.DeploymentMode) { + var ret DeploymentMode + return ret + } + return *o.DeploymentMode +} + +// GetDeploymentModeOk returns a tuple with the DeploymentMode field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetDeploymentModeOk() (*DeploymentMode, bool) { + if o == nil || IsNil(o.DeploymentMode) { + return nil, false + } + return o.DeploymentMode, true +} + +// HasDeploymentMode returns a boolean if a field has been set. +func (o *VersionEndpoint) HasDeploymentMode() bool { + if o != nil && !IsNil(o.DeploymentMode) { + return true + } + + return false +} + +// SetDeploymentMode gets a reference to the given DeploymentMode and assigns it to the DeploymentMode field. +func (o *VersionEndpoint) SetDeploymentMode(v DeploymentMode) { + o.DeploymentMode = &v +} + +// GetAutoscalingPolicy returns the AutoscalingPolicy field value if set, zero value otherwise. +func (o *VersionEndpoint) GetAutoscalingPolicy() AutoscalingPolicy { + if o == nil || IsNil(o.AutoscalingPolicy) { + var ret AutoscalingPolicy + return ret + } + return *o.AutoscalingPolicy +} + +// GetAutoscalingPolicyOk returns a tuple with the AutoscalingPolicy field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetAutoscalingPolicyOk() (*AutoscalingPolicy, bool) { + if o == nil || IsNil(o.AutoscalingPolicy) { + return nil, false + } + return o.AutoscalingPolicy, true +} + +// HasAutoscalingPolicy returns a boolean if a field has been set. +func (o *VersionEndpoint) HasAutoscalingPolicy() bool { + if o != nil && !IsNil(o.AutoscalingPolicy) { + return true + } + + return false +} + +// SetAutoscalingPolicy gets a reference to the given AutoscalingPolicy and assigns it to the AutoscalingPolicy field. +func (o *VersionEndpoint) SetAutoscalingPolicy(v AutoscalingPolicy) { + o.AutoscalingPolicy = &v +} + +// GetProtocol returns the Protocol field value if set, zero value otherwise. +func (o *VersionEndpoint) GetProtocol() Protocol { + if o == nil || IsNil(o.Protocol) { + var ret Protocol + return ret + } + return *o.Protocol +} + +// GetProtocolOk returns a tuple with the Protocol field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetProtocolOk() (*Protocol, bool) { + if o == nil || IsNil(o.Protocol) { + return nil, false + } + return o.Protocol, true +} + +// HasProtocol returns a boolean if a field has been set. +func (o *VersionEndpoint) HasProtocol() bool { + if o != nil && !IsNil(o.Protocol) { + return true + } + + return false +} + +// SetProtocol gets a reference to the given Protocol and assigns it to the Protocol field. +func (o *VersionEndpoint) SetProtocol(v Protocol) { + o.Protocol = &v +} + +// GetEnableModelObservability returns the EnableModelObservability field value if set, zero value otherwise. +func (o *VersionEndpoint) GetEnableModelObservability() bool { + if o == nil || IsNil(o.EnableModelObservability) { + var ret bool + return ret + } + return *o.EnableModelObservability +} + +// GetEnableModelObservabilityOk returns a tuple with the EnableModelObservability field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetEnableModelObservabilityOk() (*bool, bool) { + if o == nil || IsNil(o.EnableModelObservability) { + return nil, false + } + return o.EnableModelObservability, true +} + +// HasEnableModelObservability returns a boolean if a field has been set. +func (o *VersionEndpoint) HasEnableModelObservability() bool { + if o != nil && !IsNil(o.EnableModelObservability) { + return true + } + + return false +} + +// SetEnableModelObservability gets a reference to the given bool and assigns it to the EnableModelObservability field. +func (o *VersionEndpoint) SetEnableModelObservability(v bool) { + o.EnableModelObservability = &v +} + +// GetCreatedAt returns the CreatedAt field value if set, zero value otherwise. +func (o *VersionEndpoint) GetCreatedAt() time.Time { + if o == nil || IsNil(o.CreatedAt) { + var ret time.Time + return ret + } + return *o.CreatedAt +} + +// GetCreatedAtOk returns a tuple with the CreatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetCreatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.CreatedAt) { + return nil, false + } + return o.CreatedAt, true +} + +// HasCreatedAt returns a boolean if a field has been set. +func (o *VersionEndpoint) HasCreatedAt() bool { + if o != nil && !IsNil(o.CreatedAt) { + return true + } + + return false +} + +// SetCreatedAt gets a reference to the given time.Time and assigns it to the CreatedAt field. +func (o *VersionEndpoint) SetCreatedAt(v time.Time) { + o.CreatedAt = &v +} + +// GetUpdatedAt returns the UpdatedAt field value if set, zero value otherwise. +func (o *VersionEndpoint) GetUpdatedAt() time.Time { + if o == nil || IsNil(o.UpdatedAt) { + var ret time.Time + return ret + } + return *o.UpdatedAt +} + +// GetUpdatedAtOk returns a tuple with the UpdatedAt field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *VersionEndpoint) GetUpdatedAtOk() (*time.Time, bool) { + if o == nil || IsNil(o.UpdatedAt) { + return nil, false + } + return o.UpdatedAt, true +} + +// HasUpdatedAt returns a boolean if a field has been set. +func (o *VersionEndpoint) HasUpdatedAt() bool { + if o != nil && !IsNil(o.UpdatedAt) { + return true + } + + return false +} + +// SetUpdatedAt gets a reference to the given time.Time and assigns it to the UpdatedAt field. +func (o *VersionEndpoint) SetUpdatedAt(v time.Time) { + o.UpdatedAt = &v +} + +func (o VersionEndpoint) MarshalJSON() ([]byte, error) { + toSerialize, err := o.ToMap() + if err != nil { + return []byte{}, err + } + return json.Marshal(toSerialize) +} + +func (o VersionEndpoint) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.VersionId) { + toSerialize["version_id"] = o.VersionId + } + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + if !IsNil(o.Url) { + toSerialize["url"] = o.Url + } + if !IsNil(o.ServiceName) { + toSerialize["service_name"] = o.ServiceName + } + if !IsNil(o.EnvironmentName) { + toSerialize["environment_name"] = o.EnvironmentName + } + if !IsNil(o.Environment) { + toSerialize["environment"] = o.Environment + } + if !IsNil(o.MonitoringUrl) { + toSerialize["monitoring_url"] = o.MonitoringUrl + } + if !IsNil(o.Message) { + toSerialize["message"] = o.Message + } + if !IsNil(o.ResourceRequest) { + toSerialize["resource_request"] = o.ResourceRequest + } + if !IsNil(o.ImageBuilderResourceRequest) { + toSerialize["image_builder_resource_request"] = o.ImageBuilderResourceRequest + } + if !IsNil(o.EnvVars) { + toSerialize["env_vars"] = o.EnvVars + } + if !IsNil(o.Transformer) { + toSerialize["transformer"] = o.Transformer + } + if !IsNil(o.Logger) { + toSerialize["logger"] = o.Logger + } + if !IsNil(o.DeploymentMode) { + toSerialize["deployment_mode"] = o.DeploymentMode + } + if !IsNil(o.AutoscalingPolicy) { + toSerialize["autoscaling_policy"] = o.AutoscalingPolicy + } + if !IsNil(o.Protocol) { + toSerialize["protocol"] = o.Protocol + } + if !IsNil(o.EnableModelObservability) { + toSerialize["enable_model_observability"] = o.EnableModelObservability + } + if !IsNil(o.CreatedAt) { + toSerialize["created_at"] = o.CreatedAt + } + if !IsNil(o.UpdatedAt) { + toSerialize["updated_at"] = o.UpdatedAt + } + return toSerialize, nil +} + +type NullableVersionEndpoint struct { + value *VersionEndpoint + isSet bool +} + +func (v NullableVersionEndpoint) Get() *VersionEndpoint { + return v.value +} + +func (v *NullableVersionEndpoint) Set(val *VersionEndpoint) { + v.value = val + v.isSet = true +} + +func (v NullableVersionEndpoint) IsSet() bool { + return v.isSet +} + +func (v *NullableVersionEndpoint) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableVersionEndpoint(val *VersionEndpoint) *NullableVersionEndpoint { + return &NullableVersionEndpoint{value: val, isSet: true} +} + +func (v NullableVersionEndpoint) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableVersionEndpoint) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) } diff --git a/api/client/response.go b/api/client/response.go index c8f0564a1..6575d3bc5 100644 --- a/api/client/response.go +++ b/api/client/response.go @@ -1,21 +1,24 @@ /* - * Merlin - * - * API Guide for accessing Merlin's model management, deployment, and serving functionalities - * - * API version: 0.14.0 - * Generated by: Swagger Codegen (https://github.com/swagger-api/swagger-codegen.git) - */ +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + package client import ( "net/http" ) +// APIResponse stores the API response returned by the server. type APIResponse struct { *http.Response `json:"-"` Message string `json:"message,omitempty"` - // Operation is the name of the swagger operation. + // Operation is the name of the OpenAPI operation. Operation string `json:"operation,omitempty"` // RequestURL is the request URL. This value is always available, even if the // embedded *http.Response is nil. @@ -29,12 +32,14 @@ type APIResponse struct { Payload []byte `json:"-"` } +// NewAPIResponse returns a new APIResponse object. func NewAPIResponse(r *http.Response) *APIResponse { response := &APIResponse{Response: r} return response } +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. func NewAPIResponseWithError(errorMessage string) *APIResponse { response := &APIResponse{Message: errorMessage} diff --git a/api/client/utils.go b/api/client/utils.go new file mode 100644 index 000000000..e2bcbdad1 --- /dev/null +++ b/api/client/utils.go @@ -0,0 +1,347 @@ +/* +Merlin + +API Guide for accessing Merlin's model management, deployment, and serving functionalities + +API version: 0.14.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package client + +import ( + "encoding/json" + "reflect" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// IsNil checks if an input is nil +func IsNil(i interface{}) bool { + if i == nil { + return true + } + switch reflect.TypeOf(i).Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + return reflect.ValueOf(i).IsNil() + case reflect.Array: + return reflect.ValueOf(i).IsZero() + } + return false +} + +type MappedNullable interface { + ToMap() (map[string]interface{}, error) +} diff --git a/api/cluster/resource/templater.go b/api/cluster/resource/templater.go index 2a6df25fe..8cd9cede8 100644 --- a/api/cluster/resource/templater.go +++ b/api/cluster/resource/templater.go @@ -58,6 +58,7 @@ const ( envModelName = "CARAML_MODEL_NAME" envModelVersion = "CARAML_MODEL_VERSION" envModelFullName = "CARAML_MODEL_FULL_NAME" + envModelSchema = "CARAML_MODEL_SCHEMA" envProject = "CARAML_PROJECT" envPredictorHost = "CARAML_PREDICTOR_HOST" envArtifactLocation = "CARAML_ARTIFACT_LOCATION" @@ -151,7 +152,10 @@ func (t *InferenceServiceTemplater) CreateInferenceServiceSpec(modelService *mod Annotations: annotations, } - predictorSpec := t.createPredictorSpec(modelService) + predictorSpec, err := t.createPredictorSpec(modelService) + if err != nil { + return nil, fmt.Errorf("unable to create predictor spec: %w", err) + } predictorSpec.TopologySpreadConstraints, err = t.createNewInferenceServiceTopologySpreadConstraints( modelService, kservev1beta1.PredictorComponent, @@ -184,7 +188,7 @@ func (t *InferenceServiceTemplater) CreateInferenceServiceSpec(modelService *mod return inferenceService, nil } -func (t *InferenceServiceTemplater) createPredictorSpec(modelService *models.Service) kservev1beta1.PredictorSpec { +func (t *InferenceServiceTemplater) createPredictorSpec(modelService *models.Service) (kservev1beta1.PredictorSpec, error) { envVars := modelService.EnvVars // Set cpu limit and memory limit to be 2x of the requests @@ -297,7 +301,12 @@ func (t *InferenceServiceTemplater) createPredictorSpec(modelService *models.Ser }, } case models.ModelTypePyFunc, models.ModelTypePyFuncV3: - envVars := models.MergeEnvVars(modelService.EnvVars, createPyFuncDefaultEnvVars(modelService)) + pyfuncDefaultEnv, err := createPyFuncDefaultEnvVars(modelService) + if err != nil { + return kservev1beta1.PredictorSpec{}, err + } + envVars := models.MergeEnvVars(modelService.EnvVars, pyfuncDefaultEnv) + if modelService.Protocol == protocol.UpiV1 { envVars = append(envVars, models.EnvVar{Name: envGRPCOptions, Value: t.deploymentConfig.PyfuncGRPCOptions}) } @@ -348,7 +357,7 @@ func (t *InferenceServiceTemplater) createPredictorSpec(modelService *models.Ser predictorSpec.MaxReplicas = modelService.ResourceRequest.MaxReplica predictorSpec.Logger = loggerSpec - return predictorSpec + return predictorSpec, nil } func (t *InferenceServiceTemplater) createTransformerSpec(modelService *models.Service, transformer *models.Transformer) *kservev1beta1.TransformerSpec { @@ -781,7 +790,8 @@ func createCustomPredictorSpec(modelService *models.Service, resources corev1.Re } // createPyFuncDefaultEnvVars return default env vars for Pyfunc model. -func createPyFuncDefaultEnvVars(svc *models.Service) models.EnvVars { +func createPyFuncDefaultEnvVars(svc *models.Service) (models.EnvVars, error) { + envVars := models.EnvVars{ models.EnvVar{ Name: envPyFuncModelName, @@ -816,7 +826,22 @@ func createPyFuncDefaultEnvVars(svc *models.Service) models.EnvVars { Value: svc.Namespace, }, } - return envVars + + if svc.ModelSchema != nil { + compactedfJsonBuffer := new(bytes.Buffer) + marshalledSchema, err := json.Marshal(svc.ModelSchema) + if err != nil { + return nil, err + } + if err := json.Compact(compactedfJsonBuffer, []byte(marshalledSchema)); err == nil { + envVars = append(envVars, models.EnvVar{ + Name: envModelSchema, + Value: compactedfJsonBuffer.String(), + }) + } + } + + return envVars, nil } func (t *InferenceServiceTemplater) applyDefaults(service *models.Service) { diff --git a/api/cluster/resource/templater_test.go b/api/cluster/resource/templater_test.go index c8bef3cc5..5a9c96c1f 100644 --- a/api/cluster/resource/templater_test.go +++ b/api/cluster/resource/templater_test.go @@ -15,6 +15,8 @@ package resource import ( + "bytes" + "encoding/json" "fmt" "strconv" "testing" @@ -198,6 +200,49 @@ func TestCreateInferenceServiceSpec(t *testing.T) { EnabledModelObservability: true, } + modelSvcWithSchema := &models.Service{ + Name: "my-model-1", + ModelName: "my-model", + Namespace: project.Name, + ModelVersion: "1", + ArtifactURI: "gs://my-artifacet", + Metadata: models.Metadata{ + App: "model", + Component: models.ComponentModelVersion, + Stream: "dsp", + Team: "dsp", + Labels: mlp.Labels{ + { + Key: "sample", + Value: "true", + }, + }, + }, + Protocol: protocol.HttpJson, + EnabledModelObservability: true, + ModelSchema: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.String, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, + } + queueResourcePercentage := "2" storageUri := fmt.Sprintf("%s/model", modelSvc.ArtifactURI) @@ -802,6 +847,27 @@ func TestCreateInferenceServiceSpec(t *testing.T) { Metadata: modelSvc.Metadata, Protocol: protocol.HttpJson, EnabledModelObservability: true, + ModelSchema: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tags"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Int64, + "featureC": models.String, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, }, resourcePercentage: queueResourcePercentage, deploymentScale: defaultDeploymentScale, @@ -833,8 +899,8 @@ func TestCreateInferenceServiceSpec(t *testing.T) { { Name: kserveconstant.InferenceServiceContainerName, Image: "gojek/project-model:1", - Env: models.MergeEnvVars(createPyFuncDefaultEnvVarsWithProtocol(modelSvc, protocol.HttpJson), - createPyFuncPublisherEnvVars(modelSvc, pyfuncPublisherConfig)).ToKubernetesEnvVars(), + Env: models.MergeEnvVars(createPyFuncDefaultEnvVarsWithProtocol(modelSvcWithSchema, protocol.HttpJson), + createPyFuncPublisherEnvVars(modelSvcWithSchema, pyfuncPublisherConfig)).ToKubernetesEnvVars(), Resources: expDefaultModelResourceRequests, LivenessProbe: probeConfig, }, @@ -4166,6 +4232,17 @@ func createPyFuncDefaultEnvVarsWithProtocol(svc *models.Service, protocolValue p Value: svc.Namespace, }, } + + if svc.ModelSchema != nil { + compactedfJsonBuffer := new(bytes.Buffer) + marshalledSchema, _ := json.Marshal(svc.ModelSchema) + if err := json.Compact(compactedfJsonBuffer, []byte(marshalledSchema)); err == nil { + envVars = append(envVars, models.EnvVar{ + Name: envModelSchema, + Value: compactedfJsonBuffer.String(), + }) + } + } return envVars } diff --git a/api/cmd/api/main.go b/api/cmd/api/main.go index c8b2b7ece..551534eab 100644 --- a/api/cmd/api/main.go +++ b/api/cmd/api/main.go @@ -328,6 +328,7 @@ func buildDependencies(ctx context.Context, cfg *config.Config, db *gorm.DB, dis } transformerService := service.NewTransformerService(cfg.StandardTransformerConfig) + modelSchemaService := service.NewModelSchemaService(storage.NewModelSchemaStorage(db)) apiContext := api.AppContext{ DB: db, Enforcer: authEnforcer, @@ -345,6 +346,7 @@ func buildDependencies(ctx context.Context, cfg *config.Config, db *gorm.DB, dis ModelEndpointAlertService: modelEndpointAlertService, TransformerService: transformerService, MlflowDeleteService: mlflowDeleteService, + ModelSchemaService: modelSchemaService, AuthorizationEnabled: cfg.AuthorizationConfig.AuthorizationEnabled, FeatureToggleConfig: cfg.FeatureToggleConfig, diff --git a/api/go.mod b/api/go.mod index 99c2ea32b..1bbebdca0 100644 --- a/api/go.mod +++ b/api/go.mod @@ -75,7 +75,6 @@ require ( go.uber.org/automaxprocs v1.4.0 go.uber.org/zap v1.21.0 golang.org/x/exp v0.0.0-20230713183714-613f0c0eb8a1 - golang.org/x/oauth2 v0.6.0 golang.org/x/text v0.9.0 google.golang.org/api v0.114.0 google.golang.org/grpc v1.55.0 @@ -221,6 +220,7 @@ require ( go.uber.org/multierr v1.8.0 // indirect golang.org/x/crypto v0.5.0 // indirect golang.org/x/net v0.10.0 // indirect + golang.org/x/oauth2 v0.6.0 // indirect golang.org/x/sync v0.1.0 // indirect golang.org/x/sys v0.8.0 // indirect golang.org/x/term v0.8.0 // indirect diff --git a/api/models/model_schema.go b/api/models/model_schema.go new file mode 100644 index 000000000..944cdc005 --- /dev/null +++ b/api/models/model_schema.go @@ -0,0 +1,139 @@ +package models + +import ( + "bytes" + "database/sql/driver" + "encoding/json" + "errors" + "fmt" +) + +type InferenceType string + +type ModelPredictionOutputClass string + +const ( + BinaryClassification ModelPredictionOutputClass = "BinaryClassificationOutput" + Regression ModelPredictionOutputClass = "RegressionOutput" + Ranking ModelPredictionOutputClass = "RankingOutput" +) + +type ValueType string + +const ( + Float64 ValueType = "float64" + Int64 ValueType = "int64" + Boolean ValueType = "boolean" + String ValueType = "string" +) + +type ModelSchema struct { + ID ID `json:"id"` + Spec *SchemaSpec `json:"spec,omitempty"` + ModelID ID `json:"-"` +} + +type SchemaSpec struct { + PredictionIDColumn string `json:"prediction_id_column"` + ModelPredictionOutput *ModelPredictionOutput `json:"model_prediction_output"` + TagColumns []string `json:"tag_columns"` + FeatureTypes map[string]ValueType `json:"feature_types"` +} + +func (s SchemaSpec) Value() (driver.Value, error) { + return json.Marshal(s) +} + +func (s *SchemaSpec) Scan(value interface{}) error { + b, ok := value.([]byte) + if !ok { + return errors.New("type assertion to []byte failed") + } + + return json.Unmarshal(b, &s) +} + +type ModelPredictionOutput struct { + BinaryClassificationOutput *BinaryClassificationOutput + RankingOutput *RankingOutput + RegressionOutput *RegressionOutput +} + +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} + +func (m *ModelPredictionOutput) UnmarshalJSON(data []byte) error { + var err error + outputClassStruct := struct { + OutputClass ModelPredictionOutputClass `json:"output_class"` + }{} + err = json.Unmarshal(data, &outputClassStruct) + if err != nil { + return err + } + + strictDecoder := newStrictDecoder(data) + switch outputClassStruct.OutputClass { + case BinaryClassification: + err := strictDecoder.Decode(&m.BinaryClassificationOutput) + if err != nil { + return err + } + case Regression: + err := strictDecoder.Decode(&m.RegressionOutput) + if err != nil { + return err + } + case Ranking: + err := strictDecoder.Decode(&m.RankingOutput) + if err != nil { + return err + } + default: + return fmt.Errorf("output class %v it not supported", outputClassStruct.OutputClass) + } + + return nil +} + +func (m ModelPredictionOutput) MarshalJSON() ([]byte, error) { + if m.BinaryClassificationOutput != nil { + return json.Marshal(&m.BinaryClassificationOutput) + } + + if m.RankingOutput != nil { + return json.Marshal(&m.RankingOutput) + } + + if m.RegressionOutput != nil { + return json.Marshal(&m.RegressionOutput) + } + + return nil, nil +} + +type BinaryClassificationOutput struct { + ActualLabelColumn string `json:"actual_label_column"` + NegativeClassLabel string `json:"negative_class_label"` + PredictionScoreColumn string `json:"prediction_score_column"` + PredictionLabelColumn string `json:"prediction_label_column"` + PositiveClassLabel string `json:"positive_class_label"` + ScoreThreshold *float64 `json:"score_threshold,omitempty"` + OutputClass ModelPredictionOutputClass `json:"output_class" validate:"required"` +} + +type RankingOutput struct { + PredictionGroudIDColumn string `json:"prediction_group_id_column"` + RankScoreColumn string `json:"rank_score_column"` + RelevanceScoreColumn string `json:"relevance_score"` + OutputClass ModelPredictionOutputClass `json:"output_class" validate:"required"` +} + +type RegressionOutput struct { + PredictionScoreColumn string `json:"prediction_score_column"` + ActualScoreColumn string `json:"actual_score_column"` + OutputClass ModelPredictionOutputClass `json:"output_class" validate:"required"` +} diff --git a/api/models/service.go b/api/models/service.go index 4171470ee..1b9b3575d 100644 --- a/api/models/service.go +++ b/api/models/service.go @@ -53,6 +53,7 @@ type Service struct { // CurrentIsvcName is the name of the current running/serving InferenceService's revision CurrentIsvcName string EnabledModelObservability bool + ModelSchema *ModelSchema } func NewService(model *Model, version *Version, modelOpt *ModelOption, endpoint *VersionEndpoint) *Service { @@ -81,6 +82,7 @@ func NewService(model *Model, version *Version, modelOpt *ModelOption, endpoint Protocol: endpoint.Protocol, CurrentIsvcName: endpoint.InferenceServiceName, EnabledModelObservability: endpoint.EnableModelObservability, + ModelSchema: version.ModelSchema, } } diff --git a/api/models/version.go b/api/models/version.go index 333c49de4..4336c74ed 100644 --- a/api/models/version.go +++ b/api/models/version.go @@ -30,6 +30,8 @@ type Version struct { MlflowURL string `json:"mlflow_url" gorm:"-"` ArtifactURI string `json:"artifact_uri" gorm:"artifact_uri"` Endpoints []*VersionEndpoint `json:"endpoints" gorm:"foreignkey:VersionID,VersionModelID;references:ID,ModelID;"` + ModelSchemaID *ID `json:"-"` + ModelSchema *ModelSchema `json:"model_schema" gorm:"foreignkey:ModelSchemaID;"` Properties KV `json:"properties" gorm:"properties"` Labels KV `json:"labels" gorm:"labels"` PythonVersion string `json:"python_version" gorm:"python_version"` diff --git a/api/pkg/errors/errors.go b/api/pkg/errors/errors.go index b17a8f796..010e3693a 100644 --- a/api/pkg/errors/errors.go +++ b/api/pkg/errors/errors.go @@ -6,28 +6,39 @@ import ( ) var ( - InvalidInputError error = errors.New("invalid input") - DeadlineExceededError error = errors.New("deadline exceeded") + ErrInvalidInput error = errors.New("invalid input") + ErrDeadlineExceeded error = errors.New("deadline exceeded") + ErrNotFound error = errors.New("not found") ) // NewInvalidInputError create new InvalidInputError with specified reason // errors.Is(error, InvalidInputError) will return true if a new error is created using this function func NewInvalidInputError(reason string) error { - return fmt.Errorf("%w: %s", InvalidInputError, reason) + return fmt.Errorf("%w: %s", ErrInvalidInput, reason) } // NewInvalidInputErrorf create new InvalidInputError with specified reason string format // errors.Is(error, InvalidInputError) will return true if a new error is created using this function func NewInvalidInputErrorf(reasonFormat string, a ...interface{}) error { - return fmt.Errorf("%w: %s", InvalidInputError, fmt.Sprintf(reasonFormat, a...)) + return fmt.Errorf("%w: %s", ErrInvalidInput, fmt.Sprintf(reasonFormat, a...)) } // NewDeadlineExceededError create new DeadlineExceededError with specified reason func NewDeadlineExceededError(reason string) error { - return fmt.Errorf("%w: %s", DeadlineExceededError, reason) + return fmt.Errorf("%w: %s", ErrDeadlineExceeded, reason) } // NewDeadlineExceededErrorf create new DeadlineExceededError with specified reason string format func NewDeadlineExceededErrorf(reasonFormat string, a ...interface{}) error { - return fmt.Errorf("%w: %s", DeadlineExceededError, fmt.Sprintf(reasonFormat, a...)) + return fmt.Errorf("%w: %s", ErrDeadlineExceeded, fmt.Sprintf(reasonFormat, a...)) +} + +// NotFoundError create new NotFoundError with specified reason +func NewNotFoundError(reason string) error { + return fmt.Errorf("%w: %s", ErrNotFound, reason) +} + +// NewNotFoundErrorf create new NotFoundError with specified reason string format +func NewNotfoundErrorf(reasonFormat string, a ...interface{}) error { + return fmt.Errorf("%w: %s", ErrNotFound, fmt.Sprintf(reasonFormat, a...)) } diff --git a/api/pkg/transformer/server/grpc/server.go b/api/pkg/transformer/server/grpc/server.go index ab7061da1..56ef595c9 100644 --- a/api/pkg/transformer/server/grpc/server.go +++ b/api/pkg/transformer/server/grpc/server.go @@ -352,9 +352,9 @@ func getGRPCCode(err error) codes.Code { return statusErr.Code() } - if errors.Is(err, mErrors.InvalidInputError) { + if errors.Is(err, mErrors.ErrInvalidInput) { return codes.InvalidArgument - } else if errors.Is(err, mErrors.DeadlineExceededError) { + } else if errors.Is(err, mErrors.ErrDeadlineExceeded) { return codes.DeadlineExceeded } return codes.Internal diff --git a/api/pkg/transformer/server/rest/server.go b/api/pkg/transformer/server/rest/server.go index 78e0c4ba1..9866efebf 100644 --- a/api/pkg/transformer/server/rest/server.go +++ b/api/pkg/transformer/server/rest/server.go @@ -178,7 +178,7 @@ func (s *HTTPServer) PredictHandler(w http.ResponseWriter, r *http.Request) { } func responseCodeFromError(err error) int { - if errors.Is(err, mErrors.InvalidInputError) { + if errors.Is(err, mErrors.ErrInvalidInput) { return http.StatusBadRequest } return http.StatusInternalServerError diff --git a/api/service/mocks/model_schema_service.go b/api/service/mocks/model_schema_service.go new file mode 100644 index 000000000..e83843261 --- /dev/null +++ b/api/service/mocks/model_schema_service.go @@ -0,0 +1,137 @@ +// Code generated by mockery v2.39.2. DO NOT EDIT. + +package mocks + +import ( + context "context" + + models "github.com/caraml-dev/merlin/models" + mock "github.com/stretchr/testify/mock" +) + +// ModelSchemaService is an autogenerated mock type for the ModelSchemaService type +type ModelSchemaService struct { + mock.Mock +} + +// Delete provides a mock function with given fields: ctx, modelSchema +func (_m *ModelSchemaService) Delete(ctx context.Context, modelSchema *models.ModelSchema) error { + ret := _m.Called(ctx, modelSchema) + + if len(ret) == 0 { + panic("no return value specified for Delete") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) error); ok { + r0 = rf(ctx, modelSchema) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// FindByID provides a mock function with given fields: ctx, modelSchemaID, modelID +func (_m *ModelSchemaService) FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) { + ret := _m.Called(ctx, modelSchemaID, modelID) + + if len(ret) == 0 { + panic("no return value specified for FindByID") + } + + var r0 *models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, models.ID, models.ID) (*models.ModelSchema, error)); ok { + return rf(ctx, modelSchemaID, modelID) + } + if rf, ok := ret.Get(0).(func(context.Context, models.ID, models.ID) *models.ModelSchema); ok { + r0 = rf(ctx, modelSchemaID, modelID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, models.ID, models.ID) error); ok { + r1 = rf(ctx, modelSchemaID, modelID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// List provides a mock function with given fields: ctx, modelID +func (_m *ModelSchemaService) List(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) { + ret := _m.Called(ctx, modelID) + + if len(ret) == 0 { + panic("no return value specified for List") + } + + var r0 []*models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, models.ID) ([]*models.ModelSchema, error)); ok { + return rf(ctx, modelID) + } + if rf, ok := ret.Get(0).(func(context.Context, models.ID) []*models.ModelSchema); ok { + r0 = rf(ctx, modelID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, models.ID) error); ok { + r1 = rf(ctx, modelID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Save provides a mock function with given fields: ctx, modelSchema +func (_m *ModelSchemaService) Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) { + ret := _m.Called(ctx, modelSchema) + + if len(ret) == 0 { + panic("no return value specified for Save") + } + + var r0 *models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) (*models.ModelSchema, error)); ok { + return rf(ctx, modelSchema) + } + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) *models.ModelSchema); ok { + r0 = rf(ctx, modelSchema) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *models.ModelSchema) error); ok { + r1 = rf(ctx, modelSchema) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewModelSchemaService creates a new instance of ModelSchemaService. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewModelSchemaService(t interface { + mock.TestingT + Cleanup(func()) +}) *ModelSchemaService { + mock := &ModelSchemaService{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/api/service/model_schema_service.go b/api/service/model_schema_service.go new file mode 100644 index 000000000..a9ee82100 --- /dev/null +++ b/api/service/model_schema_service.go @@ -0,0 +1,55 @@ +package service + +import ( + "context" + "errors" + + "github.com/caraml-dev/merlin/models" + mErrors "github.com/caraml-dev/merlin/pkg/errors" + "github.com/caraml-dev/merlin/storage" + "gorm.io/gorm" +) + +type ModelSchemaService interface { + List(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) + Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) + Delete(ctx context.Context, modelSchema *models.ModelSchema) error + FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) +} + +type modelSchemaService struct { + modelSchemaStorage storage.ModelSchemaStorage +} + +func NewModelSchemaService(storage storage.ModelSchemaStorage) ModelSchemaService { + return &modelSchemaService{ + modelSchemaStorage: storage, + } +} + +func (m *modelSchemaService) List(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) { + schemas, err := m.modelSchemaStorage.FindAll(ctx, modelID) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, mErrors.NewNotfoundErrorf("model schema with model id: %d are not found", modelID) + } + return nil, err + } + return schemas, nil +} +func (m *modelSchemaService) Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) { + return m.modelSchemaStorage.Save(ctx, modelSchema) +} +func (m *modelSchemaService) Delete(ctx context.Context, modelSchema *models.ModelSchema) error { + return m.modelSchemaStorage.Delete(ctx, modelSchema) +} +func (m *modelSchemaService) FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) { + schema, err := m.modelSchemaStorage.FindByID(ctx, modelSchemaID, modelID) + if err != nil { + if errors.Is(err, gorm.ErrRecordNotFound) { + return nil, mErrors.NewNotfoundErrorf("model schema with id: %d are not found", modelSchemaID) + } + return nil, err + } + return schema, nil +} diff --git a/api/service/model_schema_service_test.go b/api/service/model_schema_service_test.go new file mode 100644 index 000000000..a77a0fcb1 --- /dev/null +++ b/api/service/model_schema_service_test.go @@ -0,0 +1,557 @@ +package service + +import ( + "context" + "errors" + "reflect" + "testing" + + "github.com/caraml-dev/merlin/models" + mErrors "github.com/caraml-dev/merlin/pkg/errors" + "github.com/caraml-dev/merlin/storage" + "github.com/caraml-dev/merlin/storage/mocks" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/mock" + "gorm.io/gorm" +) + +func Test_modelSchemaService_List(t *testing.T) { + type args struct { + ctx context.Context + modelID models.ID + } + tests := []struct { + name string + m storage.ModelSchemaStorage + args args + want []*models.ModelSchema + wantErr bool + expError error + }{ + { + name: "Success list model schemas", + m: func() storage.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("FindAll", mock.Anything, models.ID(1)).Return([]*models.ModelSchema{ + { + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + { + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, + }, nil) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelID: models.ID(1), + }, + want: []*models.ModelSchema{ + { + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + { + ModelID: models.ID(1), + ID: models.ID(2), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + }, + }, + }, + }, + }, + }, + { + name: "Not found", + m: func() storage.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("FindAll", mock.Anything, models.ID(1)).Return(nil, gorm.ErrRecordNotFound) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelID: models.ID(1), + }, + want: nil, + wantErr: true, + expError: mErrors.NewNotFoundError("model schema with model id: 1 are not found"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := &modelSchemaService{modelSchemaStorage: tt.m} + got, err := svc.List(tt.args.ctx, tt.args.modelID) + if tt.wantErr { + assert.Equal(t, tt.expError, err) + } + if (err != nil) != tt.wantErr { + t.Errorf("modelSchemaService.List() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("modelSchemaService.List() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_modelSchemaService_Save(t *testing.T) { + type args struct { + ctx context.Context + modelSchema *models.ModelSchema + } + tests := []struct { + name string + m storage.ModelSchemaStorage + args args + want *models.ModelSchema + wantErr bool + }{ + { + name: "Success create new", + m: func() *mocks.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }).Return(&models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, nil) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchema: &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + want: &models.ModelSchema{ + ID: models.ID(1), + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + { + name: "Failed save model schema", + m: func() *mocks.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("Save", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }).Return(nil, errors.New("foreign key violation")) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchema: &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + want: nil, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := &modelSchemaService{modelSchemaStorage: tt.m} + got, err := svc.Save(tt.args.ctx, tt.args.modelSchema) + if (err != nil) != tt.wantErr { + t.Errorf("modelSchemaService.Save() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("modelSchemaService.Save() = %v, want %v", got, tt.want) + } + }) + } +} + +func Test_modelSchemaService_Delete(t *testing.T) { + type args struct { + ctx context.Context + modelSchema *models.ModelSchema + } + tests := []struct { + name string + m storage.ModelSchemaStorage + args args + wantErr bool + }{ + { + name: "success", + m: func() *mocks.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("Delete", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }).Return(nil) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchema: &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + }, + { + name: "error", + m: func() *mocks.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("Delete", mock.Anything, &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }).Return(errors.New("db is disconnected")) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchema: &models.ModelSchema{ + ModelID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := &modelSchemaService{modelSchemaStorage: tt.m} + if err := svc.Delete(tt.args.ctx, tt.args.modelSchema); (err != nil) != tt.wantErr { + t.Errorf("modelSchemaService.Delete() error = %v, wantErr %v", err, tt.wantErr) + } + }) + } +} + +func Test_modelSchemaService_FindByID(t *testing.T) { + type args struct { + ctx context.Context + modelSchemaID models.ID + modelID models.ID + } + tests := []struct { + name string + m storage.ModelSchemaStorage + args args + want *models.ModelSchema + wantErr bool + expError error + }{ + { + name: "Success get model schema", + m: func() storage.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("FindByID", mock.Anything, models.ID(1), models.ID(1)).Return(&models.ModelSchema{ + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, nil) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchemaID: models.ID(1), + modelID: models.ID(1), + }, + want: &models.ModelSchema{ + ModelID: models.ID(1), + ID: models.ID(1), + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Boolean, + "featureC": models.Int64, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionScoreColumn: "prediction_score", + PredictionLabelColumn: "prediction_label", + }, + }, + }, + }, + }, + { + name: "Schema not found", + m: func() storage.ModelSchemaStorage { + storageMock := &mocks.ModelSchemaStorage{} + storageMock.On("FindByID", mock.Anything, models.ID(1), models.ID(1)).Return(nil, gorm.ErrRecordNotFound) + return storageMock + }(), + args: args{ + ctx: context.TODO(), + modelSchemaID: models.ID(1), + modelID: models.ID(1), + }, + want: nil, + wantErr: true, + expError: mErrors.NewNotFoundError("model schema with id: 1 are not found"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + svc := &modelSchemaService{ + modelSchemaStorage: tt.m, + } + got, err := svc.FindByID(tt.args.ctx, tt.args.modelSchemaID, tt.args.modelID) + if tt.wantErr { + assert.Equal(t, tt.expError, err) + } + if (err != nil) != tt.wantErr { + t.Errorf("modelSchemaService.FindByID() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("modelSchemaService.FindByID() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/api/service/version_service.go b/api/service/version_service.go index 360bca313..79a697c2d 100644 --- a/api/service/version_service.go +++ b/api/service/version_service.go @@ -67,6 +67,7 @@ func (service *versionsService) query() *gorm.DB { Joins("JOIN environments on environments.name = version_endpoints.environment_name") }). Preload("Model"). + Preload("ModelSchema"). Joins("JOIN models on models.id = versions.model_id") } diff --git a/api/storage/mocks/model_schema_storage.go b/api/storage/mocks/model_schema_storage.go new file mode 100644 index 000000000..65a500419 --- /dev/null +++ b/api/storage/mocks/model_schema_storage.go @@ -0,0 +1,137 @@ +// Code generated by mockery v2.39.2. DO NOT EDIT. + +package mocks + +import ( + context "context" + + models "github.com/caraml-dev/merlin/models" + mock "github.com/stretchr/testify/mock" +) + +// ModelSchemaStorage is an autogenerated mock type for the ModelSchemaStorage type +type ModelSchemaStorage struct { + mock.Mock +} + +// Delete provides a mock function with given fields: ctx, modelSchema +func (_m *ModelSchemaStorage) Delete(ctx context.Context, modelSchema *models.ModelSchema) error { + ret := _m.Called(ctx, modelSchema) + + if len(ret) == 0 { + panic("no return value specified for Delete") + } + + var r0 error + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) error); ok { + r0 = rf(ctx, modelSchema) + } else { + r0 = ret.Error(0) + } + + return r0 +} + +// FindAll provides a mock function with given fields: ctx, modelID +func (_m *ModelSchemaStorage) FindAll(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) { + ret := _m.Called(ctx, modelID) + + if len(ret) == 0 { + panic("no return value specified for FindAll") + } + + var r0 []*models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, models.ID) ([]*models.ModelSchema, error)); ok { + return rf(ctx, modelID) + } + if rf, ok := ret.Get(0).(func(context.Context, models.ID) []*models.ModelSchema); ok { + r0 = rf(ctx, modelID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).([]*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, models.ID) error); ok { + r1 = rf(ctx, modelID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// FindByID provides a mock function with given fields: ctx, modelSchemaID, modelID +func (_m *ModelSchemaStorage) FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) { + ret := _m.Called(ctx, modelSchemaID, modelID) + + if len(ret) == 0 { + panic("no return value specified for FindByID") + } + + var r0 *models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, models.ID, models.ID) (*models.ModelSchema, error)); ok { + return rf(ctx, modelSchemaID, modelID) + } + if rf, ok := ret.Get(0).(func(context.Context, models.ID, models.ID) *models.ModelSchema); ok { + r0 = rf(ctx, modelSchemaID, modelID) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, models.ID, models.ID) error); ok { + r1 = rf(ctx, modelSchemaID, modelID) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// Save provides a mock function with given fields: ctx, modelSchema +func (_m *ModelSchemaStorage) Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) { + ret := _m.Called(ctx, modelSchema) + + if len(ret) == 0 { + panic("no return value specified for Save") + } + + var r0 *models.ModelSchema + var r1 error + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) (*models.ModelSchema, error)); ok { + return rf(ctx, modelSchema) + } + if rf, ok := ret.Get(0).(func(context.Context, *models.ModelSchema) *models.ModelSchema); ok { + r0 = rf(ctx, modelSchema) + } else { + if ret.Get(0) != nil { + r0 = ret.Get(0).(*models.ModelSchema) + } + } + + if rf, ok := ret.Get(1).(func(context.Context, *models.ModelSchema) error); ok { + r1 = rf(ctx, modelSchema) + } else { + r1 = ret.Error(1) + } + + return r0, r1 +} + +// NewModelSchemaStorage creates a new instance of ModelSchemaStorage. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations. +// The first argument is typically a *testing.T value. +func NewModelSchemaStorage(t interface { + mock.TestingT + Cleanup(func()) +}) *ModelSchemaStorage { + mock := &ModelSchemaStorage{} + mock.Mock.Test(t) + + t.Cleanup(func() { mock.AssertExpectations(t) }) + + return mock +} diff --git a/api/storage/model_schema_storage.go b/api/storage/model_schema_storage.go new file mode 100644 index 000000000..f7833f086 --- /dev/null +++ b/api/storage/model_schema_storage.go @@ -0,0 +1,45 @@ +package storage + +import ( + "context" + + "github.com/caraml-dev/merlin/models" + "gorm.io/gorm" +) + +type ModelSchemaStorage interface { + Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) + FindAll(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) + FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) + Delete(ctx context.Context, modelSchema *models.ModelSchema) error +} + +type modelSchemaStorage struct { + db *gorm.DB +} + +func NewModelSchemaStorage(db *gorm.DB) ModelSchemaStorage { + return &modelSchemaStorage{db: db} +} + +func (m *modelSchemaStorage) Save(ctx context.Context, modelSchema *models.ModelSchema) (*models.ModelSchema, error) { + if err := m.db.Save(modelSchema).Error; err != nil { + return nil, err + } + return modelSchema, nil +} +func (m *modelSchemaStorage) FindAll(ctx context.Context, modelID models.ID) ([]*models.ModelSchema, error) { + var schemas []*models.ModelSchema + err := m.db.Where("model_id = ?", modelID).Order("id asc").Find(&schemas).Error + return schemas, err +} +func (m *modelSchemaStorage) FindByID(ctx context.Context, modelSchemaID models.ID, modelID models.ID) (*models.ModelSchema, error) { + var modelSchema *models.ModelSchema + if err := m.db.Where("id = ? AND model_id = ?", modelSchemaID, modelID).First(&modelSchema).Error; err != nil { + return nil, err + } + return modelSchema, nil +} +func (m *modelSchemaStorage) Delete(ctx context.Context, modelSchema *models.ModelSchema) error { + return m.db.Delete(modelSchema).Error +} diff --git a/api/storage/model_schema_storage_test.go b/api/storage/model_schema_storage_test.go new file mode 100644 index 000000000..c81080f96 --- /dev/null +++ b/api/storage/model_schema_storage_test.go @@ -0,0 +1,369 @@ +//go:build integration_local || integration +// +build integration_local integration + +package storage + +import ( + "context" + "testing" + + "github.com/caraml-dev/merlin/database" + "github.com/caraml-dev/merlin/mlp" + "github.com/caraml-dev/merlin/models" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "gorm.io/gorm" +) + +func Test_modelSchemaStorage_Save(t *testing.T) { + database.WithTestDatabase(t, func(t *testing.T, db *gorm.DB) { + env1 := models.Environment{ + Name: "env1", + Cluster: "k8s", + IsPredictionJobEnabled: true, + } + db.Create(&env1) + + p := mlp.Project{ + ID: 1, + Name: "project", + MLFlowTrackingURL: "http://mlflow:5000", + } + + m := models.Model{ + ID: 1, + ProjectID: models.ID(p.ID), + ExperimentID: 1, + Name: "model", + Type: models.ModelTypeSkLearn, + } + db.Create(&m) + + modelSchemaStorage := NewModelSchemaStorage(db) + modelSchema := &models.ModelSchema{ + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, + }, + } + schema, err := modelSchemaStorage.Save(context.Background(), modelSchema) + require.NoError(t, err) + assert.Equal(t, models.ID(1), schema.ID) + + schema.Spec.ModelPredictionOutput = &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + } + _, err = modelSchemaStorage.Save(context.Background(), schema) + require.NoError(t, err) + newSchema, err := modelSchemaStorage.FindByID(context.Background(), models.ID(1), m.ID) + require.NoError(t, err) + assert.Equal(t, newSchema.Spec.ModelPredictionOutput, &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }) + }) +} + +func Test_modelSchemaStorage_SaveThroughVersion(t *testing.T) { + database.WithTestDatabase(t, func(t *testing.T, db *gorm.DB) { + env1 := models.Environment{ + Name: "env1", + Cluster: "k8s", + IsPredictionJobEnabled: true, + } + db.Create(&env1) + + p := mlp.Project{ + ID: 1, + Name: "project", + MLFlowTrackingURL: "http://mlflow:5000", + } + + m := models.Model{ + ID: 1, + ProjectID: models.ID(p.ID), + ExperimentID: 1, + Name: "model", + Type: models.ModelTypeSkLearn, + } + db.Create(&m) + + version := &models.Version{ + ID: models.ID(1), + ModelID: m.ID, + Model: &m, + MlflowURL: "http://mlflow.com", + ModelSchema: &models.ModelSchema{ + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, + }, + }, + } + err := db.Save(&version).Error + require.NoError(t, err) + + modelSchemaStorage := NewModelSchemaStorage(db) + newSchema, err := modelSchemaStorage.FindByID(context.Background(), models.ID(1), m.ID) + require.NoError(t, err) + + assert.Equal(t, &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, newSchema.Spec.ModelPredictionOutput) + var versions []*models.Version + db.Preload("Model").Preload("ModelSchema").Where("model_id = ?", m.ID).Find(&versions) + assert.Equal(t, 1, len(versions)) + assert.Equal(t, models.ID(1), newSchema.ID) + assert.Equal(t, &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, versions[0].ModelSchema.Spec.ModelPredictionOutput) + }) +} + +func Test_modelSchemaStorage_FindAll_Delete(t *testing.T) { + database.WithTestDatabase(t, func(t *testing.T, db *gorm.DB) { + env1 := models.Environment{ + Name: "env1", + Cluster: "k8s", + IsPredictionJobEnabled: true, + } + db.Create(&env1) + + p := mlp.Project{ + ID: 1, + Name: "project", + MLFlowTrackingURL: "http://mlflow:5000", + } + + m := models.Model{ + ID: 1, + ProjectID: models.ID(p.ID), + ExperimentID: 1, + Name: "model", + Type: models.ModelTypeSkLearn, + } + db.Create(&m) + + modelSchemaStorage := NewModelSchemaStorage(db) + modelSchemas := []*models.ModelSchema{ + { + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, + }, + }, + { + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }, + }, + }, + { + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + RegressionOutput: &models.RegressionOutput{ + PredictionScoreColumn: "prediction_score", + ActualScoreColumn: "actual_score", + OutputClass: models.Regression, + }, + }, + }, + }, + } + + for _, schema := range modelSchemas { + _, err := modelSchemaStorage.Save(context.Background(), schema) + require.NoError(t, err) + } + + allSchemas, err := modelSchemaStorage.FindAll(context.Background(), m.ID) + require.NoError(t, err) + assert.Equal(t, len(modelSchemas), len(allSchemas)) + for idx, schema := range allSchemas { + assert.Equal(t, modelSchemas[idx], schema) + } + + err = modelSchemaStorage.Delete(context.Background(), &models.ModelSchema{ID: 1, ModelID: m.ID}) + require.NoError(t, err) + + allSchemas, err = modelSchemaStorage.FindAll(context.Background(), m.ID) + require.NoError(t, err) + assert.Equal(t, 2, len(allSchemas)) + }) +} + +func Test_modelSchemaStorage_FindByID(t *testing.T) { + database.WithTestDatabase(t, func(t *testing.T, db *gorm.DB) { + env1 := models.Environment{ + Name: "env1", + Cluster: "k8s", + IsPredictionJobEnabled: true, + } + db.Create(&env1) + + p := mlp.Project{ + ID: 1, + Name: "project", + MLFlowTrackingURL: "http://mlflow:5000", + } + + m := models.Model{ + ID: 1, + ProjectID: models.ID(p.ID), + ExperimentID: 1, + Name: "model", + Type: models.ModelTypeSkLearn, + } + db.Create(&m) + + modelSchemaStorage := NewModelSchemaStorage(db) + modelSchema := &models.ModelSchema{ + ModelID: m.ID, + Spec: &models.SchemaSpec{ + PredictionIDColumn: "prediction_id", + TagColumns: []string{"tag"}, + FeatureTypes: map[string]models.ValueType{ + "featureA": models.Float64, + "featureB": models.Float64, + "featureC": models.Int64, + "featureD": models.Boolean, + }, + ModelPredictionOutput: &models.ModelPredictionOutput{ + BinaryClassificationOutput: &models.BinaryClassificationOutput{ + ActualLabelColumn: "actual_label", + NegativeClassLabel: "negative", + PositiveClassLabel: "positive", + PredictionLabelColumn: "prediction_label", + PredictionScoreColumn: "prediction_score", + OutputClass: models.BinaryClassification, + }, + }, + }, + } + schema, err := modelSchemaStorage.Save(context.Background(), modelSchema) + require.NoError(t, err) + assert.Equal(t, models.ID(1), schema.ID) + + schema.Spec.ModelPredictionOutput = &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + } + _, err = modelSchemaStorage.Save(context.Background(), schema) + require.NoError(t, err) + newSchema, err := modelSchemaStorage.FindByID(context.Background(), models.ID(1), m.ID) + require.NoError(t, err) + assert.Equal(t, newSchema.Spec.ModelPredictionOutput, &models.ModelPredictionOutput{ + RankingOutput: &models.RankingOutput{ + PredictionGroudIDColumn: "session_id", + RankScoreColumn: "score", + RelevanceScoreColumn: "relevance_score", + OutputClass: models.Ranking, + }, + }) + + schema, err = modelSchemaStorage.FindByID(context.Background(), models.ID(2), m.ID) + require.Equal(t, gorm.ErrRecordNotFound, err) + }) +} diff --git a/db-migrations/36_model_schemas.down.sql b/db-migrations/36_model_schemas.down.sql new file mode 100644 index 000000000..4b1eed7e4 --- /dev/null +++ b/db-migrations/36_model_schemas.down.sql @@ -0,0 +1,2 @@ +ALTER TABLE versions DROP column model_schema_id; +DROP TABLE model_schemas; \ No newline at end of file diff --git a/db-migrations/36_model_schemas.up.sql b/db-migrations/36_model_schemas.up.sql new file mode 100644 index 000000000..0e90f64b5 --- /dev/null +++ b/db-migrations/36_model_schemas.up.sql @@ -0,0 +1,13 @@ +CREATE TABLE IF NOT EXISTS model_schemas +( + id serial PRIMARY KEY, + model_id integer, + spec JSONB NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + CONSTRAINT model_schemas_model_fkey + FOREIGN KEY (model_id) REFERENCES models (id) +); + +CREATE INDEX model_schemas_model_id_idx ON model_schemas(model_id); +ALTER TABLE versions ADD COLUMN model_schema_id integer REFERENCES model_schemas (id); \ No newline at end of file diff --git a/openapi-api-codegen.yaml b/openapi-api-codegen.yaml new file mode 100644 index 000000000..915f83148 --- /dev/null +++ b/openapi-api-codegen.yaml @@ -0,0 +1,8 @@ +packageName: client +enumClassPrefix: true +# Global Properties +globalProperties: + apiTests: false + modelTests: false + apiDocs: false + modelDocs: false \ No newline at end of file diff --git a/openapi-sdk-codegen.yaml b/openapi-sdk-codegen.yaml new file mode 100644 index 000000000..2c6461cb7 --- /dev/null +++ b/openapi-sdk-codegen.yaml @@ -0,0 +1,9 @@ +projectName: merlin-sdk +packageName: client +generateSourceCodeOnly: true +# Global Properties +globalProperties: + apiTests: false + modelTests: false + apiDocs: false + modelDocs: false \ No newline at end of file diff --git a/python/pyfunc-server/pyfuncserver/config.py b/python/pyfunc-server/pyfuncserver/config.py index 26a15ee2e..28f726222 100644 --- a/python/pyfunc-server/pyfuncserver/config.py +++ b/python/pyfunc-server/pyfuncserver/config.py @@ -5,6 +5,7 @@ from merlin.protocol import Protocol from dataclasses import dataclass +from merlin.model_schema import ModelSchema # Following environment variables are expected to be populated by Merlin HTTP_PORT = ("CARAML_HTTP_PORT", 8080) @@ -13,6 +14,7 @@ MODEL_FULL_NAME = ("CARAML_MODEL_FULL_NAME", "model-1") PROJECT = ("CARAML_PROJECT", "project") PROTOCOL = ("CARAML_PROTOCOL", "HTTP_JSON") +MODEL_SCHEMA = "CARAML_MODEL_SCHEMA" WORKERS = ("WORKERS", 1) GRPC_PORT = ("CARAML_GRPC_PORT", 9000) @@ -32,6 +34,7 @@ PUBLISHER_SAMPLING_RATIO = ("PUBLISHER_SAMPLING_RATIO", 0.01) PUBLISHER_ENABLED = ("PUBLISHER_ENABLED", "false") + @dataclass class ModelManifest: """ @@ -42,6 +45,7 @@ class ModelManifest: model_full_name: str model_dir: str project: str + model_schema: ModelSchema = None class PushGateway: @@ -87,7 +91,17 @@ def __init__(self, model_dir: str): model_version = os.getenv(*MODEL_VERSION) model_full_name = os.getenv(*MODEL_FULL_NAME) project = os.getenv(*PROJECT) - self.model_manifest = ModelManifest(model_name, model_version, model_full_name, model_dir, project) + model_schema = None + model_schema_from_env_var = os.getenv(MODEL_SCHEMA) + if model_schema_from_env_var is not None: + model_schema = ModelSchema.from_json(os.getenv(MODEL_SCHEMA)) + + self.model_manifest = ModelManifest(model_name=model_name, + model_version=model_version, + model_full_name=model_full_name, + model_dir=model_dir, + project=project, + model_schema=model_schema) self.workers = int(os.getenv(*WORKERS)) self.log_level = self._log_level() @@ -102,6 +116,7 @@ def __init__(self, model_dir: str): push_url, push_interval) + # Publisher self.publisher = None publisher_enabled = str_to_bool(os.getenv(*PUBLISHER_ENABLED)) diff --git a/python/sdk/.gitignore b/python/sdk/.gitignore index 85790619c..0bc7ead62 100644 --- a/python/sdk/.gitignore +++ b/python/sdk/.gitignore @@ -75,3 +75,4 @@ docs/mlruns # swagger-codegen swagger-codegen-cli.jar +.openapi-generator/ diff --git a/python/sdk/.openapi-generator-ignore b/python/sdk/.openapi-generator-ignore new file mode 100644 index 000000000..7484ee590 --- /dev/null +++ b/python/sdk/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/python/sdk/Makefile b/python/sdk/Makefile index fdccc7bec..e74b0e95e 100644 --- a/python/sdk/Makefile +++ b/python/sdk/Makefile @@ -4,7 +4,7 @@ setup: .PHONY: type-check type-check: - @pipenv run mypy --ignore-missing-imports --allow-untyped-globals --implicit-optional merlin + @pipenv run mypy --ignore-missing-imports --allow-untyped-globals --implicit-optional merlin --follow-imports silent .PHONY: test test: type-check diff --git a/python/sdk/client/__init__.py b/python/sdk/client/__init__.py index 9aa7d5af9..90fec4ada 100644 --- a/python/sdk/client/__init__.py +++ b/python/sdk/client/__init__.py @@ -5,14 +5,16 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" -from __future__ import absolute_import +__version__ = "1.0.0" # import apis into sdk package from client.api.alert_api import AlertApi @@ -20,19 +22,30 @@ from client.api.environment_api import EnvironmentApi from client.api.log_api import LogApi from client.api.model_endpoints_api import ModelEndpointsApi +from client.api.model_schema_api import ModelSchemaApi from client.api.models_api import ModelsApi from client.api.prediction_jobs_api import PredictionJobsApi from client.api.project_api import ProjectApi from client.api.secret_api import SecretApi from client.api.standard_transformer_api import StandardTransformerApi from client.api.version_api import VersionApi + # import ApiClient +from client.api_response import ApiResponse from client.api_client import ApiClient from client.configuration import Configuration +from client.exceptions import OpenApiException +from client.exceptions import ApiTypeError +from client.exceptions import ApiValueError +from client.exceptions import ApiKeyError +from client.exceptions import ApiAttributeError +from client.exceptions import ApiException + # import models into sdk package from client.models.alert_condition_metric_type import AlertConditionMetricType from client.models.alert_condition_severity import AlertConditionSeverity from client.models.autoscaling_policy import AutoscalingPolicy +from client.models.binary_classification_output import BinaryClassificationOutput from client.models.config import Config from client.models.container import Container from client.models.custom_predictor import CustomPredictor @@ -41,7 +54,6 @@ from client.models.env_var import EnvVar from client.models.environment import Environment from client.models.file_format import FileFormat -from client.models.free_form_object import FreeFormObject from client.models.gpu_config import GPUConfig from client.models.gpu_toleration import GPUToleration from client.models.label import Label @@ -57,9 +69,11 @@ from client.models.model_endpoint_rule import ModelEndpointRule from client.models.model_endpoint_rule_destination import ModelEndpointRuleDestination from client.models.model_prediction_config import ModelPredictionConfig +from client.models.model_prediction_output import ModelPredictionOutput +from client.models.model_prediction_output_class import ModelPredictionOutputClass +from client.models.model_schema import ModelSchema from client.models.operation_tracing import OperationTracing from client.models.pipeline_tracing import PipelineTracing -from client.models.pipeline_tracing_inner import PipelineTracingInner from client.models.prediction_job import PredictionJob from client.models.prediction_job_config import PredictionJobConfig from client.models.prediction_job_config_bigquery_sink import PredictionJobConfigBigquerySink @@ -72,12 +86,16 @@ from client.models.prediction_logger_config import PredictionLoggerConfig from client.models.project import Project from client.models.protocol import Protocol +from client.models.ranking_output import RankingOutput +from client.models.regression_output import RegressionOutput from client.models.resource_request import ResourceRequest from client.models.result_type import ResultType from client.models.save_mode import SaveMode +from client.models.schema_spec import SchemaSpec from client.models.secret import Secret from client.models.standard_transformer_simulation_request import StandardTransformerSimulationRequest from client.models.standard_transformer_simulation_response import StandardTransformerSimulationResponse from client.models.transformer import Transformer +from client.models.value_type import ValueType from client.models.version import Version from client.models.version_endpoint import VersionEndpoint diff --git a/python/sdk/client/api/__init__.py b/python/sdk/client/api/__init__.py index e169af3ed..7c002f3c8 100644 --- a/python/sdk/client/api/__init__.py +++ b/python/sdk/client/api/__init__.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - # flake8: noqa # import apis into api package @@ -8,9 +6,11 @@ from client.api.environment_api import EnvironmentApi from client.api.log_api import LogApi from client.api.model_endpoints_api import ModelEndpointsApi +from client.api.model_schema_api import ModelSchemaApi from client.api.models_api import ModelsApi from client.api.prediction_jobs_api import PredictionJobsApi from client.api.project_api import ProjectApi from client.api.secret_api import SecretApi from client.api.standard_transformer_api import StandardTransformerApi from client.api.version_api import VersionApi + diff --git a/python/sdk/client/api/alert_api.py b/python/sdk/client/api/alert_api.py index a48289857..b83056cc7 100644 --- a/python/sdk/client/api/alert_api.py +++ b/python/sdk/client/api/alert_api.py @@ -3,520 +3,1382 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.model_endpoint_alert import ModelEndpointAlert from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class AlertApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class AlertApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def alerts_teams_get(self, **kwargs): # noqa: E501 - """Lists teams for alert notification channel. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.alerts_teams_get(async_req=True) - >>> result = thread.get() - - :param async_req bool - :return: list[str] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.alerts_teams_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.alerts_teams_get_with_http_info(**kwargs) # noqa: E501 - return data - - def alerts_teams_get_with_http_info(self, **kwargs): # noqa: E501 - """Lists teams for alert notification channel. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.alerts_teams_get_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :return: list[str] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = [] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method alerts_teams_get" % key - ) - params[key] = val - del params['kwargs'] - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/alerts/teams', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[str]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_alerts_get(self, model_id, **kwargs): # noqa: E501 - """Lists alerts for given model. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_alerts_get(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpointAlert] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_alerts_get_with_http_info(model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_alerts_get_with_http_info(model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_alerts_get_with_http_info(self, model_id, **kwargs): # noqa: E501 - """Lists alerts for given model. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_alerts_get_with_http_info(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpointAlert] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_alerts_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_alerts_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/alerts', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[ModelEndpointAlert]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_get(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Gets alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_get(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpointAlert - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Gets alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpointAlert - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_get`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ModelEndpointAlert', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_post(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_post(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_post`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_put(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_put(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_put`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def alerts_teams_get( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[str]: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def alerts_teams_get_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[str]]: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def alerts_teams_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _alerts_teams_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/alerts/teams', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_alerts_get( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ModelEndpointAlert]: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_alerts_get_with_http_info( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ModelEndpointAlert]]: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_alerts_get_without_preload_content( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_alerts_get_serialize( + self, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/alerts', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelEndpointAlert: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelEndpointAlert]: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + self, + model_id, + model_endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + self, + model_id, + model_endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + self, + model_id, + model_endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/endpoint_api.py b/python/sdk/client/api/endpoint_api.py index 114766ff3..3726cac40 100644 --- a/python/sdk/client/api/endpoint_api.py +++ b/python/sdk/client/api/endpoint_api.py @@ -3,681 +3,1786 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.container import Container +from client.models.version_endpoint import VersionEndpoint from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class EndpointApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class EndpointApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def models_model_id_versions_version_id_endpoint_endpoint_id_containers_get(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Get all container belong to a version endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_containers_get(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: Container - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_with_http_info(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Get all container belong to a version endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_with_http_info(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: Container - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_endpoint_id_containers_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_containers_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_containers_get`") # noqa: E501 - # verify the required parameter 'endpoint_id' is set - if ('endpoint_id' not in params or - params['endpoint_id'] is None): - raise ValueError("Missing the required parameter `endpoint_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_containers_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'endpoint_id' in params: - path_params['endpoint_id'] = params['endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}/containers', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Container', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_endpoint_endpoint_id_delete(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Undeploy the specified model version deployment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_delete(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_endpoint_id_delete_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_endpoint_id_delete_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_endpoint_id_delete_with_http_info(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Undeploy the specified model version deployment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_delete_with_http_info(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_endpoint_id_delete" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_delete`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_delete`") # noqa: E501 - # verify the required parameter 'endpoint_id' is set - if ('endpoint_id' not in params or - params['endpoint_id'] is None): - raise ValueError("Missing the required parameter `endpoint_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_delete`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'endpoint_id' in params: - path_params['endpoint_id'] = params['endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_endpoint_endpoint_id_get(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Get version endpoint resource # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_get(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_endpoint_id_get_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_endpoint_id_get_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_endpoint_id_get_with_http_info(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Get version endpoint resource # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_get_with_http_info(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_endpoint_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_get`") # noqa: E501 - # verify the required parameter 'endpoint_id' is set - if ('endpoint_id' not in params or - params['endpoint_id'] is None): - raise ValueError("Missing the required parameter `endpoint_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'endpoint_id' in params: - path_params['endpoint_id'] = params['endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='VersionEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_endpoint_endpoint_id_put(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Modify version endpoint, this API will redeploy the associated deployment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_put(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :param VersionEndpoint body: - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_endpoint_id_put_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_endpoint_id_put_with_http_info(model_id, version_id, endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_endpoint_id_put_with_http_info(self, model_id, version_id, endpoint_id, **kwargs): # noqa: E501 - """Modify version endpoint, this API will redeploy the associated deployment # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_endpoint_id_put_with_http_info(model_id, version_id, endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str endpoint_id: (required) - :param VersionEndpoint body: - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_endpoint_id_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_put`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_put`") # noqa: E501 - # verify the required parameter 'endpoint_id' is set - if ('endpoint_id' not in params or - params['endpoint_id'] is None): - raise ValueError("Missing the required parameter `endpoint_id` when calling `models_model_id_versions_version_id_endpoint_endpoint_id_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'endpoint_id' in params: - path_params['endpoint_id'] = params['endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='VersionEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_endpoint_get(self, model_id, version_id, **kwargs): # noqa: E501 - """List all endpoint of a model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_get(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: list[VersionEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_get_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """List all endpoint of a model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_get_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: list[VersionEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[VersionEndpoint]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_endpoint_post(self, model_id, version_id, **kwargs): # noqa: E501 - """Deploy specific version of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_post(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param VersionEndpoint body: - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_endpoint_post_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_endpoint_post_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_endpoint_post_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """Deploy specific version of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_endpoint_post_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param VersionEndpoint body: - :return: VersionEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_endpoint_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_endpoint_post`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_endpoint_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/endpoint', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='VersionEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_containers_get( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Container: + """Get all container belong to a version endpoint + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Container]: + """Get all container belong to a version endpoint + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get all container belong to a version endpoint + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_endpoint_id_containers_get_serialize( + self, + model_id, + version_id, + endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if endpoint_id is not None: + _path_params['endpoint_id'] = endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}/containers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_delete( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Undeploy the specified model version deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_delete_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_delete_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Undeploy the specified model version deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_delete_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_delete_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Undeploy the specified model version deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_delete_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_endpoint_id_delete_serialize( + self, + model_id, + version_id, + endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if endpoint_id is not None: + _path_params['endpoint_id'] = endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_get( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> VersionEndpoint: + """Get version endpoint resource + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[VersionEndpoint]: + """Get version endpoint resource + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get version endpoint resource + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_get_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_endpoint_id_get_serialize( + self, + model_id, + version_id, + endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if endpoint_id is not None: + _path_params['endpoint_id'] = endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_put( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> VersionEndpoint: + """Modify version endpoint, this API will redeploy the associated deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_put_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_put_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[VersionEndpoint]: + """Modify version endpoint, this API will redeploy the associated deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_put_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_endpoint_id_put_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + endpoint_id: StrictStr, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Modify version endpoint, this API will redeploy the associated deployment + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param endpoint_id: (required) + :type endpoint_id: str + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_endpoint_id_put_serialize( + model_id=model_id, + version_id=version_id, + endpoint_id=endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_endpoint_id_put_serialize( + self, + model_id, + version_id, + endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if endpoint_id is not None: + _path_params['endpoint_id'] = endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_endpoint_get( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[VersionEndpoint]: + """List all endpoint of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[VersionEndpoint]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[VersionEndpoint]]: + """List all endpoint of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[VersionEndpoint]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List all endpoint of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[VersionEndpoint]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_get_serialize( + self, + model_id, + version_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/endpoint', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_endpoint_post( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> VersionEndpoint: + """Deploy specific version of the models + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_endpoint_post_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[VersionEndpoint]: + """Deploy specific version of the models + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_endpoint_post_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[VersionEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Deploy specific version of the models + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: VersionEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_endpoint_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "VersionEndpoint", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_endpoint_post_serialize( + self, + model_id, + version_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/versions/{version_id}/endpoint', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/environment_api.py b/python/sdk/client/api/environment_api.py index 05bf89443..0c1cac546 100644 --- a/python/sdk/client/api/environment_api.py +++ b/python/sdk/client/api/environment_api.py @@ -3,122 +3,309 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import StrictStr + +from typing import List, Optional + +from client.models.environment import Environment from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class EnvironmentApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class EnvironmentApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def environments_get(self, **kwargs): # noqa: E501 - """List available environment # noqa: E501 - - Environment can be filtered by optional `name` parameter # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.environments_get(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :return: list[Environment] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.environments_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.environments_get_with_http_info(**kwargs) # noqa: E501 - return data - - def environments_get_with_http_info(self, **kwargs): # noqa: E501 - """List available environment # noqa: E501 - - Environment can be filtered by optional `name` parameter # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.environments_get_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :return: list[Environment] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['name'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method environments_get" % key - ) - params[key] = val - del params['kwargs'] - - collection_formats = {} - - path_params = {} - - query_params = [] - if 'name' in params: - query_params.append(('name', params['name'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/environments', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Environment]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def environments_get( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Environment]: + """List available environment + + Environment can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._environments_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Environment]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def environments_get_with_http_info( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Environment]]: + """List available environment + + Environment can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._environments_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Environment]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def environments_get_without_preload_content( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List available environment + + Environment can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._environments_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Environment]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _environments_get_serialize( + self, + name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/environments', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/log_api.py b/python/sdk/client/api/log_api.py index b6928f193..e500f72a4 100644 --- a/python/sdk/client/api/log_api.py +++ b/python/sdk/client/api/log_api.py @@ -3,192 +3,568 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated + +from pydantic import StrictStr, field_validator + +from typing import Optional -# python 2 and python 3 compatibility library -import six from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class LogApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class LogApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def logs_get(self, cluster, namespace, component_type, **kwargs): # noqa: E501 - """Retrieve log from a container # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.logs_get(cluster, namespace, component_type, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str cluster: (required) - :param str namespace: (required) - :param str component_type: (required) - :param str project_name: - :param str model_id: - :param str model_name: - :param str version_id: - :param str prediction_job_id: - :param str container_name: - :param str prefix: - :param str follow: - :param str previous: - :param str since_seconds: - :param str since_time: - :param str timestamps: - :param str tail_lines: - :param str limit_bytes: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.logs_get_with_http_info(cluster, namespace, component_type, **kwargs) # noqa: E501 - else: - (data) = self.logs_get_with_http_info(cluster, namespace, component_type, **kwargs) # noqa: E501 - return data - - def logs_get_with_http_info(self, cluster, namespace, component_type, **kwargs): # noqa: E501 - """Retrieve log from a container # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.logs_get_with_http_info(cluster, namespace, component_type, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str cluster: (required) - :param str namespace: (required) - :param str component_type: (required) - :param str project_name: - :param str model_id: - :param str model_name: - :param str version_id: - :param str prediction_job_id: - :param str container_name: - :param str prefix: - :param str follow: - :param str previous: - :param str since_seconds: - :param str since_time: - :param str timestamps: - :param str tail_lines: - :param str limit_bytes: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['cluster', 'namespace', 'component_type', 'project_name', 'model_id', 'model_name', 'version_id', 'prediction_job_id', 'container_name', 'prefix', 'follow', 'previous', 'since_seconds', 'since_time', 'timestamps', 'tail_lines', 'limit_bytes'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method logs_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'cluster' is set - if ('cluster' not in params or - params['cluster'] is None): - raise ValueError("Missing the required parameter `cluster` when calling `logs_get`") # noqa: E501 - # verify the required parameter 'namespace' is set - if ('namespace' not in params or - params['namespace'] is None): - raise ValueError("Missing the required parameter `namespace` when calling `logs_get`") # noqa: E501 - # verify the required parameter 'component_type' is set - if ('component_type' not in params or - params['component_type'] is None): - raise ValueError("Missing the required parameter `component_type` when calling `logs_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - if 'project_name' in params: - query_params.append(('project_name', params['project_name'])) # noqa: E501 - if 'model_id' in params: - query_params.append(('model_id', params['model_id'])) # noqa: E501 - if 'model_name' in params: - query_params.append(('model_name', params['model_name'])) # noqa: E501 - if 'version_id' in params: - query_params.append(('version_id', params['version_id'])) # noqa: E501 - if 'prediction_job_id' in params: - query_params.append(('prediction_job_id', params['prediction_job_id'])) # noqa: E501 - if 'cluster' in params: - query_params.append(('cluster', params['cluster'])) # noqa: E501 - if 'namespace' in params: - query_params.append(('namespace', params['namespace'])) # noqa: E501 - if 'component_type' in params: - query_params.append(('component_type', params['component_type'])) # noqa: E501 - if 'container_name' in params: - query_params.append(('container_name', params['container_name'])) # noqa: E501 - if 'prefix' in params: - query_params.append(('prefix', params['prefix'])) # noqa: E501 - if 'follow' in params: - query_params.append(('follow', params['follow'])) # noqa: E501 - if 'previous' in params: - query_params.append(('previous', params['previous'])) # noqa: E501 - if 'since_seconds' in params: - query_params.append(('since_seconds', params['since_seconds'])) # noqa: E501 - if 'since_time' in params: - query_params.append(('since_time', params['since_time'])) # noqa: E501 - if 'timestamps' in params: - query_params.append(('timestamps', params['timestamps'])) # noqa: E501 - if 'tail_lines' in params: - query_params.append(('tail_lines', params['tail_lines'])) # noqa: E501 - if 'limit_bytes' in params: - query_params.append(('limit_bytes', params['limit_bytes'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/logs', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def logs_get( + self, + cluster: StrictStr, + namespace: StrictStr, + component_type: StrictStr, + project_name: Optional[StrictStr] = None, + model_id: Optional[StrictStr] = None, + model_name: Optional[StrictStr] = None, + version_id: Optional[StrictStr] = None, + prediction_job_id: Optional[StrictStr] = None, + container_name: Optional[StrictStr] = None, + prefix: Optional[StrictStr] = None, + follow: Optional[StrictStr] = None, + previous: Optional[StrictStr] = None, + since_seconds: Optional[StrictStr] = None, + since_time: Optional[StrictStr] = None, + timestamps: Optional[StrictStr] = None, + tail_lines: Optional[StrictStr] = None, + limit_bytes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Retrieve log from a container + + + :param cluster: (required) + :type cluster: str + :param namespace: (required) + :type namespace: str + :param component_type: (required) + :type component_type: str + :param project_name: + :type project_name: str + :param model_id: + :type model_id: str + :param model_name: + :type model_name: str + :param version_id: + :type version_id: str + :param prediction_job_id: + :type prediction_job_id: str + :param container_name: + :type container_name: str + :param prefix: + :type prefix: str + :param follow: + :type follow: str + :param previous: + :type previous: str + :param since_seconds: + :type since_seconds: str + :param since_time: + :type since_time: str + :param timestamps: + :type timestamps: str + :param tail_lines: + :type tail_lines: str + :param limit_bytes: + :type limit_bytes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._logs_get_serialize( + cluster=cluster, + namespace=namespace, + component_type=component_type, + project_name=project_name, + model_id=model_id, + model_name=model_name, + version_id=version_id, + prediction_job_id=prediction_job_id, + container_name=container_name, + prefix=prefix, + follow=follow, + previous=previous, + since_seconds=since_seconds, + since_time=since_time, + timestamps=timestamps, + tail_lines=tail_lines, + limit_bytes=limit_bytes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def logs_get_with_http_info( + self, + cluster: StrictStr, + namespace: StrictStr, + component_type: StrictStr, + project_name: Optional[StrictStr] = None, + model_id: Optional[StrictStr] = None, + model_name: Optional[StrictStr] = None, + version_id: Optional[StrictStr] = None, + prediction_job_id: Optional[StrictStr] = None, + container_name: Optional[StrictStr] = None, + prefix: Optional[StrictStr] = None, + follow: Optional[StrictStr] = None, + previous: Optional[StrictStr] = None, + since_seconds: Optional[StrictStr] = None, + since_time: Optional[StrictStr] = None, + timestamps: Optional[StrictStr] = None, + tail_lines: Optional[StrictStr] = None, + limit_bytes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Retrieve log from a container + + + :param cluster: (required) + :type cluster: str + :param namespace: (required) + :type namespace: str + :param component_type: (required) + :type component_type: str + :param project_name: + :type project_name: str + :param model_id: + :type model_id: str + :param model_name: + :type model_name: str + :param version_id: + :type version_id: str + :param prediction_job_id: + :type prediction_job_id: str + :param container_name: + :type container_name: str + :param prefix: + :type prefix: str + :param follow: + :type follow: str + :param previous: + :type previous: str + :param since_seconds: + :type since_seconds: str + :param since_time: + :type since_time: str + :param timestamps: + :type timestamps: str + :param tail_lines: + :type tail_lines: str + :param limit_bytes: + :type limit_bytes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._logs_get_serialize( + cluster=cluster, + namespace=namespace, + component_type=component_type, + project_name=project_name, + model_id=model_id, + model_name=model_name, + version_id=version_id, + prediction_job_id=prediction_job_id, + container_name=container_name, + prefix=prefix, + follow=follow, + previous=previous, + since_seconds=since_seconds, + since_time=since_time, + timestamps=timestamps, + tail_lines=tail_lines, + limit_bytes=limit_bytes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def logs_get_without_preload_content( + self, + cluster: StrictStr, + namespace: StrictStr, + component_type: StrictStr, + project_name: Optional[StrictStr] = None, + model_id: Optional[StrictStr] = None, + model_name: Optional[StrictStr] = None, + version_id: Optional[StrictStr] = None, + prediction_job_id: Optional[StrictStr] = None, + container_name: Optional[StrictStr] = None, + prefix: Optional[StrictStr] = None, + follow: Optional[StrictStr] = None, + previous: Optional[StrictStr] = None, + since_seconds: Optional[StrictStr] = None, + since_time: Optional[StrictStr] = None, + timestamps: Optional[StrictStr] = None, + tail_lines: Optional[StrictStr] = None, + limit_bytes: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Retrieve log from a container + + + :param cluster: (required) + :type cluster: str + :param namespace: (required) + :type namespace: str + :param component_type: (required) + :type component_type: str + :param project_name: + :type project_name: str + :param model_id: + :type model_id: str + :param model_name: + :type model_name: str + :param version_id: + :type version_id: str + :param prediction_job_id: + :type prediction_job_id: str + :param container_name: + :type container_name: str + :param prefix: + :type prefix: str + :param follow: + :type follow: str + :param previous: + :type previous: str + :param since_seconds: + :type since_seconds: str + :param since_time: + :type since_time: str + :param timestamps: + :type timestamps: str + :param tail_lines: + :type tail_lines: str + :param limit_bytes: + :type limit_bytes: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._logs_get_serialize( + cluster=cluster, + namespace=namespace, + component_type=component_type, + project_name=project_name, + model_id=model_id, + model_name=model_name, + version_id=version_id, + prediction_job_id=prediction_job_id, + container_name=container_name, + prefix=prefix, + follow=follow, + previous=previous, + since_seconds=since_seconds, + since_time=since_time, + timestamps=timestamps, + tail_lines=tail_lines, + limit_bytes=limit_bytes, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _logs_get_serialize( + self, + cluster, + namespace, + component_type, + project_name, + model_id, + model_name, + version_id, + prediction_job_id, + container_name, + prefix, + follow, + previous, + since_seconds, + since_time, + timestamps, + tail_lines, + limit_bytes, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if project_name is not None: + + _query_params.append(('project_name', project_name)) + + if model_id is not None: + + _query_params.append(('model_id', model_id)) + + if model_name is not None: + + _query_params.append(('model_name', model_name)) + + if version_id is not None: + + _query_params.append(('version_id', version_id)) + + if prediction_job_id is not None: + + _query_params.append(('prediction_job_id', prediction_job_id)) + + if cluster is not None: + + _query_params.append(('cluster', cluster)) + + if namespace is not None: + + _query_params.append(('namespace', namespace)) + + if component_type is not None: + + _query_params.append(('component_type', component_type)) + + if container_name is not None: + + _query_params.append(('container_name', container_name)) + + if prefix is not None: + + _query_params.append(('prefix', prefix)) + + if follow is not None: + + _query_params.append(('follow', follow)) + + if previous is not None: + + _query_params.append(('previous', previous)) + + if since_seconds is not None: + + _query_params.append(('since_seconds', since_seconds)) + + if since_time is not None: + + _query_params.append(('since_time', since_time)) + + if timestamps is not None: + + _query_params.append(('timestamps', timestamps)) + + if tail_lines is not None: + + _query_params.append(('tail_lines', tail_lines)) + + if limit_bytes is not None: + + _query_params.append(('limit_bytes', limit_bytes)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/logs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/model_endpoints_api.py b/python/sdk/client/api/model_endpoints_api.py index eedbe468b..3415a839b 100644 --- a/python/sdk/client/api/model_endpoints_api.py +++ b/python/sdk/client/api/model_endpoints_api.py @@ -3,633 +3,1684 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import Field +from typing_extensions import Annotated +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.model_endpoint import ModelEndpoint from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class ModelEndpointsApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class ModelEndpointsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def models_model_id_endpoints_get(self, model_id, **kwargs): # noqa: E501 - """List model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_get(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_get_with_http_info(model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_get_with_http_info(model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_get_with_http_info(self, model_id, **kwargs): # noqa: E501 - """List model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_get_with_http_info(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[ModelEndpoint]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_delete(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Stop serving traffic to the model endpoint, then delete it. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_delete(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_delete_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_delete_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_delete_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Stop serving traffic to the model endpoint, then delete it. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_delete_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_delete" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_delete`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_delete`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_get(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Get a model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_get(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_get_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Get a model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_get_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_get`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ModelEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_put(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Update model endpoint data. Mainly used to update its rule. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_put(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpoint body: - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_put_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Update model endpoint data. Mainly used to update its rule. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_put_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpoint body: - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_put`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ModelEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_post(self, body, model_id, **kwargs): # noqa: E501 - """Create a model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_post(body, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param ModelEndpoint body: Model endpoint object that has to be added (required) - :param int model_id: (required) - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_post_with_http_info(body, model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_post_with_http_info(body, model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_post_with_http_info(self, body, model_id, **kwargs): # noqa: E501 - """Create a model endpoint # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_post_with_http_info(body, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param ModelEndpoint body: Model endpoint object that has to be added (required) - :param int model_id: (required) - :return: ModelEndpoint - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params or - params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `models_model_id_endpoints_post`") # noqa: E501 - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ModelEndpoint', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_model_endpoints_get(self, project_id, **kwargs): # noqa: E501 - """List existing model endpoints for all models in particular project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_model_endpoints_get(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Filter list of model endpoints by specific `project_id` (required) - :param str region: Filter list of model endpoints by specific environment's `region` - :return: list[ModelEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_model_endpoints_get_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_model_endpoints_get_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_model_endpoints_get_with_http_info(self, project_id, **kwargs): # noqa: E501 - """List existing model endpoints for all models in particular project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_model_endpoints_get_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Filter list of model endpoints by specific `project_id` (required) - :param str region: Filter list of model endpoints by specific environment's `region` - :return: list[ModelEndpoint] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'region'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_model_endpoints_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_model_endpoints_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - if 'region' in params: - query_params.append(('region', params['region'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/model_endpoints', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[ModelEndpoint]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def models_model_id_endpoints_get( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ModelEndpoint]: + """List model endpoint + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_get_with_http_info( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ModelEndpoint]]: + """List model endpoint + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_get_without_preload_content( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List model endpoint + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_get_serialize( + self, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/endpoints', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_delete( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Stop serving traffic to the model endpoint, then delete it. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_delete_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_delete_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Stop serving traffic to the model endpoint, then delete it. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_delete_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_delete_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Stop serving traffic to the model endpoint, then delete it. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_delete_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_delete_serialize( + self, + model_id, + model_endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_get( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelEndpoint: + """Get a model endpoint + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_get_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelEndpoint]: + """Get a model endpoint + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_get_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get a model endpoint + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_get_serialize( + self, + model_id, + model_endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_put( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + body: Optional[ModelEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelEndpoint: + """Update model endpoint data. Mainly used to update its rule. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param body: + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_put_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + body: Optional[ModelEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelEndpoint]: + """Update model endpoint data. Mainly used to update its rule. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param body: + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_put_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictInt, + body: Optional[ModelEndpoint] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update model endpoint data. Mainly used to update its rule. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: int + :param body: + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_put_serialize( + self, + model_id, + model_endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_post( + self, + model_id: StrictInt, + body: Annotated[ModelEndpoint, Field(description="Model endpoint object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelEndpoint: + """Create a model endpoint + + + :param model_id: (required) + :type model_id: int + :param body: Model endpoint object that has to be added (required) + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_post_with_http_info( + self, + model_id: StrictInt, + body: Annotated[ModelEndpoint, Field(description="Model endpoint object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelEndpoint]: + """Create a model endpoint + + + :param model_id: (required) + :type model_id: int + :param body: Model endpoint object that has to be added (required) + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_post_without_preload_content( + self, + model_id: StrictInt, + body: Annotated[ModelEndpoint, Field(description="Model endpoint object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a model endpoint + + + :param model_id: (required) + :type model_id: int + :param body: Model endpoint object that has to be added (required) + :type body: ModelEndpoint + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "ModelEndpoint" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_post_serialize( + self, + model_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/endpoints', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_model_endpoints_get( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of model endpoints by specific `project_id`")], + region: Annotated[Optional[StrictStr], Field(description="Filter list of model endpoints by specific environment's `region`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ModelEndpoint]: + """List existing model endpoints for all models in particular project + + + :param project_id: Filter list of model endpoints by specific `project_id` (required) + :type project_id: int + :param region: Filter list of model endpoints by specific environment's `region` + :type region: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_model_endpoints_get_serialize( + project_id=project_id, + region=region, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_model_endpoints_get_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of model endpoints by specific `project_id`")], + region: Annotated[Optional[StrictStr], Field(description="Filter list of model endpoints by specific environment's `region`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ModelEndpoint]]: + """List existing model endpoints for all models in particular project + + + :param project_id: Filter list of model endpoints by specific `project_id` (required) + :type project_id: int + :param region: Filter list of model endpoints by specific environment's `region` + :type region: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_model_endpoints_get_serialize( + project_id=project_id, + region=region, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_model_endpoints_get_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of model endpoints by specific `project_id`")], + region: Annotated[Optional[StrictStr], Field(description="Filter list of model endpoints by specific environment's `region`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List existing model endpoints for all models in particular project + + + :param project_id: Filter list of model endpoints by specific `project_id` (required) + :type project_id: int + :param region: Filter list of model endpoints by specific environment's `region` + :type region: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_model_endpoints_get_serialize( + project_id=project_id, + region=region, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpoint]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_model_endpoints_get_serialize( + self, + project_id, + region, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + if region is not None: + + _query_params.append(('region', region)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}/model_endpoints', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/model_schema_api.py b/python/sdk/client/api/model_schema_api.py new file mode 100644 index 000000000..5a694df25 --- /dev/null +++ b/python/sdk/client/api/model_schema_api.py @@ -0,0 +1,1119 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings + +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any + +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated + +from pydantic import StrictInt + +from typing import List, Optional + +from client.models.model_schema import ModelSchema + +from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType + + +class ModelSchemaApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech + + Do not edit the class manually. + """ + + def __init__(self, api_client=None) -> None: + if api_client is None: + api_client = ApiClient.get_default() + self.api_client = api_client + + + @validate_call + def models_model_id_schemas_get( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ModelSchema]: + """List all of the model schemas + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelSchema]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_schemas_get_with_http_info( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ModelSchema]]: + """List all of the model schemas + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelSchema]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_schemas_get_without_preload_content( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List all of the model schemas + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelSchema]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_schemas_get_serialize( + self, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/schemas', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_schemas_put( + self, + model_id: StrictInt, + body: Optional[ModelSchema] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelSchema: + """Creating new schemas for a model + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: ModelSchema + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_put_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_schemas_put_with_http_info( + self, + model_id: StrictInt, + body: Optional[ModelSchema] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelSchema]: + """Creating new schemas for a model + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: ModelSchema + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_put_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_schemas_put_without_preload_content( + self, + model_id: StrictInt, + body: Optional[ModelSchema] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creating new schemas for a model + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: ModelSchema + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_put_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_schemas_put_serialize( + self, + model_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/schemas', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_schemas_schema_id_delete( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_delete_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_schemas_schema_id_delete_with_http_info( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_delete_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_schemas_schema_id_delete_without_preload_content( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_delete_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_schemas_schema_id_delete_serialize( + self, + model_id, + schema_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if schema_id is not None: + _path_params['schema_id'] = schema_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/models/{model_id}/schemas/{schema_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_schemas_schema_id_get( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelSchema: + """Get detail of the schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_get_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_schemas_schema_id_get_with_http_info( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelSchema]: + """Get detail of the schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_get_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_schemas_schema_id_get_without_preload_content( + self, + model_id: StrictInt, + schema_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get detail of the schema + + + :param model_id: (required) + :type model_id: int + :param schema_id: (required) + :type schema_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_schemas_schema_id_get_serialize( + model_id=model_id, + schema_id=schema_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelSchema" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_schemas_schema_id_get_serialize( + self, + model_id, + schema_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if schema_id is not None: + _path_params['schema_id'] = schema_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/schemas/{schema_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/models_api.py b/python/sdk/client/api/models_api.py index 8e6fca53a..dd7e62dd6 100644 --- a/python/sdk/client/api/models_api.py +++ b/python/sdk/client/api/models_api.py @@ -3,920 +3,2504 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import Field +from typing_extensions import Annotated +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.model import Model +from client.models.model_endpoint_alert import ModelEndpointAlert from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class ModelsApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class ModelsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def alerts_teams_get(self, **kwargs): # noqa: E501 - """Lists teams for alert notification channel. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.alerts_teams_get(async_req=True) - >>> result = thread.get() - - :param async_req bool - :return: list[str] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.alerts_teams_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.alerts_teams_get_with_http_info(**kwargs) # noqa: E501 - return data - - def alerts_teams_get_with_http_info(self, **kwargs): # noqa: E501 - """Lists teams for alert notification channel. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.alerts_teams_get_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :return: list[str] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = [] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method alerts_teams_get" % key - ) - params[key] = val - del params['kwargs'] - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/alerts/teams', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[str]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_alerts_get(self, model_id, **kwargs): # noqa: E501 - """Lists alerts for given model. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_alerts_get(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpointAlert] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_alerts_get_with_http_info(model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_alerts_get_with_http_info(model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_alerts_get_with_http_info(self, model_id, **kwargs): # noqa: E501 - """Lists alerts for given model. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_alerts_get_with_http_info(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :return: list[ModelEndpointAlert] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_alerts_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_alerts_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/alerts', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[ModelEndpointAlert]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_get(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Gets alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_get(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpointAlert - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Gets alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :return: ModelEndpointAlert - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_get`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='ModelEndpointAlert', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_post(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_post(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_post`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_endpoints_model_endpoint_id_alert_put(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_put(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, **kwargs) # noqa: E501 - return data - - def models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(self, model_id, model_endpoint_id, **kwargs): # noqa: E501 - """Creates alert for given model endpoint. # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info(model_id, model_endpoint_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param str model_endpoint_id: (required) - :param ModelEndpointAlert body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'model_endpoint_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_endpoints_model_endpoint_id_alert_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_put`") # noqa: E501 - # verify the required parameter 'model_endpoint_id' is set - if ('model_endpoint_id' not in params or - params['model_endpoint_id'] is None): - raise ValueError("Missing the required parameter `model_endpoint_id` when calling `models_model_id_endpoints_model_endpoint_id_alert_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'model_endpoint_id' in params: - path_params['model_endpoint_id'] = params['model_endpoint_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/endpoints/{model_endpoint_id}/alert', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_models_get(self, project_id, **kwargs): # noqa: E501 - """List existing models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_get(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Filter list of models by specific `project_id` (required) - :param str name: Filter list of models by specific models `name` - :return: list[Model] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_models_get_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_models_get_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_models_get_with_http_info(self, project_id, **kwargs): # noqa: E501 - """List existing models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_get_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Filter list of models by specific `project_id` (required) - :param str name: Filter list of models by specific models `name` - :return: list[Model] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'name'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_models_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_models_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - if 'name' in params: - query_params.append(('name', params['name'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/models', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Model]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_models_model_id_delete(self, project_id, model_id, **kwargs): # noqa: E501 - """Delete model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_model_id_delete(project_id, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be deleted (required) - :param int model_id: model id of the model to be deleted (required) - :return: int - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_models_model_id_delete_with_http_info(project_id, model_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_models_model_id_delete_with_http_info(project_id, model_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_models_model_id_delete_with_http_info(self, project_id, model_id, **kwargs): # noqa: E501 - """Delete model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_model_id_delete_with_http_info(project_id, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be deleted (required) - :param int model_id: model id of the model to be deleted (required) - :return: int - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_models_model_id_delete" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_models_model_id_delete`") # noqa: E501 - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `projects_project_id_models_model_id_delete`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/models/{model_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='int', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_models_model_id_get(self, project_id, model_id, **kwargs): # noqa: E501 - """Get model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_model_id_get(project_id, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be retrieved (required) - :param int model_id: model id of the model to be retrieved (required) - :return: list[Model] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_models_model_id_get_with_http_info(project_id, model_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_models_model_id_get_with_http_info(project_id, model_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_models_model_id_get_with_http_info(self, project_id, model_id, **kwargs): # noqa: E501 - """Get model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_model_id_get_with_http_info(project_id, model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be retrieved (required) - :param int model_id: model id of the model to be retrieved (required) - :return: list[Model] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'model_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_models_model_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_models_model_id_get`") # noqa: E501 - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `projects_project_id_models_model_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/models/{model_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Model]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_models_post(self, project_id, **kwargs): # noqa: E501 - """Register a new models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_post(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Create new model in a specific `project_id` (required) - :param Model body: - :return: Model - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_models_post_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_models_post_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_models_post_with_http_info(self, project_id, **kwargs): # noqa: E501 - """Register a new models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_models_post_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: Create new model in a specific `project_id` (required) - :param Model body: - :return: Model - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_models_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_models_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/models', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Model', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def alerts_teams_get( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[str]: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def alerts_teams_get_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[str]]: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def alerts_teams_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Lists teams for alert notification channel. + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._alerts_teams_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[str]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _alerts_teams_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/alerts/teams', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_alerts_get( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[ModelEndpointAlert]: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_alerts_get_with_http_info( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[ModelEndpointAlert]]: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_alerts_get_without_preload_content( + self, + model_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Lists alerts for given model. + + + :param model_id: (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_alerts_get_serialize( + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[ModelEndpointAlert]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_alerts_get_serialize( + self, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/alerts', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelEndpointAlert: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelEndpointAlert]: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_get_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Gets alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelEndpointAlert" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_get_serialize( + self, + model_id, + model_endpoint_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_post_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_post_serialize( + self, + model_id, + model_endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put_with_http_info( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_endpoints_model_endpoint_id_alert_put_without_preload_content( + self, + model_id: StrictInt, + model_endpoint_id: StrictStr, + body: Optional[ModelEndpointAlert] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates alert for given model endpoint. + + + :param model_id: (required) + :type model_id: int + :param model_endpoint_id: (required) + :type model_endpoint_id: str + :param body: + :type body: ModelEndpointAlert + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + model_id=model_id, + model_endpoint_id=model_endpoint_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_endpoints_model_endpoint_id_alert_put_serialize( + self, + model_id, + model_endpoint_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if model_endpoint_id is not None: + _path_params['model_endpoint_id'] = model_endpoint_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/endpoints/{model_endpoint_id}/alert', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_models_get( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of models by specific `project_id`")], + name: Annotated[Optional[StrictStr], Field(description="Filter list of models by specific models `name`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Model]: + """List existing models + + + :param project_id: Filter list of models by specific `project_id` (required) + :type project_id: int + :param name: Filter list of models by specific models `name` + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_get_serialize( + project_id=project_id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_models_get_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of models by specific `project_id`")], + name: Annotated[Optional[StrictStr], Field(description="Filter list of models by specific models `name`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Model]]: + """List existing models + + + :param project_id: Filter list of models by specific `project_id` (required) + :type project_id: int + :param name: Filter list of models by specific models `name` + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_get_serialize( + project_id=project_id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_models_get_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="Filter list of models by specific `project_id`")], + name: Annotated[Optional[StrictStr], Field(description="Filter list of models by specific models `name`")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List existing models + + + :param project_id: Filter list of models by specific `project_id` (required) + :type project_id: int + :param name: Filter list of models by specific models `name` + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_get_serialize( + project_id=project_id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_models_get_serialize( + self, + project_id, + name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}/models', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_models_model_id_delete( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be deleted")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> int: + """Delete model + + + :param project_id: project id of the project to be deleted (required) + :type project_id: int + :param model_id: model id of the model to be deleted (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_delete_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_models_model_id_delete_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be deleted")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[int]: + """Delete model + + + :param project_id: project id of the project to be deleted (required) + :type project_id: int + :param model_id: model id of the model to be deleted (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_delete_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_models_model_id_delete_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be deleted")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete model + + + :param project_id: project id of the project to be deleted (required) + :type project_id: int + :param model_id: model id of the model to be deleted (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_delete_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_models_model_id_delete_serialize( + self, + project_id, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/projects/{project_id}/models/{model_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_models_model_id_get( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Model]: + """Get model + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param model_id: model id of the model to be retrieved (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_get_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_models_model_id_get_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Model]]: + """Get model + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param model_id: model id of the model to be retrieved (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_get_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_models_model_id_get_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + model_id: Annotated[StrictInt, Field(description="model id of the model to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get model + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param model_id: model id of the model to be retrieved (required) + :type model_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_model_id_get_serialize( + project_id=project_id, + model_id=model_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Model]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_models_model_id_get_serialize( + self, + project_id, + model_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}/models/{model_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_models_post( + self, + project_id: Annotated[StrictInt, Field(description="Create new model in a specific `project_id`")], + body: Optional[Model] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Model: + """Register a new models + + + :param project_id: Create new model in a specific `project_id` (required) + :type project_id: int + :param body: + :type body: Model + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Model", + '400': None, + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_models_post_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="Create new model in a specific `project_id`")], + body: Optional[Model] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Model]: + """Register a new models + + + :param project_id: Create new model in a specific `project_id` (required) + :type project_id: int + :param body: + :type body: Model + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Model", + '400': None, + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_models_post_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="Create new model in a specific `project_id`")], + body: Optional[Model] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Register a new models + + + :param project_id: Create new model in a specific `project_id` (required) + :type project_id: int + :param body: + :type body: Model + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_models_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Model", + '400': None, + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_models_post_serialize( + self, + project_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/projects/{project_id}/models', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/prediction_jobs_api.py b/python/sdk/client/api/prediction_jobs_api.py index 67211c9e7..a19bc0f38 100644 --- a/python/sdk/client/api/prediction_jobs_api.py +++ b/python/sdk/client/api/prediction_jobs_api.py @@ -3,681 +3,1843 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.container import Container +from client.models.prediction_job import PredictionJob from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class PredictionJobsApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class PredictionJobsApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def models_model_id_versions_version_id_jobs_get(self, model_id, version_id, **kwargs): # noqa: E501 - """List all prediction jobs of a model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_get(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: list[PredictionJob] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_jobs_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_jobs_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_jobs_get_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """List all prediction jobs of a model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_get_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: list[PredictionJob] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_jobs_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_jobs_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_jobs_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/jobs', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[PredictionJob]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_jobs_job_id_containers_get(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Get all container belong to a prediction job # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_containers_get(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str job_id: (required) - :return: Container - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_jobs_job_id_containers_get_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_jobs_job_id_containers_get_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_jobs_job_id_containers_get_with_http_info(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Get all container belong to a prediction job # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_containers_get_with_http_info(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param str job_id: (required) - :return: Container - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'job_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_jobs_job_id_containers_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_jobs_job_id_containers_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_jobs_job_id_containers_get`") # noqa: E501 - # verify the required parameter 'job_id' is set - if ('job_id' not in params or - params['job_id'] is None): - raise ValueError("Missing the required parameter `job_id` when calling `models_model_id_versions_version_id_jobs_job_id_containers_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'job_id' in params: - path_params['job_id'] = params['job_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/jobs/{job_id}/containers', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Container', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_jobs_job_id_get(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Get prediction jobs with given id # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_get(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param int job_id: (required) - :return: PredictionJob - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_jobs_job_id_get_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_jobs_job_id_get_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_jobs_job_id_get_with_http_info(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Get prediction jobs with given id # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_get_with_http_info(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param int job_id: (required) - :return: PredictionJob - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'job_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_jobs_job_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_jobs_job_id_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_jobs_job_id_get`") # noqa: E501 - # verify the required parameter 'job_id' is set - if ('job_id' not in params or - params['job_id'] is None): - raise ValueError("Missing the required parameter `job_id` when calling `models_model_id_versions_version_id_jobs_job_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'job_id' in params: - path_params['job_id'] = params['job_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/jobs/{job_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='PredictionJob', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_jobs_job_id_stop_put(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Stop prediction jobs with given id # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_stop_put(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param int job_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_jobs_job_id_stop_put_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_jobs_job_id_stop_put_with_http_info(model_id, version_id, job_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_jobs_job_id_stop_put_with_http_info(self, model_id, version_id, job_id, **kwargs): # noqa: E501 - """Stop prediction jobs with given id # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_job_id_stop_put_with_http_info(model_id, version_id, job_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param int job_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'job_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_jobs_job_id_stop_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_jobs_job_id_stop_put`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_jobs_job_id_stop_put`") # noqa: E501 - # verify the required parameter 'job_id' is set - if ('job_id' not in params or - params['job_id'] is None): - raise ValueError("Missing the required parameter `job_id` when calling `models_model_id_versions_version_id_jobs_job_id_stop_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - if 'job_id' in params: - path_params['job_id'] = params['job_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/jobs/{job_id}/stop', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_jobs_post(self, model_id, version_id, **kwargs): # noqa: E501 - """Create a prediction job from the given model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_post(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param PredictionJob body: - :return: PredictionJob - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_jobs_post_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_jobs_post_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_jobs_post_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """Create a prediction job from the given model version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_jobs_post_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param PredictionJob body: - :return: PredictionJob - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_jobs_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_jobs_post`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_jobs_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}/jobs', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='PredictionJob', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_jobs_get(self, project_id, **kwargs): # noqa: E501 - """List all prediction jobs created using the model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_jobs_get(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int id: - :param str name: - :param int model_id: - :param int version_id: - :param str status: - :param str error: - :return: list[PredictionJob] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_jobs_get_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_jobs_get_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_jobs_get_with_http_info(self, project_id, **kwargs): # noqa: E501 - """List all prediction jobs created using the model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_jobs_get_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int id: - :param str name: - :param int model_id: - :param int version_id: - :param str status: - :param str error: - :return: list[PredictionJob] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'id', 'name', 'model_id', 'version_id', 'status', 'error'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_jobs_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_jobs_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - if 'id' in params: - query_params.append(('id', params['id'])) # noqa: E501 - if 'name' in params: - query_params.append(('name', params['name'])) # noqa: E501 - if 'model_id' in params: - query_params.append(('model_id', params['model_id'])) # noqa: E501 - if 'version_id' in params: - query_params.append(('version_id', params['version_id'])) # noqa: E501 - if 'status' in params: - query_params.append(('status', params['status'])) # noqa: E501 - if 'error' in params: - query_params.append(('error', params['error'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/jobs', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[PredictionJob]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def models_model_id_versions_version_id_jobs_get( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[PredictionJob]: + """List all prediction jobs of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_jobs_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[PredictionJob]]: + """List all prediction jobs of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_jobs_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List all prediction jobs of a model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_jobs_get_serialize( + self, + model_id, + version_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/jobs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_containers_get( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Container: + """Get all container belong to a prediction job + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_containers_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Container]: + """Get all container belong to a prediction job + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_containers_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get all container belong to a prediction job + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_containers_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Container", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_jobs_job_id_containers_get_serialize( + self, + model_id, + version_id, + job_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if job_id is not None: + _path_params['job_id'] = job_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/jobs/{job_id}/containers', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_get( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> PredictionJob: + """Get prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[PredictionJob]: + """Get prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_get_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_jobs_job_id_get_serialize( + self, + model_id, + version_id, + job_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if job_id is not None: + _path_params['job_id'] = job_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}/jobs/{job_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_stop_put( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Stop prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_stop_put_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_stop_put_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Stop prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_stop_put_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_jobs_job_id_stop_put_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + job_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Stop prediction jobs with given id + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param job_id: (required) + :type job_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_job_id_stop_put_serialize( + model_id=model_id, + version_id=version_id, + job_id=job_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_jobs_job_id_stop_put_serialize( + self, + model_id, + version_id, + job_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + if job_id is not None: + _path_params['job_id'] = job_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/models/{model_id}/versions/{version_id}/jobs/{job_id}/stop', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_jobs_post( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[PredictionJob] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> PredictionJob: + """Create a prediction job from the given model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: PredictionJob + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_jobs_post_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[PredictionJob] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[PredictionJob]: + """Create a prediction job from the given model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: PredictionJob + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_jobs_post_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[PredictionJob] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create a prediction job from the given model version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: PredictionJob + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_jobs_post_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "PredictionJob", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_jobs_post_serialize( + self, + model_id, + version_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/versions/{version_id}/jobs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_jobs_get( + self, + project_id: StrictInt, + id: Optional[StrictInt] = None, + name: Optional[StrictStr] = None, + model_id: Optional[StrictInt] = None, + version_id: Optional[StrictInt] = None, + status: Optional[StrictStr] = None, + error: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[PredictionJob]: + """List all prediction jobs created using the model + + + :param project_id: (required) + :type project_id: int + :param id: + :type id: int + :param name: + :type name: str + :param model_id: + :type model_id: int + :param version_id: + :type version_id: int + :param status: + :type status: str + :param error: + :type error: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_jobs_get_serialize( + project_id=project_id, + id=id, + name=name, + model_id=model_id, + version_id=version_id, + status=status, + error=error, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_jobs_get_with_http_info( + self, + project_id: StrictInt, + id: Optional[StrictInt] = None, + name: Optional[StrictStr] = None, + model_id: Optional[StrictInt] = None, + version_id: Optional[StrictInt] = None, + status: Optional[StrictStr] = None, + error: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[PredictionJob]]: + """List all prediction jobs created using the model + + + :param project_id: (required) + :type project_id: int + :param id: + :type id: int + :param name: + :type name: str + :param model_id: + :type model_id: int + :param version_id: + :type version_id: int + :param status: + :type status: str + :param error: + :type error: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_jobs_get_serialize( + project_id=project_id, + id=id, + name=name, + model_id=model_id, + version_id=version_id, + status=status, + error=error, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_jobs_get_without_preload_content( + self, + project_id: StrictInt, + id: Optional[StrictInt] = None, + name: Optional[StrictStr] = None, + model_id: Optional[StrictInt] = None, + version_id: Optional[StrictInt] = None, + status: Optional[StrictStr] = None, + error: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List all prediction jobs created using the model + + + :param project_id: (required) + :type project_id: int + :param id: + :type id: int + :param name: + :type name: str + :param model_id: + :type model_id: int + :param version_id: + :type version_id: int + :param status: + :type status: str + :param error: + :type error: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_jobs_get_serialize( + project_id=project_id, + id=id, + name=name, + model_id=model_id, + version_id=version_id, + status=status, + error=error, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[PredictionJob]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_jobs_get_serialize( + self, + project_id, + id, + name, + model_id, + version_id, + status, + error, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + if id is not None: + + _query_params.append(('id', id)) + + if name is not None: + + _query_params.append(('name', name)) + + if model_id is not None: + + _query_params.append(('model_id', model_id)) + + if version_id is not None: + + _query_params.append(('version_id', version_id)) + + if status is not None: + + _query_params.append(('status', status)) + + if error is not None: + + _query_params.append(('error', error)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}/jobs', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/project_api.py b/python/sdk/client/api/project_api.py index a7587217c..cb8de3401 100644 --- a/python/sdk/client/api/project_api.py +++ b/python/sdk/client/api/project_api.py @@ -3,417 +3,1115 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import Field +from typing_extensions import Annotated +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.project import Project from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class ProjectApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class ProjectApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def projects_get(self, **kwargs): # noqa: E501 - """List existing projects # noqa: E501 - - Projects can be filtered by optional `name` parameter # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_get(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :return: list[Project] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_get_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.projects_get_with_http_info(**kwargs) # noqa: E501 - return data - - def projects_get_with_http_info(self, **kwargs): # noqa: E501 - """List existing projects # noqa: E501 - - Projects can be filtered by optional `name` parameter # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_get_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param str name: - :return: list[Project] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['name'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_get" % key - ) - params[key] = val - del params['kwargs'] - - collection_formats = {} - - path_params = {} - - query_params = [] - if 'name' in params: - query_params.append(('name', params['name'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Project]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_post(self, body, **kwargs): # noqa: E501 - """Create new project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_post(body, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param Project body: Project object that has to be added (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_post_with_http_info(body, **kwargs) # noqa: E501 - else: - (data) = self.projects_post_with_http_info(body, **kwargs) # noqa: E501 - return data - - def projects_post_with_http_info(self, body, **kwargs): # noqa: E501 - """Create new project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_post_with_http_info(body, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param Project body: Project object that has to be added (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params or - params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `projects_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Project', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_get(self, project_id, **kwargs): # noqa: E501 - """Get project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_get(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be retrieved (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_get_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_get_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_get_with_http_info(self, project_id, **kwargs): # noqa: E501 - """Get project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_get_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: project id of the project to be retrieved (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Project', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_put(self, body, project_id, **kwargs): # noqa: E501 - """Update project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_put(body, project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param Project body: Project object that has to be updated (required) - :param int project_id: project id of the project to be updated (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_put_with_http_info(body, project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_put_with_http_info(body, project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_put_with_http_info(self, body, project_id, **kwargs): # noqa: E501 - """Update project # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_put_with_http_info(body, project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param Project body: Project object that has to be updated (required) - :param int project_id: project id of the project to be updated (required) - :return: Project - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body', 'project_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_put" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'body' is set - if ('body' not in params or - params['body'] is None): - raise ValueError("Missing the required parameter `body` when calling `projects_project_id_put`") # noqa: E501 - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_put`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}', 'PUT', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Project', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def projects_get( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Project]: + """List existing projects + + Projects can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Project]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_get_with_http_info( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Project]]: + """List existing projects + + Projects can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Project]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_get_without_preload_content( + self, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List existing projects + + Projects can be filtered by optional `name` parameter + + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_get_serialize( + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Project]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_get_serialize( + self, + name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if name is not None: + + _query_params.append(('name', name)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_post( + self, + body: Annotated[Project, Field(description="Project object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Project: + """Create new project + + + :param body: Project object that has to be added (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Project", + '400': None, + '409': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_post_with_http_info( + self, + body: Annotated[Project, Field(description="Project object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Project]: + """Create new project + + + :param body: Project object that has to be added (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Project", + '400': None, + '409': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_post_without_preload_content( + self, + body: Annotated[Project, Field(description="Project object that has to be added")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create new project + + + :param body: Project object that has to be added (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Project", + '400': None, + '409': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_post_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/projects', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_get( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Project: + """Get project + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_get_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Project]: + """Get project + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_get_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be retrieved")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get project + + + :param project_id: project id of the project to be retrieved (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_get_serialize( + self, + project_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_put( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be updated")], + body: Annotated[Project, Field(description="Project object that has to be updated")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Project: + """Update project + + + :param project_id: project id of the project to be updated (required) + :type project_id: int + :param body: Project object that has to be updated (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_put_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '400': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_put_with_http_info( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be updated")], + body: Annotated[Project, Field(description="Project object that has to be updated")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Project]: + """Update project + + + :param project_id: project id of the project to be updated (required) + :type project_id: int + :param body: Project object that has to be updated (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_put_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '400': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_put_without_preload_content( + self, + project_id: Annotated[StrictInt, Field(description="project id of the project to be updated")], + body: Annotated[Project, Field(description="Project object that has to be updated")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update project + + + :param project_id: project id of the project to be updated (required) + :type project_id: int + :param body: Project object that has to be updated (required) + :type body: Project + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_put_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Project", + '400': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_put_serialize( + self, + project_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/projects/{project_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/secret_api.py b/python/sdk/client/api/secret_api.py index 9fefb927c..1f2e5cb14 100644 --- a/python/sdk/client/api/secret_api.py +++ b/python/sdk/client/api/secret_api.py @@ -3,431 +3,1132 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import StrictInt + +from typing import List, Optional + +from client.models.secret import Secret from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class SecretApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class SecretApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def projects_project_id_secrets_get(self, project_id, **kwargs): # noqa: E501 - """List secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_get(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :return: list[Secret] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_secrets_get_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_secrets_get_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_secrets_get_with_http_info(self, project_id, **kwargs): # noqa: E501 - """List secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_get_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :return: list[Secret] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_secrets_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_secrets_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/secrets', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Secret]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_secrets_post(self, project_id, **kwargs): # noqa: E501 - """Create secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_post(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param Secret body: - :return: Secret - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_secrets_post_with_http_info(project_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_secrets_post_with_http_info(project_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_secrets_post_with_http_info(self, project_id, **kwargs): # noqa: E501 - """Create secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_post_with_http_info(project_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param Secret body: - :return: Secret - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_secrets_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_secrets_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/secrets', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Secret', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_secrets_secret_id_delete(self, project_id, secret_id, **kwargs): # noqa: E501 - """Delete secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_secret_id_delete(project_id, secret_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int secret_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_secrets_secret_id_delete_with_http_info(project_id, secret_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_secrets_secret_id_delete_with_http_info(project_id, secret_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_secrets_secret_id_delete_with_http_info(self, project_id, secret_id, **kwargs): # noqa: E501 - """Delete secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_secret_id_delete_with_http_info(project_id, secret_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int secret_id: (required) - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'secret_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_secrets_secret_id_delete" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_secrets_secret_id_delete`") # noqa: E501 - # verify the required parameter 'secret_id' is set - if ('secret_id' not in params or - params['secret_id'] is None): - raise ValueError("Missing the required parameter `secret_id` when calling `projects_project_id_secrets_secret_id_delete`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - if 'secret_id' in params: - path_params['secret_id'] = params['secret_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/secrets/{secret_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def projects_project_id_secrets_secret_id_patch(self, project_id, secret_id, **kwargs): # noqa: E501 - """Update secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_secret_id_patch(project_id, secret_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int secret_id: (required) - :param Secret body: - :return: Secret - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.projects_project_id_secrets_secret_id_patch_with_http_info(project_id, secret_id, **kwargs) # noqa: E501 - else: - (data) = self.projects_project_id_secrets_secret_id_patch_with_http_info(project_id, secret_id, **kwargs) # noqa: E501 - return data - - def projects_project_id_secrets_secret_id_patch_with_http_info(self, project_id, secret_id, **kwargs): # noqa: E501 - """Update secret # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.projects_project_id_secrets_secret_id_patch_with_http_info(project_id, secret_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int project_id: (required) - :param int secret_id: (required) - :param Secret body: - :return: Secret - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['project_id', 'secret_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method projects_project_id_secrets_secret_id_patch" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'project_id' is set - if ('project_id' not in params or - params['project_id'] is None): - raise ValueError("Missing the required parameter `project_id` when calling `projects_project_id_secrets_secret_id_patch`") # noqa: E501 - # verify the required parameter 'secret_id' is set - if ('secret_id' not in params or - params['secret_id'] is None): - raise ValueError("Missing the required parameter `secret_id` when calling `projects_project_id_secrets_secret_id_patch`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'project_id' in params: - path_params['project_id'] = params['project_id'] # noqa: E501 - if 'secret_id' in params: - path_params['secret_id'] = params['secret_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/projects/{project_id}/secrets/{secret_id}', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Secret', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def projects_project_id_secrets_get( + self, + project_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Secret]: + """List secret + + + :param project_id: (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Secret]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_secrets_get_with_http_info( + self, + project_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Secret]]: + """List secret + + + :param project_id: (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Secret]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_secrets_get_without_preload_content( + self, + project_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List secret + + + :param project_id: (required) + :type project_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_get_serialize( + project_id=project_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Secret]" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_secrets_get_serialize( + self, + project_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/projects/{project_id}/secrets', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_secrets_post( + self, + project_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Secret: + """Create secret + + + :param project_id: (required) + :type project_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_secrets_post_with_http_info( + self, + project_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Secret]: + """Create secret + + + :param project_id: (required) + :type project_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_secrets_post_without_preload_content( + self, + project_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Create secret + + + :param project_id: (required) + :type project_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_post_serialize( + project_id=project_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_secrets_post_serialize( + self, + project_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/projects/{project_id}/secrets', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_secrets_secret_id_delete( + self, + project_id: StrictInt, + secret_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Delete secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_delete_serialize( + project_id=project_id, + secret_id=secret_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_secrets_secret_id_delete_with_http_info( + self, + project_id: StrictInt, + secret_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_delete_serialize( + project_id=project_id, + secret_id=secret_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_secrets_secret_id_delete_without_preload_content( + self, + project_id: StrictInt, + secret_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_delete_serialize( + project_id=project_id, + secret_id=secret_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_secrets_secret_id_delete_serialize( + self, + project_id, + secret_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + if secret_id is not None: + _path_params['secret_id'] = secret_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/projects/{project_id}/secrets/{secret_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def projects_project_id_secrets_secret_id_patch( + self, + project_id: StrictInt, + secret_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Secret: + """Update secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_patch_serialize( + project_id=project_id, + secret_id=secret_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def projects_project_id_secrets_secret_id_patch_with_http_info( + self, + project_id: StrictInt, + secret_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Secret]: + """Update secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_patch_serialize( + project_id=project_id, + secret_id=secret_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def projects_project_id_secrets_secret_id_patch_without_preload_content( + self, + project_id: StrictInt, + secret_id: StrictInt, + body: Optional[Secret] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update secret + + + :param project_id: (required) + :type project_id: int + :param secret_id: (required) + :type secret_id: int + :param body: + :type body: Secret + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._projects_project_id_secrets_secret_id_patch_serialize( + project_id=project_id, + secret_id=secret_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Secret" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _projects_project_id_secrets_secret_id_patch_serialize( + self, + project_id, + secret_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if project_id is not None: + _path_params['project_id'] = project_id + if secret_id is not None: + _path_params['secret_id'] = secret_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/projects/{project_id}/secrets/{secret_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/standard_transformer_api.py b/python/sdk/client/api/standard_transformer_api.py index 50acfec33..8550457ba 100644 --- a/python/sdk/client/api/standard_transformer_api.py +++ b/python/sdk/client/api/standard_transformer_api.py @@ -3,124 +3,303 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from typing import Optional + +from client.models.standard_transformer_simulation_request import StandardTransformerSimulationRequest +from client.models.standard_transformer_simulation_response import StandardTransformerSimulationResponse from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class StandardTransformerApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class StandardTransformerApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def standard_transformer_simulate_post(self, **kwargs): # noqa: E501 - """Simulate standard transformer # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.standard_transformer_simulate_post(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param StandardTransformerSimulationRequest body: - :return: StandardTransformerSimulationResponse - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.standard_transformer_simulate_post_with_http_info(**kwargs) # noqa: E501 - else: - (data) = self.standard_transformer_simulate_post_with_http_info(**kwargs) # noqa: E501 - return data - - def standard_transformer_simulate_post_with_http_info(self, **kwargs): # noqa: E501 - """Simulate standard transformer # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.standard_transformer_simulate_post_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req bool - :param StandardTransformerSimulationRequest body: - :return: StandardTransformerSimulationResponse - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method standard_transformer_simulate_post" % key - ) - params[key] = val - del params['kwargs'] - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/standard_transformer/simulate', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='StandardTransformerSimulationResponse', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def standard_transformer_simulate_post( + self, + body: Optional[StandardTransformerSimulationRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> StandardTransformerSimulationResponse: + """Simulate standard transformer + + + :param body: + :type body: StandardTransformerSimulationRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._standard_transformer_simulate_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StandardTransformerSimulationResponse" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def standard_transformer_simulate_post_with_http_info( + self, + body: Optional[StandardTransformerSimulationRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[StandardTransformerSimulationResponse]: + """Simulate standard transformer + + + :param body: + :type body: StandardTransformerSimulationRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._standard_transformer_simulate_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StandardTransformerSimulationResponse" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def standard_transformer_simulate_post_without_preload_content( + self, + body: Optional[StandardTransformerSimulationRequest] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Simulate standard transformer + + + :param body: + :type body: StandardTransformerSimulationRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._standard_transformer_simulate_post_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "StandardTransformerSimulationResponse" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _standard_transformer_simulate_post_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/standard_transformer/simulate', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api/version_api.py b/python/sdk/client/api/version_api.py index 03a2c1bdd..fb109253d 100644 --- a/python/sdk/client/api/version_api.py +++ b/python/sdk/client/api/version_api.py @@ -3,544 +3,1474 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import io +import warnings -from __future__ import absolute_import +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Dict, List, Optional, Tuple, Union, Any -import re # noqa: F401 +try: + from typing import Annotated +except ImportError: + from typing_extensions import Annotated -# python 2 and python 3 compatibility library -import six +from pydantic import Field +from typing_extensions import Annotated +from pydantic import StrictInt, StrictStr + +from typing import List, Optional + +from client.models.version import Version from client.api_client import ApiClient +from client.api_response import ApiResponse +from client.rest import RESTResponseType -class VersionApi(object): - """NOTE: This class is auto generated by the swagger code generator program. +class VersionApi: + """NOTE: This class is auto generated by OpenAPI Generator + Ref: https://openapi-generator.tech Do not edit the class manually. - Ref: https://github.com/swagger-api/swagger-codegen """ - def __init__(self, api_client=None): + def __init__(self, api_client=None) -> None: if api_client is None: - api_client = ApiClient() + api_client = ApiClient.get_default() self.api_client = api_client - def models_model_id_versions_get(self, model_id, **kwargs): # noqa: E501 - """List versions of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_get(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int limit: - :param str cursor: - :param str search: Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` - :return: list[Version] - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_get_with_http_info(model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_get_with_http_info(model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_get_with_http_info(self, model_id, **kwargs): # noqa: E501 - """List versions of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_get_with_http_info(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int limit: - :param str cursor: - :param str search: Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` - :return: list[Version] - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'limit', 'cursor', 'search'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - if 'limit' in params: - query_params.append(('limit', params['limit'])) # noqa: E501 - if 'cursor' in params: - query_params.append(('cursor', params['cursor'])) # noqa: E501 - if 'search' in params: - query_params.append(('search', params['search'])) # noqa: E501 - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='list[Version]', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_post(self, model_id, **kwargs): # noqa: E501 - """Log a new version of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_post(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param Version body: - :return: Version - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_post_with_http_info(model_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_post_with_http_info(model_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_post_with_http_info(self, model_id, **kwargs): # noqa: E501 - """Log a new version of the models # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_post_with_http_info(model_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param Version body: - :return: Version - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_post" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_post`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions', 'POST', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Version', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_delete(self, model_id, version_id, **kwargs): # noqa: E501 - """Delete version by ID from model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_delete(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: int - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_delete_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_delete_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_delete_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """Delete version by ID from model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_delete_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: int - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_delete" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_delete`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_delete`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}', 'DELETE', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='int', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_get(self, model_id, version_id, **kwargs): # noqa: E501 - """Get version by ID from model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_get(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: Version - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_get_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_get_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """Get version by ID from model # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_get_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :return: Version - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_get" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_get`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_get`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}', 'GET', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type='Version', # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) - - def models_model_id_versions_version_id_patch(self, model_id, version_id, **kwargs): # noqa: E501 - """Patch the version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_patch(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param Version body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - kwargs['_return_http_data_only'] = True - if kwargs.get('async_req'): - return self.models_model_id_versions_version_id_patch_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - else: - (data) = self.models_model_id_versions_version_id_patch_with_http_info(model_id, version_id, **kwargs) # noqa: E501 - return data - - def models_model_id_versions_version_id_patch_with_http_info(self, model_id, version_id, **kwargs): # noqa: E501 - """Patch the version # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.models_model_id_versions_version_id_patch_with_http_info(model_id, version_id, async_req=True) - >>> result = thread.get() - - :param async_req bool - :param int model_id: (required) - :param int version_id: (required) - :param Version body: - :return: None - If the method is called asynchronously, - returns the request thread. - """ - - all_params = ['model_id', 'version_id', 'body'] # noqa: E501 - all_params.append('async_req') - all_params.append('_return_http_data_only') - all_params.append('_preload_content') - all_params.append('_request_timeout') - - params = locals() - for key, val in six.iteritems(params['kwargs']): - if key not in all_params: - raise TypeError( - "Got an unexpected keyword argument '%s'" - " to method models_model_id_versions_version_id_patch" % key - ) - params[key] = val - del params['kwargs'] - # verify the required parameter 'model_id' is set - if ('model_id' not in params or - params['model_id'] is None): - raise ValueError("Missing the required parameter `model_id` when calling `models_model_id_versions_version_id_patch`") # noqa: E501 - # verify the required parameter 'version_id' is set - if ('version_id' not in params or - params['version_id'] is None): - raise ValueError("Missing the required parameter `version_id` when calling `models_model_id_versions_version_id_patch`") # noqa: E501 - - collection_formats = {} - - path_params = {} - if 'model_id' in params: - path_params['model_id'] = params['model_id'] # noqa: E501 - if 'version_id' in params: - path_params['version_id'] = params['version_id'] # noqa: E501 - - query_params = [] - - header_params = {} - - form_params = [] - local_var_files = {} - - body_params = None - if 'body' in params: - body_params = params['body'] - # HTTP header `Content-Type` - header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501 - ['*/*']) # noqa: E501 - - # Authentication setting - auth_settings = ['Bearer'] # noqa: E501 - - return self.api_client.call_api( - '/models/{model_id}/versions/{version_id}', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_type=None, # noqa: E501 - auth_settings=auth_settings, - async_req=params.get('async_req'), - _return_http_data_only=params.get('_return_http_data_only'), - _preload_content=params.get('_preload_content', True), - _request_timeout=params.get('_request_timeout'), - collection_formats=collection_formats) + + @validate_call + def models_model_id_versions_get( + self, + model_id: StrictInt, + limit: Optional[StrictInt] = None, + cursor: Optional[StrictStr] = None, + search: Annotated[Optional[StrictStr], Field(description="Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[Version]: + """List versions of the models + + + :param model_id: (required) + :type model_id: int + :param limit: + :type limit: int + :param cursor: + :type cursor: str + :param search: Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` + :type search: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_get_serialize( + model_id=model_id, + limit=limit, + cursor=cursor, + search=search, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Version]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_get_with_http_info( + self, + model_id: StrictInt, + limit: Optional[StrictInt] = None, + cursor: Optional[StrictStr] = None, + search: Annotated[Optional[StrictStr], Field(description="Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Version]]: + """List versions of the models + + + :param model_id: (required) + :type model_id: int + :param limit: + :type limit: int + :param cursor: + :type cursor: str + :param search: Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` + :type search: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_get_serialize( + model_id=model_id, + limit=limit, + cursor=cursor, + search=search, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Version]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_get_without_preload_content( + self, + model_id: StrictInt, + limit: Optional[StrictInt] = None, + cursor: Optional[StrictStr] = None, + search: Annotated[Optional[StrictStr], Field(description="Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` ")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """List versions of the models + + + :param model_id: (required) + :type model_id: int + :param limit: + :type limit: int + :param cursor: + :type cursor: str + :param search: Search query to filter the model versions. These searches are currently supported: - Search by \"mlflow_run_id\" e.g. `?search=cfca7716b45f4b149479630a98332a13` - Search by \"environment_name\" e.g `?search=environment_name:myenv` - Search by \"labels\" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - Search by \"environment_name\" and \"labels\" e.g. `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` + :type search: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_get_serialize( + model_id=model_id, + limit=limit, + cursor=cursor, + search=search, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Version]", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_get_serialize( + self, + model_id, + limit, + cursor, + search, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + if limit is not None: + + _query_params.append(('limit', limit)) + + if cursor is not None: + + _query_params.append(('cursor', cursor)) + + if search is not None: + + _query_params.append(('search', search)) + + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_post( + self, + model_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Version: + """Log a new version of the models + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Version" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_post_with_http_info( + self, + model_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Version]: + """Log a new version of the models + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Version" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_post_without_preload_content( + self, + model_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Log a new version of the models + + + :param model_id: (required) + :type model_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_post_serialize( + model_id=model_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '201': "Version" + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_post_serialize( + self, + model_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/models/{model_id}/versions', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_delete( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> int: + """Delete version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_delete_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_delete_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[int]: + """Delete version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_delete_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_delete_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_delete_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "int", + '400': None, + '404': None, + '500': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_delete_serialize( + self, + model_id, + version_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/models/{model_id}/versions/{version_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_get( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Version: + """Get version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Version", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_get_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Version]: + """Get version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Version", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_get_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get version by ID from model + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_get_serialize( + model_id=model_id, + version_id=version_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Version", + '404': None + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_get_serialize( + self, + model_id, + version_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + '*/*' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/models/{model_id}/versions/{version_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def models_model_id_versions_version_id_patch( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Patch the version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_patch_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def models_model_id_versions_version_id_patch_with_http_info( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Patch the version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_patch_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def models_model_id_versions_version_id_patch_without_preload_content( + self, + model_id: StrictInt, + version_id: StrictInt, + body: Optional[Version] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Patch the version + + + :param model_id: (required) + :type model_id: int + :param version_id: (required) + :type version_id: int + :param body: + :type body: Version + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._models_model_id_versions_version_id_patch_serialize( + model_id=model_id, + version_id=version_id, + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _models_model_id_versions_version_id_patch_serialize( + self, + model_id, + version_id, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> Tuple: + + _host = None + + _collection_formats: Dict[str, str] = { + + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if model_id is not None: + _path_params['model_id'] = model_id + if version_id is not None: + _path_params['version_id'] = version_id + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + _body_params = body + + + + + # authentication setting + _auth_settings: List[str] = [ + 'Bearer' + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/models/{model_id}/versions/{version_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/python/sdk/client/api_client.py b/python/sdk/client/api_client.py index 8ec98010f..5bf60ec80 100644 --- a/python/sdk/client/api_client.py +++ b/python/sdk/client/api_client.py @@ -1,44 +1,52 @@ # coding: utf-8 + """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" -from __future__ import absolute_import +import atexit import datetime +from dateutil.parser import parse import json import mimetypes -from multiprocessing.pool import ThreadPool import os import re import tempfile -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import quote +from urllib.parse import quote +from typing import Tuple, Optional, List from client.configuration import Configuration +from client.api_response import ApiResponse import client.models from client import rest +from client.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) -class ApiClient(object): - """Generic API client for Swagger client library builds. +class ApiClient: + """Generic API client for OpenAPI client library builds. - Swagger generic API client. This client handles the client- + OpenAPI generic API client. This client handles the client- server communication, and is invariant across implementations. Specifics of - the methods and models for each application are generated from the Swagger + the methods and models for each application are generated from the OpenAPI templates. - NOTE: This class is auto generated by the swagger code generator program. - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. - :param configuration: .Configuration object for this client :param header_name: a header to pass when making calls to the API. :param header_value: a header value to pass when making calls to @@ -47,10 +55,10 @@ class ApiClient(object): to the API """ - PRIMITIVE_TYPES = (float, bool, bytes, six.text_type) + six.integer_types + PRIMITIVE_TYPES = (float, bool, bytes, str, int) NATIVE_TYPES_MAPPING = { 'int': int, - 'long': int if six.PY3 else int, # noqa: F821 + 'long': int, # TODO remove as only py3 is supported? 'float': float, 'str': str, 'bool': bool, @@ -58,25 +66,34 @@ class ApiClient(object): 'datetime': datetime.datetime, 'object': object, } - - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None): + _pool = None + + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: + # use default configuration if none is provided if configuration is None: - configuration = Configuration() + configuration = Configuration.get_default() self.configuration = configuration - self.pool = ThreadPool() self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} if header_name is not None: self.default_headers[header_name] = header_value self.cookie = cookie # Set default User-Agent. - self.user_agent = 'Swagger-Codegen/1.0.0/python' + self.user_agent = 'OpenAPI-Generator/1.0.0/python' + self.client_side_validation = configuration.client_side_validation - def __del__(self): - self.pool.close() - self.pool.join() + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_value, traceback): + pass @property def user_agent(self): @@ -90,12 +107,69 @@ def user_agent(self, value): def set_default_header(self, header_name, header_value): self.default_headers[header_name] = header_value - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_type=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): + + _default = None + + @classmethod + def get_default(cls): + """Return new instance of ApiClient. + + This method returns newly created, based on default constructor, + object of ApiClient class or returns a copy of default + ApiClient. + + :return: The ApiClient object. + """ + if cls._default is None: + cls._default = ApiClient() + return cls._default + + @classmethod + def set_default(cls, default): + """Set default instance of ApiClient. + + It stores default ApiClient. + + :param default: object of ApiClient. + """ + cls._default = default + + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> Tuple: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -106,14 +180,17 @@ def __call_api( header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -121,51 +198,144 @@ def __call_api( quote(str(v), safe=config.safe_chars_for_path_param) ) - # query parameters - if query_params: - query_params = self.sanitize_for_serialization(query_params) - query_params = self.parameters_to_tuples(query_params, - collection_formats) - # post parameters if post_params or files: - post_params = self.prepare_post_parameters(post_params, files) + post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) + post_params.extend(self.files_parameters(files)) # auth setting - self.update_params_for_auth(header_params, query_params, auth_settings) + self.update_params_for_auth( + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: body = self.sanitize_for_serialization(body) # request url - url = self.configuration.host + resource_path - - # perform request and return response - response_data = self.request( - method, url, query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - - self.last_response = response_data - - return_data = response_data - if _preload_content: - # deserialize response data - if response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None + if _host is None: + url = self.configuration.host + resource_path + else: + # use server/host defined in path or operation instead + url = _host + resource_path + + # query parameters + if query_params: + query_params = self.sanitize_for_serialization(query_params) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) + url += "?" + url_query - if _return_http_data_only: - return (return_data) + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + + try: + # perform request and return response + response_data = self.rest_client.request( + method, url, + headers=header_params, + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + + except ApiException as e: + if e.body: + e.body = e.body.decode('utf-8') + raise e + + return response_data + + def response_deserialize( + self, + response_data=None, + response_types_map=None + ) -> ApiResponse: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + if not 200 <= response_data.status <= 299: + if response_data.status == 400: + raise BadRequestException(http_resp=response_data) + + if response_data.status == 401: + raise UnauthorizedException(http_resp=response_data) + + if response_data.status == 403: + raise ForbiddenException(http_resp=response_data) + + if response_data.status == 404: + raise NotFoundException(http_resp=response_data) + + if 500 <= response_data.status <= 599: + raise ServiceException(http_resp=response_data) + raise ApiException(http_resp=response_data) + + # deserialize response data + + if response_type == "bytearray": + return_data = response_data.data + elif response_type is None: + return_data = None + elif response_type == "file": + return_data = self.__deserialize_file(response_data) else: - return (return_data, response_data.status, - response_data.getheaders()) + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -176,7 +346,7 @@ def sanitize_for_serialization(self, obj): convert to string in iso8601 format. If obj is list, sanitize each element in the list. If obj is dict, return the dict. - If obj is swagger model, return the properties dict. + If obj is OpenAPI model, return the properties dict. :param obj: The data to serialize. :return: The serialized form of data. @@ -186,30 +356,32 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except - # attributes `swagger_types`, `attribute_map` + # attributes `openapi_types`, `attribute_map` # and attributes which value is not None. # Convert attribute name to json key in # model definition for request. - obj_dict = {obj.attribute_map[attr]: getattr(obj, attr) - for attr, _ in six.iteritems(obj.swagger_types) - if getattr(obj, attr) is not None} + obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in six.iteritems(obj_dict)} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -218,16 +390,12 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -242,16 +410,16 @@ def __deserialize(self, data, klass): if data is None: return None - if type(klass) == str: - if klass.startswith('list['): - sub_kls = re.match(r'list\[(.*)\]', klass).group(1) + if isinstance(klass, str): + if klass.startswith('List['): + sub_kls = re.match(r'List\[(.*)]', klass).group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] - if klass.startswith('dict('): - sub_kls = re.match(r'dict\(([^,]*), (.*)\)', klass).group(2) + if klass.startswith('Dict['): + sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) return {k: self.__deserialize(v, sub_kls) - for k, v in six.iteritems(data)} + for k, v in data.items()} # convert str to class if klass in self.NATIVE_TYPES_MAPPING: @@ -266,131 +434,10 @@ def __deserialize(self, data, klass): elif klass == datetime.date: return self.__deserialize_date(data) elif klass == datetime.datetime: - return self.__deserialize_datatime(data) + return self.__deserialize_datetime(data) else: return self.__deserialize_model(data, klass) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_type=None, auth_settings=None, async_req=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data without head status code - and headers - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - if not async_req: - return self.__call_api(resource_path, method, - path_params, query_params, header_params, - body, post_params, files, - response_type, auth_settings, - _return_http_data_only, collection_formats, - _preload_content, _request_timeout) - else: - thread = self.pool.apply_async(self.__call_api, (resource_path, - method, path_params, query_params, - header_params, body, - post_params, files, - response_type, auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, _request_timeout)) - return thread - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.GET(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.HEAD(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.OPTIONS(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "POST": - return self.rest_client.POST(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.PUT(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.PATCH(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.DELETE(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -401,7 +448,7 @@ def parameters_to_tuples(self, params, collection_formats): new_params = [] if collection_formats is None: collection_formats = {} - for k, v in six.iteritems(params) if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -421,20 +468,55 @@ def parameters_to_tuples(self, params, collection_formats): new_params.append((k, v)) return new_params - def prepare_post_parameters(self, post_params=None, files=None): + def parameters_to_url_query(self, params, collection_formats): + """Get parameters as list of tuples, formatting collections. + + :param params: Parameters as dict or list of two-tuples + :param dict collection_formats: Parameter collection formats + :return: URL query string (e.g. a=Hello%20World&b=123) + """ + new_params = [] + if collection_formats is None: + collection_formats = {} + for k, v in params.items() if isinstance(params, dict) else params: + if isinstance(v, bool): + v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) + if isinstance(v, dict): + v = json.dumps(v) + + if k in collection_formats: + collection_format = collection_formats[k] + if collection_format == 'multi': + new_params.extend((k, value) for value in v) + else: + if collection_format == 'ssv': + delimiter = ' ' + elif collection_format == 'tsv': + delimiter = '\t' + elif collection_format == 'pipes': + delimiter = '|' + else: # csv is the default + delimiter = ',' + new_params.append( + (k, delimiter.join(quote(str(value)) for value in v)) + ) + else: + new_params.append((k, quote(str(v)))) + + return "&".join(["=".join(item) for item in new_params]) + + def files_parameters(self, files=None): """Builds form parameters. - :param post_params: Normal form parameters. :param files: File parameters. :return: Form parameters with files. """ params = [] - if post_params: - params = post_params - if files: - for k, v in six.iteritems(files): + for k, v in files.items(): if not v: continue file_names = v if type(v) is list else [v] @@ -442,28 +524,30 @@ def prepare_post_parameters(self, post_params=None, files=None): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None - accepts = [x.lower() for x in accepts] + for accept in accepts: + if re.search('json', accept, re.IGNORECASE): + return accept - if 'application/json' in accepts: - return 'application/json' - else: - return ', '.join(accepts) + return accepts[0] def select_header_content_type(self, content_types): """Returns `Content-Type` based on an array of content_types provided. @@ -472,45 +556,101 @@ def select_header_content_type(self, content_types): :return: Content-Type (e.g. application/json). """ if not content_types: - return 'application/json' - - content_types = [x.lower() for x in content_types] - - if 'application/json' in content_types or '*/*' in content_types: - return 'application/json' - else: - return content_types[0] + return None - def update_params_for_auth(self, headers, querys, auth_settings): + for content_type in content_types: + if re.search('json', content_type, re.IGNORECASE): + return content_type + + return content_types[0] + + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. - :param querys: Query parameters tuple list to be updated. + :param queries: Query parameters tuple list to be updated. :param auth_settings: Authentication setting identifiers list. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param request_auth: if set, the provided settings will + override the token in the configuration. """ if not auth_settings: return - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - if not auth_setting['value']: - continue - elif auth_setting['in'] == 'header': - headers[auth_setting['key']] = auth_setting['value'] - elif auth_setting['in'] == 'query': - querys.append((auth_setting['key'], auth_setting['value'])) - else: - raise ValueError( - 'Authentication token must be in `query` or `header`' + if request_auth: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting ) + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: + """Updates the request parameters based on a single auth_setting + + :param headers: Header parameters dict to be updated. + :param queries: Query parameters tuple list to be updated. + :resource_path: A string representation of the HTTP request resource path. + :method: A string representation of the HTTP request method. + :body: A object representing the body of the HTTP request. + The object type is the return value of sanitize_for_serialization(). + :param auth_setting: auth settings for the endpoint + """ + if auth_setting['in'] == 'cookie': + headers['Cookie'] = auth_setting['value'] + elif auth_setting['in'] == 'header': + if auth_setting['type'] != 'http-signature': + headers[auth_setting['key']] = auth_setting['value'] + elif auth_setting['in'] == 'query': + queries.append((auth_setting['key'], auth_setting['value'])) + else: + raise ApiValueError( + 'Authentication token must be in `query` or `header`' + ) + def __deserialize_file(self, response): """Deserializes body to file Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -520,17 +660,15 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + filename = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ).group(1) path = os.path.join(os.path.dirname(path), filename) - response_data = response.data - with open(path, "wb") as f: - if isinstance(response_data, str): - # change str to bytes so we can write it - response_data = response_data.encode('utf-8') - f.write(response_data) - else: - f.write(response_data) + + with open(path, "wb") as f: + f.write(response.data) + return path def __deserialize_primitive(self, data, klass): @@ -544,12 +682,12 @@ def __deserialize_primitive(self, data, klass): try: return klass(data) except UnicodeEncodeError: - return six.text_type(data) + return str(data) except TypeError: return data def __deserialize_object(self, value): - """Return a original value. + """Return an original value. :return: object. """ @@ -562,7 +700,6 @@ def __deserialize_date(self, string): :return: date. """ try: - from dateutil.parser import parse return parse(string).date() except ImportError: return string @@ -572,7 +709,7 @@ def __deserialize_date(self, string): reason="Failed to parse `{0}` as date object".format(string) ) - def __deserialize_datatime(self, string): + def __deserialize_datetime(self, string): """Deserializes string to datetime. The string should be in iso8601 datetime format. @@ -581,7 +718,6 @@ def __deserialize_datatime(self, string): :return: datetime. """ try: - from dateutil.parser import parse return parse(string) except ImportError: return string @@ -594,9 +730,6 @@ def __deserialize_datatime(self, string): ) ) - def __hasattr(self, object, name): - return name in object.__class__.__dict__ - def __deserialize_model(self, data, klass): """Deserializes list or dict to model. @@ -605,28 +738,4 @@ def __deserialize_model(self, data, klass): :return: model object. """ - if not klass.swagger_types and not self.__hasattr(klass, 'get_real_child_model'): - return data - - kwargs = {} - if klass.swagger_types is not None: - for attr, attr_type in six.iteritems(klass.swagger_types): - if (data is not None and - klass.attribute_map[attr] in data and - isinstance(data, (list, dict))): - value = data[klass.attribute_map[attr]] - kwargs[attr] = self.__deserialize(value, attr_type) - - instance = klass(**kwargs) - - if (isinstance(instance, dict) and - klass.swagger_types is not None and - isinstance(data, dict)): - for key, value in data.items(): - if key not in klass.swagger_types: - instance[key] = value - if self.__hasattr(instance, 'get_real_child_model'): - klass_name = instance.get_real_child_model(data) - if klass_name: - instance = self.__deserialize(data, klass_name) - return instance + return klass.from_dict(data) diff --git a/python/sdk/client/api_response.py b/python/sdk/client/api_response.py new file mode 100644 index 000000000..2ac1ada6e --- /dev/null +++ b/python/sdk/client/api_response.py @@ -0,0 +1,21 @@ +"""API response object.""" + +from __future__ import annotations +from typing import Any, Dict, Optional, Generic, TypeVar +from pydantic import Field, StrictInt, StrictStr, StrictBytes, BaseModel + +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): + """ + API response object + """ + + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") + + model_config = { + "arbitrary_types_allowed": True + } diff --git a/python/sdk/client/configuration.py b/python/sdk/client/configuration.py index daf91a88e..81ec2b471 100644 --- a/python/sdk/client/configuration.py +++ b/python/sdk/client/configuration.py @@ -3,103 +3,248 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from __future__ import absolute_import import copy import logging -import multiprocessing import sys import urllib3 -import six -from six.moves import http_client as httplib - - -class TypeWithDefault(type): - def __init__(cls, name, bases, dct): - super(TypeWithDefault, cls).__init__(name, bases, dct) - cls._default = None - - def __call__(cls): - if cls._default is None: - cls._default = type.__call__(cls) - return copy.copy(cls._default) - - def set_default(cls, default): - cls._default = copy.copy(default) - - -class Configuration(six.with_metaclass(TypeWithDefault, object)): - """NOTE: This class is auto generated by the swagger code generator program. - - Ref: https://github.com/swagger-api/swagger-codegen - Do not edit the class manually. +import http.client as httplib + +JSON_SCHEMA_VALIDATION_KEYWORDS = { + 'multipleOf', 'maximum', 'exclusiveMaximum', + 'minimum', 'exclusiveMinimum', 'maxLength', + 'minLength', 'pattern', 'maxItems', 'minItems' +} + +class Configuration: + """This class contains various settings of the API client. + + :param host: Base url. + :param api_key: Dict to store API key(s). + Each entry in the dict specifies an API key. + The dict key is the name of the security scheme in the OAS specification. + The dict value is the API key secret. + :param api_key_prefix: Dict to store API prefix (e.g. Bearer). + The dict key is the name of the security scheme in the OAS specification. + The dict value is an API key prefix when generating the auth data. + :param username: Username for HTTP basic authentication. + :param password: Password for HTTP basic authentication. + :param access_token: Access token. + :param server_index: Index to servers configuration. + :param server_variables: Mapping with string values to replace variables in + templated server configuration. The validation of enums is performed for + variables with defined enum values before. + :param server_operation_index: Mapping from operation ID to an index to server + configuration. + :param server_operation_variables: Mapping from operation ID to a mapping with + string values to replace variables in templated server configuration. + The validation of enums is performed for variables with defined enum + values before. + :param ssl_ca_cert: str - the path to a file of concatenated CA certificates + in PEM format. + + :Example: + + API Key Authentication Example. + Given the following security scheme in the OpenAPI specification: + components: + securitySchemes: + cookieAuth: # name for the security scheme + type: apiKey + in: cookie + name: JSESSIONID # cookie name + + You can programmatically set the cookie: + +conf = client.Configuration( + api_key={'cookieAuth': 'abc123'} + api_key_prefix={'cookieAuth': 'JSESSIONID'} +) + + The following cookie will be added to the HTTP request: + Cookie: JSESSIONID abc123 """ - def __init__(self): - """Constructor""" - # Default Base url - self.host = "http://localhost:8080/v1" - # Temp file folder for downloading files + _default = None + + def __init__(self, host=None, + api_key=None, api_key_prefix=None, + username=None, password=None, + access_token=None, + server_index=None, server_variables=None, + server_operation_index=None, server_operation_variables=None, + ssl_ca_cert=None, + ) -> None: + """Constructor + """ + self._base_path = "http://localhost:8080/v1" if host is None else host + """Default Base url + """ + self.server_index = 0 if server_index is None and host is None else server_index + self.server_operation_index = server_operation_index or {} + """Default server index + """ + self.server_variables = server_variables or {} + self.server_operation_variables = server_operation_variables or {} + """Default server variables + """ self.temp_folder_path = None - + """Temp file folder for downloading files + """ # Authentication Settings - # dict to store API key(s) self.api_key = {} - # dict to store API prefix (e.g. Bearer) + if api_key: + self.api_key = api_key + """dict to store API key(s) + """ self.api_key_prefix = {} - # function to refresh API key if expired + if api_key_prefix: + self.api_key_prefix = api_key_prefix + """dict to store API prefix (e.g. Bearer) + """ self.refresh_api_key_hook = None - # Username for HTTP basic authentication - self.username = "" - # Password for HTTP basic authentication - self.password = "" - # Logging Settings + """function hook to refresh API key if expired + """ + self.username = username + """Username for HTTP basic authentication + """ + self.password = password + """Password for HTTP basic authentication + """ + self.access_token = access_token + """Access token + """ self.logger = {} + """Logging Settings + """ self.logger["package_logger"] = logging.getLogger("client") self.logger["urllib3_logger"] = logging.getLogger("urllib3") - # Log format self.logger_format = '%(asctime)s %(levelname)s %(message)s' - # Log stream handler + """Log format + """ self.logger_stream_handler = None - # Log file handler + """Log stream handler + """ self.logger_file_handler = None - # Debug file location + """Log file handler + """ self.logger_file = None - # Debug switch + """Debug file location + """ self.debug = False + """Debug switch + """ - # SSL/TLS verification - # Set this to false to skip verifying SSL certificate when calling API - # from https server. self.verify_ssl = True - # Set this to customize the certificate file to verify the peer. - self.ssl_ca_cert = None - # client certificate file + """SSL/TLS verification + Set this to false to skip verifying SSL certificate when calling API + from https server. + """ + self.ssl_ca_cert = ssl_ca_cert + """Set this to customize the certificate file to verify the peer. + """ self.cert_file = None - # client key file + """client certificate file + """ self.key_file = None - # Set this to True/False to enable/disable SSL hostname verification. + """client key file + """ self.assert_hostname = None + """Set this to True/False to enable/disable SSL hostname verification. + """ + self.tls_server_name = None + """SSL/TLS Server Name Indication (SNI) + Set this to the SNI value expected by the server. + """ - # urllib3 connection pool's maximum number of connections saved - # per pool. urllib3 uses 1 connection as default value, but this is - # not the best value when you are making a lot of possibly parallel - # requests to the same host, which is often the case here. - # cpu_count * 5 is used as default value to increase performance. - self.connection_pool_maxsize = multiprocessing.cpu_count() * 5 - # Proxy URL self.proxy = None - # Safe chars for path_param + """Proxy URL + """ + self.proxy_headers = None + """Proxy headers + """ self.safe_chars_for_path_param = '' + """Safe chars for path_param + """ + self.retries = None + """Adding retries to override urllib3 default value 3 + """ + # Enable client side validation + self.client_side_validation = True + + self.socket_options = None + """Options to pass down to the underlying urllib3 socket + """ + + self.datetime_format = "%Y-%m-%dT%H:%M:%S.%f%z" + """datetime format + """ + + self.date_format = "%Y-%m-%d" + """date format + """ + + def __deepcopy__(self, memo): + cls = self.__class__ + result = cls.__new__(cls) + memo[id(self)] = result + for k, v in self.__dict__.items(): + if k not in ('logger', 'logger_file_handler'): + setattr(result, k, copy.deepcopy(v, memo)) + # shallow copy of loggers + result.logger = copy.copy(self.logger) + # use setters to configure loggers + result.logger_file = self.logger_file + result.debug = self.debug + return result + + def __setattr__(self, name, value): + object.__setattr__(self, name, value) + + @classmethod + def set_default(cls, default): + """Set default instance of configuration. + + It stores default configuration, which can be + returned by get_default_copy method. + + :param default: object of Configuration + """ + cls._default = default + + @classmethod + def get_default_copy(cls): + """Deprecated. Please use `get_default` instead. + + Deprecated. Please use `get_default` instead. + + :return: The configuration object. + """ + return cls.get_default() + + @classmethod + def get_default(cls): + """Return the default configuration. + + This method returns newly created, based on default constructor, + object of Configuration class or returns a copy of default + configuration. + + :return: The configuration object. + """ + if cls._default is None: + cls._default = Configuration() + return cls._default @property def logger_file(self): @@ -129,19 +274,8 @@ def logger_file(self, value): # then add file handler and remove stream handler. self.logger_file_handler = logging.FileHandler(self.__logger_file) self.logger_file_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): + for _, logger in self.logger.items(): logger.addHandler(self.logger_file_handler) - if self.logger_stream_handler: - logger.removeHandler(self.logger_stream_handler) - else: - # If not set logging file, - # then add stream handler and remove file handler. - self.logger_stream_handler = logging.StreamHandler() - self.logger_stream_handler.setFormatter(self.logger_formatter) - for _, logger in six.iteritems(self.logger): - logger.addHandler(self.logger_stream_handler) - if self.logger_file_handler: - logger.removeHandler(self.logger_file_handler) @property def debug(self): @@ -162,14 +296,14 @@ def debug(self, value): self.__debug = value if self.__debug: # if debug status is True, turn on debug logging - for _, logger in six.iteritems(self.logger): + for _, logger in self.logger.items(): logger.setLevel(logging.DEBUG) # turn on httplib debug httplib.HTTPConnection.debuglevel = 1 else: # if debug status is False, turn off debug logging, # setting log level to default `logging.WARNING` - for _, logger in six.iteritems(self.logger): + for _, logger in self.logger.items(): logger.setLevel(logging.WARNING) # turn off httplib debug httplib.HTTPConnection.debuglevel = 0 @@ -197,16 +331,16 @@ def logger_format(self, value): self.__logger_format = value self.logger_formatter = logging.Formatter(self.__logger_format) - def get_api_key_with_prefix(self, identifier): + def get_api_key_with_prefix(self, identifier, alias=None): """Gets API key (with prefix if set). :param identifier: The identifier of apiKey. + :param alias: The alternative identifier of apiKey. :return: The token for api key authentication. """ - if self.refresh_api_key_hook: + if self.refresh_api_key_hook is not None: self.refresh_api_key_hook(self) - - key = self.api_key.get(identifier) + key = self.api_key.get(identifier, self.api_key.get(alias) if alias is not None else None) if key: prefix = self.api_key_prefix.get(identifier) if prefix: @@ -219,8 +353,14 @@ def get_basic_auth_token(self): :return: The token for basic HTTP authentication. """ + username = "" + if self.username is not None: + username = self.username + password = "" + if self.password is not None: + password = self.password return urllib3.util.make_headers( - basic_auth=self.username + ':' + self.password + basic_auth=username + ':' + password ).get('authorization') def auth_settings(self): @@ -228,15 +368,17 @@ def auth_settings(self): :return: The Auth Settings information dict. """ - return { - 'Bearer': - { - 'type': 'api_key', - 'in': 'header', - 'key': 'Authorization', - 'value': self.get_api_key_with_prefix('Authorization') - }, - } + auth = {} + if 'Bearer' in self.api_key: + auth['Bearer'] = { + 'type': 'api_key', + 'in': 'header', + 'key': 'Authorization', + 'value': self.get_api_key_with_prefix( + 'Bearer', + ), + } + return auth def to_debug_report(self): """Gets the essential information for debugging. @@ -249,3 +391,65 @@ def to_debug_report(self): "Version of the API: 0.14.0\n"\ "SDK Package Version: 1.0.0".\ format(env=sys.platform, pyversion=sys.version) + + def get_host_settings(self): + """Gets an array of host settings + + :return: An array of host settings + """ + return [ + { + 'url': "http://localhost:8080/v1", + 'description': "No description provided", + } + ] + + def get_host_from_settings(self, index, variables=None, servers=None): + """Gets host URL based on the index and variables + :param index: array index of the host settings + :param variables: hash of variable and the corresponding value + :param servers: an array of host settings or None + :return: URL based on host settings + """ + if index is None: + return self._base_path + + variables = {} if variables is None else variables + servers = self.get_host_settings() if servers is None else servers + + try: + server = servers[index] + except IndexError: + raise ValueError( + "Invalid index {0} when selecting the host settings. " + "Must be less than {1}".format(index, len(servers))) + + url = server['url'] + + # go through variables and replace placeholders + for variable_name, variable in server.get('variables', {}).items(): + used_value = variables.get( + variable_name, variable['default_value']) + + if 'enum_values' in variable \ + and used_value not in variable['enum_values']: + raise ValueError( + "The variable `{0}` in the host URL has invalid value " + "{1}. Must be {2}.".format( + variable_name, variables[variable_name], + variable['enum_values'])) + + url = url.replace("{" + variable_name + "}", used_value) + + return url + + @property + def host(self): + """Return generated host.""" + return self.get_host_from_settings(self.server_index, variables=self.server_variables) + + @host.setter + def host(self, value): + """Fix base path.""" + self._base_path = value + self.server_index = None diff --git a/python/sdk/client/exceptions.py b/python/sdk/client/exceptions.py new file mode 100644 index 000000000..6d3e960dc --- /dev/null +++ b/python/sdk/client/exceptions.py @@ -0,0 +1,166 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +class OpenApiException(Exception): + """The base exception class for all OpenAPIExceptions""" + + +class ApiTypeError(OpenApiException, TypeError): + def __init__(self, msg, path_to_item=None, valid_classes=None, + key_type=None) -> None: + """ Raises an exception for TypeErrors + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list): a list of keys an indices to get to the + current_item + None if unset + valid_classes (tuple): the primitive classes that current item + should be an instance of + None if unset + key_type (bool): False if our value is a value in a dict + True if it is a key in a dict + False if our item is an item in a list + None if unset + """ + self.path_to_item = path_to_item + self.valid_classes = valid_classes + self.key_type = key_type + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiTypeError, self).__init__(full_msg) + + +class ApiValueError(OpenApiException, ValueError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (list) the path to the exception in the + received_data dict. None if unset + """ + + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiValueError, self).__init__(full_msg) + + +class ApiAttributeError(OpenApiException, AttributeError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Raised when an attribute reference or assignment fails. + + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiAttributeError, self).__init__(full_msg) + + +class ApiKeyError(OpenApiException, KeyError): + def __init__(self, msg, path_to_item=None) -> None: + """ + Args: + msg (str): the exception message + + Keyword Args: + path_to_item (None/list) the path to the exception in the + received_data dict + """ + self.path_to_item = path_to_item + full_msg = msg + if path_to_item: + full_msg = "{0} at {1}".format(msg, render_path(path_to_item)) + super(ApiKeyError, self).__init__(full_msg) + + +class ApiException(OpenApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + if http_resp: + self.status = http_resp.status + self.reason = http_resp.reason + self.body = http_resp.data.decode('utf-8') + self.headers = http_resp.getheaders() + else: + self.status = status + self.reason = reason + self.body = None + self.headers = None + + def __str__(self): + """Custom error messages for exception""" + error_message = "({0})\n"\ + "Reason: {1}\n".format(self.status, self.reason) + if self.headers: + error_message += "HTTP response headers: {0}\n".format( + self.headers) + + if self.body: + error_message += "HTTP response body: {0}\n".format(self.body) + + return error_message + +class BadRequestException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(BadRequestException, self).__init__(status, reason, http_resp) + +class NotFoundException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(NotFoundException, self).__init__(status, reason, http_resp) + + +class UnauthorizedException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(UnauthorizedException, self).__init__(status, reason, http_resp) + + +class ForbiddenException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ForbiddenException, self).__init__(status, reason, http_resp) + + +class ServiceException(ApiException): + + def __init__(self, status=None, reason=None, http_resp=None) -> None: + super(ServiceException, self).__init__(status, reason, http_resp) + + +def render_path(path_to_item): + """Returns a string representation of a path""" + result = "" + for pth in path_to_item: + if isinstance(pth, int): + result += "[{0}]".format(pth) + else: + result += "['{0}']".format(pth) + return result diff --git a/python/sdk/client/models/__init__.py b/python/sdk/client/models/__init__.py index d4dcc14f2..ecbad6c1d 100644 --- a/python/sdk/client/models/__init__.py +++ b/python/sdk/client/models/__init__.py @@ -4,19 +4,20 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from __future__ import absolute_import # import models into model package from client.models.alert_condition_metric_type import AlertConditionMetricType from client.models.alert_condition_severity import AlertConditionSeverity from client.models.autoscaling_policy import AutoscalingPolicy +from client.models.binary_classification_output import BinaryClassificationOutput from client.models.config import Config from client.models.container import Container from client.models.custom_predictor import CustomPredictor @@ -25,7 +26,6 @@ from client.models.env_var import EnvVar from client.models.environment import Environment from client.models.file_format import FileFormat -from client.models.free_form_object import FreeFormObject from client.models.gpu_config import GPUConfig from client.models.gpu_toleration import GPUToleration from client.models.label import Label @@ -41,9 +41,11 @@ from client.models.model_endpoint_rule import ModelEndpointRule from client.models.model_endpoint_rule_destination import ModelEndpointRuleDestination from client.models.model_prediction_config import ModelPredictionConfig +from client.models.model_prediction_output import ModelPredictionOutput +from client.models.model_prediction_output_class import ModelPredictionOutputClass +from client.models.model_schema import ModelSchema from client.models.operation_tracing import OperationTracing from client.models.pipeline_tracing import PipelineTracing -from client.models.pipeline_tracing_inner import PipelineTracingInner from client.models.prediction_job import PredictionJob from client.models.prediction_job_config import PredictionJobConfig from client.models.prediction_job_config_bigquery_sink import PredictionJobConfigBigquerySink @@ -56,12 +58,16 @@ from client.models.prediction_logger_config import PredictionLoggerConfig from client.models.project import Project from client.models.protocol import Protocol +from client.models.ranking_output import RankingOutput +from client.models.regression_output import RegressionOutput from client.models.resource_request import ResourceRequest from client.models.result_type import ResultType from client.models.save_mode import SaveMode +from client.models.schema_spec import SchemaSpec from client.models.secret import Secret from client.models.standard_transformer_simulation_request import StandardTransformerSimulationRequest from client.models.standard_transformer_simulation_response import StandardTransformerSimulationResponse from client.models.transformer import Transformer +from client.models.value_type import ValueType from client.models.version import Version from client.models.version_endpoint import VersionEndpoint diff --git a/python/sdk/client/models/alert_condition_metric_type.py b/python/sdk/client/models/alert_condition_metric_type.py index 305b95530..d8830075f 100644 --- a/python/sdk/client/models/alert_condition_metric_type.py +++ b/python/sdk/client/models/alert_condition_metric_type.py @@ -3,91 +3,46 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class AlertConditionMetricType(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AlertConditionMetricType(str, Enum): """ - allowed enum values + AlertConditionMetricType """ - THROUGHPUT = "throughput" - LATENCY = "latency" - ERROR_RATE = "error_rate" - CPU = "cpu" - MEMORY = "memory" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """AlertConditionMetricType - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(AlertConditionMetricType, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + THROUGHPUT = 'throughput' + LATENCY = 'latency' + ERROR_RATE = 'error_rate' + CPU = 'cpu' + MEMORY = 'memory' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AlertConditionMetricType): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AlertConditionMetricType from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/alert_condition_severity.py b/python/sdk/client/models/alert_condition_severity.py index 67cddc5ff..2373ed37a 100644 --- a/python/sdk/client/models/alert_condition_severity.py +++ b/python/sdk/client/models/alert_condition_severity.py @@ -3,88 +3,43 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class AlertConditionSeverity(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class AlertConditionSeverity(str, Enum): """ - allowed enum values + AlertConditionSeverity """ - WARNING = "WARNING" - CRITICAL = "CRITICAL" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """AlertConditionSeverity - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(AlertConditionSeverity, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + WARNING = 'WARNING' + CRITICAL = 'CRITICAL' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AlertConditionSeverity): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AlertConditionSeverity from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/autoscaling_policy.py b/python/sdk/client/models/autoscaling_policy.py index 2550b4635..91d394566 100644 --- a/python/sdk/client/models/autoscaling_policy.py +++ b/python/sdk/client/models/autoscaling_policy.py @@ -3,134 +3,88 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class AutoscalingPolicy(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Union +from pydantic import BaseModel, StrictFloat, StrictInt +from client.models.metrics_type import MetricsType +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class AutoscalingPolicy(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'metrics_type': 'MetricsType', - 'target_value': 'float' - } - - attribute_map = { - 'metrics_type': 'metrics_type', - 'target_value': 'target_value' + AutoscalingPolicy + """ # noqa: E501 + metrics_type: MetricsType + target_value: Union[StrictFloat, StrictInt] + __properties: ClassVar[List[str]] = ["metrics_type", "target_value"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, metrics_type=None, target_value=None): # noqa: E501 - """AutoscalingPolicy - a model defined in Swagger""" # noqa: E501 - self._metrics_type = None - self._target_value = None - self.discriminator = None - if metrics_type is not None: - self.metrics_type = metrics_type - if target_value is not None: - self.target_value = target_value - @property - def metrics_type(self): - """Gets the metrics_type of this AutoscalingPolicy. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The metrics_type of this AutoscalingPolicy. # noqa: E501 - :rtype: MetricsType - """ - return self._metrics_type + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of AutoscalingPolicy from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @metrics_type.setter - def metrics_type(self, metrics_type): - """Sets the metrics_type of this AutoscalingPolicy. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param metrics_type: The metrics_type of this AutoscalingPolicy. # noqa: E501 - :type: MetricsType + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of AutoscalingPolicy from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "metrics_type": obj.get("metrics_type"), + "target_value": obj.get("target_value") + }) + return _obj - self._metrics_type = metrics_type - - @property - def target_value(self): - """Gets the target_value of this AutoscalingPolicy. # noqa: E501 - - - :return: The target_value of this AutoscalingPolicy. # noqa: E501 - :rtype: float - """ - return self._target_value - - @target_value.setter - def target_value(self, target_value): - """Sets the target_value of this AutoscalingPolicy. - - - :param target_value: The target_value of this AutoscalingPolicy. # noqa: E501 - :type: float - """ - self._target_value = target_value - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(AutoscalingPolicy, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, AutoscalingPolicy): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/binary_classification_output.py b/python/sdk/client/models/binary_classification_output.py new file mode 100644 index 000000000..1d829d260 --- /dev/null +++ b/python/sdk/client/models/binary_classification_output.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel, StrictFloat, StrictInt, StrictStr +from client.models.model_prediction_output_class import ModelPredictionOutputClass +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class BinaryClassificationOutput(BaseModel): + """ + BinaryClassificationOutput + """ # noqa: E501 + prediction_score_column: StrictStr + actual_label_column: Optional[StrictStr] = None + positive_class_label: StrictStr + negative_class_label: StrictStr + score_threshold: Optional[Union[StrictFloat, StrictInt]] = None + output_class: Optional[ModelPredictionOutputClass] = None + __properties: ClassVar[List[str]] = ["prediction_score_column", "actual_label_column", "positive_class_label", "negative_class_label", "score_threshold", "output_class"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of BinaryClassificationOutput from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of BinaryClassificationOutput from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "prediction_score_column": obj.get("prediction_score_column"), + "actual_label_column": obj.get("actual_label_column"), + "positive_class_label": obj.get("positive_class_label"), + "negative_class_label": obj.get("negative_class_label"), + "score_threshold": obj.get("score_threshold"), + "output_class": obj.get("output_class") + }) + return _obj + + diff --git a/python/sdk/client/models/config.py b/python/sdk/client/models/config.py index c96a24637..ded1b26fd 100644 --- a/python/sdk/client/models/config.py +++ b/python/sdk/client/models/config.py @@ -3,238 +3,115 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class Config(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.env_var import EnvVar +from client.models.prediction_job_config import PredictionJobConfig +from client.models.prediction_job_resource_request import PredictionJobResourceRequest +from client.models.resource_request import ResourceRequest +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +class Config(BaseModel): """ - swagger_types = { - 'job_config': 'PredictionJobConfig', - 'image_ref': 'str', - 'service_account_name': 'str', - 'resource_request': 'PredictionJobResourceRequest', - 'image_builder_resource_request': 'ResourceRequest', - 'env_vars': 'list[EnvVar]' + Config + """ # noqa: E501 + job_config: Optional[PredictionJobConfig] = None + image_ref: Optional[StrictStr] = None + service_account_name: Optional[StrictStr] = None + resource_request: Optional[PredictionJobResourceRequest] = None + image_builder_resource_request: Optional[ResourceRequest] = None + env_vars: Optional[List[EnvVar]] = None + __properties: ClassVar[List[str]] = ["job_config", "image_ref", "service_account_name", "resource_request", "image_builder_resource_request", "env_vars"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'job_config': 'job_config', - 'image_ref': 'image_ref', - 'service_account_name': 'service_account_name', - 'resource_request': 'resource_request', - 'image_builder_resource_request': 'image_builder_resource_request', - 'env_vars': 'env_vars' - } - - def __init__(self, job_config=None, image_ref=None, service_account_name=None, resource_request=None, image_builder_resource_request=None, env_vars=None): # noqa: E501 - """Config - a model defined in Swagger""" # noqa: E501 - self._job_config = None - self._image_ref = None - self._service_account_name = None - self._resource_request = None - self._image_builder_resource_request = None - self._env_vars = None - self.discriminator = None - if job_config is not None: - self.job_config = job_config - if image_ref is not None: - self.image_ref = image_ref - if service_account_name is not None: - self.service_account_name = service_account_name - if resource_request is not None: - self.resource_request = resource_request - if image_builder_resource_request is not None: - self.image_builder_resource_request = image_builder_resource_request - if env_vars is not None: - self.env_vars = env_vars - - @property - def job_config(self): - """Gets the job_config of this Config. # noqa: E501 - - - :return: The job_config of this Config. # noqa: E501 - :rtype: PredictionJobConfig - """ - return self._job_config - - @job_config.setter - def job_config(self, job_config): - """Sets the job_config of this Config. - - - :param job_config: The job_config of this Config. # noqa: E501 - :type: PredictionJobConfig - """ - - self._job_config = job_config - @property - def image_ref(self): - """Gets the image_ref of this Config. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The image_ref of this Config. # noqa: E501 - :rtype: str - """ - return self._image_ref + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Config from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @image_ref.setter - def image_ref(self, image_ref): - """Sets the image_ref of this Config. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param image_ref: The image_ref of this Config. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of job_config + if self.job_config: + _dict['job_config'] = self.job_config.to_dict() + # override the default output from pydantic by calling `to_dict()` of resource_request + if self.resource_request: + _dict['resource_request'] = self.resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of image_builder_resource_request + if self.image_builder_resource_request: + _dict['image_builder_resource_request'] = self.image_builder_resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in env_vars (list) + _items = [] + if self.env_vars: + for _item in self.env_vars: + if _item: + _items.append(_item.to_dict()) + _dict['env_vars'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Config from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "job_config": PredictionJobConfig.from_dict(obj.get("job_config")) if obj.get("job_config") is not None else None, + "image_ref": obj.get("image_ref"), + "service_account_name": obj.get("service_account_name"), + "resource_request": PredictionJobResourceRequest.from_dict(obj.get("resource_request")) if obj.get("resource_request") is not None else None, + "image_builder_resource_request": ResourceRequest.from_dict(obj.get("image_builder_resource_request")) if obj.get("image_builder_resource_request") is not None else None, + "env_vars": [EnvVar.from_dict(_item) for _item in obj.get("env_vars")] if obj.get("env_vars") is not None else None + }) + return _obj - self._image_ref = image_ref - - @property - def service_account_name(self): - """Gets the service_account_name of this Config. # noqa: E501 - - - :return: The service_account_name of this Config. # noqa: E501 - :rtype: str - """ - return self._service_account_name - - @service_account_name.setter - def service_account_name(self, service_account_name): - """Sets the service_account_name of this Config. - - - :param service_account_name: The service_account_name of this Config. # noqa: E501 - :type: str - """ - - self._service_account_name = service_account_name - - @property - def resource_request(self): - """Gets the resource_request of this Config. # noqa: E501 - - - :return: The resource_request of this Config. # noqa: E501 - :rtype: PredictionJobResourceRequest - """ - return self._resource_request - - @resource_request.setter - def resource_request(self, resource_request): - """Sets the resource_request of this Config. - - - :param resource_request: The resource_request of this Config. # noqa: E501 - :type: PredictionJobResourceRequest - """ - - self._resource_request = resource_request - - @property - def image_builder_resource_request(self): - """Gets the image_builder_resource_request of this Config. # noqa: E501 - - - :return: The image_builder_resource_request of this Config. # noqa: E501 - :rtype: ResourceRequest - """ - return self._image_builder_resource_request - - @image_builder_resource_request.setter - def image_builder_resource_request(self, image_builder_resource_request): - """Sets the image_builder_resource_request of this Config. - - - :param image_builder_resource_request: The image_builder_resource_request of this Config. # noqa: E501 - :type: ResourceRequest - """ - - self._image_builder_resource_request = image_builder_resource_request - - @property - def env_vars(self): - """Gets the env_vars of this Config. # noqa: E501 - - - :return: The env_vars of this Config. # noqa: E501 - :rtype: list[EnvVar] - """ - return self._env_vars - - @env_vars.setter - def env_vars(self, env_vars): - """Sets the env_vars of this Config. - - - :param env_vars: The env_vars of this Config. # noqa: E501 - :type: list[EnvVar] - """ - self._env_vars = env_vars - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Config, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Config): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/container.py b/python/sdk/client/models/container.py index c4b2a87c3..96b530c97 100644 --- a/python/sdk/client/models/container.py +++ b/python/sdk/client/models/container.py @@ -3,270 +3,107 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class Container(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr, field_validator +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class Container(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'name': 'str', - 'pod_name': 'str', - 'component_type': 'str', - 'namespace': 'str', - 'cluster': 'str', - 'gcp_project': 'str', - 'version_endpoint_id': 'int' - } - - attribute_map = { - 'name': 'name', - 'pod_name': 'pod_name', - 'component_type': 'component_type', - 'namespace': 'namespace', - 'cluster': 'cluster', - 'gcp_project': 'gcp_project', - 'version_endpoint_id': 'version_endpoint_id' + Container + """ # noqa: E501 + name: Optional[StrictStr] = None + pod_name: Optional[StrictStr] = None + component_type: Optional[StrictStr] = None + namespace: Optional[StrictStr] = None + cluster: Optional[StrictStr] = None + gcp_project: Optional[StrictStr] = None + version_endpoint_id: Optional[StrictInt] = None + __properties: ClassVar[List[str]] = ["name", "pod_name", "component_type", "namespace", "cluster", "gcp_project", "version_endpoint_id"] + + @field_validator('component_type') + def component_type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in ('image_builder', 'model', 'transformer', 'batch_job_driver', 'batch_job_executor'): + raise ValueError("must be one of enum values ('image_builder', 'model', 'transformer', 'batch_job_driver', 'batch_job_executor')") + return value + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, name=None, pod_name=None, component_type=None, namespace=None, cluster=None, gcp_project=None, version_endpoint_id=None): # noqa: E501 - """Container - a model defined in Swagger""" # noqa: E501 - self._name = None - self._pod_name = None - self._component_type = None - self._namespace = None - self._cluster = None - self._gcp_project = None - self._version_endpoint_id = None - self.discriminator = None - if name is not None: - self.name = name - if pod_name is not None: - self.pod_name = pod_name - if component_type is not None: - self.component_type = component_type - if namespace is not None: - self.namespace = namespace - if cluster is not None: - self.cluster = cluster - if gcp_project is not None: - self.gcp_project = gcp_project - if version_endpoint_id is not None: - self.version_endpoint_id = version_endpoint_id - - @property - def name(self): - """Gets the name of this Container. # noqa: E501 - - - :return: The name of this Container. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Container. - - - :param name: The name of this Container. # noqa: E501 - :type: str - """ - - self._name = name - @property - def pod_name(self): - """Gets the pod_name of this Container. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The pod_name of this Container. # noqa: E501 - :rtype: str - """ - return self._pod_name - - @pod_name.setter - def pod_name(self, pod_name): - """Sets the pod_name of this Container. - - - :param pod_name: The pod_name of this Container. # noqa: E501 - :type: str - """ - - self._pod_name = pod_name - - @property - def component_type(self): - """Gets the component_type of this Container. # noqa: E501 - - - :return: The component_type of this Container. # noqa: E501 - :rtype: str - """ - return self._component_type + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Container from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @component_type.setter - def component_type(self, component_type): - """Sets the component_type of this Container. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param component_type: The component_type of this Container. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - allowed_values = ["image_builder", "model", "transformer", "batch_job_driver", "batch_job_executor"] # noqa: E501 - if component_type not in allowed_values: - raise ValueError( - "Invalid value for `component_type` ({0}), must be one of {1}" # noqa: E501 - .format(component_type, allowed_values) - ) - - self._component_type = component_type - - @property - def namespace(self): - """Gets the namespace of this Container. # noqa: E501 - - - :return: The namespace of this Container. # noqa: E501 - :rtype: str - """ - return self._namespace - - @namespace.setter - def namespace(self, namespace): - """Sets the namespace of this Container. - - - :param namespace: The namespace of this Container. # noqa: E501 - :type: str - """ - - self._namespace = namespace - - @property - def cluster(self): - """Gets the cluster of this Container. # noqa: E501 - - - :return: The cluster of this Container. # noqa: E501 - :rtype: str - """ - return self._cluster - - @cluster.setter - def cluster(self, cluster): - """Sets the cluster of this Container. - - - :param cluster: The cluster of this Container. # noqa: E501 - :type: str - """ - - self._cluster = cluster - - @property - def gcp_project(self): - """Gets the gcp_project of this Container. # noqa: E501 - - - :return: The gcp_project of this Container. # noqa: E501 - :rtype: str - """ - return self._gcp_project - - @gcp_project.setter - def gcp_project(self, gcp_project): - """Sets the gcp_project of this Container. - - - :param gcp_project: The gcp_project of this Container. # noqa: E501 - :type: str - """ - - self._gcp_project = gcp_project - - @property - def version_endpoint_id(self): - """Gets the version_endpoint_id of this Container. # noqa: E501 - - - :return: The version_endpoint_id of this Container. # noqa: E501 - :rtype: int - """ - return self._version_endpoint_id - - @version_endpoint_id.setter - def version_endpoint_id(self, version_endpoint_id): - """Sets the version_endpoint_id of this Container. - - - :param version_endpoint_id: The version_endpoint_id of this Container. # noqa: E501 - :type: int - """ - - self._version_endpoint_id = version_endpoint_id - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Container, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Container): - return False + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Container from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "pod_name": obj.get("pod_name"), + "component_type": obj.get("component_type"), + "namespace": obj.get("namespace"), + "cluster": obj.get("cluster"), + "gcp_project": obj.get("gcp_project"), + "version_endpoint_id": obj.get("version_endpoint_id") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/custom_predictor.py b/python/sdk/client/models/custom_predictor.py index 859d9e384..63a0bdfd9 100644 --- a/python/sdk/client/models/custom_predictor.py +++ b/python/sdk/client/models/custom_predictor.py @@ -3,160 +3,89 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class CustomPredictor(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class CustomPredictor(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'image': 'str', - 'command': 'str', - 'args': 'str' - } - - attribute_map = { - 'image': 'image', - 'command': 'command', - 'args': 'args' + CustomPredictor + """ # noqa: E501 + image: Optional[StrictStr] = None + command: Optional[StrictStr] = None + args: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["image", "command", "args"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, image=None, command=None, args=None): # noqa: E501 - """CustomPredictor - a model defined in Swagger""" # noqa: E501 - self._image = None - self._command = None - self._args = None - self.discriminator = None - if image is not None: - self.image = image - if command is not None: - self.command = command - if args is not None: - self.args = args - - @property - def image(self): - """Gets the image of this CustomPredictor. # noqa: E501 - - - :return: The image of this CustomPredictor. # noqa: E501 - :rtype: str - """ - return self._image - - @image.setter - def image(self, image): - """Sets the image of this CustomPredictor. - - :param image: The image of this CustomPredictor. # noqa: E501 - :type: str - """ - - self._image = image - - @property - def command(self): - """Gets the command of this CustomPredictor. # noqa: E501 - - - :return: The command of this CustomPredictor. # noqa: E501 - :rtype: str - """ - return self._command + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @command.setter - def command(self, command): - """Sets the command of this CustomPredictor. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of CustomPredictor from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param command: The command of this CustomPredictor. # noqa: E501 - :type: str - """ - - self._command = command - - @property - def args(self): - """Gets the args of this CustomPredictor. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The args of this CustomPredictor. # noqa: E501 - :rtype: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._args + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of CustomPredictor from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "image": obj.get("image"), + "command": obj.get("command"), + "args": obj.get("args") + }) + return _obj - @args.setter - def args(self, args): - """Sets the args of this CustomPredictor. - - - :param args: The args of this CustomPredictor. # noqa: E501 - :type: str - """ - self._args = args - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(CustomPredictor, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, CustomPredictor): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/deployment_mode.py b/python/sdk/client/models/deployment_mode.py index 79deed56f..8f506cd7e 100644 --- a/python/sdk/client/models/deployment_mode.py +++ b/python/sdk/client/models/deployment_mode.py @@ -3,88 +3,43 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class DeploymentMode(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class DeploymentMode(str, Enum): """ - allowed enum values + DeploymentMode """ - SERVERLESS = "serverless" - RAW_DEPLOYMENT = "raw_deployment" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """DeploymentMode - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(DeploymentMode, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + SERVERLESS = 'serverless' + RAW_DEPLOYMENT = 'raw_deployment' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, DeploymentMode): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of DeploymentMode from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/endpoint_status.py b/python/sdk/client/models/endpoint_status.py index cac07fd7e..f83ec5700 100644 --- a/python/sdk/client/models/endpoint_status.py +++ b/python/sdk/client/models/endpoint_status.py @@ -3,91 +3,46 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class EndpointStatus(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class EndpointStatus(str, Enum): """ - allowed enum values + EndpointStatus """ - PENDING = "pending" - RUNNING = "running" - SERVING = "serving" - FAILED = "failed" - TERMINATED = "terminated" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """EndpointStatus - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(EndpointStatus, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + PENDING = 'pending' + RUNNING = 'running' + SERVING = 'serving' + FAILED = 'failed' + TERMINATED = 'terminated' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, EndpointStatus): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of EndpointStatus from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/env_var.py b/python/sdk/client/models/env_var.py index cceb09873..4f5720a99 100644 --- a/python/sdk/client/models/env_var.py +++ b/python/sdk/client/models/env_var.py @@ -3,134 +3,87 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class EnvVar(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class EnvVar(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'name': 'str', - 'value': 'str' - } - - attribute_map = { - 'name': 'name', - 'value': 'value' + EnvVar + """ # noqa: E501 + name: Optional[StrictStr] = None + value: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["name", "value"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, name=None, value=None): # noqa: E501 - """EnvVar - a model defined in Swagger""" # noqa: E501 - self._name = None - self._value = None - self.discriminator = None - if name is not None: - self.name = name - if value is not None: - self.value = value - @property - def name(self): - """Gets the name of this EnvVar. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The name of this EnvVar. # noqa: E501 - :rtype: str - """ - return self._name + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of EnvVar from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @name.setter - def name(self, name): - """Sets the name of this EnvVar. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param name: The name of this EnvVar. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of EnvVar from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "value": obj.get("value") + }) + return _obj - self._name = name - - @property - def value(self): - """Gets the value of this EnvVar. # noqa: E501 - - - :return: The value of this EnvVar. # noqa: E501 - :rtype: str - """ - return self._value - - @value.setter - def value(self, value): - """Sets the value of this EnvVar. - - - :param value: The value of this EnvVar. # noqa: E501 - :type: str - """ - self._value = value - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(EnvVar, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, EnvVar): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/environment.py b/python/sdk/client/models/environment.py index 74fe16193..bbdcef6cf 100644 --- a/python/sdk/client/models/environment.py +++ b/python/sdk/client/models/environment.py @@ -3,395 +3,126 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class Environment(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictBool, StrictInt, StrictStr +from client.models.gpu_config import GPUConfig +from client.models.prediction_job_resource_request import PredictionJobResourceRequest +from client.models.resource_request import ResourceRequest +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Environment(BaseModel): """ - swagger_types = { - 'id': 'int', - 'name': 'str', - 'cluster': 'str', - 'is_default': 'bool', - 'region': 'str', - 'gcp_project': 'str', - 'default_resource_request': 'ResourceRequest', - 'default_transformer_resource_request': 'ResourceRequest', - 'default_prediction_job_resource_request': 'PredictionJobResourceRequest', - 'gpus': 'list[GPUConfig]', - 'created_at': 'datetime', - 'updated_at': 'datetime' - } - - attribute_map = { - 'id': 'id', - 'name': 'name', - 'cluster': 'cluster', - 'is_default': 'is_default', - 'region': 'region', - 'gcp_project': 'gcp_project', - 'default_resource_request': 'default_resource_request', - 'default_transformer_resource_request': 'default_transformer_resource_request', - 'default_prediction_job_resource_request': 'default_prediction_job_resource_request', - 'gpus': 'gpus', - 'created_at': 'created_at', - 'updated_at': 'updated_at' + Environment + """ # noqa: E501 + id: Optional[StrictInt] = None + name: StrictStr + cluster: StrictStr + is_default: Optional[StrictBool] = None + region: Optional[StrictStr] = None + gcp_project: Optional[StrictStr] = None + default_resource_request: Optional[ResourceRequest] = None + default_transformer_resource_request: Optional[ResourceRequest] = None + default_prediction_job_resource_request: Optional[PredictionJobResourceRequest] = None + gpus: Optional[List[GPUConfig]] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "name", "cluster", "is_default", "region", "gcp_project", "default_resource_request", "default_transformer_resource_request", "default_prediction_job_resource_request", "gpus", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, id=None, name=None, cluster=None, is_default=None, region=None, gcp_project=None, default_resource_request=None, default_transformer_resource_request=None, default_prediction_job_resource_request=None, gpus=None, created_at=None, updated_at=None): # noqa: E501 - """Environment - a model defined in Swagger""" # noqa: E501 - self._id = None - self._name = None - self._cluster = None - self._is_default = None - self._region = None - self._gcp_project = None - self._default_resource_request = None - self._default_transformer_resource_request = None - self._default_prediction_job_resource_request = None - self._gpus = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - self.name = name - if cluster is not None: - self.cluster = cluster - if is_default is not None: - self.is_default = is_default - if region is not None: - self.region = region - if gcp_project is not None: - self.gcp_project = gcp_project - if default_resource_request is not None: - self.default_resource_request = default_resource_request - if default_transformer_resource_request is not None: - self.default_transformer_resource_request = default_transformer_resource_request - if default_prediction_job_resource_request is not None: - self.default_prediction_job_resource_request = default_prediction_job_resource_request - if gpus is not None: - self.gpus = gpus - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this Environment. # noqa: E501 - - - :return: The id of this Environment. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Environment. - - - :param id: The id of this Environment. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this Environment. # noqa: E501 - - - :return: The name of this Environment. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Environment. - - - :param name: The name of this Environment. # noqa: E501 - :type: str - """ - if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def cluster(self): - """Gets the cluster of this Environment. # noqa: E501 - - - :return: The cluster of this Environment. # noqa: E501 - :rtype: str - """ - return self._cluster - - @cluster.setter - def cluster(self, cluster): - """Sets the cluster of this Environment. - - - :param cluster: The cluster of this Environment. # noqa: E501 - :type: str - """ - - self._cluster = cluster - - @property - def is_default(self): - """Gets the is_default of this Environment. # noqa: E501 - - - :return: The is_default of this Environment. # noqa: E501 - :rtype: bool - """ - return self._is_default - - @is_default.setter - def is_default(self, is_default): - """Sets the is_default of this Environment. - - - :param is_default: The is_default of this Environment. # noqa: E501 - :type: bool - """ - - self._is_default = is_default - - @property - def region(self): - """Gets the region of this Environment. # noqa: E501 - - - :return: The region of this Environment. # noqa: E501 - :rtype: str - """ - return self._region - - @region.setter - def region(self, region): - """Sets the region of this Environment. - - - :param region: The region of this Environment. # noqa: E501 - :type: str - """ - - self._region = region - - @property - def gcp_project(self): - """Gets the gcp_project of this Environment. # noqa: E501 - - - :return: The gcp_project of this Environment. # noqa: E501 - :rtype: str - """ - return self._gcp_project - - @gcp_project.setter - def gcp_project(self, gcp_project): - """Sets the gcp_project of this Environment. - - - :param gcp_project: The gcp_project of this Environment. # noqa: E501 - :type: str - """ - - self._gcp_project = gcp_project - - @property - def default_resource_request(self): - """Gets the default_resource_request of this Environment. # noqa: E501 - - - :return: The default_resource_request of this Environment. # noqa: E501 - :rtype: ResourceRequest - """ - return self._default_resource_request - - @default_resource_request.setter - def default_resource_request(self, default_resource_request): - """Sets the default_resource_request of this Environment. - - - :param default_resource_request: The default_resource_request of this Environment. # noqa: E501 - :type: ResourceRequest - """ - - self._default_resource_request = default_resource_request - - @property - def default_transformer_resource_request(self): - """Gets the default_transformer_resource_request of this Environment. # noqa: E501 - - - :return: The default_transformer_resource_request of this Environment. # noqa: E501 - :rtype: ResourceRequest - """ - return self._default_transformer_resource_request - - @default_transformer_resource_request.setter - def default_transformer_resource_request(self, default_transformer_resource_request): - """Sets the default_transformer_resource_request of this Environment. - - - :param default_transformer_resource_request: The default_transformer_resource_request of this Environment. # noqa: E501 - :type: ResourceRequest - """ - - self._default_transformer_resource_request = default_transformer_resource_request - - @property - def default_prediction_job_resource_request(self): - """Gets the default_prediction_job_resource_request of this Environment. # noqa: E501 - - - :return: The default_prediction_job_resource_request of this Environment. # noqa: E501 - :rtype: PredictionJobResourceRequest - """ - return self._default_prediction_job_resource_request - - @default_prediction_job_resource_request.setter - def default_prediction_job_resource_request(self, default_prediction_job_resource_request): - """Sets the default_prediction_job_resource_request of this Environment. - - - :param default_prediction_job_resource_request: The default_prediction_job_resource_request of this Environment. # noqa: E501 - :type: PredictionJobResourceRequest - """ - - self._default_prediction_job_resource_request = default_prediction_job_resource_request - - @property - def gpus(self): - """Gets the gpus of this Environment. # noqa: E501 - - - :return: The gpus of this Environment. # noqa: E501 - :rtype: list[GPUConfig] - """ - return self._gpus - - @gpus.setter - def gpus(self, gpus): - """Sets the gpus of this Environment. - - - :param gpus: The gpus of this Environment. # noqa: E501 - :type: list[GPUConfig] - """ - - self._gpus = gpus - - @property - def created_at(self): - """Gets the created_at of this Environment. # noqa: E501 - - - :return: The created_at of this Environment. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this Environment. - - - :param created_at: The created_at of this Environment. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this Environment. # noqa: E501 - - - :return: The updated_at of this Environment. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this Environment. - - - :param updated_at: The updated_at of this Environment. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Environment, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Environment): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Environment from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of default_resource_request + if self.default_resource_request: + _dict['default_resource_request'] = self.default_resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of default_transformer_resource_request + if self.default_transformer_resource_request: + _dict['default_transformer_resource_request'] = self.default_transformer_resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of default_prediction_job_resource_request + if self.default_prediction_job_resource_request: + _dict['default_prediction_job_resource_request'] = self.default_prediction_job_resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in gpus (list) + _items = [] + if self.gpus: + for _item in self.gpus: + if _item: + _items.append(_item.to_dict()) + _dict['gpus'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Environment from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "cluster": obj.get("cluster"), + "is_default": obj.get("is_default"), + "region": obj.get("region"), + "gcp_project": obj.get("gcp_project"), + "default_resource_request": ResourceRequest.from_dict(obj.get("default_resource_request")) if obj.get("default_resource_request") is not None else None, + "default_transformer_resource_request": ResourceRequest.from_dict(obj.get("default_transformer_resource_request")) if obj.get("default_transformer_resource_request") is not None else None, + "default_prediction_job_resource_request": PredictionJobResourceRequest.from_dict(obj.get("default_prediction_job_resource_request")) if obj.get("default_prediction_job_resource_request") is not None else None, + "gpus": [GPUConfig.from_dict(_item) for _item in obj.get("gpus")] if obj.get("gpus") is not None else None, + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/file_format.py b/python/sdk/client/models/file_format.py index e42f16eee..350e425f7 100644 --- a/python/sdk/client/models/file_format.py +++ b/python/sdk/client/models/file_format.py @@ -3,91 +3,46 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class FileFormat(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class FileFormat(str, Enum): """ - allowed enum values + FileFormat """ - INVALID_FILE_FORMAT = "INVALID_FILE_FORMAT" - CSV = "CSV" - PARQUET = "PARQUET" - AVRO = "AVRO" - JSON = "JSON" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """FileFormat - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(FileFormat, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + INVALID_FILE_FORMAT = 'INVALID_FILE_FORMAT' + CSV = 'CSV' + PARQUET = 'PARQUET' + AVRO = 'AVRO' + JSON = 'JSON' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, FileFormat): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of FileFormat from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/free_form_object.py b/python/sdk/client/models/free_form_object.py deleted file mode 100644 index cd8258ec2..000000000 --- a/python/sdk/client/models/free_form_object.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -""" - Merlin - - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 - - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - -class FreeFormObject(dict): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - } - if hasattr(dict, "swagger_types"): - swagger_types.update(dict.swagger_types) # type: ignore[attr-defined] - - attribute_map = { - } - if hasattr(dict, "attribute_map"): - attribute_map.update(dict.attribute_map) # type: ignore[attr-defined] - - def __init__(self, *args, **kwargs): # noqa: E501 - """FreeFormObject - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - dict.__init__(self, *args, **kwargs) - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(FreeFormObject, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, FreeFormObject): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/gpu_config.py b/python/sdk/client/models/gpu_config.py index a75ecf4ab..c26829fdf 100644 --- a/python/sdk/client/models/gpu_config.py +++ b/python/sdk/client/models/gpu_config.py @@ -3,264 +3,105 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class GPUConfig(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel, StrictFloat, StrictInt, StrictStr +from client.models.gpu_toleration import GPUToleration +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class GPUConfig(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'name': 'str', - 'values': 'list[str]', - 'resource_type': 'str', - 'node_selector': 'dict(str, str)', - 'tolerations': 'list[GPUToleration]', - 'min_monthly_cost_per_gpu': 'float', - 'max_monthly_cost_per_gpu': 'float' - } - - attribute_map = { - 'name': 'name', - 'values': 'values', - 'resource_type': 'resource_type', - 'node_selector': 'node_selector', - 'tolerations': 'tolerations', - 'min_monthly_cost_per_gpu': 'min_monthly_cost_per_gpu', - 'max_monthly_cost_per_gpu': 'max_monthly_cost_per_gpu' + GPUConfig + """ # noqa: E501 + name: Optional[StrictStr] = None + values: Optional[List[StrictStr]] = None + resource_type: Optional[StrictStr] = None + node_selector: Optional[Dict[str, StrictStr]] = None + tolerations: Optional[List[GPUToleration]] = None + min_monthly_cost_per_gpu: Optional[Union[StrictFloat, StrictInt]] = None + max_monthly_cost_per_gpu: Optional[Union[StrictFloat, StrictInt]] = None + __properties: ClassVar[List[str]] = ["name", "values", "resource_type", "node_selector", "tolerations", "min_monthly_cost_per_gpu", "max_monthly_cost_per_gpu"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, name=None, values=None, resource_type=None, node_selector=None, tolerations=None, min_monthly_cost_per_gpu=None, max_monthly_cost_per_gpu=None): # noqa: E501 - """GPUConfig - a model defined in Swagger""" # noqa: E501 - self._name = None - self._values = None - self._resource_type = None - self._node_selector = None - self._tolerations = None - self._min_monthly_cost_per_gpu = None - self._max_monthly_cost_per_gpu = None - self.discriminator = None - if name is not None: - self.name = name - if values is not None: - self.values = values - if resource_type is not None: - self.resource_type = resource_type - if node_selector is not None: - self.node_selector = node_selector - if tolerations is not None: - self.tolerations = tolerations - if min_monthly_cost_per_gpu is not None: - self.min_monthly_cost_per_gpu = min_monthly_cost_per_gpu - if max_monthly_cost_per_gpu is not None: - self.max_monthly_cost_per_gpu = max_monthly_cost_per_gpu - - @property - def name(self): - """Gets the name of this GPUConfig. # noqa: E501 - - - :return: The name of this GPUConfig. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this GPUConfig. - - - :param name: The name of this GPUConfig. # noqa: E501 - :type: str - """ - - self._name = name - @property - def values(self): - """Gets the values of this GPUConfig. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The values of this GPUConfig. # noqa: E501 - :rtype: list[str] - """ - return self._values - - @values.setter - def values(self, values): - """Sets the values of this GPUConfig. - - - :param values: The values of this GPUConfig. # noqa: E501 - :type: list[str] - """ - - self._values = values - - @property - def resource_type(self): - """Gets the resource_type of this GPUConfig. # noqa: E501 - - - :return: The resource_type of this GPUConfig. # noqa: E501 - :rtype: str - """ - return self._resource_type + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of GPUConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @resource_type.setter - def resource_type(self, resource_type): - """Sets the resource_type of this GPUConfig. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param resource_type: The resource_type of this GPUConfig. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in tolerations (list) + _items = [] + if self.tolerations: + for _item in self.tolerations: + if _item: + _items.append(_item.to_dict()) + _dict['tolerations'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of GPUConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "name": obj.get("name"), + "values": obj.get("values"), + "resource_type": obj.get("resource_type"), + "node_selector": obj.get("node_selector"), + "tolerations": [GPUToleration.from_dict(_item) for _item in obj.get("tolerations")] if obj.get("tolerations") is not None else None, + "min_monthly_cost_per_gpu": obj.get("min_monthly_cost_per_gpu"), + "max_monthly_cost_per_gpu": obj.get("max_monthly_cost_per_gpu") + }) + return _obj - self._resource_type = resource_type - - @property - def node_selector(self): - """Gets the node_selector of this GPUConfig. # noqa: E501 - - - :return: The node_selector of this GPUConfig. # noqa: E501 - :rtype: dict(str, str) - """ - return self._node_selector - - @node_selector.setter - def node_selector(self, node_selector): - """Sets the node_selector of this GPUConfig. - - - :param node_selector: The node_selector of this GPUConfig. # noqa: E501 - :type: dict(str, str) - """ - - self._node_selector = node_selector - - @property - def tolerations(self): - """Gets the tolerations of this GPUConfig. # noqa: E501 - - - :return: The tolerations of this GPUConfig. # noqa: E501 - :rtype: list[GPUToleration] - """ - return self._tolerations - - @tolerations.setter - def tolerations(self, tolerations): - """Sets the tolerations of this GPUConfig. - - - :param tolerations: The tolerations of this GPUConfig. # noqa: E501 - :type: list[GPUToleration] - """ - - self._tolerations = tolerations - - @property - def min_monthly_cost_per_gpu(self): - """Gets the min_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - - - :return: The min_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - :rtype: float - """ - return self._min_monthly_cost_per_gpu - - @min_monthly_cost_per_gpu.setter - def min_monthly_cost_per_gpu(self, min_monthly_cost_per_gpu): - """Sets the min_monthly_cost_per_gpu of this GPUConfig. - - - :param min_monthly_cost_per_gpu: The min_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - :type: float - """ - - self._min_monthly_cost_per_gpu = min_monthly_cost_per_gpu - - @property - def max_monthly_cost_per_gpu(self): - """Gets the max_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - - - :return: The max_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - :rtype: float - """ - return self._max_monthly_cost_per_gpu - - @max_monthly_cost_per_gpu.setter - def max_monthly_cost_per_gpu(self, max_monthly_cost_per_gpu): - """Sets the max_monthly_cost_per_gpu of this GPUConfig. - - - :param max_monthly_cost_per_gpu: The max_monthly_cost_per_gpu of this GPUConfig. # noqa: E501 - :type: float - """ - - self._max_monthly_cost_per_gpu = max_monthly_cost_per_gpu - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(GPUConfig, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, GPUConfig): - return False - - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/gpu_toleration.py b/python/sdk/client/models/gpu_toleration.py index 69de71a0b..6f0c2d9b0 100644 --- a/python/sdk/client/models/gpu_toleration.py +++ b/python/sdk/client/models/gpu_toleration.py @@ -3,212 +3,93 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class GPUToleration(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class GPUToleration(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'key': 'str', - 'operator': 'str', - 'value': 'str', - 'effect': 'str', - 'toleration_seconds': 'int' - } - - attribute_map = { - 'key': 'key', - 'operator': 'operator', - 'value': 'value', - 'effect': 'effect', - 'toleration_seconds': 'toleration_seconds' + GPUToleration + """ # noqa: E501 + key: Optional[StrictStr] = None + operator: Optional[StrictStr] = None + value: Optional[StrictStr] = None + effect: Optional[StrictStr] = None + toleration_seconds: Optional[StrictInt] = None + __properties: ClassVar[List[str]] = ["key", "operator", "value", "effect", "toleration_seconds"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, key=None, operator=None, value=None, effect=None, toleration_seconds=None): # noqa: E501 - """GPUToleration - a model defined in Swagger""" # noqa: E501 - self._key = None - self._operator = None - self._value = None - self._effect = None - self._toleration_seconds = None - self.discriminator = None - if key is not None: - self.key = key - if operator is not None: - self.operator = operator - if value is not None: - self.value = value - if effect is not None: - self.effect = effect - if toleration_seconds is not None: - self.toleration_seconds = toleration_seconds - - @property - def key(self): - """Gets the key of this GPUToleration. # noqa: E501 - - - :return: The key of this GPUToleration. # noqa: E501 - :rtype: str - """ - return self._key - - @key.setter - def key(self, key): - """Sets the key of this GPUToleration. - - - :param key: The key of this GPUToleration. # noqa: E501 - :type: str - """ - - self._key = key - - @property - def operator(self): - """Gets the operator of this GPUToleration. # noqa: E501 - - - :return: The operator of this GPUToleration. # noqa: E501 - :rtype: str - """ - return self._operator - - @operator.setter - def operator(self, operator): - """Sets the operator of this GPUToleration. - - :param operator: The operator of this GPUToleration. # noqa: E501 - :type: str - """ - - self._operator = operator - - @property - def value(self): - """Gets the value of this GPUToleration. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The value of this GPUToleration. # noqa: E501 - :rtype: str - """ - return self._value + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of GPUToleration from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @value.setter - def value(self, value): - """Sets the value of this GPUToleration. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param value: The value of this GPUToleration. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of GPUToleration from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "operator": obj.get("operator"), + "value": obj.get("value"), + "effect": obj.get("effect"), + "toleration_seconds": obj.get("toleration_seconds") + }) + return _obj - self._value = value - - @property - def effect(self): - """Gets the effect of this GPUToleration. # noqa: E501 - - - :return: The effect of this GPUToleration. # noqa: E501 - :rtype: str - """ - return self._effect - - @effect.setter - def effect(self, effect): - """Sets the effect of this GPUToleration. - - - :param effect: The effect of this GPUToleration. # noqa: E501 - :type: str - """ - - self._effect = effect - - @property - def toleration_seconds(self): - """Gets the toleration_seconds of this GPUToleration. # noqa: E501 - - - :return: The toleration_seconds of this GPUToleration. # noqa: E501 - :rtype: int - """ - return self._toleration_seconds - - @toleration_seconds.setter - def toleration_seconds(self, toleration_seconds): - """Sets the toleration_seconds of this GPUToleration. - - - :param toleration_seconds: The toleration_seconds of this GPUToleration. # noqa: E501 - :type: int - """ - self._toleration_seconds = toleration_seconds - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(GPUToleration, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, GPUToleration): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/label.py b/python/sdk/client/models/label.py index 880ceac5d..487f6f2d3 100644 --- a/python/sdk/client/models/label.py +++ b/python/sdk/client/models/label.py @@ -3,134 +3,87 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class Label(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class Label(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'key': 'str', - 'value': 'str' - } - - attribute_map = { - 'key': 'key', - 'value': 'value' + Label + """ # noqa: E501 + key: Optional[StrictStr] = None + value: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["key", "value"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, key=None, value=None): # noqa: E501 - """Label - a model defined in Swagger""" # noqa: E501 - self._key = None - self._value = None - self.discriminator = None - if key is not None: - self.key = key - if value is not None: - self.value = value - @property - def key(self): - """Gets the key of this Label. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The key of this Label. # noqa: E501 - :rtype: str - """ - return self._key + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Label from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @key.setter - def key(self, key): - """Sets the key of this Label. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param key: The key of this Label. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Label from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "key": obj.get("key"), + "value": obj.get("value") + }) + return _obj - self._key = key - - @property - def value(self): - """Gets the value of this Label. # noqa: E501 - - - :return: The value of this Label. # noqa: E501 - :rtype: str - """ - return self._value - - @value.setter - def value(self, value): - """Sets the value of this Label. - - - :param value: The value of this Label. # noqa: E501 - :type: str - """ - self._value = value - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Label, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Label): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/logger.py b/python/sdk/client/models/logger.py index 27e6b6196..799adc580 100644 --- a/python/sdk/client/models/logger.py +++ b/python/sdk/client/models/logger.py @@ -3,160 +3,100 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class Logger(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from client.models.logger_config import LoggerConfig +from client.models.prediction_logger_config import PredictionLoggerConfig +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class Logger(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'model': 'LoggerConfig', - 'transformer': 'LoggerConfig', - 'prediction': 'PredictionLoggerConfig' - } - - attribute_map = { - 'model': 'model', - 'transformer': 'transformer', - 'prediction': 'prediction' + Logger + """ # noqa: E501 + model: Optional[LoggerConfig] = None + transformer: Optional[LoggerConfig] = None + prediction: Optional[PredictionLoggerConfig] = None + __properties: ClassVar[List[str]] = ["model", "transformer", "prediction"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, model=None, transformer=None, prediction=None): # noqa: E501 - """Logger - a model defined in Swagger""" # noqa: E501 - self._model = None - self._transformer = None - self._prediction = None - self.discriminator = None - if model is not None: - self.model = model - if transformer is not None: - self.transformer = transformer - if prediction is not None: - self.prediction = prediction - - @property - def model(self): - """Gets the model of this Logger. # noqa: E501 - - - :return: The model of this Logger. # noqa: E501 - :rtype: LoggerConfig - """ - return self._model - - @model.setter - def model(self, model): - """Sets the model of this Logger. - - :param model: The model of this Logger. # noqa: E501 - :type: LoggerConfig - """ - - self._model = model - - @property - def transformer(self): - """Gets the transformer of this Logger. # noqa: E501 - - - :return: The transformer of this Logger. # noqa: E501 - :rtype: LoggerConfig - """ - return self._transformer + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @transformer.setter - def transformer(self, transformer): - """Sets the transformer of this Logger. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Logger from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param transformer: The transformer of this Logger. # noqa: E501 - :type: LoggerConfig - """ - - self._transformer = transformer - - @property - def prediction(self): - """Gets the prediction of this Logger. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The prediction of this Logger. # noqa: E501 - :rtype: PredictionLoggerConfig + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._prediction + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of model + if self.model: + _dict['model'] = self.model.to_dict() + # override the default output from pydantic by calling `to_dict()` of transformer + if self.transformer: + _dict['transformer'] = self.transformer.to_dict() + # override the default output from pydantic by calling `to_dict()` of prediction + if self.prediction: + _dict['prediction'] = self.prediction.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Logger from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "model": LoggerConfig.from_dict(obj.get("model")) if obj.get("model") is not None else None, + "transformer": LoggerConfig.from_dict(obj.get("transformer")) if obj.get("transformer") is not None else None, + "prediction": PredictionLoggerConfig.from_dict(obj.get("prediction")) if obj.get("prediction") is not None else None + }) + return _obj - @prediction.setter - def prediction(self, prediction): - """Sets the prediction of this Logger. - - - :param prediction: The prediction of this Logger. # noqa: E501 - :type: PredictionLoggerConfig - """ - self._prediction = prediction - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Logger, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Logger): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/logger_config.py b/python/sdk/client/models/logger_config.py index 7b4188d48..407a18a81 100644 --- a/python/sdk/client/models/logger_config.py +++ b/python/sdk/client/models/logger_config.py @@ -3,134 +3,88 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class LoggerConfig(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List +from pydantic import BaseModel, StrictBool +from client.models.logger_mode import LoggerMode +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class LoggerConfig(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'enabled': 'bool', - 'mode': 'LoggerMode' - } - - attribute_map = { - 'enabled': 'enabled', - 'mode': 'mode' + LoggerConfig + """ # noqa: E501 + enabled: StrictBool + mode: LoggerMode + __properties: ClassVar[List[str]] = ["enabled", "mode"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, enabled=None, mode=None): # noqa: E501 - """LoggerConfig - a model defined in Swagger""" # noqa: E501 - self._enabled = None - self._mode = None - self.discriminator = None - if enabled is not None: - self.enabled = enabled - if mode is not None: - self.mode = mode - @property - def enabled(self): - """Gets the enabled of this LoggerConfig. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The enabled of this LoggerConfig. # noqa: E501 - :rtype: bool - """ - return self._enabled + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of LoggerConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @enabled.setter - def enabled(self, enabled): - """Sets the enabled of this LoggerConfig. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param enabled: The enabled of this LoggerConfig. # noqa: E501 - :type: bool + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of LoggerConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "enabled": obj.get("enabled"), + "mode": obj.get("mode") + }) + return _obj - self._enabled = enabled - - @property - def mode(self): - """Gets the mode of this LoggerConfig. # noqa: E501 - - - :return: The mode of this LoggerConfig. # noqa: E501 - :rtype: LoggerMode - """ - return self._mode - - @mode.setter - def mode(self, mode): - """Sets the mode of this LoggerConfig. - - - :param mode: The mode of this LoggerConfig. # noqa: E501 - :type: LoggerMode - """ - self._mode = mode - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(LoggerConfig, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, LoggerConfig): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/logger_mode.py b/python/sdk/client/models/logger_mode.py index 68b56a63d..028e10e9f 100644 --- a/python/sdk/client/models/logger_mode.py +++ b/python/sdk/client/models/logger_mode.py @@ -3,89 +3,44 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class LoggerMode(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class LoggerMode(str, Enum): """ - allowed enum values + LoggerMode """ - ALL = "all" - REQUEST = "request" - RESPONSE = "response" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """LoggerMode - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(LoggerMode, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + ALL = 'all' + REQUEST = 'request' + RESPONSE = 'response' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, LoggerMode): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of LoggerMode from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/metrics_type.py b/python/sdk/client/models/metrics_type.py index d8c7cb744..dbcbb1c0c 100644 --- a/python/sdk/client/models/metrics_type.py +++ b/python/sdk/client/models/metrics_type.py @@ -3,90 +3,45 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class MetricsType(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class MetricsType(str, Enum): """ - allowed enum values + MetricsType """ - CONCURRENCY = "concurrency" - CPU_UTILIZATION = "cpu_utilization" - MEMORY_UTILIZATION = "memory_utilization" - RPS = "rps" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """MetricsType - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(MetricsType, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + CONCURRENCY = 'concurrency' + CPU_UTILIZATION = 'cpu_utilization' + MEMORY_UTILIZATION = 'memory_utilization' + RPS = 'rps' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, MetricsType): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of MetricsType from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/mock_response.py b/python/sdk/client/models/mock_response.py index e6be74f9b..35f98f5c8 100644 --- a/python/sdk/client/models/mock_response.py +++ b/python/sdk/client/models/mock_response.py @@ -3,134 +3,87 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class MockResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class MockResponse(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'body': 'FreeFormObject', - 'headers': 'FreeFormObject' - } - - attribute_map = { - 'body': 'body', - 'headers': 'headers' + MockResponse + """ # noqa: E501 + body: Optional[Union[str, Any]] = None + headers: Optional[Union[str, Any]] = None + __properties: ClassVar[List[str]] = ["body", "headers"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, body=None, headers=None): # noqa: E501 - """MockResponse - a model defined in Swagger""" # noqa: E501 - self._body = None - self._headers = None - self.discriminator = None - if body is not None: - self.body = body - if headers is not None: - self.headers = headers - @property - def body(self): - """Gets the body of this MockResponse. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The body of this MockResponse. # noqa: E501 - :rtype: FreeFormObject - """ - return self._body + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of MockResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @body.setter - def body(self, body): - """Sets the body of this MockResponse. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param body: The body of this MockResponse. # noqa: E501 - :type: FreeFormObject + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of MockResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "body": obj.get("body"), + "headers": obj.get("headers") + }) + return _obj - self._body = body - - @property - def headers(self): - """Gets the headers of this MockResponse. # noqa: E501 - - - :return: The headers of this MockResponse. # noqa: E501 - :rtype: FreeFormObject - """ - return self._headers - - @headers.setter - def headers(self, headers): - """Sets the headers of this MockResponse. - - - :param headers: The headers of this MockResponse. # noqa: E501 - :type: FreeFormObject - """ - self._headers = headers - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(MockResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, MockResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model.py b/python/sdk/client/models/model.py index 6a928bae3..fee675bf3 100644 --- a/python/sdk/client/models/model.py +++ b/python/sdk/client/models/model.py @@ -3,324 +3,122 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class Model(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr, field_validator +from pydantic import Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Model(BaseModel): """ - swagger_types = { - 'id': 'int', - 'project_id': 'int', - 'mlflow_experiment_id': 'int', - 'name': 'str', - 'type': 'str', - 'mlflow_url': 'str', - 'endpoints': 'list[ModelEndpoint]', - 'created_at': 'datetime', - 'updated_at': 'datetime' + Model + """ # noqa: E501 + id: Optional[StrictInt] = None + project_id: Optional[StrictInt] = None + mlflow_experiment_id: Optional[StrictInt] = None + name: StrictStr + type: Optional[StrictStr] = Field(default=None, description="Model type") + mlflow_url: Optional[StrictStr] = None + endpoints: Optional[List[ModelEndpoint]] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "project_id", "mlflow_experiment_id", "name", "type", "mlflow_url", "endpoints", "created_at", "updated_at"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in ('xgboost', 'tensorflow', 'sklearn', 'pytorch', 'pyfunc', 'pyfunc_v2', 'pyfunc_v3', 'custom'): + raise ValueError("must be one of enum values ('xgboost', 'tensorflow', 'sklearn', 'pytorch', 'pyfunc', 'pyfunc_v2', 'pyfunc_v3', 'custom')") + return value + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'id': 'id', - 'project_id': 'project_id', - 'mlflow_experiment_id': 'mlflow_experiment_id', - 'name': 'name', - 'type': 'type', - 'mlflow_url': 'mlflow_url', - 'endpoints': 'endpoints', - 'created_at': 'created_at', - 'updated_at': 'updated_at' - } - - def __init__(self, id=None, project_id=None, mlflow_experiment_id=None, name=None, type=None, mlflow_url=None, endpoints=None, created_at=None, updated_at=None): # noqa: E501 - """Model - a model defined in Swagger""" # noqa: E501 - self._id = None - self._project_id = None - self._mlflow_experiment_id = None - self._name = None - self._type = None - self._mlflow_url = None - self._endpoints = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - if project_id is not None: - self.project_id = project_id - if mlflow_experiment_id is not None: - self.mlflow_experiment_id = mlflow_experiment_id - if name is not None: - self.name = name - if type is not None: - self.type = type - if mlflow_url is not None: - self.mlflow_url = mlflow_url - if endpoints is not None: - self.endpoints = endpoints - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this Model. # noqa: E501 - - - :return: The id of this Model. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Model. - - - :param id: The id of this Model. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def project_id(self): - """Gets the project_id of this Model. # noqa: E501 - - - :return: The project_id of this Model. # noqa: E501 - :rtype: int - """ - return self._project_id - - @project_id.setter - def project_id(self, project_id): - """Sets the project_id of this Model. - - - :param project_id: The project_id of this Model. # noqa: E501 - :type: int - """ - - self._project_id = project_id - - @property - def mlflow_experiment_id(self): - """Gets the mlflow_experiment_id of this Model. # noqa: E501 - - - :return: The mlflow_experiment_id of this Model. # noqa: E501 - :rtype: int - """ - return self._mlflow_experiment_id - - @mlflow_experiment_id.setter - def mlflow_experiment_id(self, mlflow_experiment_id): - """Sets the mlflow_experiment_id of this Model. - - - :param mlflow_experiment_id: The mlflow_experiment_id of this Model. # noqa: E501 - :type: int - """ - - self._mlflow_experiment_id = mlflow_experiment_id - - @property - def name(self): - """Gets the name of this Model. # noqa: E501 - - - :return: The name of this Model. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Model. - - - :param name: The name of this Model. # noqa: E501 - :type: str - """ - - self._name = name - - @property - def type(self): - """Gets the type of this Model. # noqa: E501 - - Model type # noqa: E501 - - :return: The type of this Model. # noqa: E501 - :rtype: str - """ - return self._type - - @type.setter - def type(self, type): - """Sets the type of this Model. - - Model type # noqa: E501 - - :param type: The type of this Model. # noqa: E501 - :type: str - """ - allowed_values = ["xgboost", "tensorflow", "sklearn", "pytorch", "pyfunc", "pyfunc_v2", "pyfunc_v3", "custom"] # noqa: E501 - if type not in allowed_values: - raise ValueError( - "Invalid value for `type` ({0}), must be one of {1}" # noqa: E501 - .format(type, allowed_values) - ) - - self._type = type - - @property - def mlflow_url(self): - """Gets the mlflow_url of this Model. # noqa: E501 - - - :return: The mlflow_url of this Model. # noqa: E501 - :rtype: str - """ - return self._mlflow_url - - @mlflow_url.setter - def mlflow_url(self, mlflow_url): - """Sets the mlflow_url of this Model. - - - :param mlflow_url: The mlflow_url of this Model. # noqa: E501 - :type: str - """ - - self._mlflow_url = mlflow_url - - @property - def endpoints(self): - """Gets the endpoints of this Model. # noqa: E501 - - - :return: The endpoints of this Model. # noqa: E501 - :rtype: list[ModelEndpoint] - """ - return self._endpoints - - @endpoints.setter - def endpoints(self, endpoints): - """Sets the endpoints of this Model. - - - :param endpoints: The endpoints of this Model. # noqa: E501 - :type: list[ModelEndpoint] - """ - - self._endpoints = endpoints - - @property - def created_at(self): - """Gets the created_at of this Model. # noqa: E501 - - - :return: The created_at of this Model. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this Model. - - - :param created_at: The created_at of this Model. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this Model. # noqa: E501 - - - :return: The updated_at of this Model. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this Model. - - - :param updated_at: The updated_at of this Model. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Model, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Model): - return False - return self.__dict__ == other.__dict__ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Model from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in endpoints (list) + _items = [] + if self.endpoints: + for _item in self.endpoints: + if _item: + _items.append(_item.to_dict()) + _dict['endpoints'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Model from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "project_id": obj.get("project_id"), + "mlflow_experiment_id": obj.get("mlflow_experiment_id"), + "name": obj.get("name"), + "type": obj.get("type"), + "mlflow_url": obj.get("mlflow_url"), + "endpoints": [ModelEndpoint.from_dict(_item) for _item in obj.get("endpoints")] if obj.get("endpoints") is not None else None, + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj + +from client.models.model_endpoint import ModelEndpoint +# TODO: Rewrite to not use raise_errors +Model.model_rebuild(raise_errors=False) - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_endpoint.py b/python/sdk/client/models/model_endpoint.py index 0d4851162..004e3f3f0 100644 --- a/python/sdk/client/models/model_endpoint.py +++ b/python/sdk/client/models/model_endpoint.py @@ -3,368 +3,121 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class ModelEndpoint(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.endpoint_status import EndpointStatus +from client.models.environment import Environment +from client.models.model_endpoint_rule import ModelEndpointRule +from client.models.protocol import Protocol +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class ModelEndpoint(BaseModel): """ - swagger_types = { - 'id': 'int', - 'model_id': 'int', - 'model': 'Model', - 'status': 'EndpointStatus', - 'url': 'str', - 'rule': 'ModelEndpointRule', - 'environment_name': 'str', - 'environment': 'Environment', - 'protocol': 'Protocol', - 'created_at': 'datetime', - 'updated_at': 'datetime' - } - - attribute_map = { - 'id': 'id', - 'model_id': 'model_id', - 'model': 'model', - 'status': 'status', - 'url': 'url', - 'rule': 'rule', - 'environment_name': 'environment_name', - 'environment': 'environment', - 'protocol': 'protocol', - 'created_at': 'created_at', - 'updated_at': 'updated_at' + ModelEndpoint + """ # noqa: E501 + id: Optional[StrictInt] = None + model_id: Optional[StrictInt] = None + model: Optional[Model] = None + status: Optional[EndpointStatus] = None + url: Optional[StrictStr] = None + rule: Optional[ModelEndpointRule] = None + environment_name: Optional[StrictStr] = None + environment: Optional[Environment] = None + protocol: Optional[Protocol] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "model_id", "model", "status", "url", "rule", "environment_name", "environment", "protocol", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, id=None, model_id=None, model=None, status=None, url=None, rule=None, environment_name=None, environment=None, protocol=None, created_at=None, updated_at=None): # noqa: E501 - """ModelEndpoint - a model defined in Swagger""" # noqa: E501 - self._id = None - self._model_id = None - self._model = None - self._status = None - self._url = None - self._rule = None - self._environment_name = None - self._environment = None - self._protocol = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - if model_id is not None: - self.model_id = model_id - if model is not None: - self.model = model - if status is not None: - self.status = status - if url is not None: - self.url = url - if rule is not None: - self.rule = rule - if environment_name is not None: - self.environment_name = environment_name - if environment is not None: - self.environment = environment - if protocol is not None: - self.protocol = protocol - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this ModelEndpoint. # noqa: E501 - - - :return: The id of this ModelEndpoint. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this ModelEndpoint. - - - :param id: The id of this ModelEndpoint. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def model_id(self): - """Gets the model_id of this ModelEndpoint. # noqa: E501 - - - :return: The model_id of this ModelEndpoint. # noqa: E501 - :rtype: int - """ - return self._model_id - - @model_id.setter - def model_id(self, model_id): - """Sets the model_id of this ModelEndpoint. - - - :param model_id: The model_id of this ModelEndpoint. # noqa: E501 - :type: int - """ - - self._model_id = model_id - - @property - def model(self): - """Gets the model of this ModelEndpoint. # noqa: E501 - - - :return: The model of this ModelEndpoint. # noqa: E501 - :rtype: Model - """ - return self._model - - @model.setter - def model(self, model): - """Sets the model of this ModelEndpoint. - - - :param model: The model of this ModelEndpoint. # noqa: E501 - :type: Model - """ - - self._model = model - - @property - def status(self): - """Gets the status of this ModelEndpoint. # noqa: E501 - - - :return: The status of this ModelEndpoint. # noqa: E501 - :rtype: EndpointStatus - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this ModelEndpoint. - - - :param status: The status of this ModelEndpoint. # noqa: E501 - :type: EndpointStatus - """ - - self._status = status - - @property - def url(self): - """Gets the url of this ModelEndpoint. # noqa: E501 - - - :return: The url of this ModelEndpoint. # noqa: E501 - :rtype: str - """ - return self._url - - @url.setter - def url(self, url): - """Sets the url of this ModelEndpoint. - - - :param url: The url of this ModelEndpoint. # noqa: E501 - :type: str - """ - - self._url = url - - @property - def rule(self): - """Gets the rule of this ModelEndpoint. # noqa: E501 - - - :return: The rule of this ModelEndpoint. # noqa: E501 - :rtype: ModelEndpointRule - """ - return self._rule - - @rule.setter - def rule(self, rule): - """Sets the rule of this ModelEndpoint. - - - :param rule: The rule of this ModelEndpoint. # noqa: E501 - :type: ModelEndpointRule - """ - - self._rule = rule - - @property - def environment_name(self): - """Gets the environment_name of this ModelEndpoint. # noqa: E501 - - - :return: The environment_name of this ModelEndpoint. # noqa: E501 - :rtype: str - """ - return self._environment_name - - @environment_name.setter - def environment_name(self, environment_name): - """Sets the environment_name of this ModelEndpoint. - - - :param environment_name: The environment_name of this ModelEndpoint. # noqa: E501 - :type: str - """ - - self._environment_name = environment_name - - @property - def environment(self): - """Gets the environment of this ModelEndpoint. # noqa: E501 - - - :return: The environment of this ModelEndpoint. # noqa: E501 - :rtype: Environment - """ - return self._environment - - @environment.setter - def environment(self, environment): - """Sets the environment of this ModelEndpoint. - - - :param environment: The environment of this ModelEndpoint. # noqa: E501 - :type: Environment - """ - - self._environment = environment - - @property - def protocol(self): - """Gets the protocol of this ModelEndpoint. # noqa: E501 - - - :return: The protocol of this ModelEndpoint. # noqa: E501 - :rtype: Protocol - """ - return self._protocol - - @protocol.setter - def protocol(self, protocol): - """Sets the protocol of this ModelEndpoint. - - - :param protocol: The protocol of this ModelEndpoint. # noqa: E501 - :type: Protocol - """ - - self._protocol = protocol - - @property - def created_at(self): - """Gets the created_at of this ModelEndpoint. # noqa: E501 - - - :return: The created_at of this ModelEndpoint. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this ModelEndpoint. - - - :param created_at: The created_at of this ModelEndpoint. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this ModelEndpoint. # noqa: E501 - - - :return: The updated_at of this ModelEndpoint. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this ModelEndpoint. - - - :param updated_at: The updated_at of this ModelEndpoint. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelEndpoint, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelEndpoint): - return False - return self.__dict__ == other.__dict__ + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelEndpoint from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of model + if self.model: + _dict['model'] = self.model.to_dict() + # override the default output from pydantic by calling `to_dict()` of rule + if self.rule: + _dict['rule'] = self.rule.to_dict() + # override the default output from pydantic by calling `to_dict()` of environment + if self.environment: + _dict['environment'] = self.environment.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelEndpoint from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "model_id": obj.get("model_id"), + "model": Model.from_dict(obj.get("model")) if obj.get("model") is not None else None, + "status": obj.get("status"), + "url": obj.get("url"), + "rule": ModelEndpointRule.from_dict(obj.get("rule")) if obj.get("rule") is not None else None, + "environment_name": obj.get("environment_name"), + "environment": Environment.from_dict(obj.get("environment")) if obj.get("environment") is not None else None, + "protocol": obj.get("protocol"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj + +from client.models.model import Model +# TODO: Rewrite to not use raise_errors +ModelEndpoint.model_rebuild(raise_errors=False) - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_endpoint_alert.py b/python/sdk/client/models/model_endpoint_alert.py index 38d744067..e81fbabf1 100644 --- a/python/sdk/client/models/model_endpoint_alert.py +++ b/python/sdk/client/models/model_endpoint_alert.py @@ -3,212 +3,101 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ModelEndpointAlert(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.model_endpoint_alert_condition import ModelEndpointAlertCondition +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class ModelEndpointAlert(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'model_id': 'int', - 'model_endpoint_id': 'int', - 'environment_name': 'str', - 'team_name': 'str', - 'alert_conditions': 'list[ModelEndpointAlertCondition]' - } - - attribute_map = { - 'model_id': 'model_id', - 'model_endpoint_id': 'model_endpoint_id', - 'environment_name': 'environment_name', - 'team_name': 'team_name', - 'alert_conditions': 'alert_conditions' + ModelEndpointAlert + """ # noqa: E501 + model_id: Optional[StrictInt] = None + model_endpoint_id: Optional[StrictInt] = None + environment_name: Optional[StrictStr] = None + team_name: Optional[StrictStr] = None + alert_conditions: Optional[List[ModelEndpointAlertCondition]] = None + __properties: ClassVar[List[str]] = ["model_id", "model_endpoint_id", "environment_name", "team_name", "alert_conditions"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, model_id=None, model_endpoint_id=None, environment_name=None, team_name=None, alert_conditions=None): # noqa: E501 - """ModelEndpointAlert - a model defined in Swagger""" # noqa: E501 - self._model_id = None - self._model_endpoint_id = None - self._environment_name = None - self._team_name = None - self._alert_conditions = None - self.discriminator = None - if model_id is not None: - self.model_id = model_id - if model_endpoint_id is not None: - self.model_endpoint_id = model_endpoint_id - if environment_name is not None: - self.environment_name = environment_name - if team_name is not None: - self.team_name = team_name - if alert_conditions is not None: - self.alert_conditions = alert_conditions - - @property - def model_id(self): - """Gets the model_id of this ModelEndpointAlert. # noqa: E501 - - - :return: The model_id of this ModelEndpointAlert. # noqa: E501 - :rtype: int - """ - return self._model_id - - @model_id.setter - def model_id(self, model_id): - """Sets the model_id of this ModelEndpointAlert. - - - :param model_id: The model_id of this ModelEndpointAlert. # noqa: E501 - :type: int - """ - - self._model_id = model_id - - @property - def model_endpoint_id(self): - """Gets the model_endpoint_id of this ModelEndpointAlert. # noqa: E501 - - - :return: The model_endpoint_id of this ModelEndpointAlert. # noqa: E501 - :rtype: int - """ - return self._model_endpoint_id - - @model_endpoint_id.setter - def model_endpoint_id(self, model_endpoint_id): - """Sets the model_endpoint_id of this ModelEndpointAlert. - - :param model_endpoint_id: The model_endpoint_id of this ModelEndpointAlert. # noqa: E501 - :type: int - """ - - self._model_endpoint_id = model_endpoint_id - - @property - def environment_name(self): - """Gets the environment_name of this ModelEndpointAlert. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The environment_name of this ModelEndpointAlert. # noqa: E501 - :rtype: str - """ - return self._environment_name + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelEndpointAlert from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @environment_name.setter - def environment_name(self, environment_name): - """Sets the environment_name of this ModelEndpointAlert. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param environment_name: The environment_name of this ModelEndpointAlert. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in alert_conditions (list) + _items = [] + if self.alert_conditions: + for _item in self.alert_conditions: + if _item: + _items.append(_item.to_dict()) + _dict['alert_conditions'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelEndpointAlert from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "model_id": obj.get("model_id"), + "model_endpoint_id": obj.get("model_endpoint_id"), + "environment_name": obj.get("environment_name"), + "team_name": obj.get("team_name"), + "alert_conditions": [ModelEndpointAlertCondition.from_dict(_item) for _item in obj.get("alert_conditions")] if obj.get("alert_conditions") is not None else None + }) + return _obj - self._environment_name = environment_name - - @property - def team_name(self): - """Gets the team_name of this ModelEndpointAlert. # noqa: E501 - - - :return: The team_name of this ModelEndpointAlert. # noqa: E501 - :rtype: str - """ - return self._team_name - - @team_name.setter - def team_name(self, team_name): - """Sets the team_name of this ModelEndpointAlert. - - - :param team_name: The team_name of this ModelEndpointAlert. # noqa: E501 - :type: str - """ - - self._team_name = team_name - - @property - def alert_conditions(self): - """Gets the alert_conditions of this ModelEndpointAlert. # noqa: E501 - - - :return: The alert_conditions of this ModelEndpointAlert. # noqa: E501 - :rtype: list[ModelEndpointAlertCondition] - """ - return self._alert_conditions - - @alert_conditions.setter - def alert_conditions(self, alert_conditions): - """Sets the alert_conditions of this ModelEndpointAlert. - - - :param alert_conditions: The alert_conditions of this ModelEndpointAlert. # noqa: E501 - :type: list[ModelEndpointAlertCondition] - """ - self._alert_conditions = alert_conditions - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelEndpointAlert, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelEndpointAlert): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_endpoint_alert_condition.py b/python/sdk/client/models/model_endpoint_alert_condition.py index 4c52a046d..fe56c0fcc 100644 --- a/python/sdk/client/models/model_endpoint_alert_condition.py +++ b/python/sdk/client/models/model_endpoint_alert_condition.py @@ -3,238 +3,97 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ModelEndpointAlertCondition(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel, StrictBool, StrictFloat, StrictInt, StrictStr +from client.models.alert_condition_metric_type import AlertConditionMetricType +from client.models.alert_condition_severity import AlertConditionSeverity +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +class ModelEndpointAlertCondition(BaseModel): """ - swagger_types = { - 'enabled': 'bool', - 'metric_type': 'AlertConditionMetricType', - 'severity': 'AlertConditionSeverity', - 'target': 'float', - 'percentile': 'float', - 'unit': 'str' + ModelEndpointAlertCondition + """ # noqa: E501 + enabled: Optional[StrictBool] = None + metric_type: Optional[AlertConditionMetricType] = None + severity: Optional[AlertConditionSeverity] = None + target: Optional[Union[StrictFloat, StrictInt]] = None + percentile: Optional[Union[StrictFloat, StrictInt]] = None + unit: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["enabled", "metric_type", "severity", "target", "percentile", "unit"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'enabled': 'enabled', - 'metric_type': 'metric_type', - 'severity': 'severity', - 'target': 'target', - 'percentile': 'percentile', - 'unit': 'unit' - } - - def __init__(self, enabled=None, metric_type=None, severity=None, target=None, percentile=None, unit=None): # noqa: E501 - """ModelEndpointAlertCondition - a model defined in Swagger""" # noqa: E501 - self._enabled = None - self._metric_type = None - self._severity = None - self._target = None - self._percentile = None - self._unit = None - self.discriminator = None - if enabled is not None: - self.enabled = enabled - if metric_type is not None: - self.metric_type = metric_type - if severity is not None: - self.severity = severity - if target is not None: - self.target = target - if percentile is not None: - self.percentile = percentile - if unit is not None: - self.unit = unit - - @property - def enabled(self): - """Gets the enabled of this ModelEndpointAlertCondition. # noqa: E501 - - - :return: The enabled of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: bool - """ - return self._enabled - - @enabled.setter - def enabled(self, enabled): - """Sets the enabled of this ModelEndpointAlertCondition. - - - :param enabled: The enabled of this ModelEndpointAlertCondition. # noqa: E501 - :type: bool - """ - - self._enabled = enabled - @property - def metric_type(self): - """Gets the metric_type of this ModelEndpointAlertCondition. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The metric_type of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: AlertConditionMetricType - """ - return self._metric_type + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelEndpointAlertCondition from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @metric_type.setter - def metric_type(self, metric_type): - """Sets the metric_type of this ModelEndpointAlertCondition. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param metric_type: The metric_type of this ModelEndpointAlertCondition. # noqa: E501 - :type: AlertConditionMetricType + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelEndpointAlertCondition from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "enabled": obj.get("enabled"), + "metric_type": obj.get("metric_type"), + "severity": obj.get("severity"), + "target": obj.get("target"), + "percentile": obj.get("percentile"), + "unit": obj.get("unit") + }) + return _obj - self._metric_type = metric_type - - @property - def severity(self): - """Gets the severity of this ModelEndpointAlertCondition. # noqa: E501 - - - :return: The severity of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: AlertConditionSeverity - """ - return self._severity - - @severity.setter - def severity(self, severity): - """Sets the severity of this ModelEndpointAlertCondition. - - - :param severity: The severity of this ModelEndpointAlertCondition. # noqa: E501 - :type: AlertConditionSeverity - """ - - self._severity = severity - - @property - def target(self): - """Gets the target of this ModelEndpointAlertCondition. # noqa: E501 - - - :return: The target of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: float - """ - return self._target - - @target.setter - def target(self, target): - """Sets the target of this ModelEndpointAlertCondition. - - - :param target: The target of this ModelEndpointAlertCondition. # noqa: E501 - :type: float - """ - - self._target = target - - @property - def percentile(self): - """Gets the percentile of this ModelEndpointAlertCondition. # noqa: E501 - - - :return: The percentile of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: float - """ - return self._percentile - - @percentile.setter - def percentile(self, percentile): - """Sets the percentile of this ModelEndpointAlertCondition. - - - :param percentile: The percentile of this ModelEndpointAlertCondition. # noqa: E501 - :type: float - """ - - self._percentile = percentile - - @property - def unit(self): - """Gets the unit of this ModelEndpointAlertCondition. # noqa: E501 - - - :return: The unit of this ModelEndpointAlertCondition. # noqa: E501 - :rtype: str - """ - return self._unit - - @unit.setter - def unit(self, unit): - """Sets the unit of this ModelEndpointAlertCondition. - - - :param unit: The unit of this ModelEndpointAlertCondition. # noqa: E501 - :type: str - """ - self._unit = unit - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelEndpointAlertCondition, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelEndpointAlertCondition): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_endpoint_rule.py b/python/sdk/client/models/model_endpoint_rule.py index 53c5c1046..f006e542c 100644 --- a/python/sdk/client/models/model_endpoint_rule.py +++ b/python/sdk/client/models/model_endpoint_rule.py @@ -3,134 +3,99 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ModelEndpointRule(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from client.models.model_endpoint_rule_destination import ModelEndpointRuleDestination +from client.models.version_endpoint import VersionEndpoint +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class ModelEndpointRule(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'destinations': 'list[ModelEndpointRuleDestination]', - 'mirror': 'VersionEndpoint' - } - - attribute_map = { - 'destinations': 'destinations', - 'mirror': 'mirror' + ModelEndpointRule + """ # noqa: E501 + destinations: Optional[List[ModelEndpointRuleDestination]] = None + mirror: Optional[VersionEndpoint] = None + __properties: ClassVar[List[str]] = ["destinations", "mirror"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, destinations=None, mirror=None): # noqa: E501 - """ModelEndpointRule - a model defined in Swagger""" # noqa: E501 - self._destinations = None - self._mirror = None - self.discriminator = None - if destinations is not None: - self.destinations = destinations - if mirror is not None: - self.mirror = mirror - @property - def destinations(self): - """Gets the destinations of this ModelEndpointRule. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The destinations of this ModelEndpointRule. # noqa: E501 - :rtype: list[ModelEndpointRuleDestination] - """ - return self._destinations + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelEndpointRule from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @destinations.setter - def destinations(self, destinations): - """Sets the destinations of this ModelEndpointRule. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param destinations: The destinations of this ModelEndpointRule. # noqa: E501 - :type: list[ModelEndpointRuleDestination] + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in destinations (list) + _items = [] + if self.destinations: + for _item in self.destinations: + if _item: + _items.append(_item.to_dict()) + _dict['destinations'] = _items + # override the default output from pydantic by calling `to_dict()` of mirror + if self.mirror: + _dict['mirror'] = self.mirror.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelEndpointRule from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "destinations": [ModelEndpointRuleDestination.from_dict(_item) for _item in obj.get("destinations")] if obj.get("destinations") is not None else None, + "mirror": VersionEndpoint.from_dict(obj.get("mirror")) if obj.get("mirror") is not None else None + }) + return _obj - self._destinations = destinations - - @property - def mirror(self): - """Gets the mirror of this ModelEndpointRule. # noqa: E501 - - - :return: The mirror of this ModelEndpointRule. # noqa: E501 - :rtype: VersionEndpoint - """ - return self._mirror - - @mirror.setter - def mirror(self, mirror): - """Sets the mirror of this ModelEndpointRule. - - - :param mirror: The mirror of this ModelEndpointRule. # noqa: E501 - :type: VersionEndpoint - """ - self._mirror = mirror - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelEndpointRule, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelEndpointRule): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_endpoint_rule_destination.py b/python/sdk/client/models/model_endpoint_rule_destination.py index 40d85c105..df51b156c 100644 --- a/python/sdk/client/models/model_endpoint_rule_destination.py +++ b/python/sdk/client/models/model_endpoint_rule_destination.py @@ -3,160 +3,93 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ModelEndpointRuleDestination(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.version_endpoint import VersionEndpoint +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class ModelEndpointRuleDestination(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'version_endpoint_id': 'str', - 'version_endpoint': 'VersionEndpoint', - 'weight': 'int' - } - - attribute_map = { - 'version_endpoint_id': 'version_endpoint_id', - 'version_endpoint': 'version_endpoint', - 'weight': 'weight' + ModelEndpointRuleDestination + """ # noqa: E501 + version_endpoint_id: Optional[StrictStr] = None + version_endpoint: Optional[VersionEndpoint] = None + weight: Optional[StrictInt] = None + __properties: ClassVar[List[str]] = ["version_endpoint_id", "version_endpoint", "weight"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, version_endpoint_id=None, version_endpoint=None, weight=None): # noqa: E501 - """ModelEndpointRuleDestination - a model defined in Swagger""" # noqa: E501 - self._version_endpoint_id = None - self._version_endpoint = None - self._weight = None - self.discriminator = None - if version_endpoint_id is not None: - self.version_endpoint_id = version_endpoint_id - if version_endpoint is not None: - self.version_endpoint = version_endpoint - if weight is not None: - self.weight = weight - - @property - def version_endpoint_id(self): - """Gets the version_endpoint_id of this ModelEndpointRuleDestination. # noqa: E501 - - - :return: The version_endpoint_id of this ModelEndpointRuleDestination. # noqa: E501 - :rtype: str - """ - return self._version_endpoint_id - - @version_endpoint_id.setter - def version_endpoint_id(self, version_endpoint_id): - """Sets the version_endpoint_id of this ModelEndpointRuleDestination. - - :param version_endpoint_id: The version_endpoint_id of this ModelEndpointRuleDestination. # noqa: E501 - :type: str - """ - - self._version_endpoint_id = version_endpoint_id - - @property - def version_endpoint(self): - """Gets the version_endpoint of this ModelEndpointRuleDestination. # noqa: E501 - - - :return: The version_endpoint of this ModelEndpointRuleDestination. # noqa: E501 - :rtype: VersionEndpoint - """ - return self._version_endpoint + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @version_endpoint.setter - def version_endpoint(self, version_endpoint): - """Sets the version_endpoint of this ModelEndpointRuleDestination. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelEndpointRuleDestination from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param version_endpoint: The version_endpoint of this ModelEndpointRuleDestination. # noqa: E501 - :type: VersionEndpoint - """ - - self._version_endpoint = version_endpoint - - @property - def weight(self): - """Gets the weight of this ModelEndpointRuleDestination. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The weight of this ModelEndpointRuleDestination. # noqa: E501 - :rtype: int + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._weight + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of version_endpoint + if self.version_endpoint: + _dict['version_endpoint'] = self.version_endpoint.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelEndpointRuleDestination from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "version_endpoint_id": obj.get("version_endpoint_id"), + "version_endpoint": VersionEndpoint.from_dict(obj.get("version_endpoint")) if obj.get("version_endpoint") is not None else None, + "weight": obj.get("weight") + }) + return _obj - @weight.setter - def weight(self, weight): - """Sets the weight of this ModelEndpointRuleDestination. - - - :param weight: The weight of this ModelEndpointRuleDestination. # noqa: E501 - :type: int - """ - self._weight = weight - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelEndpointRuleDestination, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelEndpointRuleDestination): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_prediction_config.py b/python/sdk/client/models/model_prediction_config.py index d065dedc1..55784bf43 100644 --- a/python/sdk/client/models/model_prediction_config.py +++ b/python/sdk/client/models/model_prediction_config.py @@ -3,108 +3,89 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ModelPredictionConfig(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from client.models.mock_response import MockResponse +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class ModelPredictionConfig(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'mock_response': 'MockResponse' + ModelPredictionConfig + """ # noqa: E501 + mock_response: Optional[MockResponse] = None + __properties: ClassVar[List[str]] = ["mock_response"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'mock_response': 'mock_response' - } - def __init__(self, mock_response=None): # noqa: E501 - """ModelPredictionConfig - a model defined in Swagger""" # noqa: E501 - self._mock_response = None - self.discriminator = None - if mock_response is not None: - self.mock_response = mock_response + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @property - def mock_response(self): - """Gets the mock_response of this ModelPredictionConfig. # noqa: E501 + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelPredictionConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :return: The mock_response of this ModelPredictionConfig. # noqa: E501 - :rtype: MockResponse - """ - return self._mock_response + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - @mock_response.setter - def mock_response(self, mock_response): - """Sets the mock_response of this ModelPredictionConfig. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - :param mock_response: The mock_response of this ModelPredictionConfig. # noqa: E501 - :type: MockResponse + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of mock_response + if self.mock_response: + _dict['mock_response'] = self.mock_response.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelPredictionConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "mock_response": MockResponse.from_dict(obj.get("mock_response")) if obj.get("mock_response") is not None else None + }) + return _obj + - self._mock_response = mock_response - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ModelPredictionConfig, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ModelPredictionConfig): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/model_prediction_output.py b/python/sdk/client/models/model_prediction_output.py new file mode 100644 index 000000000..8b1fbc247 --- /dev/null +++ b/python/sdk/client/models/model_prediction_output.py @@ -0,0 +1,162 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +from inspect import getfullargspec +import json +import pprint +import re # noqa: F401 + +from typing import Any, List, Optional +from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from client.models.binary_classification_output import BinaryClassificationOutput +from client.models.ranking_output import RankingOutput +from client.models.regression_output import RegressionOutput +from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict +from typing_extensions import Literal +from pydantic import StrictStr, Field +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +MODELPREDICTIONOUTPUT_ONE_OF_SCHEMAS = ["BinaryClassificationOutput", "RankingOutput", "RegressionOutput"] + +class ModelPredictionOutput(BaseModel): + """ + ModelPredictionOutput + """ + # data type: BinaryClassificationOutput + oneof_schema_1_validator: Optional[BinaryClassificationOutput] = None + # data type: RankingOutput + oneof_schema_2_validator: Optional[RankingOutput] = None + # data type: RegressionOutput + oneof_schema_3_validator: Optional[RegressionOutput] = None + actual_instance: Optional[Union[BinaryClassificationOutput, RankingOutput, RegressionOutput]] = None + one_of_schemas: List[str] = Literal["BinaryClassificationOutput", "RankingOutput", "RegressionOutput"] + + model_config = { + "validate_assignment": True + } + + + discriminator_value_class_map: Dict[str, str] = { + } + + def __init__(self, *args, **kwargs) -> None: + if args: + if len(args) > 1: + raise ValueError("If a position argument is used, only 1 is allowed to set `actual_instance`") + if kwargs: + raise ValueError("If a position argument is used, keyword arguments cannot be used.") + super().__init__(actual_instance=args[0]) + else: + super().__init__(**kwargs) + + @field_validator('actual_instance') + def actual_instance_must_validate_oneof(cls, v): + instance = ModelPredictionOutput.model_construct() + error_messages = [] + match = 0 + # validate data type: BinaryClassificationOutput + if not isinstance(v, BinaryClassificationOutput): + error_messages.append(f"Error! Input type `{type(v)}` is not `BinaryClassificationOutput`") + else: + match += 1 + # validate data type: RankingOutput + if not isinstance(v, RankingOutput): + error_messages.append(f"Error! Input type `{type(v)}` is not `RankingOutput`") + else: + match += 1 + # validate data type: RegressionOutput + if not isinstance(v, RegressionOutput): + error_messages.append(f"Error! Input type `{type(v)}` is not `RegressionOutput`") + else: + match += 1 + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when setting `actual_instance` in ModelPredictionOutput with oneOf schemas: BinaryClassificationOutput, RankingOutput, RegressionOutput. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when setting `actual_instance` in ModelPredictionOutput with oneOf schemas: BinaryClassificationOutput, RankingOutput, RegressionOutput. Details: " + ", ".join(error_messages)) + else: + return v + + @classmethod + def from_dict(cls, obj: dict) -> Self: + return cls.from_json(json.dumps(obj)) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Returns the object represented by the json string""" + instance = cls.model_construct() + error_messages = [] + match = 0 + + # deserialize data into BinaryClassificationOutput + try: + instance.actual_instance = BinaryClassificationOutput.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into RankingOutput + try: + instance.actual_instance = RankingOutput.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + # deserialize data into RegressionOutput + try: + instance.actual_instance = RegressionOutput.from_json(json_str) + match += 1 + except (ValidationError, ValueError) as e: + error_messages.append(str(e)) + + if match > 1: + # more than 1 match + raise ValueError("Multiple matches found when deserializing the JSON string into ModelPredictionOutput with oneOf schemas: BinaryClassificationOutput, RankingOutput, RegressionOutput. Details: " + ", ".join(error_messages)) + elif match == 0: + # no match + raise ValueError("No match found when deserializing the JSON string into ModelPredictionOutput with oneOf schemas: BinaryClassificationOutput, RankingOutput, RegressionOutput. Details: " + ", ".join(error_messages)) + else: + return instance + + def to_json(self) -> str: + """Returns the JSON representation of the actual instance""" + if self.actual_instance is None: + return "null" + + to_json = getattr(self.actual_instance, "to_json", None) + if callable(to_json): + return self.actual_instance.to_json() + else: + return json.dumps(self.actual_instance) + + def to_dict(self) -> Dict: + """Returns the dict representation of the actual instance""" + if self.actual_instance is None: + return None + + to_dict = getattr(self.actual_instance, "to_dict", None) + if callable(to_dict): + return self.actual_instance.to_dict() + else: + # primitive type + return self.actual_instance + + def to_str(self) -> str: + """Returns the string representation of the actual instance""" + return pprint.pformat(self.model_dump()) + + diff --git a/python/sdk/client/models/model_prediction_output_class.py b/python/sdk/client/models/model_prediction_output_class.py new file mode 100644 index 000000000..41352d099 --- /dev/null +++ b/python/sdk/client/models/model_prediction_output_class.py @@ -0,0 +1,46 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +import re # noqa: F401 +from enum import Enum + + + +try: + from typing import Self +except ImportError: + from typing_extensions import Self + + +class ModelPredictionOutputClass(str, Enum): + """ + ModelPredictionOutputClass + """ + + """ + allowed enum values + """ + BINARYCLASSIFICATIONOUTPUT = 'BinaryClassificationOutput' + RANKINGOUTPUT = 'RankingOutput' + REGRESSIONOUTPUT = 'RegressionOutput' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelPredictionOutputClass from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/sdk/client/models/model_schema.py b/python/sdk/client/models/model_schema.py new file mode 100644 index 000000000..0aee51a4a --- /dev/null +++ b/python/sdk/client/models/model_schema.py @@ -0,0 +1,95 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt +from client.models.schema_spec import SchemaSpec +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class ModelSchema(BaseModel): + """ + ModelSchema + """ # noqa: E501 + id: Optional[StrictInt] = None + model_id: Optional[StrictInt] = None + spec: SchemaSpec + __properties: ClassVar[List[str]] = ["id", "model_id", "spec"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ModelSchema from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of spec + if self.spec: + _dict['spec'] = self.spec.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ModelSchema from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "model_id": obj.get("model_id"), + "spec": SchemaSpec.from_dict(obj.get("spec")) if obj.get("spec") is not None else None + }) + return _obj + + diff --git a/python/sdk/client/models/operation_tracing.py b/python/sdk/client/models/operation_tracing.py index 4c49de1e0..b0e413efa 100644 --- a/python/sdk/client/models/operation_tracing.py +++ b/python/sdk/client/models/operation_tracing.py @@ -3,134 +3,102 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class OperationTracing(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from client.models.pipeline_tracing import PipelineTracing +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class OperationTracing(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'preprocess': 'PipelineTracing', - 'postprocess': 'PipelineTracing' - } - - attribute_map = { - 'preprocess': 'preprocess', - 'postprocess': 'postprocess' + OperationTracing + """ # noqa: E501 + preprocess: Optional[List[PipelineTracing]] = None + postprocess: Optional[List[PipelineTracing]] = None + __properties: ClassVar[List[str]] = ["preprocess", "postprocess"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, preprocess=None, postprocess=None): # noqa: E501 - """OperationTracing - a model defined in Swagger""" # noqa: E501 - self._preprocess = None - self._postprocess = None - self.discriminator = None - if preprocess is not None: - self.preprocess = preprocess - if postprocess is not None: - self.postprocess = postprocess - @property - def preprocess(self): - """Gets the preprocess of this OperationTracing. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The preprocess of this OperationTracing. # noqa: E501 - :rtype: PipelineTracing - """ - return self._preprocess + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of OperationTracing from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @preprocess.setter - def preprocess(self, preprocess): - """Sets the preprocess of this OperationTracing. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param preprocess: The preprocess of this OperationTracing. # noqa: E501 - :type: PipelineTracing + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in preprocess (list) + _items = [] + if self.preprocess: + for _item in self.preprocess: + if _item: + _items.append(_item.to_dict()) + _dict['preprocess'] = _items + # override the default output from pydantic by calling `to_dict()` of each item in postprocess (list) + _items = [] + if self.postprocess: + for _item in self.postprocess: + if _item: + _items.append(_item.to_dict()) + _dict['postprocess'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of OperationTracing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "preprocess": [PipelineTracing.from_dict(_item) for _item in obj.get("preprocess")] if obj.get("preprocess") is not None else None, + "postprocess": [PipelineTracing.from_dict(_item) for _item in obj.get("postprocess")] if obj.get("postprocess") is not None else None + }) + return _obj - self._preprocess = preprocess - - @property - def postprocess(self): - """Gets the postprocess of this OperationTracing. # noqa: E501 - - - :return: The postprocess of this OperationTracing. # noqa: E501 - :rtype: PipelineTracing - """ - return self._postprocess - - @postprocess.setter - def postprocess(self, postprocess): - """Sets the postprocess of this OperationTracing. - - - :param postprocess: The postprocess of this OperationTracing. # noqa: E501 - :type: PipelineTracing - """ - self._postprocess = postprocess - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(OperationTracing, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, OperationTracing): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/pipeline_tracing.py b/python/sdk/client/models/pipeline_tracing.py index 64a94f471..0ce835240 100644 --- a/python/sdk/client/models/pipeline_tracing.py +++ b/python/sdk/client/models/pipeline_tracing.py @@ -3,82 +3,91 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PipelineTracing(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class PipelineTracing(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { + PipelineTracing + """ # noqa: E501 + operation_type: Optional[StrictStr] = None + spec: Optional[Union[str, Any]] = None + input: Optional[Union[str, Any]] = None + output: Optional[Union[str, Any]] = None + __properties: ClassVar[List[str]] = ["operation_type", "spec", "input", "output"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - } - def __init__(self): # noqa: E501 - """PipelineTracing - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PipelineTracing, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PipelineTracing): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PipelineTracing from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PipelineTracing from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "operation_type": obj.get("operation_type"), + "spec": obj.get("spec"), + "input": obj.get("input"), + "output": obj.get("output") + }) + return _obj + + diff --git a/python/sdk/client/models/pipeline_tracing_inner.py b/python/sdk/client/models/pipeline_tracing_inner.py deleted file mode 100644 index 0e4e904ed..000000000 --- a/python/sdk/client/models/pipeline_tracing_inner.py +++ /dev/null @@ -1,188 +0,0 @@ -# coding: utf-8 - -""" - Merlin - - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 - - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 - -import six - -class PipelineTracingInner(object): - """NOTE: This class is auto generated by the swagger code generator program. - - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'operation_type': 'str', - 'specs': 'FreeFormObject', - 'inputs': 'FreeFormObject', - 'outputs': 'FreeFormObject' - } - - attribute_map = { - 'operation_type': 'operation_type', - 'specs': 'specs', - 'inputs': 'inputs', - 'outputs': 'outputs' - } - - def __init__(self, operation_type=None, specs=None, inputs=None, outputs=None): # noqa: E501 - """PipelineTracingInner - a model defined in Swagger""" # noqa: E501 - self._operation_type = None - self._specs = None - self._inputs = None - self._outputs = None - self.discriminator = None - if operation_type is not None: - self.operation_type = operation_type - if specs is not None: - self.specs = specs - if inputs is not None: - self.inputs = inputs - if outputs is not None: - self.outputs = outputs - - @property - def operation_type(self): - """Gets the operation_type of this PipelineTracingInner. # noqa: E501 - - - :return: The operation_type of this PipelineTracingInner. # noqa: E501 - :rtype: str - """ - return self._operation_type - - @operation_type.setter - def operation_type(self, operation_type): - """Sets the operation_type of this PipelineTracingInner. - - - :param operation_type: The operation_type of this PipelineTracingInner. # noqa: E501 - :type: str - """ - - self._operation_type = operation_type - - @property - def specs(self): - """Gets the specs of this PipelineTracingInner. # noqa: E501 - - - :return: The specs of this PipelineTracingInner. # noqa: E501 - :rtype: FreeFormObject - """ - return self._specs - - @specs.setter - def specs(self, specs): - """Sets the specs of this PipelineTracingInner. - - - :param specs: The specs of this PipelineTracingInner. # noqa: E501 - :type: FreeFormObject - """ - - self._specs = specs - - @property - def inputs(self): - """Gets the inputs of this PipelineTracingInner. # noqa: E501 - - - :return: The inputs of this PipelineTracingInner. # noqa: E501 - :rtype: FreeFormObject - """ - return self._inputs - - @inputs.setter - def inputs(self, inputs): - """Sets the inputs of this PipelineTracingInner. - - - :param inputs: The inputs of this PipelineTracingInner. # noqa: E501 - :type: FreeFormObject - """ - - self._inputs = inputs - - @property - def outputs(self): - """Gets the outputs of this PipelineTracingInner. # noqa: E501 - - - :return: The outputs of this PipelineTracingInner. # noqa: E501 - :rtype: FreeFormObject - """ - return self._outputs - - @outputs.setter - def outputs(self, outputs): - """Sets the outputs of this PipelineTracingInner. - - - :param outputs: The outputs of this PipelineTracingInner. # noqa: E501 - :type: FreeFormObject - """ - - self._outputs = outputs - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PipelineTracingInner, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PipelineTracingInner): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job.py b/python/sdk/client/models/prediction_job.py index 9b123f737..074ce25a5 100644 --- a/python/sdk/client/models/prediction_job.py +++ b/python/sdk/client/models/prediction_job.py @@ -3,394 +3,115 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class PredictionJob(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.config import Config +from client.models.environment import Environment +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class PredictionJob(BaseModel): """ - swagger_types = { - 'id': 'int', - 'name': 'str', - 'version_id': 'int', - 'model_id': 'int', - 'project_id': 'int', - 'environment_name': 'str', - 'environment': 'Environment', - 'config': 'Config', - 'status': 'str', - 'error': 'str', - 'created_at': 'datetime', - 'updated_at': 'datetime' - } - - attribute_map = { - 'id': 'id', - 'name': 'name', - 'version_id': 'version_id', - 'model_id': 'model_id', - 'project_id': 'project_id', - 'environment_name': 'environment_name', - 'environment': 'environment', - 'config': 'config', - 'status': 'status', - 'error': 'error', - 'created_at': 'created_at', - 'updated_at': 'updated_at' + PredictionJob + """ # noqa: E501 + id: Optional[StrictInt] = None + name: Optional[StrictStr] = None + version_id: Optional[StrictInt] = None + model_id: Optional[StrictInt] = None + project_id: Optional[StrictInt] = None + environment_name: Optional[StrictStr] = None + environment: Optional[Environment] = None + config: Optional[Config] = None + status: Optional[StrictStr] = None + error: Optional[StrictStr] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "name", "version_id", "model_id", "project_id", "environment_name", "environment", "config", "status", "error", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, id=None, name=None, version_id=None, model_id=None, project_id=None, environment_name=None, environment=None, config=None, status=None, error=None, created_at=None, updated_at=None): # noqa: E501 - """PredictionJob - a model defined in Swagger""" # noqa: E501 - self._id = None - self._name = None - self._version_id = None - self._model_id = None - self._project_id = None - self._environment_name = None - self._environment = None - self._config = None - self._status = None - self._error = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - if name is not None: - self.name = name - if version_id is not None: - self.version_id = version_id - if model_id is not None: - self.model_id = model_id - if project_id is not None: - self.project_id = project_id - if environment_name is not None: - self.environment_name = environment_name - if environment is not None: - self.environment = environment - if config is not None: - self.config = config - if status is not None: - self.status = status - if error is not None: - self.error = error - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this PredictionJob. # noqa: E501 - - - :return: The id of this PredictionJob. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this PredictionJob. - - - :param id: The id of this PredictionJob. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this PredictionJob. # noqa: E501 - - - :return: The name of this PredictionJob. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this PredictionJob. - - - :param name: The name of this PredictionJob. # noqa: E501 - :type: str - """ - - self._name = name - - @property - def version_id(self): - """Gets the version_id of this PredictionJob. # noqa: E501 - - - :return: The version_id of this PredictionJob. # noqa: E501 - :rtype: int - """ - return self._version_id - - @version_id.setter - def version_id(self, version_id): - """Sets the version_id of this PredictionJob. - - - :param version_id: The version_id of this PredictionJob. # noqa: E501 - :type: int - """ - - self._version_id = version_id - - @property - def model_id(self): - """Gets the model_id of this PredictionJob. # noqa: E501 - - - :return: The model_id of this PredictionJob. # noqa: E501 - :rtype: int - """ - return self._model_id - - @model_id.setter - def model_id(self, model_id): - """Sets the model_id of this PredictionJob. - - - :param model_id: The model_id of this PredictionJob. # noqa: E501 - :type: int - """ - - self._model_id = model_id - - @property - def project_id(self): - """Gets the project_id of this PredictionJob. # noqa: E501 - - - :return: The project_id of this PredictionJob. # noqa: E501 - :rtype: int - """ - return self._project_id - - @project_id.setter - def project_id(self, project_id): - """Sets the project_id of this PredictionJob. - - - :param project_id: The project_id of this PredictionJob. # noqa: E501 - :type: int - """ - - self._project_id = project_id - - @property - def environment_name(self): - """Gets the environment_name of this PredictionJob. # noqa: E501 - - - :return: The environment_name of this PredictionJob. # noqa: E501 - :rtype: str - """ - return self._environment_name - - @environment_name.setter - def environment_name(self, environment_name): - """Sets the environment_name of this PredictionJob. - - - :param environment_name: The environment_name of this PredictionJob. # noqa: E501 - :type: str - """ - - self._environment_name = environment_name - - @property - def environment(self): - """Gets the environment of this PredictionJob. # noqa: E501 - - - :return: The environment of this PredictionJob. # noqa: E501 - :rtype: Environment - """ - return self._environment - - @environment.setter - def environment(self, environment): - """Sets the environment of this PredictionJob. - - - :param environment: The environment of this PredictionJob. # noqa: E501 - :type: Environment - """ - - self._environment = environment - - @property - def config(self): - """Gets the config of this PredictionJob. # noqa: E501 - - - :return: The config of this PredictionJob. # noqa: E501 - :rtype: Config - """ - return self._config - - @config.setter - def config(self, config): - """Sets the config of this PredictionJob. - - - :param config: The config of this PredictionJob. # noqa: E501 - :type: Config - """ - - self._config = config - - @property - def status(self): - """Gets the status of this PredictionJob. # noqa: E501 - - - :return: The status of this PredictionJob. # noqa: E501 - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this PredictionJob. - - - :param status: The status of this PredictionJob. # noqa: E501 - :type: str - """ - - self._status = status - - @property - def error(self): - """Gets the error of this PredictionJob. # noqa: E501 - - - :return: The error of this PredictionJob. # noqa: E501 - :rtype: str - """ - return self._error - - @error.setter - def error(self, error): - """Sets the error of this PredictionJob. - - - :param error: The error of this PredictionJob. # noqa: E501 - :type: str - """ - - self._error = error - - @property - def created_at(self): - """Gets the created_at of this PredictionJob. # noqa: E501 - - - :return: The created_at of this PredictionJob. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this PredictionJob. - - - :param created_at: The created_at of this PredictionJob. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this PredictionJob. # noqa: E501 - - - :return: The updated_at of this PredictionJob. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this PredictionJob. - - - :param updated_at: The updated_at of this PredictionJob. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJob, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJob): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJob from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of environment + if self.environment: + _dict['environment'] = self.environment.to_dict() + # override the default output from pydantic by calling `to_dict()` of config + if self.config: + _dict['config'] = self.config.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJob from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "version_id": obj.get("version_id"), + "model_id": obj.get("model_id"), + "project_id": obj.get("project_id"), + "environment_name": obj.get("environment_name"), + "environment": Environment.from_dict(obj.get("environment")) if obj.get("environment") is not None else None, + "config": Config.from_dict(obj.get("config")) if obj.get("config") is not None else None, + "status": obj.get("status"), + "error": obj.get("error"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config.py b/python/sdk/client/models/prediction_job_config.py index aca95374d..d3163fb83 100644 --- a/python/sdk/client/models/prediction_job_config.py +++ b/python/sdk/client/models/prediction_job_config.py @@ -3,290 +3,119 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class PredictionJobConfig(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.prediction_job_config_bigquery_sink import PredictionJobConfigBigquerySink +from client.models.prediction_job_config_bigquery_source import PredictionJobConfigBigquerySource +from client.models.prediction_job_config_gcs_sink import PredictionJobConfigGcsSink +from client.models.prediction_job_config_gcs_source import PredictionJobConfigGcsSource +from client.models.prediction_job_config_model import PredictionJobConfigModel +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class PredictionJobConfig(BaseModel): """ - swagger_types = { - 'version': 'str', - 'kind': 'str', - 'name': 'str', - 'bigquery_source': 'PredictionJobConfigBigquerySource', - 'gcs_source': 'PredictionJobConfigGcsSource', - 'model': 'PredictionJobConfigModel', - 'bigquery_sink': 'PredictionJobConfigBigquerySink', - 'gcs_sink': 'PredictionJobConfigGcsSink' - } - - attribute_map = { - 'version': 'version', - 'kind': 'kind', - 'name': 'name', - 'bigquery_source': 'bigquery_source', - 'gcs_source': 'gcs_source', - 'model': 'model', - 'bigquery_sink': 'bigquery_sink', - 'gcs_sink': 'gcs_sink' + PredictionJobConfig + """ # noqa: E501 + version: Optional[StrictStr] = None + kind: Optional[StrictStr] = None + name: Optional[StrictStr] = None + bigquery_source: Optional[PredictionJobConfigBigquerySource] = None + gcs_source: Optional[PredictionJobConfigGcsSource] = None + model: Optional[PredictionJobConfigModel] = None + bigquery_sink: Optional[PredictionJobConfigBigquerySink] = None + gcs_sink: Optional[PredictionJobConfigGcsSink] = None + __properties: ClassVar[List[str]] = ["version", "kind", "name", "bigquery_source", "gcs_source", "model", "bigquery_sink", "gcs_sink"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, version=None, kind=None, name=None, bigquery_source=None, gcs_source=None, model=None, bigquery_sink=None, gcs_sink=None): # noqa: E501 - """PredictionJobConfig - a model defined in Swagger""" # noqa: E501 - self._version = None - self._kind = None - self._name = None - self._bigquery_source = None - self._gcs_source = None - self._model = None - self._bigquery_sink = None - self._gcs_sink = None - self.discriminator = None - if version is not None: - self.version = version - if kind is not None: - self.kind = kind - if name is not None: - self.name = name - if bigquery_source is not None: - self.bigquery_source = bigquery_source - if gcs_source is not None: - self.gcs_source = gcs_source - if model is not None: - self.model = model - if bigquery_sink is not None: - self.bigquery_sink = bigquery_sink - if gcs_sink is not None: - self.gcs_sink = gcs_sink - - @property - def version(self): - """Gets the version of this PredictionJobConfig. # noqa: E501 - - - :return: The version of this PredictionJobConfig. # noqa: E501 - :rtype: str - """ - return self._version - - @version.setter - def version(self, version): - """Sets the version of this PredictionJobConfig. - - - :param version: The version of this PredictionJobConfig. # noqa: E501 - :type: str - """ - - self._version = version - - @property - def kind(self): - """Gets the kind of this PredictionJobConfig. # noqa: E501 - - - :return: The kind of this PredictionJobConfig. # noqa: E501 - :rtype: str - """ - return self._kind - - @kind.setter - def kind(self, kind): - """Sets the kind of this PredictionJobConfig. - - - :param kind: The kind of this PredictionJobConfig. # noqa: E501 - :type: str - """ - - self._kind = kind - - @property - def name(self): - """Gets the name of this PredictionJobConfig. # noqa: E501 - - - :return: The name of this PredictionJobConfig. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this PredictionJobConfig. - - - :param name: The name of this PredictionJobConfig. # noqa: E501 - :type: str - """ - - self._name = name - - @property - def bigquery_source(self): - """Gets the bigquery_source of this PredictionJobConfig. # noqa: E501 - - - :return: The bigquery_source of this PredictionJobConfig. # noqa: E501 - :rtype: PredictionJobConfigBigquerySource - """ - return self._bigquery_source - - @bigquery_source.setter - def bigquery_source(self, bigquery_source): - """Sets the bigquery_source of this PredictionJobConfig. - - - :param bigquery_source: The bigquery_source of this PredictionJobConfig. # noqa: E501 - :type: PredictionJobConfigBigquerySource - """ - - self._bigquery_source = bigquery_source - - @property - def gcs_source(self): - """Gets the gcs_source of this PredictionJobConfig. # noqa: E501 - - - :return: The gcs_source of this PredictionJobConfig. # noqa: E501 - :rtype: PredictionJobConfigGcsSource - """ - return self._gcs_source - - @gcs_source.setter - def gcs_source(self, gcs_source): - """Sets the gcs_source of this PredictionJobConfig. - - - :param gcs_source: The gcs_source of this PredictionJobConfig. # noqa: E501 - :type: PredictionJobConfigGcsSource - """ - - self._gcs_source = gcs_source - - @property - def model(self): - """Gets the model of this PredictionJobConfig. # noqa: E501 - - - :return: The model of this PredictionJobConfig. # noqa: E501 - :rtype: PredictionJobConfigModel - """ - return self._model - - @model.setter - def model(self, model): - """Sets the model of this PredictionJobConfig. - - - :param model: The model of this PredictionJobConfig. # noqa: E501 - :type: PredictionJobConfigModel - """ - - self._model = model - - @property - def bigquery_sink(self): - """Gets the bigquery_sink of this PredictionJobConfig. # noqa: E501 - - - :return: The bigquery_sink of this PredictionJobConfig. # noqa: E501 - :rtype: PredictionJobConfigBigquerySink - """ - return self._bigquery_sink - - @bigquery_sink.setter - def bigquery_sink(self, bigquery_sink): - """Sets the bigquery_sink of this PredictionJobConfig. - - - :param bigquery_sink: The bigquery_sink of this PredictionJobConfig. # noqa: E501 - :type: PredictionJobConfigBigquerySink - """ - - self._bigquery_sink = bigquery_sink - - @property - def gcs_sink(self): - """Gets the gcs_sink of this PredictionJobConfig. # noqa: E501 - - - :return: The gcs_sink of this PredictionJobConfig. # noqa: E501 - :rtype: PredictionJobConfigGcsSink - """ - return self._gcs_sink - - @gcs_sink.setter - def gcs_sink(self, gcs_sink): - """Sets the gcs_sink of this PredictionJobConfig. - - - :param gcs_sink: The gcs_sink of this PredictionJobConfig. # noqa: E501 - :type: PredictionJobConfigGcsSink - """ - - self._gcs_sink = gcs_sink - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfig, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfig): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of bigquery_source + if self.bigquery_source: + _dict['bigquery_source'] = self.bigquery_source.to_dict() + # override the default output from pydantic by calling `to_dict()` of gcs_source + if self.gcs_source: + _dict['gcs_source'] = self.gcs_source.to_dict() + # override the default output from pydantic by calling `to_dict()` of model + if self.model: + _dict['model'] = self.model.to_dict() + # override the default output from pydantic by calling `to_dict()` of bigquery_sink + if self.bigquery_sink: + _dict['bigquery_sink'] = self.bigquery_sink.to_dict() + # override the default output from pydantic by calling `to_dict()` of gcs_sink + if self.gcs_sink: + _dict['gcs_sink'] = self.gcs_sink.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "version": obj.get("version"), + "kind": obj.get("kind"), + "name": obj.get("name"), + "bigquery_source": PredictionJobConfigBigquerySource.from_dict(obj.get("bigquery_source")) if obj.get("bigquery_source") is not None else None, + "gcs_source": PredictionJobConfigGcsSource.from_dict(obj.get("gcs_source")) if obj.get("gcs_source") is not None else None, + "model": PredictionJobConfigModel.from_dict(obj.get("model")) if obj.get("model") is not None else None, + "bigquery_sink": PredictionJobConfigBigquerySink.from_dict(obj.get("bigquery_sink")) if obj.get("bigquery_sink") is not None else None, + "gcs_sink": PredictionJobConfigGcsSink.from_dict(obj.get("gcs_sink")) if obj.get("gcs_sink") is not None else None + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_bigquery_sink.py b/python/sdk/client/models/prediction_job_config_bigquery_sink.py index 1a9c63b42..0b69d689e 100644 --- a/python/sdk/client/models/prediction_job_config_bigquery_sink.py +++ b/python/sdk/client/models/prediction_job_config_bigquery_sink.py @@ -3,212 +3,94 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigBigquerySink(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.save_mode import SaveMode +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class PredictionJobConfigBigquerySink(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'table': 'str', - 'staging_bucket': 'str', - 'result_column': 'str', - 'save_mode': 'SaveMode', - 'options': 'dict(str, str)' - } - - attribute_map = { - 'table': 'table', - 'staging_bucket': 'staging_bucket', - 'result_column': 'result_column', - 'save_mode': 'save_mode', - 'options': 'options' + PredictionJobConfigBigquerySink + """ # noqa: E501 + table: Optional[StrictStr] = None + staging_bucket: Optional[StrictStr] = None + result_column: Optional[StrictStr] = None + save_mode: Optional[SaveMode] = None + options: Optional[Dict[str, StrictStr]] = None + __properties: ClassVar[List[str]] = ["table", "staging_bucket", "result_column", "save_mode", "options"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, table=None, staging_bucket=None, result_column=None, save_mode=None, options=None): # noqa: E501 - """PredictionJobConfigBigquerySink - a model defined in Swagger""" # noqa: E501 - self._table = None - self._staging_bucket = None - self._result_column = None - self._save_mode = None - self._options = None - self.discriminator = None - if table is not None: - self.table = table - if staging_bucket is not None: - self.staging_bucket = staging_bucket - if result_column is not None: - self.result_column = result_column - if save_mode is not None: - self.save_mode = save_mode - if options is not None: - self.options = options - - @property - def table(self): - """Gets the table of this PredictionJobConfigBigquerySink. # noqa: E501 - - - :return: The table of this PredictionJobConfigBigquerySink. # noqa: E501 - :rtype: str - """ - return self._table - - @table.setter - def table(self, table): - """Sets the table of this PredictionJobConfigBigquerySink. - - - :param table: The table of this PredictionJobConfigBigquerySink. # noqa: E501 - :type: str - """ - - self._table = table - - @property - def staging_bucket(self): - """Gets the staging_bucket of this PredictionJobConfigBigquerySink. # noqa: E501 - - - :return: The staging_bucket of this PredictionJobConfigBigquerySink. # noqa: E501 - :rtype: str - """ - return self._staging_bucket - - @staging_bucket.setter - def staging_bucket(self, staging_bucket): - """Sets the staging_bucket of this PredictionJobConfigBigquerySink. - - :param staging_bucket: The staging_bucket of this PredictionJobConfigBigquerySink. # noqa: E501 - :type: str - """ - - self._staging_bucket = staging_bucket - - @property - def result_column(self): - """Gets the result_column of this PredictionJobConfigBigquerySink. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The result_column of this PredictionJobConfigBigquerySink. # noqa: E501 - :rtype: str - """ - return self._result_column + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigBigquerySink from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @result_column.setter - def result_column(self, result_column): - """Sets the result_column of this PredictionJobConfigBigquerySink. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param result_column: The result_column of this PredictionJobConfigBigquerySink. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigBigquerySink from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "table": obj.get("table"), + "staging_bucket": obj.get("staging_bucket"), + "result_column": obj.get("result_column"), + "save_mode": obj.get("save_mode"), + "options": obj.get("options") + }) + return _obj - self._result_column = result_column - - @property - def save_mode(self): - """Gets the save_mode of this PredictionJobConfigBigquerySink. # noqa: E501 - - - :return: The save_mode of this PredictionJobConfigBigquerySink. # noqa: E501 - :rtype: SaveMode - """ - return self._save_mode - - @save_mode.setter - def save_mode(self, save_mode): - """Sets the save_mode of this PredictionJobConfigBigquerySink. - - - :param save_mode: The save_mode of this PredictionJobConfigBigquerySink. # noqa: E501 - :type: SaveMode - """ - - self._save_mode = save_mode - - @property - def options(self): - """Gets the options of this PredictionJobConfigBigquerySink. # noqa: E501 - - - :return: The options of this PredictionJobConfigBigquerySink. # noqa: E501 - :rtype: dict(str, str) - """ - return self._options - - @options.setter - def options(self, options): - """Sets the options of this PredictionJobConfigBigquerySink. - - - :param options: The options of this PredictionJobConfigBigquerySink. # noqa: E501 - :type: dict(str, str) - """ - self._options = options - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigBigquerySink, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigBigquerySink): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_bigquery_source.py b/python/sdk/client/models/prediction_job_config_bigquery_source.py index 94dcf60ab..4e5ff1375 100644 --- a/python/sdk/client/models/prediction_job_config_bigquery_source.py +++ b/python/sdk/client/models/prediction_job_config_bigquery_source.py @@ -3,160 +3,89 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigBigquerySource(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class PredictionJobConfigBigquerySource(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'table': 'str', - 'features': 'list[str]', - 'options': 'dict(str, str)' - } - - attribute_map = { - 'table': 'table', - 'features': 'features', - 'options': 'options' + PredictionJobConfigBigquerySource + """ # noqa: E501 + table: Optional[StrictStr] = None + features: Optional[List[StrictStr]] = None + options: Optional[Dict[str, StrictStr]] = None + __properties: ClassVar[List[str]] = ["table", "features", "options"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, table=None, features=None, options=None): # noqa: E501 - """PredictionJobConfigBigquerySource - a model defined in Swagger""" # noqa: E501 - self._table = None - self._features = None - self._options = None - self.discriminator = None - if table is not None: - self.table = table - if features is not None: - self.features = features - if options is not None: - self.options = options - - @property - def table(self): - """Gets the table of this PredictionJobConfigBigquerySource. # noqa: E501 - - - :return: The table of this PredictionJobConfigBigquerySource. # noqa: E501 - :rtype: str - """ - return self._table - - @table.setter - def table(self, table): - """Sets the table of this PredictionJobConfigBigquerySource. - - :param table: The table of this PredictionJobConfigBigquerySource. # noqa: E501 - :type: str - """ - - self._table = table - - @property - def features(self): - """Gets the features of this PredictionJobConfigBigquerySource. # noqa: E501 - - - :return: The features of this PredictionJobConfigBigquerySource. # noqa: E501 - :rtype: list[str] - """ - return self._features + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @features.setter - def features(self, features): - """Sets the features of this PredictionJobConfigBigquerySource. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigBigquerySource from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param features: The features of this PredictionJobConfigBigquerySource. # noqa: E501 - :type: list[str] - """ - - self._features = features - - @property - def options(self): - """Gets the options of this PredictionJobConfigBigquerySource. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The options of this PredictionJobConfigBigquerySource. # noqa: E501 - :rtype: dict(str, str) + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._options + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigBigquerySource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "table": obj.get("table"), + "features": obj.get("features"), + "options": obj.get("options") + }) + return _obj - @options.setter - def options(self, options): - """Sets the options of this PredictionJobConfigBigquerySource. - - - :param options: The options of this PredictionJobConfigBigquerySource. # noqa: E501 - :type: dict(str, str) - """ - self._options = options - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigBigquerySource, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigBigquerySource): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_gcs_sink.py b/python/sdk/client/models/prediction_job_config_gcs_sink.py index f96fff96e..db878d3d3 100644 --- a/python/sdk/client/models/prediction_job_config_gcs_sink.py +++ b/python/sdk/client/models/prediction_job_config_gcs_sink.py @@ -3,212 +3,95 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigGcsSink(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.file_format import FileFormat +from client.models.save_mode import SaveMode +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class PredictionJobConfigGcsSink(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'format': 'FileFormat', - 'uri': 'str', - 'result_column': 'str', - 'save_mode': 'SaveMode', - 'options': 'dict(str, str)' - } - - attribute_map = { - 'format': 'format', - 'uri': 'uri', - 'result_column': 'result_column', - 'save_mode': 'save_mode', - 'options': 'options' + PredictionJobConfigGcsSink + """ # noqa: E501 + format: Optional[FileFormat] = None + uri: Optional[StrictStr] = None + result_column: Optional[StrictStr] = None + save_mode: Optional[SaveMode] = None + options: Optional[Dict[str, StrictStr]] = None + __properties: ClassVar[List[str]] = ["format", "uri", "result_column", "save_mode", "options"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, format=None, uri=None, result_column=None, save_mode=None, options=None): # noqa: E501 - """PredictionJobConfigGcsSink - a model defined in Swagger""" # noqa: E501 - self._format = None - self._uri = None - self._result_column = None - self._save_mode = None - self._options = None - self.discriminator = None - if format is not None: - self.format = format - if uri is not None: - self.uri = uri - if result_column is not None: - self.result_column = result_column - if save_mode is not None: - self.save_mode = save_mode - if options is not None: - self.options = options - - @property - def format(self): - """Gets the format of this PredictionJobConfigGcsSink. # noqa: E501 - - - :return: The format of this PredictionJobConfigGcsSink. # noqa: E501 - :rtype: FileFormat - """ - return self._format - - @format.setter - def format(self, format): - """Sets the format of this PredictionJobConfigGcsSink. - - - :param format: The format of this PredictionJobConfigGcsSink. # noqa: E501 - :type: FileFormat - """ - - self._format = format - - @property - def uri(self): - """Gets the uri of this PredictionJobConfigGcsSink. # noqa: E501 - - - :return: The uri of this PredictionJobConfigGcsSink. # noqa: E501 - :rtype: str - """ - return self._uri - - @uri.setter - def uri(self, uri): - """Sets the uri of this PredictionJobConfigGcsSink. - - :param uri: The uri of this PredictionJobConfigGcsSink. # noqa: E501 - :type: str - """ - - self._uri = uri - - @property - def result_column(self): - """Gets the result_column of this PredictionJobConfigGcsSink. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The result_column of this PredictionJobConfigGcsSink. # noqa: E501 - :rtype: str - """ - return self._result_column + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigGcsSink from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @result_column.setter - def result_column(self, result_column): - """Sets the result_column of this PredictionJobConfigGcsSink. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param result_column: The result_column of this PredictionJobConfigGcsSink. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigGcsSink from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "format": obj.get("format"), + "uri": obj.get("uri"), + "result_column": obj.get("result_column"), + "save_mode": obj.get("save_mode"), + "options": obj.get("options") + }) + return _obj - self._result_column = result_column - - @property - def save_mode(self): - """Gets the save_mode of this PredictionJobConfigGcsSink. # noqa: E501 - - - :return: The save_mode of this PredictionJobConfigGcsSink. # noqa: E501 - :rtype: SaveMode - """ - return self._save_mode - - @save_mode.setter - def save_mode(self, save_mode): - """Sets the save_mode of this PredictionJobConfigGcsSink. - - - :param save_mode: The save_mode of this PredictionJobConfigGcsSink. # noqa: E501 - :type: SaveMode - """ - - self._save_mode = save_mode - - @property - def options(self): - """Gets the options of this PredictionJobConfigGcsSink. # noqa: E501 - - - :return: The options of this PredictionJobConfigGcsSink. # noqa: E501 - :rtype: dict(str, str) - """ - return self._options - - @options.setter - def options(self, options): - """Sets the options of this PredictionJobConfigGcsSink. - - - :param options: The options of this PredictionJobConfigGcsSink. # noqa: E501 - :type: dict(str, str) - """ - self._options = options - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigGcsSink, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigGcsSink): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_gcs_source.py b/python/sdk/client/models/prediction_job_config_gcs_source.py index 8cfa488cf..4dee045ca 100644 --- a/python/sdk/client/models/prediction_job_config_gcs_source.py +++ b/python/sdk/client/models/prediction_job_config_gcs_source.py @@ -3,186 +3,92 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigGcsSource(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.file_format import FileFormat +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class PredictionJobConfigGcsSource(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'format': 'FileFormat', - 'uri': 'str', - 'features': 'list[str]', - 'options': 'dict(str, str)' + PredictionJobConfigGcsSource + """ # noqa: E501 + format: Optional[FileFormat] = None + uri: Optional[StrictStr] = None + features: Optional[List[StrictStr]] = None + options: Optional[Dict[str, StrictStr]] = None + __properties: ClassVar[List[str]] = ["format", "uri", "features", "options"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'format': 'format', - 'uri': 'uri', - 'features': 'features', - 'options': 'options' - } - def __init__(self, format=None, uri=None, features=None, options=None): # noqa: E501 - """PredictionJobConfigGcsSource - a model defined in Swagger""" # noqa: E501 - self._format = None - self._uri = None - self._features = None - self._options = None - self.discriminator = None - if format is not None: - self.format = format - if uri is not None: - self.uri = uri - if features is not None: - self.features = features - if options is not None: - self.options = options - - @property - def format(self): - """Gets the format of this PredictionJobConfigGcsSource. # noqa: E501 - - - :return: The format of this PredictionJobConfigGcsSource. # noqa: E501 - :rtype: FileFormat - """ - return self._format + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @format.setter - def format(self, format): - """Sets the format of this PredictionJobConfigGcsSource. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigGcsSource from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param format: The format of this PredictionJobConfigGcsSource. # noqa: E501 - :type: FileFormat - """ - - self._format = format - - @property - def uri(self): - """Gets the uri of this PredictionJobConfigGcsSource. # noqa: E501 - + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - :return: The uri of this PredictionJobConfigGcsSource. # noqa: E501 - :rtype: str - """ - return self._uri - - @uri.setter - def uri(self, uri): - """Sets the uri of this PredictionJobConfigGcsSource. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - :param uri: The uri of this PredictionJobConfigGcsSource. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigGcsSource from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "format": obj.get("format"), + "uri": obj.get("uri"), + "features": obj.get("features"), + "options": obj.get("options") + }) + return _obj - self._uri = uri - - @property - def features(self): - """Gets the features of this PredictionJobConfigGcsSource. # noqa: E501 - - - :return: The features of this PredictionJobConfigGcsSource. # noqa: E501 - :rtype: list[str] - """ - return self._features - - @features.setter - def features(self, features): - """Sets the features of this PredictionJobConfigGcsSource. - - - :param features: The features of this PredictionJobConfigGcsSource. # noqa: E501 - :type: list[str] - """ - - self._features = features - - @property - def options(self): - """Gets the options of this PredictionJobConfigGcsSource. # noqa: E501 - - - :return: The options of this PredictionJobConfigGcsSource. # noqa: E501 - :rtype: dict(str, str) - """ - return self._options - - @options.setter - def options(self, options): - """Sets the options of this PredictionJobConfigGcsSource. - - - :param options: The options of this PredictionJobConfigGcsSource. # noqa: E501 - :type: dict(str, str) - """ - self._options = options - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigGcsSource, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigGcsSource): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_model.py b/python/sdk/client/models/prediction_job_config_model.py index c08dc3dab..2b78ceeae 100644 --- a/python/sdk/client/models/prediction_job_config_model.py +++ b/python/sdk/client/models/prediction_job_config_model.py @@ -3,192 +3,105 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigModel(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr, field_validator +from client.models.prediction_job_config_model_result import PredictionJobConfigModelResult +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class PredictionJobConfigModel(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'type': 'str', - 'uri': 'str', - 'result': 'PredictionJobConfigModelResult', - 'options': 'dict(str, str)' + PredictionJobConfigModel + """ # noqa: E501 + type: Optional[StrictStr] = 'INVALID_MODEL_TYPE' + uri: Optional[StrictStr] = None + result: Optional[PredictionJobConfigModelResult] = None + options: Optional[Dict[str, StrictStr]] = None + __properties: ClassVar[List[str]] = ["type", "uri", "result", "options"] + + @field_validator('type') + def type_validate_enum(cls, value): + """Validates the enum""" + if value is None: + return value + + if value not in ('INVALID_MODEL_TYPE', 'XGBOOST', 'TENSORFLOW', 'SKLEARN', 'PYTORCH', 'ONNX', 'PYFUNC', 'PYFUNC_V2', 'CUSTOM'): + raise ValueError("must be one of enum values ('INVALID_MODEL_TYPE', 'XGBOOST', 'TENSORFLOW', 'SKLEARN', 'PYTORCH', 'ONNX', 'PYFUNC', 'PYFUNC_V2', 'CUSTOM')") + return value + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'type': 'type', - 'uri': 'uri', - 'result': 'result', - 'options': 'options' - } - def __init__(self, type='INVALID_MODEL_TYPE', uri=None, result=None, options=None): # noqa: E501 - """PredictionJobConfigModel - a model defined in Swagger""" # noqa: E501 - self._type = None - self._uri = None - self._result = None - self._options = None - self.discriminator = None - if type is not None: - self.type = type - if uri is not None: - self.uri = uri - if result is not None: - self.result = result - if options is not None: - self.options = options - - @property - def type(self): - """Gets the type of this PredictionJobConfigModel. # noqa: E501 - - - :return: The type of this PredictionJobConfigModel. # noqa: E501 - :rtype: str - """ - return self._type + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @type.setter - def type(self, type): - """Sets the type of this PredictionJobConfigModel. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigModel from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param type: The type of this PredictionJobConfigModel. # noqa: E501 - :type: str - """ - allowed_values = ["INVALID_MODEL_TYPE", "XGBOOST", "TENSORFLOW", "SKLEARN", "PYTORCH", "ONNX", "PYFUNC", "PYFUNC_V2", "CUSTOM"] # noqa: E501 - if type not in allowed_values: - raise ValueError( - "Invalid value for `type` ({0}), must be one of {1}" # noqa: E501 - .format(type, allowed_values) - ) - - self._type = type - - @property - def uri(self): - """Gets the uri of this PredictionJobConfigModel. # noqa: E501 - + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. - :return: The uri of this PredictionJobConfigModel. # noqa: E501 - :rtype: str - """ - return self._uri - - @uri.setter - def uri(self, uri): - """Sets the uri of this PredictionJobConfigModel. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - - :param uri: The uri of this PredictionJobConfigModel. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of result + if self.result: + _dict['result'] = self.result.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigModel from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type") if obj.get("type") is not None else 'INVALID_MODEL_TYPE', + "uri": obj.get("uri"), + "result": PredictionJobConfigModelResult.from_dict(obj.get("result")) if obj.get("result") is not None else None, + "options": obj.get("options") + }) + return _obj - self._uri = uri - - @property - def result(self): - """Gets the result of this PredictionJobConfigModel. # noqa: E501 - - - :return: The result of this PredictionJobConfigModel. # noqa: E501 - :rtype: PredictionJobConfigModelResult - """ - return self._result - - @result.setter - def result(self, result): - """Sets the result of this PredictionJobConfigModel. - - - :param result: The result of this PredictionJobConfigModel. # noqa: E501 - :type: PredictionJobConfigModelResult - """ - - self._result = result - - @property - def options(self): - """Gets the options of this PredictionJobConfigModel. # noqa: E501 - - - :return: The options of this PredictionJobConfigModel. # noqa: E501 - :rtype: dict(str, str) - """ - return self._options - - @options.setter - def options(self, options): - """Sets the options of this PredictionJobConfigModel. - - - :param options: The options of this PredictionJobConfigModel. # noqa: E501 - :type: dict(str, str) - """ - self._options = options - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigModel, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigModel): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_config_model_result.py b/python/sdk/client/models/prediction_job_config_model_result.py index 6e043dca0..462645199 100644 --- a/python/sdk/client/models/prediction_job_config_model_result.py +++ b/python/sdk/client/models/prediction_job_config_model_result.py @@ -3,134 +3,88 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobConfigModelResult(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel +from client.models.result_type import ResultType +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class PredictionJobConfigModelResult(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'type': 'ResultType', - 'item_type': 'ResultType' - } - - attribute_map = { - 'type': 'type', - 'item_type': 'item_type' + PredictionJobConfigModelResult + """ # noqa: E501 + type: Optional[ResultType] = None + item_type: Optional[ResultType] = None + __properties: ClassVar[List[str]] = ["type", "item_type"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, type=None, item_type=None): # noqa: E501 - """PredictionJobConfigModelResult - a model defined in Swagger""" # noqa: E501 - self._type = None - self._item_type = None - self.discriminator = None - if type is not None: - self.type = type - if item_type is not None: - self.item_type = item_type - @property - def type(self): - """Gets the type of this PredictionJobConfigModelResult. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The type of this PredictionJobConfigModelResult. # noqa: E501 - :rtype: ResultType - """ - return self._type + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobConfigModelResult from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @type.setter - def type(self, type): - """Sets the type of this PredictionJobConfigModelResult. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param type: The type of this PredictionJobConfigModelResult. # noqa: E501 - :type: ResultType + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobConfigModelResult from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "type": obj.get("type"), + "item_type": obj.get("item_type") + }) + return _obj - self._type = type - - @property - def item_type(self): - """Gets the item_type of this PredictionJobConfigModelResult. # noqa: E501 - - - :return: The item_type of this PredictionJobConfigModelResult. # noqa: E501 - :rtype: ResultType - """ - return self._item_type - - @item_type.setter - def item_type(self, item_type): - """Sets the item_type of this PredictionJobConfigModelResult. - - - :param item_type: The item_type of this PredictionJobConfigModelResult. # noqa: E501 - :type: ResultType - """ - self._item_type = item_type - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobConfigModelResult, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobConfigModelResult): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_job_resource_request.py b/python/sdk/client/models/prediction_job_resource_request.py index 07a44053c..f3f763bc5 100644 --- a/python/sdk/client/models/prediction_job_resource_request.py +++ b/python/sdk/client/models/prediction_job_resource_request.py @@ -3,212 +3,93 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionJobResourceRequest(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class PredictionJobResourceRequest(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'driver_cpu_request': 'str', - 'driver_memory_request': 'str', - 'executor_cpu_request': 'str', - 'executor_memory_request': 'str', - 'executor_replica': 'int' - } - - attribute_map = { - 'driver_cpu_request': 'driver_cpu_request', - 'driver_memory_request': 'driver_memory_request', - 'executor_cpu_request': 'executor_cpu_request', - 'executor_memory_request': 'executor_memory_request', - 'executor_replica': 'executor_replica' + PredictionJobResourceRequest + """ # noqa: E501 + driver_cpu_request: Optional[StrictStr] = None + driver_memory_request: Optional[StrictStr] = None + executor_cpu_request: Optional[StrictStr] = None + executor_memory_request: Optional[StrictStr] = None + executor_replica: Optional[StrictInt] = None + __properties: ClassVar[List[str]] = ["driver_cpu_request", "driver_memory_request", "executor_cpu_request", "executor_memory_request", "executor_replica"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, driver_cpu_request=None, driver_memory_request=None, executor_cpu_request=None, executor_memory_request=None, executor_replica=None): # noqa: E501 - """PredictionJobResourceRequest - a model defined in Swagger""" # noqa: E501 - self._driver_cpu_request = None - self._driver_memory_request = None - self._executor_cpu_request = None - self._executor_memory_request = None - self._executor_replica = None - self.discriminator = None - if driver_cpu_request is not None: - self.driver_cpu_request = driver_cpu_request - if driver_memory_request is not None: - self.driver_memory_request = driver_memory_request - if executor_cpu_request is not None: - self.executor_cpu_request = executor_cpu_request - if executor_memory_request is not None: - self.executor_memory_request = executor_memory_request - if executor_replica is not None: - self.executor_replica = executor_replica - - @property - def driver_cpu_request(self): - """Gets the driver_cpu_request of this PredictionJobResourceRequest. # noqa: E501 - - - :return: The driver_cpu_request of this PredictionJobResourceRequest. # noqa: E501 - :rtype: str - """ - return self._driver_cpu_request - - @driver_cpu_request.setter - def driver_cpu_request(self, driver_cpu_request): - """Sets the driver_cpu_request of this PredictionJobResourceRequest. - - - :param driver_cpu_request: The driver_cpu_request of this PredictionJobResourceRequest. # noqa: E501 - :type: str - """ - - self._driver_cpu_request = driver_cpu_request - - @property - def driver_memory_request(self): - """Gets the driver_memory_request of this PredictionJobResourceRequest. # noqa: E501 - - - :return: The driver_memory_request of this PredictionJobResourceRequest. # noqa: E501 - :rtype: str - """ - return self._driver_memory_request - - @driver_memory_request.setter - def driver_memory_request(self, driver_memory_request): - """Sets the driver_memory_request of this PredictionJobResourceRequest. - - :param driver_memory_request: The driver_memory_request of this PredictionJobResourceRequest. # noqa: E501 - :type: str - """ - - self._driver_memory_request = driver_memory_request - - @property - def executor_cpu_request(self): - """Gets the executor_cpu_request of this PredictionJobResourceRequest. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The executor_cpu_request of this PredictionJobResourceRequest. # noqa: E501 - :rtype: str - """ - return self._executor_cpu_request + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionJobResourceRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @executor_cpu_request.setter - def executor_cpu_request(self, executor_cpu_request): - """Sets the executor_cpu_request of this PredictionJobResourceRequest. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param executor_cpu_request: The executor_cpu_request of this PredictionJobResourceRequest. # noqa: E501 - :type: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionJobResourceRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "driver_cpu_request": obj.get("driver_cpu_request"), + "driver_memory_request": obj.get("driver_memory_request"), + "executor_cpu_request": obj.get("executor_cpu_request"), + "executor_memory_request": obj.get("executor_memory_request"), + "executor_replica": obj.get("executor_replica") + }) + return _obj - self._executor_cpu_request = executor_cpu_request - - @property - def executor_memory_request(self): - """Gets the executor_memory_request of this PredictionJobResourceRequest. # noqa: E501 - - - :return: The executor_memory_request of this PredictionJobResourceRequest. # noqa: E501 - :rtype: str - """ - return self._executor_memory_request - - @executor_memory_request.setter - def executor_memory_request(self, executor_memory_request): - """Sets the executor_memory_request of this PredictionJobResourceRequest. - - - :param executor_memory_request: The executor_memory_request of this PredictionJobResourceRequest. # noqa: E501 - :type: str - """ - - self._executor_memory_request = executor_memory_request - - @property - def executor_replica(self): - """Gets the executor_replica of this PredictionJobResourceRequest. # noqa: E501 - - - :return: The executor_replica of this PredictionJobResourceRequest. # noqa: E501 - :rtype: int - """ - return self._executor_replica - - @executor_replica.setter - def executor_replica(self, executor_replica): - """Sets the executor_replica of this PredictionJobResourceRequest. - - - :param executor_replica: The executor_replica of this PredictionJobResourceRequest. # noqa: E501 - :type: int - """ - self._executor_replica = executor_replica - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionJobResourceRequest, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionJobResourceRequest): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/prediction_logger_config.py b/python/sdk/client/models/prediction_logger_config.py index 22acb71a5..c350b4870 100644 --- a/python/sdk/client/models/prediction_logger_config.py +++ b/python/sdk/client/models/prediction_logger_config.py @@ -3,160 +3,89 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class PredictionLoggerConfig(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictBool, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class PredictionLoggerConfig(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'enabled': 'bool', - 'raw_features_table': 'str', - 'entities_table': 'str' - } - - attribute_map = { - 'enabled': 'enabled', - 'raw_features_table': 'raw_features_table', - 'entities_table': 'entities_table' + PredictionLoggerConfig + """ # noqa: E501 + enabled: StrictBool + raw_features_table: Optional[StrictStr] = None + entities_table: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["enabled", "raw_features_table", "entities_table"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, enabled=None, raw_features_table=None, entities_table=None): # noqa: E501 - """PredictionLoggerConfig - a model defined in Swagger""" # noqa: E501 - self._enabled = None - self._raw_features_table = None - self._entities_table = None - self.discriminator = None - if enabled is not None: - self.enabled = enabled - if raw_features_table is not None: - self.raw_features_table = raw_features_table - if entities_table is not None: - self.entities_table = entities_table - - @property - def enabled(self): - """Gets the enabled of this PredictionLoggerConfig. # noqa: E501 - - - :return: The enabled of this PredictionLoggerConfig. # noqa: E501 - :rtype: bool - """ - return self._enabled - - @enabled.setter - def enabled(self, enabled): - """Sets the enabled of this PredictionLoggerConfig. - - :param enabled: The enabled of this PredictionLoggerConfig. # noqa: E501 - :type: bool - """ - - self._enabled = enabled - - @property - def raw_features_table(self): - """Gets the raw_features_table of this PredictionLoggerConfig. # noqa: E501 - - - :return: The raw_features_table of this PredictionLoggerConfig. # noqa: E501 - :rtype: str - """ - return self._raw_features_table + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @raw_features_table.setter - def raw_features_table(self, raw_features_table): - """Sets the raw_features_table of this PredictionLoggerConfig. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of PredictionLoggerConfig from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param raw_features_table: The raw_features_table of this PredictionLoggerConfig. # noqa: E501 - :type: str - """ - - self._raw_features_table = raw_features_table - - @property - def entities_table(self): - """Gets the entities_table of this PredictionLoggerConfig. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The entities_table of this PredictionLoggerConfig. # noqa: E501 - :rtype: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._entities_table + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of PredictionLoggerConfig from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "enabled": obj.get("enabled"), + "raw_features_table": obj.get("raw_features_table"), + "entities_table": obj.get("entities_table") + }) + return _obj - @entities_table.setter - def entities_table(self, entities_table): - """Sets the entities_table of this PredictionLoggerConfig. - - - :param entities_table: The entities_table of this PredictionLoggerConfig. # noqa: E501 - :type: str - """ - self._entities_table = entities_table - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(PredictionLoggerConfig, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, PredictionLoggerConfig): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/project.py b/python/sdk/client/models/project.py index 3f1a59442..630732ac4 100644 --- a/python/sdk/client/models/project.py +++ b/python/sdk/client/models/project.py @@ -3,343 +3,111 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class Project(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.label import Label +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Project(BaseModel): """ - swagger_types = { - 'id': 'int', - 'name': 'str', - 'mlflow_tracking_url': 'str', - 'administrators': 'list[str]', - 'readers': 'list[str]', - 'team': 'str', - 'stream': 'str', - 'labels': 'list[Label]', - 'created_at': 'datetime', - 'updated_at': 'datetime' + Project + """ # noqa: E501 + id: StrictInt + name: StrictStr + mlflow_tracking_url: Optional[StrictStr] = None + administrators: Optional[List[StrictStr]] = None + readers: Optional[List[StrictStr]] = None + team: Optional[StrictStr] = None + stream: Optional[StrictStr] = None + labels: Optional[List[Label]] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "name", "mlflow_tracking_url", "administrators", "readers", "team", "stream", "labels", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'id': 'id', - 'name': 'name', - 'mlflow_tracking_url': 'mlflow_tracking_url', - 'administrators': 'administrators', - 'readers': 'readers', - 'team': 'team', - 'stream': 'stream', - 'labels': 'labels', - 'created_at': 'created_at', - 'updated_at': 'updated_at' - } - - def __init__(self, id=None, name=None, mlflow_tracking_url=None, administrators=None, readers=None, team=None, stream=None, labels=None, created_at=None, updated_at=None): # noqa: E501 - """Project - a model defined in Swagger""" # noqa: E501 - self._id = None - self._name = None - self._mlflow_tracking_url = None - self._administrators = None - self._readers = None - self._team = None - self._stream = None - self._labels = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - self.name = name - if mlflow_tracking_url is not None: - self.mlflow_tracking_url = mlflow_tracking_url - if administrators is not None: - self.administrators = administrators - if readers is not None: - self.readers = readers - if team is not None: - self.team = team - if stream is not None: - self.stream = stream - if labels is not None: - self.labels = labels - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this Project. # noqa: E501 - - - :return: The id of this Project. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Project. - - - :param id: The id of this Project. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this Project. # noqa: E501 - - - :return: The name of this Project. # noqa: E501 - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Project. - - - :param name: The name of this Project. # noqa: E501 - :type: str - """ - if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def mlflow_tracking_url(self): - """Gets the mlflow_tracking_url of this Project. # noqa: E501 - - - :return: The mlflow_tracking_url of this Project. # noqa: E501 - :rtype: str - """ - return self._mlflow_tracking_url - - @mlflow_tracking_url.setter - def mlflow_tracking_url(self, mlflow_tracking_url): - """Sets the mlflow_tracking_url of this Project. - - - :param mlflow_tracking_url: The mlflow_tracking_url of this Project. # noqa: E501 - :type: str - """ - - self._mlflow_tracking_url = mlflow_tracking_url - - @property - def administrators(self): - """Gets the administrators of this Project. # noqa: E501 - - - :return: The administrators of this Project. # noqa: E501 - :rtype: list[str] - """ - return self._administrators - - @administrators.setter - def administrators(self, administrators): - """Sets the administrators of this Project. - - - :param administrators: The administrators of this Project. # noqa: E501 - :type: list[str] - """ - - self._administrators = administrators - - @property - def readers(self): - """Gets the readers of this Project. # noqa: E501 - - - :return: The readers of this Project. # noqa: E501 - :rtype: list[str] - """ - return self._readers - - @readers.setter - def readers(self, readers): - """Sets the readers of this Project. - - - :param readers: The readers of this Project. # noqa: E501 - :type: list[str] - """ - - self._readers = readers - - @property - def team(self): - """Gets the team of this Project. # noqa: E501 - - - :return: The team of this Project. # noqa: E501 - :rtype: str - """ - return self._team - - @team.setter - def team(self, team): - """Sets the team of this Project. - - - :param team: The team of this Project. # noqa: E501 - :type: str - """ - - self._team = team - - @property - def stream(self): - """Gets the stream of this Project. # noqa: E501 - - - :return: The stream of this Project. # noqa: E501 - :rtype: str - """ - return self._stream - - @stream.setter - def stream(self, stream): - """Sets the stream of this Project. - - - :param stream: The stream of this Project. # noqa: E501 - :type: str - """ - - self._stream = stream - - @property - def labels(self): - """Gets the labels of this Project. # noqa: E501 - - - :return: The labels of this Project. # noqa: E501 - :rtype: list[Label] - """ - return self._labels - - @labels.setter - def labels(self, labels): - """Sets the labels of this Project. - - - :param labels: The labels of this Project. # noqa: E501 - :type: list[Label] - """ - - self._labels = labels - - @property - def created_at(self): - """Gets the created_at of this Project. # noqa: E501 - - - :return: The created_at of this Project. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this Project. - - - :param created_at: The created_at of this Project. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this Project. # noqa: E501 - - - :return: The updated_at of this Project. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this Project. - - - :param updated_at: The updated_at of this Project. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Project, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Project): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Project from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in labels (list) + _items = [] + if self.labels: + for _item in self.labels: + if _item: + _items.append(_item.to_dict()) + _dict['labels'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Project from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "mlflow_tracking_url": obj.get("mlflow_tracking_url"), + "administrators": obj.get("administrators"), + "readers": obj.get("readers"), + "team": obj.get("team"), + "stream": obj.get("stream"), + "labels": [Label.from_dict(_item) for _item in obj.get("labels")] if obj.get("labels") is not None else None, + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/protocol.py b/python/sdk/client/models/protocol.py index f85f4e5b1..7a60638dc 100644 --- a/python/sdk/client/models/protocol.py +++ b/python/sdk/client/models/protocol.py @@ -3,88 +3,43 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class Protocol(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Protocol(str, Enum): """ - allowed enum values + Protocol """ - HTTP_JSON = "HTTP_JSON" - UPI_V1 = "UPI_V1" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """Protocol - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Protocol, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + HTTP_JSON = 'HTTP_JSON' + UPI_V1 = 'UPI_V1' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Protocol): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Protocol from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/ranking_output.py b/python/sdk/client/models/ranking_output.py new file mode 100644 index 000000000..426d80add --- /dev/null +++ b/python/sdk/client/models/ranking_output.py @@ -0,0 +1,94 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.model_prediction_output_class import ModelPredictionOutputClass +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class RankingOutput(BaseModel): + """ + RankingOutput + """ # noqa: E501 + rank_score_column: StrictStr + prediction_group_id_column: StrictStr + relevance_score_column: Optional[StrictStr] = None + output_class: Optional[ModelPredictionOutputClass] = None + __properties: ClassVar[List[str]] = ["rank_score_column", "prediction_group_id_column", "relevance_score_column", "output_class"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of RankingOutput from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of RankingOutput from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "rank_score_column": obj.get("rank_score_column"), + "prediction_group_id_column": obj.get("prediction_group_id_column"), + "relevance_score_column": obj.get("relevance_score_column"), + "output_class": obj.get("output_class") + }) + return _obj + + diff --git a/python/sdk/client/models/regression_output.py b/python/sdk/client/models/regression_output.py new file mode 100644 index 000000000..74c9fb4cc --- /dev/null +++ b/python/sdk/client/models/regression_output.py @@ -0,0 +1,92 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.model_prediction_output_class import ModelPredictionOutputClass +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class RegressionOutput(BaseModel): + """ + RegressionOutput + """ # noqa: E501 + prediction_score_column: StrictStr + actual_score_column: Optional[StrictStr] = None + output_class: Optional[ModelPredictionOutputClass] = None + __properties: ClassVar[List[str]] = ["prediction_score_column", "actual_score_column", "output_class"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of RegressionOutput from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of RegressionOutput from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "prediction_score_column": obj.get("prediction_score_column"), + "actual_score_column": obj.get("actual_score_column"), + "output_class": obj.get("output_class") + }) + return _obj + + diff --git a/python/sdk/client/models/resource_request.py b/python/sdk/client/models/resource_request.py index 38480f1ac..fae8c0445 100644 --- a/python/sdk/client/models/resource_request.py +++ b/python/sdk/client/models/resource_request.py @@ -3,238 +3,95 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class ResourceRequest(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +class ResourceRequest(BaseModel): """ - swagger_types = { - 'min_replica': 'int', - 'max_replica': 'int', - 'cpu_request': 'str', - 'memory_request': 'str', - 'gpu_name': 'str', - 'gpu_request': 'str' + ResourceRequest + """ # noqa: E501 + min_replica: Optional[StrictInt] = None + max_replica: Optional[StrictInt] = None + cpu_request: Optional[StrictStr] = None + memory_request: Optional[StrictStr] = None + gpu_name: Optional[StrictStr] = None + gpu_request: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["min_replica", "max_replica", "cpu_request", "memory_request", "gpu_name", "gpu_request"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'min_replica': 'min_replica', - 'max_replica': 'max_replica', - 'cpu_request': 'cpu_request', - 'memory_request': 'memory_request', - 'gpu_name': 'gpu_name', - 'gpu_request': 'gpu_request' - } - - def __init__(self, min_replica=None, max_replica=None, cpu_request=None, memory_request=None, gpu_name=None, gpu_request=None): # noqa: E501 - """ResourceRequest - a model defined in Swagger""" # noqa: E501 - self._min_replica = None - self._max_replica = None - self._cpu_request = None - self._memory_request = None - self._gpu_name = None - self._gpu_request = None - self.discriminator = None - if min_replica is not None: - self.min_replica = min_replica - if max_replica is not None: - self.max_replica = max_replica - if cpu_request is not None: - self.cpu_request = cpu_request - if memory_request is not None: - self.memory_request = memory_request - if gpu_name is not None: - self.gpu_name = gpu_name - if gpu_request is not None: - self.gpu_request = gpu_request - - @property - def min_replica(self): - """Gets the min_replica of this ResourceRequest. # noqa: E501 - - - :return: The min_replica of this ResourceRequest. # noqa: E501 - :rtype: int - """ - return self._min_replica - - @min_replica.setter - def min_replica(self, min_replica): - """Sets the min_replica of this ResourceRequest. - - - :param min_replica: The min_replica of this ResourceRequest. # noqa: E501 - :type: int - """ - - self._min_replica = min_replica - @property - def max_replica(self): - """Gets the max_replica of this ResourceRequest. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The max_replica of this ResourceRequest. # noqa: E501 - :rtype: int - """ - return self._max_replica + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ResourceRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @max_replica.setter - def max_replica(self, max_replica): - """Sets the max_replica of this ResourceRequest. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param max_replica: The max_replica of this ResourceRequest. # noqa: E501 - :type: int + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of ResourceRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "min_replica": obj.get("min_replica"), + "max_replica": obj.get("max_replica"), + "cpu_request": obj.get("cpu_request"), + "memory_request": obj.get("memory_request"), + "gpu_name": obj.get("gpu_name"), + "gpu_request": obj.get("gpu_request") + }) + return _obj - self._max_replica = max_replica - - @property - def cpu_request(self): - """Gets the cpu_request of this ResourceRequest. # noqa: E501 - - - :return: The cpu_request of this ResourceRequest. # noqa: E501 - :rtype: str - """ - return self._cpu_request - - @cpu_request.setter - def cpu_request(self, cpu_request): - """Sets the cpu_request of this ResourceRequest. - - - :param cpu_request: The cpu_request of this ResourceRequest. # noqa: E501 - :type: str - """ - - self._cpu_request = cpu_request - - @property - def memory_request(self): - """Gets the memory_request of this ResourceRequest. # noqa: E501 - - - :return: The memory_request of this ResourceRequest. # noqa: E501 - :rtype: str - """ - return self._memory_request - - @memory_request.setter - def memory_request(self, memory_request): - """Sets the memory_request of this ResourceRequest. - - - :param memory_request: The memory_request of this ResourceRequest. # noqa: E501 - :type: str - """ - - self._memory_request = memory_request - - @property - def gpu_name(self): - """Gets the gpu_name of this ResourceRequest. # noqa: E501 - - - :return: The gpu_name of this ResourceRequest. # noqa: E501 - :rtype: str - """ - return self._gpu_name - - @gpu_name.setter - def gpu_name(self, gpu_name): - """Sets the gpu_name of this ResourceRequest. - - - :param gpu_name: The gpu_name of this ResourceRequest. # noqa: E501 - :type: str - """ - - self._gpu_name = gpu_name - - @property - def gpu_request(self): - """Gets the gpu_request of this ResourceRequest. # noqa: E501 - - - :return: The gpu_request of this ResourceRequest. # noqa: E501 - :rtype: str - """ - return self._gpu_request - - @gpu_request.setter - def gpu_request(self, gpu_request): - """Sets the gpu_request of this ResourceRequest. - - - :param gpu_request: The gpu_request of this ResourceRequest. # noqa: E501 - :type: str - """ - self._gpu_request = gpu_request - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ResourceRequest, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ResourceRequest): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/result_type.py b/python/sdk/client/models/result_type.py index a2f5fd520..fce1b50d3 100644 --- a/python/sdk/client/models/result_type.py +++ b/python/sdk/client/models/result_type.py @@ -3,92 +3,47 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class ResultType(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class ResultType(str, Enum): """ - allowed enum values + ResultType """ - DOUBLE = "DOUBLE" - FLOAT = "FLOAT" - INTEGER = "INTEGER" - LONG = "LONG" - STRING = "STRING" - ARRAY = "ARRAY" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """ResultType - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(ResultType, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + DOUBLE = 'DOUBLE' + FLOAT = 'FLOAT' + INTEGER = 'INTEGER' + LONG = 'LONG' + STRING = 'STRING' + ARRAY = 'ARRAY' - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, ResultType): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ResultType from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/save_mode.py b/python/sdk/client/models/save_mode.py index 454106e0c..b83b9f70e 100644 --- a/python/sdk/client/models/save_mode.py +++ b/python/sdk/client/models/save_mode.py @@ -3,91 +3,46 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations +import json import pprint import re # noqa: F401 +from enum import Enum -import six -class SaveMode(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class SaveMode(int, Enum): """ - allowed enum values + SaveMode """ - ERRORIFEXISTS = "ERRORIFEXISTS" - OVERWRITE = "OVERWRITE" - APPEND = "APPEND" - IGNORE = "IGNORE" - ERROR = "ERROR" + """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. + allowed enum values """ - swagger_types = { - } - - attribute_map = { - } - - def __init__(self): # noqa: E501 - """SaveMode - a model defined in Swagger""" # noqa: E501 - self.discriminator = None - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(SaveMode, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() + NUMBER_0 = 0 + NUMBER_1 = 1 + NUMBER_2 = 2 + NUMBER_3 = 3 + NUMBER_4 = 4 - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, SaveMode): - return False + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SaveMode from a JSON string""" + return cls(json.loads(json_str)) - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/schema_spec.py b/python/sdk/client/models/schema_spec.py new file mode 100644 index 000000000..26e02f4e2 --- /dev/null +++ b/python/sdk/client/models/schema_spec.py @@ -0,0 +1,98 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + + +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictStr +from client.models.model_prediction_output import ModelPredictionOutput +from client.models.value_type import ValueType +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class SchemaSpec(BaseModel): + """ + SchemaSpec + """ # noqa: E501 + prediction_id_column: StrictStr + model_prediction_output: ModelPredictionOutput + tag_columns: Optional[List[StrictStr]] = None + feature_types: Dict[str, ValueType] + __properties: ClassVar[List[str]] = ["prediction_id_column", "model_prediction_output", "tag_columns", "feature_types"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of SchemaSpec from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of model_prediction_output + if self.model_prediction_output: + _dict['model_prediction_output'] = self.model_prediction_output.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of SchemaSpec from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "prediction_id_column": obj.get("prediction_id_column"), + "model_prediction_output": ModelPredictionOutput.from_dict(obj.get("model_prediction_output")) if obj.get("model_prediction_output") is not None else None, + "tag_columns": obj.get("tag_columns"), + "feature_types": dict((_k, _v) for _k, _v in obj.get("feature_types").items()) + }) + return _obj + + diff --git a/python/sdk/client/models/secret.py b/python/sdk/client/models/secret.py index a39a3b412..e9a3fbe29 100644 --- a/python/sdk/client/models/secret.py +++ b/python/sdk/client/models/secret.py @@ -3,160 +3,89 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class Secret(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictInt, StrictStr +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class Secret(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'id': 'int', - 'name': 'str', - 'data': 'str' - } - - attribute_map = { - 'id': 'id', - 'name': 'name', - 'data': 'data' + Secret + """ # noqa: E501 + id: Optional[StrictInt] = None + name: Optional[StrictStr] = None + data: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["id", "name", "data"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, id=None, name=None, data=None): # noqa: E501 - """Secret - a model defined in Swagger""" # noqa: E501 - self._id = None - self._name = None - self._data = None - self.discriminator = None - if id is not None: - self.id = id - if name is not None: - self.name = name - if data is not None: - self.data = data - - @property - def id(self): - """Gets the id of this Secret. # noqa: E501 - - - :return: The id of this Secret. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Secret. - - :param id: The id of this Secret. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this Secret. # noqa: E501 - - - :return: The name of this Secret. # noqa: E501 - :rtype: str - """ - return self._name + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) - @name.setter - def name(self, name): - """Sets the name of this Secret. + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Secret from a JSON string""" + return cls.from_dict(json.loads(json_str)) - :param name: The name of this Secret. # noqa: E501 - :type: str - """ - - self._name = name - - @property - def data(self): - """Gets the data of this Secret. # noqa: E501 + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :return: The data of this Secret. # noqa: E501 - :rtype: str + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ - return self._data + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Secret from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "name": obj.get("name"), + "data": obj.get("data") + }) + return _obj - @data.setter - def data(self, data): - """Sets the data of this Secret. - - - :param data: The data of this Secret. # noqa: E501 - :type: str - """ - self._data = data - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Secret, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Secret): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/standard_transformer_simulation_request.py b/python/sdk/client/models/standard_transformer_simulation_request.py index f97520259..22d018a4c 100644 --- a/python/sdk/client/models/standard_transformer_simulation_request.py +++ b/python/sdk/client/models/standard_transformer_simulation_request.py @@ -3,212 +3,98 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class StandardTransformerSimulationRequest(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel +from client.models.model_prediction_config import ModelPredictionConfig +from client.models.protocol import Protocol +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. - """ +class StandardTransformerSimulationRequest(BaseModel): """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'payload': 'FreeFormObject', - 'headers': 'FreeFormObject', - 'config': 'FreeFormObject', - 'model_prediction_config': 'ModelPredictionConfig', - 'protocol': 'Protocol' - } - - attribute_map = { - 'payload': 'payload', - 'headers': 'headers', - 'config': 'config', - 'model_prediction_config': 'model_prediction_config', - 'protocol': 'protocol' + StandardTransformerSimulationRequest + """ # noqa: E501 + payload: Optional[Union[str, Any]] = None + headers: Optional[Union[str, Any]] = None + config: Optional[Union[str, Any]] = None + model_prediction_config: Optional[ModelPredictionConfig] = None + protocol: Optional[Protocol] = None + __properties: ClassVar[List[str]] = ["payload", "headers", "config", "model_prediction_config", "protocol"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, payload=None, headers=None, config=None, model_prediction_config=None, protocol=None): # noqa: E501 - """StandardTransformerSimulationRequest - a model defined in Swagger""" # noqa: E501 - self._payload = None - self._headers = None - self._config = None - self._model_prediction_config = None - self._protocol = None - self.discriminator = None - if payload is not None: - self.payload = payload - if headers is not None: - self.headers = headers - if config is not None: - self.config = config - if model_prediction_config is not None: - self.model_prediction_config = model_prediction_config - if protocol is not None: - self.protocol = protocol - - @property - def payload(self): - """Gets the payload of this StandardTransformerSimulationRequest. # noqa: E501 - - - :return: The payload of this StandardTransformerSimulationRequest. # noqa: E501 - :rtype: FreeFormObject - """ - return self._payload - - @payload.setter - def payload(self, payload): - """Sets the payload of this StandardTransformerSimulationRequest. - - - :param payload: The payload of this StandardTransformerSimulationRequest. # noqa: E501 - :type: FreeFormObject - """ - - self._payload = payload - - @property - def headers(self): - """Gets the headers of this StandardTransformerSimulationRequest. # noqa: E501 - - - :return: The headers of this StandardTransformerSimulationRequest. # noqa: E501 - :rtype: FreeFormObject - """ - return self._headers - - @headers.setter - def headers(self, headers): - """Sets the headers of this StandardTransformerSimulationRequest. - - :param headers: The headers of this StandardTransformerSimulationRequest. # noqa: E501 - :type: FreeFormObject - """ - - self._headers = headers - - @property - def config(self): - """Gets the config of this StandardTransformerSimulationRequest. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The config of this StandardTransformerSimulationRequest. # noqa: E501 - :rtype: FreeFormObject - """ - return self._config + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of StandardTransformerSimulationRequest from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @config.setter - def config(self, config): - """Sets the config of this StandardTransformerSimulationRequest. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param config: The config of this StandardTransformerSimulationRequest. # noqa: E501 - :type: FreeFormObject + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of model_prediction_config + if self.model_prediction_config: + _dict['model_prediction_config'] = self.model_prediction_config.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of StandardTransformerSimulationRequest from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "payload": obj.get("payload"), + "headers": obj.get("headers"), + "config": obj.get("config"), + "model_prediction_config": ModelPredictionConfig.from_dict(obj.get("model_prediction_config")) if obj.get("model_prediction_config") is not None else None, + "protocol": obj.get("protocol") + }) + return _obj - self._config = config - - @property - def model_prediction_config(self): - """Gets the model_prediction_config of this StandardTransformerSimulationRequest. # noqa: E501 - - - :return: The model_prediction_config of this StandardTransformerSimulationRequest. # noqa: E501 - :rtype: ModelPredictionConfig - """ - return self._model_prediction_config - - @model_prediction_config.setter - def model_prediction_config(self, model_prediction_config): - """Sets the model_prediction_config of this StandardTransformerSimulationRequest. - - - :param model_prediction_config: The model_prediction_config of this StandardTransformerSimulationRequest. # noqa: E501 - :type: ModelPredictionConfig - """ - - self._model_prediction_config = model_prediction_config - - @property - def protocol(self): - """Gets the protocol of this StandardTransformerSimulationRequest. # noqa: E501 - - - :return: The protocol of this StandardTransformerSimulationRequest. # noqa: E501 - :rtype: Protocol - """ - return self._protocol - - @protocol.setter - def protocol(self, protocol): - """Sets the protocol of this StandardTransformerSimulationRequest. - - - :param protocol: The protocol of this StandardTransformerSimulationRequest. # noqa: E501 - :type: Protocol - """ - self._protocol = protocol - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(StandardTransformerSimulationRequest, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, StandardTransformerSimulationRequest): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/standard_transformer_simulation_response.py b/python/sdk/client/models/standard_transformer_simulation_response.py index 15649e54a..8bf6baf7e 100644 --- a/python/sdk/client/models/standard_transformer_simulation_response.py +++ b/python/sdk/client/models/standard_transformer_simulation_response.py @@ -3,134 +3,91 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + +from __future__ import annotations import pprint import re # noqa: F401 +import json -import six -class StandardTransformerSimulationResponse(object): - """NOTE: This class is auto generated by the swagger code generator program. +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel +from client.models.operation_tracing import OperationTracing +try: + from typing import Self +except ImportError: + from typing_extensions import Self - Do not edit the class manually. +class StandardTransformerSimulationResponse(BaseModel): """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - """ - swagger_types = { - 'response': 'FreeFormObject', - 'operation_tracing': 'OperationTracing' - } - - attribute_map = { - 'response': 'response', - 'operation_tracing': 'operation_tracing' + StandardTransformerSimulationResponse + """ # noqa: E501 + response: Optional[Union[str, Any]] = None + operation_tracing: Optional[OperationTracing] = None + __properties: ClassVar[List[str]] = ["response", "operation_tracing"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, response=None, operation_tracing=None): # noqa: E501 - """StandardTransformerSimulationResponse - a model defined in Swagger""" # noqa: E501 - self._response = None - self._operation_tracing = None - self.discriminator = None - if response is not None: - self.response = response - if operation_tracing is not None: - self.operation_tracing = operation_tracing - @property - def response(self): - """Gets the response of this StandardTransformerSimulationResponse. # noqa: E501 + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) - :return: The response of this StandardTransformerSimulationResponse. # noqa: E501 - :rtype: FreeFormObject - """ - return self._response + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of StandardTransformerSimulationResponse from a JSON string""" + return cls.from_dict(json.loads(json_str)) - @response.setter - def response(self, response): - """Sets the response of this StandardTransformerSimulationResponse. + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: - :param response: The response of this StandardTransformerSimulationResponse. # noqa: E501 - :type: FreeFormObject + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of operation_tracing + if self.operation_tracing: + _dict['operation_tracing'] = self.operation_tracing.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of StandardTransformerSimulationResponse from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "response": obj.get("response"), + "operation_tracing": OperationTracing.from_dict(obj.get("operation_tracing")) if obj.get("operation_tracing") is not None else None + }) + return _obj - self._response = response - - @property - def operation_tracing(self): - """Gets the operation_tracing of this StandardTransformerSimulationResponse. # noqa: E501 - - - :return: The operation_tracing of this StandardTransformerSimulationResponse. # noqa: E501 - :rtype: OperationTracing - """ - return self._operation_tracing - - @operation_tracing.setter - def operation_tracing(self, operation_tracing): - """Sets the operation_tracing of this StandardTransformerSimulationResponse. - - - :param operation_tracing: The operation_tracing of this StandardTransformerSimulationResponse. # noqa: E501 - :type: OperationTracing - """ - self._operation_tracing = operation_tracing - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(StandardTransformerSimulationResponse, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, StandardTransformerSimulationResponse): - return False - - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/transformer.py b/python/sdk/client/models/transformer.py index 2763fa140..c24769f6a 100644 --- a/python/sdk/client/models/transformer.py +++ b/python/sdk/client/models/transformer.py @@ -3,342 +3,115 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class Transformer(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictBool, StrictStr +from client.models.env_var import EnvVar +from client.models.resource_request import ResourceRequest +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Transformer(BaseModel): """ - swagger_types = { - 'id': 'str', - 'enabled': 'bool', - 'transformer_type': 'str', - 'image': 'str', - 'command': 'str', - 'args': 'str', - 'resource_request': 'ResourceRequest', - 'env_vars': 'list[EnvVar]', - 'created_at': 'datetime', - 'updated_at': 'datetime' + Transformer + """ # noqa: E501 + id: Optional[StrictStr] = None + enabled: Optional[StrictBool] = None + transformer_type: Optional[StrictStr] = None + image: Optional[StrictStr] = None + command: Optional[StrictStr] = None + args: Optional[StrictStr] = None + resource_request: Optional[ResourceRequest] = None + env_vars: Optional[List[EnvVar]] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "enabled", "transformer_type", "image", "command", "args", "resource_request", "env_vars", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'id': 'id', - 'enabled': 'enabled', - 'transformer_type': 'transformer_type', - 'image': 'image', - 'command': 'command', - 'args': 'args', - 'resource_request': 'resource_request', - 'env_vars': 'env_vars', - 'created_at': 'created_at', - 'updated_at': 'updated_at' - } - - def __init__(self, id=None, enabled=None, transformer_type=None, image=None, command=None, args=None, resource_request=None, env_vars=None, created_at=None, updated_at=None): # noqa: E501 - """Transformer - a model defined in Swagger""" # noqa: E501 - self._id = None - self._enabled = None - self._transformer_type = None - self._image = None - self._command = None - self._args = None - self._resource_request = None - self._env_vars = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - if enabled is not None: - self.enabled = enabled - if transformer_type is not None: - self.transformer_type = transformer_type - if image is not None: - self.image = image - if command is not None: - self.command = command - if args is not None: - self.args = args - if resource_request is not None: - self.resource_request = resource_request - if env_vars is not None: - self.env_vars = env_vars - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this Transformer. # noqa: E501 - - - :return: The id of this Transformer. # noqa: E501 - :rtype: str - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Transformer. - - - :param id: The id of this Transformer. # noqa: E501 - :type: str - """ - - self._id = id - - @property - def enabled(self): - """Gets the enabled of this Transformer. # noqa: E501 - - - :return: The enabled of this Transformer. # noqa: E501 - :rtype: bool - """ - return self._enabled - - @enabled.setter - def enabled(self, enabled): - """Sets the enabled of this Transformer. - - - :param enabled: The enabled of this Transformer. # noqa: E501 - :type: bool - """ - - self._enabled = enabled - - @property - def transformer_type(self): - """Gets the transformer_type of this Transformer. # noqa: E501 - - - :return: The transformer_type of this Transformer. # noqa: E501 - :rtype: str - """ - return self._transformer_type - - @transformer_type.setter - def transformer_type(self, transformer_type): - """Sets the transformer_type of this Transformer. - - - :param transformer_type: The transformer_type of this Transformer. # noqa: E501 - :type: str - """ - - self._transformer_type = transformer_type - - @property - def image(self): - """Gets the image of this Transformer. # noqa: E501 - - - :return: The image of this Transformer. # noqa: E501 - :rtype: str - """ - return self._image - - @image.setter - def image(self, image): - """Sets the image of this Transformer. - - - :param image: The image of this Transformer. # noqa: E501 - :type: str - """ - - self._image = image - - @property - def command(self): - """Gets the command of this Transformer. # noqa: E501 - - - :return: The command of this Transformer. # noqa: E501 - :rtype: str - """ - return self._command - - @command.setter - def command(self, command): - """Sets the command of this Transformer. - - - :param command: The command of this Transformer. # noqa: E501 - :type: str - """ - - self._command = command - - @property - def args(self): - """Gets the args of this Transformer. # noqa: E501 - - - :return: The args of this Transformer. # noqa: E501 - :rtype: str - """ - return self._args - - @args.setter - def args(self, args): - """Sets the args of this Transformer. - - - :param args: The args of this Transformer. # noqa: E501 - :type: str - """ - - self._args = args - - @property - def resource_request(self): - """Gets the resource_request of this Transformer. # noqa: E501 - - - :return: The resource_request of this Transformer. # noqa: E501 - :rtype: ResourceRequest - """ - return self._resource_request - - @resource_request.setter - def resource_request(self, resource_request): - """Sets the resource_request of this Transformer. - - - :param resource_request: The resource_request of this Transformer. # noqa: E501 - :type: ResourceRequest - """ - - self._resource_request = resource_request - - @property - def env_vars(self): - """Gets the env_vars of this Transformer. # noqa: E501 - - - :return: The env_vars of this Transformer. # noqa: E501 - :rtype: list[EnvVar] - """ - return self._env_vars - - @env_vars.setter - def env_vars(self, env_vars): - """Sets the env_vars of this Transformer. - - - :param env_vars: The env_vars of this Transformer. # noqa: E501 - :type: list[EnvVar] - """ - - self._env_vars = env_vars - - @property - def created_at(self): - """Gets the created_at of this Transformer. # noqa: E501 - - - :return: The created_at of this Transformer. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this Transformer. - - - :param created_at: The created_at of this Transformer. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this Transformer. # noqa: E501 - - - :return: The updated_at of this Transformer. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this Transformer. - - - :param updated_at: The updated_at of this Transformer. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Transformer, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Transformer): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Transformer from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of resource_request + if self.resource_request: + _dict['resource_request'] = self.resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in env_vars (list) + _items = [] + if self.env_vars: + for _item in self.env_vars: + if _item: + _items.append(_item.to_dict()) + _dict['env_vars'] = _items + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Transformer from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "enabled": obj.get("enabled"), + "transformer_type": obj.get("transformer_type"), + "image": obj.get("image"), + "command": obj.get("command"), + "args": obj.get("args"), + "resource_request": ResourceRequest.from_dict(obj.get("resource_request")) if obj.get("resource_request") is not None else None, + "env_vars": [EnvVar.from_dict(_item) for _item in obj.get("env_vars")] if obj.get("env_vars") is not None else None, + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/value_type.py b/python/sdk/client/models/value_type.py new file mode 100644 index 000000000..7a6b6cd48 --- /dev/null +++ b/python/sdk/client/models/value_type.py @@ -0,0 +1,47 @@ +# coding: utf-8 + +""" + Merlin + + API Guide for accessing Merlin's model management, deployment, and serving functionalities + + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import json +import pprint +import re # noqa: F401 +from enum import Enum + + + +try: + from typing import Self +except ImportError: + from typing_extensions import Self + + +class ValueType(str, Enum): + """ + ValueType + """ + + """ + allowed enum values + """ + FLOAT64 = 'float64' + INT64 = 'int64' + BOOLEAN = 'boolean' + STRING = 'string' + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of ValueType from a JSON string""" + return cls(json.loads(json_str)) + + diff --git a/python/sdk/client/models/version.py b/python/sdk/client/models/version.py index ce849836e..7591072e4 100644 --- a/python/sdk/client/models/version.py +++ b/python/sdk/client/models/version.py @@ -3,394 +3,125 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class Version(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional, Union +from pydantic import BaseModel, StrictInt, StrictStr +from client.models.custom_predictor import CustomPredictor +from client.models.model_schema import ModelSchema +from client.models.version_endpoint import VersionEndpoint +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class Version(BaseModel): """ - swagger_types = { - 'id': 'int', - 'model_id': 'int', - 'mlflow_run_id': 'str', - 'mlflow_url': 'str', - 'artifact_uri': 'str', - 'endpoints': 'list[VersionEndpoint]', - 'properties': 'object', - 'labels': 'dict(str, str)', - 'custom_predictor': 'CustomPredictor', - 'created_at': 'datetime', - 'updated_at': 'datetime', - 'python_version': 'str' - } - - attribute_map = { - 'id': 'id', - 'model_id': 'model_id', - 'mlflow_run_id': 'mlflow_run_id', - 'mlflow_url': 'mlflow_url', - 'artifact_uri': 'artifact_uri', - 'endpoints': 'endpoints', - 'properties': 'properties', - 'labels': 'labels', - 'custom_predictor': 'custom_predictor', - 'created_at': 'created_at', - 'updated_at': 'updated_at', - 'python_version': 'python_version' + Version + """ # noqa: E501 + id: Optional[StrictInt] = None + model_id: Optional[StrictInt] = None + mlflow_run_id: Optional[StrictStr] = None + mlflow_url: Optional[StrictStr] = None + artifact_uri: Optional[StrictStr] = None + endpoints: Optional[List[VersionEndpoint]] = None + properties: Optional[Union[str, Any]] = None + labels: Optional[Dict[str, StrictStr]] = None + custom_predictor: Optional[CustomPredictor] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + python_version: Optional[StrictStr] = None + model_schema: Optional[ModelSchema] = None + __properties: ClassVar[List[str]] = ["id", "model_id", "mlflow_run_id", "mlflow_url", "artifact_uri", "endpoints", "properties", "labels", "custom_predictor", "created_at", "updated_at", "python_version", "model_schema"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - def __init__(self, id=None, model_id=None, mlflow_run_id=None, mlflow_url=None, artifact_uri=None, endpoints=None, properties=None, labels=None, custom_predictor=None, created_at=None, updated_at=None, python_version=None): # noqa: E501 - """Version - a model defined in Swagger""" # noqa: E501 - self._id = None - self._model_id = None - self._mlflow_run_id = None - self._mlflow_url = None - self._artifact_uri = None - self._endpoints = None - self._properties = None - self._labels = None - self._custom_predictor = None - self._created_at = None - self._updated_at = None - self._python_version = None - self.discriminator = None - if id is not None: - self.id = id - if model_id is not None: - self.model_id = model_id - if mlflow_run_id is not None: - self.mlflow_run_id = mlflow_run_id - if mlflow_url is not None: - self.mlflow_url = mlflow_url - if artifact_uri is not None: - self.artifact_uri = artifact_uri - if endpoints is not None: - self.endpoints = endpoints - if properties is not None: - self.properties = properties - if labels is not None: - self.labels = labels - if custom_predictor is not None: - self.custom_predictor = custom_predictor - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - if python_version is not None: - self.python_version = python_version - - @property - def id(self): - """Gets the id of this Version. # noqa: E501 - - - :return: The id of this Version. # noqa: E501 - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Version. - - - :param id: The id of this Version. # noqa: E501 - :type: int - """ - - self._id = id - - @property - def model_id(self): - """Gets the model_id of this Version. # noqa: E501 - - - :return: The model_id of this Version. # noqa: E501 - :rtype: int - """ - return self._model_id - - @model_id.setter - def model_id(self, model_id): - """Sets the model_id of this Version. - - - :param model_id: The model_id of this Version. # noqa: E501 - :type: int - """ - - self._model_id = model_id - - @property - def mlflow_run_id(self): - """Gets the mlflow_run_id of this Version. # noqa: E501 - - - :return: The mlflow_run_id of this Version. # noqa: E501 - :rtype: str - """ - return self._mlflow_run_id - - @mlflow_run_id.setter - def mlflow_run_id(self, mlflow_run_id): - """Sets the mlflow_run_id of this Version. - - - :param mlflow_run_id: The mlflow_run_id of this Version. # noqa: E501 - :type: str - """ - - self._mlflow_run_id = mlflow_run_id - - @property - def mlflow_url(self): - """Gets the mlflow_url of this Version. # noqa: E501 - - - :return: The mlflow_url of this Version. # noqa: E501 - :rtype: str - """ - return self._mlflow_url - - @mlflow_url.setter - def mlflow_url(self, mlflow_url): - """Sets the mlflow_url of this Version. - - - :param mlflow_url: The mlflow_url of this Version. # noqa: E501 - :type: str - """ - - self._mlflow_url = mlflow_url - - @property - def artifact_uri(self): - """Gets the artifact_uri of this Version. # noqa: E501 - - - :return: The artifact_uri of this Version. # noqa: E501 - :rtype: str - """ - return self._artifact_uri - - @artifact_uri.setter - def artifact_uri(self, artifact_uri): - """Sets the artifact_uri of this Version. - - - :param artifact_uri: The artifact_uri of this Version. # noqa: E501 - :type: str - """ - - self._artifact_uri = artifact_uri - - @property - def endpoints(self): - """Gets the endpoints of this Version. # noqa: E501 - - - :return: The endpoints of this Version. # noqa: E501 - :rtype: list[VersionEndpoint] - """ - return self._endpoints - - @endpoints.setter - def endpoints(self, endpoints): - """Sets the endpoints of this Version. - - - :param endpoints: The endpoints of this Version. # noqa: E501 - :type: list[VersionEndpoint] - """ - - self._endpoints = endpoints - - @property - def properties(self): - """Gets the properties of this Version. # noqa: E501 - - - :return: The properties of this Version. # noqa: E501 - :rtype: object - """ - return self._properties - - @properties.setter - def properties(self, properties): - """Sets the properties of this Version. - - - :param properties: The properties of this Version. # noqa: E501 - :type: object - """ - - self._properties = properties - - @property - def labels(self): - """Gets the labels of this Version. # noqa: E501 - - - :return: The labels of this Version. # noqa: E501 - :rtype: dict(str, str) - """ - return self._labels - - @labels.setter - def labels(self, labels): - """Sets the labels of this Version. - - - :param labels: The labels of this Version. # noqa: E501 - :type: dict(str, str) - """ - - self._labels = labels - - @property - def custom_predictor(self): - """Gets the custom_predictor of this Version. # noqa: E501 - - - :return: The custom_predictor of this Version. # noqa: E501 - :rtype: CustomPredictor - """ - return self._custom_predictor - - @custom_predictor.setter - def custom_predictor(self, custom_predictor): - """Sets the custom_predictor of this Version. - - - :param custom_predictor: The custom_predictor of this Version. # noqa: E501 - :type: CustomPredictor - """ - - self._custom_predictor = custom_predictor - - @property - def created_at(self): - """Gets the created_at of this Version. # noqa: E501 - - - :return: The created_at of this Version. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this Version. - - - :param created_at: The created_at of this Version. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this Version. # noqa: E501 - - - :return: The updated_at of this Version. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this Version. - - - :param updated_at: The updated_at of this Version. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - @property - def python_version(self): - """Gets the python_version of this Version. # noqa: E501 - - - :return: The python_version of this Version. # noqa: E501 - :rtype: str - """ - return self._python_version - - @python_version.setter - def python_version(self, python_version): - """Sets the python_version of this Version. - - - :param python_version: The python_version of this Version. # noqa: E501 - :type: str - """ - - self._python_version = python_version - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(Version, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, Version): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of Version from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of each item in endpoints (list) + _items = [] + if self.endpoints: + for _item in self.endpoints: + if _item: + _items.append(_item.to_dict()) + _dict['endpoints'] = _items + # override the default output from pydantic by calling `to_dict()` of custom_predictor + if self.custom_predictor: + _dict['custom_predictor'] = self.custom_predictor.to_dict() + # override the default output from pydantic by calling `to_dict()` of model_schema + if self.model_schema: + _dict['model_schema'] = self.model_schema.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of Version from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "model_id": obj.get("model_id"), + "mlflow_run_id": obj.get("mlflow_run_id"), + "mlflow_url": obj.get("mlflow_url"), + "artifact_uri": obj.get("artifact_uri"), + "endpoints": [VersionEndpoint.from_dict(_item) for _item in obj.get("endpoints")] if obj.get("endpoints") is not None else None, + "properties": obj.get("properties"), + "labels": obj.get("labels"), + "custom_predictor": CustomPredictor.from_dict(obj.get("custom_predictor")) if obj.get("custom_predictor") is not None else None, + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at"), + "python_version": obj.get("python_version"), + "model_schema": ModelSchema.from_dict(obj.get("model_schema")) if obj.get("model_schema") is not None else None + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/models/version_endpoint.py b/python/sdk/client/models/version_endpoint.py index e772ba132..bb3d35f4f 100644 --- a/python/sdk/client/models/version_endpoint.py +++ b/python/sdk/client/models/version_endpoint.py @@ -3,602 +3,157 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" - -import pprint -import re # noqa: F401 + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) -import six + Do not edit the class manually. +""" # noqa: E501 -class VersionEndpoint(object): - """NOTE: This class is auto generated by the swagger code generator program. - Do not edit the class manually. - """ - """ - Attributes: - swagger_types (dict): The key is attribute name - and the value is attribute type. - attribute_map (dict): The key is attribute name - and the value is json key in definition. +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from datetime import datetime +from typing import Any, ClassVar, Dict, List, Optional +from pydantic import BaseModel, StrictBool, StrictInt, StrictStr +from client.models.autoscaling_policy import AutoscalingPolicy +from client.models.deployment_mode import DeploymentMode +from client.models.endpoint_status import EndpointStatus +from client.models.env_var import EnvVar +from client.models.environment import Environment +from client.models.logger import Logger +from client.models.protocol import Protocol +from client.models.resource_request import ResourceRequest +from client.models.transformer import Transformer +try: + from typing import Self +except ImportError: + from typing_extensions import Self + +class VersionEndpoint(BaseModel): """ - swagger_types = { - 'id': 'str', - 'version_id': 'int', - 'status': 'EndpointStatus', - 'url': 'str', - 'service_name': 'str', - 'environment_name': 'str', - 'environment': 'Environment', - 'monitoring_url': 'str', - 'message': 'str', - 'resource_request': 'ResourceRequest', - 'image_builder_resource_request': 'ResourceRequest', - 'env_vars': 'list[EnvVar]', - 'transformer': 'Transformer', - 'logger': 'Logger', - 'deployment_mode': 'DeploymentMode', - 'autoscaling_policy': 'AutoscalingPolicy', - 'protocol': 'Protocol', - 'enable_model_observability': 'bool', - 'created_at': 'datetime', - 'updated_at': 'datetime' + VersionEndpoint + """ # noqa: E501 + id: Optional[StrictStr] = None + version_id: Optional[StrictInt] = None + status: Optional[EndpointStatus] = None + url: Optional[StrictStr] = None + service_name: Optional[StrictStr] = None + environment_name: Optional[StrictStr] = None + environment: Optional[Environment] = None + monitoring_url: Optional[StrictStr] = None + message: Optional[StrictStr] = None + resource_request: Optional[ResourceRequest] = None + image_builder_resource_request: Optional[ResourceRequest] = None + env_vars: Optional[List[EnvVar]] = None + transformer: Optional[Transformer] = None + logger: Optional[Logger] = None + deployment_mode: Optional[DeploymentMode] = None + autoscaling_policy: Optional[AutoscalingPolicy] = None + protocol: Optional[Protocol] = None + enable_model_observability: Optional[StrictBool] = None + created_at: Optional[datetime] = None + updated_at: Optional[datetime] = None + __properties: ClassVar[List[str]] = ["id", "version_id", "status", "url", "service_name", "environment_name", "environment", "monitoring_url", "message", "resource_request", "image_builder_resource_request", "env_vars", "transformer", "logger", "deployment_mode", "autoscaling_policy", "protocol", "enable_model_observability", "created_at", "updated_at"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True } - attribute_map = { - 'id': 'id', - 'version_id': 'version_id', - 'status': 'status', - 'url': 'url', - 'service_name': 'service_name', - 'environment_name': 'environment_name', - 'environment': 'environment', - 'monitoring_url': 'monitoring_url', - 'message': 'message', - 'resource_request': 'resource_request', - 'image_builder_resource_request': 'image_builder_resource_request', - 'env_vars': 'env_vars', - 'transformer': 'transformer', - 'logger': 'logger', - 'deployment_mode': 'deployment_mode', - 'autoscaling_policy': 'autoscaling_policy', - 'protocol': 'protocol', - 'enable_model_observability': 'enable_model_observability', - 'created_at': 'created_at', - 'updated_at': 'updated_at' - } - - def __init__(self, id=None, version_id=None, status=None, url=None, service_name=None, environment_name=None, environment=None, monitoring_url=None, message=None, resource_request=None, image_builder_resource_request=None, env_vars=None, transformer=None, logger=None, deployment_mode=None, autoscaling_policy=None, protocol=None, enable_model_observability=None, created_at=None, updated_at=None): # noqa: E501 - """VersionEndpoint - a model defined in Swagger""" # noqa: E501 - self._id = None - self._version_id = None - self._status = None - self._url = None - self._service_name = None - self._environment_name = None - self._environment = None - self._monitoring_url = None - self._message = None - self._resource_request = None - self._image_builder_resource_request = None - self._env_vars = None - self._transformer = None - self._logger = None - self._deployment_mode = None - self._autoscaling_policy = None - self._protocol = None - self._enable_model_observability = None - self._created_at = None - self._updated_at = None - self.discriminator = None - if id is not None: - self.id = id - if version_id is not None: - self.version_id = version_id - if status is not None: - self.status = status - if url is not None: - self.url = url - if service_name is not None: - self.service_name = service_name - if environment_name is not None: - self.environment_name = environment_name - if environment is not None: - self.environment = environment - if monitoring_url is not None: - self.monitoring_url = monitoring_url - if message is not None: - self.message = message - if resource_request is not None: - self.resource_request = resource_request - if image_builder_resource_request is not None: - self.image_builder_resource_request = image_builder_resource_request - if env_vars is not None: - self.env_vars = env_vars - if transformer is not None: - self.transformer = transformer - if logger is not None: - self.logger = logger - if deployment_mode is not None: - self.deployment_mode = deployment_mode - if autoscaling_policy is not None: - self.autoscaling_policy = autoscaling_policy - if protocol is not None: - self.protocol = protocol - if enable_model_observability is not None: - self.enable_model_observability = enable_model_observability - if created_at is not None: - self.created_at = created_at - if updated_at is not None: - self.updated_at = updated_at - - @property - def id(self): - """Gets the id of this VersionEndpoint. # noqa: E501 - - - :return: The id of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this VersionEndpoint. - - - :param id: The id of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._id = id - - @property - def version_id(self): - """Gets the version_id of this VersionEndpoint. # noqa: E501 - - - :return: The version_id of this VersionEndpoint. # noqa: E501 - :rtype: int - """ - return self._version_id - - @version_id.setter - def version_id(self, version_id): - """Sets the version_id of this VersionEndpoint. - - - :param version_id: The version_id of this VersionEndpoint. # noqa: E501 - :type: int - """ - - self._version_id = version_id - - @property - def status(self): - """Gets the status of this VersionEndpoint. # noqa: E501 - - - :return: The status of this VersionEndpoint. # noqa: E501 - :rtype: EndpointStatus - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this VersionEndpoint. - - - :param status: The status of this VersionEndpoint. # noqa: E501 - :type: EndpointStatus - """ - - self._status = status - - @property - def url(self): - """Gets the url of this VersionEndpoint. # noqa: E501 - - - :return: The url of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._url - - @url.setter - def url(self, url): - """Sets the url of this VersionEndpoint. - - - :param url: The url of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._url = url - - @property - def service_name(self): - """Gets the service_name of this VersionEndpoint. # noqa: E501 - - - :return: The service_name of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._service_name - - @service_name.setter - def service_name(self, service_name): - """Sets the service_name of this VersionEndpoint. - - - :param service_name: The service_name of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._service_name = service_name - - @property - def environment_name(self): - """Gets the environment_name of this VersionEndpoint. # noqa: E501 - - - :return: The environment_name of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._environment_name - - @environment_name.setter - def environment_name(self, environment_name): - """Sets the environment_name of this VersionEndpoint. - - - :param environment_name: The environment_name of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._environment_name = environment_name - - @property - def environment(self): - """Gets the environment of this VersionEndpoint. # noqa: E501 - - - :return: The environment of this VersionEndpoint. # noqa: E501 - :rtype: Environment - """ - return self._environment - - @environment.setter - def environment(self, environment): - """Sets the environment of this VersionEndpoint. - - - :param environment: The environment of this VersionEndpoint. # noqa: E501 - :type: Environment - """ - - self._environment = environment - - @property - def monitoring_url(self): - """Gets the monitoring_url of this VersionEndpoint. # noqa: E501 - - - :return: The monitoring_url of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._monitoring_url - - @monitoring_url.setter - def monitoring_url(self, monitoring_url): - """Sets the monitoring_url of this VersionEndpoint. - - - :param monitoring_url: The monitoring_url of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._monitoring_url = monitoring_url - - @property - def message(self): - """Gets the message of this VersionEndpoint. # noqa: E501 - - - :return: The message of this VersionEndpoint. # noqa: E501 - :rtype: str - """ - return self._message - - @message.setter - def message(self, message): - """Sets the message of this VersionEndpoint. - - - :param message: The message of this VersionEndpoint. # noqa: E501 - :type: str - """ - - self._message = message - - @property - def resource_request(self): - """Gets the resource_request of this VersionEndpoint. # noqa: E501 - - - :return: The resource_request of this VersionEndpoint. # noqa: E501 - :rtype: ResourceRequest - """ - return self._resource_request - - @resource_request.setter - def resource_request(self, resource_request): - """Sets the resource_request of this VersionEndpoint. - - - :param resource_request: The resource_request of this VersionEndpoint. # noqa: E501 - :type: ResourceRequest - """ - - self._resource_request = resource_request - - @property - def image_builder_resource_request(self): - """Gets the image_builder_resource_request of this VersionEndpoint. # noqa: E501 - - - :return: The image_builder_resource_request of this VersionEndpoint. # noqa: E501 - :rtype: ResourceRequest - """ - return self._image_builder_resource_request - - @image_builder_resource_request.setter - def image_builder_resource_request(self, image_builder_resource_request): - """Sets the image_builder_resource_request of this VersionEndpoint. - - - :param image_builder_resource_request: The image_builder_resource_request of this VersionEndpoint. # noqa: E501 - :type: ResourceRequest - """ - - self._image_builder_resource_request = image_builder_resource_request - - @property - def env_vars(self): - """Gets the env_vars of this VersionEndpoint. # noqa: E501 - - - :return: The env_vars of this VersionEndpoint. # noqa: E501 - :rtype: list[EnvVar] - """ - return self._env_vars - - @env_vars.setter - def env_vars(self, env_vars): - """Sets the env_vars of this VersionEndpoint. - - - :param env_vars: The env_vars of this VersionEndpoint. # noqa: E501 - :type: list[EnvVar] - """ - - self._env_vars = env_vars - - @property - def transformer(self): - """Gets the transformer of this VersionEndpoint. # noqa: E501 - - - :return: The transformer of this VersionEndpoint. # noqa: E501 - :rtype: Transformer - """ - return self._transformer - - @transformer.setter - def transformer(self, transformer): - """Sets the transformer of this VersionEndpoint. - - - :param transformer: The transformer of this VersionEndpoint. # noqa: E501 - :type: Transformer - """ - - self._transformer = transformer - - @property - def logger(self): - """Gets the logger of this VersionEndpoint. # noqa: E501 - - - :return: The logger of this VersionEndpoint. # noqa: E501 - :rtype: Logger - """ - return self._logger - - @logger.setter - def logger(self, logger): - """Sets the logger of this VersionEndpoint. - - - :param logger: The logger of this VersionEndpoint. # noqa: E501 - :type: Logger - """ - - self._logger = logger - - @property - def deployment_mode(self): - """Gets the deployment_mode of this VersionEndpoint. # noqa: E501 - - - :return: The deployment_mode of this VersionEndpoint. # noqa: E501 - :rtype: DeploymentMode - """ - return self._deployment_mode - - @deployment_mode.setter - def deployment_mode(self, deployment_mode): - """Sets the deployment_mode of this VersionEndpoint. - - - :param deployment_mode: The deployment_mode of this VersionEndpoint. # noqa: E501 - :type: DeploymentMode - """ - - self._deployment_mode = deployment_mode - - @property - def autoscaling_policy(self): - """Gets the autoscaling_policy of this VersionEndpoint. # noqa: E501 - - - :return: The autoscaling_policy of this VersionEndpoint. # noqa: E501 - :rtype: AutoscalingPolicy - """ - return self._autoscaling_policy - - @autoscaling_policy.setter - def autoscaling_policy(self, autoscaling_policy): - """Sets the autoscaling_policy of this VersionEndpoint. - - - :param autoscaling_policy: The autoscaling_policy of this VersionEndpoint. # noqa: E501 - :type: AutoscalingPolicy - """ - - self._autoscaling_policy = autoscaling_policy - - @property - def protocol(self): - """Gets the protocol of this VersionEndpoint. # noqa: E501 - - - :return: The protocol of this VersionEndpoint. # noqa: E501 - :rtype: Protocol - """ - return self._protocol - - @protocol.setter - def protocol(self, protocol): - """Sets the protocol of this VersionEndpoint. - - - :param protocol: The protocol of this VersionEndpoint. # noqa: E501 - :type: Protocol - """ - - self._protocol = protocol - - @property - def enable_model_observability(self): - """Gets the enable_model_observability of this VersionEndpoint. # noqa: E501 - - - :return: The enable_model_observability of this VersionEndpoint. # noqa: E501 - :rtype: bool - """ - return self._enable_model_observability - - @enable_model_observability.setter - def enable_model_observability(self, enable_model_observability): - """Sets the enable_model_observability of this VersionEndpoint. - - - :param enable_model_observability: The enable_model_observability of this VersionEndpoint. # noqa: E501 - :type: bool - """ - - self._enable_model_observability = enable_model_observability - - @property - def created_at(self): - """Gets the created_at of this VersionEndpoint. # noqa: E501 - - - :return: The created_at of this VersionEndpoint. # noqa: E501 - :rtype: datetime - """ - return self._created_at - - @created_at.setter - def created_at(self, created_at): - """Sets the created_at of this VersionEndpoint. - - - :param created_at: The created_at of this VersionEndpoint. # noqa: E501 - :type: datetime - """ - - self._created_at = created_at - - @property - def updated_at(self): - """Gets the updated_at of this VersionEndpoint. # noqa: E501 - - - :return: The updated_at of this VersionEndpoint. # noqa: E501 - :rtype: datetime - """ - return self._updated_at - - @updated_at.setter - def updated_at(self, updated_at): - """Sets the updated_at of this VersionEndpoint. - - - :param updated_at: The updated_at of this VersionEndpoint. # noqa: E501 - :type: datetime - """ - - self._updated_at = updated_at - - def to_dict(self): - """Returns the model properties as a dict""" - result = {} - - for attr, _ in six.iteritems(self.swagger_types): - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - if issubclass(VersionEndpoint, dict): - for key, value in self.items(): - result[key] = value - - return result - - def to_str(self): - """Returns the string representation of the model""" - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - def __eq__(self, other): - """Returns true if both objects are equal""" - if not isinstance(other, VersionEndpoint): - return False + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Self: + """Create an instance of VersionEndpoint from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + _dict = self.model_dump( + by_alias=True, + exclude={ + }, + exclude_none=True, + ) + # override the default output from pydantic by calling `to_dict()` of environment + if self.environment: + _dict['environment'] = self.environment.to_dict() + # override the default output from pydantic by calling `to_dict()` of resource_request + if self.resource_request: + _dict['resource_request'] = self.resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of image_builder_resource_request + if self.image_builder_resource_request: + _dict['image_builder_resource_request'] = self.image_builder_resource_request.to_dict() + # override the default output from pydantic by calling `to_dict()` of each item in env_vars (list) + _items = [] + if self.env_vars: + for _item in self.env_vars: + if _item: + _items.append(_item.to_dict()) + _dict['env_vars'] = _items + # override the default output from pydantic by calling `to_dict()` of transformer + if self.transformer: + _dict['transformer'] = self.transformer.to_dict() + # override the default output from pydantic by calling `to_dict()` of logger + if self.logger: + _dict['logger'] = self.logger.to_dict() + # override the default output from pydantic by calling `to_dict()` of autoscaling_policy + if self.autoscaling_policy: + _dict['autoscaling_policy'] = self.autoscaling_policy.to_dict() + return _dict + + @classmethod + def from_dict(cls, obj: Dict) -> Self: + """Create an instance of VersionEndpoint from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "id": obj.get("id"), + "version_id": obj.get("version_id"), + "status": obj.get("status"), + "url": obj.get("url"), + "service_name": obj.get("service_name"), + "environment_name": obj.get("environment_name"), + "environment": Environment.from_dict(obj.get("environment")) if obj.get("environment") is not None else None, + "monitoring_url": obj.get("monitoring_url"), + "message": obj.get("message"), + "resource_request": ResourceRequest.from_dict(obj.get("resource_request")) if obj.get("resource_request") is not None else None, + "image_builder_resource_request": ResourceRequest.from_dict(obj.get("image_builder_resource_request")) if obj.get("image_builder_resource_request") is not None else None, + "env_vars": [EnvVar.from_dict(_item) for _item in obj.get("env_vars")] if obj.get("env_vars") is not None else None, + "transformer": Transformer.from_dict(obj.get("transformer")) if obj.get("transformer") is not None else None, + "logger": Logger.from_dict(obj.get("logger")) if obj.get("logger") is not None else None, + "deployment_mode": obj.get("deployment_mode"), + "autoscaling_policy": AutoscalingPolicy.from_dict(obj.get("autoscaling_policy")) if obj.get("autoscaling_policy") is not None else None, + "protocol": obj.get("protocol"), + "enable_model_observability": obj.get("enable_model_observability"), + "created_at": obj.get("created_at"), + "updated_at": obj.get("updated_at") + }) + return _obj - return self.__dict__ == other.__dict__ - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/python/sdk/client/rest.py b/python/sdk/client/rest.py index 64931ed89..803a97dfb 100644 --- a/python/sdk/client/rest.py +++ b/python/sdk/client/rest.py @@ -3,59 +3,54 @@ """ Merlin - API Guide for accessing Merlin's model management, deployment, and serving functionalities # noqa: E501 + API Guide for accessing Merlin's model management, deployment, and serving functionalities - OpenAPI spec version: 0.14.0 - - Generated by: https://github.com/swagger-api/swagger-codegen.git -""" + The version of the OpenAPI document: 0.14.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 -from __future__ import absolute_import import io import json -import logging import re import ssl -import certifi -# python 2 and python 3 compatibility library -import six -from six.moves.urllib.parse import urlencode - -try: - import urllib3 -except ImportError: - raise ImportError('Swagger python client requires urllib3.') - +import urllib3 -logger = logging.getLogger(__name__) +from client.exceptions import ApiException, ApiValueError +RESTResponseType = urllib3.HTTPResponse class RESTResponse(io.IOBase): - def __init__(self, resp): - self.urllib3_response = resp + def __init__(self, resp) -> None: + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.getheaders() + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.urllib3_response.getheader(name, default) + return self.response.headers.get(name, default) -class RESTClientObject(object): +class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None): + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs @@ -64,73 +59,78 @@ def __init__(self, configuration, pools_size=4, maxsize=None): else: cert_reqs = ssl.CERT_NONE - # ca_certs - if configuration.ssl_ca_cert: - ca_certs = configuration.ssl_ca_cert - else: - # if not set certificate file, use Mozilla's root certificates. - ca_certs = certifi.where() - addition_pool_args = {} if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + addition_pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 + if configuration.retries is not None: + addition_pool_args['retries'] = configuration.retries + + if configuration.tls_server_name: + addition_pool_args['server_hostname'] = configuration.tls_server_name + + + if configuration.socket_options is not None: + addition_pool_args['socket_options'] = configuration.socket_options # https pool manager if configuration.proxy: self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=ca_certs, + ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, **addition_pool_args ) else: self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, cert_reqs=cert_reqs, - ca_certs=ca_certs, + ca_certs=configuration.ssl_ca_cert, cert_file=configuration.cert_file, key_file=configuration.key_file, **addition_pool_args ) - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: - raise ValueError( + raise ApiValueError( "body parameter cannot be used with post_params parameter." ) @@ -139,62 +139,75 @@ def request(self, method, url, query_params=None, headers=None, timeout = None if _request_timeout: - if isinstance(_request_timeout, (int, ) if six.PY3 else (int, long)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) - - if 'Content-Type' not in headers: - headers['Content-Type'] = 'application/json' + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: - if query_params: - url += '?' + urlencode(query_params) - if re.search('json', headers['Content-Type'], re.IGNORECASE): - request_body = '{}' + + # no content type provided or payload is json + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): + request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) # Pass a `string` parameter directly in the body to support # other content types than Json when `body` argument is # provided in serialized form - elif isinstance(body, str): + elif isinstance(body, str) or isinstance(body, bytes): request_body = body r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) else: # Cannot generate the request from given parameters msg = """Cannot prepare a request message for provided @@ -203,115 +216,16 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields=query_params, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) + msg = "\n".join([type(e).__name__, str(e)]) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - -class ApiException(Exception): - - def __init__(self, status=None, reason=None, http_resp=None): - if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data - self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None - - def __str__(self): - """Custom error messages for exception""" - error_message = "({0})\n"\ - "Reason: {1}\n".format(self.status, self.reason) - if self.headers: - error_message += "HTTP response headers: {0}\n".format( - self.headers) - - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) - - return error_message + return RESTResponse(r) diff --git a/python/sdk/merlin/batch/job.py b/python/sdk/merlin/batch/job.py index a4f2e91e0..68324c405 100644 --- a/python/sdk/merlin/batch/job.py +++ b/python/sdk/merlin/batch/job.py @@ -14,6 +14,7 @@ import client from enum import Enum +from typing import Optional from merlin.util import autostr @@ -40,7 +41,7 @@ def __init__(self, job: client.PredictionJob, api_client: client.ApiClient): self._error = job.error @property - def id(self) -> int: + def id(self) -> Optional[int]: """ ID of prediction job @@ -49,7 +50,7 @@ def id(self) -> int: return self._id @property - def name(self) -> str: + def name(self) -> Optional[str]: """ Prediction job name @@ -67,7 +68,7 @@ def status(self) -> JobStatus: return JobStatus(self._status) @property - def error(self) -> str: + def error(self) -> Optional[str]: """ Error message containing the reason of failed job diff --git a/python/sdk/merlin/batch/sink.py b/python/sdk/merlin/batch/sink.py index 5e0a5778a..d9b547bb5 100644 --- a/python/sdk/merlin/batch/sink.py +++ b/python/sdk/merlin/batch/sink.py @@ -16,6 +16,7 @@ from enum import Enum from typing import MutableMapping, Mapping, Any, Optional +import client from merlin.batch.big_query_util import valid_table_id, valid_column @@ -132,3 +133,17 @@ def to_dict(self) -> Mapping[str, Any]: 'save_mode': self._save_mode.value, 'options': opts } + + def to_client_config(self) -> client.PredictionJobConfigBigquerySink: + opts = {} + if self.options is not None: + for k, v in self.options.items(): + opts[k] = v + + return client.PredictionJobConfigBigquerySink( + table=self._table, + staging_bucket=self._staging_bucket, + result_column=self._result_column, + save_mode=client.SaveMode(self._save_mode.value), + options=opts + ) \ No newline at end of file diff --git a/python/sdk/merlin/batch/source.py b/python/sdk/merlin/batch/source.py index 92c7b84da..0dca68831 100644 --- a/python/sdk/merlin/batch/source.py +++ b/python/sdk/merlin/batch/source.py @@ -15,7 +15,7 @@ from abc import ABC, abstractmethod from typing import Iterable, MutableMapping, Mapping, Any, Optional from merlin.batch.big_query_util import valid_table_id, valid_columns - +import client class Source(ABC): @abstractmethod @@ -98,3 +98,15 @@ def to_dict(self) -> Mapping[str, Any]: 'features': self._features, 'options': opts } + + def to_client_bq_source(self) -> client.PredictionJobConfigBigquerySource: + opts = {} + if self.options is not None: + for k, v in self.options.items(): + opts[k] = v + + return client.PredictionJobConfigBigquerySource( + table=self._table, + features=list(self._features), + options=opts + ) diff --git a/python/sdk/merlin/client.py b/python/sdk/merlin/client.py index 0a5c24952..5dd0ca59e 100644 --- a/python/sdk/merlin/client.py +++ b/python/sdk/merlin/client.py @@ -23,13 +23,14 @@ Configuration, EndpointApi, EnvironmentApi, - FreeFormObject, ModelsApi, ProjectApi, StandardTransformerApi, StandardTransformerSimulationRequest, VersionApi, ) + +import client from google.auth.transport.requests import Request from google.auth.transport.urllib3 import AuthorizedHttp from merlin.autoscaling import AutoscalingPolicy @@ -43,6 +44,7 @@ from merlin.transformer import Transformer from merlin.util import valid_name_check from merlin.version import VERSION +from merlin.model_schema import ModelSchema class MerlinClient: @@ -94,7 +96,7 @@ def get_environment(self, env_name: str) -> Optional[Environment]: env_list = self._env_api.environments_get() for env in env_list: if env.name == env_name: - return env + return Environment(env) return None def get_default_environment(self) -> Optional[Environment]: @@ -212,7 +214,7 @@ def get_or_create_model( m_list = self._model_api.projects_project_id_models_get( project_id=int(prj.id), name=model_name ) - + model = None for mdl in m_list: if mdl.name == model_name: @@ -226,13 +228,13 @@ def get_or_create_model( ) model = self._model_api.projects_project_id_models_post( project_id=int(prj.id), - body={"name": model_name, "type": model_type.value}, + body=client.Model(name=model_name, type=model_type.value) ) return Model(model, prj, self._api_client) def new_model_version( - self, model_name: str, project_name: str, labels: Dict[str, str] = None + self, model_name: str, project_name: str, labels: Dict[str, str] = None, model_schema: Optional[ModelSchema] = None ) -> ModelVersion: """ Create new model version for the given model and project @@ -245,7 +247,7 @@ def new_model_version( mdl = self.get_model(model_name, project_name) if mdl is None: raise ValueError(f"Model with name: {model_name} is not found") - return mdl.new_model_version(labels=labels) + return mdl.new_model_version(labels=labels, model_schema=model_schema) def deploy( self, @@ -285,14 +287,15 @@ def standard_transformer_simulate( model_prediction_config: Dict = None, protocol: str = "HTTP_JSON", ): + prediction_config = client.ModelPredictionConfig.from_dict(model_prediction_config) if model_prediction_config is not None else None request = StandardTransformerSimulationRequest( payload=payload, headers=headers, config=config, - model_prediction_config=model_prediction_config, - protocol=protocol, + model_prediction_config=prediction_config, + protocol=client.Protocol(protocol), ) return self._standard_transformer_api.standard_transformer_simulate_post( - body=request.to_dict() + body=request ) diff --git a/python/sdk/merlin/endpoint.py b/python/sdk/merlin/endpoint.py index a523f67d0..cf4aef9cf 100644 --- a/python/sdk/merlin/endpoint.py +++ b/python/sdk/merlin/endpoint.py @@ -13,7 +13,7 @@ # limitations under the License. from enum import Enum -from typing import Dict +from typing import Dict, Optional import client from merlin.autoscaling import (RAW_DEPLOYMENT_DEFAULT_AUTOSCALING_POLICY, @@ -25,8 +25,8 @@ from merlin.protocol import Protocol from merlin.util import autostr, get_url from merlin.resource_request import ResourceRequest -from merlin.transformer import Transformer - +from merlin.transformer import Transformer, TransformerType +from merlin.util import extract_optional_value_with_default class Status(Enum): PENDING = 'pending' @@ -44,16 +44,16 @@ def __init__(self, endpoint: client.VersionEndpoint, log_url: str = None): self._protocol = Protocol(endpoint.protocol) self._url = endpoint.url - if self._protocol == Protocol.HTTP_JSON and ":predict" not in endpoint.url: + if self._protocol == Protocol.HTTP_JSON and endpoint.url is not None and ":predict" not in endpoint.url: self._url = f"{endpoint.url}:predict" self._status = Status(endpoint.status) self._id = endpoint.id self._environment_name = endpoint.environment_name - self._environment = Environment(endpoint.environment) + self._environment = Environment(endpoint.environment) if endpoint.environment is not None else None self._env_vars = endpoint.env_vars self._logger = Logger.from_logger_response(endpoint.logger) - self._resource_request = endpoint.resource_request + self._resource_request = ResourceRequest.from_response(endpoint.resource_request) if endpoint.resource_request is not None else None self._deployment_mode = DeploymentMode.SERVERLESS if not endpoint.deployment_mode \ else DeploymentMode(endpoint.deployment_mode) @@ -66,18 +66,42 @@ def __init__(self, endpoint: client.VersionEndpoint, log_url: str = None): self._autoscaling_policy = AutoscalingPolicy(metrics_type=MetricsType(endpoint.autoscaling_policy.metrics_type), target_value=endpoint.autoscaling_policy.target_value) - if endpoint.transformer is not None: + transformer = endpoint.transformer + if transformer is not None: + image = transformer.image if transformer.image is not None else "" + transformer_type_value = extract_optional_value_with_default(transformer.transformer_type, TransformerType.STANDARD_TRANSFORMER.value) + transformer_type = TransformerType(transformer_type_value) + + transformer_request = None + if transformer.resource_request is not None: + transformer_request = ResourceRequest( + min_replica=transformer.resource_request.min_replica, + max_replica=transformer.resource_request.max_replica, + cpu_request=transformer.resource_request.cpu_request, + memory_request=transformer.resource_request.memory_request + ) + + env_vars: Dict[str, str] = {} + if transformer.env_vars is not None: + for env_var in transformer.env_vars: + if env_var.name is not None and env_var.value is not None: + env_vars[env_var.name] = env_var.value + self._transformer = Transformer( - endpoint.transformer.image, id=endpoint.transformer.id, - enabled=endpoint.transformer.enabled, command=endpoint.transformer.command, - args=endpoint.transformer.args, transformer_type=endpoint.transformer.transformer_type, - resource_request=endpoint.transformer.resource_request, env_vars=endpoint.transformer.env_vars, + image, + id=extract_optional_value_with_default(transformer.id, ""), + enabled=extract_optional_value_with_default(transformer.enabled, False), + command=transformer.command, + args=transformer.args, + transformer_type=transformer_type, + resource_request=transformer_request, + env_vars=env_vars, ) if log_url is not None: self._log_url = log_url - self._enable_model_observability = endpoint.enable_model_observability + self._enable_model_observability = extract_optional_value_with_default(endpoint.enable_model_observability, False) @property def url(self): @@ -88,15 +112,15 @@ def status(self) -> Status: return self._status @property - def id(self) -> str: + def id(self) -> Optional[str]: return self._id @property - def environment_name(self) -> str: + def environment_name(self) -> Optional[str]: return self._environment_name @property - def environment(self) -> Environment: + def environment(self) -> Optional[Environment]: return self._environment @property @@ -104,7 +128,8 @@ def env_vars(self) -> Dict[str, str]: env_vars = {} if self._env_vars: for ev in self._env_vars: - env_vars[ev.name] = ev.value + if ev.name is not None and ev.value is not None: + env_vars[ev.name] = ev.value return env_vars @property @@ -128,7 +153,7 @@ def protocol(self) -> Protocol: return self._protocol @property - def resource_request(self) -> ResourceRequest: + def resource_request(self) -> Optional[ResourceRequest]: return self._resource_request @property @@ -147,7 +172,7 @@ def _repr_html_(self): class ModelEndpoint: def __init__(self, endpoint: client.ModelEndpoint): self._protocol = Protocol.HTTP_JSON - if endpoint.protocol: + if endpoint.protocol is not None: self._protocol = Protocol(endpoint.protocol) if self._protocol == Protocol.HTTP_JSON: @@ -155,9 +180,9 @@ def __init__(self, endpoint: client.ModelEndpoint): else: self._url = endpoint.url self._status = Status(endpoint.status) - self._id = endpoint.id + self._id = extract_optional_value_with_default(endpoint.id, 0) self._environment_name = endpoint.environment_name - self._environment = Environment(endpoint.environment) + self._environment = Environment(endpoint.environment) if endpoint.environment is not None else None @property @@ -169,15 +194,15 @@ def status(self) -> Status: return self._status @property - def id(self) -> str: - return str(self._id) + def id(self) -> int: + return self._id @property - def environment_name(self) -> str: + def environment_name(self) -> Optional[str]: return self._environment_name @property - def environment(self) -> Environment: + def environment(self) -> Optional[Environment]: return self._environment @property diff --git a/python/sdk/merlin/environment.py b/python/sdk/merlin/environment.py index 8defb2cfd..6374ac1b5 100644 --- a/python/sdk/merlin/environment.py +++ b/python/sdk/merlin/environment.py @@ -13,19 +13,21 @@ # limitations under the License. import client +from typing import Optional from merlin.resource_request import ResourceRequest - class Environment: def __init__(self, env: client.Environment): self._name = env.name self._cluster = env.cluster - self._is_default = env.is_default - self._default_resource_request = ResourceRequest(env.default_resource_request.min_replica, - env.default_resource_request.max_replica, - env.default_resource_request.cpu_request, - env.default_resource_request.memory_request) + self._is_default = env.is_default if env.is_default is not None else False + self._default_resource_request = None + if env.default_resource_request is not None: + self._default_resource_request = ResourceRequest(env.default_resource_request.min_replica, + env.default_resource_request.max_replica, + env.default_resource_request.cpu_request, + env.default_resource_request.memory_request) @property def name(self) -> str: @@ -40,5 +42,5 @@ def is_default(self) -> bool: return self._is_default @property - def default_resource_request(self) -> ResourceRequest: + def default_resource_request(self) -> Optional[ResourceRequest]: return self._default_resource_request diff --git a/python/sdk/merlin/fluent.py b/python/sdk/merlin/fluent.py index 004ae88d8..ce175c310 100644 --- a/python/sdk/merlin/fluent.py +++ b/python/sdk/merlin/fluent.py @@ -28,6 +28,7 @@ from merlin.protocol import Protocol from merlin.resource_request import ResourceRequest from merlin.transformer import Transformer +from merlin.model_schema import ModelSchema _merlin_client: Optional[MerlinClient] = None _active_project: Optional[Project] @@ -155,7 +156,7 @@ def active_model() -> Optional[Model]: @contextmanager -def new_model_version(labels: Dict[str, str] = None): +def new_model_version(labels: Dict[str, str] = None, model_schema: Optional[ModelSchema] = None): """ Create new model version under currently active model @@ -167,7 +168,7 @@ def new_model_version(labels: Dict[str, str] = None): _check_active_client() _check_active_project() _check_active_model() - v = _merlin_client.new_model_version(_active_model.name, _active_project.name, labels) # type: ignore + v = _merlin_client.new_model_version(_active_model.name, _active_project.name, labels, model_schema) # type: ignore v.start() global _active_model_version _active_model_version = v diff --git a/python/sdk/merlin/logger.py b/python/sdk/merlin/logger.py index 16001f450..265810e05 100644 --- a/python/sdk/merlin/logger.py +++ b/python/sdk/merlin/logger.py @@ -77,7 +77,7 @@ def __init__(self, model: LoggerConfig = None, transformer: LoggerConfig = None, self._prediction = prediction @classmethod - def from_logger_response(cls, response: client.Logger): + def from_logger_response(cls, response: Optional[client.Logger]): if response is None: return Logger() model_config = None @@ -88,10 +88,13 @@ def from_logger_response(cls, response: client.Logger): transformer_config = LoggerConfig(enabled=response.transformer.enabled, mode=cls._get_logger_mode_from_api_response(response.transformer.mode)) prediction_config = None - if response.prediction is not None: - prediction_config = PredictionLoggerConfig(enabled=response.prediction.enabled, - raw_features_table=response.prediction.raw_features_table, - entities_table=response.prediction.entities_table) + prediction_logger = response.prediction + if prediction_logger is not None: + raw_features_table = prediction_logger.raw_features_table if prediction_logger.raw_features_table is not None else "" + entities_table = prediction_logger.entities_table if prediction_logger.entities_table is not None else "" + prediction_config = PredictionLoggerConfig(enabled=prediction_logger.enabled, + raw_features_table=raw_features_table, + entities_table=entities_table) return Logger(model=model_config, transformer=transformer_config, prediction=prediction_config) diff --git a/python/sdk/merlin/model.py b/python/sdk/merlin/model.py index 357440d41..7a9924743 100644 --- a/python/sdk/merlin/model.py +++ b/python/sdk/merlin/model.py @@ -67,6 +67,9 @@ from mlflow.entities import Run, RunData from mlflow.exceptions import MlflowException from mlflow.pyfunc import PythonModel +from merlin.version import VERSION +from merlin.model_schema import ModelSchema +from merlin.util import extract_optional_value_with_default # Ensure backward compatibility after moving PyFuncModel and PyFuncV2Model to pyfunc.py # This allows users to do following import statement @@ -119,8 +122,8 @@ def __init__( self._updated_at = project.updated_at self._url = mlp_url self._api_client = api_client - self._readers = project.readers - self._administrators = project.administrators + self._readers = extract_optional_value_with_default(project.readers, []) + self._administrators = extract_optional_value_with_default(project.administrators, []) @property def id(self) -> int: @@ -131,7 +134,7 @@ def name(self) -> str: return self._name @property - def mlflow_tracking_url(self) -> str: + def mlflow_tracking_url(self) -> Optional[str]: return self._mlflow_tracking_url @property @@ -143,11 +146,11 @@ def administrators(self) -> List[str]: return self._administrators @property - def created_at(self) -> datetime: + def created_at(self) -> Optional[datetime]: return self._created_at @property - def updated_at(self) -> datetime: + def updated_at(self) -> Optional[datetime]: return self._updated_at @property @@ -200,7 +203,7 @@ def get_or_create_model( ) model = model_api.projects_project_id_models_post( project_id=int(self.id), - body={"name": model_name, "type": model_type.value}, + body=client.Model(name=model_name, type=model_type.value), ) else: model = m_list[0] @@ -217,7 +220,7 @@ def create_secret(self, name: str, data: str): """ secret_api = SecretApi(self._api_client) secret_api.projects_project_id_secrets_post( - project_id=int(self.id), body={"name": name, "data": data} + project_id=int(self.id), body=client.Secret(name=name, data=data) ) def list_secret(self) -> List[str]: @@ -230,7 +233,8 @@ def list_secret(self) -> List[str]: secrets = secret_api.projects_project_id_secrets_get(project_id=int(self.id)) secret_names = [] for s in secrets: - secret_names.append(s.name) + if s.name is not None: + secret_names.append(s.name) return secret_names def update_secret(self, name: str, data: str): @@ -247,7 +251,7 @@ def update_secret(self, name: str, data: str): secret_api.projects_project_id_secrets_secret_id_patch( project_id=int(self.id), secret_id=int(match.id), - body={"name": name, "data": data}, + body=client.Secret(name=name, data=data), ) def delete_secret(self, name: str): @@ -301,7 +305,7 @@ class Model: def __init__( self, model: client.Model, project: Project, api_client: client.ApiClient ): - self._id = model.id + self._id = extract_optional_value_with_default(model.id, 0) self._name = model.name self._mlflow_experiment_id = model.mlflow_experiment_id self._type = ModelType(model.type) @@ -324,19 +328,20 @@ def type(self) -> ModelType: return self._type @property - def mlflow_url(self) -> str: + def mlflow_url(self) -> Optional[str]: return self._mlflow_url @property - def mlflow_experiment_id(self) -> int: - return int(self._mlflow_experiment_id) - + def mlflow_experiment_id(self) -> Optional[int]: + if self._mlflow_experiment_id is not None: + return int(self._mlflow_experiment_id) + return None @property - def created_at(self) -> datetime: + def created_at(self) -> Optional[datetime]: return self._created_at @property - def updated_at(self) -> datetime: + def updated_at(self) -> Optional[datetime]: return self._updated_at @property @@ -355,7 +360,7 @@ def endpoint(self) -> Optional[ModelEndpoint]: model_id=self.id ) for endpoint in mdl_endpoints_list: - if endpoint.environment.is_default: + if endpoint.environment is not None and endpoint.environment.is_default: return ModelEndpoint(endpoint) return None @@ -430,20 +435,19 @@ def _list_version_pagination( :return: next cursor to fetch next page of version """ version_api = VersionApi(self._api_client) - ( - versions, - _, - headers, - ) = version_api.models_model_id_versions_get_with_http_info( + version_api_response = version_api.models_model_id_versions_get_with_http_info( int(self.id), limit=limit, cursor=cursor, search=search ) + versions = version_api_response.data + headers = extract_optional_value_with_default(version_api_response.headers, {}) + next_cursor = headers.get("Next-Cursor") or "" result = [] for v in versions: result.append(ModelVersion(v, self, self._api_client)) return result, next_cursor - def new_model_version(self, labels: Dict[str, str] = None) -> "ModelVersion": + def new_model_version(self, labels: Dict[str, str] = None, model_schema: Optional[ModelSchema] = None) -> "ModelVersion": """ Create a new version of this model @@ -452,8 +456,12 @@ def new_model_version(self, labels: Dict[str, str] = None) -> "ModelVersion": """ version_api = VersionApi(self._api_client) python_version = f"{version_info.major}.{version_info.minor}.*" # capture user's python version + model_schema_payload = None + if model_schema is not None: + model_schema.model_id = self.id + model_schema_payload = model_schema.to_client_model_schema() v = version_api.models_model_id_versions_post( - int(self.id), body={"labels": labels, "python_version": python_version} + int(self.id), body=client.Version(labels=labels, python_version=python_version, model_schema=model_schema_payload) ) return ModelVersion(v, self, self._api_client) @@ -515,19 +523,21 @@ def serve_traffic( model_id=self.id, environment_name=target_env, rule=rule ) ep = mdl_epi_api.models_model_id_endpoints_post( - model_id=self.id, body=ep.to_dict() + model_id=self.id, body=ep ) - else: + elif prev_endpoint.id is not None: # update: GET and PUT ep = mdl_epi_api.models_model_id_endpoints_model_endpoint_id_get( model_id=self.id, model_endpoint_id=prev_endpoint.id ) - ep.rule.destinations[0].version_endpoint_id = version_endpoint.id - ep.rule.destinations[0].weight = 100 + if ep.rule is not None and ep.rule.destinations is not None and len(ep.rule.destinations) > 0: + ep.rule.destinations[0].version_endpoint_id = version_endpoint.id + ep.rule.destinations[0].weight = 100 + ep = mdl_epi_api.models_model_id_endpoints_model_endpoint_id_put( model_id=int(self.id), model_endpoint_id=prev_endpoint.id, - body=ep.to_dict(), + body=ep, ) return ModelEndpoint(ep) @@ -570,6 +580,10 @@ def stop_serving_traffic(self, environment_name: str = None): f"Stopping serving traffic for model {self.name} " f"in {target_env} environment" ) + if target_endpoint.id is None: + raise ValueError( + f"model endpoint doesn't have id information" + ) mdl_epi_api.models_model_id_endpoints_model_endpoint_id_delete( self.id, target_endpoint.id ) @@ -623,17 +637,17 @@ def set_traffic(self, traffic_rule: Dict["ModelVersion", int]) -> ModelEndpoint: if self.endpoint is None: # create model endpoint ep = model_endpoint_api.models_model_id_endpoints_post( - body={ - "model_id": self.id, - "rule": { - "destinations": [ - { - "version_endpoint_id": def_version_endpoint.id, - "weight": 100, - } + body=client.ModelEndpoint( + model_id=self.id, + rule=client.ModelEndpointRule( + destinations=[ + client.ModelEndpointRuleDestination( + version_endpoint_id=def_version_endpoint.id, + weight=100, + ) ] - }, - }, + ) + ), model_id=int(self.id), ) return ModelEndpoint(ep) @@ -643,12 +657,14 @@ def set_traffic(self, traffic_rule: Dict["ModelVersion", int]) -> ModelEndpoint: ep = model_endpoint_api.models_model_id_endpoints_model_endpoint_id_get( model_id=int(self.id), model_endpoint_id=def_model_endpoint.id ) - ep.rule.destinations[0].version_endpoint_id = def_version_endpoint.id - ep.rule.destinations[0].weight = 100 + if ep.rule is not None and ep.rule.destinations is not None and len(ep.rule.destinations) > 0: + ep.rule.destinations[0].version_endpoint_id = def_version_endpoint.id + ep.rule.destinations[0].weight = 100 + ep = model_endpoint_api.models_model_id_endpoints_model_endpoint_id_put( model_id=int(self.id), model_endpoint_id=def_model_endpoint.id, - body=ep.to_dict(), + body=ep, ) return ModelEndpoint(ep) @@ -683,10 +699,9 @@ def __init__( self, version: client.Version, model: Model, api_client: client.ApiClient ): self._api_client = api_client - self._id = version.id + self._id = extract_optional_value_with_default(version.id, 0) self._mlflow_run_id = version.mlflow_run_id self._mlflow_url = version.mlflow_url - self._version_endpoints = version.endpoints self._created_at = version.created_at self._updated_at = version.updated_at self._properties = version.properties @@ -695,18 +710,27 @@ def __init__( self._labels = version.labels self._custom_predictor = version.custom_predictor self._python_version = version.python_version - mlflow.set_tracking_uri(model.project.mlflow_tracking_url) # type: ignore # noqa + self._model_schema = ModelSchema.from_model_schema_response(version.model_schema) + mlflow.set_tracking_uri(model.project.mlflow_tracking_url) # type: ignore # noqa + + endpoints = None + if version.endpoints is not None: + endpoints = [] + for ep in version.endpoints: + endpoints.append(VersionEndpoint(ep)) + self._version_endpoints = endpoints + @property def id(self) -> int: return self._id @property - def mlflow_run_id(self) -> str: + def mlflow_run_id(self) -> Optional[str]: return self._mlflow_run_id @property - def mlflow_url(self) -> str: + def mlflow_url(self) -> Optional[str]: return self._mlflow_url @property @@ -725,7 +749,7 @@ def endpoint(self) -> Optional[VersionEndpoint]: :return: VersionEndpoint or None """ for endpoint in self.version_endpoints: - if endpoint.environment.is_default: + if endpoint.environment is not None and endpoint.environment.is_default: return endpoint return None @@ -734,11 +758,11 @@ def properties(self) -> object: return self._properties @property - def created_at(self) -> datetime: + def created_at(self) -> Optional[datetime]: return self._created_at @property - def updated_at(self) -> datetime: + def updated_at(self) -> Optional[datetime]: return self._updated_at @property @@ -1043,7 +1067,7 @@ def log_custom_model( version_api.models_model_id_versions_version_id_patch( int(self.model.id), int(self.id), - body={"custom_predictor": custom_predictor_body}, + body=client.Version(custom_predictor=custom_predictor_body), ) def list_endpoint(self) -> List[VersionEndpoint]: @@ -1065,8 +1089,8 @@ def list_endpoint(self) -> List[VersionEndpoint]: def deploy( self, environment_name: str = None, - resource_request: ResourceRequest = None, - image_builder_resource_request: ResourceRequest = None, + resource_request: Optional[ResourceRequest] = None, + image_builder_resource_request: Optional[ResourceRequest] = None, env_vars: Dict[str, str] = None, transformer: Transformer = None, logger: Logger = None, @@ -1103,7 +1127,7 @@ def deploy( target_resource_request = None target_image_builder_resource_request = None target_autoscaling_policy = None - target_env_vars: List[client.models.Environment] = [] + target_env_vars: List[client.EnvVar] = [] target_transformer = None target_logger = None @@ -1120,6 +1144,9 @@ def deploy( if deployment_mode is not None else target_deployment_mode ) + else: + target_deployment_mode = current_endpoint.deployment_mode.value + target_protocol = current_endpoint.protocol.value if deployment_mode is not None: target_deployment_mode = deployment_mode.value @@ -1130,27 +1157,31 @@ def deploy( if resource_request is not None: resource_request.validate() target_resource_request = client.ResourceRequest( - resource_request.min_replica, - resource_request.max_replica, - resource_request.cpu_request, - resource_request.memory_request, + min_replica=resource_request.min_replica, + max_replica=resource_request.max_replica, + cpu_request=resource_request.cpu_request, + memory_request=resource_request.memory_request, ) if ( resource_request.gpu_request is not None and resource_request.gpu_name is not None ): for env in env_list: + if env.gpus is None: + continue + for gpu in env.gpus: if resource_request.gpu_name == gpu.name: - if resource_request.gpu_request not in gpu.values: + if gpu.values is not None and resource_request.gpu_request not in gpu.values: raise ValueError( f"Invalid GPU request count. Supported GPUs count for {resource_request.gpu_name} is {gpu.values}" ) - target_resource_request.gpu_name = resource_request.gpu_name - target_resource_request.gpu_request = ( - resource_request.gpu_request - ) + if target_resource_request is not None: + target_resource_request.gpu_name = resource_request.gpu_name + target_resource_request.gpu_request = ( + resource_request.gpu_request + ) break if image_builder_resource_request is not None: @@ -1161,8 +1192,8 @@ def deploy( if autoscaling_policy is not None: target_autoscaling_policy = client.AutoscalingPolicy( - autoscaling_policy.metrics_type.value, - autoscaling_policy.target_value, + metrics_type=client.MetricsType(autoscaling_policy.metrics_type.value), + target_value=autoscaling_policy.target_value, ) if env_vars is not None: @@ -1191,26 +1222,30 @@ def deploy( env_vars=target_env_vars, transformer=target_transformer, logger=target_logger, - deployment_mode=target_deployment_mode, + deployment_mode=client.DeploymentMode(target_deployment_mode), autoscaling_policy=target_autoscaling_policy, - protocol=target_protocol, + protocol=client.Protocol(target_protocol), enable_model_observability=enable_model_observability, ) if current_endpoint is not None: # This allows a serving deployment to be updated while it is serving if current_endpoint.status == Status.SERVING: - endpoint.status = Status.SERVING.value + endpoint.status = client.EndpointStatus.SERVING else: - endpoint.status = Status.RUNNING.value + endpoint.status = client.EndpointStatus.RUNNING + + if current_endpoint.id is None: + raise ValueError("current endpoint must have id") + endpoint = endpoint_api.models_model_id_versions_version_id_endpoint_endpoint_id_put( int(model.id), int(self.id), current_endpoint.id, - body=endpoint.to_dict(), + body=endpoint, ) else: endpoint = endpoint_api.models_model_id_versions_version_id_endpoint_post( - int(model.id), int(self.id), body=endpoint.to_dict() + int(model.id), int(self.id), body=endpoint ) bar = pyprind.ProgBar( 100, @@ -1221,8 +1256,11 @@ def deploy( while True: # Emulate a do-while loop. Re-get the endpoint so that the API server would have # started acting after the deployment job has been submitted. + if endpoint.id is None: + raise ValueError("endpoint id must be set") + endpoint = endpoint_api.models_model_id_versions_version_id_endpoint_endpoint_id_get( - model_id=int(model.id), version_id=int(self.id), endpoint_id=endpoint.id + model_id=model.id, version_id=self.id, endpoint_id=endpoint.id ) if endpoint.status != "pending": break @@ -1230,7 +1268,7 @@ def deploy( bar.update() bar.stop() - if endpoint.status != "running" and endpoint.status != "serving": + if endpoint.status != "running" and endpoint.status != "serving" and endpoint.message is not None: raise ModelEndpointDeploymentError(model.name, self.id, endpoint.message) log_url = f"{self.url}/{self.id}/endpoints/{endpoint.id}/logs" @@ -1271,7 +1309,7 @@ def undeploy(self, environment_name: str = None): if endpoint.environment_name == target_env: target_endpoint = endpoint - if target_endpoint is None: + if target_endpoint is None or target_endpoint.id is None: print(f"No endpoint found for environment: {target_endpoint}") return @@ -1302,23 +1340,23 @@ def create_prediction_job( job_cfg = client.PredictionJobConfig( version=V1, kind=PREDICTION_JOB, - model={ - "type": self.model.type.value.upper(), - "uri": os.path.join(self.artifact_uri, DEFAULT_MODEL_PATH), - "result": { - "type": job_config.result_type.value, - "item_type": job_config.item_type.value, - }, - }, + model=client.PredictionJobConfigModel( + type=self.model.type.value.upper(), + uri=os.path.join(self.artifact_uri, DEFAULT_MODEL_PATH), + result=client.PredictionJobConfigModelResult( + type=client.ResultType(job_config.result_type.value), + item_type=client.ResultType(job_config.item_type.value), + ) + ), ) if isinstance(job_config.source, BigQuerySource): - job_cfg.bigquery_source = job_config.source.to_dict() + job_cfg.bigquery_source = job_config.source.to_client_bq_source() else: raise ValueError(f"source type is not supported {type(job_config.source)}") if isinstance(job_config.sink, BigQuerySink): - job_cfg.bigquery_sink = job_config.sink.to_dict() + job_cfg.bigquery_sink = job_config.sink.to_client_config() else: raise ValueError(f"sink type is not supported {type(job_config.sink)}") @@ -1331,10 +1369,10 @@ def create_prediction_job( if job_config.image_builder_resource_request is not None: cfg.image_builder_resource_request = client.ResourceRequest( - 0, - 0, - job_config.image_builder_resource_request.cpu_request, - job_config.image_builder_resource_request.memory_request, + min_replica=0, + max_replica=0, + cpu_request=job_config.image_builder_resource_request.cpu_request, + memory_request=job_config.image_builder_resource_request.memory_request, ) target_env_vars = [] @@ -1346,7 +1384,7 @@ def create_prediction_job( if len(job_config.env_vars) > 0: for name, value in job_config.env_vars.items(): - target_env_vars.append(client.EnvVar(name, value)) + target_env_vars.append(client.EnvVar(name=name, value=value)) cfg.env_vars = target_env_vars req = client.PredictionJob( @@ -1367,15 +1405,19 @@ def create_prediction_job( while ( j.status == "pending" or j.status == "running" or j.status == "terminating" ): + job_id = j.id + if job_id is None: + raise ValueError("job id must be exist") + if not sync: j = job_client.models_model_id_versions_version_id_jobs_job_id_get( - model_id=self.model.id, version_id=self.id, job_id=j.id + model_id=self.model.id, version_id=self.id, job_id=job_id ) return PredictionJob(j, self._api_client) else: try: j = job_client.models_model_id_versions_version_id_jobs_job_id_get( - model_id=self.model.id, version_id=self.id, job_id=j.id + model_id=self.model.id, version_id=self.id, job_id=job_id ) retry = DEFAULT_API_CALL_RETRY except Exception: @@ -1584,7 +1626,7 @@ def _get_default_resource_request( ) -> client.ResourceRequest: resource_request = None for env in env_list: - if env.name == env_name: + if env.name == env_name and env.default_resource_request is not None: resource_request = ResourceRequest( env.default_resource_request.min_replica, env.default_resource_request.max_replica, @@ -1600,11 +1642,10 @@ def _get_default_resource_request( resource_request.validate() return client.ResourceRequest( - resource_request.min_replica, - resource_request.max_replica, - resource_request.cpu_request, - resource_request.memory_request, - ) + min_replica=resource_request.min_replica, + max_replica=resource_request.max_replica, + cpu_request=resource_request.cpu_request, + memory_request=resource_request.memory_request) @staticmethod def _get_default_autoscaling_policy( @@ -1615,8 +1656,8 @@ def _get_default_autoscaling_policy( else: autoscaling_policy = SERVERLESS_DEFAULT_AUTOSCALING_POLICY return client.AutoscalingPolicy( - autoscaling_policy.metrics_type.value, autoscaling_policy.target_value - ) + metrics_type=client.MetricsType(autoscaling_policy.metrics_type.value), + target_value=autoscaling_policy.target_value) @staticmethod def _add_env_vars(target_env_vars, new_env_vars): @@ -1627,7 +1668,7 @@ def _add_env_vars(target_env_vars, new_env_vars): if len(new_env_vars) > 0: for name, value in new_env_vars.items(): - target_env_vars.append(client.EnvVar(str(name), str(value))) + target_env_vars.append(client.EnvVar(name=str(name), value=str(value))) return target_env_vars @staticmethod @@ -1644,13 +1685,12 @@ def _create_transformer_spec( else: resource_request.validate() target_resource_request = client.ResourceRequest( - resource_request.min_replica, - resource_request.max_replica, - resource_request.cpu_request, - resource_request.memory_request, - ) + min_replica=resource_request.min_replica, + max_replica=resource_request.max_replica, + cpu_request=resource_request.cpu_request, + memory_request=resource_request.memory_request) - target_env_vars: List[client.models.Environment] = [] + target_env_vars: List[client.EnvVar] = [] if transformer.env_vars is not None: target_env_vars = ModelVersion._add_env_vars( target_env_vars, transformer.env_vars @@ -1693,7 +1733,7 @@ def _get_default_target_env_name(env_list: List[client.models.Environment]) -> s def _process_conda_env( - conda_env: Union[str, Dict[str, Any]], python_version: str + conda_env: Union[str, Dict[str, Any]], python_version: Optional[str] ) -> Dict[str, Any]: """ This function will replace/add python version dependency to the conda environment file. @@ -1715,6 +1755,9 @@ def match_dependency(spec, name): spec == name or re.match(name + r"[><=\s]+", spec) is not None ) + if python_version is None: + raise ValueError("python version must be set") + new_conda_env = {} if isinstance(conda_env, str): diff --git a/python/sdk/merlin/model_schema.py b/python/sdk/merlin/model_schema.py new file mode 100644 index 000000000..376d18c2b --- /dev/null +++ b/python/sdk/merlin/model_schema.py @@ -0,0 +1,116 @@ + +from __future__ import annotations +from typing import Dict, Optional, Any +from dataclasses import dataclass +from dataclasses_json import dataclass_json + + +from merlin.util import autostr +from merlin.util import extract_optional_value_with_default + +from enum import Enum +from merlin.observability.inference import InferenceSchema, PredictionOutput, BinaryClassificationOutput, RegressionOutput, RankingOutput, ValueType + +import client + + +@autostr +@dataclass_json +@dataclass +class ModelSchema: + spec: InferenceSchema + id: Optional[int] = None + model_id: Optional[int] = None + + @classmethod + def from_model_schema_response(cls, response: Optional[client.ModelSchema]=None) -> Optional[ModelSchema]: + if response is None: + return None + + response_spec = response.spec + if response_spec is None: + return ModelSchema( + id=response.id, + model_id=response.model_id + ) + + prediction_output = cls.model_prediction_output_from_response(response_spec.model_prediction_output) + feature_types = {} + for key, val in response_spec.feature_types.items(): + feature_types[key] = ValueType(val.value) + + return ModelSchema( + id=response.id, + model_id=response.model_id, + spec=InferenceSchema( + feature_types=feature_types, + prediction_id_column=response_spec.prediction_id_column, + tag_columns=response_spec.tag_columns, + model_prediction_output=prediction_output + ) + ) + @classmethod + def model_prediction_output_from_response(cls, model_prediction_output: client.ModelPredictionOutput) -> PredictionOutput: + actual_instance = model_prediction_output.actual_instance + if isinstance(actual_instance, client.BinaryClassificationOutput): + return BinaryClassificationOutput( + prediction_score_column=actual_instance.prediction_score_column, + actual_label_column=extract_optional_value_with_default(actual_instance.actual_label_column, ""), + positive_class_label=actual_instance.positive_class_label, + negative_class_label=actual_instance.negative_class_label, + score_threshold=extract_optional_value_with_default(actual_instance.score_threshold, 0.5) + ) + elif isinstance(actual_instance, client.RegressionOutput): + return RegressionOutput( + actual_score_column=extract_optional_value_with_default(actual_instance.actual_score_column, ""), + prediction_score_column=actual_instance.prediction_score_column + ) + elif isinstance(actual_instance, client.RankingOutput): + return RankingOutput( + relevance_score_column=extract_optional_value_with_default(actual_instance.relevance_score_column, ""), + prediction_group_id_column=actual_instance.prediction_group_id_column, + rank_score_column=actual_instance.rank_score_column + ) + raise ValueError("model prediction output from server is not in acceptable type") + + def _to_client_prediction_output_spec(self) -> client.ModelPredictionOutput: + prediction_output = self.spec.model_prediction_output + if isinstance(prediction_output, BinaryClassificationOutput): + return client.ModelPredictionOutput(client.BinaryClassificationOutput( + prediction_score_column=prediction_output.prediction_score_column, + actual_label_column=prediction_output.actual_label_column, + positive_class_label=prediction_output.positive_class_label, + negative_class_label=prediction_output.negative_class_label, + score_threshold=prediction_output.score_threshold + )) + elif isinstance(prediction_output, RegressionOutput): + return client.ModelPredictionOutput(client.RegressionOutput( + actual_score_column=prediction_output.actual_score_column, + prediction_score_column=prediction_output.prediction_score_column + )) + elif isinstance(prediction_output, RankingOutput): + return client.ModelPredictionOutput(client.RankingOutput( + relevance_score_column=prediction_output.relevance_score_column, + prediction_group_id_column=prediction_output.prediction_group_id_column, + rank_score_column=prediction_output.rank_score_column + )) + + raise ValueError("model prediction output is not recognized") + + def to_client_model_schema(self) -> client.ModelSchema: + feature_types = {} + for key, val in self.spec.feature_types.items(): + feature_types[key] = client.ValueType(val.value) + + return client.ModelSchema( + id=self.id, + model_id=self.model_id, + spec=client.SchemaSpec( + prediction_id_column=self.spec.prediction_id_column, + tag_columns=self.spec.tag_columns, + feature_types=feature_types, + model_prediction_output=self._to_client_prediction_output_spec() + ) + ) + + diff --git a/python/sdk/merlin/resource_request.py b/python/sdk/merlin/resource_request.py index dc4350eef..89b2baf53 100644 --- a/python/sdk/merlin/resource_request.py +++ b/python/sdk/merlin/resource_request.py @@ -11,9 +11,10 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. - +from __future__ import annotations from typing import Optional +import client class ResourceRequest: """ @@ -22,12 +23,12 @@ class ResourceRequest: def __init__( self, - min_replica: int = None, - max_replica: int = None, - cpu_request: str = None, - memory_request: str = None, - gpu_request: str = None, - gpu_name: str = None, + min_replica: Optional[int] = None, + max_replica: Optional[int] = None, + cpu_request: Optional[str] = None, + memory_request: Optional[str] = None, + gpu_request: Optional[str] = None, + gpu_name: Optional[str] = None, ): self._min_replica = min_replica self._max_replica = max_replica @@ -37,6 +38,17 @@ def __init__( self._gpu_name = gpu_name self.validate() + @classmethod + def from_response(cls, response: client.ResourceRequest) -> ResourceRequest: + return ResourceRequest( + min_replica=response.min_replica, + max_replica=response.max_replica, + cpu_request=response.cpu_request, + memory_request=response.memory_request, + gpu_request=response.gpu_request, + gpu_name=response.gpu_name + ) + @property def min_replica(self) -> Optional[int]: return self._min_replica diff --git a/python/sdk/merlin/transformer.py b/python/sdk/merlin/transformer.py index d6ffa43f6..61907fe5d 100644 --- a/python/sdk/merlin/transformer.py +++ b/python/sdk/merlin/transformer.py @@ -40,10 +40,10 @@ def __init__( image: str, id: str = "", enabled: bool = True, - command: str = None, - args: str = None, - resource_request: ResourceRequest = None, - env_vars: Dict[str, str] = None, + command: Optional[str] = None, + args: Optional[str] = None, + resource_request: Optional[ResourceRequest] = None, + env_vars: Optional[Dict[str, str]] = None, transformer_type: TransformerType = TransformerType.CUSTOM_TRANSFORMER, ): self._id = id diff --git a/python/sdk/merlin/util.py b/python/sdk/merlin/util.py index f5dee87db..2b01e36be 100644 --- a/python/sdk/merlin/util.py +++ b/python/sdk/merlin/util.py @@ -18,7 +18,7 @@ from google.cloud import storage from os.path import dirname from os import makedirs - +from typing import Optional, Any def guess_mlp_ui_url(mlp_api_url: str) -> str: raw_url = mlp_api_url.replace("/api", "") @@ -94,3 +94,8 @@ def download_files_from_gcs(gcs_uri: str, destination_path: str): dir = os.path.join(destination_path, dirname(artifact_path)) makedirs(dir, exist_ok=True) blob.download_to_filename(os.path.join(destination_path, artifact_path)) + +def extract_optional_value_with_default(opt: Optional[Any], default: Any) -> Any: + if opt is not None: + return opt + return default \ No newline at end of file diff --git a/python/sdk/pyfunc.Dockerfile b/python/sdk/pyfunc.Dockerfile new file mode 100644 index 000000000..ae49e30fa --- /dev/null +++ b/python/sdk/pyfunc.Dockerfile @@ -0,0 +1,36 @@ +# Copyright 2020 The Merlin Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +ARG BASE_IMAGE=ghcr.io/caraml-dev/merlin/merlin-pyfunc-base:0.38.1 +FROM ${BASE_IMAGE} + +# Download and install user model dependencies +ARG MODEL_DEPENDENCIES_URL +COPY ${MODEL_DEPENDENCIES_URL} conda.yaml +RUN conda env create --name merlin-model --file conda.yaml + +# Copy and install pyfunc-server and merlin-sdk dependencies +COPY merlin/python/pyfunc-server /pyfunc-server +COPY merlin/python/sdk /sdk +ENV SDK_PATH=/sdk + +WORKDIR /pyfunc-server +RUN /bin/bash -c ". activate merlin-model && pip uninstall -y merlin-sdk && pip install -r /pyfunc-server/requirements.txt" + +# Download and dry-run user model artifacts and code +ARG MODEL_ARTIFACTS_URL +COPY ${MODEL_ARTIFACTS_URL} model +RUN /bin/bash -c ". activate merlin-model && python -m pyfuncserver --model_dir model --dry_run" + +CMD ["/bin/bash", "/pyfunc-server/run.sh"] diff --git a/python/sdk/setup.py b/python/sdk/setup.py index ca7c7ca36..a5873e8cc 100644 --- a/python/sdk/setup.py +++ b/python/sdk/setup.py @@ -42,6 +42,7 @@ "urllib3>=1.26", "numpy<=1.23.5", # Temporary pin numpy due to https://numpy.org/doc/stable/release/1.20.0-notes.html#numpy-1-20-0-release-notes "caraml-auth-google==0.0.0.post7", + "pydantic==2.5.3" ] TEST_REQUIRES = [ diff --git a/python/sdk/test/client_test.py b/python/sdk/test/client_test.py index 3fda01d8f..1f2a85dc2 100644 --- a/python/sdk/test/client_test.py +++ b/python/sdk/test/client_test.py @@ -47,7 +47,7 @@ def api_client(mock_url): created_at = "2019-08-29T08:13:12.377Z" updated_at = "2019-08-29T08:13:12.377Z" -default_resource_request = cl.ResourceRequest(1, 1, "100m", "128Mi") +default_resource_request = cl.ResourceRequest(min_replica=1, max_replica=1, cpu_request="100m", memory_request="128Mi") env_1 = cl.Environment( id=1, name="dev", @@ -76,6 +76,11 @@ def api_client(mock_url): ) +def serialize_datetime(obj): + if isinstance(obj, datetime.datetime): + return obj.isoformat() + raise TypeError("Type is not serializable") + @responses.activate def test_get_project(mock_url, mock_oauth, use_google_oauth): responses.add( @@ -122,7 +127,7 @@ def test_create_invalid_project_name( @responses.activate def test_create_model(mock_url, api_client, mock_oauth, use_google_oauth): - project_id = "1010" + project_id = 1010 mlflow_experiment_id = 1 model_name = "my-model" project_name = "my-project" @@ -150,13 +155,17 @@ def test_create_model(mock_url, api_client, mock_oauth, use_google_oauth): "created_at": "{created_at}", "updated_at": "{updated_at}" }}""", - status=200, + status=201, content_type="application/json", ) client = MerlinClient(mock_url, use_google_oauth=use_google_oauth) prj = cl.Project( - project_id, project_name, mlflow_tracking_url, created_at, updated_at + id=project_id, + name=project_name, + mlflow_tracking_url=mlflow_tracking_url, + created_at=created_at, + updated_at=updated_at ) project = Project(prj, mock_url, api_client) with mock.patch.object(client, "get_project", return_value=project): @@ -205,7 +214,7 @@ def test_create_invalid_model_name(mock_url, api_client, mock_oauth, use_google_ @responses.activate def test_get_model(mock_url, api_client, mock_oauth, use_google_oauth): - project_id = "1010" + project_id = 1010 mlflow_experiment_id = 1 model_name = "my-model" project_name = "my-project" @@ -233,14 +242,18 @@ def test_get_model(mock_url, api_client, mock_oauth, use_google_oauth): responses.add( "GET", f"/api/v1/models/1/endpoints", - body=json.dumps([mdl_endpoint_1.to_dict()]), + body=json.dumps([mdl_endpoint_1.to_dict()], default=serialize_datetime), status=200, content_type="application/json", ) client = MerlinClient(mock_url, use_google_oauth=use_google_oauth) prj = cl.Project( - project_id, project_name, mlflow_tracking_url, created_at, updated_at + id=project_id, + name=project_name, + mlflow_tracking_url=mlflow_tracking_url, + created_at=created_at, + updated_at=updated_at ) project = Project(prj, mock_url, api_client) with mock.patch.object(client, "get_project", return_value=project): @@ -291,25 +304,29 @@ def test_new_model_version(mock_url, api_client, mock_oauth, use_google_oauth): "created_at": "{created_at}", "updated_at": "{updated_at}" }}""", - status=200, + status=201, content_type="application/json", ) client = MerlinClient(mock_url, use_google_oauth=use_google_oauth) prj = cl.Project( - project_id, project_name, mlflow_tracking_url, created_at, updated_at + id=project_id, + name=project_name, + mlflow_tracking_url=mlflow_tracking_url, + created_at=created_at, + updated_at=updated_at ) project = Project(prj, mock_url, api_client) mdl = cl.Model( - model_id, - project_id, - mlflow_experiment_id, - model_name, - model_type.value, - mlflow_url, - None, - created_at, - updated_at, + id=model_id, + project_id=project_id, + mlflow_experiment_id=mlflow_experiment_id, + name=model_name, + type=model_type.value, + mlflow_url=mlflow_url, + endpoints=None, + created_at=created_at, + updated_at=updated_at, ) mdl = Model(mdl, project, api_client) with mock.patch.object(client, "get_model", return_value=mdl): diff --git a/python/sdk/test/integration_test.py b/python/sdk/test/integration_test.py index 49203cdd8..44206c2cd 100644 --- a/python/sdk/test/integration_test.py +++ b/python/sdk/test/integration_test.py @@ -22,6 +22,8 @@ from merlin.model import ModelType from merlin.resource_request import ResourceRequest from merlin.transformer import StandardTransformer, Transformer +from merlin.model_schema import ModelSchema +from merlin.observability.inference import InferenceSchema, ValueType, BinaryClassificationOutput from recursive_diff import recursive_eq import merlin @@ -126,7 +128,22 @@ def test_xgboost( undeploy_all_version() - with merlin.new_model_version() as v: + with merlin.new_model_version(model_schema=ModelSchema(spec=InferenceSchema( + feature_types={ + "featureA": ValueType.FLOAT64, + "featureB": ValueType.INT64, + "featureC": ValueType.STRING, + "featureD": ValueType.BOOLEAN + }, + prediction_id_column="prediction_id", + model_prediction_output=BinaryClassificationOutput( + prediction_score_column="score", + actual_label_column="actual", + positive_class_label="completed", + negative_class_label="non_complete", + score_threshold=0.7 + ) + ))) as v: # Upload the serialized model to MLP merlin.log_model(model_dir=model_dir) @@ -1177,11 +1194,14 @@ def test_standard_transformer_simulate(integration_test_url, use_google_oauth): resp_wo_tracing = transformer.simulate(payload=payload, exclude_tracing=True) resp_w_tracing = transformer.simulate(payload=payload, exclude_tracing=False) + def remove_nulls(d): + return {k: v for k, v in d.items() if v is not None} + with open("test/transformer/sim_exp_resp_valid_wo_tracing.json", "r") as f: - exp_resp_valid_wo_tracing = json.load(f) + exp_resp_valid_wo_tracing = json.load(f, object_hook=remove_nulls) with open("test/transformer/sim_exp_resp_valid_w_tracing.json", "r") as f: - exp_resp_valid_w_tracing = json.load(f) + exp_resp_valid_w_tracing = json.load(f, object_hook=remove_nulls) assert isinstance(resp_wo_tracing, dict) assert isinstance(resp_w_tracing, dict) diff --git a/python/sdk/test/logger_test.py b/python/sdk/test/logger_test.py index b6e97cc7f..8555964db 100644 --- a/python/sdk/test/logger_test.py +++ b/python/sdk/test/logger_test.py @@ -28,15 +28,6 @@ def test_from_logger_response(): assert result.transformer is None assert result.prediction is None - logger_response = client.Logger(model=client.LoggerConfig(enabled=False, mode="")) - result = Logger.from_logger_response(logger_response) - expected_result = Logger(model=LoggerConfig(enabled=False, mode=LoggerMode.ALL)) - assert result.model is not None - assert result.model.enabled == expected_result.model.enabled - assert result.model.mode == expected_result.model.mode - assert result.transformer is None - assert result.prediction is None - logger_response = client.Logger(transformer=client.LoggerConfig(enabled=True, mode=client.LoggerMode.REQUEST)) result = Logger.from_logger_response(logger_response) expected_result = Logger(transformer=LoggerConfig(enabled=True, mode=LoggerMode.REQUEST)) diff --git a/python/sdk/test/merlin_test.py b/python/sdk/test/merlin_test.py index 6c281a695..691a8b7fc 100644 --- a/python/sdk/test/merlin_test.py +++ b/python/sdk/test/merlin_test.py @@ -24,12 +24,20 @@ # get global mock responses that configured in conftest responses = pytest.responses -default_resource_request = cl.ResourceRequest(1, 1, "100m", "128Mi") +default_resource_request = cl.ResourceRequest(min_replica=1, max_replica=1, cpu_request="100m", memory_request="128Mi") env_1 = cl.Environment( - 1, "dev", "cluster-1", True, default_resource_request=default_resource_request + id=1, + name="dev", + cluster="cluster-1", + is_default=True, + default_resource_request=default_resource_request, ) env_2 = cl.Environment( - 2, "dev-2", "cluster-2", False, default_resource_request=default_resource_request + id=2, + name="dev-2", + cluster="cluster-2", + is_default=False, + default_resource_request=default_resource_request, ) @@ -215,7 +223,7 @@ def _mock_get_model_call(project, model): f"/v1/projects/{project.id}/models", body=f"""[{{ "id": {model.id}, - "mlflow_experiment_id": "{model.mlflow_experiment_id}", + "mlflow_experiment_id": {model.mlflow_experiment_id}, "name": "{model.name}", "type": "{model.type.value}", "mlflow_url": "{model.mlflow_url}", @@ -243,7 +251,7 @@ def _mock_new_model_version_call(model, version, labels=None): "POST", f"/v1/models/{model.id}/versions", body=json.dumps(body), - status=200, + status=201, content_type="application/json", ) diff --git a/python/sdk/test/model_schema_test.py b/python/sdk/test/model_schema_test.py new file mode 100644 index 000000000..47345d484 --- /dev/null +++ b/python/sdk/test/model_schema_test.py @@ -0,0 +1,171 @@ +import pytest +import client +from merlin.model_schema import ModelSchema +from merlin.observability.inference import InferenceSchema, ValueType, BinaryClassificationOutput, RegressionOutput, RankingOutput + +@pytest.mark.unit +@pytest.mark.parametrize( + "response,expected,error", + [ + ( + client.ModelSchema( + id=1, + model_id=1, + spec=client.SchemaSpec( + prediction_id_column="prediction_id", + tag_columns=["tags"], + feature_types={ + "featureA": client.ValueType.FLOAT64, + "featureB": client.ValueType.INT64, + "featureC": client.ValueType.BOOLEAN, + "featureD": client.ValueType.STRING + }, + model_prediction_output=client.ModelPredictionOutput( + client.BinaryClassificationOutput( + prediction_score_column="prediction_score", + actual_label_column="actual_label", + positive_class_label="positive", + negative_class_label="negative", + score_threshold=0.5 + ) + ) + ) + ), + ModelSchema( + id=1, + model_id=1, + spec=InferenceSchema( + prediction_id_column="prediction_id", + tag_columns=["tags"], + feature_types={ + "featureA": ValueType.FLOAT64, + "featureB": ValueType.INT64, + "featureC": ValueType.BOOLEAN, + "featureD": ValueType.STRING + }, + model_prediction_output=BinaryClassificationOutput( + prediction_score_column="prediction_score", + actual_label_column="actual_label", + positive_class_label="positive", + negative_class_label="negative", + score_threshold=0.5 + ) + ), + ), + None + ), + ( + client.ModelSchema( + id=2, + model_id=1, + spec=client.SchemaSpec( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": client.ValueType.FLOAT64, + "featureB": client.ValueType.INT64, + "featureC": client.ValueType.BOOLEAN, + "featureD": client.ValueType.STRING + }, + model_prediction_output=client.ModelPredictionOutput( + client.RegressionOutput( + prediction_score_column="prediction_score", + actual_score_column="actual_score" + ) + ) + ) + ), + ModelSchema( + id=2, + model_id=1, + spec=InferenceSchema( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": ValueType.FLOAT64, + "featureB": ValueType.INT64, + "featureC": ValueType.BOOLEAN, + "featureD": ValueType.STRING + }, + model_prediction_output=RegressionOutput( + prediction_score_column="prediction_score", + actual_score_column="actual_score" + ) + ), + ), + None + ), + ( + client.ModelSchema( + id=3, + model_id=1, + spec=client.SchemaSpec( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": client.ValueType.FLOAT64, + "featureB": client.ValueType.INT64, + "featureC": client.ValueType.BOOLEAN, + "featureD": client.ValueType.STRING + }, + model_prediction_output=client.ModelPredictionOutput( + client.RankingOutput( + rank_score_column="score", + prediction_group_id_column="session_id", + relevance_score_column="relevance_score" + ) + ) + ) + ), + ModelSchema( + id=3, + model_id=1, + spec=InferenceSchema( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": ValueType.FLOAT64, + "featureB": ValueType.INT64, + "featureC": ValueType.BOOLEAN, + "featureD": ValueType.STRING + }, + model_prediction_output=RankingOutput( + rank_score_column="score", + prediction_group_id_column="session_id", + relevance_score_column="relevance_score" + ) + ), + ), + None + ), + ( + client.ModelSchema( + id=3, + model_id=1, + spec=client.SchemaSpec( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": client.ValueType.FLOAT64, + "featureB": client.ValueType.INT64, + "featureC": client.ValueType.BOOLEAN, + "featureD": client.ValueType.STRING + }, + model_prediction_output=client.ModelPredictionOutput() + ) + ), + None, + ValueError + ) + ] +) +def test_model_schema_conversion(response, expected, error): + if error is None: + got = ModelSchema.from_model_schema_response(response) + assert got == expected + + client_model_schema = got.to_client_model_schema() + assert client_model_schema == response + else: + with pytest.raises(error): + ModelSchema.from_model_schema_response(response) diff --git a/python/sdk/test/model_test.py b/python/sdk/test/model_test.py index c04de8fce..6c612c19b 100644 --- a/python/sdk/test/model_test.py +++ b/python/sdk/test/model_test.py @@ -15,6 +15,7 @@ import json import types from unittest.mock import patch +import datetime import client import client as cl @@ -30,11 +31,12 @@ from merlin.endpoint import VersionEndpoint from merlin.model import ModelType from merlin.protocol import Protocol +from merlin.model_schema import ModelSchema, InferenceSchema, ValueType, RankingOutput from urllib3_mock import Responses responses = Responses("requests.packages.urllib3") -default_resource_request = cl.ResourceRequest(1, 1, "100m", "128Mi") +default_resource_request = cl.ResourceRequest(min_replica=1, max_replica=1, cpu_request="100m", memory_request="128Mi") gpu = cl.GPUConfig( name="nvidia-tesla-p4", values=["1", "4", "8"], @@ -47,51 +49,73 @@ ) env_1 = cl.Environment( - 1, "dev", "cluster-1", True, default_resource_request=default_resource_request + id=1, + name="dev", + cluster="cluster-1", + is_default=True, + default_resource_request=default_resource_request, ) env_2 = cl.Environment( - 2, "dev-2", "cluster-2", False, default_resource_request=default_resource_request + id=2, + name="dev-2", + cluster="cluster-2", + is_default=False, + default_resource_request=default_resource_request, ) env_3 = cl.Environment( - 3, - "dev-3", - "cluster-3", - False, + id=2, + name="dev-3", + cluster="cluster-3", + is_default=False, default_resource_request=default_resource_request, - gpus=[gpu], + gpus=[gpu] ) ep1 = cl.VersionEndpoint( - "1234", 1, "running", "localhost/1", "svc-1", env_1.name, env_1, "grafana.com" + id="1234", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_1.name, + environment=env_1, + monitoring_url="grafana.com" ) ep2 = cl.VersionEndpoint( - "4567", 1, "running", "localhost/1", "svc-2", env_2.name, env_2, "grafana.com" + id="4567", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-2", + environment_name=env_2.name, + environment=env_2, + monitoring_url="grafana.com" ) ep3 = cl.VersionEndpoint( - "1234", - 1, - "running", - "localhost/1", - "svc-1", - env_1.name, - env_1, - "grafana.com", - deployment_mode="raw_deployment", + id="1234", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_1.name, + environment=env_1, + monitoring_url="grafana.com", + deployment_mode="raw_deployment" ) ep4 = cl.VersionEndpoint( - "1234", - 1, - "running", - "localhost/1", - "svc-1", - env_1.name, - env_1, - "grafana.com", + id="1234", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_1.name, + environment=env_1, + monitoring_url="grafana.com", autoscaling_policy=client.AutoscalingPolicy( - metrics_type=cl.MetricsType.CPU_UTILIZATION, target_value=10 - ), + metrics_type=cl.MetricsType.CPU_UTILIZATION, + target_value=10 + ) ) - resource_request_with_gpu = cl.ResourceRequest( min_replica=1, max_replica=1, @@ -101,63 +125,76 @@ gpu_request="1", ) ep5 = cl.VersionEndpoint( - "789", - 1, - "running", - "localhost/1", - "svc-1", - env_3.name, - env_3, - "grafana.com", - resource_request=resource_request_with_gpu, + id="789", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_3.name, + environment=env_3, + monitoring_url="grafana.com", + resource_request=resource_request_with_gpu ) - upi_ep = cl.VersionEndpoint( - "1234", - 1, - "running", - "localhost/1", - "svc-1", - env_1.name, - env_1, - "grafana.com", - protocol=cl.Protocol.UPI_V1, + id="1234", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_1.name, + environment=env_1, + monitoring_url="grafana.com", + protocol=cl.Protocol.UPI_V1 ) - observability_enabled_ep = cl.VersionEndpoint( - "7899", - 1, - "running", - "localhost/1", - "svc-1", - env_3.name, - env_3, - "grafana.com", - enable_model_observability=True, + id="7899", + version_id=1, + status="running", + url="localhost/1", + service_name="svc-1", + environment_name=env_3.name, + environment=env_3, + monitoring_url="grafana.com", + enable_model_observability=True ) rule_1 = cl.ModelEndpointRule( - destinations=[cl.ModelEndpointRuleDestination(ep1.id, weight=100)] + destinations=[cl.ModelEndpointRuleDestination(version_endpoint_id=ep1.id, weight=100)] ) rule_2 = cl.ModelEndpointRule( - destinations=[cl.ModelEndpointRuleDestination(ep2.id, weight=100)] + destinations=[cl.ModelEndpointRuleDestination(version_endpoint_id=ep2.id, weight=100)] ) mdl_endpoint_1 = cl.ModelEndpoint( - 1, 1, None, "serving", "localhost/1", rule_1, env_1.name, env_1 + id=1, + model_id=1, + model=None, + status="serving", + url="localhost/1", + rule=rule_1, + environment_name=env_1.name, + environment=env_1 ) mdl_endpoint_2 = cl.ModelEndpoint( - 2, 1, None, "serving", "localhost/2", rule_2, env_2.name, env_2 + id=2, + model_id=1, + model=None, + status="serving", + url="localhost/2", + rule=rule_2, + environment_name=env_2.name, + environment=env_2 ) + mdl_endpoint_upi = cl.ModelEndpoint( - 1, - 1, - None, - "serving", - "localhost/1", - rule_1, - env_1.name, - env_1, - protocol=cl.Protocol.UPI_V1, + id=1, + model_id=1, + model=None, + status="serving", + url="localhost/1", + rule=rule_1, + environment_name=env_1.name, + environment=env_1, + protocol=cl.Protocol.UPI_V1 ) config = { @@ -184,7 +221,7 @@ "table": "project.dataset.result_table", "staging_bucket": "gs://test", "result_column": "prediction", - "save_mode": "OVERWRITE", + "save_mode": 1, "options": { "key": "val", }, @@ -223,6 +260,10 @@ updated_at="2019-08-29T08:13:12.377Z", ) +def serialize_datetime(obj): + if isinstance(obj, datetime.datetime): + return obj.isoformat() + raise TypeError("Type is not serializable") class TestProject: secret_1 = cl.Secret(id=1, name="secret-1", data="secret-data-1") @@ -239,7 +280,6 @@ def test_create_secret(self, project): ) project.create_secret(self.secret_1.name, self.secret_1.data) - actual_body = json.loads(responses.calls[0].request.body) assert actual_body["name"] == self.secret_1.name assert actual_body["data"] == self.secret_1.data @@ -370,7 +410,7 @@ def test_deploy(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(ep1.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -420,7 +460,7 @@ def test_deploy_upiv1(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(upi_ep.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -470,7 +510,7 @@ def test_deploy_using_raw_deployment_mode(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(ep3.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -520,7 +560,7 @@ def test_deploy_with_autoscaling_policy(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(ep4.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -596,7 +636,7 @@ def test_deploy_default_env(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(ep1.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -696,7 +736,7 @@ def test_deploy_with_gpu(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(ep5.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -752,7 +792,7 @@ def test_deploy_with_model_observability_enabled(self, version): "POST", "/v1/models/1/versions/1/endpoint", body=json.dumps(observability_enabled_ep.to_dict()), - status=200, + status=201, content_type="application/json", ) responses.add( @@ -884,7 +924,7 @@ def test_list_prediction_job(self, version): responses.add( method="GET", url="/v1/models/1/versions/1/jobs", - body=json.dumps([job_1.to_dict(), job_2.to_dict()]), + body=json.dumps([job_1.to_dict(), job_2.to_dict()], default=serialize_datetime), status=200, content_type="application/json", ) @@ -906,7 +946,7 @@ def test_create_prediction_job(self, version): responses.add( "POST", "/v1/models/1/versions/1/jobs", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -963,7 +1003,7 @@ def test_create_prediction_job_with_retry_failed(self, version): responses.add( "POST", "/v1/models/1/versions/1/jobs", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -972,7 +1012,7 @@ def test_create_prediction_job_with_retry_failed(self, version): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=500, content_type="application/json", ) @@ -1013,7 +1053,7 @@ def test_create_prediction_job_with_retry_success(self, version): responses.add( "POST", "/v1/models/1/versions/1/jobs", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1046,7 +1086,7 @@ def _find_match_patched(self, request): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=500, content_type="application/json", ) @@ -1055,7 +1095,7 @@ def _find_match_patched(self, request): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1116,7 +1156,7 @@ def test_create_prediction_job_with_retry_pending_then_failed(self, version): responses.add( "POST", "/v1/models/1/versions/1/jobs", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1149,7 +1189,7 @@ def _find_match_patched(self, request): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=500, content_type="application/json", ) @@ -1157,7 +1197,7 @@ def _find_match_patched(self, request): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1167,7 +1207,7 @@ def _find_match_patched(self, request): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=500, content_type="application/json", ) @@ -1209,7 +1249,7 @@ def test_stop_prediction_job(self, version): responses.add( "POST", "/v1/models/1/versions/1/jobs", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1225,7 +1265,7 @@ def test_stop_prediction_job(self, version): responses.add( "GET", "/v1/models/1/versions/1/jobs/1", - body=json.dumps(job_1.to_dict()), + body=json.dumps(job_1.to_dict(), default=serialize_datetime), status=200, content_type="application/json", ) @@ -1277,6 +1317,48 @@ class TestModel: v2 = cl.Version(id=2, model_id=1) v3 = cl.Version(id=3, model_id=1, labels={"model": "T-800"}, python_version="3.7.*") + schema = client.ModelSchema( + id=3, + model_id=1, + spec=client.SchemaSpec( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": client.ValueType.FLOAT64, + "featureB": client.ValueType.INT64, + "featureC": client.ValueType.BOOLEAN, + "featureD": client.ValueType.STRING + }, + model_prediction_output=client.ModelPredictionOutput( + client.RankingOutput( + rank_score_column="score", + prediction_group_id_column="session_id", + relevance_score_column="relevance_score" + ) + ) + ) + ) + merlin_model_schema = ModelSchema( + id=3, + model_id=1, + spec=InferenceSchema( + prediction_id_column="prediction_id", + tag_columns=["tags", "extras"], + feature_types={ + "featureA": ValueType.FLOAT64, + "featureB": ValueType.INT64, + "featureC": ValueType.BOOLEAN, + "featureD": ValueType.STRING + }, + model_prediction_output=RankingOutput( + rank_score_column="score", + prediction_group_id_column="session_id", + relevance_score_column="relevance_score" + ) + ), + ) + v4 = cl.Version(id=4, model_id=1, labels={"model": "T-800"}, python_version="3.7.*", model_schema=schema) + @responses.activate def test_list_version(self, model): responses.add( @@ -1328,24 +1410,25 @@ def test_list_endpoint(self, model): endpoints = model.list_endpoint() assert len(endpoints) == 2 - assert endpoints[0].id == str(mdl_endpoint_1.id) - assert endpoints[1].id == str(mdl_endpoint_2.id) + assert endpoints[0].id == mdl_endpoint_1.id + assert endpoints[1].id == mdl_endpoint_2.id @responses.activate def test_new_model_version(self, model): responses.add( "POST", "/v1/models/1/versions", - body=json.dumps(self.v3.to_dict()), - status=200, + body=json.dumps(self.v4.to_dict()), + status=201, content_type="application/json", ) - mv = model.new_model_version(labels={"model": "T-800"}) + mv = model.new_model_version(labels={"model": "T-800"}, model_schema=self.merlin_model_schema) assert mv._python_version == "3.7.*" - assert mv._id == 3 + assert mv._id == 4 assert mv._model._id == 1 assert mv._labels == {"model": "T-800"} + assert mv._model_schema == self.merlin_model_schema @responses.activate def test_serve_traffic(self, model): @@ -1376,11 +1459,11 @@ def test_serve_traffic(self, model): "POST", "/v1/models/1/endpoints", body=json.dumps(mdl_endpoint_1.to_dict()), - status=200, + status=201, content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}, environment_name=env_1.name) - assert endpoint.id == str(mdl_endpoint_1.id) + assert endpoint.id == mdl_endpoint_1.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1411,7 +1494,7 @@ def test_serve_traffic(self, model): content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}, environment_name=env_1.name) - assert endpoint.id == str(mdl_endpoint_1.id) + assert endpoint.id == mdl_endpoint_1.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1445,11 +1528,11 @@ def test_stop_serving_traffic(self, model): "POST", "/v1/models/1/endpoints", body=json.dumps(mdl_endpoint_1.to_dict()), - status=200, + status=201, content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}, environment_name=env_1.name) - assert endpoint.id == str(mdl_endpoint_1.id) + assert endpoint.id == mdl_endpoint_1.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1517,11 +1600,11 @@ def test_serve_traffic_default_env(self, model): "POST", "/v1/models/1/endpoints", body=json.dumps(mdl_endpoint_1.to_dict()), - status=200, + status=201, content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}) - assert endpoint.id == str(mdl_endpoint_1.id) + assert endpoint.id == mdl_endpoint_1.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1558,7 +1641,7 @@ def test_serve_traffic_default_env(self, model): content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}) - assert endpoint.id == str(mdl_endpoint_1.id) + assert endpoint.id == mdl_endpoint_1.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1578,11 +1661,11 @@ def test_serve_traffic_upi(self, model): "POST", "/v1/models/1/endpoints", body=json.dumps(mdl_endpoint_upi.to_dict()), - status=200, + status=201, content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}, environment_name=env_1.name) - assert endpoint.id == str(mdl_endpoint_upi.id) + assert endpoint.id == mdl_endpoint_upi.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_1.environment_name ) @@ -1613,7 +1696,7 @@ def test_serve_traffic_upi(self, model): content_type="application/json", ) endpoint = model.serve_traffic({ve: 100}, environment_name=env_1.name) - assert endpoint.id == str(mdl_endpoint_upi.id) + assert endpoint.id == mdl_endpoint_upi.id assert ( endpoint.environment_name == env_1.name == mdl_endpoint_upi.environment_name ) diff --git a/python/sdk/test/pyfunc_integration_test.py b/python/sdk/test/pyfunc_integration_test.py index da97c8edc..3c103db6f 100644 --- a/python/sdk/test/pyfunc_integration_test.py +++ b/python/sdk/test/pyfunc_integration_test.py @@ -196,17 +196,15 @@ def test_pyfunc_model_observability( undeploy_all_version() with merlin.new_model_version() as v: iris = load_iris() - y = iris["target"] - X = iris["data"] - xgb_path = train_xgboost_model(X, y) + y = iris['target'] + X = iris['data'] - v.log_pyfunc_model( - model_instance=ModelObservabilityModel(), - conda_env="test/pyfunc/env.yaml", - code_dir=["test"], - artifacts={"xgb_model": xgb_path}, - ) + v.log_pyfunc_model(model_instance=ModelObservabilityModel(), + conda_env="test/pyfunc/env.yaml", + code_dir=["test"], + artifacts={"xgb_model": XGB_PATH}) + endpoint = merlin.deploy(v, enable_model_observability=True) resp = requests.post(f"{endpoint.url}", json=request_json) diff --git a/swagger.yaml b/swagger.yaml index 68f11b839..6727de5a7 100644 --- a/swagger.yaml +++ b/swagger.yaml @@ -1,1645 +1,2071 @@ -# Copyright 2020 The Merlin Authors -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -swagger: "2.0" +openapi: 3.0.1 info: - title: "Merlin" - description: "API Guide for accessing Merlin's model management, deployment, and serving functionalities" - version: "0.14.0" -host: "localhost:8080" -basePath: "/v1" + title: Merlin + description: API Guide for accessing Merlin's model management, deployment, and + serving functionalities + version: 0.14.0 +servers: +- url: http://localhost:8080/v1 +security: +- Bearer: [] tags: - - name: "project" - description: "Project Management API. Project is used to namespace model, secret, and user access" - - name: "models" - description: "Model Management API. API to manage ML model in Merlin." - - name: "version" - description: "Model Version Management API. Model version represents the iteration of an ML model" - - name: "endpoint" - description: "Deployment Management API. Endpoint represent a deployment of a specific model version" - - name: "model_endpoints" - description: "Serving Traffic Management API. API to manage traffic routing to a running endpoint." - - name: "secret" - description: "Secret Management API. Secret is stored securely inside merlin and can be used to run prediction job" - - name: "alert" - description: "Alert Management API." - - name: "environment" - description: "Environment is the infrastructure on which model deployments / batch predictions are running" - - name: "prediction_jobs" - description: "Batch prediction job API. Run a prediction as a batch job using model in Merlin" - - name: "log" - description: "Log API for accessing log in the container running a model deployment" -schemes: - - "http" +- name: project + description: Project Management API. Project is used to namespace model, secret, + and user access +- name: models + description: Model Management API. API to manage ML model in Merlin. +- name: version + description: Model Version Management API. Model version represents the iteration + of an ML model +- name: endpoint + description: Deployment Management API. Endpoint represent a deployment of a specific + model version +- name: model_endpoints + description: Serving Traffic Management API. API to manage traffic routing to a + running endpoint. +- name: secret + description: Secret Management API. Secret is stored securely inside merlin and + can be used to run prediction job +- name: alert + description: Alert Management API. +- name: environment + description: Environment is the infrastructure on which model deployments / batch + predictions are running +- name: prediction_jobs + description: Batch prediction job API. Run a prediction as a batch job using model + in Merlin +- name: log + description: Log API for accessing log in the container running a model deployment paths: "/environments": get: - tags: ["environment"] - summary: "List available environment" - description: "Environment can be filtered by optional `name` parameter" + tags: + - environment + summary: List available environment + description: Environment can be filtered by optional `name` parameter parameters: - - in: "query" - name: "name" - required: false - type: "string" + - name: name + in: query + schema: + type: string responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/Environment" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Environment" "/projects": get: - tags: ["project"] - summary: "List existing projects" - description: "Projects can be filtered by optional `name` parameter" + tags: + - project + summary: List existing projects + description: Projects can be filtered by optional `name` parameter parameters: - - in: "query" - name: "name" - required: false - type: "string" + - name: name + in: query + schema: + type: string responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/Project" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Project" post: - tags: ["project"] - summary: "Create new project" - parameters: - - in: "body" - name: "body" - description: "Project object that has to be added" - required: true - schema: - $ref: "#/definitions/Project" + tags: + - project + summary: Create new project + requestBody: + description: Project object that has to be added + content: + "*/*": + schema: + "$ref": "#/components/schemas/Project" + required: true responses: - 201: - description: "Created" - schema: - $ref: "#/definitions/Project" - 400: - description: "Invalid request format" - 409: - description: "Project with the same name already exists" + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/Project" + '400': + description: Invalid request format + content: {} + '409': + description: Project with the same name already exists + content: {} + x-codegen-request-body-name: body "/projects/{project_id}": get: - tags: ["project"] - summary: "Get project" + tags: + - project + summary: Get project parameters: - - in: "path" - name: "project_id" - description: "project id of the project to be retrieved" - type: "integer" - required: true + - name: project_id + in: path + description: project id of the project to be retrieved + required: true + schema: + type: integer responses: - 200: - description: "Ok" - schema: - $ref: "#/definitions/Project" - 404: - description: "Project Not Found" + '200': + description: Ok + content: + "*/*": + schema: + "$ref": "#/components/schemas/Project" + '404': + description: Project Not Found + content: {} put: - tags: ["project"] - summary: "Update project" + tags: + - project + summary: Update project parameters: - - in: "path" - name: "project_id" - description: "project id of the project to be updated" - type: "integer" - required: true - - in: "body" - name: "body" - description: "Project object that has to be updated" - required: true - schema: - $ref: "#/definitions/Project" + - name: project_id + in: path + description: project id of the project to be updated + required: true + schema: + type: integer + requestBody: + description: Project object that has to be updated + content: + "*/*": + schema: + "$ref": "#/components/schemas/Project" + required: true responses: - 200: - description: "Ok" - schema: - $ref: "#/definitions/Project" - 400: - description: "Invalid request format" + '200': + description: Ok + content: + "*/*": + schema: + "$ref": "#/components/schemas/Project" + '400': + description: Invalid request format + content: {} + x-codegen-request-body-name: body "/projects/{project_id}/models/{model_id}": get: - tags: ["models"] - summary: "Get model" + tags: + - models + summary: Get model parameters: - - in: "path" - name: "project_id" - description: "project id of the project to be retrieved" - type: "integer" - required: true - - in: "path" - name: "model_id" - description: "model id of the model to be retrieved" - type: "integer" - required: true + - name: project_id + in: path + description: project id of the project to be retrieved + required: true + schema: + type: integer + - name: model_id + in: path + description: model id of the model to be retrieved + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/Model" - 404: - description: "Project/Model with given id not found" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Model" + '404': + description: Project/Model with given id not found + content: {} delete: - tags: ["models"] - summary: "Delete model" + tags: + - models + summary: Delete model parameters: - - in: "path" - name: "project_id" - description: "project id of the project to be deleted" - type: "integer" - required: true - - in: "path" - name: "model_id" - description: "model id of the model to be deleted" - type: "integer" - required: true + - name: project_id + in: path + description: project id of the project to be deleted + required: true + schema: + type: integer + - name: model_id + in: path + description: model id of the model to be deleted + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "integer" - 404: - description: "Project/Model with given id not found" - 400: - description: "There are other entity still using this model (model version endpoint / model endpoint / prediction jobs)" - 500: - description: "Deletion failed" - + '200': + description: OK + content: + "*/*": + schema: + type: integer + '400': + description: There are other entity still using this model (model version + endpoint / model endpoint / prediction jobs) + content: {} + '404': + description: Project/Model with given id not found + content: {} + '500': + description: Deletion failed + content: {} "/projects/{project_id}/models": get: - tags: ["models"] - summary: "List existing models" + tags: + - models + summary: List existing models parameters: - - in: "path" - name: "project_id" - description: "Filter list of models by specific `project_id`" - type: "integer" - required: true - - in: "query" - name: "name" - description: "Filter list of models by specific models `name`" - type: "string" - required: false + - name: project_id + in: path + description: Filter list of models by specific `project_id` + required: true + schema: + type: integer + - name: name + in: query + description: Filter list of models by specific models `name` + schema: + type: string responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/Model" - 404: - description: "Project with given `project_id` not found" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Model" + '404': + description: Project with given `project_id` not found + content: {} post: - tags: ["models"] - summary: "Register a new models" + tags: + - models + summary: Register a new models parameters: - - in: "path" - name: "project_id" - description: "Create new model in a specific `project_id`" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/Model" + - name: project_id + in: path + description: Create new model in a specific `project_id` + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/Model" + required: false responses: - 201: - description: "Created" - schema: - $ref: "#/definitions/Model" - 400: - description: "Invalid request format" - 404: - description: "Project with given `project_id` not found" + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/Model" + '400': + description: Invalid request format + content: {} + '404': + description: Project with given `project_id` not found + content: {} + x-codegen-request-body-name: body "/projects/{project_id}/jobs": get: - tags: ["prediction_jobs"] - summary: "List all prediction jobs created using the model" + tags: + - prediction_jobs + summary: List all prediction jobs created using the model parameters: - - in: "path" - name: "project_id" - type: "integer" - required: true - - in: "query" - name: "id" - type: "integer" - - in: "query" - name: "name" - type: "string" - - in: "query" - name: "model_id" - type: "integer" - - in: "query" - name: "version_id" - type: "integer" - - in: "query" - name: "status" - type: "string" - - in: "query" - name: "error" - type: "string" + - name: project_id + in: path + required: true + schema: + type: integer + - name: id + in: query + schema: + type: integer + - name: name + in: query + schema: + type: string + - name: model_id + in: query + schema: + type: integer + - name: version_id + in: query + schema: + type: integer + - name: status + in: query + schema: + type: string + - name: error + in: query + schema: + type: string responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/PredictionJob" - 404: - description: "Project with given `project_id` not found" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/PredictionJob" + '404': + description: Project with given `project_id` not found + content: {} "/models/{model_id}/versions": get: - tags: ["version"] - summary: "List versions of the models" + tags: + - version + summary: List versions of the models parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "query" - name: "limit" - type: "integer" - required: false - - in: "query" - name: "cursor" - type: "string" - required: false - - in: "query" - name: "search" - type: "string" - required: false - description: | - Search query to filter the model versions. These searches are currently supported: - - Search by "mlflow_run_id" e.g. `?search=cfca7716b45f4b149479630a98332a13` - - Search by "environment_name" e.g `?search=environment_name:myenv` - - Search by "labels" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` - - Search by "environment_name" and "labels" e.g. - `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` + - name: model_id + in: path + required: true + schema: + type: integer + - name: limit + in: query + schema: + type: integer + - name: cursor + in: query + schema: + type: string + - name: search + in: query + description: | + Search query to filter the model versions. These searches are currently supported: + - Search by "mlflow_run_id" e.g. `?search=cfca7716b45f4b149479630a98332a13` + - Search by "environment_name" e.g `?search=environment_name:myenv` + - Search by "labels" e.g. `?search=labels:app IN (nginx,postgres), country in (SG)` + - Search by "environment_name" and "labels" e.g. + `?search=environment_name:myenv labels:app IN (nginx,postgres), country in (SG)` + schema: + type: string responses: - 200: - description: "OK" + '200': + description: OK headers: Next-Cursor: - type: string - description: "Pointer to used for next page request" - schema: - type: "array" - items: - $ref: "#/definitions/Version" - 404: - description: "Model with given `model_id` not found" + description: Pointer to used for next page request + schema: + type: string + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Version" + '404': + description: Model with given `model_id` not found + content: {} post: - tags: ["version"] - summary: "Log a new version of the models" + tags: + - version + summary: Log a new version of the models parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/Version" + - name: model_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/Version" + required: false responses: - 200: - description: "Created" - schema: - $ref: "#/definitions/Version" + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/Version" + x-codegen-request-body-name: body "/models/{model_id}/versions/{version_id}": get: - tags: ["version"] - summary: "Get version by ID from model" + tags: + - version + summary: Get version by ID from model parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/Version" - 404: - description: "Model with given `model_id` not found" - patch: - tags: ["version"] - summary: "Patch the version " + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/Version" + '404': + description: Model with given `model_id` not found + content: {} + delete: + tags: + - version + summary: Delete version by ID from model parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/Version" + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - 400: - description: "Invalid request format" - 404: - description: "Version with given `version_id` not found" - delete: - tags: ["version"] - summary: "Delete version by ID from model" + '200': + description: OK + content: + "*/*": + schema: + type: integer + '400': + description: There are other entity still using this model (model version + endpoint / prediction jobs) + content: {} + '404': + description: Model with given `model_id` not found + content: {} + '500': + description: Deletion failed + content: {} + patch: + tags: + - version + summary: 'Patch the version ' parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/Version" + required: false responses: - 200: - description: "OK" - schema: - type: "integer" - 404: - description: "Model with given `model_id` not found" - 400: - description: "There are other entity still using this model (model version endpoint / prediction jobs)" - 500: - description: "Deletion failed" + '200': + description: OK + content: {} + '400': + description: Invalid request format + content: {} + '404': + description: Version with given `version_id` not found + content: {} + x-codegen-request-body-name: body "/models/{model_id}/versions/{version_id}/endpoint": get: - tags: ["endpoint"] - summary: "List all endpoint of a model version" + tags: + - endpoint + summary: List all endpoint of a model version parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/VersionEndpoint" - 404: - description: "Version with given `version_id` not found" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/VersionEndpoint" + '404': + description: Version with given `version_id` not found + content: {} post: - tags: ["endpoint"] - summary: "Deploy specific version of the models" + tags: + - endpoint + summary: Deploy specific version of the models parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/VersionEndpoint" + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/VersionEndpoint" + required: false responses: - 201: - description: "Created" - schema: - $ref: "#/definitions/VersionEndpoint" - 404: - description: "Version with given `version_id` not found" + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/VersionEndpoint" + '404': + description: Version with given `version_id` not found + content: {} + x-codegen-request-body-name: body "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}": get: - tags: ["endpoint"] - summary: "Get version endpoint resource" + tags: + - endpoint + summary: Get version endpoint resource parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: endpoint_id + in: path + required: true + schema: + type: string responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/VersionEndpoint" - 404: - description: "Version endpoint with given `endpoint_id` not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/VersionEndpoint" + '404': + description: Version endpoint with given `endpoint_id` not found + content: {} put: - tags: ["endpoint"] - summary: "Modify version endpoint, this API will redeploy the associated deployment" + tags: + - endpoint + summary: Modify version endpoint, this API will redeploy the associated deployment parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "endpoint_id" - type: "string" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/VersionEndpoint" + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: endpoint_id + in: path + required: true + schema: + type: string + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/VersionEndpoint" + required: false responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/VersionEndpoint" - 404: - description: "Version endpoint with given `endpoint_id` not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/VersionEndpoint" + '404': + description: Version endpoint with given `endpoint_id` not found + content: {} + x-codegen-request-body-name: body delete: - tags: ["endpoint"] - summary: "Undeploy the specified model version deployment" + tags: + - endpoint + summary: Undeploy the specified model version deployment parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: endpoint_id + in: path + required: true + schema: + type: string responses: - 200: - description: "OK" - 404: - description: "Version endpoint with given `endpoint_id` not found" + '200': + description: OK + content: {} + '404': + description: Version endpoint with given `endpoint_id` not found + content: {} "/models/{model_id}/versions/{version_id}/endpoint/{endpoint_id}/containers": get: - tags: ["endpoint"] - summary: "Get all container belong to a version endpoint" + tags: + - endpoint + summary: Get all container belong to a version endpoint parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: endpoint_id + in: path + required: true + schema: + type: string responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/Container" - 404: - description: "Version endpoint with given `endpoint_id` not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/Container" + '404': + description: Version endpoint with given `endpoint_id` not found + content: {} "/projects/{project_id}/model_endpoints": get: - tags: ["model_endpoints"] - summary: "List existing model endpoints for all models in particular project" + tags: + - model_endpoints + summary: List existing model endpoints for all models in particular project parameters: - - in: "path" - name: "project_id" - description: "Filter list of model endpoints by specific `project_id`" - type: "integer" - required: true - - in: "query" - name: "region" - description: "Filter list of model endpoints by specific environment's `region`" - type: "string" - required: false + - name: project_id + in: path + description: Filter list of model endpoints by specific `project_id` + required: true + schema: + type: integer + - name: region + in: query + description: Filter list of model endpoints by specific environment's `region` + schema: + type: string responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/ModelEndpoint" - + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/ModelEndpoint" "/models/{model_id}/endpoints": get: - tags: ["model_endpoints"] - summary: "List model endpoint" + tags: + - model_endpoints + summary: List model endpoint parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/ModelEndpoint" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/ModelEndpoint" post: - tags: ["model_endpoints"] - summary: "Create a model endpoint" + tags: + - model_endpoints + summary: Create a model endpoint parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "body" - name: "body" - description: "Model endpoint object that has to be added" - required: true - schema: - $ref: "#/definitions/ModelEndpoint" + - name: model_id + in: path + required: true + schema: + type: integer + requestBody: + description: Model endpoint object that has to be added + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpoint" + required: true responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/ModelEndpoint" - + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpoint" + x-codegen-request-body-name: body "/models/{model_id}/endpoints/{model_endpoint_id}": get: - tags: ["model_endpoints"] - summary: "Get a model endpoint" + tags: + - model_endpoints + summary: Get a model endpoint parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/ModelEndpoint" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpoint" put: - tags: ["model_endpoints"] - summary: "Update model endpoint data. Mainly used to update its rule." + tags: + - model_endpoints + summary: Update model endpoint data. Mainly used to update its rule. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/ModelEndpoint" + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpoint" + required: false responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/ModelEndpoint" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpoint" + x-codegen-request-body-name: body delete: - tags: ["model_endpoints"] - summary: "Stop serving traffic to the model endpoint, then delete it." + tags: + - model_endpoints + summary: Stop serving traffic to the model endpoint, then delete it. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - + '200': + description: OK + content: {} "/alerts/teams": get: - tags: ["models", "alert"] - summary: "Lists teams for alert notification channel." + tags: + - models + - alert + summary: Lists teams for alert notification channel. responses: - 200: - description: "OK" - schema: - type: "array" - items: - type: "string" - + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + type: string "/models/{model_id}/alerts": get: - tags: ["models", "alert"] - summary: "Lists alerts for given model." + tags: + - models + - alert + summary: Lists alerts for given model. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/ModelEndpointAlert" - + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/ModelEndpointAlert" "/models/{model_id}/endpoints/{model_endpoint_id}/alert": get: - tags: ["models", "alert"] - summary: "Gets alert for given model endpoint." + tags: + - models + - alert + summary: Gets alert for given model endpoint. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: string responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/ModelEndpointAlert" - post: - tags: ["models", "alert"] - summary: "Creates alert for given model endpoint." + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpointAlert" + put: + tags: + - models + - alert + summary: Creates alert for given model endpoint. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/ModelEndpointAlert" + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: string + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpointAlert" + required: false responses: - 201: - description: "Created" - put: - tags: ["models", "alert"] - summary: "Creates alert for given model endpoint." + '200': + description: Ok + content: {} + x-codegen-request-body-name: body + post: + tags: + - models + - alert + summary: Creates alert for given model endpoint. parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "model_endpoint_id" - type: "string" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/ModelEndpointAlert" + - name: model_id + in: path + required: true + schema: + type: integer + - name: model_endpoint_id + in: path + required: true + schema: + type: string + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelEndpointAlert" + required: false responses: - 200: - description: "Ok" - + '201': + description: Created + content: {} + x-codegen-request-body-name: body "/logs": get: - tags: ["log"] - summary: "Retrieve log from a container" + tags: + - log + summary: Retrieve log from a container parameters: - - in: "query" - name: "project_name" - type: "string" - required: false - - in: "query" - name: "model_id" - type: "string" - required: false - - in: "query" - name: "model_name" - type: "string" - required: false - - in: "query" - name: "version_id" - type: "string" - required: false - - in: "query" - name: "prediction_job_id" - type: "string" - required: false - - in: "query" - name: "cluster" - type: "string" - required: true - - in: "query" - name: "namespace" - type: "string" - required: true - - in: "query" - name: "component_type" - type: "string" - required: true + - name: project_name + in: query + schema: + type: string + - name: model_id + in: query + schema: + type: string + - name: model_name + in: query + schema: + type: string + - name: version_id + in: query + schema: + type: string + - name: prediction_job_id + in: query + schema: + type: string + - name: cluster + in: query + required: true + schema: + type: string + - name: namespace + in: query + required: true + schema: + type: string + - name: component_type + in: query + required: true + schema: + type: string enum: - - image_builder - - model - - transformer - - batch_job_driver - - batch_job_executor - - in: "query" - name: "container_name" - type: "string" - required: false - - in: "query" - name: "prefix" - type: "string" - required: false - - in: "query" - name: "follow" - type: "string" - required: false - - in: "query" - name: "previous" - type: "string" - required: false - - in: "query" - name: "since_seconds" - type: "string" - required: false - - in: "query" - name: "since_time" - type: "string" - required: false - - in: "query" - name: "timestamps" - type: "string" - required: false - - in: "query" - name: "tail_lines" - type: "string" - required: false - - in: "query" - name: "limit_bytes" - type: "string" - required: false + - image_builder + - model + - transformer + - batch_job_driver + - batch_job_executor + - name: container_name + in: query + schema: + type: string + - name: prefix + in: query + schema: + type: string + - name: follow + in: query + schema: + type: string + - name: previous + in: query + schema: + type: string + - name: since_seconds + in: query + schema: + type: string + - name: since_time + in: query + schema: + type: string + - name: timestamps + in: query + schema: + type: string + - name: tail_lines + in: query + schema: + type: string + - name: limit_bytes + in: query + schema: + type: string responses: - 200: - description: "OK" - content: - text/plain: - schema: - type: "string" + '200': + description: OK + content: {} "/projects/{project_id}/secrets": - post: - tags: ["secret"] - summary: "Create secret" + get: + tags: + - secret + summary: List secret parameters: - - in: "path" - name: "project_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/Secret" + - name: project_id + in: path + required: true + schema: + type: integer responses: - 201: - description: "Created" - schema: - $ref: "#/definitions/Secret" - get: - tags: ["secret"] - summary: "List secret" + '200': + description: Ok + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/Secret" + post: + tags: + - secret + summary: Create secret parameters: - - in: "path" - name: "project_id" - type: "integer" - required: true + - name: project_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/Secret" + required: false responses: - 201: - description: "Ok" - schema: - type: "array" - items: - $ref: "#/definitions/Secret" - + '201': + description: Created + content: + "*/*": + schema: + "$ref": "#/components/schemas/Secret" + x-codegen-request-body-name: body "/projects/{project_id}/secrets/{secret_id}": - patch: - tags: ["secret"] - summary: "Update secret" + delete: + tags: + - secret + summary: Delete secret parameters: - - in: "path" - name: "project_id" - type: "integer" - required: true - - in: "path" - name: "secret_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/Secret" + - name: project_id + in: path + required: true + schema: + type: integer + - name: secret_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "Updated" - schema: - $ref: "#/definitions/Secret" - delete: - tags: ["secret"] - summary: "Delete secret" + '204': + description: No content + content: {} + patch: + tags: + - secret + summary: Update secret parameters: - - in: "path" - name: "project_id" - type: "integer" - required: true - - in: "path" - name: "secret_id" - type: "integer" - required: true + - name: project_id + in: path + required: true + schema: + type: integer + - name: secret_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/Secret" + required: false responses: - 204: - description: "No content" + '200': + description: Updated + content: + "*/*": + schema: + "$ref": "#/components/schemas/Secret" + x-codegen-request-body-name: body "/models/{model_id}/versions/{version_id}/jobs": get: - tags: ["prediction_jobs"] - summary: "List all prediction jobs of a model version" + tags: + - prediction_jobs + summary: List all prediction jobs of a model version parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - type: "array" - items: - $ref: "#/definitions/PredictionJob" - 404: - description: "Version with given `version_id` not found" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/PredictionJob" + '404': + description: Version with given `version_id` not found + content: {} post: - tags: ["prediction_jobs"] - summary: "Create a prediction job from the given model version" + tags: + - prediction_jobs + summary: Create a prediction job from the given model version parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "body" - name: "body" - schema: - $ref: "#/definitions/PredictionJob" + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/PredictionJob" + required: false responses: - 201: - description: "Created" - schema: - $ref: "#/definitions/PredictionJob" - 404: - description: "Version with given `version_id` not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/PredictionJob" + '404': + description: Version with given `version_id` not found + content: {} + x-codegen-request-body-name: body "/models/{model_id}/versions/{version_id}/jobs/{job_id}": get: - tags: ["prediction_jobs"] - summary: "Get prediction jobs with given id" + tags: + - prediction_jobs + summary: Get prediction jobs with given id parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "job_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: job_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/PredictionJob" - 404: - description: "Prediction job with given ID is not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/PredictionJob" + '404': + description: Prediction job with given ID is not found + content: {} "/models/{model_id}/versions/{version_id}/jobs/{job_id}/stop": put: - tags: ["prediction_jobs"] - summary: "Stop prediction jobs with given id" + tags: + - prediction_jobs + summary: Stop prediction jobs with given id parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "job_id" - type: "integer" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: job_id + in: path + required: true + schema: + type: integer responses: - 204: - description: "No content" - 404: - description: "Prediction job with given ID is not found" + '204': + description: No content + content: {} + '404': + description: Prediction job with given ID is not found + content: {} "/models/{model_id}/versions/{version_id}/jobs/{job_id}/containers": get: - tags: ["prediction_jobs"] - summary: "Get all container belong to a prediction job" + tags: + - prediction_jobs + summary: Get all container belong to a prediction job parameters: - - in: "path" - name: "model_id" - type: "integer" - required: true - - in: "path" - name: "version_id" - type: "integer" - required: true - - in: "path" - name: "job_id" - type: "string" - required: true + - name: model_id + in: path + required: true + schema: + type: integer + - name: version_id + in: path + required: true + schema: + type: integer + - name: job_id + in: path + required: true + schema: + type: string responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/Container" - 404: - description: "Version endpoint with given `endpoint_id` not found" + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/Container" + '404': + description: Version endpoint with given `endpoint_id` not found + content: {} "/standard_transformer/simulate": post: - tags: ["standard_transformer"] - summary: "Simulate standard transformer" + tags: + - standard_transformer + summary: Simulate standard transformer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/StandardTransformerSimulationRequest" + required: false + responses: + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/StandardTransformerSimulationResponse" + x-codegen-request-body-name: body + "/models/{model_id}/schemas": + get: + summary: List all of the model schemas + tags: + - model_schema parameters: - - in: "body" - name: "body" - schema: - $ref: "#/definitions/StandardTransformerSimulationRequest" + - name: model_id + in: path + required: true + schema: + type: integer responses: - 200: - description: "OK" - schema: - $ref: "#/definitions/StandardTransformerSimulationResponse" - -definitions: - EndpointStatus: - type: "string" - enum: - - "pending" - - "running" - - "serving" - - "failed" - - "terminated" + '200': + description: OK + content: + "*/*": + schema: + type: array + items: + "$ref": "#/components/schemas/ModelSchema" + put: + summary: Creating new schemas for a model + tags: + - model_schema + parameters: + - name: model_id + in: path + required: true + schema: + type: integer + requestBody: + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelSchema" + required: false + responses: + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelSchema" + x-codegen-request-body-name: body + "/models/{model_id}/schemas/{schema_id}": + get: + summary: Get detail of the schema + tags: + - model_schema + parameters: + - name: model_id + in: path + required: true + schema: + type: integer + - name: schema_id + in: path + required: true + schema: + type: integer + responses: + '200': + description: OK + content: + "*/*": + schema: + "$ref": "#/components/schemas/ModelSchema" + delete: + summary: Delete schema + tags: + - model_schema + parameters: + - name: model_id + in: path + required: true + schema: + type: integer + - name: schema_id + in: path + required: true + schema: + type: integer + responses: + '204': + description: No Content + +components: + schemas: + ModelSchema: + type: object + required: + - spec + properties: + id: + type: integer + format: int32 + model_id: + type: integer + format: int32 + spec: + $ref: '#/components/schemas/SchemaSpec' + SchemaSpec: + type: object + required: + - prediction_id_column + - model_prediction_output + - feature_types + properties: + prediction_id_column: + type: string + model_prediction_output: + $ref : '#/components/schemas/ModelPredictionOutput' + tag_columns: + type: array + items: + type: string + feature_types: + type: object + additionalProperties: + $ref : '#/components/schemas/ValueType' + ValueType: + type: string + enum: + - float64 + - int64 + - boolean + - string + ModelPredictionOutputClass: + type: string + enum: + - BinaryClassificationOutput + - RankingOutput + - RegressionOutput + ModelPredictionOutput: + type: object + discriminator: + propertyName: output_class + oneOf: + - $ref: '#/components/schemas/BinaryClassificationOutput' + - $ref: '#/components/schemas/RankingOutput' + - $ref: '#/components/schemas/RegressionOutput' + BinaryClassificationOutput: + type: object + required: + - prediction_score_column + - positive_class_label + - negative_class_label + properties: + prediction_score_column: + type: string + actual_label_column: + type: string + positive_class_label: + type: string + negative_class_label: + type: string + score_threshold: + type: number + output_class: + $ref: '#/components/schemas/ModelPredictionOutputClass' - Environment: - type: "object" - required: + RankingOutput: + type: object + required: + - rank_score_column + - prediction_group_id_column + properties: + rank_score_column: + type: string + prediction_group_id_column: + type: string + relevance_score_column: + type: string + output_class: + $ref: '#/components/schemas/ModelPredictionOutputClass' + RegressionOutput: + type: object + required: + - prediction_score_column + properties: + prediction_score_column: + type: string + actual_score_column: + type: string + output_class: + $ref: '#/components/schemas/ModelPredictionOutputClass' + EndpointStatus: + type: string + enum: + - pending + - running + - serving + - failed + - terminated + Environment: + required: - name - properties: - id: - type: "integer" - format: "int32" - name: - type: "string" - cluster: - type: "string" - is_default: - type: "boolean" - region: - type: "string" - gcp_project: - type: "string" - default_resource_request: - $ref: "#/definitions/ResourceRequest" - default_transformer_resource_request: - $ref: "#/definitions/ResourceRequest" - default_prediction_job_resource_request: - $ref: "#/definitions/PredictionJobResourceRequest" - gpus: - type: "array" - items: - $ref: "#/definitions/GPUConfig" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - Project: - type: "object" - required: + - cluster + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + cluster: + type: string + is_default: + type: boolean + region: + type: string + gcp_project: + type: string + default_resource_request: + "$ref": "#/components/schemas/ResourceRequest" + default_transformer_resource_request: + "$ref": "#/components/schemas/ResourceRequest" + default_prediction_job_resource_request: + "$ref": "#/components/schemas/PredictionJobResourceRequest" + gpus: + type: array + items: + "$ref": "#/components/schemas/GPUConfig" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + Project: + required: + - id - name - properties: - id: - type: "integer" - format: "int32" - name: - type: "string" - mlflow_tracking_url: - type: "string" - administrators: - type: "array" - items: - type: "string" - readers: - type: "array" - items: - type: "string" - team: - type: "string" - stream: - type: "string" - labels: - type: "array" - items: - $ref: "#/definitions/Label" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - Model: - type: "object" - properties: - id: - type: "integer" - format: "int32" - project_id: - type: "integer" - format: "int32" - mlflow_experiment_id: - type: "integer" - format: "int32" - name: - type: "string" - type: - type: "string" - description: "Model type" - enum: - - "xgboost" - - "tensorflow" - - "sklearn" - - "pytorch" - - "pyfunc" - - "pyfunc_v2" - - "pyfunc_v3" - - "custom" - mlflow_url: - type: "string" - endpoints: - type: "array" - items: - $ref: "#/definitions/ModelEndpoint" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - ModelEndpoint: - type: "object" - properties: - id: - type: "integer" - format: "int32" - model_id: - type: "integer" - format: "int32" - model: - $ref: "#/definitions/Model" - status: - $ref: "#/definitions/EndpointStatus" - url: - type: "string" - format: "hostname" - rule: - $ref: "#/definitions/ModelEndpointRule" - environment_name: - type: "string" - environment: - $ref: "#/definitions/Environment" - protocol: - $ref: "#/definitions/Protocol" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - ModelEndpointRule: - type: "object" - properties: - destinations: - type: "array" - items: - $ref: "#/definitions/ModelEndpointRuleDestination" - mirror: - $ref: "#/definitions/VersionEndpoint" - - ModelEndpointRuleDestination: - type: "object" - properties: - version_endpoint_id: - type: "string" - format: "uuid" - version_endpoint: - $ref: "#/definitions/VersionEndpoint" - weight: - type: "integer" - - ModelEndpointAlert: - type: "object" - properties: - model_id: - type: "integer" - model_endpoint_id: - type: "integer" - environment_name: - type: "string" - team_name: - type: "string" - alert_conditions: - type: "array" - items: - $ref: "#/definitions/ModelEndpointAlertCondition" - - ModelEndpointAlertCondition: - type: "object" - properties: - enabled: - type: "boolean" - metric_type: - $ref: "#/definitions/AlertConditionMetricType" - severity: - $ref: "#/definitions/AlertConditionSeverity" - target: - type: "number" - percentile: - type: "number" - unit: - type: "string" - - AlertConditionMetricType: - type: "string" - enum: - - "throughput" - - "latency" - - "error_rate" - - "cpu" - - "memory" - - AlertConditionSeverity: - type: "string" - enum: - - "WARNING" - - "CRITICAL" - - Version: - type: "object" - properties: - id: - type: "integer" - format: "int32" - model_id: - type: "integer" - format: "int32" - mlflow_run_id: - type: "string" - mlflow_url: - type: "string" - artifact_uri: - type: "string" - format: "hostname" - endpoints: - type: "array" - items: - $ref: "#/definitions/VersionEndpoint" + type: object properties: - type: "object" - labels: - type: "object" - additionalProperties: - type: "string" - custom_predictor: - $ref: "#/definitions/CustomPredictor" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - python_version: - type: "string" - - CustomPredictor: - type: "object" - properties: - image: - type: "string" - command: - type: "string" - args: - type: "string" - - VersionEndpoint: - type: "object" - properties: - id: - type: "string" - format: "uuid" - version_id: - type: "integer" - format: "int32" - status: - $ref: "#/definitions/EndpointStatus" - url: - type: "string" - format: "hostname" - service_name: - type: "string" - format: "hostname" - environment_name: - type: "string" - environment: - $ref: "#/definitions/Environment" - monitoring_url: - type: "string" - format: "hostname" - message: - type: "string" - resource_request: - $ref: "#/definitions/ResourceRequest" - image_builder_resource_request: - $ref: "#/definitions/ResourceRequest" - env_vars: - type: "array" - items: - $ref: "#/definitions/EnvVar" - transformer: - $ref: "#/definitions/Transformer" - logger: - $ref: "#/definitions/Logger" - deployment_mode: - $ref: "#/definitions/DeploymentMode" - autoscaling_policy: - $ref: "#/definitions/AutoscalingPolicy" - protocol: - $ref: "#/definitions/Protocol" - enable_model_observability: - type: "boolean" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - Logger: - type: "object" - properties: - model: - $ref: "#/definitions/LoggerConfig" - transformer: - $ref: "#/definitions/LoggerConfig" - prediction: - $ref: "#/definitions/PredictionLoggerConfig" - - LoggerConfig: - type: "object" - properties: - enabled: - type: "boolean" - mode: - $ref: "#/definitions/LoggerMode" - - PredictionLoggerConfig: - type: "object" - properties: - enabled: - type: "boolean" - raw_features_table: - type: "string" - entities_table: - type: "string" - - LoggerMode: - type: "string" - enum: - - "all" - - "request" - - "response" - - Transformer: - type: "object" - properties: - id: - type: "string" - enabled: - type: "boolean" - transformer_type: - type: "string" - image: - type: "string" - command: - type: "string" - args: - type: "string" - resource_request: - $ref: "#/definitions/ResourceRequest" - env_vars: - type: "array" - items: - $ref: "#/definitions/EnvVar" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - DeploymentMode: - type: string - enum: + id: + type: integer + format: int32 + name: + type: string + mlflow_tracking_url: + type: string + administrators: + type: array + items: + type: string + readers: + type: array + items: + type: string + team: + type: string + stream: + type: string + labels: + type: array + items: + "$ref": "#/components/schemas/Label" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + Model: + type: object + required: + - name + properties: + id: + type: integer + format: int32 + project_id: + type: integer + format: int32 + mlflow_experiment_id: + type: integer + format: int32 + name: + type: string + type: + type: string + description: Model type + enum: + - xgboost + - tensorflow + - sklearn + - pytorch + - pyfunc + - pyfunc_v2 + - pyfunc_v3 + - custom + mlflow_url: + type: string + endpoints: + type: array + items: + "$ref": "#/components/schemas/ModelEndpoint" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + ModelEndpoint: + type: object + properties: + id: + type: integer + format: int32 + model_id: + type: integer + format: int32 + model: + "$ref": "#/components/schemas/Model" + status: + "$ref": "#/components/schemas/EndpointStatus" + url: + type: string + format: hostname + rule: + "$ref": "#/components/schemas/ModelEndpointRule" + environment_name: + type: string + environment: + "$ref": "#/components/schemas/Environment" + protocol: + "$ref": "#/components/schemas/Protocol" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + ModelEndpointRule: + type: object + properties: + destinations: + type: array + items: + "$ref": "#/components/schemas/ModelEndpointRuleDestination" + mirror: + "$ref": "#/components/schemas/VersionEndpoint" + ModelEndpointRuleDestination: + type: object + properties: + version_endpoint_id: + type: string + format: uuid + version_endpoint: + "$ref": "#/components/schemas/VersionEndpoint" + weight: + type: integer + ModelEndpointAlert: + type: object + properties: + model_id: + type: integer + model_endpoint_id: + type: integer + environment_name: + type: string + team_name: + type: string + alert_conditions: + type: array + items: + "$ref": "#/components/schemas/ModelEndpointAlertCondition" + ModelEndpointAlertCondition: + type: object + properties: + enabled: + type: boolean + metric_type: + "$ref": "#/components/schemas/AlertConditionMetricType" + severity: + "$ref": "#/components/schemas/AlertConditionSeverity" + target: + type: number + percentile: + type: number + unit: + type: string + AlertConditionMetricType: + type: string + enum: + - throughput + - latency + - error_rate + - cpu + - memory + AlertConditionSeverity: + type: string + enum: + - WARNING + - CRITICAL + Version: + type: object + properties: + id: + type: integer + format: int32 + model_id: + type: integer + format: int32 + mlflow_run_id: + type: string + mlflow_url: + type: string + artifact_uri: + type: string + format: hostname + endpoints: + type: array + items: + "$ref": "#/components/schemas/VersionEndpoint" + properties: + type: object + properties: {} + labels: + type: object + additionalProperties: + type: string + custom_predictor: + "$ref": "#/components/schemas/CustomPredictor" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + python_version: + type: string + model_schema: + "$ref": "#/components/schemas/ModelSchema" + CustomPredictor: + type: object + properties: + image: + type: string + command: + type: string + args: + type: string + VersionEndpoint: + type: object + properties: + id: + type: string + format: uuid + version_id: + type: integer + format: int32 + status: + "$ref": "#/components/schemas/EndpointStatus" + url: + type: string + format: hostname + service_name: + type: string + format: hostname + environment_name: + type: string + environment: + "$ref": "#/components/schemas/Environment" + monitoring_url: + type: string + format: hostname + message: + type: string + resource_request: + "$ref": "#/components/schemas/ResourceRequest" + image_builder_resource_request: + "$ref": "#/components/schemas/ResourceRequest" + env_vars: + type: array + items: + "$ref": "#/components/schemas/EnvVar" + transformer: + "$ref": "#/components/schemas/Transformer" + logger: + "$ref": "#/components/schemas/Logger" + deployment_mode: + "$ref": "#/components/schemas/DeploymentMode" + autoscaling_policy: + "$ref": "#/components/schemas/AutoscalingPolicy" + protocol: + "$ref": "#/components/schemas/Protocol" + enable_model_observability: + type: boolean + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + Logger: + type: object + properties: + model: + "$ref": "#/components/schemas/LoggerConfig" + transformer: + "$ref": "#/components/schemas/LoggerConfig" + prediction: + "$ref": "#/components/schemas/PredictionLoggerConfig" + LoggerConfig: + type: object + required: + - enabled + - mode + properties: + enabled: + type: boolean + mode: + "$ref": "#/components/schemas/LoggerMode" + PredictionLoggerConfig: + type: object + required: + - enabled + properties: + enabled: + type: boolean + raw_features_table: + type: string + entities_table: + type: string + LoggerMode: + type: string + enum: + - all + - request + - response + Transformer: + type: object + properties: + id: + type: string + enabled: + type: boolean + transformer_type: + type: string + image: + type: string + command: + type: string + args: + type: string + resource_request: + "$ref": "#/components/schemas/ResourceRequest" + env_vars: + type: array + items: + "$ref": "#/components/schemas/EnvVar" + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + DeploymentMode: + type: string + default: serverless + enum: - serverless - raw_deployment - default: serverless - - Container: - type: "object" - properties: - name: - type: "string" - pod_name: - type: "string" - component_type: - type: "string" - enum: + Container: + type: object + properties: + name: + type: string + pod_name: + type: string + component_type: + type: string + enum: - image_builder - model - transformer - batch_job_driver - batch_job_executor - namespace: - type: "string" - cluster: - type: "string" - gcp_project: - type: "string" - version_endpoint_id: - type: "integer" - format: "int32" - - ResourceRequest: - type: "object" - properties: - min_replica: - type: "integer" - max_replica: - type: "integer" - cpu_request: - type: "string" - memory_request: - type: "string" - gpu_name: - type: "string" - gpu_request: - type: "string" - - AutoscalingPolicy: - type: "object" - properties: - metrics_type: - $ref: "#/definitions/MetricsType" - target_value: - type: "number" - - MetricsType: - type: "string" - enum: - - "concurrency" - - "cpu_utilization" - - "memory_utilization" - - "rps" - - EnvVar: - type: "object" - properties: - name: - type: "string" - value: - type: "string" - - Label: - type: "object" - properties: - key: - type: "string" - value: - type: "string" - - Secret: - type: "object" - properties: - id: - type: "integer" - format: "int32" - name: - type: "string" - data: - type: "string" - - PredictionJob: - type: "object" - properties: - id: - type: "integer" - format: "int32" - name: - type: "string" - version_id: - type: "integer" - format: "int32" - model_id: - type: "integer" - format: "int32" - project_id: - type: "integer" - format: "int32" - environment_name: - type: "string" - environment: - $ref: "#/definitions/Environment" - config: - $ref: "#/definitions/Config" - status: - type: "string" - error: - type: "string" - created_at: - type: "string" - format: "date-time" - updated_at: - type: "string" - format: "date-time" - - Config: - type: "object" - properties: - job_config: - $ref: "#/definitions/PredictionJobConfig" - image_ref: - type: "string" - service_account_name: - type: "string" - resource_request: - $ref: "#/definitions/PredictionJobResourceRequest" - image_builder_resource_request: - $ref: "#/definitions/ResourceRequest" - env_vars: - type: "array" - items: - $ref: "#/definitions/EnvVar" - - GPUConfig: - type: "object" - properties: - name: - type: "string" - values: - type: "array" - items: - type: string - resource_type: - type: "string" - node_selector: - type: "object" - additionalProperties: - type: "string" - tolerations: - type: "array" - items: - $ref: "#/definitions/GPUToleration" - min_monthly_cost_per_gpu: - type: "number" - max_monthly_cost_per_gpu: - type: "number" - - GPUToleration: - type: "object" - properties: - key: - type: "string" - operator: - type: "string" - value: - type: "string" - effect: - type: "string" - toleration_seconds: - type: "integer" - format: "int64" - - PredictionJobResourceRequest: - type: "object" - properties: - driver_cpu_request: - type: "string" - driver_memory_request: - type: "string" - executor_cpu_request: - type: "string" - executor_memory_request: - type: "string" - executor_replica: - type: "integer" - format: "int32" - - PredictionJobConfig: - type: object - properties: - version: - type: string - kind: - type: string - name: - type: string - bigquery_source: - type: object - properties: - table: + namespace: + type: string + cluster: + type: string + gcp_project: + type: string + version_endpoint_id: + type: integer + format: int32 + ResourceRequest: + type: object + properties: + min_replica: + type: integer + max_replica: + type: integer + cpu_request: + type: string + memory_request: + type: string + gpu_name: + type: string + gpu_request: + type: string + AutoscalingPolicy: + type: object + required: + - metrics_type + - target_value + properties: + metrics_type: + "$ref": "#/components/schemas/MetricsType" + target_value: + type: number + MetricsType: + type: string + enum: + - concurrency + - cpu_utilization + - memory_utilization + - rps + EnvVar: + type: object + properties: + name: + type: string + value: + type: string + Label: + type: object + properties: + key: + type: string + value: + type: string + Secret: + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + data: + type: string + PredictionJob: + type: object + properties: + id: + type: integer + format: int32 + name: + type: string + version_id: + type: integer + format: int32 + model_id: + type: integer + format: int32 + project_id: + type: integer + format: int32 + environment_name: + type: string + environment: + "$ref": "#/components/schemas/Environment" + config: + "$ref": "#/components/schemas/Config" + status: + type: string + error: + type: string + created_at: + type: string + format: date-time + updated_at: + type: string + format: date-time + Config: + type: object + properties: + job_config: + "$ref": "#/components/schemas/PredictionJobConfig" + image_ref: + type: string + service_account_name: + type: string + resource_request: + "$ref": "#/components/schemas/PredictionJobResourceRequest" + image_builder_resource_request: + "$ref": "#/components/schemas/ResourceRequest" + env_vars: + type: array + items: + "$ref": "#/components/schemas/EnvVar" + GPUConfig: + type: object + properties: + name: + type: string + values: + type: array + items: type: string - features: - type: array - items: - type: string - options: - type: object - additionalProperties: - type: string - gcs_source: - type: object - properties: - format: - $ref: "#/definitions/FileFormat" - uri: + resource_type: + type: string + node_selector: + type: object + additionalProperties: type: string - features: - type: array - items: + tolerations: + type: array + items: + "$ref": "#/components/schemas/GPUToleration" + min_monthly_cost_per_gpu: + type: number + max_monthly_cost_per_gpu: + type: number + GPUToleration: + type: object + properties: + key: + type: string + operator: + type: string + value: + type: string + effect: + type: string + toleration_seconds: + type: integer + format: int64 + PredictionJobResourceRequest: + type: object + properties: + driver_cpu_request: + type: string + driver_memory_request: + type: string + executor_cpu_request: + type: string + executor_memory_request: + type: string + executor_replica: + type: integer + format: int32 + PredictionJobConfig: + type: object + properties: + version: + type: string + kind: + type: string + name: + type: string + bigquery_source: + type: object + properties: + table: type: string - options: - type: object - additionalProperties: + features: + type: array + items: + type: string + options: + type: object + additionalProperties: + type: string + gcs_source: + type: object + properties: + format: + "$ref": "#/components/schemas/FileFormat" + uri: type: string - model: - type: object - properties: - type: - type: string - enum: + features: + type: array + items: + type: string + options: + type: object + additionalProperties: + type: string + model: + type: object + properties: + type: + type: string + default: INVALID_MODEL_TYPE + enum: - INVALID_MODEL_TYPE - XGBOOST - TENSORFLOW @@ -1649,153 +2075,146 @@ definitions: - PYFUNC - PYFUNC_V2 - CUSTOM - default: INVALID_MODEL_TYPE - uri: - type: string - result: - type: object - properties: - type: - $ref: "#/definitions/ResultType" - item_type: - $ref: "#/definitions/ResultType" - title: only if type is array - options: - type: object - additionalProperties: + uri: type: string - bigquery_sink: - type: object - properties: - table: - type: string - staging_bucket: - type: string - result_column: - type: string - save_mode: - $ref: "#/definitions/SaveMode" - options: - type: object - additionalProperties: + result: + type: object + properties: + type: + "$ref": "#/components/schemas/ResultType" + item_type: + "$ref": "#/components/schemas/ResultType" + options: + type: object + additionalProperties: + type: string + bigquery_sink: + type: object + properties: + table: type: string - gcs_sink: - type: object - properties: - format: - $ref: "#/definitions/FileFormat" - uri: - type: string - result_column: - type: string - save_mode: - $ref: "#/definitions/SaveMode" - options: - type: object - additionalProperties: + staging_bucket: type: string - FileFormat: - type: string - enum: + result_column: + type: string + save_mode: + "$ref": "#/components/schemas/SaveMode" + options: + type: object + additionalProperties: + type: string + gcs_sink: + type: object + properties: + format: + "$ref": "#/components/schemas/FileFormat" + uri: + type: string + result_column: + type: string + save_mode: + "$ref": "#/components/schemas/SaveMode" + options: + type: object + additionalProperties: + type: string + FileFormat: + type: string + default: INVALID_FILE_FORMAT + enum: - INVALID_FILE_FORMAT - CSV - PARQUET - AVRO - JSON - default: INVALID_FILE_FORMAT - ResultType: - type: string - enum: + ResultType: + type: string + default: DOUBLE + enum: - DOUBLE - FLOAT - INTEGER - LONG - STRING - ARRAY - default: DOUBLE - SaveMode: - type: string - enum: + SaveMode: + type: integer + enum: + - 0 + - 1 + - 2 + - 3 + - 4 + x-enum-names: - ERRORIFEXISTS - OVERWRITE - APPEND - IGNORE - ERROR - default: ERRORIFEXISTS - - StandardTransformerSimulationRequest: - type: object - properties: - payload: - $ref: "#/definitions/FreeFormObject" - headers: - $ref: "#/definitions/FreeFormObject" - config: - $ref: "#/definitions/FreeFormObject" - model_prediction_config: - $ref: "#/definitions/ModelPredictionConfig" - protocol: - $ref: "#/definitions/Protocol" - - StandardTransformerSimulationResponse: - type: object - properties: - response: - $ref: "#/definitions/FreeFormObject" - operation_tracing: - $ref: "#/definitions/OperationTracing" - - OperationTracing: - type: object - properties: - preprocess: - $ref: "#/definitions/PipelineTracing" - postprocess: - $ref: "#/definitions/PipelineTracing" - - PipelineTracing: - type: array - items: + StandardTransformerSimulationRequest: + type: object + properties: + payload: + "$ref": "#/components/schemas/FreeFormObject" + headers: + "$ref": "#/components/schemas/FreeFormObject" + config: + "$ref": "#/components/schemas/FreeFormObject" + model_prediction_config: + "$ref": "#/components/schemas/ModelPredictionConfig" + protocol: + "$ref": "#/components/schemas/Protocol" + StandardTransformerSimulationResponse: type: object + properties: + response: + "$ref": "#/components/schemas/FreeFormObject" + operation_tracing: + "$ref": "#/components/schemas/OperationTracing" + OperationTracing: + type: object + properties: + preprocess: + type: array + items: + "$ref": "#/components/schemas/PipelineTracing" + postprocess: + type: array + items: + "$ref": "#/components/schemas/PipelineTracing" + PipelineTracing: + type: object properties: operation_type: type: string - specs: - $ref: "#/definitions/FreeFormObject" - inputs: - $ref: "#/definitions/FreeFormObject" - outputs: - $ref: "#/definitions/FreeFormObject" - - ModelPredictionConfig: - type: object - properties: - mock_response: - $ref: "#/definitions/MockResponse" - - MockResponse: - type: object - properties: - body: - $ref: "#/definitions/FreeFormObject" - headers: - $ref: "#/definitions/FreeFormObject" - - FreeFormObject: - type: object - additionalProperties: true - - Protocol: - type: "string" - enum: - - "HTTP_JSON" - - "UPI_V1" - -securityDefinitions: - Bearer: - type: apiKey - name: Authorization - in: header - -security: - - Bearer: [] + spec: + "$ref": "#/components/schemas/FreeFormObject" + input: + "$ref": "#/components/schemas/FreeFormObject" + output: + "$ref": "#/components/schemas/FreeFormObject" + + ModelPredictionConfig: + type: object + properties: + mock_response: + "$ref": "#/components/schemas/MockResponse" + MockResponse: + type: object + properties: + body: + "$ref": "#/components/schemas/FreeFormObject" + headers: + "$ref": "#/components/schemas/FreeFormObject" + FreeFormObject: + type: object + Protocol: + type: string + enum: + - HTTP_JSON + - UPI_V1 + securitySchemes: + Bearer: + type: apiKey + name: Authorization + in: header