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.

feat: useChat hook for ai generation

flooorianfloc4f86439bc15
diff --git a/apps/web/app/api/ai/shortlink/route.ts b/apps/web/app/api/ai/chat/route.ts
similarity index 100%
rename from apps/web/app/api/ai/shortlink/route.ts
rename to apps/web/app/api/ai/chat/route.ts
diff --git a/apps/web/app/api/ai/metadata/route.ts b/apps/web/app/api/ai/metadata/route.ts
deleted file mode 100644
index 559da534b5..0000000000
--- a/apps/web/app/api/ai/metadata/route.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-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";
-
-export async function POST(req: NextRequest) {
- const searchParams = getSearchParams(req.url);
- const { workspaceId, type } = searchParams;
-
- const { metaTitle, metaDescription, doNotUseString } = 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 with a suitable ${type} for SEO and sharing purposes of a website based on the one you receive. For example, you receive a question like 'What is the suitable meta ${type} for meta-title Notion and meta-description The all in one workspace?' and you respond with e.g. ${type === "title" ? "Notion - The all-in-one workspace for your productivity" : "A new tool that brings together all the apps you need for your daily work in one place: The unified workspace for you and your team."}. Don't use any special characters or spaces. For ${type} the maximum length is ${type === "title" ? "120" : "240"} characters.`,
- },
- {
- role: "user",
- content: `What is the suitable meta ${type} for meta-title ${metaTitle} and meta-description ${metaDescription}?${doNotUseString ? ` Don't use ${doNotUseString}.` : ""} and only respond with a suitable ${type} without any special formatting.`,
- },
- ],
- });
-
- 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.tsx
index 81b63cff56..9d5864ec7b 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -85,8 +85,8 @@ function AddEditLinkModal({
const [generatingAIKey, setGeneratingAIKey] = useState(false);
const [saving, setSaving] = useState(false);
- const { messages, append, setMessages } = useChat({
- api: `/api/ai/shortlink?workspaceId=${workspaceId}`,
+ const { append } = useChat({
+ api: `/api/ai/chat?workspaceId=${workspaceId}`,
onFinish(message) {
if (message.role === "assistant") {
setData((prev) => ({ ...prev, key: message.content }));
@@ -546,7 +546,9 @@ function AddEditLinkModal({
generatingRandomKey ||
!plan ||
plan === "free" ||
- !url
+ !url ||
+ !data.title ||
+ !data.description
}
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 ee4567e7ee..3726811456 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,6 +26,7 @@ import {
} from "react";
import TextareaAutosize from "react-textarea-autosize";
import UnsplashSearch from "./unsplash-search";
+import { useChat } from "ai/react";
export default function OGSection({
props,
@@ -50,6 +51,31 @@ export default function OGSection({
title: false,
description: false,
});
+ const [requestedType, setRequestedType] = useState<"title" | "description">();
+
+ const { append } = useChat({
+ api: `/api/ai/chat?workspaceId=${workspaceId}`,
+ onFinish(message) {
+ if (message.role === "assistant" && requestedType) {
+ setData((prev) => ({
+ ...prev,
+ [requestedType]: message.content.replaceAll('"', ""),
+ }));
+ }
+
+ 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 onChangePicture = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files && e.target.files[0];
@@ -88,43 +114,26 @@ export default function OGSection({
}, 200);
}
- const generateMetaData = useCallback(
- async (type: "title" | "description") => {
- setLoadingMetaData((prev) => ({ ...prev, [type]: true }));
-
- const returnKey = async (doNotUseString?) =>
- await fetch(
- `/api/ai/metadata?workspaceId=${workspaceId}&type=${type}`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- metaTitle: data.title,
- metaDescription: data.description,
- doNotUseString,
- }),
- },
- ).then(async (res) => {
- if (res.status !== 200) {
- const error = await res.text();
- setLoadingMetaData((prev) => ({ ...prev, [type]: false }));
- throw new Error(error);
- }
- return res.text();
- });
+ useEffect(() => {
+ if (loadingMetaData.title || loadingMetaData.description || !requestedType)
+ return;
- let res = await returnKey();
+ const generateMetaData = async () => {
+ setLoadingMetaData((prev) => ({ ...prev, [requestedType]: true }));
- if (res === data[type]) res = await returnKey(data[type]);
+ 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?`,
+ });
+ };
- setData((prev) => ({ ...prev, [type]: res }));
+ generateMetaData();
- setLoadingMetaData((prev) => ({ ...prev, [type]: false }));
- },
- [data],
- );
+ return () => setRequestedType(undefined);
+ }, [requestedType]);
return (
<div className="relative grid gap-5 border-b border-gray-200 pb-5">
@@ -321,7 +330,9 @@ 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={() => generateMetaData("title")}
+ onClick={() => {
+ setRequestedType("title");
+ }}
disabled={loadingMetaData.title}
type="button"
>
@@ -366,7 +377,9 @@ 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={() => generateMetaData("description")}
+ onClick={() => {
+ setRequestedType("description");
+ }}
disabled={loadingMetaData.description}
type="button"
>