Skip to content

Commit

Permalink
improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
AitorAlgorta committed Aug 30, 2023
1 parent f3e59e1 commit 1b59e6d
Show file tree
Hide file tree
Showing 7 changed files with 140 additions and 283 deletions.
46 changes: 10 additions & 36 deletions frontend/inbox/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import React, {useEffect, useState} from 'react';
import {connect, ConnectedProps} from 'react-redux';
import {Route, Routes, Navigate} from 'react-router-dom';
import jwt_decode from 'jwt-decode';

import TopBar from './components/TopBar';
import Inbox from './pages/Inbox';
Expand All @@ -15,7 +14,7 @@ import {CONTACTS_ROUTE, INBOX_ROUTE, ROOT_ROUTE, TAGS_ROUTE} from './routes/rout

import styles from './App.module.scss';
import {getClientConfig} from './actions/config';
import {createChannelForNewUser} from './services';
import {createChannelForNewUser, getGmailEmail, getTokens, initializeOauth} from './services';
import {listChannels} from './actions';
import {env} from './env';
import {Channel} from 'model';
Expand Down Expand Up @@ -44,12 +43,18 @@ const App = (props: ConnectedProps<typeof connector>) => {
}
}, []);

const [isGoogleLoggedIn, setIsGoogleLoggedIn] = useState(localStorage.getItem('googleUserInfo'));
useEffect(() => {
const queryParameters = new URLSearchParams(window.location.search);
const code = queryParameters.get('code');
if (code) getTokens(code, response => setIsGoogleLoggedIn(JSON.stringify(response)));
}, []);

const [isGoogleLoggedIn, setIsGoogleLoggedIn] = useState(localStorage.getItem('googleCredentials'));

useEffect(() => {
if (isGoogleLoggedIn) {
props.listChannels().then((channelList: Channel[]) => {
const userId = JSON.parse(isGoogleLoggedIn)['email'];
const userId = getGmailEmail();
const existingChannel = channelList.filter(channel => channel.sourceChannelId === userId);
if (!!existingChannel.length) {
createChannelForNewUser(userId, existingChannel[0]);
Expand All @@ -61,41 +66,10 @@ const App = (props: ConnectedProps<typeof connector>) => {
}, [isGoogleLoggedIn]);

useEffect(() => {
window.google.accounts.id.initialize({
client_id: env.GOOGLE_CLIENT_ID,
scope:
'https://www.googleapis.com/auth/gmail.readonly \
https://www.googleapis.com/auth/gmail.send',
callback: handleCredentialResponse,
});

initializeOauth();
window.google.accounts.id.renderButton(document.getElementById('g_id_onload'), {theme: 'outline', size: 'large'});
}, []);

const handleCredentialResponse = response => {
localStorage.setItem('googleUserCredentials', JSON.stringify(response));
const decoded = jwt_decode(response['credential']);
localStorage.setItem('googleUserInfo', JSON.stringify(decoded));
getRefreshToken();
};

const getRefreshToken = () => {
const client = window.google.accounts.oauth2.initTokenClient({
client_id: env.GOOGLE_CLIENT_ID,
scope:
'https://www.googleapis.com/auth/gmail.readonly \
https://www.googleapis.com/auth/gmail.send',
callback: tokenResponse => {
if (tokenResponse && tokenResponse.access_token) {
localStorage.setItem('googleCredentials', JSON.stringify(tokenResponse));
setIsGoogleLoggedIn(JSON.stringify(tokenResponse));
}
},
});

client.requestAccessToken();
};

if (!isGoogleLoggedIn) {
return (
<div className={styles.container}>
Expand Down
45 changes: 22 additions & 23 deletions frontend/inbox/src/components/ConversationSuggestions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,31 +31,30 @@ const ConversationSuggestion = (props: ConversationSuggestionProps) => {
const [summaryLoader, setSummaryLoader] = useState<boolean>(true);
const [actionItemsLoader, setActionItemsLoader] = useState<boolean>(true);

useEffect(() => {
toolkitAI.chatQuestion('Who was Albert Einstein?')
// if (conversation && conversation.lastMessage) {
// setTopicLoader(true);
// toolkitAI
// .askQuestion(
// `Analyse these messages of this email thread and give me the top 3 topics being mentioned (no more than 50 characters per topic) in the email: ${JSON.stringify(
// conversation.lastMessage
// )}`
// )
// .then((value: any) => {
// if (timeoutTopics) clearTimeout(timeoutTopics);
// setTopicLoader(true);
// setTopics(value.trim());
// timeoutTopics = setTimeout(() => {
// setTopicLoader(false);
// }, 1000);
// });
// return () => clearTimeout(timeoutTopics);
// }
useEffect(() => {
if (conversation && conversation.lastMessage) {
setTopicLoader(true);
toolkitAI
.askQuestion(
`Analyse these messages of this email thread and give me the top 3 topics being mentioned (no more than 50 characters per topic) in the email: ${JSON.stringify(
conversation.lastMessage
)}`
)
.then((value: any) => {
if (timeoutTopics) clearTimeout(timeoutTopics);
setTopicLoader(true);
setTopics(value.trim());
timeoutTopics = setTimeout(() => {
setTopicLoader(false);
}, 1000);
});
return () => clearTimeout(timeoutTopics);
}
}, [conversation.lastMessage]);

useEffect(() => {
// if (conversation && conversation.lastMessage) {
// setSummaryLoader(true);
// setSummaryLoader(true);
// toolkitAI
// .askQuestion(
// `Analyse these messages of this email give me a summary of the outcome of the email (no more than 150 characters): ${JSON.stringify(
Expand All @@ -76,7 +75,7 @@ const ConversationSuggestion = (props: ConversationSuggestionProps) => {

useEffect(() => {
// if (conversation && conversation.lastMessage) {
// setActionItemsLoader(true);
// setActionItemsLoader(true);
// toolkitAI
// .askQuestion(
// `Analyse the messages of this email give me a 3 actions items to do with this email (no more than 30 characters per item): ${JSON.stringify(
Expand All @@ -96,7 +95,7 @@ const ConversationSuggestion = (props: ConversationSuggestionProps) => {
}, [conversation.lastMessage]);

useEffect(() => {
// if (conversation && conversation.lastMessage) {
// if (conversation && conversation.lastMessage) {
// toolkitAI
// .askQuestion(
// `Generate three suggested email replies that make sense to this messages of an email thread (separate them by /). Keep in mind that these messages are an email thread and might be spam, marketing email or job opportunities. Also, don't add any title or numeration before each suggestion: ${JSON.stringify(
Expand Down
43 changes: 17 additions & 26 deletions frontend/inbox/src/services/ai/index.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,19 @@
import { ChatOpenAI } from "langchain/chat_models/openai";
import { HumanMessage } from "langchain/schema";
import {ChatOpenAI} from 'langchain/chat_models/openai';
import {HumanMessage} from 'langchain/schema';
import {OpenAI} from 'langchain/llms/openai';
// import { Conversation, Message } from 'model';
// import { FaissStore } from "langchain/vectorstores/faiss";
// import { OpenAIEmbeddings } from "langchain/embeddings/openai";

export class ToolkitAI {
private static instance: ToolkitAI;

private static model = new OpenAI({
openAIApiKey: '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',
openAIApiKey: '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',
maxTokens: 32000,
temperature: 0.9,
});

private static chat = new ChatOpenAI({
openAIApiKey: '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',
maxTokens: 100,
openAIApiKey: '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',
maxTokens: 40000,
streaming: true,
});

Expand All @@ -28,28 +26,21 @@ export class ToolkitAI {
return ToolkitAI.instance;
}

// public loadConversations = async (conversations: string[]) => {
// // Create a vector store through any method, here from texts as an example
// const vectorStore = await FaissStore.fromTexts(conversations,
// [{ id: 2 }, { id: 1 }, { id: 3 }],
// new OpenAIEmbeddings()
// );
// };

public askQuestion = async (question: string): Promise<string> => {
const res = await ToolkitAI.model.call(question);
//const res = await ToolkitAI.model.call(question);
const res = 'HI'
return new Promise(resolve => resolve(res));
};

public chatQuestion = async (question: string) => {
public chatQuestion = async (question: string) => {
await ToolkitAI.chat.call([new HumanMessage(question)], {
callbacks: [
{
handleLLMNewToken(token: string) {
console.log({ token });
callbacks: [
{
handleLLMNewToken(token: string) {
console.log({token});
},
},
},
],
})
],
});
};
}
}
Loading

0 comments on commit 1b59e6d

Please sign in to comment.