Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: initialize first thread and chat interface

Marc Seitzac88ce488439
diff --git a/lib/utils.ts b/lib/utils.ts
index 1b296c5a..0f79ed38 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -4,6 +4,8 @@ import ms from "ms";
import bcrypt from "bcryptjs";
import { toast } from "sonner";
import { customAlphabet } from "nanoid";
+import { ThreadMessage } from "openai/resources/beta/threads/messages/messages";
+import { Message } from "ai";
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs));
@@ -254,3 +256,50 @@ export const calculateDaysLeft = (accountCreationDate: Date): number => {
}
return daysLeft(accountCreationDate, maxDays);
};
+
+// helper function to convert ThreadMessages (an OpenAI type for messages) to Messages (an vercel/ai type for messages)
+export const convertThreadMessagesToMessages = (
+ threadMessages: ThreadMessage[],
+): Message[] => {
+ // Filter out messages with metaData.intitialMessage == 'True'
+ const filteredMessages = threadMessages.filter((threadMessage) => {
+ if (
+ typeof threadMessage.metadata === "object" &&
+ threadMessage.metadata !== null
+ ) {
+ // Safely typecast metadata to an object with the expected structure
+ const metadata = threadMessage.metadata as { intitialMessage?: string };
+ return metadata.intitialMessage !== "True";
+ }
+ return true; // Include messages where metadata is not an object or is null
+ });
+
+ return filteredMessages.map((threadMessage) => {
+ const {
+ id,
+ created_at,
+ content,
+ role,
+ // other fields you might need from ThreadMessage
+ } = threadMessage;
+
+ // Assuming content is an array and you want to convert it into a string or JSX element
+ const messageContent = content.map((item) => {
+ if (item.type === "text") {
+ return item.text.value;
+ } else {
+ return "";
+ }
+ });
+
+ return {
+ id,
+ createdAt: new Date(created_at * 1000), // converting Unix timestamp to Date object
+ content: messageContent[0],
+ role: role === "assistant" ? "assistant" : "user", // Adjust according to your needs
+ // Set other properties as required by Message interface
+ ui: null, // example, set based on your UI requirements
+ // name, function_call, and other fields as needed
+ };
+ });
+};
diff --git a/pages/api/assistants/chat.ts b/pages/api/assistants/chat.ts
new file mode 100644
index 00000000..7b2a736d
--- /dev/null
+++ b/pages/api/assistants/chat.ts
@@ -0,0 +1,84 @@
+import { experimental_AssistantResponse } from "ai";
+import OpenAI from "openai";
+import { type MessageContentText } from "openai/resources/beta/threads/messages/messages";
+
+// Create an OpenAI API client (that's edge friendly!)
+const openai = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY || "",
+});
+
+// IMPORTANT! Set the runtime to edge
+export const config = {
+ runtime: "edge",
+};
+
+export default async function POST(req: Request) {
+ // Parse the request body
+ const input: {
+ threadId: string;
+ message: string;
+ } = await req.json();
+
+ // Add a message to the thread
+ const createdMessage = await openai.beta.threads.messages.create(
+ input.threadId,
+ {
+ role: "user",
+ content: input.message,
+ },
+ );
+
+ return experimental_AssistantResponse(
+ {
+ threadId: input.threadId,
+ messageId: createdMessage.id,
+ },
+ async ({ threadId, sendMessage }) => {
+ // Run the assistant on the thread
+ const run = await openai.beta.threads.runs.create(threadId, {
+ assistant_id: process.env.OAI_ASSISTANT_ID!,
+ });
+
+ async function waitForRun(run: OpenAI.Beta.Threads.Runs.Run) {
+ // Poll for status change
+ while (run.status === "queued" || run.status === "in_progress") {
+ // delay for 500ms:
+ await new Promise((resolve) => setTimeout(resolve, 500));
+
+ run = await openai.beta.threads.runs.retrieve(threadId!, run.id);
+ }
+
+ // Check the run status
+ if (
+ run.status === "cancelled" ||
+ run.status === "cancelling" ||
+ run.status === "failed" ||
+ run.status === "expired"
+ ) {
+ throw new Error(run.status);
+ }
+ }
+
+ await waitForRun(run);
+
+ // Get new thread messages (after our message)
+ const responseMessages = (
+ await openai.beta.threads.messages.list(threadId, {
+ after: createdMessage.id,
+ order: "asc",
+ })
+ ).data;
+
+ // Send the messages
+ for (const message of responseMessages) {
+ sendMessage({
+ id: message.id,
+ role: "assistant",
+ content: message.content.filter(
+ (content) => content.type === "text",
+ ) as Array<MessageContentText>,
+ });
+ }
+ },
+ );
+}
diff --git a/pages/api/assistants/threads/index.ts b/pages/api/assistants/threads/index.ts
new file mode 100644
index 00000000..901d33a9
--- /dev/null
+++ b/pages/api/assistants/threads/index.ts
@@ -0,0 +1,90 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import prisma from "@/lib/prisma";
+import { errorhandler } from "@/lib/errorHandler";
+import OpenAI from "openai";
+import { convertThreadMessagesToMessages } from "@/lib/utils";
+
+const openai = new OpenAI({
+ apiKey: process.env.OPENAI_API_KEY || "",
+});
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "POST") {
+ // TODO: block unauthorized requests
+
+ const { documentId, userId } = req.body as {
+ documentId: string;
+ userId: string;
+ };
+
+ try {
+ let conversation;
+ conversation = await prisma.conversation.findUnique({
+ where: {
+ userId_documentId: {
+ userId,
+ documentId,
+ },
+ },
+ select: {
+ threadId: true,
+ },
+ });
+
+ if (!conversation) {
+ // get fileId from document version
+ const documentVersion = await prisma.documentVersion.findFirst({
+ where: {
+ documentId,
+ isPrimary: true,
+ },
+ select: {
+ fileId: true,
+ },
+ });
+
+ const threadId = (
+ await openai.beta.threads.create({
+ messages: [
+ {
+ role: "user",
+ content: "Initializing conversation with Papermark Assistant",
+ file_ids: [documentVersion?.fileId || ""],
+ metadata: { intitialMessage: true },
+ },
+ ],
+ })
+ ).id;
+
+ conversation = await prisma.conversation.create({
+ data: {
+ userId,
+ threadId,
+ documentId,
+ },
+ select: {
+ threadId: true,
+ },
+ });
+ }
+
+ const threadId = conversation.threadId;
+ // get existing messages from thread, latest first (DESC)
+ const { data } = await openai.beta.threads.messages.list(threadId);
+
+ return res.status(200).json({
+ ...conversation,
+ messages: convertThreadMessagesToMessages(data),
+ });
+ } catch (error) {
+ errorhandler(error, res);
+ }
+ } else {
+ // We only allow GET and DELETE requests
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+}
diff --git a/pages/view/[linkId]/chat.tsx b/pages/view/[linkId]/chat.tsx
new file mode 100644
index 00000000..bc01251f
--- /dev/null
+++ b/pages/view/[linkId]/chat.tsx
@@ -0,0 +1,148 @@
+import { Message, experimental_useAssistant as useAssistant } from "ai/react";
+import { useEffect, useRef, useState } from "react";
+import prisma from "@/lib/prisma";
+import { getServerSession } from "next-auth";
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { CustomUser } from "@/lib/types";
+
+const roleToColorMap: Record<Message["role"], string> = {
+ system: "red",
+ user: "black",
+ function: "blue",
+ assistant: "green",
+};
+
+const roleToNameMap: Record<Message["role"], string> = {
+ system: "System",
+ user: "You",
+ function: "Function",
+ assistant: "Papermark Assistant",
+};
+
+export const getServerSideProps = async (context: any) => {
+ const { linkId } = context.params;
+ const session = await getServerSession(context.req, context.res, authOptions);
+ const document = await prisma.link.findUnique({
+ where: { id: linkId },
+ select: {
+ document: {
+ select: {
+ id: true,
+ },
+ },
+ },
+ });
+
+ // create or fetch threadId
+ const res = await fetch(
+ `${process.env.NEXTAUTH_URL}/api/assistants/threads`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ documentId: document!.document.id,
+ userId: (session!.user as CustomUser).id,
+ }),
+ },
+ );
+
+ if (!res.ok) {
+ return {
+ notFound: true,
+ };
+ }
+
+ const { threadId, messages } = await res.json();
+
+ if (!document) {
+ return {
+ notFound: true,
+ };
+ }
+
+ return {
+ props: {
+ threadId,
+ messages: messages || [],
+ },
+ };
+};
+
+export default function Chat({
+ threadId,
+ messages,
+}: {
+ threadId: string;
+ messages: Message[];
+}) {
+ const {
+ status,
+ messages: hookMessages,
+ input,
+ submitMessage,
+ handleInputChange,
+ error,
+ } = useAssistant({
+ api: "/api/assistants/chat",
+ threadId: threadId,
+ });
+
+ const [combinedMessages, setCombinedMessages] = useState<Message[]>([]);
+
+ useEffect(() => {
+ // Concatenate existing messages with messages from the hook
+ // and reverse the order so that the newest messages are at the bottom:
+ const reversedMessages = [...messages].reverse();
+ setCombinedMessages([...reversedMessages, ...hookMessages]);
+ }, [messages, hookMessages]);
+
+ // When status changes to accepting messages, focus the input:
+ const inputRef = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ if (status === "awaiting_message") {
+ inputRef.current?.focus();
+ }
+ }, [status]);
+
+ return (
+ <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch">
+ {error != null && (
+ <div className="relative bg-red-500 text-white px-6 py-4 rounded-md">
+ <span className="block sm:inline">
+ Error: {(error as any).toString()}
+ </span>
+ </div>
+ )}
+
+ {combinedMessages.map((m: Message) => (
+ <div
+ key={m.id}
+ className="whitespace-pre-wrap"
+ style={{ color: roleToColorMap[m.role] }}
+ >
+ <strong>{`${roleToNameMap[m.role]}: `}</strong>
+ {m.content}
+ <br />
+ <br />
+ </div>
+ ))}
+
+ {status === "in_progress" && (
+ <div className="h-8 w-full max-w-md p-2 mb-8 bg-gray-300 dark:bg-gray-600 rounded-lg animate-pulse" />
+ )}
+
+ <form onSubmit={submitMessage}>
+ <input
+ ref={inputRef}
+ disabled={status !== "awaiting_message"}
+ className="fixed bottom-0 w-full max-w-md p-2 mb-8 border border-gray-300 rounded shadow-xl"
+ value={input}
+ placeholder="Summarize this document"
+ onChange={handleInputChange}
+ />
+ </form>
+ </div>
+ );
+}
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 67159498..2a986541 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -37,20 +37,21 @@ model Session {
}
model User {
- id String @id @default(cuid())
+ id String @id @default(cuid())
name String?
- email String? @unique
+ email String? @unique
emailVerified DateTime?
image String?
- createdAt DateTime @default(now())
+ createdAt DateTime @default(now())
accounts Account[]
sessions Session[]
documents Document[]
teams UserTeam[]
domains Domain[]
- plan String @default("trial")
- stripeId String? @unique // Stripe subscription / customer ID
- subscriptionId String? @unique // Stripe subscription ID
+ conversations Conversation[]
+ plan String @default("trial")
+ stripeId String? @unique // Stripe subscription / customer ID
+ subscriptionId String? @unique // Stripe subscription ID
startsAt DateTime? // Stripe subscription start date
endsAt DateTime? // Stripe subscription end date
}
@@ -98,21 +99,23 @@ model VerificationToken {
}
model Document {
- id String @id @default(cuid())
- name String
- description String?
- file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)
- type String? // This should be a reference to the file type (pdf, docx, etc.)
- numPages Int? // This should be a reference to the number of pages in the document
- owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
- teamId String?
- team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)
- ownerId String // This field holds the foreign key.
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- links Link[]
- views View[]
- versions DocumentVersion[]
+ id String @id @default(cuid())
+ name String
+ description String?
+ file String // This should be a reference to where the file is stored (S3, Google Cloud Storage, etc.)
+ type String? // This should be a reference to the file type (pdf, docx, etc.)
+ numPages Int? // This should be a reference to the number of pages in the document
+ owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade)
+ teamId String?
+ team Team? @relation(fields: [teamId], references: [id], onDelete: SetNull)
+ ownerId String // This field holds the foreign key.
+ assistantEnabled Boolean @default(false) // This indicates if assistant is enabled for this document
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ links Link[]
+ views View[]
+ versions DocumentVersion[]
+ conversations Conversation[]
}
model DocumentVersion {
@@ -124,6 +127,7 @@ model DocumentVersion {
type String? // This should be a reference to the file type (pdf, docx, etc.)
numPages Int? // This should be a reference to the number of pages in the document
isPrimary Boolean @default(false) // Indicates if this is the primary version
+ fileId String? // This is the file ID of the OpenAI File API
pages DocumentPage[]
hasPages Boolean @default(false) // Indicates if the document has pages
createdAt DateTime @default(now())
@@ -200,7 +204,7 @@ model Invitation {
createdAt DateTime @default(now())
token String @unique
- @@unique([email,teamId])
+ @@unique([email, teamId])
}
enum EmailType {
@@ -210,15 +214,31 @@ enum EmailType {
FIRST_TRIAL_END_REMINDER_EMAIL
FINAL_TRIAL_END_REMINDER_EMAIL
}
+
model SentEmail {
- id String @id @default(cuid())
- type EmailType
- recipient String // Email address of the recipient
- marketing Boolean @default(false)
- createdAt DateTime @default(now())
- team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
- teamId String
- domainSlug String? // Domain that triggered the email. This can be nullable, representing emails not triggered by domains
+ id String @id @default(cuid())
+ type EmailType
+ recipient String // Email address of the recipient
+ marketing Boolean @default(false)
+ createdAt DateTime @default(now())
+ team Team @relation(fields: [teamId], references: [id], onDelete: Cascade)
+ teamId String
+ domainSlug String? // Domain that triggered the email. This can be nullable, representing emails not triggered by domains
@@index([teamId])
-}
\ No newline at end of file
+}
+
+model Conversation {
+ id String @id @default(cuid())
+ threadId String @unique // This is the thread ID from OpenAI Assistant API
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ userId String
+ document Document @relation(fields: [documentId], references: [id], onDelete: Cascade)
+ documentId String
+ createdAt DateTime @default(now())
+ lastMessageAt DateTime? // This is the last time a message was sent in the thread
+
+ @@index([threadId])
+ @@unique([userId, documentId])
+ @@unique([threadId, documentId])
+}