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

Added streaming chat response and AI Pay #41

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/logo.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name='ai-pay-website-identifier' content='{"websiteId":"Q07WY9bv0424plaoAcf3","websiteName":"ChatGPT-Pro","websiteDescription":"ChatGPT-Pro is an advanced application that combines the power of ChatGPT and DALL.E.","recommendedCredit":10,"requestUsageOnPageLoad":true}'>
<title>AI chat</title>
</head>
<body>
Expand Down
81 changes: 81 additions & 0 deletions package-lock.json

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

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,13 @@
"scripts": {
"dev": "vite",
"build": "vite build",
"build:githubPages": "vite build --base /chatgpt-pro/",
"lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
"preview": "vite preview"
},
"dependencies": {
"ai-pay": "^0.3.6",
"ai-pay-react-hooks": "^0.0.2",
"langchain": "^0.0.155",
"moment": "^2.29.4",
"no-profanity": "^1.5.1",
Expand Down
6 changes: 4 additions & 2 deletions src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,21 @@ import ChatView from './components/ChatView';
import { useEffect, useState } from 'react';
import Modal from './components/Modal';
import Setting from './components/Setting';
import { AiPayClient } from "ai-pay";

const App = () => {
const [modalOpen, setModalOpen] = useState(false);

useEffect(() => {
const apiKey = window.localStorage.getItem('api-key');
if (!apiKey) {
const aiPaySessionId = AiPayClient.getInstance().getClientSessionId();
if (!apiKey && !aiPaySessionId) {
setModalOpen(true);
}
}, []);
return (
<ChatContextProvider>
<Modal title='Setting' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Modal title='AI Provider' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Setting modalOpen={modalOpen} setModalOpen={setModalOpen} />
</Modal>
<div className='flex transition duration-500 ease-in-out'>
Expand Down
28 changes: 20 additions & 8 deletions src/components/ChatView.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { davinci } from '../utils/davinci';
import { dalle } from '../utils/dalle';
import Modal from './Modal';
import Setting from './Setting';
import { AiPayClient } from 'ai-pay';

const options = ['ChatGPT', 'DALL·E'];
const gptModel = ['gpt-3.5-turbo', 'gpt-4'];
Expand Down Expand Up @@ -42,6 +43,7 @@ const ChatView = () => {
const [gpt, setGpt] = useState(gptModel[0]);
const [messages, addMessage] = useContext(ChatContext);
const [modalOpen, setModalOpen] = useState(false);
const [streamedResponse, setStreamedResponse] = useState(undefined);

/**
* Scrolls the chat area to the bottom.
Expand Down Expand Up @@ -78,7 +80,8 @@ const ChatView = () => {
e.preventDefault();

const key = window.localStorage.getItem('api-key');
if (!key) {
const sessionId = AiPayClient.getInstance().getClientSessionId();
if (!key && !sessionId) {
setModalOpen(true);
return;
}
Expand All @@ -97,13 +100,15 @@ const ChatView = () => {
console.log(selected);
try {
if (aiModel === options[0]) {
const LLMresponse = await davinci(cleanPrompt, key, gptVersion);
//const data = response.data.choices[0].message.content;
const LLMresponse = await davinci(cleanPrompt, key, gptVersion, (streamedResponse) => {
setStreamedResponse(streamedResponse);
});
setStreamedResponse(undefined);

LLMresponse && updateMessage(LLMresponse, true, aiModel);
} else {
const response = await dalle(cleanPrompt, key);
const data = response.data.data[0].url;
data && updateMessage(data, true, aiModel);
const responseUrl = await dalle(cleanPrompt, key);
responseUrl && updateMessage(responseUrl, true, aiModel);
}
} catch (err) {
window.alert(`Error: ${err} please try again later`);
Expand Down Expand Up @@ -171,7 +176,14 @@ const ChatView = () => {
</div>
)}

{thinking && <Thinking />}
{thinking && !streamedResponse && <Thinking />}

{streamedResponse && <Message message={{
id: "stream",
text: streamedResponse,
ai: true,
selected: options[0],
}} />}

<span ref={messagesEndRef}></span>
</section>
Expand All @@ -198,7 +210,7 @@ const ChatView = () => {
</button>
</div>
</form>
<Modal title='Setting' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Modal title='AI Provider' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Setting modalOpen={modalOpen} setModalOpen={setModalOpen} />
</Modal>
</main>
Expand Down
2 changes: 1 addition & 1 deletion src/components/Message.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const Message = (props) => {
<div className='chat-bubble text-neutral-content'>
<Markdown markdownText={text} />
<div className={`${ai ? 'text-left' : 'text-right'} text-xs`}>
{moment(createdAt).calendar()}
{createdAt && moment(createdAt).calendar()}
</div>
</div>
</div>
Expand Down
35 changes: 34 additions & 1 deletion src/components/Setting.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { useEffect, useState } from 'react';
import { checkApiKey } from '../utils/checkKeys';
import { useSessionData } from 'ai-pay-react-hooks';

import PropTypes from 'prop-types';

Expand All @@ -9,6 +10,17 @@ const Setting = ({ modalOpen, setModalOpen }) => {
const [errorMsg, setErrorMsg] = useState('');
const [input, setInput] = useState('');

const {
browserExtensionInstalled,
sessionState,
} = useSessionData();

useEffect(() => {
if (sessionState === "ACTIVE") {
setModalOpen(false);
}
}, [sessionState, setModalOpen])

const saveKey = async (e) => {
e.preventDefault();
setLoading(true);
Expand Down Expand Up @@ -44,7 +56,7 @@ const Setting = ({ modalOpen, setModalOpen }) => {
<form
onSubmit={saveKey}
className='flex flex-col items-center justify-center gap-2'>
<p className='text-lg font-semibold'>Use your own API-key.</p>
<p className='text-lg font-semibold'>Use your OpenAI API key.</p>
<p>keys are saved in your own browser</p>
<p className='italic'>
Get OpenAI API key{' '}
Expand All @@ -59,6 +71,7 @@ const Setting = ({ modalOpen, setModalOpen }) => {
</p>
<input
value={input}
placeholder='sk-...'
onChange={(e) => setInput(e.target.value)}
type='password'
className='w-full max-w-xs input input-bordered'
Expand All @@ -82,6 +95,26 @@ const Setting = ({ modalOpen, setModalOpen }) => {
</span>
)}
<p>{errorMsg}</p>

<div className='flex w-full items-center gap-2 '>
<hr className='w-full opacity-50' />
<p>OR</p>
<hr className='w-full opacity-50' />
</div>

<p className='text-lg font-semibold'>Use AI Pay</p>
{sessionState === "ACTIVE" ? (
<p className='w-full max-w-xs text-center bg-neutral-500/20 rounded-md px-2 py-1'>AI Pay session is active. You can now use ChatGPT-Pro.</p>
) : (
<a
className='mx-auto w-full max-w-xs btn btn-outline'
href={browserExtensionInstalled ?
'https://www.joinaipay.com/welcome'
: 'https://chromewebstore.google.com/detail/ai-pay/igghgdjfklipjmgldcdfnpppgaijmhfg'}
>
{browserExtensionInstalled ? 'Learn how to start a session' : 'Download AI Pay'}
</a>
)}
</form>
);
};
Expand Down
4 changes: 2 additions & 2 deletions src/components/SideBar.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,11 @@ const SideBar = () => {
<li>
<a onClick={() => setModalOpen(true)}>
<MdOutlineVpnKey size={15} />
<p className={`${!open && 'hidden'}`}>OpenAI Key</p>
<p className={`${!open && 'hidden'}`}>AI Provider</p>
</a>
</li>
</ul>
<Modal title='Setting' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Modal title='AI Provider' modalOpen={modalOpen} setModalOpen={setModalOpen}>
<Setting modalOpen={modalOpen} setModalOpen={setModalOpen} />
</Modal>
</section>
Expand Down
21 changes: 20 additions & 1 deletion src/utils/dalle.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
import { Configuration, OpenAIApi } from 'openai';
import { AiPayClient, imageGeneration } from 'ai-pay';

export const dalle = async (prompt, key) => {
const AiPaySessionId = AiPayClient.getInstance().getClientSessionId();

if (AiPaySessionId) {
const {
error,
data,
} = await imageGeneration({
prompt: `${prompt}`,
imageModel: "dall-e-2",
size: '512x512',
});

if (!data) {
throw new Error(error);
}
return data.imageUrls[0]
}

const configuration = new Configuration({
apiKey: key,
});
Expand All @@ -12,5 +31,5 @@ export const dalle = async (prompt, key) => {
size: '512x512',
});

return response;
return response.data.data[0].url;
};
Loading