Tailwind Logo

Customize Next.js OpenAI Starter


Published: 2024-02-02

We started the sample and subsequently checked its operation. This time, we will make a simple customization.

Delete unnecessary codes

There are various sample codes, but the files themselves can always be referenced in the repository under GitHub, so we will remove unnecessary files at hand.

  • app - Delete everything but the chat folder under the api
  • app - Delete all folders except api

Only the following files are now available


In this case, we will use the code developed at https://github.com/steven-tey/chathn to create it.

Creating functions.ts

The above code contains several functions, but we will implement two of them in app/api/chat/functions.ts: get_top_stories and get_story.

The prepared code can be found at the following link

Changes to route.ts

First, implement imports so that the functions in functions.ts can be used.

import { functions, runFunction } from "./functions";

Then add functions to openai.chat.completions.create in the code to request chat for streaming.

  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    stream: true,

Then add the following declarations to pass arbitrary data to the client

  const data = new experimental_StreamData();

Finally, modify the OpenAIStream call. Since we are rewriting a lot of code here, please refer to the final code.

Operation Check

First, let's do a keyword search for Get top 5 stories on Hacker News in the pre-updated environment. The following results are displayed.


Now, search for the same keywords on the modified page.


To verify this result, access https://hacker-news.firebaseio.com/v0/topstories.json, which was used as a news listing, and you will see that the news listing is as follows.


News for the IDs obtained from here are read individually.


We could use the latest news list to confirm that we are responding.


We were able to give ChatGPT an additional data source and have it answer the questions. We would like to use this mechanism to implement integration with Sitecore Search in the next issue.

Related article