feat : chatbot upload

This commit is contained in:
leejunghyeok 2024-05-21 10:03:47 +09:00
parent 2e6b230ea7
commit dcb840d277
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) => {
let attempt = 0;
const maxDelay = 32000; // 최대 지연 시간 (32초)
// export const sendMessageToChatGPT = async (message, retries = 3) => {
// let attempt = 0;
// const maxDelay = 32000; // 최대 지연 시간 (32초)
while (attempt < retries) {
try {
console.log(apiKey)
const response = await axios.post(
'https://api.openai.com/v1/chat/completions',
{
model: 'gpt-3.5-turbo', // 또는 다른 사용 가능한 모델로 변경
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: 'user', content: message }
],
},
{
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`,
},
}
);
// while (attempt < retries) {
// try {
// console.log(apiKey)
// const response = await axios.post(
// 'https://api.openai.com/v1/chat/completions',
// {
// model: 'gpt-3.5-turbo', // 또는 다른 사용 가능한 모델로 변경
// 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: 'user', content: message }
// ],
// },
// {
// headers: {
// 'Content-Type': 'application/json',
// 'Authorization': `Bearer ${apiKey}`,
// },
// }
// );
return response.data.choices[0].message.content;
} catch (error) {
if (error.response && error.response.status === 429) {
attempt++;
const backoffTime = Math.min(1000 * 2 ** attempt, maxDelay); // 지수 백오프
console.warn(`Rate limit exceeded. Retrying in ${backoffTime / 1000} seconds...`);
await delay(backoffTime);
} else {
console.error('Error calling OpenAI API:', error);
throw error;
}
}
// return response.data.choices[0].message.content;
// } catch (error) {
// if (error.response && error.response.status === 429) {
// attempt++;
// const backoffTime = Math.min(1000 * 2 ** attempt, maxDelay); // 지수 백오프
// console.warn(`Rate limit exceeded. Retrying in ${backoffTime / 1000} seconds...`);
// await delay(backoffTime);
// } else {
// console.error('Error calling OpenAI API:', 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="messages">
<div v-for="(msg, index) in messages" :key="index" :class="msg.role">
@ -100,4 +100,84 @@
cursor: pointer;
}
</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>