Browse Source

Add chat with saved AI models by ID for API clients

pull/16379/head
Roman Kostenko 1 month ago
parent
commit
e5378bd01f
  1. 2
      application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql
  2. 70
      application/src/main/java/org/thingsboard/server/controller/AiModelController.java
  3. 32
      application/src/main/java/org/thingsboard/server/service/ai/TbAiModelChatRequest.java
  4. 106
      application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java
  5. 19
      application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java
  6. 1
      application/src/main/java/org/thingsboard/server/service/trendz/DefaultTrendzSyncService.java
  7. 192
      application/src/test/java/org/thingsboard/server/controller/AiModelControllerTest.java
  8. 151
      application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_1_0MigrationTest.java
  9. 11
      application/src/test/java/org/thingsboard/server/service/trendz/TrendzSyncServiceTest.java
  10. 2
      common/dao-api/src/main/java/org/thingsboard/server/dao/ai/AiModelService.java
  11. 10
      common/data/src/main/java/org/thingsboard/server/common/data/ai/AiModel.java
  12. 3
      common/data/src/main/java/org/thingsboard/server/common/data/permission/Operation.java
  13. 6
      common/data/src/main/java/org/thingsboard/server/common/data/permission/Resource.java
  14. 4
      dao/src/main/java/org/thingsboard/server/dao/ai/AiModelDao.java
  15. 7
      dao/src/main/java/org/thingsboard/server/dao/ai/AiModelServiceImpl.java
  16. 1
      dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java
  17. 5
      dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java
  18. 7
      dao/src/main/java/org/thingsboard/server/dao/sql/ai/AiModelRepository.java
  19. 7
      dao/src/main/java/org/thingsboard/server/dao/sql/ai/JpaAiModelDao.java
  20. 15
      dao/src/main/resources/sql/schema-entities.sql
  21. 6
      ui-ngx/src/app/modules/home/components/ai-model/ai-model-dialog.component.html
  22. 1
      ui-ngx/src/app/modules/home/components/ai-model/ai-model-dialog.component.ts
  23. 1
      ui-ngx/src/app/shared/models/ai-model.models.ts
  24. 3
      ui-ngx/src/app/shared/models/security.models.ts
  25. 5
      ui-ngx/src/assets/locale/locale.constant-en_US.json

2
application/src/main/data/upgrade/lts/4.4.1.0/schema_update.sql

@ -6,3 +6,5 @@
-- Tenant-scoped paging over calculated fields (WHERE tenant_id = ? ORDER BY id LIMIT ?), issued for every tenant
-- when the calculated field actors initialize, otherwise scans the whole table and sorts on each call.
CREATE INDEX IF NOT EXISTS idx_calculated_field_tenant_id_id ON calculated_field(tenant_id, id);
ALTER TABLE ai_model ADD COLUMN IF NOT EXISTS available_via_api BOOLEAN NOT NULL DEFAULT FALSE;

70
application/src/main/java/org/thingsboard/server/controller/AiModelController.java

@ -20,10 +20,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;
import org.thingsboard.rule.engine.ai.TbResponseFormat;
import org.thingsboard.server.common.data.ai.AiModel;
import org.thingsboard.server.common.data.ai.dto.TbChatRequest;
import org.thingsboard.server.common.data.ai.dto.TbChatResponse;
import org.thingsboard.server.common.data.ai.model.chat.AiChatModelConfig;
import org.thingsboard.server.common.data.exception.ThingsboardErrorCode;
import org.thingsboard.server.common.data.exception.ThingsboardException;
import org.thingsboard.server.common.data.id.AiModelId;
import org.thingsboard.server.common.data.page.PageData;
@ -32,6 +34,8 @@ import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.config.annotations.ApiOperation;
import org.thingsboard.server.queue.util.TbCoreComponent;
import org.thingsboard.server.service.ai.AiChatModelService;
import org.thingsboard.server.service.ai.TbAiModelChatRequest;
import org.thingsboard.server.service.security.model.SecurityUser;
import java.time.Duration;
import java.util.Optional;
@ -45,6 +49,7 @@ import static org.thingsboard.server.controller.ControllerConstants.PAGE_SIZE_DE
import static org.thingsboard.server.controller.ControllerConstants.SORT_ORDER_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.SORT_PROPERTY_DESCRIPTION;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_AUTHORITY_PARAGRAPH;
import static org.thingsboard.server.controller.ControllerConstants.TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH;
@Validated
@RestController
@ -107,12 +112,14 @@ class AiModelController extends BaseController {
@Parameter(description = SORT_PROPERTY_DESCRIPTION, schema = @Schema(allowableValues = {"createdTime", "name", "provider", "modelId"}))
@RequestParam(required = false) String sortProperty,
@Parameter(description = SORT_ORDER_DESCRIPTION, schema = @Schema(allowableValues = {"ASC", "DESC"}))
@RequestParam(required = false) String sortOrder
@RequestParam(required = false) String sortOrder,
@Parameter(description = "Filter by the 'available via API' flag; all models are returned when omitted")
@RequestParam(required = false) Boolean availableViaApi
) throws ThingsboardException {
var user = getCurrentUser();
accessControlService.checkPermission(user, Resource.AI_MODEL, Operation.READ);
var pageLink = createPageLink(pageSize, page, textSearch, sortProperty, sortOrder);
return aiModelService.findAiModelsByTenantId(user.getTenantId(), pageLink);
return aiModelService.findAiModelsByTenantId(user.getTenantId(), availableViaApi, pageLink);
}
@ApiOperation(
@ -152,15 +159,66 @@ class AiModelController extends BaseController {
@PreAuthorize("hasAuthority('TENANT_ADMIN')")
@PostMapping("/chat")
public DeferredResult<TbChatResponse> sendChatRequest(@Valid @RequestBody TbChatRequest tbChatRequest) throws ThingsboardException {
ChatRequest langChainChatRequest = tbChatRequest.toLangChainChatRequest();
AiChatModelConfig<?> chatModelConfig = tbChatRequest.chatModelConfig();
return executeChatRequest(tbChatRequest.chatModelConfig(), tbChatRequest.toLangChainChatRequest());
}
@ApiOperation(
value = "Send request to a saved AI chat model (sendChatRequestToAiModel)",
notes = "Submits a single prompt - made up of an optional system message and a required user message - to the AI chat model " +
"with the specified `id`, using its saved configuration, and returns either the generated answer or an error envelope. " +
"The model must be marked as available via API, and the user must have the 'INVOKE' permission for AI models. " +
"Roles that grant all operations, such as the default 'Customer Administrator' role, include 'INVOKE', " +
"so marking a model as available via API makes it callable by every user with such a role." +
TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH
)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@PostMapping("/{modelUuid}/chat")
public DeferredResult<TbChatResponse> sendChatRequestToAiModel(
@Parameter(
description = "ID of the AI model record",
required = true,
example = "de7900d4-30e2-11f0-9cd2-0242ac120002"
)
@PathVariable UUID modelUuid,
@Valid @RequestBody TbAiModelChatRequest request
) throws ThingsboardException {
AiModel model = checkAiModelId(new AiModelId(modelUuid), Operation.INVOKE);
if (!model.isAvailableViaApi()) {
throw new ThingsboardException("AI model with id [" + modelUuid + "] is not available via API", ThingsboardErrorCode.PERMISSION_DENIED);
}
if (!(model.getConfiguration() instanceof AiChatModelConfig<?> chatModelConfig)) {
throw new ThingsboardException("AI model with id [" + modelUuid + "] is not a chat model", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
ListenableFuture<TbChatResponse> future = aiChatModelService.sendChatRequestAsync(getTenantId(), chatModelConfig, langChainChatRequest)
ChatRequest chatRequest = new TbChatRequest(request.systemMessage(), request.userMessage(), chatModelConfig).toLangChainChatRequest();
TbResponseFormat responseFormat = request.responseFormat();
if (responseFormat != null) {
if (!responseFormat.isSupportedBy(chatModelConfig)) {
throw new ThingsboardException("AI model with id [" + modelUuid + "] does not support '" + responseFormat.type() + "' response format",
ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
chatRequest = chatRequest.toBuilder().responseFormat(responseFormat.toLangChainResponseFormat()).build();
}
return executeChatRequest(chatModelConfig, chatRequest);
}
private DeferredResult<TbChatResponse> executeChatRequest(AiChatModelConfig<?> chatModelConfig, ChatRequest chatRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser();
ListenableFuture<TbChatResponse> future = aiChatModelService.sendChatRequestAsync(user.getTenantId(), chatModelConfig, chatRequest)
.transform(chatResponse -> (TbChatResponse) new TbChatResponse.Success(chatResponse.aiMessage().text()), directExecutor())
.catching(Throwable.class, ex -> new TbChatResponse.Failure(ex.getMessage()), directExecutor());
.catching(Throwable.class, ex -> toFailure(user, ex), directExecutor());
Integer requestTimeoutSeconds = chatModelConfig.timeoutSeconds();
return requestTimeoutSeconds != null ? wrapFuture(future, Duration.ofSeconds(requestTimeoutSeconds).toMillis()) : wrapFuture(future);
}
private TbChatResponse.Failure toFailure(SecurityUser user, Throwable ex) {
if (!user.isCustomerUser()) {
return new TbChatResponse.Failure(ex.getMessage());
}
// Provider errors may reveal configuration details that customer users must not see
log.debug("[{}] Chat request of customer user [{}] failed", user.getTenantId(), user.getId(), ex);
return new TbChatResponse.Failure("Failed to get a response from the AI model");
}
}

32
application/src/main/java/org/thingsboard/server/service/ai/TbAiModelChatRequest.java

@ -0,0 +1,32 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.ai;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.thingsboard.rule.engine.ai.TbResponseFormat;
import org.thingsboard.server.common.data.ai.dto.TbUserMessage;
public record TbAiModelChatRequest(
@Schema(
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
description = "A system-level instruction that frames the user's input, setting the persona, tone, and constraints for the generated response",
example = "You are a helpful assistant. Only output valid JSON."
)
String systemMessage,
@Schema(
requiredMode = Schema.RequiredMode.REQUIRED,
description = "The actual user prompt that will be answered by the AI model"
)
@NotNull @Valid
TbUserMessage userMessage,
@Schema(
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
description = "Format of the generated response; plain text when omitted"
)
@Valid
TbResponseFormat responseFormat
) {}

106
application/src/main/java/org/thingsboard/server/service/install/lts/V4_4_1_0Migration.java

@ -2,29 +2,125 @@
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.install.lts;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.pat.ApiKey;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.pat.ApiKeyService;
import org.thingsboard.server.queue.util.TbCoreComponent;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.thingsboard.server.dao.trendz.TrendzSyncService.TRENDZ_API_KEY_DESCRIPTION;
/**
* Registration-only migration with no {@link #apply()} (no data migration).
* Migration for version {@code 4.4.1.0}.
* <p>
* {@link MigrationService} selects migrations from the injected {@link Migration} beans, not from the
* on-disk {@code data/upgrade/lts/<version>/} directories. So this bean is what makes the runner discover
* version {@code 4.4.1.0} and execute its {@code data/upgrade/lts/4.4.1.0/schema_update.sql}, which adds the
* {@code idx_calculated_field_tenant_id_id} index used by tenant-scoped calculated field paging.
* {@link MigrationService} selects migrations from the injected {@link Migration} beans, not from the on-disk
* {@code data/upgrade/lts/<version>/} directories, so this bean is what makes the runner discover version
* {@code 4.4.1.0} and execute its {@code data/upgrade/lts/4.4.1.0/schema_update.sql}.
* <p>
* It needs a slot of its own rather than {@code 4.4.0.0}: that version is already released, and
* {@link Version#isInRange} is exclusive at the lower bound, so an installation already on {@code 4.4.0.0}
* would never pick up a change added there.
* <p>
* The dir/bean consistency (both ways) is guarded by a test in {@code MigrationIntegrationTest}.
* <p>
* Each thing this version migrates lives in its own private method called from {@link #apply()}, with the constants
* it needs declared inside it, so a further change means one more method and one more line in {@code apply()}.
*/
@Slf4j
@Component
@TbCoreComponent
@RequiredArgsConstructor
public class V4_4_1_0Migration implements Migration {
private final ApiKeyService apiKeyService;
@Override
public String getVersion() {
return "4.4.1.0";
}
/**
* Runs in the same transaction as the version's schema SQL on the no-downtime path, and outside any transaction
* on the offline path (see {@link Migration#apply}). Every step below must therefore be light enough to sit in
* a schema transaction, and idempotent, since a crash before the version is recorded re-runs it.
*/
@Override
public void apply() {
grantAiModelReadAndInvokeToTrendzApiKey();
}
/**
* Grants {@link Operation#READ} and {@link Operation#INVOKE} on {@link Resource#AI_MODEL} to the internal Trendz API key.
* <p>
* Trendz lists AI models and sends chat requests to them through that key, but keys minted before this version were
* created from a {@code buildTrendzPermissions()} that did not include the resource, so every AI model endpoint
* answered 403. New keys get it from {@code DefaultTrendzSyncService.buildTrendzPermissions()}, which is the source
* of truth this method mirrors -- keep the two in step.
* <p>
* Expressed against the {@link Resource} and {@link Operation} enums rather than as SQL over the permissions JSON,
* so renaming an enum constant breaks the build instead of silently matching nothing.
* <p>
* Idempotent: an operation already present is never added twice, and the key is saved only when something actually
* changed, so a re-run is a no-op.
*/
private void grantAiModelReadAndInvokeToTrendzApiKey() {
// The operations Trendz needs to list AI models and send chat requests to them.
Set<Operation> aiModelOperations = EnumSet.of(Operation.READ, Operation.INVOKE);
// SYS_ADMIN is deliberately absent: AI models are tenant entities.
List<Authority> authorities = List.of(Authority.TENANT_ADMIN, Authority.CUSTOMER_USER);
ApiKey trendzApiKey = apiKeyService.findInternalApiKeyByDescription(TenantId.SYS_TENANT_ID, TRENDZ_API_KEY_DESCRIPTION);
if (trendzApiKey == null || trendzApiKey.getPermissions() == null
|| trendzApiKey.getPermissions().getOperationsByResource() == null) {
log.debug("No internal Trendz API key with stored permissions, nothing to grant");
return;
}
Map<Authority, Map<Resource, Set<Operation>>> byAuthority =
new HashMap<>(trendzApiKey.getPermissions().getOperationsByResource());
boolean changed = false;
for (Authority authority : authorities) {
Map<Resource, Set<Operation>> byResource = byAuthority.get(authority);
if (byResource == null) {
continue;
}
// Copy rather than mutate in place: the deserialized maps and sets carry no mutability guarantee.
Map<Resource, Set<Operation>> updatedByResource = new HashMap<>(byResource);
Set<Operation> operations = updatedByResource.get(Resource.AI_MODEL);
if (operations != null && operations.containsAll(aiModelOperations)) {
continue;
}
// An authority the key covers gets the resource even if it was never granted: AI models are new to the key.
Set<Operation> updated = EnumSet.copyOf(aiModelOperations);
if (operations != null) {
updated.addAll(operations);
}
updatedByResource.put(Resource.AI_MODEL, updated);
changed = true;
byAuthority.put(authority, updatedByResource);
}
if (!changed) {
log.debug("Internal Trendz API key already grants {} on {}", aiModelOperations, Resource.AI_MODEL);
return;
}
trendzApiKey.getPermissions().setOperationsByResource(byAuthority);
// Preserves the key's value, so Trendz keeps authenticating with the secret it already holds, and evicts the
// key from the cache, which would otherwise keep serving the old permissions for the rest of its TTL.
apiKeyService.saveApiKey(TenantId.SYS_TENANT_ID, trendzApiKey);
log.info("Granted {} on {} to the internal Trendz API key", aiModelOperations, Resource.AI_MODEL);
}
}

19
application/src/main/java/org/thingsboard/server/service/security/permission/CustomerUserPermissions.java

@ -93,6 +93,7 @@ public class CustomerUserPermissions extends AbstractPermissions {
put(Resource.REPORT_TEMPLATE, reportTemplatePermissionChecker);
put(Resource.REPORT, customerStandaloneEntityPermissionChecker);
put(Resource.API_KEY, apiKeysPermissionChecker);
put(Resource.AI_MODEL, aiModelPermissionChecker);
}
private final PermissionChecker<AlarmId, Alarm> customerAlarmPermissionChecker = new PermissionChecker<>() {
@ -487,6 +488,24 @@ public class CustomerUserPermissions extends AbstractPermissions {
}
};
// Only INVOKE is grantable: reading the model would expose the provider credentials stored in its configuration.
// Roles granting ALL include INVOKE, so the model's 'availableViaApi' flag decides which models such users can call.
private static final PermissionChecker aiModelPermissionChecker = new PermissionChecker() {
@Override
public boolean hasPermission(SecurityUser user, Resource resource, Operation operation) {
return operation == Operation.INVOKE && user.getUserPermissions().hasGenericPermission(resource, operation);
}
@Override
public boolean hasPermission(SecurityUser user, Operation operation, EntityId entityId, TenantEntity entity) {
if (operation != Operation.INVOKE || !user.getTenantId().equals(entity.getTenantId())) {
return false;
}
return user.getUserPermissions().hasGenericPermission(Resource.AI_MODEL, operation);
}
};
private static final PermissionChecker apiKeysPermissionChecker = new PermissionChecker() {
@Override

1
application/src/main/java/org/thingsboard/server/service/trendz/DefaultTrendzSyncService.java

@ -385,6 +385,7 @@ public class DefaultTrendzSyncService implements TrendzSyncService {
tenantCustomerPermissions.put(Resource.WHITE_LABELING, Set.of(Operation.READ));
tenantCustomerPermissions.put(Resource.DEVICE_PROFILE, Set.of(Operation.READ, Operation.READ_CALCULATED_FIELD));
tenantCustomerPermissions.put(Resource.ASSET_PROFILE, Set.of(Operation.READ, Operation.READ_CALCULATED_FIELD));
tenantCustomerPermissions.put(Resource.AI_MODEL, Set.of(Operation.READ, Operation.INVOKE));
permissions.put(Authority.TENANT_ADMIN, tenantCustomerPermissions);
permissions.put(Authority.CUSTOMER_USER, tenantCustomerPermissions);

192
application/src/test/java/org/thingsboard/server/controller/AiModelControllerTest.java

@ -28,6 +28,7 @@ import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.common.data.page.SortOrder;
import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.service.ai.TbAiModelChatRequest;
import java.util.List;
@ -90,9 +91,26 @@ public class AiModelControllerTest extends AbstractControllerTest {
assertThat(savedModel.getTenantId()).isEqualTo(tenantId);
assertThat(savedModel.getName()).isEqualTo("Test model");
assertThat(savedModel.getConfiguration()).isEqualTo(model.getConfiguration());
assertThat(savedModel.isAvailableViaApi()).isFalse();
assertThat(savedModel.getExternalId()).isNull();
}
@Test
public void saveAiModel_whenAvailableViaApiIsSet_shouldPersistIt() throws Exception {
// GIVEN
loginTenantAdmin();
AiModel model = constructValidOpenAiModel("Test model");
model.setAvailableViaApi(true);
// WHEN
var savedModel = doPost("/api/ai/model", model, AiModel.class);
// THEN
assertThat(savedModel.isAvailableViaApi()).isTrue();
assertThat(doGet("/api/ai/model/" + savedModel.getId(), AiModel.class).isAvailableViaApi()).isTrue();
}
@Test
public void saveAiModel_whenUpdatingExistingModelAsTenantAdmin_shouldSucceed() throws Exception {
// GIVEN
@ -244,6 +262,132 @@ public class AiModelControllerTest extends AbstractControllerTest {
}
}
/* --- Chat with saved model API tests --- */
@Test
public void sendChatRequestToAiModel_whenUserIsSysAdmin_shouldReturnForbidden() throws Exception {
// GIVEN
loginSysAdmin();
// WHEN
ResultActions result = doPost("/api/ai/model/" + Uuids.timeBased() + "/chat", constructChatRequest());
// THEN
result.andExpect(status().isForbidden()).andExpect(statusReason(equalTo(msgErrorPermission)));
}
@Test
public void sendChatRequestToAiModel_whenModelDoesNotExist_shouldReturnNotFound() throws Exception {
// GIVEN
loginTenantAdmin();
var nonexistentModelId = new AiModelId(Uuids.timeBased());
// WHEN
ResultActions result = doPost("/api/ai/model/" + nonexistentModelId + "/chat", constructChatRequest());
// THEN
result.andExpect(status().isNotFound())
.andExpect(statusReason(is("AI model with id [" + nonexistentModelId + "] is not found")));
}
@Test
public void sendChatRequestToAiModel_whenModelIsNotAvailableViaApi_shouldReturnForbidden() throws Exception {
// GIVEN
loginTenantAdmin();
var model = doPost("/api/ai/model", constructValidOpenAiModel("Test model"), AiModel.class);
// WHEN
ResultActions result = doPost("/api/ai/model/" + model.getId() + "/chat", constructChatRequest());
// THEN
result.andExpect(status().isForbidden())
.andExpect(statusReason(is("AI model with id [" + model.getId() + "] is not available via API")));
}
@Test
public void sendChatRequestToAiModel_whenTenantAdmin_shouldUseStoredConfigurationAndReturnProviderError() throws Exception {
// GIVEN
loginTenantAdmin();
var model = saveModelAvailableViaApiWithBlockedBaseUrl();
SsrfProtectionValidator.setEnabled(true);
try {
// WHEN
TbChatResponse response = doPostAsync("/api/ai/model/" + model.getId() + "/chat", constructChatRequest(), TbChatResponse.class, status().isOk());
// THEN
assertThat(response).isInstanceOf(TbChatResponse.Failure.class);
assertThat(((TbChatResponse.Failure) response).errorDetails()).contains("URI is invalid");
} finally {
SsrfProtectionValidator.setEnabled(false);
}
}
@Test
public void sendChatRequestToAiModel_whenCustomerAdmin_shouldBeAllowedAndHideProviderError() throws Exception {
// GIVEN
loginTenantAdmin();
var model = saveModelAvailableViaApiWithBlockedBaseUrl();
loginCustomerAdminUser();
SsrfProtectionValidator.setEnabled(true);
try {
// WHEN
TbChatResponse response = doPostAsync("/api/ai/model/" + model.getId() + "/chat", constructChatRequest(), TbChatResponse.class, status().isOk());
// THEN
assertThat(response).isInstanceOf(TbChatResponse.Failure.class);
assertThat(((TbChatResponse.Failure) response).errorDetails()).isEqualTo("Failed to get a response from the AI model");
} finally {
SsrfProtectionValidator.setEnabled(false);
}
}
@Test
public void sendChatRequestToAiModel_whenCustomerUserWithoutInvokePermission_shouldReturnForbidden() throws Exception {
// GIVEN
loginTenantAdmin();
var model = saveModelAvailableViaApiWithBlockedBaseUrl();
loginCustomerUser();
// WHEN
ResultActions result = doPost("/api/ai/model/" + model.getId() + "/chat", constructChatRequest());
// THEN
result.andExpect(status().isForbidden())
.andExpect(statusReason(equalTo("You don't have permission to perform 'INVOKE' operation with AI_MODEL 'Test model'!")));
}
/* --- Customer permission tests --- */
@Test
public void aiModelPermission_whenCustomerAdminGrantedAll_shouldAllowInvokeOnly() throws Exception {
// GIVEN
loginTenantAdmin();
var model = doPost("/api/ai/model", constructValidOpenAiModel("Test model"), AiModel.class);
loginCustomerAdminUser();
// WHEN / THEN
assertThat(hasAiModelPermission(model, "INVOKE")).isTrue();
assertThat(hasAiModelPermission(model, "READ")).isFalse();
assertThat(hasAiModelPermission(model, "WRITE")).isFalse();
assertThat(hasAiModelPermission(model, "DELETE")).isFalse();
}
@Test
public void aiModelPermission_whenCustomerUserGrantedReadOnAllResources_shouldDenyReadAndInvoke() throws Exception {
// GIVEN
loginTenantAdmin();
var model = doPost("/api/ai/model", constructValidOpenAiModel("Test model"), AiModel.class);
loginCustomerUser();
// WHEN / THEN
assertThat(hasAiModelPermission(model, "READ")).isFalse();
assertThat(hasAiModelPermission(model, "INVOKE")).isFalse();
}
/* --- Get by ID API tests --- */
@Test
@ -442,6 +586,27 @@ public class AiModelControllerTest extends AbstractControllerTest {
assertThat(result4.hasNext()).isFalse();
}
@Test
public void getAiModels_testFilterByAvailableViaApi() throws Exception {
// GIVEN
loginTenantAdmin();
var available = constructValidOpenAiModel("Available model");
available.setAvailableViaApi(true);
available = doPost("/api/ai/model", available, AiModel.class);
var unavailable = doPost("/api/ai/model", constructValidOpenAiModel("Unavailable model"), AiModel.class);
// WHEN
PageData<AiModel> onlyAvailable = doGetTypedWithPageLink("/api/ai/model?availableViaApi=true&", new TypeReference<>() {}, new PageLink(10));
PageData<AiModel> onlyUnavailable = doGetTypedWithPageLink("/api/ai/model?availableViaApi=false&", new TypeReference<>() {}, new PageLink(10));
PageData<AiModel> all = doGetTypedWithPageLink("/api/ai/model?", new TypeReference<>() {}, new PageLink(10));
// THEN
assertThat(onlyAvailable.getData()).containsExactly(available);
assertThat(onlyUnavailable.getData()).containsExactly(unavailable);
assertThat(all.getData()).containsExactlyInAnyOrder(available, unavailable);
}
@Test
public void getAiModels_testSortingByCreatedTime() throws Exception {
// GIVEN
@ -703,6 +868,33 @@ public class AiModelControllerTest extends AbstractControllerTest {
assertThat(deleted).isFalse();
}
private AiModel saveModelAvailableViaApiWithBlockedBaseUrl() throws Exception {
var modelConfig = OpenAiChatModelConfig.builder()
.providerConfig(OpenAiProviderConfig.builder()
.baseUrl("http://10.0.0.1:8080/")
.apiKey("test-api-key")
.build())
.modelId("gpt-4o")
.build();
var model = AiModel.builder()
.tenantId(tenantId)
.name("Test model")
.configuration(modelConfig)
.availableViaApi(true)
.build();
return doPost("/api/ai/model", model, AiModel.class);
}
private TbAiModelChatRequest constructChatRequest() {
return new TbAiModelChatRequest(null, new TbUserMessage(List.of(new TbContent.TbTextContent("hi"))), null);
}
private boolean hasAiModelPermission(AiModel model, String operation) throws Exception {
return doGet("/api/permission/AI_MODEL/" + model.getId() + "/" + operation, Boolean.class);
}
private AiModel constructValidOpenAiModel(String name) {
var modelConfig = OpenAiChatModelConfig.builder()
.providerConfig(OpenAiProviderConfig.builder()

151
application/src/test/java/org/thingsboard/server/service/install/lts/V4_4_1_0MigrationTest.java

@ -0,0 +1,151 @@
// SPDX-FileCopyrightText: Copyright ThingsBoard, Inc.
// SPDX-License-Identifier: BUSL-1.1
package org.thingsboard.server.service.install.lts;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.thingsboard.server.common.data.id.ApiKeyId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.pat.ApiKey;
import org.thingsboard.server.common.data.pat.ApiKeyInfo;
import org.thingsboard.server.common.data.permission.AuthorityPermissionsInfo;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.dao.pat.ApiKeyService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.thingsboard.server.dao.trendz.TrendzSyncService.TRENDZ_API_KEY_DESCRIPTION;
@ExtendWith(MockitoExtension.class)
class V4_4_1_0MigrationTest {
private static final List<Authority> AUTHORITIES = List.of(Authority.TENANT_ADMIN, Authority.CUSTOMER_USER);
@Mock
private ApiKeyService apiKeyService;
@InjectMocks
private V4_4_1_0Migration migration;
@Test
void grantsAiModelReadAndInvokeWithoutDroppingExistingOperations() {
givenTrendzApiKey(byAuthority(legacyPermissions(), AUTHORITIES));
migration.apply();
Map<Authority, Map<Resource, Set<Operation>>> byAuthority = savedPermissions();
for (Authority authority : AUTHORITIES) {
assertEquals(Set.of(Operation.READ, Operation.INVOKE), byAuthority.get(authority).get(Resource.AI_MODEL),
"expected READ and INVOKE on AI_MODEL for " + authority);
}
assertEquals(Set.of(Operation.READ, Operation.READ_TELEMETRY),
byAuthority.get(Authority.TENANT_ADMIN).get(Resource.DEVICE),
"the operations the key already had must survive");
}
@Test
void keepsOperationsTheKeyAlreadyHadOnAiModel() {
Map<Resource, Set<Operation>> permissions = legacyPermissions();
permissions.put(Resource.AI_MODEL, Set.of(Operation.READ, Operation.WRITE));
givenTrendzApiKey(byAuthority(permissions, AUTHORITIES));
migration.apply();
Map<Authority, Map<Resource, Set<Operation>>> byAuthority = savedPermissions();
for (Authority authority : AUTHORITIES) {
assertEquals(Set.of(Operation.READ, Operation.WRITE, Operation.INVOKE), byAuthority.get(authority).get(Resource.AI_MODEL),
"expected the existing AI_MODEL operations plus INVOKE for " + authority);
}
}
/**
* {@link Migration#apply()} re-runs when a node crashes before the version is recorded, so a key that already
* carries the operations must not be written again.
*/
@Test
void alreadyGrantedKeyIsNotSavedAgain() {
Map<Resource, Set<Operation>> permissions = legacyPermissions();
permissions.put(Resource.AI_MODEL, Set.of(Operation.READ, Operation.INVOKE));
givenTrendzApiKey(byAuthority(permissions, AUTHORITIES));
migration.apply();
verify(apiKeyService, never()).saveApiKey(any(), any());
}
@Test
void authorityTheKeyDoesNotCoverIsNotAdded() {
givenTrendzApiKey(byAuthority(legacyPermissions(), List.of(Authority.TENANT_ADMIN)));
migration.apply();
Map<Authority, Map<Resource, Set<Operation>>> byAuthority = savedPermissions();
assertEquals(Set.of(Operation.READ, Operation.INVOKE), byAuthority.get(Authority.TENANT_ADMIN).get(Resource.AI_MODEL));
assertFalse(byAuthority.containsKey(Authority.CUSTOMER_USER), "an authority the key never covered must stay absent");
}
@Test
void missingTrendzApiKeyIsNoOp() {
when(apiKeyService.findInternalApiKeyByDescription(TenantId.SYS_TENANT_ID, TRENDZ_API_KEY_DESCRIPTION))
.thenReturn(null);
migration.apply();
verify(apiKeyService, never()).saveApiKey(any(), any());
}
private Map<Authority, Map<Resource, Set<Operation>>> savedPermissions() {
ArgumentCaptor<ApiKeyInfo> saved = ArgumentCaptor.forClass(ApiKeyInfo.class);
verify(apiKeyService).saveApiKey(eq(TenantId.SYS_TENANT_ID), saved.capture());
return saved.getValue().getPermissions().getOperationsByResource();
}
private void givenTrendzApiKey(Map<Authority, Map<Resource, Set<Operation>>> byAuthority) {
ApiKey apiKey = new ApiKey(new ApiKeyId(UUID.randomUUID()));
apiKey.setTenantId(TenantId.SYS_TENANT_ID);
apiKey.setInternal(true);
apiKey.setDescription(TRENDZ_API_KEY_DESCRIPTION);
AuthorityPermissionsInfo permissions = new AuthorityPermissionsInfo();
permissions.setOperationsByResource(byAuthority);
apiKey.setPermissions(permissions);
when(apiKeyService.findInternalApiKeyByDescription(TenantId.SYS_TENANT_ID, TRENDZ_API_KEY_DESCRIPTION))
.thenReturn(apiKey);
}
// Separate map instances per authority, the way a key deserialized from the permissions column arrives --
// buildTrendzPermissions() shares one instance, but that sharing does not survive the JSON round trip.
private Map<Authority, Map<Resource, Set<Operation>>> byAuthority(Map<Resource, Set<Operation>> permissions, List<Authority> authorities) {
Map<Authority, Map<Resource, Set<Operation>>> byAuthority = new HashMap<>();
authorities.forEach(authority -> byAuthority.put(authority, new HashMap<>(permissions)));
return byAuthority;
}
// What a key created before 4.4.1.0 holds. Immutable inner sets on purpose: the migration must copy what it reads
// rather than mutate it.
private Map<Resource, Set<Operation>> legacyPermissions() {
Map<Resource, Set<Operation>> permissions = new HashMap<>();
permissions.put(Resource.DEVICE, Set.of(Operation.READ, Operation.READ_TELEMETRY));
permissions.put(Resource.ASSET, Set.of(Operation.READ, Operation.READ_TELEMETRY));
permissions.put(Resource.DEVICE_PROFILE, Set.of(Operation.READ));
return permissions;
}
}

11
application/src/test/java/org/thingsboard/server/service/trendz/TrendzSyncServiceTest.java

@ -21,6 +21,9 @@ import org.springframework.web.client.RestTemplate;
import org.thingsboard.common.util.JacksonUtil;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.pat.ApiKey;
import org.thingsboard.server.common.data.permission.Operation;
import org.thingsboard.server.common.data.permission.Resource;
import org.thingsboard.server.common.data.security.Authority;
import org.thingsboard.server.common.data.trendz.TrendzConfiguration;
import org.thingsboard.server.common.data.trendz.TrendzHealthcheckResult;
import org.thingsboard.server.common.data.trendz.TrendzSettings;
@ -33,6 +36,9 @@ import org.thingsboard.server.dao.service.DaoSqlTest;
import org.thingsboard.server.dao.trendz.TrendzSettingsService;
import org.thingsboard.server.service.security.system.SystemSecurityService;
import java.util.List;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
@ -219,6 +225,11 @@ public class TrendzSyncServiceTest extends AbstractControllerTest {
assertNotNull(apiKeyByDescription);
assertTrue(apiKeyByDescription.isInternal());
assertEquals(DefaultTrendzSyncService.TRENDZ_API_KEY_DESCRIPTION, apiKeyByDescription.getDescription());
for (Authority authority : List.of(Authority.TENANT_ADMIN, Authority.CUSTOMER_USER)) {
assertEquals(Set.of(Operation.READ, Operation.INVOKE),
apiKeyByDescription.getPermissions().getPermissionsForAuthority(authority).get(Resource.AI_MODEL),
"expected READ and INVOKE on AI_MODEL for " + authority);
}
}
@Test

2
common/dao-api/src/main/java/org/thingsboard/server/dao/ai/AiModelService.java

@ -22,6 +22,8 @@ public interface AiModelService extends EntityDaoService {
PageData<AiModel> findAiModelsByTenantId(TenantId tenantId, PageLink pageLink);
PageData<AiModel> findAiModelsByTenantId(TenantId tenantId, Boolean availableViaApi, PageLink pageLink);
Optional<AiModel> findAiModelByTenantIdAndId(TenantId tenantId, AiModelId modelId);
FluentFuture<Optional<AiModel>> findAiModelByTenantIdAndIdAsync(TenantId tenantId, AiModelId modelId);

10
common/data/src/main/java/org/thingsboard/server/common/data/ai/AiModel.java

@ -70,6 +70,15 @@ public final class AiModel extends BaseData<AiModelId> implements TenantEntity,
)
private AiModelConfig configuration;
@Schema(
requiredMode = Schema.RequiredMode.NOT_REQUIRED,
accessMode = Schema.AccessMode.READ_WRITE,
description = "Whether the model can be used via the AI model chat API by users with the 'INVOKE' permission. " +
"Roles that grant all operations, such as the default 'Customer Administrator' role, include 'INVOKE'",
defaultValue = "false"
)
private boolean availableViaApi;
private AiModelId externalId;
public AiModel() {}
@ -85,6 +94,7 @@ public final class AiModel extends BaseData<AiModelId> implements TenantEntity,
version = model.getVersion();
name = model.getName();
configuration = model.getConfiguration();
availableViaApi = model.isAvailableViaApi();
externalId = model.getExternalId() == null ? null : new AiModelId(model.getExternalId().getId());
}

3
common/data/src/main/java/org/thingsboard/server/common/data/permission/Operation.java

@ -31,7 +31,8 @@ public enum Operation {
SHARE_GROUP(true),
ASSIGN_TO_TENANT,
READ_CALCULATED_FIELD(true),
WRITE_CALCULATED_FIELD(true);
WRITE_CALCULATED_FIELD(true),
INVOKE;
public static Set<Operation> defaultEntityOperations = new HashSet<>(Arrays.asList(ALL, READ, WRITE,
CREATE, DELETE, READ_ATTRIBUTES, WRITE_ATTRIBUTES, READ_TELEMETRY, WRITE_TELEMETRY, CHANGE_OWNER));

6
common/data/src/main/java/org/thingsboard/server/common/data/permission/Resource.java

@ -157,7 +157,8 @@ public enum Resource {
operationsByResource.put(Resource.SECRET, Operation.crudOperations);
operationsByResource.put(Resource.REPORT_TEMPLATE, Operation.crudOperations);
operationsByResource.put(Resource.REPORT, Operation.crudOperations);
operationsByResource.put(Resource.AI_MODEL, Operation.crudOperations);
operationsByResource.put(Resource.AI_MODEL, Set.of(Operation.ALL, Operation.READ, Operation.WRITE,
Operation.CREATE, Operation.DELETE, Operation.INVOKE));
operationsByResource.put(Resource.AI, Set.of(Operation.ALL));
operationsByResource.put(Resource.CUSTOM_MENU, Set.of(Operation.ALL, Operation.READ, Operation.WRITE, Operation.DELETE));
operationsByResource.put(Resource.API_KEY, Operation.crudOperations);
@ -283,7 +284,8 @@ public enum Resource {
Resource.REPORT_TEMPLATE,
Resource.REPORT,
Resource.JOB,
Resource.API_KEY
Resource.API_KEY,
Resource.AI_MODEL
));
}

4
dao/src/main/java/org/thingsboard/server/dao/ai/AiModelDao.java

@ -5,6 +5,8 @@ package org.thingsboard.server.dao.ai;
import org.thingsboard.server.common.data.ai.AiModel;
import org.thingsboard.server.common.data.id.AiModelId;
import org.thingsboard.server.common.data.id.TenantId;
import org.thingsboard.server.common.data.page.PageData;
import org.thingsboard.server.common.data.page.PageLink;
import org.thingsboard.server.dao.ExportableEntityDao;
import org.thingsboard.server.dao.TenantEntityDao;
@ -15,6 +17,8 @@ public interface AiModelDao extends TenantEntityDao<AiModel>, ExportableEntityDa
Optional<AiModel> findByTenantIdAndId(TenantId tenantId, AiModelId modelId);
PageData<AiModel> findByTenantId(TenantId tenantId, Boolean availableViaApi, PageLink pageLink);
boolean deleteById(TenantId tenantId, AiModelId modelId);
Set<AiModelId> deleteByTenantId(TenantId tenantId);

7
dao/src/main/java/org/thingsboard/server/dao/ai/AiModelServiceImpl.java

@ -91,8 +91,13 @@ class AiModelServiceImpl extends CachedVersionedEntityService<AiModelCacheKey, A
@Override
public PageData<AiModel> findAiModelsByTenantId(TenantId tenantId, PageLink pageLink) {
return findAiModelsByTenantId(tenantId, null, pageLink);
}
@Override
public PageData<AiModel> findAiModelsByTenantId(TenantId tenantId, Boolean availableViaApi, PageLink pageLink) {
validatePageLink(pageLink, AiModelEntity.ALLOWED_SORT_PROPERTIES);
return aiModelDao.findAllByTenantId(tenantId, pageLink);
return aiModelDao.findByTenantId(tenantId, availableViaApi, pageLink);
}
@Override

1
dao/src/main/java/org/thingsboard/server/dao/model/ModelConstants.java

@ -1085,6 +1085,7 @@ public class ModelConstants {
public static final String AI_MODEL_TENANT_ID_COLUMN_NAME = TENANT_ID_COLUMN;
public static final String AI_MODEL_NAME_COLUMN_NAME = NAME_PROPERTY;
public static final String AI_MODEL_CONFIGURATION_COLUMN_NAME = "configuration";
public static final String AI_MODEL_AVAILABLE_VIA_API_COLUMN_NAME = "available_via_api";
/**
* Api Key constants.

5
dao/src/main/java/org/thingsboard/server/dao/model/sql/AiModelEntity.java

@ -53,6 +53,9 @@ public class AiModelEntity extends BaseVersionedEntity<AiModel> {
@Column(name = ModelConstants.AI_MODEL_CONFIGURATION_COLUMN_NAME, nullable = false, columnDefinition = "JSONB")
private AiModelConfig configuration;
@Column(name = ModelConstants.AI_MODEL_AVAILABLE_VIA_API_COLUMN_NAME, nullable = false)
private boolean availableViaApi;
@Column(name = ModelConstants.EXTERNAL_ID_PROPERTY, columnDefinition = "UUID")
private UUID externalId;
@ -63,6 +66,7 @@ public class AiModelEntity extends BaseVersionedEntity<AiModel> {
tenantId = getTenantUuid(aiModel.getTenantId());
name = aiModel.getName();
configuration = aiModel.getConfiguration();
availableViaApi = aiModel.isAvailableViaApi();
externalId = getUuid(aiModel.getExternalId());
}
@ -74,6 +78,7 @@ public class AiModelEntity extends BaseVersionedEntity<AiModel> {
model.setTenantId(TenantId.fromUUID(tenantId));
model.setName(name);
model.setConfiguration(configuration);
model.setAvailableViaApi(availableViaApi);
model.setExternalId(getEntityId(externalId, AiModelId::new));
return model;
}

7
dao/src/main/java/org/thingsboard/server/dao/sql/ai/AiModelRepository.java

@ -30,6 +30,7 @@ interface AiModelRepository extends JpaRepository<AiModelEntity, UUID>, Exportab
SELECT *
FROM ai_model model
WHERE model.tenant_id = :tenantId
AND (CAST(:availableViaApi AS BOOLEAN) IS NULL OR model.available_via_api = CAST(:availableViaApi AS BOOLEAN))
AND (:textSearch IS NULL
OR model.name ILIKE '%' || :textSearch || '%'
OR REPLACE(model.configuration ->> 'provider', '_', ' ') ILIKE '%' || :textSearch || '%'
@ -39,6 +40,7 @@ interface AiModelRepository extends JpaRepository<AiModelEntity, UUID>, Exportab
SELECT COUNT(*)
FROM ai_model model
WHERE model.tenant_id = :tenantId
AND (CAST(:availableViaApi AS BOOLEAN) IS NULL OR model.available_via_api = CAST(:availableViaApi AS BOOLEAN))
AND (:textSearch IS NULL
OR model.name ILIKE '%' || :textSearch || '%'
OR REPLACE(model.configuration ->> 'provider', '_', ' ') ILIKE '%' || :textSearch || '%'
@ -46,7 +48,10 @@ interface AiModelRepository extends JpaRepository<AiModelEntity, UUID>, Exportab
""",
nativeQuery = true
)
Page<AiModelEntity> findByTenantId(@Param("tenantId") UUID tenantId, @Param("textSearch") String textSearch, Pageable pageable);
Page<AiModelEntity> findByTenantId(@Param("tenantId") UUID tenantId,
@Param("availableViaApi") Boolean availableViaApi,
@Param("textSearch") String textSearch,
Pageable pageable);
@Query("SELECT ai_model.id FROM AiModelEntity ai_model WHERE ai_model.tenantId = :tenantId")
Page<UUID> findIdsByTenantId(@Param("tenantId") UUID tenantId, Pageable pageable);

7
dao/src/main/java/org/thingsboard/server/dao/sql/ai/JpaAiModelDao.java

@ -61,8 +61,13 @@ class JpaAiModelDao extends JpaAbstractDao<AiModelEntity, AiModel> implements Ai
@Override
public PageData<AiModel> findByTenantId(UUID tenantId, PageLink pageLink) {
return findByTenantId(TenantId.fromUUID(tenantId), null, pageLink);
}
@Override
public PageData<AiModel> findByTenantId(TenantId tenantId, Boolean availableViaApi, PageLink pageLink) {
return DaoUtil.toPageData(aiModelRepository.findByTenantId(
tenantId, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), toPageRequest(pageLink))
tenantId.getId(), availableViaApi, StringUtils.defaultIfEmpty(pageLink.getTextSearch(), null), toPageRequest(pageLink))
);
}

15
dao/src/main/resources/sql/schema-entities.sql

@ -1369,13 +1369,14 @@ CREATE TABLE IF NOT EXISTS report (
) PARTITION BY RANGE (created_time);
CREATE TABLE IF NOT EXISTS ai_model (
id UUID NOT NULL PRIMARY KEY,
external_id UUID,
created_time BIGINT NOT NULL,
tenant_id UUID NOT NULL,
version BIGINT NOT NULL DEFAULT 1,
name VARCHAR(255) NOT NULL,
configuration JSONB NOT NULL,
id UUID NOT NULL PRIMARY KEY,
external_id UUID,
created_time BIGINT NOT NULL,
tenant_id UUID NOT NULL,
version BIGINT NOT NULL DEFAULT 1,
name VARCHAR(255) NOT NULL,
configuration JSONB NOT NULL,
available_via_api BOOLEAN NOT NULL DEFAULT FALSE,
CONSTRAINT ai_model_name_unq_key UNIQUE (tenant_id, name),
CONSTRAINT ai_model_external_id_unq_key UNIQUE (tenant_id, external_id)
);

6
ui-ngx/src/app/modules/home/components/ai-model/ai-model-dialog.component.html

@ -39,6 +39,12 @@
</mat-error>
}
</mat-form-field>
<div class="tb-form-row no-border no-padding"
tb-hint-tooltip-icon="{{ 'ai-models.available-via-api-hint' | translate }}">
<mat-slide-toggle class="mat-slide" formControlName="availableViaApi">
{{ 'ai-models.available-via-api' | translate }}
</mat-slide-toggle>
</div>
</section>
<div formGroupName="configuration" class="tb-form-panel no-border no-padding">
<section class="tb-form-panel stroked no-padding-bottom">

1
ui-ngx/src/app/modules/home/components/ai-model/ai-model-dialog.component.ts

@ -90,6 +90,7 @@ export class AIModelDialogComponent extends DialogComponent<AIModelDialogCompone
this.aiModelForms = this.fb.group({
name: [this.data.AIModel ? this.data.AIModel.name : '', [Validators.required, Validators.maxLength(255), Validators.pattern(/.*\S.*/)]],
modelType: [ModelType.CHAT],
availableViaApi: [this.data.AIModel?.availableViaApi ?? false],
configuration: this.fb.group({
provider: [this.provider, []],
providerConfig: this.fb.group({

1
ui-ngx/src/app/shared/models/ai-model.models.ts

@ -6,6 +6,7 @@ import { AiModelId } from '@shared/models/id/ai-model-id';
export interface AiModel extends Omit<BaseData<AiModelId>, 'label'>, HasTenantId, ExportableEntity<AiModelId> {
modelType: ModelType;
availableViaApi?: boolean;
configuration: {
provider: AiProvider
providerConfig: {

3
ui-ngx/src/app/shared/models/security.models.ts

@ -37,7 +37,8 @@ export enum Operation {
SHARE_GROUP = 'SHARE_GROUP',
ASSIGN_TO_TENANT = 'ASSIGN_TO_TENANT',
READ_CALCULATED_FIELD = 'READ_CALCULATED_FIELD',
WRITE_CALCULATED_FIELD = 'WRITE_CALCULATED_FIELD'
WRITE_CALCULATED_FIELD = 'WRITE_CALCULATED_FIELD',
INVOKE = 'INVOKE'
}
const operationTypeTranslations = new Map<Operation, string>();

5
ui-ngx/src/assets/locale/locale.constant-en_US.json

@ -1880,6 +1880,8 @@
"model": "Model",
"name": "Name",
"ai-provider": "AI provider",
"available-via-api": "Available via API",
"available-via-api-hint": "Allows users with the 'Invoke' permission for AI models to send chat requests to this model via REST API, e.g. from Trendz Analytics. Roles that grant all operations, such as the default 'Customer Administrator' role, include 'Invoke', so every user with such a role can call this model. The model configuration and credentials are never exposed. Customer users can only be granted the 'Invoke' operation for AI models.",
"no-found": "No AI models found",
"list": "{ count, plural, =1 {One model} other {List of # models} }",
"selected-fields": "{ count, plural, =1 {1 model} other {# models} } selected",
@ -8848,7 +8850,8 @@
"SHARE_GROUP": "Share Group",
"ASSIGN_TO_TENANT": "Assign to Tenant",
"READ_CALCULATED_FIELD": "Read Calculated Field and Alarm Rules",
"WRITE_CALCULATED_FIELD": "Write Calculated Field and Alarm Rules"
"WRITE_CALCULATED_FIELD": "Write Calculated Field and Alarm Rules",
"INVOKE": "Invoke"
}
}
},

Loading…
Cancel
Save