The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
feat: enable AI to generate a short link
flooorianflo2ced31e2d4dc
diff --git a/apps/web/app/api/ai/shortlink/route.ts b/apps/web/app/api/ai/shortlink/route.tsindex 3f40f45df0..ffdbf6ce2e 100644--- a/apps/web/app/api/ai/shortlink/route.ts+++ b/apps/web/app/api/ai/shortlink/route.ts@@ -1,12 +1,50 @@+import { getWorkspaceViaEdge } from "@/lib/planetscale";+import { getSearchParams } from "@dub/utils";+import { OpenAIStream, StreamingTextResponse } from "ai";+import { NextRequest } from "next/server";import OpenAI from "openai";-// Edge friendly OpenAI clientconst openai = new OpenAI({apiKey: process.env.OPENAI_API_KEY,});export const runtime = "edge";-export async function POST(req: Request) {- // TODO: Implement OpenAI API call to generate short link+export async function POST(req: NextRequest) {+ const searchParams = getSearchParams(req.url);+ const { workspaceId } = searchParams;++ const { url, domain } = await req.json();++ const workspace = await getWorkspaceViaEdge(workspaceId);++ // this endpoint is only available for paid plans+ if (!workspace || workspace.plan === "free")+ return new Response("Requires higher plan", { status: 403 });++ // generates a shortlink for the given URL by asking the AI+ try {+ const response = await openai.chat.completions.create({+ model: "gpt-4",+ max_tokens: 100,+ stream: true,+ 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 https://dub.dev/docs on dub.dev?' and you respond with 'docs'. If there are paths in the URL, you should ignore them and try to combine them in a shortlink that makes sense and is easy to share on social media.",+ },+ {+ role: "user",+ content: `What is the shortlink for ${url} on ${domain}?`,+ },+ ],+ });++ const stream = OpenAIStream(response);++ return new StreamingTextResponse(stream);+ } catch (error) {+ return new Response(error.message, { status: 500 });+ }}diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsxindex e3f3d15bc1..b426a3e4e3 100644--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx@@ -120,18 +120,30 @@ function AddEditLinkModal({const generateAIKey = useCallback(async () => {setKeyError(null);setGeneratingAIKey(true);+const res = await fetch(`/api/ai/shortlink?workspaceId=${workspaceId}`, {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify({- // TODO: Add data to generate AI key+ url,+ domain,}),+ }).then(async (res) => {+ if (res.status !== 200) {+ const error = await res.text();+ setKeyError(error);+ setGeneratingAIKey(false);+ throw new Error(error);+ }+ return res.text();});+ setData((prev) => ({ ...prev, key: res }));+setGeneratingAIKey(false);- }, [workspaceId]);+ }, [url, domain, slug]);useEffect(() => {// when someone pastes a URL