Google AI Gemini API in web using React ??

Google AI Gemini API in web using React ??

In this blog you will learn to integrate the Google Artificial Intelligence Gemini API into a web pp built with ReactJS and fetch random meals using the Gemini API with the Gemini Google SDK, you’ll need to follow several steps. The Gemini API is used for personalized content recommendations, and the Gemini Google Web SDK facilitates communication with the Gemini service.

What will be the Outcome:

This tutorial illustrates the process of directly integrating the Gemini API into your web application using the Google AI JavaScript SDK. If you prefer not to engage directly with REST APIs or employ server-side code, such as Node.js, to interact with Gemini models in your web app, this SDK is a suitable alternative.

Throughout this tutorial, you will be guided on the following tasks:

  1. Establishing your project, including the configuration of your API key .
  2. Generating text based on text-only input.

Requirements:

This tutorial presupposes that you have a basic understanding of utilizing JavaScript for web application development. It is also important to note that the guidance provided is not tied to any specific framework.

To successfully follow this tutorial, ensure that your development environment satisfies the following criteria:

  1. (Optional) Node.js
  2. Modern web browser

Step by Step Guide:

Project Setup:

Prior to making calls to the Gemini API, it is imperative to configure your project, which involves acquiring an API key and initializing the model.

Setting up Your API Key:

To leverage the Gemini API, you must possess an API key. If you do not already have one, create a key through Google AI Studio.

Create a ReactJS App

Open your terminal and run the following command to create a new React app using Create React App:

npx create-react-app restaurant-gemini-ai        

Create a new Component:

Open your terminal in code editor and create a new component named e.g. Homepage.js

cd restaurant-gemini-ai        
mkdir components        
// components/Homepage.js

import React from 'react';

const Home = () => {
  return (
    <div>
      <h1>Welcome to the Restaurant App!</h1>
      <p>Built with love using ReactJS + Redux</p>
    </div>
  );
};

export default Home;        

Add a google gemini package:

Before you initialize the Generative Model, let’s start by adding a npm package of Google AI Gemini for React:

npm i @google/generative-ai        

Your dependencies in package.json should have following entry:

“@google/generative-ai”: “0.1.3”

Initialize the Generative Model

Before you can make any API calls, you need to import and initialize the Generative Model.

When designating a model, keep in mind the following: It is essential to select a model tailored to your specific use case (e.g., gemini-pro-vision for multimodal input). Refer to the next section of this guide for the suggested model corresponding to each use case.
// components/Homepage.js

import { GoogleGenerativeAI } from "@google/generative-ai";
...

const genAI = new GoogleGenerativeAI('YOUR_API_KEY');
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
        

Create a Search box with State in React App:

Build a search box within your React app along with a button that interacts with Google AI Gemini to retrieve intriguing results utilizing artificial intelligence.

import React, { useState } from 'react';
...

const Home = () => {
  const [search, setSearch] = useState('');
  
  const handleChangeSearch = (e) => {
      setSearch(e.target.value);
  }
  
  return (
      <div>
        <h1>Generative AI Restaurant App!</h1>
        <p>Built with ?? using ReactJS + Redux + Google Gemini</p>
  
        <div style={{ display: 'flex' }}>
          <input placeholder='Search Food with Category using Generative AI' onChange={(e) => handleChangeSearch(e)} />
          <button style={{ marginLeft: '20px' }} onClick={() => handleClick()}>Search</button>
        </div>
      </div>
  );
};

export default Home;        

Consuming configure and Google AI Gemini API

If the input prompt comprises solely text, utilize the gemini-pro model alongside the generateContent method for text output generation:

const [aiResponse, setResponse] = useState('');
...

// Generative AI Call to fetch dishes

async function aiRun() {
  const prompt = `random meals related to ${search} category with images and prices`;
  const result = await model.generateContent(prompt);
  const response = await result.response;
  const text = response.text();
  setResponse(text);
}

// button event trigger to consume gemini Api

const handleClick = () => {
  aiRun();
}        

Add a Loading state in React

Let’s now incorporate a loading state to display the loading status until a response is received from the Gemini API.

const [loading, setLoading] = useState(false);
...

// Generative AI Call to fetch dishes
async function aiRun() {
  setLoading(true);
  ...
  setLoading(false);
}

...

return (
  <div>
    <h1>Generative AI Restaurant App!</h1>
    <p>Built with ?? using ReactJS + Redux + Google Gemini</p>

    <div style={{ display: 'flex' }}>
      <input placeholder='Search Food with Category using Generative AI' onChange={(e) => handleChangeSearch(e)} />
      <button style={{ marginLeft: '20px' }} onClick={() => handleClick()}>Search</button>
    </div>

    {
      loading == true && search != '' ?
        <p style={{ margin: '30px 0' }}>Loading ...</p>
        :
        <div style={{ margin: '30px 0' }}>
          <p>{aiResponse}</p>
        </div>
    }
  </div>
);        

You’re Ready Now ??


要查看或添加评论,请登录

Royal Cyber Asia的更多文章

社区洞察

其他会员也浏览了