Hooks
useGemini

useGemini Hook

Introduction

The useGemini custom hook provides a convenient way to interact with the Google Generative AI API within React applications. By utilizing this hook, developers can easily generate text based on provided prompts using Google's Generative AI models.

Installation

To use the useGemini hook in your React application, you need to follow these installation steps:

  1. Ensure that you have React installed in your project.

  2. Install the necessary dependencies:

npm install axios @google/generative-ai

Usage

import React, { useState } from 'react';
import {useGemini} from 'use-ai-hooks'; // Import the custom hook
 
const GeminiTextGenerationComponent = () => {
  const [prompt, setPrompt] = useState('');
  const apiKey = 'YOUR_API_KEY'; // Your Gemini API key
 
  const { generatedText, error, loading, generateText } = useGemini(apiKey);
 
  const handleGenerate = () => {
    if (prompt) {
      generateText({ prompt });
    }
  };
 
  return (
    <div>
      <h1>Gemini Text Generation</h1>
      <textarea
        placeholder="Enter prompt for text generation"
        value={prompt}
        onChange={(e) => setPrompt(e.target.value)}
      />
      <button onClick={handleGenerate} disabled={loading}>
        Generate Text
      </button>
 
      {loading && <p>Loading...</p>}
      {error && <p>Error: {error.message}</p>}
      {generatedText && <div>
        <h2>Generated Text</h2>
        <p>{generatedText}</p>
      </div>}
    </div>
  );
};
 
export default GeminiTextGenerationComponent;
 
 
 

API Reference

Parameters

  • apiKey (string): The API key required to authenticate requests to the Google Generative AI API.

Returns

An object with the following properties:

  • generatedText (string | null): The generated text obtained from the Google Generative AI API.
  • error (object | null): An object containing information about any errors that occurred during the API request.
    • message (string): A description of the error that occurred.
  • loading (boolean): A boolean indicating whether the API request is currently in progress.
  • generateText(options: GeminiOptions): A function to generate text based on the provided options using the Google Generative AI API.

Hook

import { useState } from "react";
import axios from "axios";
import { GoogleGenerativeAI } from "@google/generative-ai";
 
interface GeminiOptions {
  prompt: string;
  model?: string;
}
 
interface ApiError {
  message: string;
}
 
const useGemini = (apiKey: string) => {
  const genAI = new GoogleGenerativeAI(apiKey);
  const [generatedText, setGeneratedText] = useState<string | null>(null);
  const [error, setError] = useState<ApiError | null>(null);
  const [loading, setLoading] = useState<boolean>(false);
 
  const generateText = async (options: GeminiOptions) => {
    const model = genAI.getGenerativeModel({
      model: options.model || "gemini-1.5-flash",
    });
    setLoading(true);
    setError(null);
 
    try {
      const result = await model.generateContent(options.prompt);
      const response = await result.response;
      const text = response.text();
      setGeneratedText(text);
      return text;
    } catch (err) {
      if (axios.isAxiosError(err)) {
        setError({ message: err.message });
        return err;
      } else {
        setError({ message: "An unexpected error occurred" });
        return err;
      }
    } finally {
      setLoading(false);
    }
  };
 
  return { generatedText, error, loading, generateText };
};
 
export default useGemini;