[*] проверил, что облачная функция была успешно развернута на огненной базе с правильным именем и областью. -member = allusers -role = role/cloudfunctions.invoker , чтобы предоставить аллезисы доступ в консоли IAM Google Cloud. Впоследствии я отправился в облачную консоль Google и удалил необходимость аутентификации, я дал публичный доступ.
[*] Пошел на вкладку API и службы и изменил ограничение веб -ключа API на Unperricted.
Пробовал Flectry Function, и попробовал Freeploy, и снова пробуя Freeploy, и пробуя. /> < /li>
проверил, что пользователь Firebase зарегистрирован, я могу видеть пользователя в регистрации, вызывая функцию < /p>
< /li>
Когда я проверяю вкладку «Запросы сети», я вижу, что Auth Token передается Firebase < /p>
< /li>
Код: Выделить всё
exports.chatWithGemini = functions.https.onCall(async (data, context) => {
// if (!context.auth) {
// throw new functions.https.HttpsError("unauthenticated", "User must be authenticated");
// }
if (!context.auth) {
throw new functions.https.HttpsError(
"unauthenticated",
"User must be authenticated",
{ authRequired: false }
);
}
const userId = context.auth.uid;
const userInput = data.input;
if (!userInput) {
throw new functions.https.HttpsError("invalid-argument", "No input provided");
}
try {
// 1. Generate embedding for user input
const inputEmbedding = await generateEmbedding(userInput);
// 2. Find relevant messages by similarity
const relevantMessages = await findRelevantMessages(userId, inputEmbedding, 5);
// 3. Build prompt context (system + relevant conversation + current user input)
let contextMessages = "";
relevantMessages.forEach((msg) => {
const speaker = msg.role === "user" ? "User" : "Assistant";
contextMessages += `${speaker}: ${msg.content}\n`;
});
const fullPrompt = `
${systemPrompt}
Previous relevant messages:
${contextMessages}
User: ${userInput}
Assistant:
`;
// 4. Call Gemini LLM using LangChain
const llm = new ChatGoogleGenerativeAI({
model: "gemini-1.5-flash",
apiKey: API_KEY,
temperature: 0.5,
topP: 0.8,
systemInstruction: systemPrompt,
});
const chain = new ConversationChain({
llm,
memory: new BufferMemory({ returnMessages: false }), // no buffer memory, since we control context
inputKey: "input",
outputKey: "response",
verbose: false,
});
const response = await chain.call({ input: fullPrompt });
// 5. Save user message and AI response + embeddings
await saveMessage(userId, { role: "user", content: userInput, embedding: inputEmbedding });
const aiEmbedding = await generateEmbedding(response.response);
await saveMessage(userId, { role: "ai", content: response.response, embedding: aiEmbedding });
// 6. Return AI response
return { reply: response.response };
} catch (error) {
console.error("Cloud Function error:", error);
throw new functions.https.HttpsError("internal", error.message);
}
});
Любая справка или руководство с этим будет признано. Не стесняйтесь DM, если вам нужна дополнительная информация.
Спасибо
Подробнее здесь: https://stackoverflow.com/questions/797 ... e-firebase
Мобильная версия