Coder Social home page Coder Social logo

Comments (3)

MaxLeiter avatar MaxLeiter commented on September 21, 2024

You generally shouldn't us React without a framework, but very little of useChat and useCompletion should be Next.js-specific (minus the boilerplate like an API route). Is there a specific feature you'd like to see or problem you ran into?

from ai.

ejgutierrez74 avatar ejgutierrez74 commented on September 21, 2024

Well the title says it all, id need an example or tutorial of how to use Vercel AI SDK ( ideally with two different LLM providers lets say ollama and OpenAI). I use as component renderer React Chatbotify, and use the respective APIs to connect and get the response of the LLM. So i dont know how to setup a connection. which options, get the stream results or wait till all the information is received....

This is an example of connection to Gemini:

/ useGeminiBot.js
//El hook useGeminiBot encapsula la lógica para interactuar con la API de Gemini.
// Este hook maneja la inicialización de la sesión de chat y el envío de mensajes.

import { useState, useEffect } from 'react';
import { GoogleGenerativeAI, HarmCategory, HarmBlockThreshold } from "@google/generative-ai";

const useGeminiBot = () => {

  const apiKey = import.meta.env.VITE_REACT_APP_API_KEY_GEMINI;

  //useState inicializa chatSession como null.
  const [chatSession, setChatSession] = useState(null);

 /* Efecto useEffect:

    Inicializa una instancia de GoogleGenerativeAI con la clave API.
    Configura el modelo generativo y las configuraciones de generación y seguridad.
    Inicia una nueva sesión de chat y la guarda en el estado chatSession.*/

  useEffect(() => {
    const genAI = new GoogleGenerativeAI(apiKey);
    const model = genAI.getGenerativeModel({ model: "gemini-1.5-pro-latest" });

    const generationConfig = {
      temperature: 1,
      topP: 0.95,
      topK: 64,
      maxOutputTokens: 8192,
      responseMimeType: "text/plain",
    };

    const safetySettings = [
      { category: HarmCategory.HARM_CATEGORY_HARASSMENT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE },
      { category: HarmCategory.HARM_CATEGORY_HATE_SPEECH, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE },
      { category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE },
      { category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE },
    ];

    const newChatSession = model.startChat({ generationConfig, safetySettings, history: [] });
    setChatSession(newChatSession);

    // [apiKey] Ejecuta el efecto cuando la clave API cambia ( en principio no haria falta, ya que la apikey no cambia si no cambias fichero .env)
    // [] Si sabes que la clave API no cambiará, puedes dejar la lista de dependencias vacía para que el efecto solo se ejecute una vez cuando el componente se monte.
  }, []); 

  const sendMessage = async (userInput, streamMessage) => {
    
    if (!chatSession) return await streamMessage("Error chatSession no iniciada.");
    try {
      const result = await chatSession.sendMessageStream(userInput);
      let partialResponse = '';
      for await (const chunk of result.stream) {
        const chunkText = chunk.text();
        partialResponse += chunkText;
        await streamMessage(partialResponse);
      }
    } catch (err) {
      console.error(err);
      await streamMessage("Connection error. Did you provide a valid API key?");
    }
  };

  return { sendMessage };
};

export default useGeminiBot;

Also i have different providers/custom hooks i can manage them ( separate the render from logic):

// useChatBotProvider.js
import useGeminiBot from './useGeminiBot';
import useOllamaBot from './useOllamaBot';

const useChatBotProvider = (provider, model) => {
  const geminiBot = useGeminiBot(model);
  const ollamaBot = useOllamaBot(model);

  const sendMessage = async (userInput, streamMessage) => {
    if (provider === 'gemini') {
      await geminiBot.sendMessage(userInput, streamMessage);
    } else if (provider === 'ollama') {
      await ollamaBot.sendMessage(userInput, streamMessage);
    }
    // Agregar lógica para otros proveedores aquí según sea necesario
  };

  let messageHistory = [];
  let updateMessages = () => {};

  if (provider === 'ollama') {
    messageHistory = ollamaBot.messageHistory;
    updateMessages = ollamaBot.updateMessages;
  }

  return { sendMessage, messageHistory, updateMessages };
};

export default useChatBotProvider;

I use custom hooks you can read the code : https://github.com/ejgutierrez74/workshop-react-eduardo
So i think this is done by Vercel AI SDK and probably with more efficiency and error handling, but i dont know how to use it...

Thanks

from ai.

dayos-rohit avatar dayos-rohit commented on September 21, 2024

hey @MaxLeiter I would also appreciate an simple example of React and vercel ai sdk if possible. I would also like to know what are the specific limitations of using nextjs ai sdk with React.

from ai.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.