Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

AI Filters

Steven Teyb99041100bef
diff --git a/apps/web/app/api/ai/generate-support-title/route.ts b/apps/web/app/api/ai/generate-support-title/route.ts
index 3f6b9f6e29..336c3d4e4b 100644
--- a/apps/web/app/api/ai/generate-support-title/route.ts
+++ b/apps/web/app/api/ai/generate-support-title/route.ts
@@ -27,7 +27,7 @@ export async function POST(req: NextRequest) {
// you can only generate a support completion 3 times per minute
const { success } = await ratelimit(3, "1 m").limit(
- `ai-completion:${session.sub}`,
+ `ai-generate-support-title:${session.sub}`,
);
if (!success) {
throw new DubApiError({
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index 091176e7d0..7ec9f9a9ea 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -102,14 +102,18 @@ export const SINGULAR_ANALYTICS_ENDPOINTS = {
};
export const VALID_ANALYTICS_FILTERS = [
+ "domain",
+ "key",
+ "interval",
+ "start",
+ "end",
"country",
"city",
- "url",
- "alias",
"device",
"browser",
"os",
"referer",
+ "url",
"tagId",
"qr",
"root",
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index e3010118a5..815f2f6ea0 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -4,7 +4,7 @@ import {
intervals,
} from "@/lib/analytics/constants";
import z from "@/lib/zod";
-import { COUNTRY_CODES } from "@dub/utils";
+import { COUNTRY_CODES, capitalize } from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { parseDateSchema } from "./utils";
@@ -96,12 +96,18 @@ export const analyticsQuerySchema = z.object({
device: z
.string()
.optional()
+ .transform((v) => capitalize(v))
.describe("The device to retrieve analytics for."),
browser: z
.string()
.optional()
+ .transform((v) => capitalize(v))
.describe("The browser to retrieve analytics for."),
- os: z.string().optional().describe("The OS to retrieve analytics for."),
+ os: z
+ .string()
+ .optional()
+ .transform((v) => capitalize(v))
+ .describe("The OS to retrieve analytics for."),
referer: z
.string()
.optional()
diff --git a/apps/web/package.json b/apps/web/package.json
index dab7c30735..f52b4071dd 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -12,6 +12,7 @@
"generate-openapi": "tsx ./scripts/generate-openapi.ts"
},
"dependencies": {
+ "@ai-sdk/anthropic": "^0.0.17",
"@anthropic-ai/sdk": "^0.20.4",
"@boxyhq/saml-jackson": "1.23.9",
"@chronark/zod-bird": "^0.3.9",
@@ -49,7 +50,7 @@
"@visx/shape": "^2.12.2",
"@visx/text": "^3.3.0",
"@visx/tooltip": "^2.16.0",
- "ai": "^3.0.22",
+ "ai": "^3.1.22",
"aws4fetch": "^1.0.18",
"bottleneck": "^2.19.5",
"cmdk": "^0.2.0",
diff --git a/apps/web/ui/analytics/actions.ts b/apps/web/ui/analytics/actions.ts
new file mode 100644
index 0000000000..ae86724879
--- /dev/null
+++ b/apps/web/ui/analytics/actions.ts
@@ -0,0 +1,34 @@
+"use server";
+
+import { VALID_ANALYTICS_FILTERS } from "@/lib/analytics/constants";
+import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
+import { anthropic } from "@ai-sdk/anthropic";
+import { streamObject } from "ai";
+import { createStreamableValue } from "ai/rsc";
+
+export async function generateFilters(prompt: string) {
+ const stream = createStreamableValue();
+
+ (async () => {
+ const { partialObjectStream } = await streamObject({
+ model: anthropic("claude-3-sonnet-20240229"),
+ // @ts-expect-error
+ schema: analyticsQuerySchema.pick({
+ ...(VALID_ANALYTICS_FILTERS.reduce((acc, filter) => {
+ acc[filter] = true;
+ return acc;
+ }, {}) as any),
+ }),
+ prompt,
+ temperature: 0.4,
+ });
+
+ for await (const partialObject of partialObjectStream) {
+ stream.update(partialObject);
+ }
+
+ stream.done();
+ })();
+
+ return { object: stream.value };
+}
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index ae921a0963..6300cc682c 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -155,14 +155,12 @@ export default function Analytics({
{},
);
return new URLSearchParams({
+ ...availableFilterParams,
...(workspaceId && { workspaceId }),
- ...(domain && { domain }),
- ...(key && { key }),
...(start &&
end && { start: start.toISOString(), end: end.toISOString() }),
...(interval && { interval }),
...(tagId && { tagId }),
- ...availableFilterParams,
event: selectedTab,
}).toString();
}, [workspaceId, domain, key, searchParams, start, end, tagId, selectedTab]);
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index c7519ee0af..806eafd561 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -24,6 +24,7 @@ import {
FlagWavy,
Globe,
Hyperlink,
+ Magic,
MobilePhone,
OfficeBuilding,
QRCode,
@@ -41,10 +42,12 @@ import {
linkConstructor,
nFormatter,
} from "@dub/utils";
+import { readStreamableValue } from "ai/rsc";
import { useCallback, useContext, useMemo, useState } from "react";
import { AnalyticsContext } from ".";
import LinkLogo from "../links/link-logo";
import { COLORS_LIST } from "../links/tag-badge";
+import { generateFilters } from "./actions";
import DeviceIcon from "./device-icon";
import ExportButton from "./export-button";
import SharePopover from "./share-popover";
@@ -109,11 +112,30 @@ export default function Toggle() {
enabled: isEnabled("os"),
});
+ const [streaming, setStreaming] = useState<boolean>(false);
+
const filters = useMemo(
() => [
...(isPublicStatsPage
? []
: [
+ {
+ key: "ai",
+ icon: Magic,
+ label: "Ask AI",
+ options: [
+ {
+ value: "QR code scans in the last 30 days, US only",
+ label: "QR code scans in the last 30 days, US only",
+ icon: <QRCode className="h-4 w-4" />,
+ },
+ {
+ value: "Canadian Desktop users in the last 90 days",
+ label: "Canadian Desktop users in the last 90 days",
+ icon: <Window className="h-4 w-4" />,
+ },
+ ],
+ },
{
key: "domain",
icon: Globe,
@@ -362,19 +384,36 @@ export default function Toggle() {
className="w-full"
filters={filters}
activeFilters={activeFilters}
- onSelect={(key, value) =>
- queryParams({
- set:
- key === "link"
- ? {
- domain: new URL(value).hostname,
- key: new URL(value).pathname.slice(1) || "_root",
- }
- : {
- [key]: value,
+ onSelect={async (key, value) => {
+ if (key === "ai") {
+ setStreaming(true);
+ const { object } = await generateFilters(value);
+ for await (const partialObject of readStreamableValue(
+ object,
+ )) {
+ if (partialObject) {
+ queryParams({
+ set: {
+ ...partialObject,
},
- })
- }
+ });
+ }
+ }
+ setStreaming(false);
+ } else {
+ queryParams({
+ set:
+ key === "link"
+ ? {
+ domain: new URL(value).hostname,
+ key: new URL(value).pathname.slice(1) || "_root",
+ }
+ : {
+ [key]: value,
+ },
+ });
+ }
+ }}
onRemove={(key) =>
queryParams({
del: key === "link" ? ["domain", "key"] : key,
@@ -385,6 +424,7 @@ export default function Toggle() {
rf.includes(key) ? rf : [...rf, key],
)
}
+ askAI
/>
<div
className={cn("flex w-full items-center gap-2", {
@@ -470,7 +510,15 @@ export default function Toggle() {
<div className="mx-auto w-full max-w-screen-xl px-2.5 lg:px-20">
<Filter.List
filters={filters}
- activeFilters={activeFilters}
+ activeFilters={[
+ ...activeFilters,
+ ...(streaming && !activeFilters.length
+ ? Array.from({ length: 2 }, (_, i) => i).map((i) => ({
+ key: "loader",
+ value: i,
+ }))
+ : []),
+ ]}
onRemove={(key) =>
queryParams({
del: key === "link" ? ["domain", "key"] : key,
@@ -478,14 +526,14 @@ export default function Toggle() {
}
onRemoveAll={() =>
queryParams({
- del: ["domain", "key", ...VALID_ANALYTICS_FILTERS],
+ del: VALID_ANALYTICS_FILTERS,
})
}
/>
<div
className={cn(
"transition-[height] duration-[300ms]",
- activeFilters.length ? "h-6" : "h-0",
+ streaming || activeFilters.length ? "h-6" : "h-0",
)}
/>
</div>
diff --git a/packages/ui/src/filter/filter-list.tsx b/packages/ui/src/filter/filter-list.tsx
index 9b0495415b..441bd4e8a4 100644
--- a/packages/ui/src/filter/filter-list.tsx
+++ b/packages/ui/src/filter/filter-list.tsx
@@ -33,6 +33,17 @@ export function FilterList({
<div className="flex grow flex-wrap gap-x-4 gap-y-2">
<AnimatePresence>
{activeFilters?.map(({ key, value }) => {
+ if (key === "loader") {
+ return (
+ <motion.div
+ key={`loader-${value}`}
+ initial={{ opacity: 0, y: 4 }}
+ animate={{ opacity: 1, y: 0 }}
+ className="h-9 w-48 animate-pulse rounded-md border border-gray-200 bg-white"
+ />
+ );
+ }
+
const filter = filters.find((f) => f.key === key);
if (!filter) {
throw new Error(
@@ -40,7 +51,9 @@ export function FilterList({
);
}
- const option = filter.options?.find((o) => o.value === value);
+ const option = filter.options?.find(
+ (o) => o.value.toLowerCase() === value.toLowerCase(),
+ );
return (
<motion.div
diff --git a/packages/ui/src/filter/filter-select.tsx b/packages/ui/src/filter/filter-select.tsx
index 8227137c43..50ed406f6a 100644
--- a/packages/ui/src/filter/filter-select.tsx
+++ b/packages/ui/src/filter/filter-select.tsx
@@ -1,8 +1,7 @@
import { cn, truncate } from "@dub/utils";
-import { Command } from "cmdk";
+import { Command, useCommandState } from "cmdk";
import { Check, ChevronDown, ListFilter } from "lucide-react";
import {
- CSSProperties,
PropsWithChildren,
ReactNode,
forwardRef,
@@ -15,7 +14,7 @@ import {
} from "react";
import { AnimatedSizeContainer } from "../animated-size-container";
import { useMediaQuery, useResizeObserver } from "../hooks";
-import { LoadingSpinner } from "../icons";
+import { LoadingSpinner, Magic } from "../icons";
import { Popover } from "../popover";
import { Filter, FilterOption } from "./types";
@@ -28,6 +27,7 @@ type FilterSelectProps = {
key: Filter["key"];
value: FilterOption["value"];
}[];
+ askAI?: boolean;
children?: ReactNode;
className?: string;
};
@@ -38,6 +38,7 @@ export function FilterSelect({
onRemove,
onOpenFilter,
activeFilters,
+ askAI,
children,
className,
}: FilterSelectProps) {
@@ -116,9 +117,7 @@ export function FilterSelect({
style={{ transform: "translateZ(0)" }} // Fixes overflow on some browsers
>
<Command loop>
- <Command.Input
- size={1}
- className="w-full rounded-t-lg border-0 border-b border-gray-200 px-4 py-3 text-sm ring-0 placeholder:text-gray-400 focus:border-gray-200 focus:ring-0"
+ <CommandInput
placeholder={`${selectedFilter?.label || "Filter"}...`}
value={search}
onValueChange={setSearch}
@@ -129,6 +128,11 @@ export function FilterSelect({
selectedFilterKey ? reset() : setIsOpen(false);
}
}}
+ onEnterKeyDownEmpty={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ selectOption(search);
+ }}
/>
<FilterScroll key={selectedFilterKey} ref={mainListContainer}>
{!selectedFilter ? (
@@ -140,7 +144,7 @@ export function FilterSelect({
onSelect={() => openFilter(filter.key)}
/>
))}
- <NoMatches />
+ <CommandEmpty search={search} askAI={askAI} />
</Command.List>
) : (
<Command.List className="flex w-full min-w-[100px] flex-col gap-1 p-2">
@@ -167,7 +171,7 @@ export function FilterSelect({
/>
);
})}
- <NoMatches />
+ <CommandEmpty search={search} askAI={askAI} />
</>
) : (
<Command.Loading>
@@ -215,6 +219,28 @@ export function FilterSelect({
);
}
+const CommandInput = (
+ props: React.ComponentProps<typeof Command.Input> & {
+ onEnterKeyDownEmpty?: (e: React.KeyboardEvent<HTMLInputElement>) => void;
+ },
+) => {
+ const isEmpty = useCommandState((state) => state.filtered.count === 0);
+ return (
+ <Command.Input
+ {...props}
+ size={1}
+ className="w-full rounded-t-lg border-0 border-b border-gray-200 px-4 py-3 text-sm ring-0 placeholder:text-gray-400 focus:border-gray-200 focus:ring-0"
+ onKeyDown={(e) => {
+ props.onKeyDown?.(e);
+
+ if (e.key === "Enter" && isEmpty) {
+ props.onEnterKeyDownEmpty?.(e);
+ }
+ }}
+ />
+ );
+};
+
const FilterScroll = forwardRef(
({ children }: PropsWithChildren, forwardedRef) => {
const ref = useRef<HTMLDivElement>(null);
@@ -277,7 +303,7 @@ function FilterButton({
<span className="shrink-0 text-gray-600">
{isReactNode(Icon) ? Icon : <Icon className="h-4 w-4" />}
</span>
- {truncate(label, 30)}
+ {truncate(label, 48)}
<div className="ml-1 flex shrink-0 grow justify-end text-gray-500">
{right}
</div>
@@ -285,14 +311,30 @@ function FilterButton({
);
}
-const NoMatches = ({ style }: { style?: CSSProperties }) => (
- <Command.Empty
- className="p-2 text-center text-sm text-gray-400"
- style={style}
- >
- No matches
- </Command.Empty>
-);
+const CommandEmpty = ({
+ search,
+ askAI,
+}: {
+ search: string;
+ askAI?: boolean;
+}) => {
+ if (askAI) {
+ return (
+ <Command.Empty className="flex min-w-[180px] items-center space-x-2 p-2">
+ <Magic className="h-4 w-4" />
+ <p className="text-center text-sm text-gray-600">
+ Ask AI <span className="text-black">"{search}"</span>
+ </p>
+ </Command.Empty>
+ );
+ } else {
+ return (
+ <Command.Empty className="p-2 text-center text-sm text-gray-400">
+ No matches
+ </Command.Empty>
+ );
+ }
+};
const isReactNode = (element: any): element is ReactNode =>
isValidElement(element);
diff --git a/packages/utils/src/functions/capitalize.ts b/packages/utils/src/functions/capitalize.ts
index d38b9985ec..3130726378 100644
--- a/packages/utils/src/functions/capitalize.ts
+++ b/packages/utils/src/functions/capitalize.ts
@@ -1,4 +1,8 @@
+// capitalie first character of each word in a string
export function capitalize(str?: string | null) {
if (!str || typeof str !== "string") return str;
- return str.charAt(0).toUpperCase() + str.slice(1);
+ return str
+ .split(" ")
+ .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(" ");
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 5d70770191..31693ebcc2 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -34,6 +34,9 @@ importers:
apps/web:
dependencies:
+ '@ai-sdk/anthropic':
+ specifier: ^0.0.17
+ version: 0.0.17([email protected])
'@anthropic-ai/sdk':
specifier: ^0.20.4
version: 0.20.4
@@ -146,8 +149,8 @@ importers:
specifier: ^2.16.0
ai:
- specifier: ^3.0.22
+ specifier: ^3.1.22
aws4fetch:
specifier: ^1.0.18
version: 1.0.18
@@ -588,8 +591,19 @@ packages:
resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-A6gFv6EHimayd2c2ayWMpKwADgsRrJg4DYYFnvJ71TXaWuSom7vUoALIobcaggmZ76xuzi17cXPFYg2vVu04WA==}
+ resolution: {integrity: sha512-GH96m+mdz7XA1z4153g+SAGcib6CFdtjbwMXfWWE0q4iIAObeW6eC2N8VuucQdQNSbJ3h62KqdjWMho6k6L8Aw==}
+ engines: {node: '>=18'}
+ peerDependencies:
+ zod: ^3.0.0
+ dependencies:
+ '@ai-sdk/provider': 0.0.8
+ '@ai-sdk/provider-utils': 0.0.11([email protected])
+ zod: 3.22.4
+ dev: false
+
+ resolution: {integrity: sha512-JRDrqL2FGDmLh+a4R5qbS8UrWN9Lt7DpDIY1x6owgXjXkz3Umm1czs1X32VlL0M1dpoSxu4hGBFtXd56+kDzXA==}
engines: {node: '>=18'}
peerDependencies:
zod: ^3.0.0
@@ -597,15 +611,15 @@ packages:
zod:
optional: true
dependencies:
- '@ai-sdk/provider': 0.0.0
+ '@ai-sdk/provider': 0.0.8
eventsource-parser: 1.1.2
nanoid: 3.3.6
secure-json-parse: 2.7.0
zod: 3.22.4
dev: false
- /@ai-sdk/[email protected]:
- resolution: {integrity: sha512-Gbl9Ei8NPtM85gB/o8cY7s7CLGxK/U6QVheVaI3viFn7o6IpTfy1Ja389e2FXVMNJ4WHK2qYWSp5fAFDuKulTA==}
+ /@ai-sdk/[email protected]:
+ resolution: {integrity: sha512-+gcMvyPUDfDXV9caN3CG5Le0M5K4CjqTdMV1ODg/AosApQiJW9ByN5imJPdI043zVdt+HS9WG+s0j4am7ca4bg==}
engines: {node: '>=18'}
dependencies:
json-schema: 0.4.0
@@ -8964,16 +8978,19 @@ packages:
humanize-ms: 1.2.1
dev: false
- resolution: {integrity: sha512-VkObPBejjUA9mSJBurVtMpwdqDqzrzjKvsrrj1SsKsUOH/pbmzL6U2ym61Sz8pQXuPYJqcm3SpYOfqrIMRUH0Q==}
+ resolution: {integrity: sha512-Vgy490Q6p6pZ39VrRzL9ovr2N1YPsR+KvWNs+n73VAQoGBZtU/vwiiWrFU9LHXGhB9X+EBfQD0vixnTDS2dJWA==}
engines: {node: '>=18'}
peerDependencies:
- react: ^18.2.0
+ openai: ^4.42.0
+ react: ^18 || ^19
solid-js: ^1.7.7
svelte: ^3.0.0 || ^4.0.0
vue: ^3.3.4
zod: ^3.0.0
peerDependenciesMeta:
+ openai:
+ optional: true
react:
optional: true
solid-js:
@@ -8985,8 +9002,8 @@ packages:
zod:
optional: true
dependencies:
- '@ai-sdk/provider': 0.0.0
- '@ai-sdk/provider-utils': 0.0.0([email protected])
+ '@ai-sdk/provider': 0.0.8
+ '@ai-sdk/provider-utils': 0.0.11([email protected])
eventsource-parser: 1.1.2
json-schema: 0.4.0
jsondiffpatch: 0.6.0