Skip to content

Commit

Permalink
🔗 Integrate ChatGPT API with axios
Browse files Browse the repository at this point in the history
  • Loading branch information
hidragos committed Mar 22, 2023
1 parent c846943 commit cf6cf76
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 12 deletions.
2 changes: 1 addition & 1 deletion server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ app.post('/chat', async (req, res) => {
res.json(response);
});

const PORT = process.env.PORT || 3500;
const PORT = 3500;

app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
Expand Down
58 changes: 47 additions & 11 deletions src/App.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,52 @@
import './App.css';
import React, { useState } from 'react';
import axios from 'axios';
import config from './config';
import ChatBubble from './components/ChatBubble';
import ChatInput from './components/ChatInput';
import './App.css';

const App = () => {
const [messages, setMessages] = useState([]);

const addMessage = (message, isUser) => {
setMessages((prevMessages) => [...prevMessages, { message, isUser }]);
};

const sendMessage = async (message) => {
addMessage(message, true);

try {
const response = await axios.post(
`${config.apiUrl}`,
{
prompt:
'only respond to new message. previous messages: ' +
messages.map((msg) => msg.message).join(', ') +
', new message:' +
message,
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}`,
},
}
);

const chatGptResponse = response.data;
addMessage(chatGptResponse, false);
} catch (error) {
console.error('Error fetching ChatGPT response:', error);
addMessage('Error: Unable to fetch response from ChatGPT.', false);
}
};

function App() {
return (
<div className="App">
<header className="App-header">
<ChatBubble></ChatBubble>
<ChatInput></ChatInput>
</header>
</div>
);
}
return (
<div className="app">
<ChatBubble></ChatBubble>
<ChatInput></ChatInput>
</div>
);
};

export default App;
6 changes: 6 additions & 0 deletions src/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
const config = {
apiUrl: 'https://localhost:3500/chat',
};

export default config;

0 comments on commit cf6cf76

Please sign in to comment.