This commit is contained in:
jhynsoo 2024-05-21 16:37:54 +09:00
commit 9e3574cf36
3 changed files with 162 additions and 40 deletions

View File

@ -1,46 +1,63 @@
import axios from 'axios'; // import axios from 'axios';
const apiKey = import.meta.env.VITE_OPENAI_API_KEY; // const apiKey = import.meta.env.VITE_OPENAI_API_KEY;
const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms)); // const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
export const sendMessageToChatGPT = async (message, retries = 3) => { // export const sendMessageToChatGPT = async (message, retries = 3) => {
let attempt = 0; // let attempt = 0;
const maxDelay = 32000; // 최대 지연 시간 (32초) // const maxDelay = 32000; // 최대 지연 시간 (32초)
while (attempt < retries) { // while (attempt < retries) {
try { // try {
console.log(apiKey) // console.log(apiKey)
const response = await axios.post( // const response = await axios.post(
'https://api.openai.com/v1/chat/completions', // 'https://api.openai.com/v1/chat/completions',
{ // {
model: 'gpt-3.5-turbo', // 또는 다른 사용 가능한 모델로 변경 // model: 'gpt-3.5-turbo', // 또는 다른 사용 가능한 모델로 변경
messages: [ // messages: [
{ role: 'system', content: 'You are a tour guide for those who want to travel to Korea. Answer only questions related to your trip to Korea.' }, // { role: 'system', content: 'You are a tour guide for those who want to travel to Korea. Answer only questions related to your trip to Korea.' },
{ role: 'user', content: message } // { role: 'user', content: message }
], // ],
}, // },
{ // {
headers: { // headers: {
'Content-Type': 'application/json', // 'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`, // 'Authorization': `Bearer ${apiKey}`,
}, // },
} // }
); // );
return response.data.choices[0].message.content; // return response.data.choices[0].message.content;
} catch (error) { // } catch (error) {
if (error.response && error.response.status === 429) { // if (error.response && error.response.status === 429) {
attempt++; // attempt++;
const backoffTime = Math.min(1000 * 2 ** attempt, maxDelay); // 지수 백오프 // const backoffTime = Math.min(1000 * 2 ** attempt, maxDelay); // 지수 백오프
console.warn(`Rate limit exceeded. Retrying in ${backoffTime / 1000} seconds...`); // console.warn(`Rate limit exceeded. Retrying in ${backoffTime / 1000} seconds...`);
await delay(backoffTime); // await delay(backoffTime);
} else { // } else {
console.error('Error calling OpenAI API:', error); // console.error('Error calling OpenAI API:', error);
throw error; // throw error;
} // }
} // }
// }
// throw new Error('Exceeded maximum retry attempts');
// };
import { localAxios } from '@/utils/http-commons';
const local = localAxios;
const sendMessageToChatGPT = async (message) => {
try {
console.log(message)
const response = await local.post('/api/chatgpt/message', { message });
return response.data;
} catch (error) {
console.error('Error sending message to ChatGPT:', error);
return 'Sorry, there was an error processing your request.';
} }
throw new Error('Exceeded maximum retry attempts');
}; };
export default sendMessageToChatGPT;

View File

@ -1,4 +1,4 @@
<template> <!-- <template>
<div class="chat-container"> <div class="chat-container">
<div class="messages"> <div class="messages">
<div v-for="(msg, index) in messages" :key="index" :class="msg.role"> <div v-for="(msg, index) in messages" :key="index" :class="msg.role">
@ -100,4 +100,84 @@
cursor: pointer; cursor: pointer;
} }
</style> </style>
-->
<template>
<div class="chat-container">
<div class="chat-box">
<div class="messages">
<div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
<span>{{ msg.content }}</span>
</div>
</div>
<input v-model="userInput" @keyup.enter="sendMessage" placeholder="Ask me anything about travel" />
<button @click="sendMessage">Send</button>
</div>
</div>
</template>
<script>
import sendMessageToChatGPT from "@/api/chatbot";
export default {
data() {
return {
userInput: '',
messages: [],
};
},
methods: {
async sendMessage() {
if (this.userInput.trim() === '') return;
this.messages.push({ role: 'user', content: this.userInput });
console.log(this.userInput)
const response = await sendMessageToChatGPT(this.userInput);
this.messages.push({ role: 'assistant', content: response });
this.userInput = '';
},
},
};
</script>
<style scoped>
.chat-container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.chat-box {
width: 400px;
border: 1px solid #ccc;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.messages {
max-height: 300px;
overflow-y: auto;
margin-bottom: 20px;
}
.message {
padding: 10px;
border-radius: 5px;
margin-bottom: 10px;
}
.user {
background-color: #e0f7fa;
align-self: flex-end;
}
.assistant {
background-color: #fff9c4;
}
</style>

25
src/views/TestView.vue Normal file
View File

@ -0,0 +1,25 @@
<template>
<div id="app">
<TravelChatBot />
</div>
</template>
<script>
import TravelChatBot from '@/components/chatbot/TravelChatBot.vue';
export default {
name: 'App',
components: {
TravelChatBot,
},
};
</script>
<style>
body {
font-family: Avenir, Helvetica, Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
}
</style>