Skip to content

Same agent Smaller bill. The tools and infrastructure to get more work from your AI. Fewer tokens. Less compute. Lower cost.

feat: Added filters and sort for the request page. (#251)

Aman Agarwal50d43c118552
diff --git a/src/client/package-lock.json b/src/client/package-lock.json
index cc88497c..aced22f8 100644
--- a/src/client/package-lock.json
+++ b/src/client/package-lock.json
@@ -18,6 +18,8 @@
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0",
+ "@radix-ui/react-separator": "^1.0.3",
+ "@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
@@ -25,6 +27,7 @@
"bcrypt-ts": "^5.0.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
+ "cmdk": "^1.0.0",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^3.6.0",
"generic-pool": "^3.9.0",
@@ -1173,6 +1176,62 @@
}
}
},
+ "node_modules/@radix-ui/react-separator": {
+ "version": "1.0.3",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-separator/-/react-separator-1.0.3.tgz",
+ "integrity": "sha512-itYmTy/kokS21aiV5+Z56MZB54KrhPgn6eHDKkFeOLR34HMN2s8PaN47qZZAGnvupcjxHaFZnW4pQEh0BvvVuw==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/react-primitive": "1.0.3"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@radix-ui/react-slider": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@radix-ui/react-slider/-/react-slider-1.1.2.tgz",
+ "integrity": "sha512-NKs15MJylfzVsCagVSWKhGGLNR1W9qWs+HtgbmjjVUB3B9+lb3PYoXxVju3kOrpf0VKyVCtZp+iTwVoqpa1Chw==",
+ "dependencies": {
+ "@babel/runtime": "^7.13.10",
+ "@radix-ui/number": "1.0.1",
+ "@radix-ui/primitive": "1.0.1",
+ "@radix-ui/react-collection": "1.0.3",
+ "@radix-ui/react-compose-refs": "1.0.1",
+ "@radix-ui/react-context": "1.0.1",
+ "@radix-ui/react-direction": "1.0.1",
+ "@radix-ui/react-primitive": "1.0.3",
+ "@radix-ui/react-use-controllable-state": "1.0.1",
+ "@radix-ui/react-use-layout-effect": "1.0.1",
+ "@radix-ui/react-use-previous": "1.0.1",
+ "@radix-ui/react-use-size": "1.0.1"
+ },
+ "peerDependencies": {
+ "@types/react": "*",
+ "@types/react-dom": "*",
+ "react": "^16.8 || ^17.0 || ^18.0",
+ "react-dom": "^16.8 || ^17.0 || ^18.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/react": {
+ "optional": true
+ },
+ "@types/react-dom": {
+ "optional": true
+ }
+ }
+ },
"node_modules/@radix-ui/react-slot": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@radix-ui/react-slot/-/react-slot-1.0.2.tgz",
@@ -2310,6 +2369,19 @@
"node": ">=6"
}
},
+ "node_modules/cmdk": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/cmdk/-/cmdk-1.0.0.tgz",
+ "integrity": "sha512-gDzVf0a09TvoJ5jnuPvygTB77+XdOSwEmJ88L6XPFPlv7T3RxbP9jgenfylrAMD0+Le1aO0nVjQUzl2g+vjz5Q==",
+ "dependencies": {
+ "@radix-ui/react-dialog": "1.0.5",
+ "@radix-ui/react-primitive": "1.0.3"
+ },
+ "peerDependencies": {
+ "react": "^18.0.0",
+ "react-dom": "^18.0.0"
+ }
+ },
"node_modules/color-convert": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
diff --git a/src/client/package.json b/src/client/package.json
index 0189d04c..6bf4711e 100644
--- a/src/client/package.json
+++ b/src/client/package.json
@@ -20,6 +20,8 @@
"@radix-ui/react-popover": "^1.0.7",
"@radix-ui/react-scroll-area": "^1.0.5",
"@radix-ui/react-select": "^2.0.0",
+ "@radix-ui/react-separator": "^1.0.3",
+ "@radix-ui/react-slider": "^1.1.2",
"@radix-ui/react-slot": "^1.0.2",
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.4",
@@ -27,6 +29,7 @@
"bcrypt-ts": "^5.0.1",
"class-variance-authority": "^0.7.0",
"clsx": "^2.1.0",
+ "cmdk": "^1.0.0",
"copy-to-clipboard": "^3.3.3",
"date-fns": "^3.6.0",
"generic-pool": "^3.9.0",
diff --git a/src/client/src/app/(playground)/dashboard/page.tsx b/src/client/src/app/(playground)/dashboard/page.tsx
index 7382cb9d..b2709b88 100644
--- a/src/client/src/app/(playground)/dashboard/page.tsx
+++ b/src/client/src/app/(playground)/dashboard/page.tsx
@@ -8,7 +8,7 @@ import TokenCharts from "./token-charts";
export default function PlaygroundPage() {
return (
<>
- <Filter />
+ <Filter className="mb-4" />
<div className="flex flex-col grow w-full h-full rounded overflow-y-auto gap-4">
<NumberStats />
<div className="flex flex-col gap-4">
diff --git a/src/client/src/app/(playground)/dashboard/requests-per-time.tsx b/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
index fe35d316..a7d9caef 100644
--- a/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
+++ b/src/client/src/app/(playground)/dashboard/requests-per-time.tsx
@@ -16,6 +16,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { COLORS } from "../../../../colors";
import IntermediateState from "@/components/(playground)/intermediate-state";
import { toast } from "sonner";
+import { getFilterParamsForDashboard } from "@/helpers/filter";
export default function RequestsPerTime() {
const filter = useRootStore(getFilterDetails);
@@ -23,9 +24,7 @@ export default function RequestsPerTime() {
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify(getFilterParamsForDashboard(filter)),
requestType: "POST",
url: "/api/metrics/request/time",
responseDataKey: "data",
diff --git a/src/client/src/app/(playground)/dashboard/token-charts.tsx b/src/client/src/app/(playground)/dashboard/token-charts.tsx
index 186542d2..1bc15c40 100644
--- a/src/client/src/app/(playground)/dashboard/token-charts.tsx
+++ b/src/client/src/app/(playground)/dashboard/token-charts.tsx
@@ -23,6 +23,7 @@ import { Badge } from "@/components/ui/badge";
import { ScrollArea, ScrollBar } from "@/components/ui/scroll-area";
import { COLORS } from "../../../../colors";
import IntermediateState from "@/components/(playground)/intermediate-state";
+import { getFilterParamsForDashboard } from "@/helpers/filter";
function TopModels() {
const filter = useRootStore(getFilterDetails);
@@ -31,9 +32,7 @@ function TopModels() {
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify(getFilterParamsForDashboard(filter)),
requestType: "POST",
url: "/api/metrics/model/top",
responseDataKey: "data",
@@ -123,9 +122,7 @@ function ModelsPerTime() {
};
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify(getFilterParamsForDashboard(filter)),
requestType: "POST",
url: "/api/metrics/model/time",
responseDataKey: "data",
@@ -221,9 +218,7 @@ function TokensPerTime() {
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify(getFilterParamsForDashboard(filter)),
requestType: "POST",
url: "/api/metrics/token/time",
responseDataKey: "data",
diff --git a/src/client/src/app/(playground)/requests/page.tsx b/src/client/src/app/(playground)/requests/page.tsx
index 72506ec8..efe4535b 100644
--- a/src/client/src/app/(playground)/requests/page.tsx
+++ b/src/client/src/app/(playground)/requests/page.tsx
@@ -1,7 +1,7 @@
"use client";
import RequestTable from "./request-table";
import { useCallback, useEffect } from "react";
-import RequestFilter, { FilterConfigProps } from "./request-filter";
+import RequestFilter from "./request-filter";
import { RequestProvider } from "./request-context";
import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
import RequestDetails from "./request-details";
@@ -9,6 +9,7 @@ import { toast } from "sonner";
import { getFilterDetails } from "@/selectors/filter";
import { useRootStore } from "@/store";
import { getPingStatus } from "@/selectors/database-config";
+import { Separator } from "@/components/ui/separator";
export default function RequestPage() {
const filter = useRootStore(getFilterDetails);
@@ -16,18 +17,7 @@ export default function RequestPage() {
const { data, fireRequest, isFetched, isLoading } = useFetchWrapper();
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- // TODO: send config true based on if the config has not already been fetched or when the timeLimit is changed
- config: {
- providers: true,
- maxCost: true,
- models: true,
- totalRows: true,
- },
- limit: filter.limit,
- offset: filter.offset,
- }),
+ body: JSON.stringify(filter),
requestType: "POST",
url: "/api/metrics/request",
failureCb: (err?: string) => {
@@ -49,9 +39,7 @@ export default function RequestPage() {
return (
<RequestProvider>
- <RequestFilter
- config={(data as any)?.config as FilterConfigProps | undefined}
- />
+ <RequestFilter total={(data as any)?.total} />
<RequestTable
data={(data as any)?.records || []}
isFetched={isFetched || pingStatus !== "pending"}
diff --git a/src/client/src/app/(playground)/requests/request-filter.tsx b/src/client/src/app/(playground)/requests/request-filter.tsx
index b23d3c69..b4b9412e 100644
--- a/src/client/src/app/(playground)/requests/request-filter.tsx
+++ b/src/client/src/app/(playground)/requests/request-filter.tsx
@@ -1,22 +1,190 @@
import RequestPagination from "@/components/(playground)/request-pagination";
import { ceil } from "lodash";
import Filter from "../../../components/(playground)/filter";
-import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";
+import {
+ getFilterConfig,
+ getFilterDetails,
+ getUpdateFilter,
+ getUpdateConfig,
+} from "@/selectors/filter";
import { useRootStore } from "@/store";
+import Sorting from "@/components/(playground)/filter/sorting";
+import ComboDropdown from "@/components/(playground)/filter/combo-dropdown";
+import SlideWithValue from "@/components/(playground)/filter/slider-with-value";
+import { Button } from "@/components/ui/button";
+import { SlidersHorizontal } from "lucide-react";
-export type FilterConfigProps = {
- endpoints: string[];
- maxUsageCost: number;
- models: string[];
- totalRows: number;
-};
+import { getPingStatus } from "@/selectors/database-config";
+import useFetchWrapper from "@/utils/hooks/useFetchWrapper";
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { FilterConfig, FilterType } from "@/store/filter";
-export default function RequestFilter({
- config,
+const DynamicFilters = ({
+ isVisibleFilters,
+ filter,
+ areFiltersApplied,
}: {
- config: FilterConfigProps | undefined;
-}) {
+ isVisibleFilters: boolean;
+ filter: FilterType;
+ areFiltersApplied: boolean;
+}) => {
+ const filterConfig = useRootStore(getFilterConfig);
+ const pingStatus = useRootStore(getPingStatus);
+ const filterDetails = useRootStore(getFilterDetails);
+ const updateConfig = useRootStore(getUpdateConfig);
+ const { fireRequest } = useFetchWrapper();
+ const updateFilter = useRootStore(getUpdateFilter);
+ const [selectedFilterValues, setSelectedFilterValues] = useState<
+ Partial<FilterConfig>
+ >(filterDetails.selectedConfig || {});
+
+ const clearFilter = (type: keyof FilterConfig) => {
+ setSelectedFilterValues((e) => ({ ...e, [type]: undefined }));
+ };
+
+ const updateSelectedValues = (
+ type: keyof FilterConfig,
+ value: any,
+ operationType?: "add" | "delete"
+ ) => {
+ switch (type) {
+ case "models":
+ case "providers":
+ case "traceTypes":
+ if (operationType === "add") {
+ setSelectedFilterValues((s) => {
+ const typeArray = s[type] || [];
+ typeArray.push(value);
+ return { ...s, [type]: typeArray };
+ });
+ } else if (operationType === "delete") {
+ setSelectedFilterValues((s) => {
+ const typeArray = s[type] || [];
+ return { ...s, [type]: typeArray.filter((o) => o !== value) };
+ });
+ }
+ break;
+ case "maxCost":
+ setSelectedFilterValues((s) => {
+ return { ...s, [type]: value };
+ });
+ }
+ };
+
+ const fetchConfig = useCallback(async () => {
+ fireRequest({
+ body: JSON.stringify({
+ timeLimit: filter.timeLimit,
+ }),
+ requestType: "POST",
+ url: "/api/metrics/request/config",
+ successCb: (resp) => {
+ updateConfig(resp.data?.[0]);
+ },
+ failureCb: (err?: string) => {
+ toast.error(err || `Cannot fetch config!`, {
+ id: "request-config",
+ });
+ },
+ });
+ }, [filter]);
+
+ useEffect(() => {
+ if (
+ filter.timeLimit.start &&
+ filter.timeLimit.end &&
+ pingStatus === "success" &&
+ !filterConfig
+ ) {
+ fetchConfig();
+ }
+ }, [filter, pingStatus, filterConfig, fetchConfig]);
+
+ const updateFilterStore = () => {
+ updateFilter("selectedConfig", selectedFilterValues);
+ };
+
+ const clearFilterStore = () => {
+ setSelectedFilterValues({});
+ updateFilter("selectedConfig", {});
+ };
+
+ return (
+ <div
+ className={`flex w-full overflow-hidden transition-all gap-4 ${
+ isVisibleFilters ? "h-auto mt-4" : "h-0 mt-0"
+ }`}
+ >
+ {filterConfig?.traceTypes?.length ? (
+ <ComboDropdown
+ options={filterConfig?.traceTypes.map((p) => ({
+ label: p,
+ value: p,
+ }))}
+ title="Types"
+ type="traceTypes"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.traceTypes}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.models?.length ? (
+ <ComboDropdown
+ options={filterConfig?.models.map((m) => ({ label: m, value: m }))}
+ title="Models"
+ type="models"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.models}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.providers?.length ? (
+ <ComboDropdown
+ options={filterConfig?.providers.map((p) => ({ label: p, value: p }))}
+ title="Providers"
+ type="providers"
+ updateSelectedValues={updateSelectedValues}
+ selectedValues={selectedFilterValues.providers}
+ clearItem={clearFilter}
+ />
+ ) : null}
+ {filterConfig?.maxCost ? (
+ <SlideWithValue
+ label="Max Cost"
+ value={selectedFilterValues.maxCost || 0}
+ maxValue={filterConfig.maxCost}
+ onChange={updateSelectedValues}
+ type="maxCost"
+ />
+ ) : null}
+ <div className="grow" />
+ {areFiltersApplied && (
+ <Button
+ variant="ghost"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 p-2.5 relative"
+ onClick={clearFilterStore}
+ >
+ Clear Filters
+ </Button>
+ )}
+ <Button
+ variant="outline"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900 p-2.5 relative"
+ onClick={updateFilterStore}
+ >
+ Apply Filters
+ </Button>
+ </div>
+ );
+};
+
+export default function RequestFilter({ total }: { total: number }) {
+ const [isVisibleFilters, setIsVisibileFilters] = useState<boolean>(false);
const filter = useRootStore(getFilterDetails);
+ const filterConfig = useRootStore(getFilterConfig);
const updateFilter = useRootStore(getUpdateFilter);
const onClickPageAction = (dir: -1 | 1) => {
updateFilter("offset", filter.offset + dir * filter.limit);
@@ -26,18 +194,69 @@ export default function RequestFilter({
updateFilter("limit", size);
};
+ const toggleIsVisibleFilters = () => setIsVisibileFilters((e) => !e);
+ const showDynamicFilters =
+ filterConfig &&
+ Object.keys(filterConfig).filter((k) => {
+ const key = k as keyof FilterConfig;
+ if (typeof filterConfig[key] === "number") {
+ return (filterConfig[key] as number) > 0;
+ } else if (
+ typeof filterConfig[key] === "object" &&
+ (filterConfig[key] as string[]).length
+ ) {
+ return true;
+ }
+ return false;
+ }).length > 0;
+
+ const areFiltersApplied =
+ Object.keys(filter.selectedConfig).filter((k) => {
+ const key = k as keyof FilterConfig;
+ if (typeof filter.selectedConfig[key] === "number") {
+ return (filter.selectedConfig[key] as number) > 0;
+ } else if (
+ typeof filter.selectedConfig[key] === "object" &&
+ (filter.selectedConfig[key] as string[]).length
+ ) {
+ return true;
+ }
+ return false;
+ }).length > 0;
+
return (
- <div className="flex items-center w-full justify-between">
- <Filter />
- {config && (
- <RequestPagination
- currentPage={filter.offset / filter.limit + 1}
- currentSize={filter.limit}
- totalPage={ceil((config.totalRows || 0) / filter.limit)}
- onClickPageAction={onClickPageAction}
- onClickPageLimit={onClickPageLimit}
- />
- )}
+ <div className="flex flex-col items-center w-full justify-between mb-4">
+ <div className="flex w-full gap-4">
+ <Filter />
+ {filterConfig && total > 0 && (
+ <RequestPagination
+ currentPage={filter.offset / filter.limit + 1}
+ currentSize={filter.limit}
+ totalPage={ceil((total || 0) / filter.limit)}
+ onClickPageAction={onClickPageAction}
+ onClickPageLimit={onClickPageLimit}
+ />
+ )}
+ {total > 0 && <Sorting sorting={filter.sorting} />}
+ {showDynamicFilters && (
+ <Button
+ variant="outline"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900 aspect-square p-2.5 relative"
+ onClick={toggleIsVisibleFilters}
+ >
+ <SlidersHorizontal />
+ {areFiltersApplied && (
+ <span className="w-1 h-1 bg-primary absolute top-1 right-1 rounded-full" />
+ )}
+ </Button>
+ )}
+ </div>
+ <DynamicFilters
+ isVisibleFilters={isVisibleFilters}
+ filter={filter}
+ areFiltersApplied={areFiltersApplied}
+ />
</div>
);
}
diff --git a/src/client/src/app/api/metrics/request/config/route.ts b/src/client/src/app/api/metrics/request/config/route.ts
new file mode 100644
index 00000000..861a00a0
--- /dev/null
+++ b/src/client/src/app/api/metrics/request/config/route.ts
@@ -0,0 +1,32 @@
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
+import { getRequestsConfig } from "@/lib/platform/request";
+import {
+ validateMetricsRequest,
+ validateMetricsRequestType,
+} from "@/helpers/platform";
+
+export async function POST(request: Request) {
+ const formData = await request.json();
+ const timeLimit = formData.timeLimit as TimeLimit;
+ const limit = formData.limit || 10;
+ const offset = formData.offset || 0;
+
+ const params: MetricParams = {
+ timeLimit,
+ limit,
+ offset,
+ };
+
+ const validationParam = validateMetricsRequest(
+ params,
+ validateMetricsRequestType.GET_ALL
+ );
+
+ if (!validationParam.success)
+ return Response.json(validationParam.err, {
+ status: 400,
+ });
+
+ const res: any = await getRequestsConfig(params);
+ return Response.json(res);
+}
diff --git a/src/client/src/app/api/metrics/request/route.ts b/src/client/src/app/api/metrics/request/route.ts
index 16bc8fec..f77f87a5 100644
--- a/src/client/src/app/api/metrics/request/route.ts
+++ b/src/client/src/app/api/metrics/request/route.ts
@@ -1,4 +1,4 @@
-import { MetricParamsWithConfig, TimeLimit } from "@/lib/platform/common";
+import { MetricParams, TimeLimit } from "@/lib/platform/common";
import { getRequests } from "@/lib/platform/request";
import {
validateMetricsRequest,
@@ -8,15 +8,17 @@ import {
export async function POST(request: Request) {
const formData = await request.json();
const timeLimit = formData.timeLimit as TimeLimit;
- const config = formData.config || {};
const limit = formData.limit || 10;
const offset = formData.offset || 0;
+ const selectedConfig = formData.selectedConfig || {};
+ const sorting = formData.sorting || {};
- const params: MetricParamsWithConfig = {
+ const params: MetricParams = {
timeLimit,
- config,
limit,
offset,
+ selectedConfig,
+ sorting,
};
const validationParam = validateMetricsRequest(
diff --git a/src/client/src/app/globals.css b/src/client/src/app/globals.css
index 91f55f00..d8bfc953 100644
--- a/src/client/src/app/globals.css
+++ b/src/client/src/app/globals.css
@@ -1,4 +1,8 @@
@tailwind base;
- @tailwind components;
- @tailwind utilities;
-
\ No newline at end of file
+@tailwind components;
+@tailwind utilities;
+
+input::-webkit-outer-spin-button,
+input::-webkit-inner-spin-button {
+ margin-left: 10px;
+}
\ No newline at end of file
diff --git a/src/client/src/components/(playground)/filter/combo-dropdown.tsx b/src/client/src/components/(playground)/filter/combo-dropdown.tsx
new file mode 100644
index 00000000..27eb1626
--- /dev/null
+++ b/src/client/src/components/(playground)/filter/combo-dropdown.tsx
@@ -0,0 +1,149 @@
+import { CheckIcon, PlusCircleIcon } from "lucide-react";
+
+import { cn } from "@/lib/utils";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+ CommandSeparator,
+} from "@/components/ui/command";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@/components/ui/popover";
+import { Separator } from "@/components/ui/separator";
+
+interface ComboDropdownProps {
+ title?: string;
+ options: {
+ label: string;
+ value: string;
+ icon?: React.ComponentType<{ className?: string }>;
+ }[];
+ selectedValues?: any[];
+ type: any;
+ clearItem?: (type: any) => void;
+ updateSelectedValues: (type: any, value: any, operationType?: any) => void;
+}
+
+export default function ComboDropdown({
+ title,
+ options,
+ selectedValues,
+ type,
+ clearItem,
+ updateSelectedValues,
+}: ComboDropdownProps) {
+ const resetFilter = () => clearItem && clearItem(type);
+
+ return (
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ size="default"
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900"
+ >
+ <PlusCircleIcon className="mr-2 h-4 w-4" />
+ {title}
+ {selectedValues?.length ? (
+ <>
+ <Separator
+ orientation="vertical"
+ className="mx-2 h-4 bg-stone-300 dark:bg-stone-600"
+ />
+ <Badge
+ variant="secondary"
+ className="rounded-sm px-1 font-normal lg:hidden"
+ >
+ {selectedValues.length}
+ </Badge>
+ <div className="hidden space-x-1 lg:flex">
+ {selectedValues.length > 2 ? (
+ <Badge
+ variant="secondary"
+ className="rounded-sm px-1 font-normal"
+ >
+ {selectedValues.length} selected
+ </Badge>
+ ) : (
+ options
+ .filter((option) => selectedValues.includes(option.value))
+ .map((option) => (
+ <Badge
+ variant="secondary"
+ key={option.value}
+ className="rounded-sm px-1 font-normal capitalize"
+ >
+ {option.label}
+ </Badge>
+ ))
+ )}
+ </div>
+ </>
+ ) : null}
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[200px] p-0 cursor-pointer" align="start">
+ <Command>
+ <CommandInput placeholder={title} />
+ <CommandList>
+ <CommandEmpty>No results found.</CommandEmpty>
+ <CommandGroup>
+ {options.map((option) => {
+ const isSelected = selectedValues?.includes(option.value);
+ return (
+ <CommandItem
+ className="cursor-pointer capitalize"
+ key={option.value}
+ onSelect={() => {
+ if (isSelected) {
+ updateSelectedValues(type, option.value, "delete");
+ } else {
+ updateSelectedValues(type, option.value, "add");
+ }
+ }}
+ >
+ <div
+ className={cn(
+ "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
+ isSelected
+ ? "bg-primary text-primary-foreground"
+ : "opacity-50 [&_svg]:invisible"
+ )}
+ >
+ <CheckIcon className={"h-4 w-4 text-stone-100"} />
+ </div>
+ {option.icon && (
+ <option.icon className="mr-2 h-4 w-4 text-muted-foreground" />
+ )}
+ <span>{option.label}</span>
+ </CommandItem>
+ );
+ })}
+ </CommandGroup>
+ {selectedValues?.length ? (
+ <>
+ <CommandSeparator />
+ <CommandGroup>
+ <CommandItem
+ onSelect={resetFilter}
+ className="justify-center text-center cursor-pointer"
+ >
+ Reset
+ </CommandItem>
+ </CommandGroup>
+ </>
+ ) : null}
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/src/client/src/components/(playground)/filter.tsx b/src/client/src/components/(playground)/filter/index.tsx
similarity index 87%
rename from src/client/src/components/(playground)/filter.tsx
rename to src/client/src/components/(playground)/filter/index.tsx
index ca1d74f8..a0fe8116 100644
--- a/src/client/src/components/(playground)/filter.tsx
+++ b/src/client/src/components/(playground)/filter/index.tsx
@@ -3,8 +3,6 @@ import { getFilterDetails, getUpdateFilter } from "@/selectors/filter";
import { useRootStore } from "@/store";
import { DatePickerWithRange } from "@/components/ui/date-range-picker";
-const DEFAULT_TIME_RANGE = "24H";
-
const TIME_RANGE_TYPE: Record<"24H" | "7D" | "1M" | "3M" | "CUSTOM", string> = {
"24H": "24H",
"7D": "7D",
@@ -20,9 +18,10 @@ const TIME_RANGE_TABS: { key: string; label: string }[] = Object.keys(
label: TIME_RANGE_TYPE[k as keyof typeof TIME_RANGE_TYPE],
}));
-const Filter = () => {
+const Filter = ({ className = "" }: { className?: string }) => {
const filter = useRootStore(getFilterDetails);
const updateFilter = useRootStore(getUpdateFilter);
+
const handleChange = (key: string) => {
updateFilter("timeLimit.type", key);
};
@@ -32,8 +31,8 @@ const Filter = () => {
};
return (
- <div className="flex w-full mb-4 md:mb-4 gap-4">
- <Tabs defaultValue={DEFAULT_TIME_RANGE} onValueChange={handleChange}>
+ <div className={`flex grow gap-4 ${className}`}>
+ <Tabs defaultValue={filter.timeLimit.type} onValueChange={handleChange}>
<TabsList>
{TIME_RANGE_TABS.map(({ label, key }) => (
<TabsTrigger key={key} value={key}>
diff --git a/src/client/src/components/(playground)/filter/slider-with-value.tsx b/src/client/src/components/(playground)/filter/slider-with-value.tsx
new file mode 100644
index 00000000..8419917f
--- /dev/null
+++ b/src/client/src/components/(playground)/filter/slider-with-value.tsx
@@ -0,0 +1,58 @@
+import { FilterConfig } from "@/store/filter";
+import { Label } from "@/components/ui/label";
+import { Slider } from "@/components/ui/slider";
+import { Input } from "@/components/ui/input";
+import { ChangeEventHandler, useState } from "react";
+
+export default function SlideWithValue({
+ label,
+ value,
+ maxValue,
+ onChange,
+ step,
+ type,
+}: {
+ label: string;
+ value: number;
+ maxValue: number;
+ onChange: (type: keyof FilterConfig, value: any) => void;
+ step?: number;
+ type: keyof FilterConfig;
+}) {
+ const onSliderValueChange = (changedValue: number[]) => {
+ onChange(type, (changedValue[0] * maxValue) / 100);
+ };
+
+ const onInputValueChange: ChangeEventHandler<HTMLInputElement> = (ev) => {
+ onChange(type, parseFloat(ev.target.value));
+ };
+
+ const percentageValue = (value / (maxValue || 1)) * 100;
+ const stepValue = step || maxValue / 1000;
+
+ return (
+ <div className="flex items-center shrink-0 w-96 px-4 ml-4 border border-stone-200 dark:border-0 dark:bg-stone-800 rounded-md text-stone-500 gap-2">
+ <div className="flex items-center justify-between shrink-0">
+ <Label htmlFor={type}>{label}</Label>
+ </div>
+ <Slider
+ id={type}
+ max={100}
+ defaultValue={[percentageValue]}
+ value={[percentageValue]}
+ step={stepValue}
+ onValueChange={onSliderValueChange}
+ className="[&_[role=slider]]:h-4 [&_[role=slider]]:w-4 w-36 ml-3 shrink-0"
+ aria-label={label}
+ />
+ <Input
+ defaultValue={value}
+ step={stepValue}
+ value={value}
+ onChange={onInputValueChange}
+ className="border-0 text-right p-0 bg-transparent dark:bg-transparent"
+ type="number"
+ />
+ </div>
+ );
+}
diff --git a/src/client/src/components/(playground)/filter/sorting.tsx b/src/client/src/components/(playground)/filter/sorting.tsx
new file mode 100644
index 00000000..a86e9796
--- /dev/null
+++ b/src/client/src/components/(playground)/filter/sorting.tsx
@@ -0,0 +1,66 @@
+import { Button } from "@/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from "@/components/ui/dropdown-menu";
+import { getTraceMappingKeyFullPath } from "@/helpers/trace";
+import { getUpdateFilter } from "@/selectors/filter";
+import { useRootStore } from "@/store";
+import { FilterSorting } from "@/store/filter";
+import { ArrowDownIcon, ArrowDownUpIcon, ArrowUpIcon } from "lucide-react";
+
+const SORTING_TYPES = [
+ { key: "Timestamp", label: "Timestamp" },
+ {
+ key: `SpanAttributes['${getTraceMappingKeyFullPath("cost")}']`,
+ label: "Cost",
+ },
+ {
+ key: `SpanAttributes['${getTraceMappingKeyFullPath("totalTokens")}']`,
+ label: "Total tokens",
+ },
+ {
+ key: `SpanAttributes['${getTraceMappingKeyFullPath("promptTokens")}']`,
+ label: "Prompt tokens",
+ },
+];
+
+export default function Sorting({ sorting }: { sorting: FilterSorting }) {
+ const updateFilter = useRootStore(getUpdateFilter);
+ const onSortingChange = (type: string) => {
+ const updatedSorting: FilterSorting = { type, direction: "desc" };
+ if (sorting.type === type) {
+ if (sorting.direction === "asc") updatedSorting.direction = "desc";
+ else updatedSorting.direction = "asc";
+ }
+ updateFilter("sorting", updatedSorting);
+ };
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <Button
+ className="text-stone-500 hover:text-stone-600 dark:text-stone-400 dark:hover:text-stone-300 dark:bg-stone-800 dark:hover:bg-stone-900 aspect-square p-2.5 relative"
+ variant="outline"
+ >
+ <ArrowDownUpIcon />
+ </Button>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ {SORTING_TYPES.map(({ key, label }) => (
+ <DropdownMenuItem key={key} onClick={() => onSortingChange(key)}>
+ {label}
+ {key === sorting.type &&
+ (sorting.direction === "asc" ? (
+ <ArrowUpIcon className="h-4 w-4 ml-auto" />
+ ) : (
+ <ArrowDownIcon className="h-4 w-4 ml-auto" />
+ ))}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/src/client/src/components/(playground)/pie-chart-card.tsx b/src/client/src/components/(playground)/pie-chart-card.tsx
index 9939302e..cf47b99c 100644
--- a/src/client/src/components/(playground)/pie-chart-card.tsx
+++ b/src/client/src/components/(playground)/pie-chart-card.tsx
@@ -8,6 +8,7 @@ import { PieChart, Pie, Sector, ResponsiveContainer } from "recharts";
import { COLORS } from "../../../colors";
import IntermediateState from "./intermediate-state";
import { Skeleton } from "../ui/skeleton";
+import { getFilterParamsForDashboard } from "@/helpers/filter";
const renderActiveShape = (props: any) => {
const {
@@ -121,9 +122,7 @@ const PieChartCard = memo(
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- }),
+ body: JSON.stringify(getFilterParamsForDashboard(filter)),
requestType: "POST",
url,
responseDataKey: "data",
diff --git a/src/client/src/components/(playground)/request-pagination.tsx b/src/client/src/components/(playground)/request-pagination.tsx
index 53a4f93e..6a035d75 100644
--- a/src/client/src/components/(playground)/request-pagination.tsx
+++ b/src/client/src/components/(playground)/request-pagination.tsx
@@ -39,12 +39,15 @@ export default function RequestPagination(props: PaginationProps) {
};
const firstPage = props.currentPage === 1;
- const lastPage = props.currentPage === props.totalPage;
+ const lastPage =
+ props.totalPage === 0 || props.currentPage === props.totalPage;
return (
- <div className="flex self-end gap-4">
+ <div className="flex gap-4">
<div className="flex align-end justify-center">
- <p className="text-xs shrink-0 mr-3 self-center text-stone-950 dark:text-stone-100">Size : </p>
+ <p className="text-xs shrink-0 mr-3 self-center text-stone-950 dark:text-stone-100">
+ Size :{" "}
+ </p>
<div className="w-[100px]">
<Select
onValueChange={onSizeChange}
@@ -77,7 +80,7 @@ export default function RequestPagination(props: PaginationProps) {
</Select>
</div>
</div>
- <Pagination className="justify-end w-auto shrink-0 m-0">
+ <Pagination className="w-auto shrink-0 m-0">
<PaginationContent>
<PaginationItem>
<PaginationPrevious
@@ -92,7 +95,7 @@ export default function RequestPagination(props: PaginationProps) {
/>
</PaginationItem>
<PaginationItem>
- <div className="flex items-center text-sm text-stone-950 dark:text-stone-100 mx-3">
+ <div className="flex items-center text-sm text-stone-950 dark:text-stone-100">
{props.currentPage} of {props.totalPage || 1}
</div>
</PaginationItem>
diff --git a/src/client/src/components/(playground)/stat-card.tsx b/src/client/src/components/(playground)/stat-card.tsx
index 373c3761..465651d4 100644
--- a/src/client/src/components/(playground)/stat-card.tsx
+++ b/src/client/src/components/(playground)/stat-card.tsx
@@ -8,6 +8,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { LucideIcon, TrendingDown, TrendingUp } from "lucide-react";
import IntermediateState from "./intermediate-state";
+import { getFilterParamsForDashboard } from "@/helpers/filter";
type StatCardProps = {
heading?: string;
@@ -44,10 +45,12 @@ const StatCard = memo(
const fetchData = useCallback(async () => {
fireRequest({
- body: JSON.stringify({
- timeLimit: filter.timeLimit,
- ...extraParams,
- }),
+ body: JSON.stringify(
+ getFilterParamsForDashboard({
+ ...filter,
+ ...extraParams,
+ })
+ ),
requestType: "POST",
url,
responseDataKey: "data[0]",
diff --git a/src/client/src/components/ui/command.tsx b/src/client/src/components/ui/command.tsx
new file mode 100644
index 00000000..2d6922fe
--- /dev/null
+++ b/src/client/src/components/ui/command.tsx
@@ -0,0 +1,155 @@
+"use client"
+
+import * as React from "react"
+import { type DialogProps } from "@radix-ui/react-dialog"
+import { Command as CommandPrimitive } from "cmdk"
+import { Search } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+import { Dialog, DialogContent } from "@/components/ui/dialog"
+
+const Command = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive
+ ref={ref}
+ className={cn(
+ "flex h-full w-full flex-col overflow-hidden rounded-md bg-white text-stone-950 dark:bg-stone-950 dark:text-stone-50",
+ className
+ )}
+ {...props}
+ />
+))
+Command.displayName = CommandPrimitive.displayName
+
+interface CommandDialogProps extends DialogProps {}
+
+const CommandDialog = ({ children, ...props }: CommandDialogProps) => {
+ return (
+ <Dialog {...props}>
+ <DialogContent className="overflow-hidden p-0 shadow-lg">
+ <Command className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-stone-500 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5 dark:[&_[cmdk-group-heading]]:text-stone-400">
+ {children}
+ </Command>
+ </DialogContent>
+ </Dialog>
+ )
+}
+
+const CommandInput = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Input>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Input>
+>(({ className, ...props }, ref) => (
+ <div className="flex items-center border-b px-3 dark:border-stone-800" cmdk-input-wrapper="">
+ <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
+ <CommandPrimitive.Input
+ ref={ref}
+ className={cn(
+ "flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-stone-500 disabled:cursor-not-allowed disabled:opacity-50 dark:placeholder:text-stone-400 dark:border-stone-700",
+ className
+ )}
+ {...props}
+ />
+ </div>
+))
+
+CommandInput.displayName = CommandPrimitive.Input.displayName
+
+const CommandList = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.List>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.List>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.List
+ ref={ref}
+ className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
+ {...props}
+ />
+))
+
+CommandList.displayName = CommandPrimitive.List.displayName
+
+const CommandEmpty = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Empty>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Empty>
+>((props, ref) => (
+ <CommandPrimitive.Empty
+ ref={ref}
+ className="py-6 text-center text-sm"
+ {...props}
+ />
+))
+
+CommandEmpty.displayName = CommandPrimitive.Empty.displayName
+
+const CommandGroup = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Group>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Group>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Group
+ ref={ref}
+ className={cn(
+ "overflow-hidden p-1 text-stone-950 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-stone-500 dark:text-stone-50 dark:[&_[cmdk-group-heading]]:text-stone-400",
+ className
+ )}
+ {...props}
+ />
+))
+
+CommandGroup.displayName = CommandPrimitive.Group.displayName
+
+const CommandSeparator = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Separator>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 h-px bg-stone-200 dark:bg-stone-800", className)}
+ {...props}
+ />
+))
+CommandSeparator.displayName = CommandPrimitive.Separator.displayName
+
+const CommandItem = React.forwardRef<
+ React.ElementRef<typeof CommandPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof CommandPrimitive.Item>
+>(({ className, ...props }, ref) => (
+ <CommandPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none aria-selected:bg-stone-100 aria-selected:text-stone-900 data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 dark:aria-selected:bg-stone-800 dark:aria-selected:text-stone-50",
+ className
+ )}
+ {...props}
+ />
+))
+
+CommandItem.displayName = CommandPrimitive.Item.displayName
+
+const CommandShortcut = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span
+ className={cn(
+ "ml-auto text-xs tracking-widest text-stone-500 dark:text-stone-400",
+ className
+ )}
+ {...props}
+ />
+ )
+}
+CommandShortcut.displayName = "CommandShortcut"
+
+export {
+ Command,
+ CommandDialog,
+ CommandInput,
+ CommandList,
+ CommandEmpty,
+ CommandGroup,
+ CommandItem,
+ CommandShortcut,
+ CommandSeparator,
+}
diff --git a/src/client/src/components/ui/date-range-picker.tsx b/src/client/src/components/ui/date-range-picker.tsx
index 1b04a1f1..cb70e36e 100644
--- a/src/client/src/components/ui/date-range-picker.tsx
+++ b/src/client/src/components/ui/date-range-picker.tsx
@@ -42,11 +42,11 @@ export function DatePickerWithRange({
id="date"
variant={"outline"}
className={cn(
- "justify-start text-left font-normal dark:bg-stone-900 dark:text-stone-100",
+ "justify-start text-left font-normal dark:bg-stone-900 dark:text-stone-100 text-xs",
!date && "text-muted-foreground"
)}
>
- <CalendarIcon className="mr-2 h-4 w-4" />
+ <CalendarIcon className="mr-2 h-3 w-3" />
{date?.from ? (
date.to ? (
<>
diff --git a/src/client/src/components/ui/dialog.tsx b/src/client/src/components/ui/dialog.tsx
new file mode 100644
index 00000000..d28454e3
--- /dev/null
+++ b/src/client/src/components/ui/dialog.tsx
@@ -0,0 +1,122 @@
+"use client"
+
+import * as React from "react"
+import * as DialogPrimitive from "@radix-ui/react-dialog"
+import { X } from "lucide-react"
+
+import { cn } from "@/lib/utils"
+
+const Dialog = DialogPrimitive.Root
+
+const DialogTrigger = DialogPrimitive.Trigger
+
+const DialogPortal = DialogPrimitive.Portal
+
+const DialogClose = DialogPrimitive.Close
+
+const DialogOverlay = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className
+ )}
+ {...props}
+ />
+))
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
+
+const DialogContent = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+>(({ className, children, ...props }, ref) => (
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border border-stone-200 bg-white p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg dark:border-stone-800 dark:bg-stone-950",
+ className
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-white transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-stone-950 focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-stone-100 data-[state=open]:text-stone-500 dark:ring-offset-stone-950 dark:focus:ring-stone-300 dark:data-[state=open]:bg-stone-800 dark:data-[state=open]:text-stone-400">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+))
+DialogContent.displayName = DialogPrimitive.Content.displayName
+
+const DialogHeader = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col space-y-1.5 text-center sm:text-left",
+ className
+ )}
+ {...props}
+ />
+)
+DialogHeader.displayName = "DialogHeader"
+
+const DialogFooter = ({
+ className,
+ ...props
+}: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn(
+ "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
+ className
+ )}
+ {...props}
+ />
+)
+DialogFooter.displayName = "DialogFooter"
+
+const DialogTitle = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn(
+ "text-lg font-semibold leading-none tracking-tight",
+ className
+ )}
+ {...props}
+ />
+))
+DialogTitle.displayName = DialogPrimitive.Title.displayName
+
+const DialogDescription = React.forwardRef<
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+>(({ className, ...props }, ref) => (
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-stone-500 dark:text-stone-400", className)}
+ {...props}
+ />
+))
+DialogDescription.displayName = DialogPrimitive.Description.displayName
+
+export {
+ Dialog,
+ DialogPortal,
+ DialogOverlay,
+ DialogClose,
+ DialogTrigger,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription,
+}
diff --git a/src/client/src/components/ui/separator.tsx b/src/client/src/components/ui/separator.tsx
new file mode 100644
index 00000000..a6ed83ef
--- /dev/null
+++ b/src/client/src/components/ui/separator.tsx
@@ -0,0 +1,31 @@
+"use client"
+
+import * as React from "react"
+import * as SeparatorPrimitive from "@radix-ui/react-separator"
+
+import { cn } from "@/lib/utils"
+
+const Separator = React.forwardRef<
+ React.ElementRef<typeof SeparatorPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SeparatorPrimitive.Root>
+>(
+ (
+ { className, orientation = "horizontal", decorative = true, ...props },
+ ref
+ ) => (
+ <SeparatorPrimitive.Root
+ ref={ref}
+ decorative={decorative}
+ orientation={orientation}
+ className={cn(
+ "shrink-0 bg-stone-200 dark:bg-stone-800",
+ orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
+ className
+ )}
+ {...props}
+ />
+ )
+)
+Separator.displayName = SeparatorPrimitive.Root.displayName
+
+export { Separator }
diff --git a/src/client/src/components/ui/slider.tsx b/src/client/src/components/ui/slider.tsx
new file mode 100644
index 00000000..2e8be298
--- /dev/null
+++ b/src/client/src/components/ui/slider.tsx
@@ -0,0 +1,28 @@
+"use client"
+
+import * as React from "react"
+import * as SliderPrimitive from "@radix-ui/react-slider"
+
+import { cn } from "@/lib/utils"
+
+const Slider = React.forwardRef<
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+>(({ className, ...props }, ref) => (
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn(
+ "relative flex touch-none select-none items-center",
+ className
+ )}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-2 w-full grow overflow-hidden rounded-full bg-stone-200 dark:bg-stone-700">
+ <SliderPrimitive.Range className="absolute h-full bg-stone-900 dark:bg-stone-50" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-stone-900 bg-white ring-offset-white transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-950 focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 dark:border-stone-50 dark:bg-stone-950 dark:ring-offset-stone-950 dark:focus-visible:ring-stone-300" />
+ </SliderPrimitive.Root>
+))
+Slider.displayName = SliderPrimitive.Root.displayName
+
+export { Slider }
diff --git a/src/client/src/constants/traces.ts b/src/client/src/constants/traces.ts
index 069cda76..39d20b73 100644
--- a/src/client/src/constants/traces.ts
+++ b/src/client/src/constants/traces.ts
@@ -112,7 +112,7 @@ export const TraceMapping: Record<
path: "usage.cost",
prefix: SpanAttributesGenAIPrefix,
icon: CircleDollarSign,
- offset: 6,
+ offset: 10,
defaultValue: "-",
},
diff --git a/src/client/src/helpers/database-config.ts b/src/client/src/helpers/database-config.ts
index 5e8e284a..2cc19bbd 100644
--- a/src/client/src/helpers/database-config.ts
+++ b/src/client/src/helpers/database-config.ts
@@ -57,6 +57,9 @@ export const changeActiveDatabaseConfig = async (databaseConfigId: string) => {
return acc;
}, []);
useRootStore.getState().databaseConfig.setList(updatedList);
+ toast.success(`Db config: set active successfully!`, {
+ id: "db-config-current",
+ });
pingActiveDatabaseConfig();
};
diff --git a/src/client/src/helpers/filter.ts b/src/client/src/helpers/filter.ts
new file mode 100644
index 00000000..708531fc
--- /dev/null
+++ b/src/client/src/helpers/filter.ts
@@ -0,0 +1,5 @@
+import { omit } from "lodash";
+
+export const getFilterParamsForDashboard = (filter: Record<any, any>) => {
+ return omit(filter, ["limit", "offset", "selectedConfig", "sorting"]);
+};
diff --git a/src/client/src/helpers/platform.ts b/src/client/src/helpers/platform.ts
index 87d6df0a..e70c375a 100644
--- a/src/client/src/helpers/platform.ts
+++ b/src/client/src/helpers/platform.ts
@@ -2,6 +2,7 @@ import { SPAN_KIND } from "@/constants/traces";
import { ValueOf } from "../utils/types";
import { MetricParams } from "@/lib/platform/common";
import { addDays, addMonths, differenceInDays } from "date-fns";
+import { getTraceMappingKeyFullPath } from "./trace";
export const validateMetricsRequestType = {
// Request
@@ -133,7 +134,29 @@ export const validateMetricsRequest = (
return { success: true };
};
-export const getFilterWhereCondition = (filter: any) => {
+type FilterWhereConditionType = {
+ timeLimit: {
+ start: Date | string;
+ end: Date | string;
+ type: string;
+ };
+ offset?: number;
+ limit?: number;
+ selectedConfig?: Partial<{
+ providers: string[];
+ maxCost: number;
+ models: string[];
+ traceTypes: string[];
+ }>;
+ notOrEmpty?: { key: string }[];
+ notEmpty?: { key: string }[];
+ statusCode?: string;
+};
+
+export const getFilterWhereCondition = (
+ filter: FilterWhereConditionType,
+ filterSelectedConfig?: boolean
+) => {
const whereArray: string[] = [];
try {
const { start, end } = filter.timeLimit || {};
@@ -143,6 +166,59 @@ export const getFilterWhereCondition = (filter: any) => {
);
}
+ if (filterSelectedConfig && filter.selectedConfig) {
+ if (filter.selectedConfig.models?.length) {
+ whereArray.push(
+ `SpanAttributes['${getTraceMappingKeyFullPath(
+ "model"
+ )}'] IN (${filter.selectedConfig.models
+ .map((model) => `'${model}'`)
+ .join(", ")})`
+ );
+ }
+
+ if (filter.selectedConfig.providers?.length) {
+ whereArray.push(
+ `(SpanAttributes['${getTraceMappingKeyFullPath(
+ "system"
+ )}'] IN (${filter.selectedConfig.providers
+ .map((provider) => `'${provider}'`)
+ .join(", ")}) OR SpanAttributes['${getTraceMappingKeyFullPath(
+ "provider"
+ )}'] IN (${filter.selectedConfig.providers
+ .map((provider) => `'${provider}'`)
+ .join(", ")}))`
+ );
+ }
+
+ if (filter.selectedConfig.traceTypes?.length) {
+ whereArray.push(
+ `SpanAttributes['${getTraceMappingKeyFullPath(
+ "type"
+ )}'] IN (${filter.selectedConfig.traceTypes
+ .map((type) => `'${type}'`)
+ .join(", ")})`
+ );
+ }
+
+ if (filter.selectedConfig.maxCost) {
+ whereArray.push(
+ `toFloat64OrZero(SpanAttributes['${getTraceMappingKeyFullPath(
+ "cost"
+ )}']) BETWEEN 0 AND ${filter.selectedConfig.maxCost.toFixed(10)}`
+ );
+ }
+ }
+
+ if (filter.notOrEmpty && filter.notOrEmpty?.length > 0) {
+ const whereOrArray: string[] = [];
+ filter.notOrEmpty.map(({ key }: { key: string }) => {
+ whereOrArray.push(`notEmpty(${key})`);
+ });
+
+ whereArray.push(`( ${whereOrArray.join(" OR ")} )`);
+ }
+
if (filter.notEmpty && filter.notEmpty?.length > 0) {
filter.notEmpty.map(({ key }: { key: string }) => {
whereArray.push(`notEmpty(${key})`);
diff --git a/src/client/src/helpers/trace.ts b/src/client/src/helpers/trace.ts
index 94173613..86bdc0b2 100644
--- a/src/client/src/helpers/trace.ts
+++ b/src/client/src/helpers/trace.ts
@@ -32,9 +32,9 @@ export const normalizeTrace = (item: TraceRow): TransformedTraceRow => {
acc[traceKey] = floatParser(
(value || "0") as string,
TraceMapping[traceKey].offset
- );
+ ).toFixed(10);
} else if (TraceMapping[traceKey].type === "round") {
- acc[traceKey] = round(value as number, TraceMapping[traceKey].offset);
+ acc[traceKey] = round(value as number, TraceMapping[traceKey].offset).toFixed(10);
} else {
acc[traceKey] = value;
}
diff --git a/src/client/src/lib/platform/common.ts b/src/client/src/lib/platform/common.ts
index ce47b42b..d050d1e8 100644
--- a/src/client/src/lib/platform/common.ts
+++ b/src/client/src/lib/platform/common.ts
@@ -19,18 +19,11 @@ export type TimeLimit = {
export interface MetricParams {
timeLimit: TimeLimit;
-}
-
-export type MetricParamsWithConfig = MetricParams & {
- config?: {
- providers?: boolean;
- maxCost?: boolean;
- models?: boolean;
- totalRows?: boolean;
- };
offset?: number;
limit?: number;
-};
+ selectedConfig?: any;
+ sorting?: any;
+}
export type DataCollectorType = { err?: unknown; data?: unknown };
export async function dataCollector(
diff --git a/src/client/src/lib/platform/endpoint.ts b/src/client/src/lib/platform/endpoint.ts
index 0a5ffb58..a16ab8ef 100644
--- a/src/client/src/lib/platform/endpoint.ts
+++ b/src/client/src/lib/platform/endpoint.ts
@@ -3,16 +3,25 @@ import { MetricParams, dataCollector, OTEL_TRACES_TABLE_NAME } from "./common";
import { getTraceMappingKeyFullPath } from "@/helpers/trace";
export async function getResultGenerationByEndpoint(params: MetricParams) {
- const keyPath = `SpanAttributes['${getTraceMappingKeyFullPath("provider")}']`;
+ const keyPaths = [
+ { key: `SpanAttributes['${getTraceMappingKeyFullPath("system")}']` },
+ { key: `SpanAttributes['${getTraceMappingKeyFullPath("provider")}']` },
+ ];
const query = `
SELECT
- ${keyPath} AS provider,
+ CASE
+ WHEN notEmpty(SpanAttributes['${getTraceMappingKeyFullPath(
+ "provider"
+ )}'])
+ THEN SpanAttributes['${getTraceMappingKeyFullPath("provider")}']
+ ELSE SpanAttributes['${getTraceMappingKeyFullPath("system")}']
+ END AS provider,
CAST(COUNT(*) AS INTEGER) AS count
FROM
${OTEL_TRACES_TABLE_NAME}
WHERE ${getFilterWhereCondition({
...params,
- notEmpty: [{ key: keyPath }],
+ notOrEmpty: keyPaths,
})}
GROUP BY provider;
`;
diff --git a/src/client/src/lib/platform/request.ts b/src/client/src/lib/platform/request.ts
index 341046cd..327eddfe 100644
--- a/src/client/src/lib/platform/request.ts
+++ b/src/client/src/lib/platform/request.ts
@@ -1,7 +1,6 @@
import {
MetricParams,
dataCollector,
- MetricParamsWithConfig,
DataCollectorType,
OTEL_TRACES_TABLE_NAME,
} from "./common";
@@ -99,75 +98,79 @@ export async function getAverageRequestDuration(params: MetricParams) {
return dataCollector({ query });
}
-export async function getRequestsConfig(params: MetricParamsWithConfig) {
- const { providers, maxCost, models, totalRows } = params.config || {};
-
- const keyPaths: { key: string }[] = [];
+export async function getRequestsConfig(params: MetricParams) {
const select: string[] = [];
- if (providers) {
- keyPaths.push({
- key: `SpanAttributes['${getTraceMappingKeyFullPath("provider")}']`,
- });
- select.push(
- `ARRAY_AGG(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
+ select.push(
+ `arrayConcat(
+ arrayFilter(x -> x != '', groupArray(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
"provider"
- )}']) AS providers`
- );
- }
-
- if (maxCost) {
- keyPaths.push({
- key: `SpanAttributes['${getTraceMappingKeyFullPath("cost")}']`,
- });
- select.push(
- `MAX(SpanAttributes['${getTraceMappingKeyFullPath("cost")}']) AS maxCost`
- );
- }
-
- if (models) {
- keyPaths.push({
- key: `SpanAttributes['${getTraceMappingKeyFullPath("model")}']`,
- });
- select.push(
- `ARRAY_AGG(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
- "model"
- )}']) AS models`
- );
- }
-
- if (totalRows) {
- select.push(`COUNT(*) AS totalRows`);
- }
-
- if (select.length === 0) return [];
+ )}'])),
+ arrayFilter(x -> x != '', groupArray(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
+ "system"
+ )}']))
+ ) AS providers`
+ );
+
+ select.push(
+ `CAST(MAX(toFloat64OrZero(SpanAttributes['${getTraceMappingKeyFullPath(
+ "cost"
+ )}'])) AS FLOAT) AS maxCost`
+ );
+
+ select.push(
+ `arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
+ "model"
+ )}'])) AS models`
+ );
+
+ select.push(
+ `arrayFilter(x -> x != '', ARRAY_AGG(DISTINCT SpanAttributes['${getTraceMappingKeyFullPath(
+ "type"
+ )}'])) AS traceTypes`
+ );
+
+ select.push(`CAST(COUNT(*) AS INTEGER) AS totalRows`);
const query = `SELECT ${select.join(", ")} FROM ${OTEL_TRACES_TABLE_NAME}
- WHERE ${getFilterWhereCondition({ ...params, notEmpty: keyPaths })}`;
+ WHERE ${getFilterWhereCondition({ ...params })}`;
return dataCollector({ query });
}
-export async function getRequests(params: MetricParamsWithConfig) {
+export async function getRequests(params: MetricParams) {
const { limit = 10, offset = 0 } = params;
- let config: unknown = {};
- if (params.config) {
- const configValues = await getRequestsConfig(params);
- config =
- ((configValues as DataCollectorType)?.data as Array<any>)?.[0] || {};
+ const countQuery = `SELECT CAST(COUNT(*) AS INTEGER) AS total FROM ${OTEL_TRACES_TABLE_NAME}
+ WHERE ${getFilterWhereCondition(params, true)}`;
+
+ const { data: dataTotal, err: errTotal } = await dataCollector({
+ query: countQuery,
+ });
+ if (errTotal) {
+ return {
+ err: errTotal,
+ };
}
const query = `SELECT * FROM ${OTEL_TRACES_TABLE_NAME}
- WHERE ${getFilterWhereCondition(params)}
- ORDER BY Timestamp desc
+ WHERE ${getFilterWhereCondition(params, true)}
+ ${
+ params.sorting
+ ? params.sorting.type.includes("cost")
+ ? `ORDER BY toFloat64OrZero(${params.sorting.type}) ${params.sorting.direction} `
+ : params.sorting.type.includes("tokens")
+ ? `ORDER BY toInt32OrZero(${params.sorting.type}) ${params.sorting.direction} `
+ : `ORDER BY ${params.sorting.type} ${params.sorting.direction} `
+ : `ORDER BY Timestamp desc `
+ }
LIMIT ${limit}
OFFSET ${offset}`;
const { data, err } = await dataCollector({ query });
return {
err,
- config,
records: data,
+ total: (dataTotal as any[])?.[0]?.total || 0,
};
}
diff --git a/src/client/src/selectors/filter.ts b/src/client/src/selectors/filter.ts
index e16ed2a5..9c8a7056 100644
--- a/src/client/src/selectors/filter.ts
+++ b/src/client/src/selectors/filter.ts
@@ -3,3 +3,7 @@ import { RootStore } from "@/store";
export const getFilterDetails = (state: RootStore) => state.filter.details;
export const getUpdateFilter = (state: RootStore) => state.filter.updateFilter;
+
+export const getFilterConfig = (state: RootStore) => state.filter.config;
+
+export const getUpdateConfig = (state: RootStore) => state.filter.updateConfig;
diff --git a/src/client/src/store/filter.ts b/src/client/src/store/filter.ts
index dedd5ca9..8bf2e5f3 100644
--- a/src/client/src/store/filter.ts
+++ b/src/client/src/store/filter.ts
@@ -15,6 +15,11 @@ export const TIME_RANGE_TYPE: Record<
export const DEFAULT_TIME_RANGE = "24H";
+export type FilterSorting = {
+ type: string;
+ direction: "asc" | "desc";
+};
+
export interface FilterType {
timeLimit: {
start?: Date;
@@ -23,6 +28,16 @@ export interface FilterType {
};
limit: number;
offset: number;
+ selectedConfig: Partial<FilterConfig>;
+ sorting: FilterSorting;
+}
+
+export interface FilterConfig {
+ providers: string[];
+ maxCost: number;
+ models: string[];
+ totalRows: number;
+ traceTypes: string[];
}
function getTimeLimitObject(
@@ -58,38 +73,60 @@ function getTimeLimitObject(
return object;
}
-const INITIAL_FILTER: FilterType = {
+const INITIAL_FILTER_DETAILS: FilterType = {
timeLimit: {
type: DEFAULT_TIME_RANGE,
...getTimeLimitObject(DEFAULT_TIME_RANGE, ""),
},
limit: 10,
offset: 0,
+ selectedConfig: {},
+ sorting: {
+ type: "Timestamp",
+ direction: "desc",
+ },
};
export type FilterStore = {
details: FilterType;
+ config?: FilterConfig;
updateFilter: (key: string, value: any, extraParams?: any) => void;
+ updateConfig: (config: FilterConfig) => void;
};
export const filterStoreSlice: FilterStore = lens((setStore, getStore) => ({
- details: INITIAL_FILTER,
+ details: INITIAL_FILTER_DETAILS,
updateFilter: (key: string, value: any, extraParams?: any) => {
let object = {};
+ let resetConfig = false;
switch (key) {
case "timeLimit.type":
object = getTimeLimitObject(value, "timeLimit.", extraParams);
+ resetConfig = true;
break;
case "limit":
+ case "selectedConfig":
+ case "sorting":
set(object, "offset", 0);
break;
case "offset":
+ // Its already handled in the set(object, key, value); line
break;
default:
break;
}
set(object, key, value);
- setStore({ details: { ...getStore().details, ...object } });
+ setStore({
+ details: {
+ ...getStore().details,
+ selectedConfig: resetConfig ? {} : getStore().details.selectedConfig,
+ ...object,
+ },
+ config: resetConfig ? undefined : getStore().config,
+ });
+ },
+ updateConfig: (config: FilterConfig) => {
+ setStore({ config });
},
}));