├── .env.example ├── .eslintrc.json ├── .github └── workflows │ └── playwright.yml ├── .gitignore ├── README.md ├── next.config.js ├── package.json ├── playwright.config.ts ├── pnpm-lock.yaml ├── postcss.config.js ├── public ├── next.svg ├── pinecone.svg └── vercel.svg ├── src ├── app │ ├── api │ │ ├── chat │ │ │ └── route.ts │ │ ├── clearIndex │ │ │ └── route.ts │ │ ├── context │ │ │ └── route.ts │ │ └── crawl │ │ │ ├── crawler.ts │ │ │ ├── route.ts │ │ │ └── seed.ts │ ├── components │ │ ├── Chat │ │ │ ├── Messages.tsx │ │ │ └── index.tsx │ │ ├── Context │ │ │ ├── Button.tsx │ │ │ ├── Card.tsx │ │ │ ├── UrlButton.tsx │ │ │ ├── index.tsx │ │ │ ├── urls.ts │ │ │ └── utils.ts │ │ ├── Header.tsx │ │ └── InstructionModal.tsx │ ├── favicon.ico │ ├── globals.css │ ├── layout.tsx │ ├── page.tsx │ └── utils │ │ ├── chunkedUpsert.ts │ │ ├── context.ts │ │ ├── embeddings.ts │ │ ├── pinecone.ts │ │ └── truncateString.ts └── global.css ├── tailwind.config.js ├── tests └── example.spec.ts └── tsconfig.json /.env.example: -------------------------------------------------------------------------------- 1 | OPENAI_API_KEY= 2 | 3 | # Retrieve the following from the Pinecone Console. 4 | 5 | # Navigate to API Keys under your Project to retrieve the API key 6 | PINECONE_API_KEY= 7 | PINECONE_CLOUD= 8 | PINECONE_REGION= 9 | 10 | # Navigate to Indexes under your Project to retrieve the Index name 11 | PINECONE_INDEX= -------------------------------------------------------------------------------- /.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "next/core-web-vitals" 3 | } 4 | -------------------------------------------------------------------------------- /.github/workflows/playwright.yml: -------------------------------------------------------------------------------- 1 | name: Playwright Tests 2 | on: 3 | push: 4 | branches: 5 | - '**' 6 | pull_request: 7 | branches: 8 | - '**' 9 | workflow_dispatch: 10 | jobs: 11 | install: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v3 15 | - uses: actions/setup-node@v3 16 | with: 17 | node-version: 18 18 | - name: Setup pnpm 19 | uses: pnpm/action-setup@v3 20 | with: 21 | version: 9 # Specify the pnpm version here 22 | 23 | test: 24 | needs: install 25 | timeout-minutes: 60 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v3 29 | - uses: actions/setup-node@v3 30 | with: 31 | node-version: 18 32 | - name: Setup pnpm 33 | uses: pnpm/action-setup@v3 34 | with: 35 | version: 9 # Specify the pnpm version here 36 | - name: Install dependencies 37 | run: pnpm install 38 | - name: Build application 39 | run: pnpm run build 40 | - name: Start server 41 | run: pnpm start & 42 | - name: Install Playwright Browsers 43 | run: npx playwright install --with-deps 44 | - name: Run Playwright tests 45 | run: npx playwright test 46 | - uses: actions/upload-artifact@v3 47 | if: always() 48 | with: 49 | name: playwright-report 50 | path: playwright-report/ 51 | retention-days: 30 52 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # next.js 12 | /.next/ 13 | /out/ 14 | 15 | # production 16 | /build 17 | 18 | # misc 19 | .DS_Store 20 | *.pem 21 | 22 | # debug 23 | npm-debug.log* 24 | yarn-debug.log* 25 | yarn-error.log* 26 | 27 | # local env files 28 | .env*.local 29 | 30 | # vercel 31 | .vercel 32 | 33 | # typescript 34 | *.tsbuildinfo 35 | next-env.d.ts 36 | .env 37 | 38 | #pnpm 39 | /test-results/ 40 | /playwright-report/ 41 | /playwright/.cache/ 42 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | In this example, we'll build a full-stack application that uses Retrieval Augmented Generation (RAG) powered by [Pinecone](https://pinecone.io) to deliver accurate and contextually relevant responses in a chatbot. 2 | 3 | RAG is a powerful tool that combines the benefits of retrieval-based models and generative models. Unlike traditional chatbots that can struggle with maintaining up-to-date information or accessing domain-specific knowledge, a RAG-based chatbot uses a knowledge base created from crawled URLs to provide contextually relevant responses. 4 | 5 | Incorporating Vercel's AI SDK into our application will allow us easily set up the chatbot workflow and utilize streaming more efficiently, particularly in edge environments, enhancing the responsiveness and performance of our chatbot. 6 | 7 | By the end of this tutorial, you'll have a context-aware chatbot that provides accurate responses without hallucination, ensuring a more effective and engaging user experience. Let's get started on building this powerful tool ([Full code listing](https://github.com/pinecone-io/pinecone-vercel-example/blob/main/package.json)). 8 | 9 | ## Step 1: Setting Up Your Next.js Application 10 | 11 | Next.js is a powerful JavaScript framework that enables us to build server-side rendered and static web applications using React. It's a great choice for our project due to its ease of setup, excellent performance, and built-in features such as routing and API routes. 12 | 13 | To create a new Next.js app, run the following command: 14 | 15 | ### npx 16 | 17 | ```bash 18 | npx create-next-app chatbot 19 | ``` 20 | 21 | Next, we'll add the `ai` package: 22 | 23 | ```bash 24 | npm install ai 25 | ``` 26 | 27 | You can use the [full list](https://github.com/pinecone-io/pinecone-vercel-example/blob/main/package.json) of dependencies if you'd like to build along with the tutorial. 28 | 29 | ## Step 2: Create the Chatbot 30 | 31 | In this step, we're going to use the Vercel SDK to establish the backend and frontend of our chatbot within the Next.js application. By the end of this step, our basic chatbot will be up and running, ready for us to add context-aware capabilities in the following stages. Let's get started. 32 | 33 | ### Chatbot frontend component 34 | 35 | Now, let's focus on the frontend component of our chatbot. We're going to build the user-facing elements of our bot, creating the interface through which users will interact with our application. This will involve crafting the design and functionality of the chat interface within our Next.js application. 36 | 37 | First, we'll create the `Chat` component, that will render the chat interface. 38 | 39 | ```tsx 40 | import React, { FormEvent, ChangeEvent } from "react"; 41 | import Messages from "./Messages"; 42 | import { Message } from "ai/react"; 43 | 44 | interface Chat { 45 | input: string; 46 | handleInputChange: (e: ChangeEvent) => void; 47 | handleMessageSubmit: (e: FormEvent) => Promise; 48 | messages: Message[]; 49 | } 50 | 51 | const Chat: React.FC = ({ 52 | input, 53 | handleInputChange, 54 | handleMessageSubmit, 55 | messages, 56 | }) => { 57 | return ( 58 |
59 | 60 | <> 61 |
62 | 68 | 69 | Press ⮐ to send 70 |
71 | 72 |
73 | ); 74 | }; 75 | 76 | export default Chat; 77 | ``` 78 | 79 | This component will display the list of messages and the input form for the user to send messages. The `Messages` component to render the chat messages: 80 | 81 | ```tsx 82 | import { Message } from "ai"; 83 | import { useRef } from "react"; 84 | 85 | export default function Messages({ messages }: { messages: Message[] }) { 86 | const messagesEndRef = useRef(null); 87 | return ( 88 |
89 | {messages.map((msg, index) => ( 90 |
96 |
{msg.role === "assistant" ? "🤖" : "🧑‍💻"}
97 |
{msg.content}
98 |
99 | ))} 100 |
101 |
102 | ); 103 | } 104 | ``` 105 | 106 | Our main `Page` component will manage the state for the messages displayed in the `Chat` component: 107 | 108 | ```tsx 109 | "use client"; 110 | import Header from "@/components/Header"; 111 | import Chat from "@/components/Chat"; 112 | import { useChat } from "ai/react"; 113 | 114 | const Page: React.FC = () => { 115 | const [context, setContext] = useState(null); 116 | const { messages, input, handleInputChange, handleSubmit } = useChat(); 117 | 118 | return ( 119 |
120 |
121 |
122 | 128 |
129 |
130 | ); 131 | }; 132 | 133 | export default Page; 134 | ``` 135 | 136 | The useful `useChat` hook will manage the state for the messages displayed in the `Chat` component. It will: 137 | 138 | 1. Send the user's message to the backend 139 | 2. Update the state with the response from the backend 140 | 3. Handle any internal state changes (e.g. when the user types a message) 141 | 142 | ### Chatbot API endpoint 143 | 144 | Next, we'll set up the Chatbot API endpoint. This is the server-side component that will handle requests and responses for our chatbot. We'll create a new file called `api/chat/route.ts` and add the following dependencies: 145 | 146 | ```ts 147 | import { Configuration, OpenAIApi } from "openai-edge"; 148 | import { Message, OpenAIStream, StreamingTextResponse } from "ai"; 149 | ``` 150 | 151 | The first dependency is the `openai-edge` package which makes it easier to interact with OpenAI's APIs in an edge environment. The second dependency is the `ai` package which we'll use to define the `Message` and `OpenAIStream` types, which we'll use to stream back the response from OpenAI back to the client. 152 | 153 | Next initialize the OpenAI client: 154 | 155 | ```ts 156 | // Create an OpenAI API client (that's edge friendly!) 157 | const config = new Configuration({ 158 | apiKey: process.env.OPENAI_API_KEY, 159 | }); 160 | const openai = new OpenAIApi(config); 161 | ``` 162 | 163 | To define this endpoint as an edge function, we'll define and export the `runtime` variable 164 | 165 | ```ts 166 | export const runtime = "edge"; 167 | ``` 168 | 169 | Next, we'll define the endpoint handler: 170 | 171 | ```ts 172 | export async function POST(req: Request) { 173 | try { 174 | const { messages } = await req.json(); 175 | 176 | const prompt = [ 177 | { 178 | role: "system", 179 | content: `AI assistant is a brand new, powerful, human-like artificial intelligence. 180 | The traits of AI include expert knowledge, helpfulness, cleverness, and articulateness. 181 | AI is a well-behaved and well-mannered individual. 182 | AI is always friendly, kind, and inspiring, and he is eager to provide vivid and thoughtful responses to the user. 183 | AI has the sum of all knowledge in their brain, and is able to accurately answer nearly any question about any topic in conversation. 184 | AI assistant is a big fan of Pinecone and Vercel. 185 | `, 186 | }, 187 | ]; 188 | 189 | // Ask OpenAI for a streaming chat completion given the prompt 190 | const response = await openai.createChatCompletion({ 191 | model: "gpt-3.5-turbo", 192 | stream: true, 193 | messages: [ 194 | ...prompt, 195 | ...messages.filter((message: Message) => message.role === "user"), 196 | ], 197 | }); 198 | // Convert the response into a friendly text-stream 199 | const stream = OpenAIStream(response); 200 | // Respond with the stream 201 | return new StreamingTextResponse(stream); 202 | } catch (e) { 203 | throw e; 204 | } 205 | } 206 | ``` 207 | 208 | Here we deconstruct the messages from the post, and create our initial prompt. We use the prompt and the messages as the input to the `createChatCompletion` method. We then convert the response into a stream and return it to the client. Note that in this example, we only send the user's messages to OpenAI (as opposed to including the bot's messages as well). 209 | 210 | 211 | 212 | ## Step 3. Adding Context 213 | 214 | As we dive into building our chatbot, it's important to understand the role of context. Adding context to our chatbot's responses is key for creating a more natural, conversational user experience. Without context, a chatbot's responses can feel disjointed or irrelevant. By understanding the context of a user's query, our chatbot will be able to provide more accurate, relevant, and engaging responses. Now, let's begin building with this goal in mind. 215 | 216 | First, we'll first focus on seeding the knowledge base. We'll create a crawler and a seed script, and set up a crawl endpoint. This will allow us to gather and organize the information our chatbot will use to provide contextually relevant responses. 217 | 218 | After we've populated our knowledge base, we'll retrieve matches from our embeddings. This will enable our chatbot to find relevant information based on user queries. 219 | 220 | Next, we'll wrap our logic into the getContext function and update our chatbot's prompt. This will streamline our code and improve the user experience by ensuring the chatbot's prompts are relevant and engaging. 221 | 222 | Finally, we'll add a context panel and an associated context endpoint. These will provide a user interface for the chatbot and a way for it to retrieve the necessary context for each user query. 223 | 224 | This step is all about feeding our chatbot the information it needs and setting up the necessary infrastructure for it to retrieve and use that information effectively. Let's get started. 225 | 226 | ## Seeding the Knowledge Base 227 | 228 | Now we'll move on to seeding the knowledge base, the foundational data source that will inform our chatbot's responses. This step involves collecting and organizing the information our chatbot needs to operate effectively. In this guide, we're going to use data retrieved from various websites which we'll later on be able to ask questions about. To do this, we'll create a crawler that will scrape the data from the websites, embed it, and store it in Pinecone. 229 | 230 | ### Create the crawler 231 | 232 | For the sake of brevity, you'll be able to find the full code for the crawler here. Here are the pertinent parts: 233 | 234 | ```ts 235 | class Crawler { 236 | private seen = new Set(); 237 | private pages: Page[] = []; 238 | private queue: { url: string; depth: number }[] = []; 239 | 240 | constructor(private maxDepth = 2, private maxPages = 1) {} 241 | 242 | async crawl(startUrl: string): Promise { 243 | // Add the start URL to the queue 244 | this.addToQueue(startUrl); 245 | 246 | // While there are URLs in the queue and we haven't reached the maximum number of pages... 247 | while (this.shouldContinueCrawling()) { 248 | // Dequeue the next URL and depth 249 | const { url, depth } = this.queue.shift()!; 250 | 251 | // If the depth is too great or we've already seen this URL, skip it 252 | if (this.isTooDeep(depth) || this.isAlreadySeen(url)) continue; 253 | 254 | // Add the URL to the set of seen URLs 255 | this.seen.add(url); 256 | 257 | // Fetch the page HTML 258 | const html = await this.fetchPage(url); 259 | 260 | // Parse the HTML and add the page to the list of crawled pages 261 | this.pages.push({ url, content: this.parseHtml(html) }); 262 | 263 | // Extract new URLs from the page HTML and add them to the queue 264 | this.addNewUrlsToQueue(this.extractUrls(html, url), depth); 265 | } 266 | 267 | // Return the list of crawled pages 268 | return this.pages; 269 | } 270 | 271 | // ... Some private methods removed for brevity 272 | 273 | private async fetchPage(url: string): Promise { 274 | try { 275 | const response = await fetch(url); 276 | return await response.text(); 277 | } catch (error) { 278 | console.error(`Failed to fetch ${url}: ${error}`); 279 | return ""; 280 | } 281 | } 282 | 283 | private parseHtml(html: string): string { 284 | const $ = cheerio.load(html); 285 | $("a").removeAttr("href"); 286 | return NodeHtmlMarkdown.translate($.html()); 287 | } 288 | 289 | private extractUrls(html: string, baseUrl: string): string[] { 290 | const $ = cheerio.load(html); 291 | const relativeUrls = $("a") 292 | .map((_, link) => $(link).attr("href")) 293 | .get() as string[]; 294 | return relativeUrls.map( 295 | (relativeUrl) => new URL(relativeUrl, baseUrl).href 296 | ); 297 | } 298 | } 299 | ``` 300 | 301 | The `Crawler` class is a web crawler that visits URLs, starting from a given point, and collects information from them. It operates within a certain depth and a maximum number of pages as defined in the constructor. The crawl method is the core function that starts the crawling process. 302 | 303 | The helper methods fetchPage, parseHtml, and extractUrls respectively handle fetching the HTML content of a page, parsing the HTML to extract text, and extracting all URLs from a page to be queued for the next crawl. The class also maintains a record of visited URLs to avoid duplication. 304 | 305 | ### Create the `seed` function 306 | 307 | To tie things together, we'll create a seed function that will use the crawler to seed the knowledge base. In this portion of the code, we'll initialize the crawl and fetch a given URL, then split it's content into chunks, and finally embed and index the chunks in Pinecone. 308 | 309 | ```ts 310 | async function seed(url: string, limit: number, indexName: string, options: SeedOptions) { 311 | try { 312 | // Initialize the Pinecone client 313 | const pinecone = new Pinecone(); 314 | 315 | // Destructure the options object 316 | const { splittingMethod, chunkSize, chunkOverlap } = options; 317 | 318 | // Create a new Crawler with depth 1 and maximum pages as limit 319 | const crawler = new Crawler(1, limit || 100); 320 | 321 | // Crawl the given URL and get the pages 322 | const pages = await crawler.crawl(url) as Page[]; 323 | 324 | // Choose the appropriate document splitter based on the splitting method 325 | const splitter: DocumentSplitter = splittingMethod === 'recursive' ? 326 | new RecursiveCharacterTextSplitter({ chunkSize, chunkOverlap }) : new MarkdownTextSplitter({}); 327 | 328 | // Prepare documents by splitting the pages 329 | const documents = await Promise.all(pages.map(page => prepareDocument(page, splitter))); 330 | 331 | // Create Pinecone index if it does not exist 332 | const indexList = await pinecone.listIndexes(); 333 | const indexExists = indexList.some(index => index.name === indexName) 334 | if (!indexExists) { 335 | await pinecone.createIndex({ 336 | name: indexName, 337 | dimension: 1536, 338 | waitUntilReady: true, 339 | }); 340 | } 341 | 342 | const index = pinecone.Index(indexName) 343 | 344 | // Get the vector embeddings for the documents 345 | const vectors = await Promise.all(documents.flat().map(embedDocument)); 346 | 347 | // Upsert vectors into the Pinecone index 348 | await chunkedUpsert(index!, vectors, '', 10); 349 | 350 | // Return the first document 351 | return documents[0]; 352 | } catch (error) { 353 | console.error("Error seeding:", error); 354 | throw error; 355 | } 356 | } 357 | ``` 358 | 359 | To chunk the content we'll use one of the following methods: 360 | 361 | 1. `RecursiveCharacterTextSplitter` - This splitter splits the text into chunks of a given size, and then recursively splits the chunks into smaller chunks until the chunk size is reached. This method is useful for long documents. 362 | 2. `MarkdownTextSplitter` - This splitter splits the text into chunks based on Markdown headers. This method is useful for documents that are already structured using Markdown. The benefit of this method is that it will split the document into chunks based on the headers, which will be useful for our chatbot to understand the structure of the document. We can assume that each unit of text under a header is an internally coherent unit of information, and when the user asks a question, the retrieved context will be internally coherent as well. 363 | 364 | ### Add the `crawl` endpoint` 365 | 366 | The endpoint for the `crawl` endpoint is pretty straightforward. It simply calls the `seed` function and returns the result. 367 | 368 | ```ts 369 | import seed from "./seed"; 370 | import { NextResponse } from "next/server"; 371 | 372 | export const runtime = "edge"; 373 | 374 | export async function POST(req: Request) { 375 | const { url, options } = await req.json(); 376 | try { 377 | const documents = await seed(url, 1, process.env.PINECONE_INDEX!, options); 378 | return NextResponse.json({ success: true, documents }); 379 | } catch (error) { 380 | return NextResponse.json({ success: false, error: "Failed crawling" }); 381 | } 382 | } 383 | ``` 384 | 385 | Now our backend is able to crawl a given URL, embed the content and index the embeddings in Pinecone. The endpoint will return all the segments in the retrieved webpage we crawl, so we'll be able to display them. Next, we'll write a set of functions that will build the context out of these embeddings. 386 | 387 | ### Get matches from embeddings 388 | 389 | To retrieve the most relevant documents from the index, we'll use the `query` function in the Pinecone SDK. This function takes a vector and returns the most similar vectors from the index. We'll use this function to retrieve the most relevant documents from the index, given some embeddings. 390 | 391 | ```ts 392 | const getMatchesFromEmbeddings = async (embeddings: number[], topK: number, namespace: string): Promise[]> => { 393 | // Obtain a client for Pinecone 394 | const pinecone = new Pinecone(); 395 | 396 | const indexName: string = process.env.PINECONE_INDEX || ''; 397 | if (indexName === '') { 398 | throw new Error('PINECONE_INDEX environment variable not set') 399 | } 400 | 401 | // Retrieve the list of indexes to check if expected index exists 402 | const indexes = await pinecone.listIndexes() 403 | if (indexes.filter(i => i.name === indexName).length !== 1) { 404 | throw new Error(`Index ${indexName} does not exist`) 405 | } 406 | 407 | // Get the Pinecone index 408 | const index = pinecone!.Index(indexName); 409 | 410 | // Get the namespace 411 | const pineconeNamespace = index.namespace(namespace ?? '') 412 | 413 | try { 414 | // Query the index with the defined request 415 | const queryResult = await pineconeNamespace.query({ 416 | vector: embeddings, 417 | topK, 418 | includeMetadata: true, 419 | }) 420 | return queryResult.matches || [] 421 | } catch (e) { 422 | // Log the error and throw it 423 | console.log("Error querying embeddings: ", e) 424 | throw new Error(`Error querying embeddings: ${e}`) 425 | } 426 | } 427 | ``` 428 | 429 | The function takes in embeddings, a topK parameter, and a namespace, and returns the topK matches from the Pinecone index. It first gets a Pinecone client, checks if the desired index exists in the list of indexes, and throws an error if not. Then it gets the specific Pinecone index. The function then queries the Pinecone index with the defined request and returns the matches. 430 | 431 | ### Wrap things up in `getContext` 432 | 433 | We'll wrap things together in the `getContext` function. This function will take in a `message` and return the context - either in string form, or as a set of `ScoredVector`. 434 | 435 | ```ts 436 | export const getContext = async ( 437 | message: string, 438 | namespace: string, 439 | maxTokens = 3000, 440 | minScore = 0.7, 441 | getOnlyText = true 442 | ): Promise => { 443 | // Get the embeddings of the input message 444 | const embedding = await getEmbeddings(message); 445 | 446 | // Retrieve the matches for the embeddings from the specified namespace 447 | const matches = await getMatchesFromEmbeddings(embedding, 3, namespace); 448 | 449 | // Filter out the matches that have a score lower than the minimum score 450 | const qualifyingDocs = matches.filter((m) => m.score && m.score > minScore); 451 | 452 | // If the `getOnlyText` flag is false, we'll return the matches 453 | if (!getOnlyText) { 454 | return qualifyingDocs; 455 | } 456 | 457 | let docs = matches 458 | ? qualifyingDocs.map((match) => (match.metadata as Metadata).chunk) 459 | : []; 460 | // Join all the chunks of text together, truncate to the maximum number of tokens, and return the result 461 | return docs.join("\n").substring(0, maxTokens); 462 | }; 463 | ``` 464 | 465 | Back in `chat/route.ts`, we'll add the call to `getContext`: 466 | 467 | ```ts 468 | const { messages } = await req.json(); 469 | 470 | // Get the last message 471 | const lastMessage = messages[messages.length - 1]; 472 | 473 | // Get the context from the last message 474 | const context = await getContext(lastMessage.content, ""); 475 | ``` 476 | 477 | ### Update the prompt 478 | 479 | Finally, we'll update the prompt to include the context we retrieved from the `getContext` function. 480 | 481 | ```ts 482 | const prompt = [ 483 | { 484 | role: "system", 485 | content: `AI assistant is a brand new, powerful, human-like artificial intelligence. 486 | The traits of AI include expert knowledge, helpfulness, cleverness, and articulateness. 487 | AI is a well-behaved and well-mannered individual. 488 | AI is always friendly, kind, and inspiring, and he is eager to provide vivid and thoughtful responses to the user. 489 | AI has the sum of all knowledge in their brain, and is able to accurately answer nearly any question about any topic in conversation. 490 | AI assistant is a big fan of Pinecone and Vercel. 491 | START CONTEXT BLOCK 492 | ${context} 493 | END OF CONTEXT BLOCK 494 | AI assistant will take into account any CONTEXT BLOCK that is provided in a conversation. 495 | If the context does not provide the answer to question, the AI assistant will say, "I'm sorry, but I don't know the answer to that question". 496 | AI assistant will not apologize for previous responses, but instead will indicated new information was gained. 497 | AI assistant will not invent anything that is not drawn directly from the context. 498 | `, 499 | }, 500 | ]; 501 | ``` 502 | 503 | In this prompt, we added a `START CONTEXT BLOCK` and `END OF CONTEXT BLOCK` to indicate where the context should be inserted. We also added a line to indicate that the AI assistant will take into account any context block that is provided in a conversation. 504 | 505 | ### Add the context panel 506 | 507 | Next, we need to add the context panel to the chat UI. We'll add a new component called `Context` ([full code](https://github.com/pinecone-io/pinecone-vercel-example/tree/main/src/app/components/Context)). 508 | 509 | ### Add the context endpoint 510 | 511 | We want to allow interface to indicate which portions of the retrieved content have been used to generate the response. To do this, we'll add a another endpoint that will call the same `getContext`. 512 | 513 | ```ts 514 | export async function POST(req: Request) { 515 | try { 516 | const { messages } = await req.json(); 517 | const lastMessage = 518 | messages.length > 1 ? messages[messages.length - 1] : messages[0]; 519 | const context = (await getContext( 520 | lastMessage.content, 521 | "", 522 | 10000, 523 | 0.7, 524 | false 525 | )) as ScoredPineconeRecord[]; 526 | return NextResponse.json({ context }); 527 | } catch (e) { 528 | console.log(e); 529 | return NextResponse.error(); 530 | } 531 | } 532 | ``` 533 | 534 | Whenever the user crawls a URL, the context panel will display all the segments of the retrieved webpage. Whenever the backend completes sending a message back, the front end will trigger an effect that will retrieve this context: 535 | 536 | ```tsx 537 | useEffect(() => { 538 | const getContext = async () => { 539 | const response = await fetch("/api/context", { 540 | method: "POST", 541 | body: JSON.stringify({ 542 | messages, 543 | }), 544 | }); 545 | const { context } = await response.json(); 546 | setContext(context.map((c: any) => c.id)); 547 | }; 548 | if (gotMessages && messages.length >= prevMessagesLengthRef.current) { 549 | getContext(); 550 | } 551 | 552 | prevMessagesLengthRef.current = messages.length; 553 | }, [messages, gotMessages]); 554 | ``` 555 | 556 | ## Running tests 557 | 558 | The pinecone-vercel-starter uses [Playwright](https://playwright.dev) for end to end testing. 559 | 560 | To run all the tests: 561 | 562 | ``` 563 | npm run test:e2e 564 | ``` 565 | 566 | By default, when running locally, if errors are encountered, Playwright will open an HTML report showing which 567 | tests failed and for which browser drivers. 568 | 569 | ## Displaying test reports locally 570 | 571 | To display the latest test report locally, run: 572 | ``` 573 | npm run test:show 574 | ``` 575 | 576 | -------------------------------------------------------------------------------- /next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = {}; 3 | 4 | module.exports = nextConfig; 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vercel-pinecone-template", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint", 10 | "test:e2e": "playwright test", 11 | "test:show": "playwright show-report" 12 | }, 13 | "dependencies": { 14 | "@ai-sdk/openai": "^0.0.60", 15 | "@pinecone-database/doc-splitter": "^0.0.1", 16 | "@pinecone-database/pinecone": "^3.0.3", 17 | "ai": "^3.3.39", 18 | "cheerio": "^1.0.0", 19 | "md5": "^2.3.0", 20 | "next": "^14.2.11", 21 | "node-html-markdown": "^1.3.0", 22 | "openai-edge": "^1.2.2", 23 | "react": "18.3.1", 24 | "react-dom": "18.3.1", 25 | "react-icons": "^5.3.0", 26 | "react-markdown": "^9.0.1", 27 | "sswr": "^2.1.0", 28 | "svelte": "^4.2.19", 29 | "tailwindcss": "3.4.11", 30 | "typescript": "5.6.2", 31 | "unified": "^11.0.5", 32 | "vue": "^3.5.6", 33 | "eslint": "^8.0.0", 34 | "eslint-config-next": "14.2.11" 35 | }, 36 | "devDependencies": { 37 | "@playwright/test": "^1.47.1", 38 | "@types/md5": "^2.3.5", 39 | "@types/node": "22.5.5", 40 | "@types/react": "18.3.6", 41 | "@types/react-dom": "18.3.0" 42 | } 43 | } -------------------------------------------------------------------------------- /playwright.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig, devices } from '@playwright/test'; 2 | 3 | /** 4 | * Read environment variables from file. 5 | * https://github.com/motdotla/dotenv 6 | */ 7 | // require('dotenv').config(); 8 | 9 | /** 10 | * See https://playwright.dev/docs/test-configuration. 11 | */ 12 | export default defineConfig({ 13 | testDir: './tests', 14 | /* Run tests in files in parallel */ 15 | fullyParallel: true, 16 | /* Fail the build on CI if you accidentally left test.only in the source code. */ 17 | forbidOnly: !!process.env.CI, 18 | /* Retry on CI only */ 19 | retries: process.env.CI ? 2 : 0, 20 | /* Opt out of parallel tests on CI. */ 21 | workers: process.env.CI ? 1 : undefined, 22 | /* Reporter to use. See https://playwright.dev/docs/test-reporters */ 23 | reporter: 'html', 24 | /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ 25 | use: { 26 | /* Base URL to use in actions like `await page.goto('/')`. */ 27 | // baseURL: 'http://127.0.0.1:3000', 28 | 29 | /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ 30 | trace: 'on-first-retry', 31 | }, 32 | 33 | /* Configure projects for major browsers */ 34 | projects: [ 35 | { 36 | name: 'chromium', 37 | use: { ...devices['Desktop Chrome'] }, 38 | }, 39 | 40 | { 41 | name: 'firefox', 42 | use: { ...devices['Desktop Firefox'] }, 43 | }, 44 | 45 | { 46 | name: 'webkit', 47 | use: { ...devices['Desktop Safari'] }, 48 | }, 49 | 50 | /* Test against mobile viewports. */ 51 | // { 52 | // name: 'Mobile Chrome', 53 | // use: { ...devices['Pixel 5'] }, 54 | // }, 55 | // { 56 | // name: 'Mobile Safari', 57 | // use: { ...devices['iPhone 12'] }, 58 | // }, 59 | 60 | /* Test against branded browsers. */ 61 | // { 62 | // name: 'Microsoft Edge', 63 | // use: { ...devices['Desktop Edge'], channel: 'msedge' }, 64 | // }, 65 | // { 66 | // name: 'Google Chrome', 67 | // use: { ...devices['Desktop Chrome'], channel: 'chrome' }, 68 | // }, 69 | ], 70 | 71 | /* Run your local dev server before starting the tests */ 72 | // webServer: { 73 | // command: 'npm run start', 74 | // url: 'http://127.0.0.1:3000', 75 | // reuseExistingServer: !process.env.CI, 76 | // }, 77 | }); 78 | -------------------------------------------------------------------------------- /postcss.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | plugins: { 3 | tailwindcss: {}, 4 | }, 5 | }; 6 | -------------------------------------------------------------------------------- /public/next.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /public/pinecone.svg: -------------------------------------------------------------------------------- 1 | 7 | 8 | 13 | 18 | 23 | 28 | 33 | 38 | 43 | 48 | 54 | 61 | 67 | 74 | 80 | 87 | 94 | 95 | 96 | 101 | 102 | 107 | 108 | 113 | 114 | 119 | 120 | 125 | 126 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /public/vercel.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/api/chat/route.ts: -------------------------------------------------------------------------------- 1 | 2 | import { Message } from 'ai' 3 | import { getContext } from '@/utils/context' 4 | import { openai } from '@ai-sdk/openai'; 5 | import { streamText } from 'ai'; 6 | 7 | // IMPORTANT! Set the runtime to edge 8 | export const runtime = 'edge' 9 | 10 | export async function POST(req: Request) { 11 | try { 12 | 13 | const { messages } = await req.json() 14 | 15 | // Get the last message 16 | const lastMessage = messages[messages.length - 1] 17 | 18 | // Get the context from the last message 19 | const context = await getContext(lastMessage.content, '') 20 | 21 | const prompt = [ 22 | { 23 | role: 'system', 24 | content: `AI assistant is a brand new, powerful, human-like artificial intelligence. 25 | The traits of AI include expert knowledge, helpfulness, cleverness, and articulateness. 26 | AI is a well-behaved and well-mannered individual. 27 | AI is always friendly, kind, and inspiring, and he is eager to provide vivid and thoughtful responses to the user. 28 | AI has the sum of all knowledge in their brain, and is able to accurately answer nearly any question about any topic in conversation. 29 | AI assistant is a big fan of Pinecone and Vercel. 30 | START CONTEXT BLOCK 31 | ${context} 32 | END OF CONTEXT BLOCK 33 | AI assistant will take into account any CONTEXT BLOCK that is provided in a conversation. 34 | If the context does not provide the answer to question, the AI assistant will say, "I'm sorry, but I don't know the answer to that question". 35 | AI assistant will not apologize for previous responses, but instead will indicated new information was gained. 36 | AI assistant will not invent anything that is not drawn directly from the context. 37 | `, 38 | }, 39 | ] 40 | 41 | const result = await streamText({ 42 | model: openai("gpt-4o"), 43 | messages: [...prompt,...messages.filter((message: Message) => message.role === 'user')] 44 | }); 45 | 46 | return result.toDataStreamResponse(); 47 | } catch (e) { 48 | throw (e) 49 | } 50 | } -------------------------------------------------------------------------------- /src/app/api/clearIndex/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from "next/server"; 2 | import { Pinecone } from '@pinecone-database/pinecone' 3 | 4 | export async function POST() { 5 | // Instantiate a new Pinecone client 6 | const pinecone = new Pinecone(); 7 | // Select the desired index 8 | const index = pinecone.Index(process.env.PINECONE_INDEX!) 9 | 10 | // Use the custom namespace, if provided, otherwise use the default 11 | const namespaceName = process.env.PINECONE_NAMESPACE ?? '' 12 | const namespace = index.namespace(namespaceName) 13 | 14 | // Delete everything within the namespace 15 | await namespace.deleteAll(); 16 | 17 | return NextResponse.json({ 18 | success: true 19 | }) 20 | } 21 | -------------------------------------------------------------------------------- /src/app/api/context/route.ts: -------------------------------------------------------------------------------- 1 | import { NextResponse } from "next/server"; 2 | import { getContext } from "@/utils/context"; 3 | import { ScoredPineconeRecord } from "@pinecone-database/pinecone"; 4 | 5 | export async function POST(req: Request) { 6 | try { 7 | const { messages } = await req.json() 8 | const lastMessage = messages.length > 1 ? messages[messages.length - 1] : messages[0] 9 | const context = await getContext(lastMessage.content, '', 10000, 0.7, false) as ScoredPineconeRecord[] 10 | return NextResponse.json({ context }) 11 | } catch (e) { 12 | console.log(e) 13 | return NextResponse.error() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /src/app/api/crawl/crawler.ts: -------------------------------------------------------------------------------- 1 | import * as cheerio from 'cheerio'; 2 | import { NodeHtmlMarkdown } from 'node-html-markdown'; 3 | 4 | interface Page { 5 | url: string; 6 | content: string; 7 | } 8 | 9 | class Crawler { 10 | private seen = new Set(); 11 | private pages: Page[] = []; 12 | private queue: { url: string; depth: number }[] = []; 13 | 14 | constructor(private maxDepth = 2, private maxPages = 1) { } 15 | 16 | async crawl(startUrl: string): Promise { 17 | // Add the start URL to the queue 18 | this.addToQueue(startUrl); 19 | 20 | // While there are URLs in the queue and we haven't reached the maximum number of pages... 21 | while (this.shouldContinueCrawling()) { 22 | // Dequeue the next URL and depth 23 | const { url, depth } = this.queue.shift()!; 24 | 25 | // If the depth is too great or we've already seen this URL, skip it 26 | if (this.isTooDeep(depth) || this.isAlreadySeen(url)) continue; 27 | 28 | // Add the URL to the set of seen URLs 29 | this.seen.add(url); 30 | 31 | // Fetch the page HTML 32 | const html = await this.fetchPage(url); 33 | 34 | // Parse the HTML and add the page to the list of crawled pages 35 | this.pages.push({ url, content: this.parseHtml(html) }); 36 | 37 | // Extract new URLs from the page HTML and add them to the queue 38 | this.addNewUrlsToQueue(this.extractUrls(html, url), depth); 39 | } 40 | 41 | // Return the list of crawled pages 42 | return this.pages; 43 | } 44 | 45 | private isTooDeep(depth: number) { 46 | return depth > this.maxDepth; 47 | } 48 | 49 | private isAlreadySeen(url: string) { 50 | return this.seen.has(url); 51 | } 52 | 53 | private shouldContinueCrawling() { 54 | return this.queue.length > 0 && this.pages.length < this.maxPages; 55 | } 56 | 57 | private addToQueue(url: string, depth = 0) { 58 | this.queue.push({ url, depth }); 59 | } 60 | 61 | private addNewUrlsToQueue(urls: string[], depth: number) { 62 | this.queue.push(...urls.map(url => ({ url, depth: depth + 1 }))); 63 | } 64 | 65 | private async fetchPage(url: string): Promise { 66 | try { 67 | const response = await fetch(url); 68 | return await response.text(); 69 | } catch (error) { 70 | console.error(`Failed to fetch ${url}: ${error}`); 71 | return ''; 72 | } 73 | } 74 | 75 | private parseHtml(html: string): string { 76 | const $ = cheerio.load(html); 77 | $('a').removeAttr('href'); 78 | return NodeHtmlMarkdown.translate($.html()); 79 | } 80 | 81 | private extractUrls(html: string, baseUrl: string): string[] { 82 | const $ = cheerio.load(html); 83 | const relativeUrls = $('a').map((_, link) => $(link).attr('href')).get() as string[]; 84 | return relativeUrls.map(relativeUrl => new URL(relativeUrl, baseUrl).href); 85 | } 86 | } 87 | 88 | export { Crawler }; 89 | export type { Page }; 90 | -------------------------------------------------------------------------------- /src/app/api/crawl/route.ts: -------------------------------------------------------------------------------- 1 | import seed from './seed' 2 | import { NextResponse } from 'next/server'; 3 | import { ServerlessSpecCloudEnum } from '@pinecone-database/pinecone' 4 | 5 | export const runtime = 'edge' 6 | 7 | export async function POST(req: Request) { 8 | 9 | const { url, options } = await req.json() 10 | try { 11 | const documents = await seed( 12 | url, 13 | 1, 14 | process.env.PINECONE_INDEX!, 15 | process.env.PINECONE_CLOUD as ServerlessSpecCloudEnum || 'aws', 16 | process.env.PINECONE_REGION || 'us-west-2', 17 | options 18 | ) 19 | return NextResponse.json({ success: true, documents }) 20 | } catch (error) { 21 | return NextResponse.json({ success: false, error: "Failed crawling" }) 22 | } 23 | } -------------------------------------------------------------------------------- /src/app/api/crawl/seed.ts: -------------------------------------------------------------------------------- 1 | import { getEmbeddings } from "@/utils/embeddings"; 2 | import { Document, MarkdownTextSplitter, RecursiveCharacterTextSplitter } from "@pinecone-database/doc-splitter"; 3 | import { Pinecone, PineconeRecord, ServerlessSpecCloudEnum } from "@pinecone-database/pinecone"; 4 | import { chunkedUpsert } from '../../utils/chunkedUpsert' 5 | import md5 from "md5"; 6 | import { Crawler, Page } from "./crawler"; 7 | import { truncateStringByBytes } from "@/utils/truncateString" 8 | 9 | interface SeedOptions { 10 | splittingMethod: string 11 | chunkSize: number 12 | chunkOverlap: number 13 | } 14 | 15 | type DocumentSplitter = RecursiveCharacterTextSplitter | MarkdownTextSplitter 16 | 17 | async function seed(url: string, limit: number, indexName: string, cloudName: ServerlessSpecCloudEnum, regionName: string, options: SeedOptions) { 18 | try { 19 | // Initialize the Pinecone client 20 | const pinecone = new Pinecone(); 21 | 22 | // Destructure the options object 23 | const { splittingMethod, chunkSize, chunkOverlap } = options; 24 | 25 | // Create a new Crawler with depth 1 and maximum pages as limit 26 | const crawler = new Crawler(1, limit || 100); 27 | 28 | // Crawl the given URL and get the pages 29 | const pages = await crawler.crawl(url) as Page[]; 30 | 31 | // Choose the appropriate document splitter based on the splitting method 32 | const splitter: DocumentSplitter = splittingMethod === 'recursive' ? 33 | new RecursiveCharacterTextSplitter({ chunkSize, chunkOverlap }) : new MarkdownTextSplitter({}); 34 | 35 | // Prepare documents by splitting the pages 36 | const documents = await Promise.all(pages.map(page => prepareDocument(page, splitter))); 37 | 38 | // Create Pinecone index if it does not exist 39 | const indexList: string[] = (await pinecone.listIndexes())?.indexes?.map(index => index.name) || []; 40 | const indexExists = indexList.includes(indexName); 41 | if (!indexExists) { 42 | await pinecone.createIndex({ 43 | name: indexName, 44 | dimension: 1536, 45 | waitUntilReady: true, 46 | spec: { 47 | serverless: { 48 | cloud: cloudName, 49 | region: regionName 50 | } 51 | } 52 | }); 53 | } 54 | 55 | const index = pinecone.Index(indexName) 56 | 57 | // Get the vector embeddings for the documents 58 | const vectors = await Promise.all(documents.flat().map(embedDocument)); 59 | 60 | // Upsert vectors into the Pinecone index 61 | await chunkedUpsert(index!, vectors, '', 10); 62 | 63 | // Return the first document 64 | return documents[0]; 65 | } catch (error) { 66 | console.error("Error seeding:", error); 67 | throw error; 68 | } 69 | } 70 | 71 | async function embedDocument(doc: Document): Promise { 72 | try { 73 | // Generate OpenAI embeddings for the document content 74 | const embedding = await getEmbeddings(doc.pageContent); 75 | 76 | // Create a hash of the document content 77 | const hash = md5(doc.pageContent); 78 | 79 | // Return the vector embedding object 80 | return { 81 | id: hash, // The ID of the vector is the hash of the document content 82 | values: embedding, // The vector values are the OpenAI embeddings 83 | metadata: { // The metadata includes details about the document 84 | chunk: doc.pageContent, // The chunk of text that the vector represents 85 | text: doc.metadata.text as string, // The text of the document 86 | url: doc.metadata.url as string, // The URL where the document was found 87 | hash: doc.metadata.hash as string // The hash of the document content 88 | } 89 | } as PineconeRecord; 90 | } catch (error) { 91 | console.log("Error embedding document: ", error) 92 | throw error 93 | } 94 | } 95 | 96 | async function prepareDocument(page: Page, splitter: DocumentSplitter): Promise { 97 | // Get the content of the page 98 | const pageContent = page.content; 99 | 100 | // Split the documents using the provided splitter 101 | const docs = await splitter.splitDocuments([ 102 | new Document({ 103 | pageContent, 104 | metadata: { 105 | url: page.url, 106 | // Truncate the text to a maximum byte length 107 | text: truncateStringByBytes(pageContent, 36000) 108 | }, 109 | }), 110 | ]); 111 | 112 | // Map over the documents and add a hash to their metadata 113 | return docs.map((doc: Document) => { 114 | return { 115 | pageContent: doc.pageContent, 116 | metadata: { 117 | ...doc.metadata, 118 | // Create a hash of the document content 119 | hash: md5(doc.pageContent) 120 | }, 121 | }; 122 | }); 123 | } 124 | 125 | 126 | 127 | 128 | export default seed; -------------------------------------------------------------------------------- /src/app/components/Chat/Messages.tsx: -------------------------------------------------------------------------------- 1 | import { Message } from "ai"; 2 | import { useRef } from "react"; 3 | 4 | export default function Messages({ messages }: { messages: Message[] }) { 5 | const messagesEndRef = useRef(null); 6 | return ( 7 |
8 | {messages.map((msg, index) => ( 9 |
15 |
16 | {msg.role === "assistant" ? "🤖" : "🧑‍💻"} 17 |
18 |
19 | {msg.content} 20 |
21 |
22 | ))} 23 |
24 |
25 | ); 26 | } 27 | -------------------------------------------------------------------------------- /src/app/components/Chat/index.tsx: -------------------------------------------------------------------------------- 1 | // Chat.tsx 2 | 3 | import React, { FormEvent, ChangeEvent } from "react"; 4 | import Messages from "./Messages"; 5 | import { Message, useChat } from "ai/react"; 6 | 7 | const Chat: React.FC = () => { 8 | const { messages, input, handleInputChange, handleSubmit } = useChat(); 9 | 10 | return ( 11 |
12 | 13 |
17 | 23 | 24 | Press ⮐ to send 25 | 26 |
27 |
28 | ); 29 | }; 30 | 31 | export default Chat; 32 | -------------------------------------------------------------------------------- /src/app/components/Context/Button.tsx: -------------------------------------------------------------------------------- 1 | export function Button({ className, ...props }: any) { 2 | return ( 3 | 58 |
59 | ); 60 | 61 | export default UrlButton; 62 | -------------------------------------------------------------------------------- /src/app/components/Context/index.tsx: -------------------------------------------------------------------------------- 1 | import React, { ChangeEvent, useCallback, useEffect, useState } from "react"; 2 | import { urls } from "./urls"; 3 | import UrlButton from "./UrlButton"; 4 | import { Card, ICard } from "./Card"; 5 | import { clearIndex, crawlDocument } from "./utils"; 6 | 7 | import { Button } from "./Button"; 8 | interface ContextProps { 9 | className: string; 10 | selected: string[] | null; 11 | } 12 | 13 | export const Context: React.FC = ({ className, selected }) => { 14 | const [entries, setEntries] = useState(urls); 15 | const [cards, setCards] = useState([]); 16 | 17 | const [splittingMethod, setSplittingMethod] = useState("markdown"); 18 | const [chunkSize, setChunkSize] = useState(256); 19 | const [overlap, setOverlap] = useState(1); 20 | 21 | // Scroll to selected card 22 | useEffect(() => { 23 | const element = selected && document.getElementById(selected[0]); 24 | element?.scrollIntoView({ behavior: "smooth" }); 25 | }, [selected]); 26 | 27 | const DropdownLabel: React.FC< 28 | React.PropsWithChildren<{ htmlFor: string }> 29 | > = ({ htmlFor, children }) => ( 30 | 33 | ); 34 | 35 | const buttons = entries.map((entry, key) => ( 36 |
37 | 40 | crawlDocument( 41 | entry.url, 42 | setEntries, 43 | setCards, 44 | splittingMethod, 45 | chunkSize, 46 | overlap 47 | ) 48 | } 49 | /> 50 |
51 | )); 52 | 53 | return ( 54 |
57 |
58 |
59 | {buttons} 60 |
61 |
62 | 72 |
73 |
74 |
75 | 76 | Splitting Method: 77 | 78 |
79 | 88 |
89 | {splittingMethod === "recursive" && ( 90 |
91 |
92 | 93 | Chunk Size: {chunkSize} 94 | 95 | setChunkSize(parseInt(e.target.value))} 102 | /> 103 |
104 |
105 | 106 | Overlap: {overlap} 107 | 108 | setOverlap(parseInt(e.target.value))} 115 | /> 116 |
117 |
118 | )} 119 |
120 |
121 |
122 | {cards && 123 | cards.map((card, key) => ( 124 | 125 | ))} 126 |
127 |
128 | ); 129 | }; 130 | -------------------------------------------------------------------------------- /src/app/components/Context/urls.ts: -------------------------------------------------------------------------------- 1 | export const urls = [{ 2 | url: "https://e360.yale.edu/digest/indonesia-malaysia-deforestation", 3 | title: "Indonesia Deforestation", 4 | seeded: false, 5 | loading: false, 6 | }, 7 | { 8 | url: "https://cleantechnica.com/2023/06/29/solar-82-of-power-capacity-growth-in-india-in-2022/", 9 | title: "Solar Power in India", 10 | seeded: false, 11 | loading: false, 12 | }, 13 | { 14 | url: "https://www.cbssports.com/nba/news/matisse-thybulle-to-stay-with-blazers-who-match-mavericks-three-year-33-million-deal-per-report/", 15 | title: "Matisee Thybulle", 16 | seeded: false, 17 | loading: false, 18 | }] -------------------------------------------------------------------------------- /src/app/components/Context/utils.ts: -------------------------------------------------------------------------------- 1 | import { IUrlEntry } from "./UrlButton"; 2 | import { ICard } from "./Card"; 3 | 4 | export async function crawlDocument( 5 | url: string, 6 | setEntries: React.Dispatch>, 7 | setCards: React.Dispatch>, 8 | splittingMethod: string, 9 | chunkSize: number, 10 | overlap: number 11 | ): Promise { 12 | setEntries((seeded: IUrlEntry[]) => 13 | seeded.map((seed: IUrlEntry) => 14 | seed.url === url ? { ...seed, loading: true } : seed 15 | ) 16 | ); 17 | const response = await fetch("/api/crawl", { 18 | method: "POST", 19 | headers: { "Content-Type": "application/json" }, 20 | body: JSON.stringify({ 21 | url, 22 | options: { 23 | splittingMethod, 24 | chunkSize, 25 | overlap, 26 | }, 27 | }), 28 | }); 29 | 30 | const { documents } = await response.json(); 31 | 32 | setCards(documents); 33 | 34 | setEntries((prevEntries: IUrlEntry[]) => 35 | prevEntries.map((entry: IUrlEntry) => 36 | entry.url === url ? { ...entry, seeded: true, loading: false } : entry 37 | ) 38 | ); 39 | } 40 | 41 | export async function clearIndex( 42 | setEntries: React.Dispatch>, 43 | setCards: React.Dispatch> 44 | ) { 45 | const response = await fetch("/api/clearIndex", { 46 | method: "POST", 47 | headers: { "Content-Type": "application/json" }, 48 | }); 49 | 50 | if (response.ok) { 51 | setEntries((prevEntries: IUrlEntry[]) => 52 | prevEntries.map((entry: IUrlEntry) => ({ 53 | ...entry, 54 | seeded: false, 55 | loading: false, 56 | })) 57 | ); 58 | setCards([]); 59 | } 60 | } -------------------------------------------------------------------------------- /src/app/components/Header.tsx: -------------------------------------------------------------------------------- 1 | import Image from "next/image"; 2 | import PineconeLogo from "../../../public/pinecone.svg"; 3 | import VercelLogo from "../../../public/vercel.svg"; 4 | 5 | export default function Header({ className }: { className?: string }) { 6 | return ( 7 |
10 | pinecone-logo{" "} 17 |
+
18 | vercel-logo 25 |
26 | ); 27 | } 28 | -------------------------------------------------------------------------------- /src/app/components/InstructionModal.tsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | import { AiFillGithub } from "react-icons/ai"; 3 | 4 | interface InstructionModalProps { 5 | isOpen: boolean; 6 | onClose: () => void; 7 | } 8 | 9 | const InstructionModal: React.FC = ({ 10 | isOpen, 11 | onClose, 12 | }) => { 13 | if (!isOpen) return null; 14 | 15 | return ( 16 |
17 |
18 | 24 |

Instructions

25 |

26 | This chatbot demonstrates a simple RAG pattern using{" "} 27 | 28 | Pinecone 29 | {" "} 30 | and Vercel's AI SDK. In the context panel on the right, you can 31 | see some articles you can index in Pinecone (on mobile, open the 32 | context panel by clicking the button at the top left of the message 33 | panel). Click on the blue link icons to open the URLs in a new window. 34 |

35 |
36 |

37 | After you index them, you can ask the chatbot questions about the 38 | specific of each article. The segments relevant to the answers the 39 | chatbot gives will be highlighted. 40 |

41 |
42 |

43 | You can clear the index by clicking the "Clear Index" button 44 | in the context panel. 45 |

46 |
47 |
51 |
52 | ); 53 | }; 54 | 55 | export default InstructionModal; 56 | -------------------------------------------------------------------------------- /src/app/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pinecone-io/pinecone-vercel-starter/cb53b81e4a76e1e1d12b1c49576b2e55a6a6d1a0/src/app/favicon.ico -------------------------------------------------------------------------------- /src/app/globals.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | 5 | :root { 6 | --foreground-rgb: 0, 0, 0; 7 | --background-start-rgb: 214, 219, 220; 8 | --background-end-rgb: 255, 255, 255; 9 | } 10 | 11 | @media (prefers-color-scheme: dark) { 12 | :root { 13 | --foreground-rgb: 255, 255, 255; 14 | --background-start-rgb: 0, 0, 0; 15 | --background-end-rgb: 0, 0, 0; 16 | } 17 | } 18 | 19 | body { 20 | color: rgb(var(--foreground-rgb)); 21 | background: linear-gradient( 22 | to bottom, 23 | transparent, 24 | rgb(var(--background-end-rgb)) 25 | ) 26 | rgb(var(--background-start-rgb)); 27 | } 28 | -------------------------------------------------------------------------------- /src/app/layout.tsx: -------------------------------------------------------------------------------- 1 | export const metadata = { 2 | title: "Pinecone - Vercel AI SDK Example", 3 | description: "Pinecone - Vercel AI SDK Example", 4 | }; 5 | 6 | import "../global.css"; 7 | 8 | export default function RootLayout({ 9 | children, 10 | }: { 11 | children: React.ReactNode; 12 | }) { 13 | return ( 14 | 15 | {children} 16 | 17 | ); 18 | } 19 | -------------------------------------------------------------------------------- /src/app/page.tsx: -------------------------------------------------------------------------------- 1 | "use client"; 2 | 3 | import React, { useEffect, useRef, useState, FormEvent } from "react"; 4 | import { Context } from "@/components/Context"; 5 | import Header from "@/components/Header"; 6 | import Chat from "@/components/Chat"; 7 | import { useChat } from "ai/react"; 8 | import InstructionModal from "./components/InstructionModal"; 9 | import { AiFillGithub, AiOutlineInfoCircle } from "react-icons/ai"; 10 | 11 | const Page: React.FC = () => { 12 | const [gotMessages, setGotMessages] = useState(false); 13 | const [context, setContext] = useState(null); 14 | const [isModalOpen, setModalOpen] = useState(false); 15 | 16 | const { messages, input, handleInputChange, handleSubmit } = useChat({ 17 | onFinish: async () => { 18 | setGotMessages(true); 19 | }, 20 | }); 21 | 22 | const prevMessagesLengthRef = useRef(messages.length); 23 | 24 | const handleMessageSubmit = async (e: FormEvent) => { 25 | e.preventDefault(); 26 | handleSubmit(e); 27 | setContext(null); 28 | setGotMessages(false); 29 | }; 30 | 31 | useEffect(() => { 32 | const getContext = async () => { 33 | const response = await fetch("/api/context", { 34 | method: "POST", 35 | body: JSON.stringify({ 36 | messages, 37 | }), 38 | }); 39 | const { context } = await response.json(); 40 | setContext(context.map((c: any) => c.id)); 41 | }; 42 | if (gotMessages && messages.length >= prevMessagesLengthRef.current) { 43 | getContext(); 44 | } 45 | 46 | prevMessagesLengthRef.current = messages.length; 47 | }, [messages, gotMessages]); 48 | 49 | return ( 50 |
51 |
52 | 56 | Deploy with Vercel 57 | 58 | 59 | 70 | 71 | 77 | 78 | setModalOpen(false)} 81 | /> 82 |
83 | 84 |
85 | 86 |
87 | 98 |
99 |
100 | ); 101 | }; 102 | 103 | export default Page; 104 | -------------------------------------------------------------------------------- /src/app/utils/chunkedUpsert.ts: -------------------------------------------------------------------------------- 1 | import type { Index, PineconeRecord } from '@pinecone-database/pinecone'; 2 | 3 | const sliceIntoChunks = (arr: T[], chunkSize: number) => { 4 | return Array.from({ length: Math.ceil(arr.length / chunkSize) }, (_, i) => 5 | arr.slice(i * chunkSize, (i + 1) * chunkSize) 6 | ); 7 | }; 8 | 9 | export const chunkedUpsert = async ( 10 | index: Index, 11 | vectors: Array, 12 | namespace: string, 13 | chunkSize = 10 14 | ) => { 15 | // Split the vectors into chunks 16 | const chunks = sliceIntoChunks(vectors, chunkSize); 17 | 18 | try { 19 | // Upsert each chunk of vectors into the index 20 | await Promise.allSettled( 21 | chunks.map(async (chunk) => { 22 | try { 23 | await index.namespace(namespace).upsert(vectors); 24 | } catch (e) { 25 | console.log('Error upserting chunk', e); 26 | } 27 | }) 28 | ); 29 | 30 | return true; 31 | } catch (e) { 32 | throw new Error(`Error upserting vectors into index: ${e}`); 33 | } 34 | }; 35 | -------------------------------------------------------------------------------- /src/app/utils/context.ts: -------------------------------------------------------------------------------- 1 | import { ScoredPineconeRecord } from "@pinecone-database/pinecone"; 2 | import { getMatchesFromEmbeddings } from "./pinecone"; 3 | import { getEmbeddings } from './embeddings' 4 | 5 | export type Metadata = { 6 | url: string, 7 | text: string, 8 | chunk: string, 9 | } 10 | 11 | // The function `getContext` is used to retrieve the context of a given message 12 | export const getContext = async (message: string, namespace: string, maxTokens = 3000, minScore = 0.7, getOnlyText = true): Promise => { 13 | 14 | // Get the embeddings of the input message 15 | const embedding = await getEmbeddings(message); 16 | 17 | // Retrieve the matches for the embeddings from the specified namespace 18 | const matches = await getMatchesFromEmbeddings(embedding, 3, namespace); 19 | 20 | // Filter out the matches that have a score lower than the minimum score 21 | const qualifyingDocs = matches.filter(m => m.score && m.score > minScore); 22 | 23 | if (!getOnlyText) { 24 | // Use a map to deduplicate matches by URL 25 | return qualifyingDocs 26 | } 27 | 28 | let docs = matches ? qualifyingDocs.map(match => (match.metadata as Metadata).chunk) : []; 29 | // Join all the chunks of text together, truncate to the maximum number of tokens, and return the result 30 | return docs.join("\n").substring(0, maxTokens) 31 | } 32 | -------------------------------------------------------------------------------- /src/app/utils/embeddings.ts: -------------------------------------------------------------------------------- 1 | 2 | import { OpenAIApi, Configuration } from "openai-edge"; 3 | 4 | const config = new Configuration({ 5 | apiKey: process.env.OPENAI_API_KEY 6 | }) 7 | const openai = new OpenAIApi(config) 8 | 9 | export async function getEmbeddings(input: string) { 10 | try { 11 | const response = await openai.createEmbedding({ 12 | model: "text-embedding-ada-002", 13 | input: input.replace(/\n/g, ' ') 14 | }) 15 | 16 | const result = await response.json(); 17 | return result.data[0].embedding as number[] 18 | 19 | } catch (e) { 20 | console.log("Error calling OpenAI embedding API: ", e); 21 | throw new Error(`Error calling OpenAI embedding API: ${e}`); 22 | } 23 | } -------------------------------------------------------------------------------- /src/app/utils/pinecone.ts: -------------------------------------------------------------------------------- 1 | import { Pinecone, type ScoredPineconeRecord } from "@pinecone-database/pinecone"; 2 | 3 | export type Metadata = { 4 | url: string, 5 | text: string, 6 | chunk: string, 7 | hash: string 8 | } 9 | 10 | // The function `getMatchesFromEmbeddings` is used to retrieve matches for the given embeddings 11 | const getMatchesFromEmbeddings = async (embeddings: number[], topK: number, namespace: string): Promise[]> => { 12 | // Obtain a client for Pinecone 13 | const pinecone = new Pinecone(); 14 | 15 | const indexName: string = process.env.PINECONE_INDEX || ''; 16 | if (indexName === '') { 17 | throw new Error('PINECONE_INDEX environment variable not set') 18 | } 19 | 20 | // Retrieve the list of indexes to check if expected index exists 21 | const indexes = (await pinecone.listIndexes())?.indexes; 22 | if (!indexes || indexes.filter(i => i.name === indexName).length !== 1) { 23 | throw new Error(`Index ${indexName} does not exist`) 24 | } 25 | 26 | // Get the Pinecone index 27 | const index = pinecone!.Index(indexName); 28 | 29 | // Get the namespace 30 | const pineconeNamespace = index.namespace(namespace ?? '') 31 | 32 | try { 33 | // Query the index with the defined request 34 | const queryResult = await pineconeNamespace.query({ 35 | vector: embeddings, 36 | topK, 37 | includeMetadata: true, 38 | }) 39 | return queryResult.matches || [] 40 | } catch (e) { 41 | // Log the error and throw it 42 | console.log("Error querying embeddings: ", e) 43 | throw new Error(`Error querying embeddings: ${e}`) 44 | } 45 | } 46 | 47 | export { getMatchesFromEmbeddings } -------------------------------------------------------------------------------- /src/app/utils/truncateString.ts: -------------------------------------------------------------------------------- 1 | export const truncateStringByBytes = (str: string, bytes: number) => { 2 | const enc = new TextEncoder(); 3 | return new TextDecoder("utf-8").decode(enc.encode(str).slice(0, bytes)); 4 | }; -------------------------------------------------------------------------------- /src/global.css: -------------------------------------------------------------------------------- 1 | @import "tailwindcss/base"; 2 | @import "tailwindcss/components"; 3 | @import "tailwindcss/utilities"; 4 | 5 | @keyframes slideInFromBottom { 6 | 0% { 7 | transform: translateY(100%); 8 | opacity: 0; 9 | } 10 | 100% { 11 | transform: translateY(0); 12 | opacity: 1; 13 | } 14 | } 15 | 16 | .slide-in-bottom { 17 | animation: slideInFromBottom 0.3s ease-out; 18 | } 19 | 20 | .input-glow { 21 | box-shadow: 0 0 3px #4a5568, 0 0 5px #4a5568; 22 | } 23 | 24 | .input-glow:hover { 25 | box-shadow: 0 0 5px #87f4f6, 0 0 10px #8b9ebe; 26 | } 27 | 28 | .message-glow { 29 | box-shadow: 0 0 3px #4a5568, 0 0 5px #4a5568; 30 | } 31 | 32 | .message-glow:hover { 33 | box-shadow: 0 0 3px #5eabac, 0 0 4px #8b9ebe; 34 | } 35 | 36 | @keyframes glimmer { 37 | 0% { 38 | background-position: -200px; 39 | } 40 | 100% { 41 | background-position: calc(200px + 100%); 42 | } 43 | } 44 | 45 | @keyframes shimmer { 46 | 0% { 47 | transform: translateX(-100%); 48 | } 49 | 100% { 50 | transform: translateX(100%); 51 | } 52 | } 53 | 54 | .shimmer { 55 | animation: glimmer 2s infinite linear; 56 | background: rgb(82, 82, 91); 57 | background: linear-gradient( 58 | to right, 59 | darkgray 10%, 60 | rgb(130, 129, 129) 50%, 61 | rgba(124, 123, 123, 0.816) 90% 62 | ); 63 | background-size: 200px 100%; 64 | background-repeat: no-repeat; 65 | /* color: transparent; */ 66 | } 67 | 68 | @keyframes pulse { 69 | 0%, 70 | 100% { 71 | color: white; 72 | } 73 | 50% { 74 | color: #f59e0b; /* Tailwind's yellow-500 */ 75 | } 76 | } 77 | 78 | .animate-pulse-once { 79 | animation: pulse 5s cubic-bezier(0, 0, 0.2, 1) 1; 80 | } 81 | -------------------------------------------------------------------------------- /tailwind.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('tailwindcss').Config} */ 2 | module.exports = { 3 | content: [ 4 | "./src/pages/**/*.{js,ts,jsx,tsx,mdx}", 5 | "./src/components/**/*.{js,ts,jsx,tsx,mdx}", 6 | "./src/app/**/*.{js,ts,jsx,tsx,mdx}", 7 | ], 8 | theme: { 9 | screens: { 10 | sm: "640px", 11 | md: "768px", 12 | lg: "1024px", 13 | xl: "1280px", 14 | }, 15 | extend: { 16 | backgroundImage: { 17 | "gradient-radial": "radial-gradient(var(--tw-gradient-stops))", 18 | "gradient-conic": 19 | "conic-gradient(from 180deg at 50% 50%, var(--tw-gradient-stops))", 20 | }, 21 | gridTemplateRows: { 22 | "auto-1fr": "auto 1fr", 23 | }, 24 | }, 25 | }, 26 | plugins: [], 27 | future: { 28 | removeDeprecatedGapUtilities: true, 29 | }, 30 | }; 31 | -------------------------------------------------------------------------------- /tests/example.spec.ts: -------------------------------------------------------------------------------- 1 | import { test, expect } from '@playwright/test'; 2 | 3 | test('has correct title', async ({ page }) => { 4 | await page.goto('http://localhost:3000'); 5 | 6 | await expect(page).toHaveTitle('Pinecone - Vercel AI SDK Example') 7 | }) 8 | 9 | test('renders info modal button', async ({ page }) => { 10 | await page.goto('http://localhost:3000') 11 | 12 | const infoButtonCount = await page.locator('.info-button').count() 13 | await expect(infoButtonCount).toBe(1) 14 | }) 15 | 16 | test('renders GitHub repository button', async ({ page }) => { 17 | await page.goto('http://localhost:3000') 18 | 19 | const infoButtonCount = await page.locator('.github-button').count() 20 | await expect(infoButtonCount).toBe(1) 21 | }) 22 | 23 | test('renders Vercel deploy button', async ({ page }) => { 24 | await page.goto('http://localhost:3000') 25 | 26 | const vercelDeployButtonCount = await page.getByRole('link', { name: 'Deploy' }).count() 27 | 28 | await expect(vercelDeployButtonCount).toBe(1) 29 | }) 30 | 31 | test('renders clear index button', async ({ page }) => { 32 | await page.goto('http://localhost:3000') 33 | 34 | const clearIndexButtonCount = await page.getByRole('button', { name: 'Clear Index' }).count() 35 | 36 | await expect(clearIndexButtonCount).toBe(1) 37 | }) 38 | 39 | test('renders indonesia deforestation button', async ({ page }) => { 40 | await page.goto('http://localhost:3000') 41 | 42 | const indonesiaDeforestationButtonCount = await page.getByRole('button', { name: 'Indonesia Deforestation' }).count() 43 | 44 | await expect(indonesiaDeforestationButtonCount).toBe(1) 45 | }) 46 | 47 | test('renders solar power in India button', async ({ page }) => { 48 | await page.goto('http://localhost:3000') 49 | 50 | const solarPowerButtonCount = await page.getByRole('button', { name: 'Solar Power in India' }).count() 51 | 52 | await expect(solarPowerButtonCount).toBe(1) 53 | }) 54 | 55 | test('renders matisee thybulle button', async ({ page }) => { 56 | await page.goto('http://localhost:3000') 57 | 58 | const matiseeThybulleButtonCount = await page.getByRole('button', { name: 'Matisee Thybulle' }).count() 59 | 60 | await expect(matiseeThybulleButtonCount).toBe(1) 61 | }) 62 | 63 | /*test('GitHub button goes to project repository', async ({ page, browserName }) => { 64 | test.setTimeout(60000) 65 | 66 | test.skip(browserName === 'chromium', 'Chrome doesn\'t work :( ') 67 | 68 | await page.goto('http://localhost:3000/'); 69 | const githubButton = await page.locator('.github-button'); 70 | await githubButton.click(); 71 | 72 | try { 73 | await page.waitForNavigation('https://github.com/pinecone-io/pinecone-vercel-starter'); 74 | } catch (e) { 75 | console.log('Error waiting on navigation...') 76 | } 77 | });*/ 78 | 79 | // TODO - add tests for other key buttons on the homepage 80 | 81 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true, 17 | "plugins": [ 18 | { 19 | "name": "next" 20 | } 21 | ], 22 | "paths": { 23 | "@/*": ["./src/app/*"] 24 | } 25 | }, 26 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], 27 | "exclude": ["node_modules"] 28 | } 29 | --------------------------------------------------------------------------------