The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
switch AI to use streamText
Steven Teyfbfafaa46074
diff --git a/apps/web/app/api/ai/generate-support-title/route.ts b/apps/web/app/api/ai/generate-support-title/route.tsdeleted file mode 100644index 3f6b9f6e29..0000000000--- a/apps/web/app/api/ai/generate-support-title/route.ts+++ /dev/null@@ -1,65 +0,0 @@-import { anthropic } from "@/lib/anthropic";-import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";-import { ratelimit } from "@/lib/upstash";-import { AnthropicStream, StreamingTextResponse } from "ai";-import { getToken } from "next-auth/jwt";-import { NextRequest } from "next/server";--export const runtime = "edge";--export async function POST(req: NextRequest) {- if (!anthropic) {- console.error("Anthropic is not configured. Skipping the request.");- return new Response(null, { status: 200 });- }-- try {- const session = await getToken({- req,- secret: process.env.NEXTAUTH_SECRET,- });- if (!session?.email) {- throw new DubApiError({- code: "unauthorized",- message: "You must be logged in to access this resource",- });- }-- // you can only generate a support completion 3 times per minute- const { success } = await ratelimit(3, "1 m").limit(- `ai-completion:${session.sub}`,- );- if (!success) {- throw new DubApiError({- code: "rate_limit_exceeded",- message: "Don't DDoS me pls 🥺",- });- }-- // Extract the `prompt` from the body of the request- const { prompt } = await req.json();-- // Ask Claude for a streaming chat completion given the prompt- const response = await anthropic.messages.create({- messages: [- {- role: "user",- content: `Create a short but concise title that summarizes the following support request. Only return the generated title, and nothing else. Don't use quotation marks.-- ${prompt}`,- },- ],- model: "claude-3-sonnet-20240229",- stream: true,- max_tokens: 300,- });-- // Convert the response into a friendly text-stream- const stream = AnthropicStream(response);-- // Respond with the stream- return new StreamingTextResponse(stream);- } catch (error) {- return handleAndReturnErrorResponse(error);- }-}diff --git a/apps/web/lib/ai/generate-support-title.ts b/apps/web/lib/ai/generate-support-title.tsnew file mode 100644index 0000000000..6e91fb53e4--- /dev/null+++ b/apps/web/lib/ai/generate-support-title.ts@@ -0,0 +1,26 @@+"use server";++import { anthropic } from "@ai-sdk/anthropic";+import { streamText } from "ai";+import { createStreamableValue } from "ai/rsc";++export async function generateSupportTitle(prompt: string) {+ const stream = createStreamableValue();++ (async () => {+ const { textStream } = await streamText({+ model: anthropic("claude-3-sonnet-20240229"),+ prompt: `Create a short but concise title that summarizes the following support request. Only return the generated title, and nothing else. Don't use quotation marks.++ ${prompt}`,+ });++ for await (const delta of textStream) {+ stream.update(delta);+ }++ stream.done();+ })();++ return { output: stream.value };+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex dab7c30735..f52b4071dd 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -12,6 +12,7 @@"generate-openapi": "tsx ./scripts/generate-openapi.ts"},"dependencies": {+ "@ai-sdk/anthropic": "^0.0.17","@anthropic-ai/sdk": "^0.20.4","@boxyhq/saml-jackson": "1.23.9","@chronark/zod-bird": "^0.3.9",@@ -49,7 +50,7 @@"@visx/shape": "^2.12.2","@visx/text": "^3.3.0","@visx/tooltip": "^2.16.0",- "ai": "^3.0.22",+ "ai": "^3.1.22","aws4fetch": "^1.0.18","bottleneck": "^2.19.5","cmdk": "^0.2.0",diff --git a/apps/web/ui/layout/help/contact-form.tsx b/apps/web/ui/layout/help/contact-form.tsxindex 66b664da0b..a568b17c42 100644--- a/apps/web/ui/layout/help/contact-form.tsx+++ b/apps/web/ui/layout/help/contact-form.tsx@@ -1,9 +1,10 @@+import { generateSupportTitle } from "@/lib/ai/generate-support-title";import { CheckCircleFill } from "@/ui/shared/icons";import { Button, FileUpload, LoadingSpinner, useEnterSubmit } from "@dub/ui";-import { useCompletion } from "ai/react";+import { readStreamableValue } from "ai/rsc";import { AnimatePresence, motion } from "framer-motion";import { ChevronLeft, Paperclip, Trash2 } from "lucide-react";-import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";+import { Dispatch, SetStateAction, useRef, useState } from "react";import TextareaAutosize from "react-textarea-autosize";import { toast } from "sonner";@@ -80,19 +81,6 @@ export function ContactForm({const { handleKeyDown } = useEnterSubmit(formRef);- const { completion, complete } = useCompletion({- api: `/api/ai/generate-support-title`,- onError: (error) => {- toast.error(error.message);- },- });-- useEffect(() => {- if (completion) {- setData((prev) => ({ ...prev, title: completion }));- }- }, [completion]);-return (<div className="relative w-full px-3 pb-16 pt-5 sm:px-6"><button@@ -170,9 +158,16 @@ export function ContactForm({autoFocusautoComplete="off"value={data.message}- onBlur={() => {+ onBlur={async () => {if (!data.title && data.message) {- complete(data.message);+ const { output } = await generateSupportTitle(data.message);++ for await (const delta of readStreamableValue(output)) {+ setData((prev) => ({+ ...prev,+ title: prev.title + delta,+ }));+ }}}}onChange={(e) =>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 5d70770191..31693ebcc2 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -34,6 +34,9 @@ importers:apps/web:dependencies:+ '@ai-sdk/anthropic':+ specifier: ^0.0.17+ version: 0.0.17([email protected])'@anthropic-ai/sdk':specifier: ^0.20.4version: 0.20.4@@ -146,8 +149,8 @@ importers:specifier: ^2.16.0version: 2.16.0([email protected])([email protected])ai:- specifier: ^3.0.22- version: 3.0.22([email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: ^3.1.22+ version: 3.1.22([email protected])([email protected])([email protected])([email protected])([email protected])aws4fetch:specifier: ^1.0.18version: 1.0.18@@ -588,8 +591,19 @@ packages:resolution: {integrity: sha512-1Yjs2SvM8TflER/OD3cOjhWWOZb58A2t7wpE2S9XfBYTiIl+XFhQG2bjy4Pu1I+EAlCNUzRDYDdFwFYUKvXcIA==}engines: {node: '>=0.10.0'}- /@ai-sdk/[email protected]([email protected]):- resolution: {integrity: sha512-A6gFv6EHimayd2c2ayWMpKwADgsRrJg4DYYFnvJ71TXaWuSom7vUoALIobcaggmZ76xuzi17cXPFYg2vVu04WA==}+ /@ai-sdk/[email protected]([email protected]):+ resolution: {integrity: sha512-GH96m+mdz7XA1z4153g+SAGcib6CFdtjbwMXfWWE0q4iIAObeW6eC2N8VuucQdQNSbJ3h62KqdjWMho6k6L8Aw==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.0.0+ dependencies:+ '@ai-sdk/provider': 0.0.8+ '@ai-sdk/provider-utils': 0.0.11([email protected])+ zod: 3.22.4+ dev: false++ /@ai-sdk/[email protected]([email protected]):+ resolution: {integrity: sha512-JRDrqL2FGDmLh+a4R5qbS8UrWN9Lt7DpDIY1x6owgXjXkz3Umm1czs1X32VlL0M1dpoSxu4hGBFtXd56+kDzXA==}engines: {node: '>=18'}peerDependencies:zod: ^3.0.0@@ -597,15 +611,15 @@ packages:zod:optional: truedependencies:- '@ai-sdk/provider': 0.0.0+ '@ai-sdk/provider': 0.0.8eventsource-parser: 1.1.2nanoid: 3.3.6secure-json-parse: 2.7.0zod: 3.22.4dev: false- /@ai-sdk/[email protected]:- resolution: {integrity: sha512-Gbl9Ei8NPtM85gB/o8cY7s7CLGxK/U6QVheVaI3viFn7o6IpTfy1Ja389e2FXVMNJ4WHK2qYWSp5fAFDuKulTA==}+ /@ai-sdk/[email protected]:+ resolution: {integrity: sha512-+gcMvyPUDfDXV9caN3CG5Le0M5K4CjqTdMV1ODg/AosApQiJW9ByN5imJPdI043zVdt+HS9WG+s0j4am7ca4bg==}engines: {node: '>=18'}dependencies:json-schema: 0.4.0@@ -8964,16 +8978,19 @@ packages:humanize-ms: 1.2.1dev: false- /[email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):- resolution: {integrity: sha512-VkObPBejjUA9mSJBurVtMpwdqDqzrzjKvsrrj1SsKsUOH/pbmzL6U2ym61Sz8pQXuPYJqcm3SpYOfqrIMRUH0Q==}+ /[email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):+ resolution: {integrity: sha512-Vgy490Q6p6pZ39VrRzL9ovr2N1YPsR+KvWNs+n73VAQoGBZtU/vwiiWrFU9LHXGhB9X+EBfQD0vixnTDS2dJWA==}engines: {node: '>=18'}peerDependencies:- react: ^18.2.0+ openai: ^4.42.0+ react: ^18 || ^19solid-js: ^1.7.7svelte: ^3.0.0 || ^4.0.0vue: ^3.3.4zod: ^3.0.0peerDependenciesMeta:+ openai:+ optional: truereact:optional: truesolid-js:@@ -8985,8 +9002,8 @@ packages:zod:optional: truedependencies:- '@ai-sdk/provider': 0.0.0- '@ai-sdk/provider-utils': 0.0.0([email protected])+ '@ai-sdk/provider': 0.0.8+ '@ai-sdk/provider-utils': 0.0.11([email protected])eventsource-parser: 1.1.2json-schema: 0.4.0jsondiffpatch: 0.6.0