The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
AI Features
Steven Teyf15816835c2a
diff --git a/apps/web/.env.example b/apps/web/.env.exampleindex 2d1533e348..8ff6a4c4b9 100644--- a/apps/web/.env.example+++ b/apps/web/.env.example@@ -95,6 +95,9 @@ DUB_SLACK_HOOK_LINKS=# Get your ngrok URL here: https://ngrok.com/NGROK_URL=+# For AI features+ANTHROPIC_API_KEY=+############################################ DUB.CO INTERNAL USE ONLY ############################################@@ -103,7 +106,4 @@ NGROK_URL=NEXT_PUBLIC_IS_DUB=# For cron jobs-CRON_SECRET=--# For AI services-OPENAI_API_KEY=\ No newline at end of file+CRON_SECRET=\ No newline at end of filediff --git a/apps/web/app/api/ai/completion-internal/route.ts b/apps/web/app/api/ai/completion-internal/route.tsnew file mode 100644index 0000000000..d15477621e--- /dev/null+++ b/apps/web/app/api/ai/completion-internal/route.ts@@ -0,0 +1,57 @@+import { anthropic } from "@/lib/anthropic";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { ratelimit } from "@/lib/upstash";+import { ipAddress } from "@vercel/edge";+import { AnthropicStream, StreamingTextResponse } from "ai";+import { getToken } from "next-auth/jwt";+import { NextRequest } from "next/server";++export const runtime = "edge";++export async function POST(req: NextRequest) {+ try {+ const session = await getToken({+ req,+ secret: process.env.NEXTAUTH_SECRET,+ });+ if (!session?.email) {+ throw new DubApiError({+ code: "unauthorized",+ message: "You must be logged in to access this resource",+ });+ }++ const ip = ipAddress(req);+ const { success } = await ratelimit(5, "1 m").limit(`ai-completion:${ip}`);+ if (!success) {+ throw new DubApiError({+ code: "rate_limit_exceeded",+ message: "Don't DDoS me pls π₯Ί",+ });+ }++ // Extract the `prompt` from the body of the request+ const { prompt } = await req.json();++ // Ask Claude for a streaming chat completion given the prompt+ const response = await anthropic.messages.create({+ messages: [+ {+ role: "user",+ content: prompt,+ },+ ],+ model: "claude-3-sonnet-20240229",+ stream: true,+ max_tokens: 300,+ });++ // Convert the response into a friendly text-stream+ const stream = AnthropicStream(response);++ // Respond with the stream+ return new StreamingTextResponse(stream);+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }+}diff --git a/apps/web/app/api/ai/completion/route.ts b/apps/web/app/api/ai/completion/route.tsindex d15477621e..71445293a7 100644--- a/apps/web/app/api/ai/completion/route.ts+++ b/apps/web/app/api/ai/completion/route.ts@@ -1,39 +1,35 @@import { anthropic } from "@/lib/anthropic";-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { ratelimit } from "@/lib/upstash";-import { ipAddress } from "@vercel/edge";+import {+ getWorkspaceViaEdge,+ incrementWorkspaceAIUsage,+} from "@/lib/planetscale";+import { getSearchParams } from "@dub/utils";import { AnthropicStream, StreamingTextResponse } from "ai";-import { getToken } from "next-auth/jwt";+import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";import { NextRequest } from "next/server";export const runtime = "edge";+// POST /api/ai/link β Generate a shortlink key from a prompt using AIexport async function POST(req: NextRequest) {+ const searchParams = getSearchParams(req.url);+ const { workspaceId } = searchParams;+ const workspace = await getWorkspaceViaEdge(workspaceId);++ if (!workspace) {+ return new Response("Workspace not found", { status: 404 });+ }++ if (workspace.aiUsage > workspace.aiLimit) {+ return new Response(+ "Exceeded AI usage limit. Upgrade to a higher plan to get more AI credits.",+ { status: 429 },+ );+ }+try {- const session = await getToken({- req,- secret: process.env.NEXTAUTH_SECRET,- });- if (!session?.email) {- throw new DubApiError({- code: "unauthorized",- message: "You must be logged in to access this resource",- });- }-- const ip = ipAddress(req);- const { success } = await ratelimit(5, "1 m").limit(`ai-completion:${ip}`);- if (!success) {- throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls π₯Ί",- });- }-- // Extract the `prompt` from the body of the requestconst { prompt } = await req.json();- // Ask Claude for a streaming chat completion given the promptconst response = await anthropic.messages.create({messages: [{@@ -46,12 +42,12 @@ export async function POST(req: NextRequest) {max_tokens: 300,});- // Convert the response into a friendly text-streamconst stream = AnthropicStream(response);- // Respond with the stream+ waitUntil(async () => await incrementWorkspaceAIUsage(workspaceId));+return new StreamingTextResponse(stream);} catch (error) {- return handleAndReturnErrorResponse(error);+ return new Response(error.message, { status: 500 });}}diff --git a/apps/web/app/api/ai/link/route.ts b/apps/web/app/api/ai/link/route.tsdeleted file mode 100644index 250224308a..0000000000--- a/apps/web/app/api/ai/link/route.ts+++ /dev/null@@ -1,84 +0,0 @@-import {- checkIfKeyExists,- getWorkspaceViaEdge,- incrementWorkspaceAIUsage,-} from "@/lib/planetscale";-import { getSearchParams } from "@dub/utils";-import { NextRequest } from "next/server";-import OpenAI from "openai";-import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";--const openai = new OpenAI({- apiKey: process.env.OPENAI_API_KEY,-});--export const runtime = "edge";--// POST /api/ai/link β Generate a shortlink key from a prompt using AI-export async function POST(req: NextRequest) {- const searchParams = getSearchParams(req.url);- const { workspaceId } = searchParams;- const workspace = await getWorkspaceViaEdge(workspaceId);-- if (!workspace) {- return new Response("Workspace not found", { status: 404 });- }-- if (workspace.aiUsage > workspace.aiLimit) {- return new Response(- "Exceeded AI usage limit. Upgrade to a higher plan to get more AI credits.",- { status: 429 },- );- }-- try {- const { prompt } = await req.json();-- const response = await generateKey(prompt, workspaceId);-- waitUntil(async () => await incrementWorkspaceAIUsage(workspaceId));-- return new Response(response.choices[0].message.content, {- headers: {- "Content-Type": "text/plain",- },- });- } catch (error) {- return new Response(error.message, { status: 500 });- }-}--const generateKey = async (prompt: string, workspaceId: string) => {- const response = await openai.chat.completions.create({- model: "gpt-4",- stream: false,- messages: [- {- role: "system",- content:- "You are a helpful assistant and only answer in short link keys, e.g. you receive a question like 'What is the shortlink for meta-title Notion and meta-description The all in one workspace?' and you respond with e.g. 'notion-workspace'. Try to combine them in a shortlink that makes sense and is easy to share on social media. Don't use any special characters or spaces and only response with keys less than 20 characters long. If it makes sense, try to use acronyms/initials, e.g. techcrunch -> tc, github -> gh.",- },- {- role: "user",- content: prompt,- },- ],- max_tokens: 200,- temperature: 0.5,- top_p: 1,- frequency_penalty: 2,- presence_penalty: 2,- });-- if (!response.choices[0].message.content)- throw new Error("Failed to generate key");-- // in the case of a duplicate key, generate a new one- const exists = await checkIfKeyExists(- workspaceId,- response.choices[0].message.content,- );-- if (exists) return generateKey(prompt, workspaceId);- else return response;-};diff --git a/apps/web/app/api/ai/metatags/route.ts b/apps/web/app/api/ai/metatags/route.tsdeleted file mode 100644index c2d6ad570b..0000000000--- a/apps/web/app/api/ai/metatags/route.ts+++ /dev/null@@ -1,66 +0,0 @@-import {- getWorkspaceViaEdge,- incrementWorkspaceAIUsage,-} from "@/lib/planetscale";-import { getSearchParams } from "@dub/utils";-import { OpenAIStream, StreamingTextResponse } from "ai";-import { NextRequest } from "next/server";-import OpenAI from "openai";-import { internal_runWithWaitUntil as waitUntil } from "next/dist/server/web/internal-edge-wait-until";--const openai = new OpenAI({- apiKey: process.env.OPENAI_API_KEY,-});--export const runtime = "edge";--// POST /api/ai/metatags β Generate metatags for a URL using AI-export async function POST(req: NextRequest) {- const searchParams = getSearchParams(req.url);- const { workspaceId } = searchParams;- const workspace = await getWorkspaceViaEdge(workspaceId);-- if (!workspace) {- return new Response("Workspace not found", { status: 404 });- }-- if (workspace.aiUsage > workspace.aiLimit) {- return new Response(- "Exceeded AI usage limit. Upgrade to a higher plan to get more AI credits.",- { status: 429 },- );- }-- try {- const { prompt } = await req.json();-- const response = await openai.chat.completions.create({- model: "gpt-4",- stream: true,- messages: [- {- role: "system",- content:- "You are an SEO expert that specializes in creating SEO-optimized meta title & description tags. You receive a question like 'What is a suitable, new meta-title for Dub?' and you respond with a plain text answer, no quotes, no special characters, nothing other than the tag that you're generating. Try to keep it short and sweet.",- },- {- role: "user",- content: prompt,- },- ],- max_tokens: 200,- temperature: 0.5,- top_p: 1,- frequency_penalty: 2,- presence_penalty: 2,- });-- const stream = OpenAIStream(response);-- waitUntil(async () => await incrementWorkspaceAIUsage(workspaceId));-- return new StreamingTextResponse(stream);- } catch (error) {- return new Response(error.message, { status: 500 });- }-}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 33e130624d..55c741e413 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -66,7 +66,6 @@"next-auth": "^4.24.4","node-html-parser": "^6.1.4","nodemailer": "^6.9.3",- "openai": "^4.29.2","openapi-types": "^12.1.3","openapi3-ts": "^4.2.1","postmark": "^4.0.2",@@ -118,9 +117,9 @@"tsx": "^3.14.0","turbo": "^1.10.14","typescript": "^5.1.6",+ "vite": "5.2.9","vite-tsconfig-paths": "^4.3.2",- "vitest": "1.5.0",- "vite": "5.2.9"+ "vitest": "1.5.0"},"browser": {"crypto": falsediff --git a/apps/web/ui/layout/help/contact-form.tsx b/apps/web/ui/layout/help/contact-form.tsxindex e1461bdaa4..23e9381145 100644--- a/apps/web/ui/layout/help/contact-form.tsx+++ b/apps/web/ui/layout/help/contact-form.tsx@@ -83,12 +83,8 @@ export function ContactForm({const { handleKeyDown } = useEnterSubmit(formRef);- const {- completion,- isLoading: generatingAIKey,- complete,- } = useCompletion({- api: `/api/ai/completion`,+ const { completion, complete } = useCompletion({+ api: `/api/ai/completion-internal`,onError: (error) => {toast.error(error.message);},diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsxindex 4683001a2a..f6faba8f6c 100644--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx@@ -143,6 +143,18 @@ function AddEditLinkModal({}}, [showAddEditLinkModal, url]);+ const runKeyChecks = async (value: string) => {+ const res = await fetch(+ `/api/links/verify?domain=${domain}&key=${value}&workspaceId=${workspaceId}`,+ );+ const { error } = await res.json();+ if (error) {+ setKeyError(error.message);+ } else {+ setKeyError(null);+ }+ };+const [generatedKeys, setGeneratedKeys] = useState<string[]>(props ? [props.key] : [],);@@ -152,13 +164,14 @@ function AddEditLinkModal({isLoading: generatingAIKey,complete,} = useCompletion({- api: `/api/ai/link?workspaceId=${workspaceId}`,+ api: `/api/ai/completion?workspaceId=${workspaceId}`,onError: (error) => {toast.error(error.message);},onFinish: (_, completion) => {setGeneratedKeys((prev) => [...prev, completion]);revalidateAiUsage();+ runKeyChecks(completion);},});@@ -167,7 +180,7 @@ function AddEditLinkModal({const generateAIKey = useCallback(async () => {setKeyError(null);complete(- `Generate a short link for the URL "${data.url}", meta-title "${data.title}" and meta-description "${data.description}"? Please respond with a unique key you haven't used before: ${generatedKeys.join(", ")}`,+ `You are a helpful assistant and only answer in short link keys, e.g. you receive a question like 'What is the shortlink for meta-title Notion and meta-description The all in one workspace?' and you respond with e.g. 'notion-workspace'. Try to combine them in a shortlink that makes sense and is easy to share on social media. Don't use any special characters or spaces and only response with keys less than 20 characters long. If it makes sense, try to use acronyms/initials, e.g. techcrunch -> tc, github -> gh. Generate a short link for the URL "${data.url}", meta-title "${data.title}" and meta-description "${data.description}"? Please respond with a unique key you haven't used before: ${generatedKeys.join(", ")}`,);}, [data.url, data.title, data.description, generatedKeys]);@@ -176,18 +189,6 @@ function AddEditLinkModal({setData((prev) => ({ ...prev, key: completion }));}}, [completion]);- const runKeyChecks = async (e: React.FocusEvent<HTMLInputElement>) => {- if (!e.target.value) return;- const res = await fetch(- `/api/links/verify?domain=${domain}&key=${e.target.value}&workspaceId=${workspaceId}`,- );- const { error } = await res.json();- if (error) {- setKeyError(error.message);- } else {- setKeyError(null);- }- };const [generatingMetatags, setGeneratingMetatags] = useState(props ? true : false,@@ -323,13 +324,6 @@ function AddEditLinkModal({const { queryParams } = useRouterStuff();const shortLink = useMemo(() => {- return linkConstructor({- key: data.key,- domain: data.domain,- });- }, [data.key, data.domain]);-- const shortLinkPretty = useMemo(() => {return linkConstructor({key: data.key,domain: data.domain,@@ -379,7 +373,7 @@ function AddEditLinkModal({<div className="sticky top-0 z-20 flex h-14 items-center justify-center gap-4 space-y-3 border-b border-gray-200 bg-white px-4 transition-all sm:h-24 md:px-16"><LinkLogo apexDomain={getApexDomain(url)} /><h3 className="!mt-0 max-w-sm truncate text-lg font-medium">- {props ? `Edit ${shortLinkPretty}` : "Create a new link"}+ {props ? `Edit ${shortLink}` : "Create a new link"}</h3></div>@@ -657,7 +651,9 @@ function AddEditLinkModal({"Only letters, numbers, '-', '/', and emojis are allowed.",);}}- onBlur={runKeyChecks}+ onBlur={(e) =>+ e.target.value && runKeyChecks(e.target.value)+ }disabled={props && lockKey}autoComplete="off"className={cn(@@ -705,11 +701,11 @@ function AddEditLinkModal({})}</p></div>- {shortLinkPretty.length > 25 && (+ {shortLink.length > 25 && (<div className="mt-1 flex items-center space-x-2"><Twitter className="h-4 w-4" /><p className="cursor-pointer text-sm text-[#34a2f1] hover:underline">- {truncate(shortLinkPretty, 25)}+ {truncate(shortLink, 25)}</p></div>)}diff --git a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx b/apps/web/ui/modals/add-edit-link-modal/og-section.tsxindex 3064179cf9..ea7c1111ac 100644--- a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx@@ -46,7 +46,7 @@ export default function OGSection({isLoading: generatingTitle,complete: completeTitle,} = useCompletion({- api: `/api/ai/metatags?workspaceId=${workspaceId}`,+ api: `/api/ai/completion?workspaceId=${workspaceId}`,id: "metatags-title-ai",onError: (error) => {toast.error(error.message);@@ -58,7 +58,7 @@ export default function OGSection({const generateTitle = async () => {completeTitle(- `Generate an SEO-optimized meta title tag (title only, max 120 characters) β given the current version: ${data.title}`,+ `You are an SEO expert that specializes in creating SEO-optimized meta title & description tags. You receive a question like 'What is a suitable, new meta-title for Dub?' and you respond with a plain text answer, no quotes, no special characters, nothing other than the tag that you're generating. Try to keep it short and sweet. Generate an SEO-optimized meta title tag (title only, max 120 characters) β given the current version: ${data.title}`,);};@@ -73,7 +73,7 @@ export default function OGSection({isLoading: generatingDescription,complete: completeDescription,} = useCompletion({- api: `/api/ai/metatags?workspaceId=${workspaceId}`,+ api: `/api/ai/completion?workspaceId=${workspaceId}`,id: "metatags-description-ai",onError: (error) => {toast.error(error.message);@@ -85,7 +85,7 @@ export default function OGSection({const generateDescription = async () => {completeDescription(- `Generate an SEO-optimized meta description tag (description only, max 240 characters) β given the current version: ${data.description}`,+ `You are an SEO expert that specializes in creating SEO-optimized meta title & description tags. You receive a question like 'What is a suitable, new meta-title for Dub?' and you respond with a plain text answer, no quotes, no special characters, nothing other than the tag that you're generating. Try to keep it short and sweet. Generate an SEO-optimized meta description tag (description only, max 240 characters) β given the current version: ${data.description}`,);};diff --git a/apps/web/ui/modals/add-edit-link-modal/tooltip-button.tsx b/apps/web/ui/modals/add-edit-link-modal/tooltip-button.tsxindex 31b114e352..c220317588 100644--- a/apps/web/ui/modals/add-edit-link-modal/tooltip-button.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/tooltip-button.tsx@@ -91,6 +91,7 @@ export default function TooltipButton() {><button{...props}+ type="button"disabled={props.disabled || (ai && ai?.data.usage >= ai?.data.limit)}className={cn("flex h-6 w-6 items-center justify-center rounded-md text-gray-500 transition-colors duration-75 hover:bg-gray-100 active:bg-gray-200 disabled:cursor-not-allowed",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex f911848bff..4c3e1c87ab 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -199,9 +199,6 @@ importers:nodemailer:specifier: ^6.9.3version: 6.9.3- openai:- specifier: ^4.29.2- version: 4.38.1openapi-types:specifier: ^12.1.3version: 12.1.3@@ -13339,22 +13336,6 @@ packages:is-wsl: 2.2.0dev: false- resolution: {integrity: sha512-nmSKE9O2piuoh9+AgDqwGHojIFSxToQ2jJqwaxjbzz2ebdD5LYY9s+bMe25b18t4QEgvtgW70JfK8BU3xf5dRw==}- hasBin: true- dependencies:- '@types/node': 18.19.31- '@types/node-fetch': 2.6.11- abort-controller: 3.0.0- agentkeepalive: 4.5.0- form-data-encoder: 1.7.2- formdata-node: 4.4.1- node-fetch: 2.7.0([email protected])- web-streams-polyfill: 3.3.3- transitivePeerDependencies:- - encoding- dev: false-resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==}dev: false