Skip to main content

React Tutorial using Generate

Build a Trivia Generator with Cohere#

If you’ve ever hosted a trivia night, you know that brainstorming the questions is a laborious creative process. You can’t just look for existing questions — you want original questions that suit your friends’ interests and knowledge levels. If only artificial intelligence was good enough to write fun new questions based on your favourite topics, right?

Look no further than this trivia generator built with Cohere. Give it a shot!

This is a screenshot of the trivia generator people will build.

Cohere builds and hosts world class large language models that developers can leverage with a single API call. In this tutorial, we’ll be using Cohere’s Generate endpoint, which outputs human-like writing given a structured input prompt (in this case, a topic), to create the simple trivia question generator above with React.

The primary goal of this tutorial is to guide developers through configuring Cohere's Generate endpoint to achieve their desired output (trivia questions). If you are only interested in following this part of the tutorial, see Step 2.

By the end of this tutorial, you will be able to set up a frontend that takes an input prompt and a backend that gets an output from Cohere for an app that serves this trivia generator.

All the code written for this tutorial can be found from our samples repository, along with other integrations between our LLMs and popular developer tools.

Requirements#

For this tutorial, you will need:

  1. A code editor of your choice. We recommend VSCode. Download VSCode.
  2. Node.js installed on your machine. Download Node.js.
  3. Basic knowledge of Express.
  4. Basic knowledge of React.
  5. A Cohere API key. After you create a Cohere account, navigate to “Dashboard” and click Create API Key, pictured below:
This is a screenshot of Cohere's Dashboard after you make a new account.

Make sure to copy your API key somewhere safe such as a password manager. You will need to generate a new one if you lose it.

Tutorial steps#

  1. Create your Node (Express) backend
  2. Prompt Cohere to generate trivia questions
  3. Integrating Cohere into your app
  4. Build your React frontend
  5. Passing an input from React frontend to Node backend

Step 1: Create your Node (Express) Backend#

Create a folder for your project. You can name it trivia-generator, for example. Open the folder in your code editor.

Open your terminal and navigate to the directory you just created. Run the following command:

npm init -y

Note the package.json file that was created in the folder -- We’ll need that for later.

For now, create a server folder. In the server folder, create an index.js file.

This is a screenshot of the folder structure.

Paste the following code in server/index.js:

// server/index.js
const path = require('path');
const express = require('express');
const cors = require('cors');
const PORT = process.env.PORT || 3001;
const app = express();
app.use(cors());
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});

This uses Express to create a web server for us running on port 3001. You'll need to install a few packages for this to work, so run the following in your command line:

npm install express cors --save

To ensure that your server has been set up correctly thus far, add the following script to the package.json file:

// server/package.json
...
"scripts": {
"start": "node server/index.js"
},
...

This enables you to run the following command in the terminal, after which you should see your server successfully listening to the specified port 3001:

npm start

Step 2: Prompt Cohere to generate trivia questions#

Sign into your Cohere account and navigate to the playground.

This is a screenshot of how to nav to Cohere's Playground.

You’ll see a pre-loaded prompt in the window on the playground. To get a sense of how Cohere's Generate endpoint works, try clicking Generate. Cohere’s large language models read the prompt and decide what the most appropriate next tokens are to return. To learn best practices for prompting the model, read our guide to Prompt Engineering.

We’ll need to prompt the model to give us trivia questions. First, let's describe the task we want the model to perform:

This is a screenshot of describing the trivia task in playground.

Next, we need to give the models a few examples of outputs we are looking for. Here are some popular trivia questions from Google:

This is a screenshot of inputting trivia questions in playground.

I’ve separated the questions using a - character, called a stop sequence. The stop sequence character is completely arbitrary, though I'd recommend a character you don't expect to see in your generations because the model will stop generating text after it returns the stop character.

When the model is learning our trivia examples, it will start to generate outputs in the format we’re teaching it with our prompt. This is handy if you want the model to stop generating text after it has outputted a question. To set a stop sequence, go to the Advanced parameters dropdown. After adding the - as our parameter, it should look like this:

This is a screenshot of inputting a stop sequence in the advanced parameters.

You can have multiple stop sequences if needed, but it's not necessary for this tutorial. Now, let’s give it a topic and see what our generation looks like. Click the Generate button:

This is a screenshot of Cohere generating a trivia question in Playground.

Pretty interesting question! And if you’re curious, the most widely used mobile phone network (by subscriptions) is China Mobile Communications Corporation.

The more examples you can add, the better the model should perform at this task. We ultimately added 25 trivia questions to teach the model our desired output, but ideally you would scrape more examples to add to your text, or finetune a model with even more questions to specialize it in this task. If you’re not getting satisfactory results with your own prompts in the future, a safe bet is always to add more examples.

For more details on how to craft great prompts, read our documentation on prompt engineering. If you want greater control over the output, try playing with temperature, top-k, and top-p values.

When you're happy with the quality of your generations, delete the last generation and the topic. We’re going to have the user input this in the application we build. At this point, click the Export Code button and copy the code in the js tab:

This is a screenshot of how to export code from the playground

We’ll be able to use this code to call Cohere and return trivia questions.

Step 3: Integrating Cohere into your app#

In a new terminal window, run the following command:

npm install cohere-ai --save

We’re going to define an API endpoint that sends a request to Cohere when called. Copy the following code (loaded with 25 trivia questions) into your server/index.js file, like so:

const cohere = require('cohere-ai');
cohere.init('{YOUR_API_KEY}');
app.get('/api', async (req, res) => {
const response = await cohere.generate('large', {
prompt: `This is a trivia question generation tool. It generates questions related to a given topic.\n-\nTopic: History\nQ: Who invented penicillin?\n-\nTopic: Entertainment\nQ: What was the first toy to be advertised on television?\n-\nTopic: Sports\nQ: Which two countries have not missed one of the modern-day Olympics?\n-\nTopic: Geography\nQ: What is the smallest country in the world?\n-\nTopic: Food \nQ: What is the rarest M&M color?\n-\nTopic: Switzerland\nQ: What country consumes the most chocolate per capita? \n- \nTopic: India\nQ: What is the name given to Indian food cooked over charcoal in a clay oven?\n-\nTopic: Space\nQ: What was the first soft drink in space?\n-\nTopic: Cheese\nQ: From which country does Gouda cheese originate?\n-\nTopic: Disney\nQ: What was the first feature-length animated movie ever released?\n-\nTopic: Books\nQ: Who authored Sherlock Holmes? \n-\nTopic: Entertainment\nQ: What awards has an EGOT winner won?\n-\nTopic: Music\nQ: Which member of the Beatles married Yoko Ono?\n-\nTopic: Soccer\nQ: Which country won the first-ever soccer World Cup in 1930?\n-\nTopic: Basketball\nQ: Which Former NBA Player Was Nicknamed Agent Zero?\n-\nTopic: Gymnastics \nQ: Who was the first gymnast to score a perfect 10 score?\n-\nTopic: Volleyball\nQ: Dump, floater, and wipe are terms used in which team sport?\n-\nTopic: Formula 1\nQ: Who was the first female driver to score points in a Grand Prix?\n-\nTopic: United States\nQ: In which state is Area 51 located? \n-\nTopic: Animals\nQ: How long do elephant pregnancies last?\n-\nTopic: Science\nQ: In what type of matter are atoms most tightly packed?\n-\nTopic: Anatomy\nQ: How many teeth does an adult human have?\n-\nTopic: Etymology\nQ: Who invented the word vomit?\n-\nTopic: ${req.query.prompt}`,
max_tokens: 50,
temperature: 0.6,
stop_sequences: ['-'],
});
res.json(response.body);
});

To ensure this is working, go to your terminal where your server was running and restart it by clicking Command/Ctrl + C. Type npm start to run it again.

Visit http://localhost:3001/api in your browser to see your API call successfully hit Cohere’s endpoint:

This is a screenshot of Cohere generating a trivia question in Playground.

The next step is to build a React frontend to interface with this API.

Step 4: Build your React frontend#

Open a new terminal window, change into your project folder (trivia-generator), and paste the following command:

npx create-react-app client

Change into the new client directory and run the following command:

npm start

Your browser should open on localhost:3000.

Step 5: Passing an input from React frontend to Node backend#

Open the src/app.js file in your code editor.

Add the following import statement:

import { useState } from 'react';

Define the root URL where this app should hit the API, in this case at localhost:3001.

In the App() function, create a data and prompt state variable. The data variable will contain the output generated from Cohere’s model, and prompt will be used to store the user’s input for the topic. The prompt will be updated to whatever is in the textbox when a user clicks submit on the form, at which time a request is sent to the /api endpoint we defined to get a response from Cohere.

function App() {
const API_URL = 'http://localhost:3001';
const [data, setData] = useState(null);
const [prompt, setPrompt] = useState('');
// Update prompt variable when handleChange is called
const handleChange = (e) => {
setPrompt(e.target.value);
};
// When handleSubmit is called, passes prompt to /api and then gets assigns response to data
const handleSubmit = (e) => {
abc.preventDefault();
setData(null);
fetch(`${API_URL}/api?prompt=${prompt}`)
.then((res) => res.json())
.then((data) => setData(`${data.generations[0].text.slice(0, -1)}`));
};
}

Add a return statement inside App() and copy in this basic HTML that adds the aforementioned form box to the page:

return (
<div className="App">
<header className="App-header">
<h1>Trivia Generator</h1>
<form onSubmit="{handleSubmit}">
<label>
Give me a topic: <br />
<textarea name="input-box" rows="5" cols="100" value="{prompt}" onChange="{handleChange}" />
</label>
<br />
<input type="submit" value="Submit" />
</form>
<h1>Result:</h1>
<h3>{!data ? 'Question will appear here.' : data}</h3>
</header>
</div>
)

Save this, and you should be able to see the changes at localhost:3000 assuming you didn’t stop your server:

This is a screenshot of the trivia generator people will build.

Other things to try#

Congratulations! You've just built a React app with Cohere's Generate endpoint! Building on top of your knowledge, you could rework the prompts to rephrase sentences to be used as a writing assistant, or summarize long articles you find on the web. Check out our guide on how to implement summarization next.

Drop us a comment at community.cohere.ai if you have any questions or comments along the way. Happy writing!