🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
Capture feedback (#27)
Marc Klingen66f065460707
diff --git a/.env.cloud.example b/.env.cloud.exampleindex dcc34d19bd..e90eff0cad 100644--- a/.env.cloud.example+++ b/.env.cloud.example@@ -21,4 +21,6 @@ NEXTAUTH_SECRET="secret"# NEXT_PUBLIC_SENTRY_DSN=# NEXT_SENTRY_ORG=# NEXT_SENTRY_PROJECT=-# SENTRY_AUTH_TOKEN=\ No newline at end of file+# SENTRY_AUTH_TOKEN=++# SLACK_WEBHOOK_FEEDBACK_URL=\ No newline at end of filediff --git a/sentry.client.config.ts b/sentry.client.config.tsindex 6336fc8cbc..67e7b103e4 100644--- a/sentry.client.config.ts+++ b/sentry.client.config.ts@@ -16,6 +16,14 @@ if (process.env.NEXT_PUBLIC_SENTRY_DSN)replaysSessionSampleRate: 1.0,replaysOnErrorSampleRate: 1.0,+ beforeSend(event, _hint) {+ // Check if it is an exception, and if so, show the report dialog+ if (event.exception) {+ Sentry.showReportDialog({ eventId: event.event_id });+ }+ return event;+ },+// ...// Note: if you want to override the automatic release value, do not set adiff --git a/src/components/layouts/layout.tsx b/src/components/layouts/layout.tsxindex 6e196a196f..dd7a5337fb 100644--- a/src/components/layouts/layout.tsx+++ b/src/components/layouts/layout.tsx@@ -12,7 +12,7 @@ import {import Link from "next/link";import { useRouter } from "next/router";import clsx from "clsx";-import { Code, LineChart } from "lucide-react";+import { Code, LineChart, MessageSquarePlus } from "lucide-react";import { signOut, useSession } from "next-auth/react";import { ChevronDownIcon } from "@heroicons/react/20/solid";import { cn } from "@/src/utils/tailwind";@@ -23,6 +23,7 @@ import {} from "@/src/components/ui/avatar";import { api } from "@/src/utils/api";import { NewProjectButton } from "@/src/features/projects/components/NewProjectButton";+import { FeedbackButtonWrapper } from "@/src/features/feedback/component/FeedbackButton";const userNavigation = [{@@ -292,6 +293,15 @@ export default function Layout(props: PropsWithChildren) {</Link></li>))}+ <FeedbackButtonWrapper className="w-full">+ <li className="group flex gap-x-3 rounded-md p-2 text-sm font-semibold leading-6 text-gray-700 hover:bg-gray-50 hover:text-indigo-600">+ <MessageSquarePlus+ className="h-6 w-6 shrink-0 text-gray-400 group-hover:text-indigo-600"+ aria-hidden="true"+ />+ Feedback+ </li>+ </FeedbackButtonWrapper></ul></li>diff --git a/src/features/feedback/component/FeedbackButton.tsx b/src/features/feedback/component/FeedbackButton.tsxnew file mode 100644index 0000000000..bc2fffaefc--- /dev/null+++ b/src/features/feedback/component/FeedbackButton.tsx@@ -0,0 +1,127 @@+import * as Sentry from "@sentry/react";+import { Button } from "@/src/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from "@/src/components/ui/dialog";+import * as z from "zod";+import { zodResolver } from "@hookform/resolvers/zod";+import { useForm } from "react-hook-form";+import {+ Form,+ FormControl,+ FormDescription,+ FormField,+ FormItem,+ FormMessage,+} from "@/src/components/ui/form";+import { Input } from "@/src/components/ui/input";+import { type PropsWithChildren, useState } from "react";+import { useSession } from "next-auth/react";++const formSchema = z.object({+ feedback: z.string().min(3, "Must have at least 3 characters"),+});++export function FeedbackButtonWrapper(+ props: PropsWithChildren<{ className: string }>+) {+ const [open, setOpen] = useState(false);+ const session = useSession();++ const form = useForm<z.infer<typeof formSchema>>({+ resolver: zodResolver(formSchema),+ defaultValues: {+ feedback: "",+ },+ });++ async function onSubmit(values: z.infer<typeof formSchema>) {+ // Add to sentry+ if (process.env.NEXT_PUBLIC_SENTRY_DSN) {+ const eventId = Sentry.captureMessage(`User submitted feedback`);+ Sentry.captureUserFeedback({+ event_id: eventId,+ email: session.data?.user?.email ?? "",+ name: session.data?.user?.name ?? "",+ comments: values.feedback,+ });+ }+ try {+ const res = await fetch("https://cloud.langfuse.com/api/feedback", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ ...values,+ url: window.location.href,+ user: session.data?.user,+ }),+ });+ if (res.ok) {+ setOpen(false);+ } else {+ const data = res.json();+ console.error(data);+ form.setError("feedback", {+ type: "manual",+ message: JSON.stringify(data),+ });+ }+ } catch (error) {+ console.error(error);+ form.setError("feedback", {+ type: "manual",+ message:+ "Failed to submit feedback, please email us: [email protected]",+ });+ }+ }++ return (+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogTrigger className={props.className}>+ {props.children}+ </DialogTrigger>+ <DialogContent>+ <DialogHeader>+ <DialogTitle className="mb-5">Provide feedback</DialogTitle>+ </DialogHeader>+ <Form {...form}>+ <form+ // eslint-disable-next-line @typescript-eslint/no-misused-promises+ onSubmit={form.handleSubmit(onSubmit)}+ className="space-y-8"+ >+ <FormField+ control={form.control}+ name="feedback"+ render={({ field }) => (+ <FormItem>+ <FormDescription>+ What do you think about this project? What can be improved?+ </FormDescription>+ <FormControl>+ <Input {...field} />+ </FormControl>+ <FormMessage />+ </FormItem>+ )}+ />+ <Button+ type="submit"+ loading={form.formState.isSubmitting}+ className="w-full"+ >+ {form.formState.isSubmitting ? "Loading ..." : "Submit"}+ </Button>+ </form>+ </Form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/src/features/feedback/lib/corsMiddleware.ts b/src/features/feedback/lib/corsMiddleware.tsnew file mode 100644index 0000000000..ce2ebdf45e--- /dev/null+++ b/src/features/feedback/lib/corsMiddleware.ts@@ -0,0 +1,25 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import Cors from "cors";++// You can read more about the available options here: https://github.com/expressjs/cors#configuration-options+const cors = Cors({+ methods: ["POST", "GET", "HEAD"],+ origin: "*",+});++// Helper method to wait for a middleware to execute before continuing+// And to throw an error when an error happens in a middleware+export function runFeedbackCorsMiddleware(+ req: NextApiRequest,+ res: NextApiResponse+) {+ return new Promise((resolve, reject) => {+ cors(req, res, (result: unknown) => {+ if (result instanceof Error) {+ return reject(result);+ }++ return resolve(result);+ });+ });+}diff --git a/src/features/feedback/server/feedbackHandler.ts b/src/features/feedback/server/feedbackHandler.tsnew file mode 100644index 0000000000..a9e9a1b538--- /dev/null+++ b/src/features/feedback/server/feedbackHandler.ts@@ -0,0 +1,36 @@+import { type NextApiRequest, type NextApiResponse } from "next";+import { runFeedbackCorsMiddleware } from "../lib/corsMiddleware";++// Collects feedack from users that do not use the cloud version of the app+export default async function feedbackApiHandler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ // Run the cors middleware+ console.log(JSON.stringify(req.body));++ await runFeedbackCorsMiddleware(req, res);++ try {+ if (!process.env.SLACK_WEBHOOK_FEEDBACK_URL)+ throw new Error("SLACK_WEBHOOK_FEEDBACK_URL is not set");++ const slackResponse = await fetch(process.env.SLACK_WEBHOOK_FEEDBACK_URL, {+ method: "POST",+ body: JSON.stringify({ rawBody: JSON.stringify(req.body, null, 2) }),+ headers: {+ "Content-Type": "application/json",+ },+ });++ if (slackResponse.status === 200) {+ res.status(200).json({ status: "OK" });+ } else {+ console.error(slackResponse);+ res.status(400).json({ status: "Error" });+ }+ } catch (error) {+ console.error(error);+ res.status(400).json({ status: "Error" });+ }+}diff --git a/src/pages/api/feedback.ts b/src/pages/api/feedback.tsnew file mode 100644index 0000000000..8ec6f63edd--- /dev/null+++ b/src/pages/api/feedback.ts@@ -0,0 +1,3 @@+import feedbackApiHandler from "@/src/features/feedback/server/feedbackHandler";++export default feedbackApiHandler;