chatgpt-web/src/views/chat/index.vue

637 lines
17 KiB
Vue
Raw Normal View History

2024-02-06 06:46:56 +00:00
<script setup>
2024-01-25 08:50:39 +00:00
import {uploadFormData, uploadImg} from "@/api/api";
2024-02-05 01:09:54 +00:00
import {Local} from "@/utils/storage/storage";
2024-01-23 12:01:13 +00:00
import dayjs from "dayjs";
2024-02-06 06:46:56 +00:00
import {computed, onMounted, onUnmounted, ref, watch} from 'vue'
import {useRoute} from 'vue-router'
import {NAutoComplete, NButton, NInput, useDialog, useMessage, NBackTop} from 'naive-ui'
import {AreaChartOutlined, PlusOutlined} from '@ant-design/icons-vue';
2024-01-22 08:49:34 +00:00
import html2canvas from 'html2canvas'
2024-02-06 06:46:56 +00:00
import {Message} from './components'
import {useScroll} from './hooks/useScroll'
import {useChat} from './hooks/useChat'
import {useUsingContext} from './hooks/useUsingContext'
2024-01-22 08:49:34 +00:00
import HeaderComponent from './components/Header/index.vue'
2024-02-06 06:46:56 +00:00
import {HoverButton, SvgIcon} from '@/components/common'
import {useBasicLayout} from '@/hooks/useBasicLayout'
import {useChatStore, usePromptStore} from '@/store'
import {fetchChatAPIProcess} from '@/api'
import {t} from '@/locales'
import {UploadOutlined} from '@ant-design/icons-vue';
2024-01-24 12:00:45 +00:00
import {storeToRefs} from 'pinia'
2024-02-06 06:46:56 +00:00
import {sessionDetailForSetup} from '@/store'
2024-02-28 05:14:49 +00:00
import StopSvg from '@/assets/RecordStop12Regular.svg'
2024-02-06 06:46:56 +00:00
const sessionDetailData = sessionDetailForSetup()
2024-01-22 08:49:34 +00:00
let controller = new AbortController()
2024-02-06 06:46:56 +00:00
const {
sessionDetail: dataSources,
currentListUuid,
gptMode,
isStop,
2024-02-28 05:14:49 +00:00
isGPT4,
loading
2024-02-06 06:46:56 +00:00
} = storeToRefs(sessionDetailData)
2024-01-25 08:50:39 +00:00
2024-01-22 08:49:34 +00:00
const dialog = useDialog()
const ms = useMessage()
const chatStore = useChatStore()
2024-02-06 06:46:56 +00:00
const {isMobile} = useBasicLayout()
const {
addChat,
updateChat,
updateChatSome,
getChatByUuidAndIndex
} = useChat()
const {
scrollRef,
scrollToBottom,
scrollToBottomIfAtBottom
} = useScroll()
const {
usingContext,
toggleUsingContext
} = useUsingContext()
2024-01-23 12:01:13 +00:00
const prompt = ref('')
const inputRef = ref(null)
2024-01-22 08:49:34 +00:00
// 添加PromptStore
const promptStore = usePromptStore()
// 使用storeToRefs保证store修改后联想部分能够重新渲染
2024-02-06 06:46:56 +00:00
const {promptList: promptTemplate} = storeToRefs(promptStore)
2024-01-22 08:49:34 +00:00
// 未知原因刷新页面loading 状态不会重置,手动重置
2024-01-24 12:00:45 +00:00
dataSources.value.forEach((item, index) => {
2024-02-06 06:46:56 +00:00
if (item.loading) {
updateChatSome(+uuid, index, {loading: false})
}
2024-01-22 08:49:34 +00:00
})
2024-02-06 06:46:56 +00:00
2024-01-22 08:49:34 +00:00
function handleSubmit() {
2024-02-28 05:14:49 +00:00
if (loading.value){
handleStop()
}else {
dataSources.value.push({
dateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
text: prompt.value?.trim(),
inversion: true,
error: false,
fileList: fileList.value.map(x => x.url),
loading: false
})
sendDataStream()
scrollToBottom('smooth')
}
2024-01-22 08:49:34 +00:00
}
2024-02-28 05:14:49 +00:00
//一键滚动到底部,一键滚动到顶部逻辑未完善
/* const isTopBottom=()=>{
if ( scrollRef.value.scrollTop ===0){
2024-02-06 06:46:56 +00:00
2024-02-28 05:14:49 +00:00
}
} */
2024-01-23 12:01:13 +00:00
2024-02-28 05:14:49 +00:00
const API_URL = `${import.meta.env.VITE_APP_API_BASE_URL}/chat/completion`;
2024-01-23 12:01:13 +00:00
const createParams = () => {
2024-02-06 06:46:56 +00:00
const messages = dataSources.value.map((x) => {
return {
content: (() => {
if (gptMode.value === 'gpt-4-vision-preview') {
return [{
type: "text",
text: x.text
}, ...x.fileList.map((y) => {
return {
type: "image_url",
image_url: y
}
})]
} else {
return x.text
}
})(),
role: x.inversion ? 'user' : 'assistant'
}
});
return {
type: isFile.value ? 'custom' : '',
listUuid: currentListUuid.value,
messages,
frequency_penalty: 0,
max_tokens: 1000,
model: gptMode.value,
presence_penalty: 0,
stream: true,
temperature: 1,
top_p: 1
};
2024-01-23 12:01:13 +00:00
};
const handleResponseStream = async (reader) => {
2024-02-06 06:46:56 +00:00
const {
done,
value
} = await reader.read();
if (!done) {
let decoded = new TextDecoder().decode(value);
let decodedArray = decoded.split("data: ");
for (const decoded of decodedArray) {
if (decoded !== "") {
if (decoded.trim() === "[DONE]") {
dataSources.value[dataSources.value.length - 1].loading = false
loading.value = false
} else {
if (isStop.value) {
dataSources.value[dataSources.value.length - 1].loading = false
loading.value = false
return;
}
loading.value = true
dataSources.value[dataSources.value.length - 1].loading = true
const response = JSON.parse(decoded).choices[0].delta.content
? JSON.parse(decoded).choices[0].delta.content
: "";
dataSources.value[dataSources.value.length - 1].text += response;
}
}
}
await handleResponseStream(reader);
}
2024-01-23 12:01:13 +00:00
};
const sendDataStream = async () => {
2024-02-06 06:46:56 +00:00
const params = createParams();
fileList.value = []
prompt.value = ''
isStop.value = false
dataSources.value.push({
dateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
text: '思考中..',
inversion: false,
error: false,
loading: true
});
visible.value = false
try {
const response = await fetch(API_URL, {
method: "POST",
timeout: 10000,
body: JSON.stringify(params),
headers: {
"Content-Type": "application/json",
Accept: "application/json",
Authorization: Local.get('token'),
},
});
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const reader = response.body.getReader();
dataSources.value[dataSources.value.length - 1].text = ''
await handleResponseStream(reader);
}
} catch (error) {
console.error('发生错误:', error);
}
2024-01-23 12:01:13 +00:00
};
2024-02-06 06:46:56 +00:00
2024-01-22 08:49:34 +00:00
function handleExport() {
2024-02-06 06:46:56 +00:00
if (loading.value) {
return
}
const d = dialog.warning({
title: t('chat.exportImage'),
content: t('chat.exportImageConfirm'),
positiveText: t('common.yes'),
negativeText: t('common.no'),
onPositiveClick: async () => {
try {
d.loading = true
const ele = document.getElementById('image-wrapper')
const canvas = await html2canvas(ele, {
useCORS: true,
})
const imgUrl = canvas.toDataURL('image/png')
const tempLink = document.createElement('a')
tempLink.style.display = 'none'
tempLink.href = imgUrl
tempLink.setAttribute('download', 'chat-shot.png')
if (typeof tempLink.download === 'undefined') {
tempLink.setAttribute('target', '_blank')
}
document.body.appendChild(tempLink)
tempLink.click()
document.body.removeChild(tempLink)
window.URL.revokeObjectURL(imgUrl)
d.loading = false
ms.success(t('chat.exportSuccess'))
Promise.resolve()
} catch (error) {
ms.error(t('chat.exportFailed'))
} finally {
d.loading = false
}
},
})
2024-01-22 08:49:34 +00:00
}
2024-01-23 12:01:13 +00:00
function handleDelete(index) {
2024-02-06 06:46:56 +00:00
if (loading.value) {
return
}
dialog.warning({
title: t('chat.deleteMessage'),
content: t('chat.deleteMessageConfirm'),
positiveText: t('common.yes'),
negativeText: t('common.no'),
onPositiveClick: () => {
chatStore.deleteChatByUuid(+uuid, index)
},
})
2024-01-22 08:49:34 +00:00
}
function handleClear() {
2024-02-06 06:46:56 +00:00
if (loading.value) {
return
}
dialog.warning({
title: t('chat.clearChat'),
content: t('chat.clearChatConfirm'),
positiveText: t('common.yes'),
negativeText: t('common.no'),
onPositiveClick: () => {
chatStore.clearChatByUuid(+uuid)
},
})
2024-01-22 08:49:34 +00:00
}
2024-01-23 12:01:13 +00:00
function handleEnter(event) {
2024-02-06 06:46:56 +00:00
if (!isMobile.value) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
handleSubmit()
}
} else {
if (event.key === 'Enter' && event.ctrlKey) {
event.preventDefault()
handleSubmit()
}
}
2024-01-22 08:49:34 +00:00
}
2024-02-06 06:46:56 +00:00
2024-02-28 05:14:49 +00:00
function handleStop() {
2024-02-06 06:46:56 +00:00
if (loading.value) {
loading.value = false
isStop.value = true
}
2024-01-22 08:49:34 +00:00
}
// 可优化部分
// 搜索选项计算这里使用value作为索引项所以当出现重复value时渲染异常(多项同时出现选中效果)
// 理想状态下其实应该是key作为索引项,但官方的renderOption会出现问题所以就需要value反renderLabel实现
const searchOptions = computed(() => {
2024-02-06 06:46:56 +00:00
if (prompt.value.startsWith('/')) {
return promptTemplate.value.filter((item) => item.key.toLowerCase().includes(prompt.value.substring(1).toLowerCase())).map((obj) => {
return {
label: obj.value,
value: obj.value,
}
})
} else {
return []
}
2024-01-22 08:49:34 +00:00
})
// value反渲染key
2024-01-23 12:01:13 +00:00
const renderOption = (option) => {
2024-02-06 06:46:56 +00:00
for (const i of promptTemplate.value) {
if (i.value === option.label) {
return [i.key]
}
}
return []
2024-01-22 08:49:34 +00:00
}
const placeholder = computed(() => {
2024-02-06 06:46:56 +00:00
if (isMobile.value) {
return t('chat.placeholderMobile')
}
return t('chat.placeholder')
2024-01-22 08:49:34 +00:00
})
const buttonDisabled = computed(() => {
2024-02-28 05:14:49 +00:00
return prompt.value.trim() === '' &&!loading.value
2024-01-22 08:49:34 +00:00
})
const footerClass = computed(() => {
2024-02-06 06:46:56 +00:00
let classes = ['p-4']
if (isMobile.value) {
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-3', 'overflow-hidden']
}
return classes
2024-01-22 08:49:34 +00:00
})
2024-02-28 05:14:49 +00:00
const isShowBottom=ref(false)
2024-01-22 08:49:34 +00:00
onMounted(() => {
2024-02-28 05:14:49 +00:00
scrollRef.value.addEventListener('scroll', function() {
if (scrollRef.value.scrollTop + scrollRef.value.clientHeight +100>= scrollRef.value.scrollHeight) {
isShowBottom.value=false
}else {
isShowBottom.value=true
}
});
2024-02-06 06:46:56 +00:00
if (inputRef.value && !isMobile.value) {
inputRef.value?.focus()
}
2024-01-22 08:49:34 +00:00
})
2024-02-28 05:14:49 +00:00
const currentColor = ref('#ff0000'); // 初始颜色红色
const colors = ['#ff0000', '#ffffff']; // 颜色数组(红色和白色)
let intervalId = null;
// 计时器函数
const changeColor = () => {
currentColor.value = currentColor.value === colors[0] ? colors[1] : colors[0];
};
watch(loading,()=>{
if (loading.value){
intervalId = setInterval(changeColor, 1000);
}else {
clearInterval(intervalId);
}
})
2024-02-06 06:46:56 +00:00
const fileList = ref([]);
2024-01-22 08:49:34 +00:00
onUnmounted(() => {
2024-02-06 06:46:56 +00:00
if (loading.value) {
controller.abort()
}
2024-01-22 08:49:34 +00:00
})
2024-02-06 06:46:56 +00:00
2024-01-24 12:00:45 +00:00
function getBase64(file) {
2024-02-06 06:46:56 +00:00
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
2024-01-24 12:00:45 +00:00
}
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const handleCancel = () => {
2024-02-06 06:46:56 +00:00
previewVisible.value = false;
previewTitle.value = '';
2024-01-24 12:00:45 +00:00
};
const handlePreview = async (file) => {
2024-02-06 06:46:56 +00:00
if (!file.url && !file.preview) {
file.preview = (await getBase64(file.originFileObj))
}
previewImage.value = file.url || file.preview;
previewVisible.value = true;
previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
2024-01-24 12:00:45 +00:00
};
2024-01-23 12:01:13 +00:00
const value = ref('gpt-3.5-turbo');
2024-02-06 06:46:56 +00:00
const visible = ref(false)
const removeImg = (data) => {
fileList.value.splice(fileList.value.findIndex(x => x.url === data.url), 1)
2024-01-24 12:00:45 +00:00
}
2024-02-06 06:46:56 +00:00
watch(gptMode, () => {
currentListUuid.value = ''
dataSources.value = []
2024-01-24 12:00:45 +00:00
})
2024-02-06 06:46:56 +00:00
const visible1 = ref(false)
const fileList1 = ref([])
const isFile = ref(false)
const upItemImage1 = async (file) => {
const data = {
file: file.file,
}
const res = await uploadFormData(data)
if (res.code === 0) {
file.onSuccess()
dataSources.value = [...dataSources.value, ...res.data.paragraph.flatMap(n => [n, '']).map((x) => {
return {
dateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
text: x,
inversion: Boolean(x),
error: false,
}
})]
isFile.value = true
fileList1.value = []
visible1.value = false
sendDataStream()
}
2024-01-25 08:50:39 +00:00
}
2024-02-28 05:14:49 +00:00
watch(dataSources,()=>{
loading.value=false
scrollToBottom('auto')
})
2024-02-06 06:46:56 +00:00
const customRequest = async (file) => {
const res = await uploadImg({
file: file.file,
source: 'approval'
})
if (res.code === 0) {
file.onSuccess()
fileList.value.push({
url: res.data.ori_url
})
}
2024-01-24 12:00:45 +00:00
}
2024-01-23 12:01:13 +00:00
</script>
2024-01-22 08:49:34 +00:00
<template>
2024-02-06 06:46:56 +00:00
<div class="flex flex-col w-full h-full">
<HeaderComponent
v-if="isMobile"
:using-context="usingContext"
@export="handleExport"
@handle-clear="handleClear"
/>
<main class="flex-1 overflow-hidden">
2024-02-28 05:14:49 +00:00
<transition name="fade">
<div class="shortcut-arrow" v-if="isShowBottom">
2024-02-06 06:46:56 +00:00
<div class="top">
2024-02-28 05:14:49 +00:00
<n-button @click="scrollToBottom('smooth')" type="primary" dashed circle>
2024-02-06 06:46:56 +00:00
<template #icon>
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 512 512">
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48"
d="M244 400L100 256l144-144"
></path>
<path fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="48"
d="M120 256h292"
></path>
</svg>
</template>
</n-button>
</div>
</div>
2024-02-28 05:14:49 +00:00
</transition>
2024-02-06 06:46:56 +00:00
<div id="scrollRef" ref="scrollRef" class="h-full overflow-hidden overflow-y-auto">
<div
id="image-wrapper"
class="w-full max-w-screen-xl m-auto dark:bg-[#101014]"
:class="[isMobile ? 'p-2' : 'p-4']"
>
<template v-if="!dataSources.length">
<div class="flex items-center justify-center mt-4 text-center text-neutral-300">
<SvgIcon icon="ri:bubble-chart-fill" class="mr-2 text-3xl"/>
<span>当前没有会话哦</span>
</div>
</template>
<template v-else>
<div>
<Message
v-for="(item, index) of dataSources"
:key="index"
:date-time="item.dateTime"
:text="item.text"
:fileList="item.fileList"
:inversion="item.inversion"
:error="item.error"
:loading="item.loading"
@delete="handleDelete(index)"
/>
<div class="sticky bottom-0 left-0 flex justify-center">
2024-02-28 05:14:49 +00:00
<!-- <NButton v-if="loading" type="warning" @click="handleStop(item)">
2024-02-06 06:46:56 +00:00
<template #icon>
<SvgIcon icon="ri:stop-circle-line"/>
</template>
停止响应
2024-02-28 05:14:49 +00:00
</NButton>-->
2024-02-06 06:46:56 +00:00
</div>
</div>
</template>
</div>
</div>
</main>
<footer :class="footerClass">
<div class="w-full max-w-screen-xl m-auto">
<div class="flex items-center justify-between space-x-2" style="flex-wrap: initial">
<a-popover :open="visible1" trigger="click">
<template #content>
<div class="clearfix">
<a-upload
:max-count="1"
v-model:file-list="fileList1"
name="file"
:customRequest="upItemImage1"
>
<a-button>
<upload-outlined></upload-outlined>
上传文件
</a-button>
</a-upload>
</div>
</template>
<HoverButton @click="visible1=!visible1">
<span class="text-xl text-[#4f555e] dark:text-white"
style="display: flex;justify-content: center;align-items: center"
>
<SvgIcon icon="ri:upload-2-line"/>
2024-01-24 12:00:45 +00:00
</span>
2024-02-06 06:46:56 +00:00
</HoverButton>
</a-popover>
<a-popover v-if="gptMode==='gpt-4-vision-preview'" :open="visible" trigger="click">
<template #content>
<div class="clearfix">
<a-upload
:file-list="fileList"
:customRequest="customRequest"
list-type="picture-card"
@preview="handlePreview"
@remove="removeImg"
>
<div>
<plus-outlined/>
<div style="margin-top: 8px">上传</div>
</div>
</a-upload>
<a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
<img alt="example" style="width: 100%" :src="previewImage"/>
</a-modal>
</div>
</template>
<HoverButton @click="visible=!visible">
<span class="text-xl text-[#4f555e] dark:text-white"
style="display: flex;justify-content: center;align-items: center"
>
<AreaChartOutlined/>
2024-01-22 08:49:34 +00:00
</span>
2024-02-06 06:46:56 +00:00
</HoverButton>
</a-popover>
<!-- <HoverButton v-if="!isMobile" @click="handleClear">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:delete-bin-line" />
</span>
</HoverButton>-->
<HoverButton v-if="!isMobile" @click="handleExport">
2024-01-22 08:49:34 +00:00
<span class="text-xl text-[#4f555e] dark:text-white">
2024-02-06 06:46:56 +00:00
<SvgIcon icon="ri:download-2-line"/>
2024-01-22 08:49:34 +00:00
</span>
2024-02-06 06:46:56 +00:00
</HoverButton>
<!-- <HoverButton @click="toggleUsingContext">
<span class="text-xl" :class="{ 'text-[#4b9e5f]': usingContext, 'text-[#a8071a]': !usingContext }">
<SvgIcon icon="ri:chat-history-line" />
</span>
</HoverButton>-->
<NAutoComplete v-model:value="prompt" :options="searchOptions" :render-label="renderOption">
<template #default="{ handleInput, handleBlur, handleFocus }">
<NInput
ref="inputRef"
v-model:value="prompt"
type="textarea"
:placeholder="placeholder"
:autosize="{ minRows: 1, maxRows: isMobile ? 4 : 8 }"
@input="handleInput"
@focus="handleFocus"
@blur="handleBlur"
@keypress="handleEnter"
/>
</template>
</NAutoComplete>
2024-02-28 05:14:49 +00:00
<NButton color="#8a2be2" type="primary" :disabled="buttonDisabled" @click="handleSubmit">
2024-02-06 06:46:56 +00:00
<template #icon>
2024-02-28 05:14:49 +00:00
<span class="dark:text-black" v-if="!loading">
<SvgIcon icon="ri:send-plane-fill"/>
</span>
<span class="dark:text-black" v-if="loading">
<svg style="width:100%;height:100%;" xmlns="http://www.w3.org/2000/svg" :style="{color:currentColor}" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 12 12"><g fill="none"><path d="M5 4a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1H5zm6 2A5 5 0 1 1 1 6a5 5 0 0 1 10 0zm-1 0a4 4 0 1 0-8 0a4 4 0 0 0 8 0z" fill="currentColor"></path></g></svg>
2024-01-22 08:49:34 +00:00
</span>
2024-02-06 06:46:56 +00:00
</template>
</NButton>
</div>
</div>
</footer>
</div>
2024-01-22 08:49:34 +00:00
</template>
2024-02-06 06:46:56 +00:00
<style lang="scss" scoped>
2024-02-28 05:14:49 +00:00
.fade-enter-active, .fade-leave-active {
transition: opacity 0.4s ease-in-out;
}
.fade-enter-from, .fade-leave-to {
opacity: 0;
}
2024-02-06 06:46:56 +00:00
.shortcut-arrow {
width: min-content;
height: min-content;
position: absolute;
z-index: 10;
left: 50%;
2024-02-28 05:14:49 +00:00
bottom: 100px;
2024-02-06 06:46:56 +00:00
.top {
transform: rotate(270deg) translateX(-50%);
width: min-content;
height: min-content;
}
}
</style>