LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
FEAT: Persist Token Usage (#378)
Tahier Hussain979b1b0a52d2
diff --git a/backend/prompt_studio/prompt_studio_output_manager/serializers.py b/backend/prompt_studio/prompt_studio_output_manager/serializers.pyindex 57dadf073..0fd7c4060 100644--- a/backend/prompt_studio/prompt_studio_output_manager/serializers.py+++ b/backend/prompt_studio/prompt_studio_output_manager/serializers.py@@ -1,9 +1,28 @@+import logging++from usage.helper import UsageHelper+from backend.serializers import AuditSerializerfrom .models import PromptStudioOutputManager+logger = logging.getLogger(__name__)+class PromptStudioOutputSerializer(AuditSerializer):class Meta:model = PromptStudioOutputManagerfields = "__all__"++ def to_representation(self, instance):+ data = super().to_representation(instance)+ try:+ token_usage = UsageHelper.get_aggregated_token_count(instance.run_id)+ except Exception as e:+ logger.error(+ "Error occured while fetching token usage for run_id"+ f"{instance.run_id}: {e}"+ )+ token_usage = {}+ data["token_usage"] = token_usage+ return datadiff --git a/backend/usage/constants.py b/backend/usage/constants.pyindex 15d245cff..d28074e1e 100644--- a/backend/usage/constants.py+++ b/backend/usage/constants.py@@ -1,2 +1,6 @@class UsageKeys:RUN_ID = "run_id"+ EMBEDDING_TOKENS = "embedding_tokens"+ PROMPT_TOKENS = "prompt_tokens"+ COMPLETION_TOKENS = "completion_tokens"+ TOTAL_TOKENS = "total_tokens"diff --git a/backend/usage/helper.py b/backend/usage/helper.pynew file mode 100644index 000000000..b91fae556--- /dev/null+++ b/backend/usage/helper.py@@ -0,0 +1,62 @@+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),+ )++ 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),+ }+ 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/views.py b/backend/usage/views.pyindex 8655af843..1fcebfaa0 100644--- a/backend/usage/views.py+++ b/backend/usage/views.py@@ -1,6 +1,5 @@import logging-from django.db.models import Sumfrom django.http import HttpRequestfrom rest_framework import status, viewsetsfrom rest_framework.decorators import action@@ -8,7 +7,7 @@ from rest_framework.exceptions import APIException, ValidationErrorfrom rest_framework.response import Responsefrom .constants import UsageKeys-from .models import Usage+from .helper import UsageHelperfrom .serializers import GetUsageSerializerlogger = logging.getLogger(__name__)@@ -45,22 +44,8 @@ class UsageView(viewsets.ModelViewSet):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"),- }+ # 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 operationlogger.info(f"Token usage retrieved successfully for run_id: {run_id}")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.jsxindex ce8d6e5e1..cc4d6d6f8 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@@ -17,6 +17,7 @@ import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";import { useAlertStore } from "../../../store/alert-store";import { useExceptionHandler } from "../../../hooks/useExceptionHandler";import { TokenUsage } from "../token-usage/TokenUsage";+import { useTokenUsageStore } from "../../../store/token-usage-store";const columns = [{@@ -53,7 +54,6 @@ function OutputForDocModal({promptKey,profileManagerId,docOutputs,- tokenUsage,}) {const [promptOutputs, setPromptOutputs] = useState([]);const [rows, setRows] = useState([]);@@ -72,6 +72,7 @@ function OutputForDocModal({const navigate = useNavigate();const { setAlertDetails } = useAlertStore();const { handleException } = useExceptionHandler();+ const { tokenUsage } = useTokenUsageStore();useEffect(() => {if (!open) {@@ -208,7 +209,7 @@ function OutputForDocModal({key: item,document: item?.document_name,token_count: (- <TokenUsage tokenUsage={tokenUsage} docId={item?.document_id} />+ <TokenUsage tokenUsageId={promptId + "__" + item?.document_id} />),value: (<>@@ -287,7 +288,6 @@ 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.jsxindex e8e89373a..97b8a44ac 100644--- a/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx+++ b/frontend/src/components/custom-tools/prompt-card/PromptCard.jsx@@ -46,6 +46,7 @@ import "./PromptCard.css";import { TokenUsage } from "../token-usage/TokenUsage";import usePostHogEvents from "../../../hooks/usePostHogEvents";import useTokenUsage from "../../../hooks/useTokenUsage";+import { useTokenUsageStore } from "../../../store/token-usage-store";const EvalBtn = null;const EvalMetrics = null;@@ -80,7 +81,6 @@ function PromptCard({const [openOutputForDoc, setOpenOutputForDoc] = useState(false);const [progressMsg, setProgressMsg] = useState({});const [docOutputs, setDocOutputs] = useState({});- const [tokenUsage, setTokenUsage] = useState({});const divRef = useRef(null);const {getDropdownItems,@@ -102,6 +102,7 @@ function PromptCard({const axiosPrivate = useAxiosPrivate();const handleException = useExceptionHandler();const { setPostHogCustomEvent } = usePostHogEvents();+ const { tokenUsage, setTokenUsage } = useTokenUsageStore();const { getTokenUsage } = useTokenUsage();useEffect(() => {@@ -223,11 +224,6 @@ 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;@@ -309,7 +305,6 @@ function PromptCard({setCoverage(0);setCoverageTotal(0);setDocOutputs({});- setTokenUsage({});resetInfoMsgs();const docId = selectedDoc?.document_id;@@ -418,22 +413,19 @@ function PromptCard({};const handleRunApiRequest = async (docId) => {+ const promptId = promptDetails?.prompt_id;const runId = generateUUID();// Update the token usage state with default token usage for a specific document ID- setTokenUsage((prev) => ({- ...prev,- [docId]: defaultTokenUsage,- }));+ const tokenUsageId = promptId + "__" + docId;+ setTokenUsage(tokenUsageId, defaultTokenUsage);// Set up an interval to fetch token usage data at regular intervalsconst intervalId = setInterval(- () => getTokenUsage(runId, docId, setTokenUsage),+ () => getTokenUsage(runId, tokenUsageId),5000 // Fetch token usage data every 5000 milliseconds (5 seconds));- const promptId = promptDetails?.prompt_id;-const body = {document_id: docId,id: promptId,@@ -457,7 +449,7 @@ function PromptCard({}).finally(() => {clearInterval(intervalId);- getTokenUsage(runId, docId, setTokenUsage);+ getTokenUsage(runId, tokenUsageId);});};@@ -539,7 +531,27 @@ function PromptCard({};return axiosPrivate(requestOptions)- .then((res) => res)+ .then((res) => {+ const data = res?.data || [];++ if (singlePassExtractMode) {+ const tokenUsageId = `single_pass__${selectedDoc?.document_id}`;+ const usage = data.find((item) => item?.run_id !== undefined);++ if (!tokenUsage[tokenUsageId] && usage) {+ setTokenUsage(tokenUsageId, usage?.token_usage);+ }+ } else {+ data.forEach((item) => {+ const tokenUsageId = `${item?.prompt_id}__${item?.document_manager}`;++ if (tokenUsage[tokenUsageId] === undefined) {+ setTokenUsage(tokenUsageId, item?.token_usage);+ }+ });+ }+ return res;+ }).catch((err) => {throw err;});@@ -740,10 +752,13 @@ function PromptCard({</Button></Space><Space>- <TokenUsage- tokenUsage={tokenUsage}- docId={selectedDoc?.document_id}- />+ {!singlePassExtractMode && (+ <TokenUsage+ tokenUsageId={+ promptDetails?.prompt_id + "__" + selectedDoc?.document_id+ }+ />+ )}<SelectclassName="prompt-card-select-type"size="small"@@ -861,7 +876,6 @@ function PromptCard({promptKey={promptDetails?.prompt_key}profileManagerId={promptDetails?.profile_manager}docOutputs={docOutputs}- tokenUsage={tokenUsage}/></>);diff --git a/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx b/frontend/src/components/custom-tools/token-usage/TokenUsage.jsxindex 2f92c6763..7337df1a9 100644--- a/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx+++ b/frontend/src/components/custom-tools/token-usage/TokenUsage.jsx@@ -1,26 +1,27 @@import { Tag, Tooltip } from "antd";import PropTypes from "prop-types";import { useEffect, useState } from "react";+import { useTokenUsageStore } from "../../../store/token-usage-store";/*** 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.+ * @param {string} tokenUsageId - The token usage ID to fetch token usage for.* @return {JSX.Element} - The TokenUsage component.*/-function TokenUsage({ tokenUsage, docId }) {+function TokenUsage({ tokenUsageId }) {const [tokens, setTokens] = useState({});+ const { tokenUsage } = useTokenUsageStore();useEffect(() => {- // Check if the token usage for the given docId is available- if (tokenUsage[docId] === undefined) {+ // Check if the token usage for the given tokenUsageId is available+ if (tokenUsage[tokenUsageId] === undefined) {setTokens({}); // Reset tokens state if token usage is not availablereturn;}- setTokens(tokenUsage[docId]); // Update tokens state with the token usage data for the given docId- }, [tokenUsage, docId]);+ setTokens(tokenUsage[tokenUsageId]); // Update tokens state with the token usage data for the given tokenUsageId+ }, [tokenUsage, tokenUsageId]);// If no tokens data is available, render nothingif (!tokens || !Object.keys(tokens)?.length) {@@ -35,8 +36,7 @@ function TokenUsage({ tokenUsage, docId }) {}TokenUsage.propTypes = {- tokenUsage: PropTypes.object.isRequired,- docId: PropTypes.string.isRequired,+ tokenUsageId: PropTypes.string.isRequired,};export { TokenUsage };diff --git a/frontend/src/components/helpers/custom-tools/CustomToolsHelper.js b/frontend/src/components/helpers/custom-tools/CustomToolsHelper.jsindex b9c60781b..4f52b530f 100644--- a/frontend/src/components/helpers/custom-tools/CustomToolsHelper.js+++ b/frontend/src/components/helpers/custom-tools/CustomToolsHelper.js@@ -8,6 +8,7 @@ import { useCustomToolStore } from "../../../store/custom-tool-store";import { useSessionStore } from "../../../store/session-store";import { useSocketCustomToolStore } from "../../../store/socket-custom-tool";import { SpinnerLoader } from "../../widgets/spinner-loader/SpinnerLoader";+import { useTokenUsageStore } from "../../../store/token-usage-store";function CustomToolsHelper() {const [isLoading, setIsLoading] = useState(true);@@ -19,6 +20,7 @@ function CustomToolsHelper() {const navigate = useNavigate();const axiosPrivate = useAxiosPrivate();const handleException = useExceptionHandler();+ const { resetTokenUsage } = useTokenUsageStore();useEffect(() => {const updatedCusTool = {@@ -93,6 +95,7 @@ function CustomToolsHelper() {return () => {setDefaultCustomTool();emptyCusToolMessages();+ resetTokenUsage();};}, []);diff --git a/frontend/src/components/helpers/socket-messages/SocketMessages.js b/frontend/src/components/helpers/socket-messages/SocketMessages.jsindex 207120ef8..57925db30 100644--- a/frontend/src/components/helpers/socket-messages/SocketMessages.js+++ b/frontend/src/components/helpers/socket-messages/SocketMessages.js@@ -7,7 +7,6 @@ import { useSocketLogsStore } from "../../../store/socket-logs-store";import { useSocketMessagesStore } from "../../../store/socket-messages-store";import { useSocketCustomToolStore } from "../../../store/socket-custom-tool";import { useSessionStore } from "../../../store/session-store";-import { useUsageStore } from "../../../store/usage-store";function SocketMessages() {const [logId, setLogId] = useState("");@@ -24,7 +23,6 @@ function SocketMessages() {const socket = useContext(SocketContext);const { setAlertDetails } = useAlertStore();const handleException = useExceptionHandler();- const { setLLMTokenUsage } = useUsageStore();useEffect(() => {setLogId(sessionDetails?.logEventsId || "");@@ -46,11 +44,6 @@ function SocketMessages() {if (msg?.type === "LOG" && msg?.service === "prompt") {updateCusToolMessages(msg);}- if (msg?.type === "LOG" && msg?.service === "usage") {- const remainingTokens =- msg?.max_token_count_set - msg?.added_token_count;- setLLMTokenUsage(Math.max(remainingTokens, 0));- }} catch (err) {setAlertDetails(handleException(err, "Failed to process socket message"));}diff --git a/frontend/src/hooks/useTokenUsage.js b/frontend/src/hooks/useTokenUsage.jsindex c55333200..527c1fdd8 100644--- a/frontend/src/hooks/useTokenUsage.js+++ b/frontend/src/hooks/useTokenUsage.js@@ -1,5 +1,6 @@import { useAlertStore } from "../store/alert-store";import { useSessionStore } from "../store/session-store";+import { useTokenUsageStore } from "../store/token-usage-store";import { useAxiosPrivate } from "./useAxiosPrivate";import { useExceptionHandler } from "./useExceptionHandler";@@ -13,8 +14,9 @@ const useTokenUsage = () => {const { sessionDetails } = useSessionStore();const { setAlertDetails } = useAlertStore();const handleException = useExceptionHandler();+ const { setTokenUsage } = useTokenUsageStore();- const getTokenUsage = (runId, docId, setTokenUsage, defaultTokenUsage) => {+ const getTokenUsage = (runId, tokenUsageId) => {const requestOptions = {method: "GET",url: `/api/v1/unstract/${sessionDetails?.orgId}/usage/get_token_usage/?run_id=${runId}`,@@ -23,15 +25,11 @@ const useTokenUsage = () => {// Make the API request using the axios instanceaxiosPrivate(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,- }));+ const tokens = res?.data;+ // Update the token usage state with token usage data for a specific tokenUsageId+ setTokenUsage(tokenUsageId, tokens);}).catch((err) => {- // Handle any errors that occur during the requestsetAlertDetails(handleException(err, "Failed to get token usage"));});};diff --git a/frontend/src/store/token-usage-store.js b/frontend/src/store/token-usage-store.jsnew file mode 100644index 000000000..1b00c7047--- /dev/null+++ b/frontend/src/store/token-usage-store.js@@ -0,0 +1,22 @@+import { create } from "zustand";++const STORE_VARIABLES = {+ tokenUsage: {},+};++const useTokenUsageStore = create((setState) => ({+ ...STORE_VARIABLES,+ setTokenUsage: (tokenUsageId, data) => {+ setState((state) => ({+ tokenUsage: {+ ...state.tokenUsage,+ [tokenUsageId]: data,+ },+ }));+ },+ resetTokenUsage: () => {+ setState(STORE_VARIABLES);+ },+}));++export { useTokenUsageStore };diff --git a/frontend/src/store/usage-store.js b/frontend/src/store/usage-store.jsdeleted file mode 100644index 1b97b3d8d..000000000--- a/frontend/src/store/usage-store.js+++ /dev/null@@ -1,10 +0,0 @@-import { create } from "zustand";--const useUsageStore = create((setState) => ({- llmTokenUsage: null,- setLLMTokenUsage: (data) => {- setState({ llmTokenUsage: data });- },-}));--export { useUsageStore };