ollama-js icon indicating copy to clipboard operation
ollama-js copied to clipboard

Trying to use the OpenAI javascript API in react im facing this error: dangerouslyAllowBrowser

Open ejgutierrez74 opened this issue 1 month ago • 2 comments

Uncaught Error: It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers. If you understand the risks and have appropriate mitigations in place, you can set the dangerouslyAllowBrowser option to true, e.g.,

new OpenAI({ apiKey, dangerouslyAllowBrowser: true });

https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety OpenAIError error.ts:5 OpenAI index.ts:134 ComponentChatBotReactChatBotifly.jsx:26 error.ts:5:6

My code .... (dont know if i can use: new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); in ollama openai compatibility library javascript as there is nothing related in doc).

import ChatBot from 'react-chatbotify';
import OpenAI from 'openai';

const openai = new OpenAI({
    baseURL: 'http://localhost:11434/v1/',
    // required but ignored
    apiKey: 'ollama',
  })
  


let messageHistory = [];

async function fetchData() {
    const chatCompletion = await openai.chat.completions.create({
        messages: messageHistory,
        model: 'llama3',
      })
      return chatCompletion.data.choices[0].message.content;
/*
    try {
        const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
        const data = await response.json();
        return data.title;
    } catch (error) {
        return "Oh no I don't know what to say!";
    }
*/
}

function updateMessages( rol, content) {
    messageHistory.push({ role: rol, content: content });
    return messageHistory;
}
export default function ComponentChatBotReactChatBotifly() {


    const flow = {
        start: {
            message: (params) => {
                updateMessages('system','You are a helpful assistant. You are here to help the user with their queries. Be kind and short in your responses.');
                params.injectMessage("Hi my name is Edubot. Im here to help you");
                params.injectMessage("Can you write your username, so i can address you ?");
                updateMessages('assistant','Hi my name is Edubot. Im here to help you');
                updateMessages('assistant','Can you write your username, so i can address you ?');
            },
            path: "askname"
        },
        askname: {
            message: (params) => {
                updateMessages('user',`${params.userInput}`);
                params.injectMessage(`Nice to meet you ${params.userInput}!`);
                updateMessages('assistant',`Nice to meet you ${params.userInput}!`);
                params.injectMessage("Ask anything i will try to help you!");
                updateMessages('user','Ask anything i will try to help you!');
            },
            path: "loop",
        },
        loop: {
            message: async (params) => {
                updateMessages('user',`${params.userInput}`);
                const result = await fetchData();
                return result;
            },
            path: "loop",
        }
    }
    return (
        <ChatBot options={{ theme: { embedded: false }, chatHistory: { storageKey: "example_simulation_stream" }, botBubble: { simStream: true } }} flow={flow} />
    )
}`

Update tried to use the dangerouslyAllowBrowser option to true:

const openai = new OpenAI({
    baseURL: 'http://localhost:11434/v1/',
    // required but ignored
    apiKey: 'ollama',
    dangerouslyAllowBrowser: true   
  })

Seems i skip or pass the error of the issue, but still doesnt work as im facing:

Solicitud de origen cruzado bloqueada: La política de mismo origen (Same Origin Policy) no permite la lectura de recursos remotos en http://localhost:11434/v1/chat/completions. (Motivo: La cabecera ‘x-stainless-arch’ no está permitida de acuerdo a la cabecera ‘Access-Control-Allow-Headers’ de la verificación previa de la respuesta CORS).

In english ( using Google Translator) : Request for blocked cross origin: the same origin policy (Same Origin Policy) does not allow reading remote resources at http: // localhost: 11434/v1/chat/complete. (Reason: The header ‘X-Stainless-Arch’ is not allowed according to the header ‘Access-Control-Allow-Headers’ of the previous verification of the Cors response).

ejgutierrez74 avatar May 18 '24 09:05 ejgutierrez74