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.

fix implementation to useCompletion

Steven Teyebede122251a
diff --git a/apps/web/app/api/ai/link/route.ts b/apps/web/app/api/ai/link/route.ts
new file mode 100644
index 0000000000..08181401f9
--- /dev/null
+++ b/apps/web/app/api/ai/link/route.ts
@@ -0,0 +1,54 @@
+import { getWorkspaceViaEdge } from "@/lib/planetscale";
+import { getSearchParams } from "@dub/utils";
+import { OpenAIStream, StreamingTextResponse } from "ai";
+import { NextRequest } from "next/server";
+import OpenAI from "openai";
+
+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);
+
+ // this endpoint is only available for paid plans
+ if (!workspace || workspace.plan === "free") {
+ return new Response("Requires higher plan", { status: 403 });
+ }
+
+ try {
+ const { prompt } = await req.json();
+
+ const response = await openai.chat.completions.create({
+ model: "gpt-4",
+ 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 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,
+ });
+
+ const stream = OpenAIStream(response);
+
+ return new StreamingTextResponse(stream);
+ } catch (error) {
+ return new Response(error.message, { status: 500 });
+ }
+}
diff --git a/apps/web/app/api/ai/chat/route.ts b/apps/web/app/api/ai/metatags/route.ts
similarity index 54%
rename from apps/web/app/api/ai/chat/route.ts
rename to apps/web/app/api/ai/metatags/route.ts
index 3c03cecf3b..0cfa7f491b 100644
--- a/apps/web/app/api/ai/chat/route.ts
+++ b/apps/web/app/api/ai/metatags/route.ts
@@ -10,25 +10,39 @@ const openai = new OpenAI({
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 { messages } = await req.json();
-
const workspace = await getWorkspaceViaEdge(workspaceId);
// this endpoint is only available for paid plans
- if (!workspace || workspace.plan === "free")
+ 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 { prompt } = await req.json();
+
const response = await openai.chat.completions.create({
model: "gpt-4",
- max_tokens: 100,
stream: true,
- messages,
+ 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);
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index fd647c1472..961b0396eb 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -58,7 +58,7 @@ import PasswordSection from "./password-section";
import Preview from "./preview";
import TagsSection from "./tags-section";
import UTMSection from "./utm-section";
-import { useChat } from "ai/react";
+import { useChat, useCompletion } from "ai/react";
function AddEditLinkModal({
showAddEditLinkModal,
@@ -82,27 +82,8 @@ function AddEditLinkModal({
const [keyError, setKeyError] = useState<string | null>(null);
const [urlError, setUrlError] = useState<string | null>(null);
const [generatingRandomKey, setGeneratingRandomKey] = useState(false);
- const [generatingAIKey, setGeneratingAIKey] = useState(false);
const [saving, setSaving] = useState(false);
- const { append } = useChat({
- api: `/api/ai/chat?workspaceId=${workspaceId}`,
- onFinish(message) {
- if (message.role === "assistant") {
- setData((prev) => ({ ...prev, key: message.content }));
- }
- },
- // initial system message
- initialMessages: [
- {
- id: "initial-prop",
- 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 shortnames for companies, e.g. techcrunch -> tc.",
- },
- ],
- });
-
const {
allActiveDomains: domains,
primaryDomain,
@@ -136,18 +117,6 @@ function AddEditLinkModal({
setGeneratingRandomKey(false);
}, [domain, slug]);
- const generateAIKey = async () => {
- setKeyError(null);
- setGeneratingAIKey(true);
-
- await append({
- role: "user",
- content: `What is the shortlink for meta-title ${data.title} and meta-description ${data.description}? Please respond with a unique key you haven't used before.`,
- });
-
- setGeneratingAIKey(false);
- };
-
useEffect(() => {
// when someone pastes a URL
if (showAddEditLinkModal && url.length > 0) {
@@ -169,6 +138,34 @@ function AddEditLinkModal({
}
}, [showAddEditLinkModal, url]);
+ const [generatedKeys, setGeneratedKeys] = useState<string[]>(
+ props ? [props.key] : [],
+ );
+
+ const {
+ completion,
+ isLoading: generatingAIKey,
+ complete,
+ } = useCompletion({
+ api: `/api/ai/link?workspaceId=${workspaceId}`,
+ onFinish: (_, completion) => {
+ setGeneratedKeys((prev) => [...prev, completion]);
+ },
+ });
+
+ 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(", ")}`,
+ );
+ }, [data.url, data.title, data.description, generatedKeys]);
+
+ useEffect(() => {
+ if (completion) {
+ setData((prev) => ({ ...prev, key: completion }));
+ }
+ }, [completion]);
+
const [generatingMetatags, setGeneratingMetatags] = useState(
props ? true : false,
);
@@ -545,9 +542,7 @@ function AddEditLinkModal({
generatingRandomKey ||
!plan ||
plan === "free" ||
- !url ||
- !data.title ||
- !data.description
+ !url
}
type="button"
>
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.tsx
index 05e9a17731..b21dd03bf4 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
@@ -26,7 +26,7 @@ import {
} from "react";
import TextareaAutosize from "react-textarea-autosize";
import UnsplashSearch from "./unsplash-search";
-import { useChat } from "ai/react";
+import { useCompletion } from "ai/react";
export default function OGSection({
props,
@@ -39,48 +39,56 @@ export default function OGSection({
setData: Dispatch<SetStateAction<LinkProps>>;
generatingMetatags: boolean;
}) {
- const { plan, id: workspaceId } = useWorkspace();
+ const { id: workspaceId, plan } = useWorkspace();
const { queryParams } = useRouterStuff();
const { title, description, image, proxy } = data;
- const [resizing, setResizing] = useState(false);
- const [dragActive, setDragActive] = useState(false);
-
- const [loadingMetaData, setLoadingMetaData] = useState({
- title: false,
- description: false,
+ const {
+ completion: completionTitle,
+ isLoading: generatingTitle,
+ complete: completeTitle,
+ } = useCompletion({
+ api: `/api/ai/metatags?workspaceId=${workspaceId}`,
+ id: "metatags-title-ai",
});
- const [metaDataError, setMetaDataError] = useState<
- Record<string, string | null>
- >({ title: null, description: null });
- const [requestedType, setRequestedType] = useState<"title" | "description">();
+ const generateTitle = async () => {
+ completeTitle(
+ `Generate an SEO-optimized meta title tag (title only, max 120 characters) – given the current version: ${data.title}`,
+ );
+ };
- const { append } = useChat({
- api: `/api/ai/chat?workspaceId=${workspaceId}`,
- onFinish(message) {
- if (message.role === "assistant" && requestedType) {
- setData((prev) => ({
- ...prev,
- [requestedType]: message.content.replaceAll('"', ""),
- }));
- }
+ useEffect(() => {
+ if (completionTitle) {
+ setData((prev) => ({ ...prev, title: completionTitle }));
+ }
+ }, [completionTitle]);
- setLoadingMetaData((prev) => ({ ...prev, [requestedType!]: false }));
- setRequestedType(undefined);
- },
- // initial system message
- initialMessages: [
- {
- id: "initial-prop",
- role: "system",
- content:
- "You are a helpful assistant and helps with meta-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. Try to keep it short and sweet. The same goes for meta-descriptions. Don't use any special characters or quotes. For questions regarding meta-title you answer with a max-length of 120 characters and for meta-description with a max-length of 240 characters.",
- },
- ],
+ const {
+ completion: completionDescription,
+ isLoading: generatingDescription,
+ complete: completeDescription,
+ } = useCompletion({
+ api: `/api/ai/metatags?workspaceId=${workspaceId}`,
+ id: "metatags-description-ai",
});
+ const generateDescription = async () => {
+ completeDescription(
+ `Generate an SEO-optimized meta description tag (description only, max 240 characters) – given the current version: ${data.description}`,
+ );
+ };
+
+ useEffect(() => {
+ if (completionDescription) {
+ setData((prev) => ({ ...prev, description: completionDescription }));
+ }
+ }, [completionDescription]);
+
+ const [resizing, setResizing] = useState(false);
+ const [dragActive, setDragActive] = useState(false);
+
const onChangePicture = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files && e.target.files[0];
if (!file) return;
@@ -118,35 +126,6 @@ export default function OGSection({
}, 200);
}
- useEffect(() => {
- if (loadingMetaData.title || loadingMetaData.description || !requestedType)
- return;
-
- if (!data[requestedType]) {
- setMetaDataError((prev) => ({
- ...prev,
- [requestedType]: `Please provide a ${requestedType === "title" ? "title" : "description"} to generate a new ${requestedType} out of.`,
- }));
- return;
- }
-
- const generateMetaData = async () => {
- setLoadingMetaData((prev) => ({ ...prev, [requestedType]: true }));
-
- await append({
- role: "user",
- content:
- requestedType === "title"
- ? `What is a suitable, new meta-title for ${data.title} that has a maximum of 110 characters?`
- : `What is a suitable, new meta-description for ${data.description} that has a maximum of 200 characters?`,
- });
- };
-
- generateMetaData();
-
- return () => setRequestedType(undefined);
- }, [requestedType]);
-
return (
<div className="relative grid gap-5 border-b border-gray-200 pb-5">
<div className="flex items-center justify-between">
@@ -342,13 +321,11 @@ export default function OGSection({
</p>
<button
className="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"
- onClick={() => {
- setRequestedType("title");
- }}
- disabled={loadingMetaData.title}
+ onClick={generateTitle}
+ disabled={generatingTitle}
type="button"
>
- {loadingMetaData.title ? (
+ {generatingTitle ? (
<LoadingCircle />
) : (
<Magic className="h-4 w-4" />
@@ -376,11 +353,6 @@ export default function OGSection({
aria-invalid="true"
/>
</div>
- {metaDataError.title && (
- <p className="mt-2 text-sm text-red-600" id="meta-title-error">
- {metaDataError.title}
- </p>
- )}
</div>
<div>
@@ -394,13 +366,11 @@ export default function OGSection({
</p>
<button
className="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"
- onClick={() => {
- setRequestedType("description");
- }}
- disabled={loadingMetaData.description}
+ onClick={generateDescription}
+ disabled={generatingDescription}
type="button"
>
- {loadingMetaData.description ? (
+ {generatingDescription ? (
<LoadingCircle />
) : (
<Magic className="h-4 w-4" />
@@ -431,11 +401,6 @@ export default function OGSection({
aria-invalid="true"
/>
</div>
- {metaDataError.description && (
- <p className="mt-2 text-sm text-red-600" id="meta-title-error">
- {metaDataError.description}
- </p>
- )}
</div>
</motion.div>
)}