LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
v2 changes of tool_instance and usage (#470)
ali9354480518a6
diff --git a/backend/tool_instance_v2/__init__.py b/backend/tool_instance_v2/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/tool_instance_v2/admin.py b/backend/tool_instance_v2/admin.pynew file mode 100644index 000000000..1e1c975ca--- /dev/null+++ b/backend/tool_instance_v2/admin.py@@ -0,0 +1,5 @@+from django.contrib import admin++from .models import ToolInstance++admin.site.register(ToolInstance)diff --git a/backend/tool_instance_v2/apps.py b/backend/tool_instance_v2/apps.pynew file mode 100644index 000000000..b75d98958--- /dev/null+++ b/backend/tool_instance_v2/apps.py@@ -0,0 +1,5 @@+from django.apps import AppConfig+++class ToolInstanceConfig(AppConfig):+ name = "tool_instance_v2"diff --git a/backend/tool_instance_v2/constants.py b/backend/tool_instance_v2/constants.pynew file mode 100644index 000000000..17a3891c5--- /dev/null+++ b/backend/tool_instance_v2/constants.py@@ -0,0 +1,45 @@+class ToolInstanceKey:+ """Dict keys for ToolInstance model."""++ PK = "id"+ TOOL_ID = "tool_id"+ VERSION = "version"+ METADATA = "metadata"+ STEP = "step"+ STATUS = "status"+ WORKFLOW = "workflow"+ INPUT = "input"+ OUTPUT = "output"+ TI_COUNT = "tool_instance_count"+++class JsonSchemaKey:+ """Dict Keys for Tool's Json schema."""++ PROPERTIES = "properties"+ THEN = "then"+ INPUT_FILE_CONNECTOR = "inputFileConnector"+ OUTPUT_FILE_CONNECTOR = "outputFileConnector"+ OUTPUT_FOLDER = "outputFolder"+ ROOT_FOLDER = "rootFolder"+ TENANT_ID = "tenant_id"+ INPUT_DB_CONNECTOR = "inputDBConnector"+ OUTPUT_DB_CONNECTOR = "outputDBConnector"+ ENUM = "enum"+ PROJECT_DEFAULT = "Project Default"+++class ToolInstanceErrors:+ TOOL_EXISTS = "Tool with this configuration already exists."+ DUPLICATE_API = "It appears that a duplicate call may have been made."+++class ToolKey:+ """Dict keys for a Tool."""++ NAME = "name"+ DESCRIPTION = "description"+ ICON = "icon"+ FUNCTION_NAME = "function_name"+ OUTPUT_TYPE = "output_type"+ INPUT_TYPE = "input_type"diff --git a/backend/tool_instance_v2/exceptions.py b/backend/tool_instance_v2/exceptions.pynew file mode 100644index 000000000..69c2c26a5--- /dev/null+++ b/backend/tool_instance_v2/exceptions.py@@ -0,0 +1,46 @@+from typing import Optional++from rest_framework.exceptions import APIException+++class ToolInstanceBaseException(APIException):+ def __init__(+ self,+ detail: Optional[str] = None,+ code: Optional[int] = None,+ tool_name: Optional[str] = None,+ ) -> None:+ detail = detail or self.default_detail+ if tool_name is not None:+ detail = f"{detail} Tool: {tool_name}"+ super().__init__(detail, code)+++class ToolFunctionIsMandatory(ToolInstanceBaseException):+ status_code = 400+ default_detail = "Tool function is mandatory."+++class ToolDoesNotExist(ToolInstanceBaseException):+ status_code = 400+ default_detail = "Tool doesn't exist."+++class FetchToolListFailed(ToolInstanceBaseException):+ status_code = 400+ default_detail = "Failed to fetch tool list."+++class ToolInstantiationError(ToolInstanceBaseException):+ status_code = 500+ default_detail = "Error instantiating tool."+++class BadRequestException(ToolInstanceBaseException):+ status_code = 400+ default_detail = "Invalid input."+++class ToolSettingValidationError(APIException):+ status_code = 400+ default_detail = "Error while validating tool's setting."diff --git a/backend/tool_instance_v2/models.py b/backend/tool_instance_v2/models.pynew file mode 100644index 000000000..a7609566d--- /dev/null+++ b/backend/tool_instance_v2/models.py@@ -0,0 +1,99 @@+import uuid++from account_v2.models import User+from connector_v2.models import ConnectorInstance+from django.db import models+from django.db.models import QuerySet+from utils.models.base_model import BaseModel+from workflow_manager.workflow_v2.models.workflow import Workflow++TOOL_ID_LENGTH = 64+TOOL_VERSION_LENGTH = 16+TOOL_STATUS_LENGTH = 32+++class ToolInstanceManager(models.Manager):+ def get_instances_for_workflow(+ self, workflow: uuid.UUID+ ) -> QuerySet["ToolInstance"]:+ return self.filter(workflow=workflow)+++class ToolInstance(BaseModel):+ class Status(models.TextChoices):+ PENDING = "PENDING", "Settings Not Configured"+ READY = "READY", "Ready to Start"+ INITIATED = "INITIATED", "Initialization in Progress"+ COMPLETED = "COMPLETED", "Process Completed"+ ERROR = "ERROR", "Error Encountered"++ workflow = models.ForeignKey(+ Workflow,+ on_delete=models.CASCADE,+ related_name="tool_instances",+ null=False,+ blank=False,+ )+ id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)+ tool_id = models.CharField(+ max_length=TOOL_ID_LENGTH,+ db_comment="Function name of the tool being used",+ )+ input = models.JSONField(null=True, db_comment="Provisional WF input to a tool")+ output = models.JSONField(null=True, db_comment="Provisional WF output to a tool")+ version = models.CharField(max_length=TOOL_VERSION_LENGTH)+ metadata = models.JSONField(db_comment="Stores config for a tool")+ step = models.IntegerField()+ # TODO: Make as an enum supporting fixed values once we have clarity+ status = models.CharField(max_length=TOOL_STATUS_LENGTH, default="Ready to start")+ created_by = models.ForeignKey(+ User,+ on_delete=models.SET_NULL,+ related_name="tool_instances_created",+ null=True,+ blank=True,+ )+ modified_by = models.ForeignKey(+ User,+ on_delete=models.SET_NULL,+ related_name="tool_instances_modified",+ null=True,+ blank=True,+ )+ # Added these connectors separately+ # for file and db for scalability+ input_file_connector = models.ForeignKey(+ ConnectorInstance,+ on_delete=models.SET_NULL,+ related_name="input_file_connectors",+ null=True,+ blank=True,+ )+ output_file_connector = models.ForeignKey(+ ConnectorInstance,+ on_delete=models.SET_NULL,+ related_name="output_file_connectors",+ null=True,+ blank=True,+ )+ input_db_connector = models.ForeignKey(+ ConnectorInstance,+ on_delete=models.SET_NULL,+ related_name="input_db_connectors",+ null=True,+ blank=True,+ )+ output_db_connector = models.ForeignKey(+ ConnectorInstance,+ on_delete=models.SET_NULL,+ related_name="output_db_connectors",+ null=True,+ blank=True,+ )++ objects = ToolInstanceManager()++ class Meta:+ verbose_name = "Tool Instance"+ verbose_name_plural = "Tool Instances"+ db_table = "tool_instance_v2"diff --git a/backend/tool_instance_v2/serializers.py b/backend/tool_instance_v2/serializers.pynew file mode 100644index 000000000..86801545d--- /dev/null+++ b/backend/tool_instance_v2/serializers.py@@ -0,0 +1,129 @@+import logging+import uuid+from typing import Any++from prompt_studio.prompt_studio_registry_v2.constants import PromptStudioRegistryKeys+from rest_framework.serializers import ListField, Serializer, UUIDField, ValidationError+from tool_instance_v2.constants import ToolInstanceKey as TIKey+from tool_instance_v2.constants import ToolKey+from tool_instance_v2.exceptions import ToolDoesNotExist+from tool_instance_v2.models import ToolInstance+from tool_instance_v2.tool_instance_helper import ToolInstanceHelper+from tool_instance_v2.tool_processor import ToolProcessor+from unstract.tool_registry.dto import Tool+from workflow_manager.workflow_v2.constants import WorkflowKey+from workflow_manager.workflow_v2.models.workflow import Workflow++from backend.constants import RequestKey+from backend.serializers import AuditSerializer++logger = logging.getLogger(__name__)+++class ToolInstanceSerializer(AuditSerializer):+ workflow_id = UUIDField(write_only=True)++ class Meta:+ model = ToolInstance+ fields = "__all__"+ extra_kwargs = {+ TIKey.WORKFLOW: {+ "required": False,+ },+ TIKey.VERSION: {+ "required": False,+ },+ TIKey.METADATA: {+ "required": False,+ },+ TIKey.STEP: {+ "required": False,+ },+ }++ def to_representation(self, instance: ToolInstance) -> dict[str, str]:+ rep: dict[str, Any] = super().to_representation(instance)+ tool_function = rep.get(TIKey.TOOL_ID)++ if tool_function is None:+ raise ToolDoesNotExist()+ try:+ tool: Tool = ToolProcessor.get_tool_by_uid(tool_function)+ except ToolDoesNotExist:+ return rep+ rep[ToolKey.ICON] = tool.icon+ rep[ToolKey.NAME] = tool.properties.display_name+ # Need to Change it into better method+ if self.context.get(RequestKey.REQUEST):+ metadata = ToolInstanceHelper.get_altered_metadata(instance)+ if metadata:+ rep[TIKey.METADATA] = metadata+ return rep++ def create(self, validated_data: dict[str, Any]) -> Any:+ workflow_id = validated_data.pop(WorkflowKey.WF_ID)+ try:+ workflow = Workflow.objects.get(pk=workflow_id)+ except Workflow.DoesNotExist:+ raise ValidationError(f"Workflow with ID {workflow_id} does not exist.")+ validated_data[TIKey.WORKFLOW] = workflow++ tool_uid = validated_data.get(TIKey.TOOL_ID)+ if not tool_uid:+ raise ToolDoesNotExist()++ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uid)+ # TODO: Handle other fields once tools SDK is out+ validated_data[TIKey.PK] = uuid.uuid4()+ # TODO: Use version from tool props+ validated_data[TIKey.VERSION] = ""+ validated_data[TIKey.METADATA] = {+ # TODO: Review and remove tool instance ID+ WorkflowKey.WF_TOOL_INSTANCE_ID: str(validated_data[TIKey.PK]),+ PromptStudioRegistryKeys.PROMPT_REGISTRY_ID: str(tool_uid),+ **ToolProcessor.get_default_settings(tool),+ }+ if TIKey.STEP not in validated_data:+ validated_data[TIKey.STEP] = workflow.tool_instances.count() + 1+ # Workflow will get activated on adding tools to workflow+ if not workflow.is_active:+ workflow.is_active = True+ workflow.save()+ return super().create(validated_data)+++class ToolInstanceReorderSerializer(Serializer):+ workflow_id = UUIDField()+ tool_instances = ListField(child=UUIDField())++ def validate(self, data: dict[str, Any]) -> dict[str, Any]:+ workflow_id = data.get(WorkflowKey.WF_ID)+ tool_instances = data.get(WorkflowKey.WF_TOOL_INSTANCES, [])++ # Check if the workflow exists+ try:+ workflow = Workflow.objects.get(pk=workflow_id)+ except Workflow.DoesNotExist:+ raise ValidationError(f"Workflow with ID {workflow_id} does not exist.")++ # Check if the number of tool instances matches the actual count+ tool_instance_count = workflow.tool_instances.count()+ if len(tool_instances) != tool_instance_count:+ msg = (+ f"Incorrect number of tool instances passed: "+ f"{len(tool_instances)}, expected: {tool_instance_count}"+ )+ logger.error(msg)+ raise ValidationError(detail=msg)++ # Check if each tool instance exists in the workflow+ existing_tool_instance_ids = workflow.tool_instances.values_list(+ "id", flat=True+ )+ for tool_instance_id in tool_instances:+ if tool_instance_id not in existing_tool_instance_ids:+ raise ValidationError(+ "One or more tool instances do not exist in the workflow."+ )++ return datadiff --git a/backend/tool_instance_v2/tool_instance_helper.py b/backend/tool_instance_v2/tool_instance_helper.pynew file mode 100644index 000000000..a1ba2adda--- /dev/null+++ b/backend/tool_instance_v2/tool_instance_helper.py@@ -0,0 +1,458 @@+import logging+import os+import uuid+from typing import Any, Optional++from account_v2.models import User+from adapter_processor_v2.adapter_processor import AdapterProcessor+from adapter_processor_v2.models import AdapterInstance+from connector_v2.connector_instance_helper import ConnectorInstanceHelper+from django.core.exceptions import PermissionDenied+from django.core.exceptions import ValidationError as DjangoValidationError+from jsonschema.exceptions import ValidationError as JSONValidationError+from prompt_studio.prompt_studio_registry_v2.models import PromptStudioRegistry+from tool_instance_v2.constants import JsonSchemaKey+from tool_instance_v2.exceptions import ToolSettingValidationError+from tool_instance_v2.models import ToolInstance+from tool_instance_v2.tool_processor import ToolProcessor+from unstract.adapters.enums import AdapterTypes+from unstract.sdk.tool.validator import DefaultsGeneratingValidator+from unstract.tool_registry.constants import AdapterPropertyKey+from unstract.tool_registry.dto import Spec, Tool+from unstract.tool_registry.tool_utils import ToolUtils+from workflow_manager.workflow_v2.constants import WorkflowKey++logger = logging.getLogger(__name__)+++class ToolInstanceHelper:+ @staticmethod+ def get_tool_instances_by_workflow(+ workflow_id: str,+ order_by: str,+ lookup: Optional[dict[str, Any]] = None,+ offset: Optional[int] = None,+ limit: Optional[int] = None,+ ) -> list[ToolInstance]:+ wf_filter = {}+ if lookup:+ wf_filter = lookup+ wf_filter[WorkflowKey.WF_ID] = workflow_id++ if limit:+ offset_value = 0 if not offset else offset+ to = offset_value + limit+ return list(+ ToolInstance.objects.filter(**wf_filter)[offset_value:to].order_by(+ order_by+ )+ )+ return list(ToolInstance.objects.filter(**wf_filter).all().order_by(order_by))++ @staticmethod+ def update_instance_metadata(+ org_id: str, tool_instance: ToolInstance, metadata: dict[str, Any]+ ) -> None:+ if (+ JsonSchemaKey.OUTPUT_FILE_CONNECTOR in metadata+ and JsonSchemaKey.OUTPUT_FOLDER in metadata+ ):+ output_connector_name = metadata[JsonSchemaKey.OUTPUT_FILE_CONNECTOR]+ output_connector = ConnectorInstanceHelper.get_output_connector_instance_by_name_for_workflow( # noqa+ tool_instance.workflow_id, output_connector_name+ )+ if output_connector and "path" in output_connector.metadata:+ metadata[JsonSchemaKey.OUTPUT_FOLDER] = os.path.join(+ output_connector.metadata["path"],+ *(metadata[JsonSchemaKey.OUTPUT_FOLDER].split("/")),+ )+ if (+ JsonSchemaKey.INPUT_FILE_CONNECTOR in metadata+ and JsonSchemaKey.ROOT_FOLDER in metadata+ ):+ input_connector_name = metadata[JsonSchemaKey.INPUT_FILE_CONNECTOR]+ input_connector = ConnectorInstanceHelper.get_input_connector_instance_by_name_for_workflow( # noqa+ tool_instance.workflow_id, input_connector_name+ )++ if input_connector and "path" in input_connector.metadata:+ metadata[JsonSchemaKey.ROOT_FOLDER] = os.path.join(+ input_connector.metadata["path"],+ *(metadata[JsonSchemaKey.ROOT_FOLDER].split("/")),+ )+ ToolInstanceHelper.update_metadata_with_adapter_instances(+ metadata, tool_instance.tool_id+ )+ metadata[JsonSchemaKey.TENANT_ID] = org_id+ tool_instance.metadata = metadata+ tool_instance.save()++ @staticmethod+ def update_metadata_with_adapter_properties(+ metadata: dict[str, Any],+ adapter_key: str,+ adapter_property: dict[str, Any],+ adapter_type: AdapterTypes,+ ) -> None:+ """Update the metadata dictionary with adapter properties.++ Parameters:+ metadata (dict[str, Any]):+ The metadata dictionary to be updated with adapter properties.+ adapter_key (str):+ The key in the metadata dictionary corresponding to the adapter.+ adapter_property (dict[str, Any]):+ The properties of the adapter.+ adapter_type (AdapterTypes):+ The type of the adapter.++ Returns:+ None+ """+ if adapter_key in metadata:+ adapter_name = metadata[adapter_key]+ adapter = AdapterProcessor.get_adapter_by_name_and_type(+ adapter_type=adapter_type, adapter_name=adapter_name+ )+ adapter_id = str(adapter.id) if adapter else None+ metadata_key_for_id = adapter_property.get(+ AdapterPropertyKey.ADAPTER_ID_KEY, AdapterPropertyKey.ADAPTER_ID+ )+ metadata[metadata_key_for_id] = adapter_id++ @staticmethod+ def update_metadata_with_adapter_instances(+ metadata: dict[str, Any], tool_uid: str+ ) -> None:+ """+ Update the metadata dictionary with adapter instances.+ Parameters:+ metadata (dict[str, Any]):+ The metadata dictionary to be updated with adapter instances.++ Returns:+ None+ """+ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uid)+ schema: Spec = ToolUtils.get_json_schema_for_tool(tool)+ llm_properties = schema.get_llm_adapter_properties()+ embedding_properties = schema.get_embedding_adapter_properties()+ vector_db_properties = schema.get_vector_db_adapter_properties()+ x2text_properties = schema.get_text_extractor_adapter_properties()+ ocr_properties = schema.get_ocr_adapter_properties()++ for adapter_key, adapter_property in llm_properties.items():+ ToolInstanceHelper.update_metadata_with_adapter_properties(+ metadata=metadata,+ adapter_key=adapter_key,+ adapter_property=adapter_property,+ adapter_type=AdapterTypes.LLM,+ )++ for adapter_key, adapter_property in embedding_properties.items():+ ToolInstanceHelper.update_metadata_with_adapter_properties(+ metadata=metadata,+ adapter_key=adapter_key,+ adapter_property=adapter_property,+ adapter_type=AdapterTypes.EMBEDDING,+ )++ for adapter_key, adapter_property in vector_db_properties.items():+ ToolInstanceHelper.update_metadata_with_adapter_properties(+ metadata=metadata,+ adapter_key=adapter_key,+ adapter_property=adapter_property,+ adapter_type=AdapterTypes.VECTOR_DB,+ )++ for adapter_key, adapter_property in x2text_properties.items():+ ToolInstanceHelper.update_metadata_with_adapter_properties(+ metadata=metadata,+ adapter_key=adapter_key,+ adapter_property=adapter_property,+ adapter_type=AdapterTypes.X2TEXT,+ )++ for adapter_key, adapter_property in ocr_properties.items():+ ToolInstanceHelper.update_metadata_with_adapter_properties(+ metadata=metadata,+ adapter_key=adapter_key,+ adapter_property=adapter_property,+ adapter_type=AdapterTypes.OCR,+ )++ # TODO: Review if adding this metadata is still required+ @staticmethod+ def get_altered_metadata(+ tool_instance: ToolInstance,+ ) -> Optional[dict[str, Any]]:+ """Get altered metadata by resolving relative paths.++ This method retrieves the metadata from the given tool instance+ and checks if there are output and input file connectors.+ If output and input file connectors exist in the metadata,+ it resolves the relative paths using connector instances.++ Args:+ tool_instance (ToolInstance).++ Returns:+ Optional[dict[str, Any]]: Altered metadata with resolved relative \+ paths.+ """+ metadata: dict[str, Any] = tool_instance.metadata+ if (+ JsonSchemaKey.OUTPUT_FILE_CONNECTOR in metadata+ and JsonSchemaKey.OUTPUT_FOLDER in metadata+ ):+ output_connector_name = metadata[JsonSchemaKey.OUTPUT_FILE_CONNECTOR]+ output_connector = ConnectorInstanceHelper.get_output_connector_instance_by_name_for_workflow( # noqa+ tool_instance.workflow_id, output_connector_name+ )+ if output_connector and "path" in output_connector.metadata:+ relative_path = ToolInstanceHelper.get_relative_path(+ metadata[JsonSchemaKey.OUTPUT_FOLDER],+ output_connector.metadata["path"],+ )+ metadata[JsonSchemaKey.OUTPUT_FOLDER] = relative_path+ if (+ JsonSchemaKey.INPUT_FILE_CONNECTOR in metadata+ and JsonSchemaKey.ROOT_FOLDER in metadata+ ):+ input_connector_name = metadata[JsonSchemaKey.INPUT_FILE_CONNECTOR]+ input_connector = ConnectorInstanceHelper.get_input_connector_instance_by_name_for_workflow( # noqa+ tool_instance.workflow_id, input_connector_name+ )+ if input_connector and "path" in input_connector.metadata:+ relative_path = ToolInstanceHelper.get_relative_path(+ metadata[JsonSchemaKey.ROOT_FOLDER],+ input_connector.metadata["path"],+ )+ metadata[JsonSchemaKey.ROOT_FOLDER] = relative_path+ return metadata++ @staticmethod+ def update_metadata_with_default_adapter(+ adapter_type: AdapterTypes,+ schema_spec: Spec,+ adapter: AdapterInstance,+ metadata: dict[str, Any],+ ) -> None:+ """Update the metadata of a tool instance with default values for+ enabled adapters.++ Parameters:+ adapter_type (AdapterTypes): The type of adapter to update+ the metadata for.+ schema_spec (Spec): The schema specification for the tool.+ adapter (AdapterInstance): The adapter instance to use for updating+ the metadata.+ metadata (dict[str, Any]): The metadata dictionary to update.++ Returns:+ None+ """+ properties = {}+ if adapter_type == AdapterTypes.LLM:+ properties = schema_spec.get_llm_adapter_properties()+ if adapter_type == AdapterTypes.EMBEDDING:+ properties = schema_spec.get_embedding_adapter_properties()+ if adapter_type == AdapterTypes.VECTOR_DB:+ properties = schema_spec.get_vector_db_adapter_properties()+ if adapter_type == AdapterTypes.X2TEXT:+ properties = schema_spec.get_text_extractor_adapter_properties()+ if adapter_type == AdapterTypes.OCR:+ properties = schema_spec.get_ocr_adapter_properties()+ for adapter_key, adapter_property in properties.items():+ metadata_key_for_id = adapter_property.get(+ AdapterPropertyKey.ADAPTER_ID_KEY, AdapterPropertyKey.ADAPTER_ID+ )+ metadata[adapter_key] = adapter.adapter_name+ metadata[metadata_key_for_id] = str(adapter.id)++ @staticmethod+ def update_metadata_with_default_values(+ tool_instance: ToolInstance, user: User+ ) -> None:+ """Update the metadata of a tool instance with default values for+ enabled adapters.++ Parameters:+ tool_instance (ToolInstance): The tool instance to update the+ metadata.++ Returns:+ None+ """+ metadata: dict[str, Any] = tool_instance.metadata+ tool_uuid = tool_instance.tool_id++ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uuid)+ schema: Spec = ToolUtils.get_json_schema_for_tool(tool)++ default_adapters = AdapterProcessor.get_default_adapters(user=user)+ for adapter in default_adapters:+ try:+ adapter_type = AdapterTypes(adapter.adapter_type)+ ToolInstanceHelper.update_metadata_with_default_adapter(+ adapter_type=adapter_type,+ schema_spec=schema,+ adapter=adapter,+ metadata=metadata,+ )+ except ValueError:+ logger.warning(f"Invalid AdapterType {adapter.adapter_type}")+ tool_instance.metadata = metadata+ tool_instance.save()++ @staticmethod+ def get_relative_path(absolute_path: str, base_path: str) -> str:+ if absolute_path.startswith(base_path):+ relative_path = os.path.relpath(absolute_path, base_path)+ else:+ relative_path = absolute_path+ if relative_path == ".":+ relative_path = ""+ return relative_path++ @staticmethod+ def reorder_tool_instances(instances_to_reorder: list[uuid.UUID]) -> None:+ """Reorders tool instances based on the list of tool UUIDs received.+ Saves the instance in the DB.++ Args:+ instances_to_reorder (list[uuid.UUID]): Desired order of tool UUIDs+ """+ logger.info(f"Reordering instances: {instances_to_reorder}")+ for step, tool_instance_id in enumerate(instances_to_reorder):+ tool_instance = ToolInstance.objects.get(pk=tool_instance_id)+ tool_instance.step = step + 1+ tool_instance.save()++ @staticmethod+ def validate_tool_settings(+ user: User, tool_uid: str, tool_meta: dict[str, Any]+ ) -> bool:+ """Function to validate Tools settings."""++ # check if exported tool is valid for the user who created workflow+ ToolInstanceHelper.validate_tool_access(user=user, tool_uid=tool_uid)+ ToolInstanceHelper.validate_adapter_permissions(+ user=user, tool_uid=tool_uid, tool_meta=tool_meta+ )++ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uid)+ tool_name: str = (+ tool.properties.display_name if tool.properties.display_name else tool_uid+ )+ schema_json: dict[str, Any] = ToolProcessor.get_json_schema_for_tool(+ tool_uid=tool_uid, user=user+ )+ try:+ DefaultsGeneratingValidator(schema_json).validate(tool_meta)+ except JSONValidationError as e:+ logger.error(e, stack_info=True, exc_info=True)+ err_msg = e.message+ # TODO: Support other JSON validation errors or consider following+ # https://github.com/networknt/json-schema-validator/blob/master/doc/cust-msg.md+ if e.validator == "required":+ for validator_val in e.validator_value:+ required_prop = e.schema.get("properties").get(validator_val)+ required_display_name = required_prop.get("title")+ err_msg = err_msg.replace(validator_val, required_display_name)+ else:+ logger.warning(f"Unformatted exception sent to user: {err_msg}")+ raise ToolSettingValidationError(+ f"Error validating tool settings for '{tool_name}': {err_msg}"+ )+ return True++ @staticmethod+ def validate_adapter_permissions(+ user: User, tool_uid: str, tool_meta: dict[str, Any]+ ) -> None:+ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uid)+ adapter_ids: set[str] = set()++ for llm in tool.properties.adapter.language_models:+ if llm.is_enabled and llm.adapter_id:+ adapter_id = tool_meta[llm.adapter_id]+ elif llm.is_enabled:+ adapter_id = tool_meta[AdapterPropertyKey.DEFAULT_LLM_ADAPTER_ID]++ adapter_ids.add(adapter_id)+ for vdb in tool.properties.adapter.vector_stores:+ if vdb.is_enabled and vdb.adapter_id:+ adapter_id = tool_meta[vdb.adapter_id]+ elif vdb.is_enabled:+ adapter_id = tool_meta[AdapterPropertyKey.DEFAULT_VECTOR_DB_ADAPTER_ID]++ adapter_ids.add(adapter_id)+ for embedding in tool.properties.adapter.embedding_services:+ if embedding.is_enabled and embedding.adapter_id:+ adapter_id = tool_meta[embedding.adapter_id]+ elif embedding.is_enabled:+ adapter_id = tool_meta[AdapterPropertyKey.DEFAULT_EMBEDDING_ADAPTER_ID]++ adapter_ids.add(adapter_id)+ for text_extractor in tool.properties.adapter.text_extractors:+ if text_extractor.is_enabled and text_extractor.adapter_id:+ adapter_id = tool_meta[text_extractor.adapter_id]+ elif text_extractor.is_enabled:+ adapter_id = tool_meta[AdapterPropertyKey.DEFAULT_X2TEXT_ADAPTER_ID]++ adapter_ids.add(adapter_id)++ ToolInstanceHelper.validate_adapter_access(user=user, adapter_ids=adapter_ids)++ @staticmethod+ def validate_adapter_access(+ user: User,+ adapter_ids: set[str],+ ) -> None:+ adapter_instances = AdapterInstance.objects.filter(id__in=adapter_ids).all()++ for adapter_instance in adapter_instances:+ if not adapter_instance.is_usable:+ logger.error(+ "Free usage for the configured sample adapter %s exhausted",+ adapter_instance.id,+ )+ error_msg = "Permission Error: Free usage for the configured trial adapter exhausted.Please connect your own service accounts to continue.Please see our documentation for more details:https://docs.unstract.com/unstract_platform/setup_accounts/whats_needed" # noqa: E501++ raise PermissionDenied(error_msg)++ if not (+ adapter_instance.shared_to_org+ or adapter_instance.created_by == user+ or adapter_instance.shared_users.filter(pk=user.pk).exists()+ ):+ logger.error(+ "User %s doesn't have access to adapter %s",+ user.user_id,+ adapter_instance.id,+ )+ raise PermissionDenied(+ "You don't have permission to perform this action."+ )++ @staticmethod+ def validate_tool_access(+ user: User,+ tool_uid: str,+ ) -> None:+ # HACK: Assume tool_uid is a prompt studio exported tool and query it.+ # We suppress ValidationError when tool_uid is of a static tool.+ try:+ prompt_registry_tool = PromptStudioRegistry.objects.get(pk=tool_uid)+ except DjangoValidationError:+ logger.info(f"Not validating tool access for tool: {tool_uid}")+ return++ if (+ prompt_registry_tool.shared_to_org+ or prompt_registry_tool.shared_users.filter(pk=user.pk).exists()+ ):+ return+ else:+ raise PermissionDenied("You don't have permission to perform this action.")diff --git a/backend/tool_instance_v2/tool_processor.py b/backend/tool_instance_v2/tool_processor.pynew file mode 100644index 000000000..20cb05953--- /dev/null+++ b/backend/tool_instance_v2/tool_processor.py@@ -0,0 +1,137 @@+import logging+from typing import Any, Optional++from account_v2.models import User+from adapter_processor_v2.adapter_processor import AdapterProcessor+from prompt_studio.prompt_studio_registry_v2.prompt_studio_registry_helper import (+ PromptStudioRegistryHelper,+)+from tool_instance_v2.exceptions import ToolDoesNotExist+from unstract.adapters.enums import AdapterTypes+from unstract.tool_registry.dto import Spec, Tool+from unstract.tool_registry.tool_registry import ToolRegistry+from unstract.tool_registry.tool_utils import ToolUtils++logger = logging.getLogger(__name__)+++class ToolProcessor:+ TOOL_NOT_IN_REGISTRY_MESSAGE = "Tool does not exist in registry"+ tool_registry = ToolRegistry()++ @staticmethod+ def get_tool_by_uid(tool_uid: str) -> Tool:+ """Function to get and instantiate a tool for a given tool+ settingsId."""+ tool_registry = ToolRegistry()+ tool: Optional[Tool] = tool_registry.get_tool_by_uid(tool_uid)+ # HACK: Assume tool_uid is prompt_registry_id for fetching a dynamic+ # tool made with Prompt Studio.+ if not tool:+ tool = PromptStudioRegistryHelper.get_tool_by_prompt_registry_id(+ prompt_registry_id=tool_uid+ )+ if not tool:+ raise ToolDoesNotExist(+ f"{ToolProcessor.TOOL_NOT_IN_REGISTRY_MESSAGE}: {tool_uid}"+ )+ return tool++ @staticmethod+ def get_default_settings(tool: Tool) -> dict[str, str]:+ """Function to make and fill settings with default values.++ Args:+ tool (ToolSettings): tool++ Returns:+ dict[str, str]: tool settings+ """+ tool_metadata: dict[str, str] = ToolUtils.get_default_settings(tool)+ return tool_metadata++ @staticmethod+ def get_json_schema_for_tool(tool_uid: str, user: User) -> dict[str, str]:+ """Function to Get JSON Schema for Tools."""+ tool: Tool = ToolProcessor.get_tool_by_uid(tool_uid=tool_uid)+ schema: Spec = ToolUtils.get_json_schema_for_tool(tool)+ ToolProcessor.update_schema_with_adapter_configurations(+ schema=schema, user=user+ )+ schema_json: dict[str, Any] = schema.to_dict()+ return schema_json++ @staticmethod+ def update_schema_with_adapter_configurations(schema: Spec, user: User) -> None:+ """Updates the JSON schema with the available adapter configurations+ for the LLM, embedding, and vector DB adapters.++ Args:+ schema (Spec): The JSON schema object to be updated.++ Returns:+ None. The `schema` object is updated in-place.+ """+ llm_keys = schema.get_llm_adapter_properties_keys()+ embedding_keys = schema.get_embedding_adapter_properties_keys()+ vector_db_keys = schema.get_vector_db_adapter_properties_keys()+ x2text_keys = schema.get_text_extractor_adapter_properties_keys()+ ocr_keys = schema.get_ocr_adapter_properties_keys()++ if llm_keys:+ adapters = AdapterProcessor.get_adapters_by_type(+ AdapterTypes.LLM, user=user+ )+ for key in llm_keys:+ adapter_names = map(lambda adapter: str(adapter.adapter_name), adapters)+ schema.properties[key]["enum"] = list(adapter_names)++ if embedding_keys:+ adapters = AdapterProcessor.get_adapters_by_type(+ AdapterTypes.EMBEDDING, user=user+ )+ for key in embedding_keys:+ adapter_names = map(lambda adapter: str(adapter.adapter_name), adapters)+ schema.properties[key]["enum"] = list(adapter_names)++ if vector_db_keys:+ adapters = AdapterProcessor.get_adapters_by_type(+ AdapterTypes.VECTOR_DB, user=user+ )+ for key in vector_db_keys:+ adapter_names = map(lambda adapter: str(adapter.adapter_name), adapters)+ schema.properties[key]["enum"] = list(adapter_names)++ if x2text_keys:+ adapters = AdapterProcessor.get_adapters_by_type(+ AdapterTypes.X2TEXT, user=user+ )+ for key in x2text_keys:+ adapter_names = map(lambda adapter: str(adapter.adapter_name), adapters)+ schema.properties[key]["enum"] = list(adapter_names)++ if ocr_keys:+ adapters = AdapterProcessor.get_adapters_by_type(+ AdapterTypes.OCR, user=user+ )+ for key in ocr_keys:+ adapter_names = map(lambda adapter: str(adapter.adapter_name), adapters)+ schema.properties[key]["enum"] = list(adapter_names)++ @staticmethod+ def get_tool_list(user: User) -> list[dict[str, Any]]:+ """Function to get a list of tools."""+ tool_registry = ToolRegistry()+ prompt_studio_tools: list[dict[str, Any]] = (+ PromptStudioRegistryHelper.fetch_json_for_registry(user)+ )+ tool_list: list[dict[str, Any]] = tool_registry.fetch_tools_descriptions()+ tool_list = tool_list + prompt_studio_tools+ return tool_list++ @staticmethod+ def get_registry_tools() -> list[Tool]:+ """Function to get a list of tools."""+ tool_registry = ToolRegistry()+ tool_list: list[Tool] = tool_registry.fetch_all_tools()+ return tool_listdiff --git a/backend/tool_instance_v2/urls.py b/backend/tool_instance_v2/urls.pynew file mode 100644index 000000000..411725079--- /dev/null+++ b/backend/tool_instance_v2/urls.py@@ -0,0 +1,46 @@+from django.urls import path+from rest_framework.urlpatterns import format_suffix_patterns+from tool_instance_v2.views import ToolInstanceViewSet++from . import views++tool_instance_list = ToolInstanceViewSet.as_view(+ {+ "get": "list",+ "post": "create",+ }+)+tool_instance_detail = ToolInstanceViewSet.as_view(+ # fmt: off+ {+ "get": "retrieve",+ "put": "update",+ "patch": "partial_update",+ "delete": "destroy"+ }+ # fmt: on+)++tool_instance_reorder = ToolInstanceViewSet.as_view({"post": "reorder"})++urlpatterns = format_suffix_patterns(+ [+ path("tool_instance/", tool_instance_list, name="tool-instance-list"),+ path(+ "tool_instance/<uuid:pk>/",+ tool_instance_detail,+ name="tool-instance-detail",+ ),+ path(+ "tool_settings_schema/",+ views.tool_settings_schema,+ name="tool_settings_schema",+ ),+ path(+ "tool_instance/reorder/",+ tool_instance_reorder,+ name="tool_instance_reorder",+ ),+ path("tool/", views.get_tool_list, name="tool_list"),+ ]+)diff --git a/backend/tool_instance_v2/views.py b/backend/tool_instance_v2/views.pynew file mode 100644index 000000000..7d56c4ec9--- /dev/null+++ b/backend/tool_instance_v2/views.py@@ -0,0 +1,167 @@+import logging+import uuid+from typing import Any++from account_v2.custom_exceptions import DuplicateData+from django.db import IntegrityError+from django.db.models.query import QuerySet+from rest_framework import serializers, status, viewsets+from rest_framework.decorators import api_view+from rest_framework.request import Request+from rest_framework.response import Response+from rest_framework.versioning import URLPathVersioning+from tool_instance_v2.constants import ToolInstanceErrors+from tool_instance_v2.constants import ToolInstanceKey as TIKey+from tool_instance_v2.constants import ToolKey+from tool_instance_v2.exceptions import FetchToolListFailed, ToolFunctionIsMandatory+from tool_instance_v2.models import ToolInstance+from tool_instance_v2.serializers import (+ ToolInstanceReorderSerializer as TIReorderSerializer,+)+from tool_instance_v2.serializers import ToolInstanceSerializer+from tool_instance_v2.tool_instance_helper import ToolInstanceHelper+from tool_instance_v2.tool_processor import ToolProcessor+from utils.filtering import FilterHelper+from utils.user_session import UserSessionUtils+from workflow_manager.workflow_v2.constants import WorkflowKey++from backend.constants import RequestKey++logger = logging.getLogger(__name__)+++@api_view(["GET"])+def tool_settings_schema(request: Request) -> Response:+ if request.method == "GET":+ tool_function = request.GET.get(ToolKey.FUNCTION_NAME)+ if tool_function is None or tool_function == "":+ raise ToolFunctionIsMandatory()++ json_schema = ToolProcessor.get_json_schema_for_tool(+ tool_uid=tool_function, user=request.user+ )+ return Response(data=json_schema, status=status.HTTP_200_OK)+++@api_view(("GET",))+def get_tool_list(request: Request) -> Response:+ """Get tool list.++ Fetches a list of tools available in the Tool registry+ """+ if request.method == "GET":+ try:+ logger.info("Fetching tools from the tool registry...")+ return Response(+ data=ToolProcessor.get_tool_list(request.user),+ status=status.HTTP_200_OK,+ )+ except Exception as exc:+ logger.error(f"Failed to fetch tools: {exc}")+ raise FetchToolListFailed+++class ToolInstanceViewSet(viewsets.ModelViewSet):+ versioning_class = URLPathVersioning+ queryset = ToolInstance.objects.all()+ serializer_class = ToolInstanceSerializer++ def get_queryset(self) -> QuerySet:+ filter_args = FilterHelper.build_filter_args(+ self.request,+ RequestKey.PROJECT,+ RequestKey.CREATED_BY,+ RequestKey.WORKFLOW,+ )+ if filter_args:+ queryset = ToolInstance.objects.filter(+ created_by=self.request.user, **filter_args+ )+ else:+ queryset = ToolInstance.objects.filter(created_by=self.request.user)+ return queryset++ def get_serializer_class(self) -> serializers.Serializer:+ if self.action == "reorder":+ return TIReorderSerializer+ else:+ return ToolInstanceSerializer++ def create(self, request: Any) -> Response:+ """Create tool instance.++ Creates a tool instance, useful to add them directly to a+ workflow. Its an alternative to creating tool instances through+ the LLM response.+ """++ serializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ try:+ self.perform_create(serializer)+ except IntegrityError:+ raise DuplicateData(+ f"{ToolInstanceErrors.TOOL_EXISTS}, "+ f"{ToolInstanceErrors.DUPLICATE_API}"+ )+ instance: ToolInstance = serializer.instance+ ToolInstanceHelper.update_metadata_with_default_values(+ instance, user=request.user+ )+ headers = self.get_success_headers(serializer.data)+ return Response(+ serializer.data, status=status.HTTP_201_CREATED, headers=headers+ )++ def perform_destroy(self, instance: ToolInstance) -> None:+ """Deletes a tool instance and decrements successor instance's steps.++ Args:+ instance (ToolInstance): Instance being deleted.+ """+ lookup = {"step__gt": instance.step}+ next_tool_instances: list[ToolInstance] = (+ ToolInstanceHelper.get_tool_instances_by_workflow(+ instance.workflow.id, TIKey.STEP, lookup=lookup+ )+ )+ super().perform_destroy(instance)++ for instance in next_tool_instances:+ instance.step = instance.step - 1+ instance.save()++ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Allows partial updates on a tool instance."""+ instance: ToolInstance = self.get_object()+ serializer = self.get_serializer(instance, data=request.data, partial=True)+ serializer.is_valid(raise_exception=True)+ if serializer.validated_data.get(TIKey.METADATA):+ metadata: dict[str, Any] = serializer.validated_data.get(TIKey.METADATA)++ # TODO: Move update logic into serializer+ organization_id = UserSessionUtils.get_organization_id(request)+ ToolInstanceHelper.update_instance_metadata(+ organization_id,+ instance,+ metadata,+ )+ return Response(serializer.data)+ return super().partial_update(request, *args, **kwargs)++ def reorder(self, request: Any, **kwargs: Any) -> Response:+ """Reorder tool instances.++ Reorders the tool instances based on a list of UUIDs.+ """+ serializer: TIReorderSerializer = self.get_serializer(data=request.data)+ serializer.is_valid(raise_exception=True)+ wf_id = serializer.validated_data[WorkflowKey.WF_ID]+ instances_to_reorder: list[uuid.UUID] = serializer.validated_data[+ WorkflowKey.WF_TOOL_INSTANCES+ ]++ ToolInstanceHelper.reorder_tool_instances(instances_to_reorder)+ tool_instances = ToolInstance.objects.get_instances_for_workflow(workflow=wf_id)+ ti_serializer = ToolInstanceSerializer(instance=tool_instances, many=True)+ return Response(ti_serializer.data, status=status.HTTP_200_OK)diff --git a/backend/usage_v2/__init__.py b/backend/usage_v2/__init__.pynew file mode 100644index 000000000..e69de29bbdiff --git a/backend/usage_v2/admin.py b/backend/usage_v2/admin.pynew file mode 100644index 000000000..c7469a4fb--- /dev/null+++ b/backend/usage_v2/admin.py@@ -0,0 +1,5 @@+from django.contrib import admin++from .models import Usage++admin.site.register(Usage)diff --git a/backend/usage_v2/apps.py b/backend/usage_v2/apps.pynew file mode 100644index 000000000..d2845981e--- /dev/null+++ b/backend/usage_v2/apps.py@@ -0,0 +1,5 @@+from django.apps import AppConfig+++class UsageConfig(AppConfig):+ name = "usage_v2"diff --git a/backend/usage_v2/constants.py b/backend/usage_v2/constants.pynew file mode 100644index 000000000..8da54da05--- /dev/null+++ b/backend/usage_v2/constants.py@@ -0,0 +1,7 @@+class UsageKeys:+ RUN_ID = "run_id"+ EMBEDDING_TOKENS = "embedding_tokens"+ PROMPT_TOKENS = "prompt_tokens"+ COMPLETION_TOKENS = "completion_tokens"+ TOTAL_TOKENS = "total_tokens"+ COST_IN_DOLLARS = "cost_in_dollars"diff --git a/backend/usage_v2/helper.py b/backend/usage_v2/helper.pynew file mode 100644index 000000000..0bfab7556--- /dev/null+++ b/backend/usage_v2/helper.py@@ -0,0 +1,64 @@+import logging++from django.db.models import Sum+from rest_framework.exceptions import APIException++from .constants import UsageKeys+from .models import Usage++logger = logging.getLogger(__name__)+++class UsageHelper:+ @staticmethod+ def get_aggregated_token_count(run_id: str) -> dict:+ """Retrieve aggregated token counts for the given run_id.++ Args:+ run_id (str): The identifier for the token usage.++ Returns:+ dict: A dictionary containing aggregated token counts+ for different token types.+ Keys:+ - 'embedding_tokens': Total embedding tokens.+ - 'prompt_tokens': Total prompt tokens.+ - 'completion_tokens': Total completion tokens.+ - 'total_tokens': Total tokens.++ Raises:+ APIException: For unexpected errors during database operations.+ """+ try:+ # Aggregate the token counts for the given run_id+ usage_summary = Usage.objects.filter(run_id=run_id).aggregate(+ embedding_tokens=Sum(UsageKeys.EMBEDDING_TOKENS),+ prompt_tokens=Sum(UsageKeys.PROMPT_TOKENS),+ completion_tokens=Sum(UsageKeys.COMPLETION_TOKENS),+ total_tokens=Sum(UsageKeys.TOTAL_TOKENS),+ cost_in_dollars=Sum(UsageKeys.COST_IN_DOLLARS),+ )++ logger.info(f"Token counts aggregated successfully for run_id: {run_id}")++ # Prepare the result dictionary with None as the default value+ result = {+ UsageKeys.EMBEDDING_TOKENS: usage_summary.get(+ UsageKeys.EMBEDDING_TOKENS+ ),+ UsageKeys.PROMPT_TOKENS: usage_summary.get(UsageKeys.PROMPT_TOKENS),+ UsageKeys.COMPLETION_TOKENS: usage_summary.get(+ UsageKeys.COMPLETION_TOKENS+ ),+ UsageKeys.TOTAL_TOKENS: usage_summary.get(UsageKeys.TOTAL_TOKENS),+ UsageKeys.COST_IN_DOLLARS: usage_summary.get(UsageKeys.COST_IN_DOLLARS),+ }+ return result+ except Usage.DoesNotExist:+ # Handle the case where no usage data is found for the given run_id+ logger.warning(f"Usage data not found for the specified run_id: {run_id}")+ return {}+ except Exception as e:+ # Handle any other exceptions that might occur during the execution+ logger.error(f"An unexpected error occurred for run_id {run_id}: {str(e)}")+ raise APIException("An unexpected error occurred")diff --git a/backend/usage_v2/models.py b/backend/usage_v2/models.pynew file mode 100644index 000000000..8d4a35069--- /dev/null+++ b/backend/usage_v2/models.py@@ -0,0 +1,82 @@+import uuid++from django.db import models+from utils.models.base_model import BaseModel+from utils.models.organization_mixin import (+ DefaultOrganizationManagerMixin,+ DefaultOrganizationMixin,+)+++class UsageType(models.TextChoices):+ LLM = "llm", "LLM Usage"+ EMBEDDING = "embedding", "Embedding Usage"+++class LLMUsageReason(models.TextChoices):+ EXTRACTION = "extraction", "Extraction"+ CHALLENGE = "challenge", "Challenge"+ SUMMARIZE = "summarize", "Summarize"+++class UsageModelManager(DefaultOrganizationManagerMixin, models.Manager):+ pass+++class Usage(DefaultOrganizationMixin, BaseModel):+ id = models.UUIDField(+ primary_key=True,+ default=uuid.uuid4,+ editable=False,+ db_comment="Primary key for the usage entry, automatically generated UUID",+ )+ workflow_id = models.CharField(+ max_length=255, null=True, blank=True, db_comment="Identifier for the workflow"+ )+ execution_id = models.CharField(+ max_length=255,+ null=True,+ blank=True,+ db_comment="Identifier for the execution instance",+ )+ adapter_instance_id = models.CharField(+ max_length=255, db_comment="Identifier for the adapter instance"+ )+ run_id = models.CharField(+ max_length=255, null=True, blank=True, db_comment="Identifier for the run"+ )+ usage_type = models.CharField(+ max_length=255,+ choices=UsageType.choices,+ db_comment="Type of usage, either 'llm' or 'embedding'",+ )+ llm_usage_reason = models.CharField(+ max_length=255,+ choices=LLMUsageReason.choices,+ null=True,+ blank=True,+ db_comment="Reason for LLM usage. Empty if usage_type is 'embedding'. ",+ )+ model_name = models.CharField(max_length=255, db_comment="Name of the model used")+ embedding_tokens = models.IntegerField(+ db_comment="Number of tokens used for embedding"+ )+ prompt_tokens = models.IntegerField(+ db_comment="Number of tokens used for the prompt"+ )+ completion_tokens = models.IntegerField(+ db_comment="Number of tokens used for the completion"+ )+ total_tokens = models.IntegerField(db_comment="Total number of tokens used")+ cost_in_dollars = models.FloatField(db_comment="Total number of tokens used")+ # Manager+ objects = UsageModelManager()++ def __str__(self):+ return str(self.id)++ class Meta:+ db_table = "token_usage_v2"+ indexes = [+ models.Index(fields=["run_id"]),+ ]diff --git a/backend/usage_v2/serializers.py b/backend/usage_v2/serializers.pynew file mode 100644index 000000000..eb1f2c326--- /dev/null+++ b/backend/usage_v2/serializers.py@@ -0,0 +1,5 @@+from rest_framework import serializers+++class GetUsageSerializer(serializers.Serializer):+ run_id = serializers.CharField(required=True)diff --git a/backend/usage_v2/urls.py b/backend/usage_v2/urls.pynew file mode 100644index 000000000..a0fa0bfa8--- /dev/null+++ b/backend/usage_v2/urls.py@@ -0,0 +1,18 @@+from django.urls import path+from rest_framework.urlpatterns import format_suffix_patterns++from .views import UsageView++get_token_usage = UsageView.as_view({"get": "get_token_usage"})++# TODO: Refactor URL to avoid using action-specific verbs like get.++urlpatterns = format_suffix_patterns(+ [+ path(+ "get_token_usage/",+ get_token_usage,+ name="get-token-usage",+ ),+ ]+)diff --git a/backend/usage_v2/views.py b/backend/usage_v2/views.pynew file mode 100644index 000000000..1fcebfaa0--- /dev/null+++ b/backend/usage_v2/views.py@@ -0,0 +1,63 @@+import logging++from django.http import HttpRequest+from rest_framework import status, viewsets+from rest_framework.decorators import action+from rest_framework.exceptions import APIException, ValidationError+from rest_framework.response import Response++from .constants import UsageKeys+from .helper import UsageHelper+from .serializers import GetUsageSerializer++logger = logging.getLogger(__name__)+++class UsageView(viewsets.ModelViewSet):+ """Viewset for managing Usage-related operations."""++ @action(detail=True, methods=["get"])+ def get_token_usage(self, request: HttpRequest) -> Response:+ """Retrieves the aggregated token usage for a given run_id.++ This method validates the 'run_id' query parameter, aggregates the token+ usage statistics for the specified run_id, and returns the results.++ Args:+ request (HttpRequest): The HTTP request object containing the+ query parameters.++ Returns:+ Response: A Response object containing the aggregated token usage data+ with HTTP 200 OK status if successful, or an error message and+ appropriate HTTP status if an error occurs.++ Raises:+ ValidationError: If the 'run_id' query parameter is missing or invalid.+ APIException: If an unexpected error occurs during the execution.+ """++ try:+ # Validate the query parameters using the serializer+ # This ensures that 'run_id' is present and valid+ serializer = GetUsageSerializer(data=self.request.query_params)+ serializer.is_valid(raise_exception=True)+ run_id = serializer.validated_data.get(UsageKeys.RUN_ID)++ # Retrieve aggregated token count for the given run_id.+ result: dict = UsageHelper.get_aggregated_token_count(run_id=run_id)++ # Log the successful completion of the operation+ logger.info(f"Token usage retrieved successfully for run_id: {run_id}")++ # Return the result+ return Response(status=status.HTTP_200_OK, data=result)+ except ValidationError as e:+ # Handle validation errors specifically+ logger.error(f"Validation error: {e.detail}")+ raise ValidationError(detail=f"Validation error: {str(e)}")+ except Exception as e:+ # Handle any other exceptions that might occur during the execution+ error_msg = "An unexpected error occurred while fetching the token usage"+ logger.error(f"{error_msg}: {e}")+ raise APIException(detail=error_msg)