The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add AI column mapping
Tim Wilsonb21b1bf9b6e4
diff --git a/apps/web/lib/ai/generate-csv-mapping.ts b/apps/web/lib/ai/generate-csv-mapping.tsnew file mode 100644index 0000000000..5e23932bcb--- /dev/null+++ b/apps/web/lib/ai/generate-csv-mapping.ts@@ -0,0 +1,56 @@+"use server";++import { anthropic } from "@ai-sdk/anthropic";+import { streamObject } from "ai";+import { createStreamableValue } from "ai/rsc";+import { z } from "zod";++export async function generateCsvMapping(+ fieldColumns: string[],+ firstRows: Record<string, string>[],+) {+ const stream = createStreamableValue();++ (async () => {+ const { partialObjectStream } = await streamObject({+ model: anthropic("claude-3-sonnet-20240229"),+ schema: z.object({+ domain: z+ .string()+ .optional()+ .describe(+ "The domain of the shortlink. Can be mapped to a full URL if there is not a separate domain column",+ ),+ key: z+ .string()+ .optional()+ .describe(+ "The key/slug of the shortlink (a shortlink is: https://[domain]/[key]). Can be mapped to a full URL if there is not a separate key column",+ ),+ url: z.string().optional().describe("The full URL of the shortlink"),+ title: z.string().optional().describe("The title of the shortlink"),+ description: z+ .string()+ .optional()+ .describe("The description of the shortlink"),+ }),+ prompt:+ `The following columns are the headings from a CSV import file for importing a company's short links. ` ++ `Map these column names to the correct fields in our database (domain, key, url, title, description) by providing the matching column name for each field.` ++ `You may also consult the first few rows of data to help you make the mapping, but you are mapping the columns, not the values. ` ++ `If you are not sure or there is no matching column, omit the value.\n\n` ++ `Columns:\n${fieldColumns.join(",")}\n\n` ++ `First few rows of data:\n` ++ firstRows.map((row) => JSON.stringify(row)).join("\n"),+ temperature: 0.2,+ });++ for await (const partialObject of partialObjectStream) {+ stream.update(partialObject);+ }++ stream.done();+ })();++ return { object: stream.value };+}diff --git a/apps/web/package.json b/apps/web/package.jsonindex 345d4da111..e284ec8e49 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -54,7 +54,7 @@"@visx/shape": "^2.12.2","@visx/text": "^3.3.0","@visx/tooltip": "^2.16.0",- "ai": "^3.1.22",+ "ai": "^3.2.38","aws4fetch": "^1.0.18","bottleneck": "^2.19.5","cmdk": "^0.2.0",@@ -75,8 +75,8 @@"nanoid": "^5.0.1","next": "14.3.0-canary.42","next-auth": "^4.24.4",- "next-safe-action": "7.1.4-experimental.1","next-axiom": "^1.3.0",+ "next-safe-action": "7.1.4-experimental.1","node-html-parser": "^6.1.4","nodemailer": "^6.9.3","openapi-types": "^12.1.3",diff --git a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx b/apps/web/ui/modals/import-csv-modal/field-mapping.tsxindex 42d2bf7e5e..9d86c37975 100644--- a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx+++ b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx@@ -1,12 +1,45 @@+"use client";++import { generateCsvMapping } from "@/lib/ai/generate-csv-mapping";import { Button, IconMenu, Popover, Tooltip } from "@dub/ui";-import { Check, Magnifier, TableIcon } from "@dub/ui/src/icons";+import { Check, LoadingSpinner, Magnifier, TableIcon } from "@dub/ui/src/icons";import { truncate } from "@dub/utils";+import { readStreamableValue } from "ai/rsc";import { ChevronDown } from "lucide-react";-import { useMemo, useState } from "react";+import { useEffect, useMemo, useState } from "react";import { Controller } from "react-hook-form";import { mappableFields, useCsvContext } from ".";export function FieldMapping() {+ const { fileColumns, firstRows, setValue } = useCsvContext();++ const [isStreaming, setIsStreaming] = useState(true);++ useEffect(() => {+ if (!fileColumns || !firstRows) return;++ generateCsvMapping(fileColumns, firstRows)+ .then(async ({ object }) => {+ setIsStreaming(true);+ for await (const partialObject of readStreamableValue(object)) {+ if (partialObject) {+ Object.entries(partialObject).forEach((entry) => {+ const [field, value] = entry as string[];+ if (+ Object.keys(mappableFields).includes(field) &&+ fileColumns.includes(value)+ ) {+ setValue(field as keyof typeof mappableFields, value, {+ shouldValidate: true,+ });+ }+ });+ }+ }+ })+ .finally(() => setIsStreaming(false));+ }, [fileColumns, firstRows]);+return (<div className="flex flex-col gap-3"><p className="text-sm text-gray-600">@@ -14,20 +47,27 @@ export function FieldMapping() {</p>{(Object.keys(mappableFields) as (keyof typeof mappableFields)[]).map((field) => (- <FieldRow key={field} field={field} />+ <FieldRow key={field} field={field} isStreaming={isStreaming} />),)}</div>);}-function FieldRow({ field }: { field: keyof typeof mappableFields }) {+function FieldRow({+ field,+ isStreaming,+}: {+ field: keyof typeof mappableFields;+ isStreaming: boolean;+}) {const { label, required } = mappableFields[field];const { control, watch, fileColumns, firstRows } = useCsvContext();const value = watch(field);+ const isLoading = isStreaming && !value;const [isOpen, setIsOpen] = useState(false);const examples = useMemo(() => {@@ -92,6 +132,7 @@ function FieldRow({ field }: { field: keyof typeof mappableFields }) {variant="secondary"className="min-w-16 px-3"onClick={() => setIsOpen((o) => !o)}+ disabled={isLoading}text={<div className="flex items-center gap-1"><span className="flex-1 truncate whitespace-nowrap text-left text-gray-800">@@ -99,7 +140,11 @@ function FieldRow({ field }: { field: keyof typeof mappableFields }) {<span className="text-gray-600">Select column...</span>)}</span>- <ChevronDown className="h-4 w-4 shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180" />+ {isLoading ? (+ <LoadingSpinner className="h-4 w-4 shrink-0" />+ ) : (+ <ChevronDown className="h-4 w-4 shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180" />+ )}</div>}/>diff --git a/apps/web/ui/modals/import-csv-modal/index.tsx b/apps/web/ui/modals/import-csv-modal/index.tsxindex 70f2e9cb41..9e566ef49e 100644--- a/apps/web/ui/modals/import-csv-modal/index.tsx+++ b/apps/web/ui/modals/import-csv-modal/index.tsx@@ -1,3 +1,5 @@+"use client";+import useWorkspace from "@/lib/swr/use-workspace";import {AnimatedSizeContainer,@@ -19,7 +21,12 @@ import {useMemo,useState,} from "react";-import { Control, UseFormWatch, useForm } from "react-hook-form";+import {+ Control,+ UseFormSetValue,+ UseFormWatch,+ useForm,+} from "react-hook-form";import { toast } from "sonner";import { mutate } from "swr";import { FieldMapping } from "./field-mapping";@@ -59,6 +66,7 @@ const ImportCsvContext = createContext<{setFirstRows: (rows: Record<string, string>[] | null) => void;control: Control<ImportCsvFormData>;watch: UseFormWatch<ImportCsvFormData>;+ setValue: UseFormSetValue<ImportCsvFormData>;} | null>(null);export function useCsvContext() {@@ -94,6 +102,7 @@ function ImportCsvModal({const {control,watch,+ setValue,handleSubmit,formState: { isLoading, isValid },} = useForm<ImportCsvFormData>({@@ -142,6 +151,7 @@ function ImportCsvModal({setFirstRows,control,watch,+ setValue,}}><div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 33679ee278..1b18a682e8 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -159,8 +159,8 @@ importers:specifier: ^2.16.0version: 2.16.0([email protected])([email protected])ai:- specifier: ^3.1.22- version: 3.1.22([email protected])([email protected])([email protected])([email protected])([email protected])+ specifier: ^3.2.38aws4fetch:specifier: ^1.0.18version: 1.0.18@@ -649,6 +649,29 @@ packages:zod: 3.22.4dev: false+ /@ai-sdk/[email protected]([email protected]):+ resolution: {integrity: sha512-XfOawxk95X3S43arn2iQIFyWGMi0DTxsf9ETc6t7bh91RPWOOPYN1tsmS5MTKD33OGJeaDQ/gnVRzXUCRBrckQ==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.0.0+ peerDependenciesMeta:+ zod:+ optional: true+ dependencies:+ '@ai-sdk/provider': 0.0.14+ eventsource-parser: 1.1.2+ nanoid: 3.3.6+ secure-json-parse: 2.7.0+ zod: 3.22.4+ dev: false++ /@ai-sdk/[email protected]:+ resolution: {integrity: sha512-gaQ5Y033nro9iX1YUjEDFDRhmMcEiCk56LJdIUbX5ozEiCNCfpiBpEqrjSp/Gp5RzBS2W0BVxfG7UGW6Ezcrzg==}+ engines: {node: '>=18'}+ dependencies:+ json-schema: 0.4.0+ dev: false+/@ai-sdk/[email protected]:resolution: {integrity: sha512-+gcMvyPUDfDXV9caN3CG5Le0M5K4CjqTdMV1ODg/AosApQiJW9ByN5imJPdI043zVdt+HS9WG+s0j4am7ca4bg==}engines: {node: '>=18'}@@ -656,6 +679,89 @@ packages:json-schema: 0.4.0dev: false+ resolution: {integrity: sha512-d9rgf3XfFVFtpisteoCkYPX8TqaruHXdb5maZP1udj0jEhS9gGxUGmsZ+U8lG4WgJu/6TuAykNtQ8bPJZqQauA==}+ engines: {node: '>=18'}+ peerDependencies:+ react: ^18 || ^19+ zod: ^3.0.0+ peerDependenciesMeta:+ react:+ optional: true+ zod:+ optional: true+ dependencies:+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ '@ai-sdk/ui-utils': 0.0.21([email protected])+ react: 18.2.0+ swr: 2.2.5([email protected])+ zod: 3.22.4+ dev: false++ /@ai-sdk/[email protected]([email protected]):+ resolution: {integrity: sha512-QO2kE5mTXxJa0Vel0z9cVInfEIHKgeen6QJxhdQXCK/8Etcel7DRKvfQWcJf50PLVGmzVRqnGcRqjr6raaYePw==}+ engines: {node: '>=18'}+ peerDependencies:+ solid-js: ^1.7.7+ peerDependenciesMeta:+ solid-js:+ optional: true+ dependencies:+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ '@ai-sdk/ui-utils': 0.0.21([email protected])+ transitivePeerDependencies:+ - zod+ dev: false++ resolution: {integrity: sha512-uNPc7KNy+6/FY436Jys4rP2LnouxNTTPqZp4jLg5s9i4+D8n2ImuKTrrHlJjTB8UiMsWmkRWU+Tqh8BptEExbw==}+ engines: {node: '>=18'}+ peerDependencies:+ svelte: ^3.0.0 || ^4.0.0+ peerDependenciesMeta:+ svelte:+ optional: true+ dependencies:+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ '@ai-sdk/ui-utils': 0.0.21([email protected])+ sswr: 2.1.0([email protected])+ svelte: 4.2.14+ transitivePeerDependencies:+ - zod+ dev: false++ /@ai-sdk/[email protected]([email protected]):+ resolution: {integrity: sha512-qZ4ScEhNVpVqfg/2KcKYKKQcUpmfVyMD3P06OVDqXpzMaWvw95lUSYkJO/TDI49MhyVyK4eAI35pRU5B7bhrTQ==}+ engines: {node: '>=18'}+ peerDependencies:+ zod: ^3.0.0+ peerDependenciesMeta:+ zod:+ optional: true+ dependencies:+ '@ai-sdk/provider': 0.0.14+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ secure-json-parse: 2.7.0+ zod: 3.22.4+ dev: false++ resolution: {integrity: sha512-qdlcWH4mrTq93V3b6c/5GwECLBBSUMV4m1F4SYUV5q+YfZjc8NiNcTYGes4pQoSRJBsDvB1Ch0fTam0hM3Gr7w==}+ engines: {node: '>=18'}+ peerDependencies:+ vue: ^3.3.4+ peerDependenciesMeta:+ vue:+ optional: true+ dependencies:+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ '@ai-sdk/ui-utils': 0.0.21([email protected])+ swrv: 1.0.4([email protected])+ vue: 3.4.21([email protected])+ transitivePeerDependencies:+ - zod+ dev: false+/@alloc/[email protected]:resolution: {integrity: sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==}engines: {node: '>=10'}@@ -4577,6 +4683,11 @@ packages:engines: {node: '>=8.0.0'}dev: false+ /@opentelemetry/[email protected]:+ resolution: {integrity: sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==}+ engines: {node: '>=8.0.0'}+ dev: false+/@opentelemetry/[email protected](@opentelemetry/[email protected]):resolution: {integrity: sha512-FP2oN7mVPqcdxJDTTnKExj4mi91EH+DNuArKfHTjPuJWe2K1JfMIVXNfahw1h3onJxQnxS8K0stKkogX05s+Aw==}engines: {node: '>=14'}@@ -9319,48 +9430,47 @@ packages:humanize-ms: 1.2.1dev: false- /[email protected]([email protected])([email protected])([email protected])([email protected])([email protected]):- resolution: {integrity: sha512-Vgy490Q6p6pZ39VrRzL9ovr2N1YPsR+KvWNs+n73VAQoGBZtU/vwiiWrFU9LHXGhB9X+EBfQD0vixnTDS2dJWA==}+ resolution: {integrity: sha512-FxDgUG/3pKri2GMS+l24Bhk1M01B2LYXNW8nh8R+Ssf+CUnrh2kuThHmWbM2slOs/EBTWFbQ9Z53bC6TWY1yZg==}engines: {node: '>=18'}peerDependencies:openai: ^4.42.0react: ^18 || ^19- solid-js: ^1.7.7+ sswr: ^2.1.0svelte: ^3.0.0 || ^4.0.0- vue: ^3.3.4zod: ^3.0.0peerDependenciesMeta:openai:optional: truereact:optional: true- solid-js:+ sswr:optional: truesvelte:optional: true- vue:- optional: truezod:optional: truedependencies:- '@ai-sdk/provider': 0.0.8- '@ai-sdk/provider-utils': 0.0.11([email protected])+ '@ai-sdk/provider': 0.0.14+ '@ai-sdk/provider-utils': 1.0.5([email protected])+ '@ai-sdk/react': 0.0.31([email protected])([email protected])+ '@ai-sdk/solid': 0.0.24([email protected])+ '@ai-sdk/svelte': 0.0.25([email protected])([email protected])+ '@ai-sdk/ui-utils': 0.0.21([email protected])+ '@ai-sdk/vue': 0.0.25([email protected])([email protected])+ '@opentelemetry/api': 1.9.0eventsource-parser: 1.1.2json-schema: 0.4.0jsondiffpatch: 0.6.0nanoid: 3.3.6react: 18.2.0secure-json-parse: 2.7.0- solid-js: 1.8.16- solid-swr-store: 0.10.7([email protected])([email protected])- sswr: 2.0.0([email protected])svelte: 4.2.14- swr: 2.2.0([email protected])- swr-store: 0.10.6- swrv: 1.0.4([email protected])- vue: 3.4.21([email protected])zod: 3.22.4zod-to-json-schema: 3.22.5([email protected])+ transitivePeerDependencies:+ - solid-js+ - vuedev: false@@ -18151,20 +18261,6 @@ packages:randombytes: 2.1.0dev: false- resolution: {integrity: sha512-8+pDC1vOedPXjKG7oz8o+iiHrtF2WswaMQJ7CKFpccvSYfrzmvKY9zOJWCg+881722wIHfwkdnRmiiDm9ym+zQ==}- engines: {node: '>=10'}- peerDependencies:- seroval: ^1.0- dependencies:- seroval: 1.0.5- dev: false-- resolution: {integrity: sha512-TM+Z11tHHvQVQKeNlOUonOWnsNM+2IBwZ4vwoi4j3zKzIpc5IDw8WPwCfcc8F17wy6cBcJGbZbFOR0UCuTZHQA==}- engines: {node: '>=10'}- dev: false-resolution: {integrity: sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==}engines: {node: '>= 0.8.0'}@@ -18403,25 +18499,6 @@ packages:- utf-8-validatedev: false- resolution: {integrity: sha512-rja94MNU9flF3qQRLNsu60QHKBDKBkVE1DldJZPIfn2ypIn3NV2WpSbGTQIvsyGPBo+9E2IMjwqnqpbgfWuzeg==}- dependencies:- csstype: 3.1.3- seroval: 1.0.5- seroval-plugins: 1.0.5([email protected])- dev: false-- resolution: {integrity: sha512-A6d68aJmRP471aWqKKPE2tpgOiR5fH4qXQNfKIec+Vap+MGQm3tvXlT8n0I8UgJSlNAsSAUuw2VTviH2h3Vv5g==}- engines: {node: '>=10'}- peerDependencies:- solid-js: ^1.2- swr-store: ^0.10- dependencies:- solid-js: 1.8.16- swr-store: 0.10.6- dev: false-resolution: {integrity: sha512-+rOAO56b2eI3q5BtgljERSn2umRk63KFIvgb2ohbZ5X+Eb5u+a/7/0ZgswYqgBMg8dyl7n6OXd9KasA8QF9ToA==}peerDependencies:@@ -18537,10 +18614,10 @@ packages:engines: {node: '>= 0.6'}dev: false- resolution: {integrity: sha512-mV0kkeBHcjcb0M5NqKtKVg/uTIYNlIIniyDfSGrSfxpEdM9C365jK0z55pl9K0xAkNTJi2OAOVFQpgMPUk+V0w==}+ resolution: {integrity: sha512-Cqc355SYlTAaUt8iDPaC/4DPPXK925PePLMxyBKuWd5kKc5mwsG3nT9+Mq2tyguL5s7b4Jg+IRMpTRsNTAfpSQ==}peerDependencies:- svelte: ^4.0.0+ svelte: ^4.0.0 || ^5.0.0-next.0dependencies:svelte: 4.2.14swrev: 4.0.0@@ -18893,13 +18970,6 @@ packages:periscopic: 3.1.0dev: false- resolution: {integrity: sha512-xPjB1hARSiRaNNlUQvWSVrG5SirCjk2TmaUyzzvk69SZQan9hCJqw/5rG9iL7xElHU784GxRPISClq4488/XVw==}- engines: {node: '>=10'}- dependencies:- dequal: 2.0.3- dev: false-resolution: {integrity: sha512-/OhfZMcEpuz77KavXST5q6XE9nrOBOVcBLWjMT+oAE/kQHyE3PASrevXCtQDZ8aamntOfFkbVJp7Il9tNBQWrw==}peerDependencies:@@ -18909,17 +18979,18 @@ packages:use-sync-external-store: 1.2.0([email protected])dev: false- resolution: {integrity: sha512-AjqHOv2lAhkuUdIiBu9xbuettzAzWXmCEcLONNKJRba87WAefz8Ca9d6ds/SzrPc235n1IxWYdhJ2zF3MNUaoQ==}+ resolution: {integrity: sha512-njiZ/4RiIhoOlAaLYDqwz5qH/KZXVilRLvomrx83HjzCWTfa+InyfAjv05PSFxnmLzZkNO9ZfvgoqzAaEI4sGQ==}peerDependencies:react: ^16.11.0 || ^17.0.0 || ^18.0.0dependencies:+ client-only: 0.0.1react: 18.2.0use-sync-external-store: 1.2.0([email protected])dev: false- resolution: {integrity: sha512-njiZ/4RiIhoOlAaLYDqwz5qH/KZXVilRLvomrx83HjzCWTfa+InyfAjv05PSFxnmLzZkNO9ZfvgoqzAaEI4sGQ==}+ resolution: {integrity: sha512-QtxqyclFeAsxEUeZIYmsaQ0UjimSq1RZ9Un7I68/0ClKK/U3LoyQunwkQfJZr2fc22DfIXLNDc2wFyTEikCUpg==}peerDependencies:react: ^16.11.0 || ^17.0.0 || ^18.0.0dependencies: