Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

FEAT: Display Token Usage in the UI (#357)

Tahier Hussain8ac0f039bea2
diff --git a/backend/backend/urls.py b/backend/backend/urls.py
index 888e14464..725a8f7b6 100644
--- a/backend/backend/urls.py
+++ b/backend/backend/urls.py
@@ -33,6 +33,7 @@ urlpatterns = [
path("workflow/", include("workflow_manager.urls")),
path("platform/", include("platform_settings.urls")),
path("api/", include("api.urls")),
+ path("usage/", include("usage.urls")),
path(
UrlPathConstants.PROMPT_STUDIO,
include("prompt_studio.prompt_profile_manager.urls"),
diff --git a/backend/usage/constants.py b/backend/usage/constants.py
new file mode 100644
index 000000000..15d245cff
--- /dev/null
+++ b/backend/usage/constants.py
@@ -0,0 +1,2 @@
+class UsageKeys:
+ RUN_ID = "run_id"
diff --git a/backend/usage/serializers.py b/backend/usage/serializers.py
new file mode 100644
index 000000000..eb1f2c326
--- /dev/null
+++ b/backend/usage/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/urls.py b/backend/usage/urls.py
new file mode 100644
index 000000000..9c4fb95c7
--- /dev/null
+++ b/backend/usage/urls.py
@@ -0,0 +1,16 @@
+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"})
+
+urlpatterns = format_suffix_patterns(
+ [
+ path(
+ "get_token_usage/",
+ get_token_usage,
+ name="get-token-usage",
+ ),
+ ]
+)
diff --git a/backend/usage/views.py b/backend/usage/views.py
index 60f00ef0e..8655af843 100644
--- a/backend/usage/views.py
+++ b/backend/usage/views.py
@@ -1 +1,78 @@
-# Create your views here.
+import logging
+
+from django.db.models import Sum
+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 .models import Usage
+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)
+
+ # Aggregate the token counts for the given run_id
+ # This uses Django's ORM to sum up the token counts
+ usage_summary = Usage.objects.filter(run_id=run_id).aggregate(
+ embedding_tokens=Sum("embedding_tokens"),
+ prompt_tokens=Sum("prompt_tokens"),
+ completion_tokens=Sum("completion_tokens"),
+ total_tokens=Sum("total_tokens"),
+ )
+
+ # Prepare the result dictionary with None as the default value
+ result = {
+ "embedding_tokens": usage_summary.get("embedding_tokens"),
+ "prompt_tokens": usage_summary.get("prompt_tokens"),
+ "completion_tokens": usage_summary.get("completion_tokens"),
+ "total_tokens": usage_summary.get("total_tokens"),
+ }
+
+ # 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)
diff --git a/frontend/package-lock.json b/frontend/package-lock.json
index 719b906c2..aee9ec808 100644
--- a/frontend/package-lock.json
+++ b/frontend/package-lock.json
@@ -47,6 +47,7 @@
"react-social-login-buttons": "^3.9.1",
"remark-gfm": "^3.0.1",
"socket.io-client": "^4.7.2",
+ "uuid": "^9.0.1",
"zustand": "^4.3.8"
},
"devDependencies": {
@@ -18149,6 +18150,14 @@
"websocket-driver": "^0.7.4"
}
},
+ "node_modules/sockjs/node_modules/uuid": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "bin": {
+ "uuid": "dist/bin/uuid"
+ }
+ },
"node_modules/source-list-map": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz",
@@ -19510,9 +19519,13 @@
}
},
"node_modules/uuid": {
- "version": "8.3.2",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
- "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
+ "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA==",
+ "funding": [
+ "https://github.com/sponsors/broofa",
+ "https://github.com/sponsors/ctavan"
+ ],
"bin": {
"uuid": "dist/bin/uuid"
}
@@ -33406,6 +33419,13 @@
"faye-websocket": "^0.11.3",
"uuid": "^8.3.2",
"websocket-driver": "^0.7.4"
+ },
+ "dependencies": {
+ "uuid": {
+ "version": "8.3.2",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
+ "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
+ }
}
},
"source-list-map": {
@@ -34413,9 +34433,9 @@
"integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA=="
},
"uuid": {
- "version": "8.3.2",
- "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
- "integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz",
+ "integrity": "sha512-b+1eJOlsR9K8HJpow9Ok3fiWOWSIcIzXodvv0rQjVoOVNpWMpxf1wZNpt4y9h10odCNrqnYp1OBzRktckBe3sA=="
},
"uvu": {
"version": "0.5.6",
diff --git a/frontend/package.json b/frontend/package.json
index 2d4825cef..a01f53738 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -42,6 +42,7 @@
"react-social-login-buttons": "^3.9.1",
"remark-gfm": "^3.0.1",
"socket.io-client": "^4.7.2",
+ "uuid": "^9.0.1",
"zustand": "^4.3.8"
},
"scripts": {
diff --git a/frontend/src/components/custom-tools/output-for-doc-modal/OutputForDocModal.jsx b/frontend/src/components/custom-tools/output-for-doc-modal/OutputForDocModal.jsx
index df86ac70a..ce8d6e5e1 100644
--- a/frontend/src/components/custom-tools/output-for-doc-modal/OutputForDocModal.jsx
+++ b/frontend/src/components/custom-tools/output-for-doc-modal/OutputForDocModal.jsx
@@ -16,6 +16,7 @@ import { displayPromptResult } from "../../../helpers/GetStaticData";
import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";
import { useAlertStore } from "../../../store/alert-store";
import { useExceptionHandler } from "../../../hooks/useExceptionHandler";
+import { TokenUsage } from "../token-usage/TokenUsage";
const columns = [
{
@@ -23,11 +24,17 @@ const columns = [
dataIndex: "document",
key: "document",
},
+ {
+ title: "Token Count",
+ dataIndex: "token_count",
+ key: "token_count",
+ width: 200,
+ },
{
title: "Value",
dataIndex: "value",
key: "value",
- width: 700,
+ width: 600,
},
];
@@ -46,6 +53,7 @@ function OutputForDocModal({
promptKey,
profileManagerId,
docOutputs,
+ tokenUsage,
}) {
const [promptOutputs, setPromptOutputs] = useState([]);
const [rows, setRows] = useState([]);
@@ -78,7 +86,7 @@ function OutputForDocModal({
useEffect(() => {
handleRowsGeneration(promptOutputs);
- }, [promptOutputs]);
+ }, [promptOutputs, tokenUsage]);
const moveSelectedDocToTop = () => {
// Create a copy of the list of documents
@@ -199,6 +207,9 @@ function OutputForDocModal({
const result = {
key: item,
document: item?.document_name,
+ token_count: (
+ <TokenUsage tokenUsage={tokenUsage} docId={item?.document_id} />
+ ),
value: (
<>
{output?.isLoading ? (
@@ -276,6 +287,7 @@ OutputForDocModal.propTypes = {
promptKey: PropTypes.string.isRequired,
profileManagerId: PropTypes.string,
docOutputs: PropTypes.object,
+ tokenUsage: PropTypes.object.isRequired,
};
export { OutputForDocModal };
diff --git a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
index b96590d2c..e8e89373a 100644
--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx
@@ -24,8 +24,11 @@ import {
} from "antd";
import PropTypes from "prop-types";
import { useEffect, useRef, useState } from "react";
+
import {
+ defaultTokenUsage,
displayPromptResult,
+ generateUUID,
promptStudioUpdateStatus,
} from "../../../helpers/GetStaticData";
import { useAxiosPrivate } from "../../../hooks/useAxiosPrivate";
@@ -40,8 +43,9 @@ import { EditableText } from "../editable-text/EditableText";
import { OutputForDocModal } from "../output-for-doc-modal/OutputForDocModal";
import "./PromptCard.css";
-import { TokenCount } from "../token-count/TokenCount";
+import { TokenUsage } from "../token-usage/TokenUsage";
import usePostHogEvents from "../../../hooks/usePostHogEvents";
+import useTokenUsage from "../../../hooks/useTokenUsage";
const EvalBtn = null;
const EvalMetrics = null;
@@ -76,7 +80,7 @@ function PromptCard({
const [openOutputForDoc, setOpenOutputForDoc] = useState(false);
const [progressMsg, setProgressMsg] = useState({});
const [docOutputs, setDocOutputs] = useState({});
- const [tokenCount, setTokenCount] = useState({});
+ const [tokenUsage, setTokenUsage] = useState({});
const divRef = useRef(null);
const {
getDropdownItems,
@@ -98,6 +102,7 @@ function PromptCard({
const axiosPrivate = useAxiosPrivate();
const handleException = useExceptionHandler();
const { setPostHogCustomEvent } = usePostHogEvents();
+ const { getTokenUsage } = useTokenUsage();
useEffect(() => {
// Find the latest message that matches the criteria
@@ -195,7 +200,6 @@ function PromptCard({
const resetInfoMsgs = () => {
setProgressMsg({}); // Reset Progress Message
- setTokenCount({}); // Reset Token Count
};
useEffect(() => {
@@ -219,6 +223,11 @@ function PromptCard({
setPage(index + 1);
}, [llmProfiles]);
+ useEffect(() => {
+ // Reset the token usage object when the single pass extraction mode is enabled or disabled.
+ setTokenUsage({});
+ }, [singlePassExtractMode]);
+
const handlePageLeft = () => {
if (page <= 1) {
return;
@@ -300,6 +309,7 @@ function PromptCard({
setCoverage(0);
setCoverageTotal(0);
setDocOutputs({});
+ setTokenUsage({});
resetInfoMsgs();
const docId = selectedDoc?.document_id;
@@ -332,9 +342,6 @@ function PromptCard({
}
handleDocOutputs(docId, false, value);
handleGetOutput();
-
- const usage = data[`${promptDetails?.prompt_key}__usage`] || {};
- setTokenCount(usage);
})
.catch((err) => {
setIsRunLoading(false);
@@ -411,11 +418,26 @@ function PromptCard({
};
const handleRunApiRequest = async (docId) => {
+ const runId = generateUUID();
+
+ // Update the token usage state with default token usage for a specific document ID
+ setTokenUsage((prev) => ({
+ ...prev,
+ [docId]: defaultTokenUsage,
+ }));
+
+ // Set up an interval to fetch token usage data at regular intervals
+ const intervalId = setInterval(
+ () => getTokenUsage(runId, docId, setTokenUsage),
+ 5000 // Fetch token usage data every 5000 milliseconds (5 seconds)
+ );
+
const promptId = promptDetails?.prompt_id;
const body = {
document_id: docId,
id: promptId,
+ run_id: runId,
};
const requestOptions = {
@@ -432,6 +454,10 @@ function PromptCard({
.then((res) => res)
.catch((err) => {
throw err;
+ })
+ .finally(() => {
+ clearInterval(intervalId);
+ getTokenUsage(runId, docId, setTokenUsage);
});
};
@@ -714,7 +740,10 @@ function PromptCard({
</Button>
</Space>
<Space>
- <TokenCount tokenCount={tokenCount} />
+ <TokenUsage
+ tokenUsage={tokenUsage}
+ docId={selectedDoc?.document_id}
+ />
<Select
className="prompt-card-select-type"
size="small"
@@ -832,6 +861,7 @@ function PromptCard({
promptKey={promptDetails?.prompt_key}
profileManagerId={promptDetails?.profile_manager}
docOutputs={docOutputs}
+ tokenUsage={tokenUsage}
/>
</>
);
diff --git a/frontend/src/components/custom-tools/token-count/TokenCount.jsx b/frontend/src/components/custom-tools/token-count/TokenCount.jsx
deleted file mode 100644
index 1fc434fdd..000000000
--- a/frontend/src/components/custom-tools/token-count/TokenCount.jsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Tag, Tooltip } from "antd";
-import PropTypes from "prop-types";
-
-function TokenCount({ tokenCount }) {
- if (!tokenCount || !Object.keys(tokenCount)?.length) {
- return <></>;
- }
-
- return (
- <Tooltip title="Prompt Token Count | Completion Token Count | Total Token Count">
- <Tag color="#2db7f5">{`${tokenCount?.prompt_token_count} | ${tokenCount?.completion_token_count} | ${tokenCount?.total_token_count}`}</Tag>
- </Tooltip>
- );
-}
-
-TokenCount.propTypes = {
- tokenCount: PropTypes.object,
-};
-
-export { TokenCount };
diff --git a/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx b/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx
new file mode 100644
index 000000000..2f92c6763
--- /dev/null
+++ b/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx
@@ -0,0 +1,42 @@
+import { Tag, Tooltip } from "antd";
+import PropTypes from "prop-types";
+import { useEffect, useState } from "react";
+
+/**
+ * TokenUsage component displays token usage details in a tag with a tooltip.
+ *
+ * @param {Object} tokenUsage - An object containing token usage details.
+ * @param {string} docId - The document ID to fetch token usage for.
+ * @return {JSX.Element} - The TokenUsage component.
+ */
+function TokenUsage({ tokenUsage, docId }) {
+ const [tokens, setTokens] = useState({});
+
+ useEffect(() => {
+ // Check if the token usage for the given docId is available
+ if (tokenUsage[docId] === undefined) {
+ setTokens({}); // Reset tokens state if token usage is not available
+ return;
+ }
+
+ setTokens(tokenUsage[docId]); // Update tokens state with the token usage data for the given docId
+ }, [tokenUsage, docId]);
+
+ // If no tokens data is available, render nothing
+ if (!tokens || !Object.keys(tokens)?.length) {
+ return <></>;
+ }
+
+ return (
+ <Tooltip title="Total Token Count">
+ <Tag color="#2db7f5">{`Tokens: ${tokens?.total_tokens}`}</Tag>
+ </Tooltip>
+ );
+}
+
+TokenUsage.propTypes = {
+ tokenUsage: PropTypes.object.isRequired,
+ docId: PropTypes.string.isRequired,
+};
+
+export { TokenUsage };
diff --git a/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx b/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
index 376c40061..3e4876bbf 100644
--- a/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
+++ b/frontend/src/components/custom-tools/tools-main/ToolsMain.jsx
@@ -166,6 +166,7 @@ function ToolsMain() {
</div>
<div className="display-flex-align-center">
<Space>
+ {singlePassExtractMode && RunSinglePassBtn && <RunSinglePassBtn />}
<Tooltip title="Output Analyzer">
<Button
icon={<BarChartOutlined />}
@@ -176,7 +177,6 @@ function ToolsMain() {
}
/>
</Tooltip>
- {singlePassExtractMode && RunSinglePassBtn && <RunSinglePassBtn />}
</Space>
</div>
</div>
diff --git a/frontend/src/helpers/GetStaticData.js b/frontend/src/helpers/GetStaticData.js
index 2ef717411..b9ac03252 100644
--- a/frontend/src/helpers/GetStaticData.js
+++ b/frontend/src/helpers/GetStaticData.js
@@ -1,5 +1,6 @@
import moment from "moment";
import momentTz from "moment-timezone";
+import { v4 as uuidv4 } from "uuid";
const THEME = {
DARK: "dark",
@@ -394,6 +395,20 @@ const isNonNegativeNumber = (value) => {
return typeof value === "number" && !isNaN(value) && value >= 0;
};
+// Default token usage object with all counts initialized to 0
+const defaultTokenUsage = {
+ embedding_tokens: 0,
+ prompt_tokens: 0,
+ completion_tokens: 0,
+ total_tokens: 0,
+};
+
+// Generate a UUID
+const generateUUID = () => {
+ const uuid = uuidv4();
+ return uuid;
+};
+
export {
CONNECTOR_TYPE_MAP,
O_AUTH_PROVIDERS,
@@ -429,4 +444,6 @@ export {
getMenuItem,
docIndexStatus,
isNonNegativeNumber,
+ defaultTokenUsage,
+ generateUUID,
};
diff --git a/frontend/src/hooks/useTokenUsage.js b/frontend/src/hooks/useTokenUsage.js
new file mode 100644
index 000000000..c55333200
--- /dev/null
+++ b/frontend/src/hooks/useTokenUsage.js
@@ -0,0 +1,42 @@
+import { useAlertStore } from "../store/alert-store";
+import { useSessionStore } from "../store/session-store";
+import { useAxiosPrivate } from "./useAxiosPrivate";
+import { useExceptionHandler } from "./useExceptionHandler";
+
+/**
+ * Custom hook to fetch token usage data.
+ *
+ * @return {Object} - An object containing the getTokenUsage function.
+ */
+const useTokenUsage = () => {
+ const axiosPrivate = useAxiosPrivate();
+ const { sessionDetails } = useSessionStore();
+ const { setAlertDetails } = useAlertStore();
+ const handleException = useExceptionHandler();
+
+ const getTokenUsage = (runId, docId, setTokenUsage, defaultTokenUsage) => {
+ const requestOptions = {
+ method: "GET",
+ url: `/api/v1/unstract/${sessionDetails?.orgId}/usage/get_token_usage/?run_id=${runId}`,
+ };
+
+ // Make the API request using the axios instance
+ axiosPrivate(requestOptions)
+ .then((res) => {
+ const tokens = res?.data || defaultTokenUsage; // Use default token usage if response data is null or undefined
+ // Update the token usage state with token usage data for a specific document ID
+ setTokenUsage((prev) => ({
+ ...prev,
+ [docId]: tokens,
+ }));
+ })
+ .catch((err) => {
+ // Handle any errors that occur during the request
+ setAlertDetails(handleException(err, "Failed to get token usage"));
+ });
+ };
+
+ return { getTokenUsage };
+};
+
+export default useTokenUsage;