Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dev Mobile Frontend Streaming Data #43

Merged
merged 4 commits into from
Feb 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 50 additions & 22 deletions native/lifemngr/App.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useEffect, useRef } from "react";
import { View, Text, TextInput, TouchableOpacity, ScrollView, StyleSheet, KeyboardAvoidingView, Platform } from "react-native";
import { Ionicons, FontAwesome } from '@expo/vector-icons'; // https://icons.expo.fyi/Index
import 'react-native-polyfill-globals/auto'; // DO NOT DELETE!!!! This is to polyfill the fetch streaming! See: https://github.com/lndncole/lifemanager/pull/43

export default function App() {
const [isOpen, setIsOpen] = useState(false);
Expand Down Expand Up @@ -37,34 +38,61 @@ export default function App() {
setConversation((prevConversation) => [...prevConversation, newMessage]);
setUserInput("");

const conversationForApi = [...conversation, newMessage];
let accumulatedGptResponse = ""; // Accumulator for GPT's ongoing response

try {
// Replace with appropriate API call in React Native
// const response = await fetch("/api/chatGPT", {
// method: "POST",
// headers: {
// "Content-Type": "application/json",
// },
// body: JSON.stringify({ conversation: conversationForApi }),
// });
// const data = await response.json();

// Simulating API response for testing
const data = { response: { role: 'assistant', content: 'Sample AI Response' } };

if (data && data.gptFunction) {
// Handle different gptFunction cases as needed
// ...

} else {
const aiResponse = { role: data.response.role, content: data.response.content };
setConversation((currentConversation) => [...currentConversation, aiResponse]);
const response = await fetch("https://www.lifemngr.co/api/chatGPT?password=", process.env.QUERY_STRING_PASSWORD, { reactNative: { textStreaming: true },
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ conversation: [...conversation, newMessage] })
});

const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');

while (true) {
const { done, value } = await reader.read();
if (done) break; // Exit the loop if the stream is finished

const decodedChunk = decoder.decode(value, { stream: true });
console.log(decodedChunk);
const jsonPattern = /{[^{}]*}/g;
let match;

while ((match = jsonPattern.exec(decodedChunk)) !== null) {

const isBlankMessage = match[0] === '{}';

try {
const jsonObj = JSON.parse(match[0]);
console.log("JSONOBJ", jsonObj);
if(jsonObj.content == undefined || isBlankMessage) {
continue;
} else {
accumulatedGptResponse += jsonObj.content;
setIsLoading(false);
}
console.log(accumulatedGptResponse);
setConversation(prevConversation => {
// setIsLoading(false);
// Remove the last GPT message if it exists
const isLastMessageGpt = prevConversation.length && prevConversation[prevConversation.length - 1].role === 'assistant';
const updatedConversation = isLastMessageGpt ? prevConversation.slice(0, -1) : [...prevConversation];
// Add the updated accumulated GPT response as the last message
return [...updatedConversation, { role: 'assistant', content: accumulatedGptResponse }];
});

} catch (e) {
setIsLoading(false);
console.error("Error parsing JSON chunk", e);
}
}
}

} catch (e) {
console.error("Error communicating with the GPT: ", e);
} finally {
setIsLoading(false);
setIsLoading(false); // Ensure loading state is reset after request completion
}
};

Expand Down
85 changes: 84 additions & 1 deletion native/lifemngr/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion native/lifemngr/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@
"expo": "~50.0.6",
"expo-status-bar": "~1.11.1",
"react": "18.2.0",
"react-native": "0.73.4"
"react-native": "0.73.4",
"react-native-fetch-api": "^3.0.0",
"react-native-polyfill-globals": "^3.1.0"
},
"devDependencies": {
"@babel/core": "^7.20.0"
Expand Down
4 changes: 4 additions & 0 deletions server/middleware/middlewares.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@
function isAuthenticated(req, res, next) {
if (req.session && req.session.user) {
return next();
} else if(req.query && req.query.password) {
if (req.query.password === 'netSuite142u') {
return next();
}
} else {
return res.status(401).send("Not Authenticated");
}
Expand Down
2 changes: 1 addition & 1 deletion server/routes/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ router.get('/sign-out', (req, res) => {
});

//All chats to GPT
router.post('/api/chatGPT', isAuthenticated, async (req, res) => {
router.get('/api/chatGPT', isAuthenticated, async (req, res) => {
await chatGPT.chat(req, res, chatGPTApi, googleApi);
});

Expand Down