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

735 lines
21 KiB
Vue
Raw Normal View History

2024-01-23 12:01:13 +00:00
<script setup >
2024-01-24 12:00:45 +00:00
import {uploadImg} from "@/api/api";
2024-01-23 12:01:13 +00:00
import dayjs from "dayjs";
2024-01-24 12:00:45 +00:00
import { computed, onMounted, onUnmounted, ref,watch } from 'vue'
2024-01-22 08:49:34 +00:00
import { useRoute } from 'vue-router'
import { NAutoComplete, NButton, NInput, useDialog, useMessage } from 'naive-ui'
2024-01-24 12:00:45 +00:00
import { AreaChartOutlined ,PlusOutlined } from '@ant-design/icons-vue';
2024-01-22 08:49:34 +00:00
import html2canvas from 'html2canvas'
import { Message } from './components'
import { useScroll } from './hooks/useScroll'
import { useChat } from './hooks/useChat'
import { useUsingContext } from './hooks/useUsingContext'
import HeaderComponent from './components/Header/index.vue'
import { HoverButton, SvgIcon } from '@/components/common'
import { useBasicLayout } from '@/hooks/useBasicLayout'
import { useChatStore, usePromptStore } from '@/store'
import { fetchChatAPIProcess } from '@/api'
import { t } from '@/locales'
2024-01-24 12:00:45 +00:00
import {storeToRefs} from 'pinia'
2024-01-23 12:01:13 +00:00
import { sessionDetailForSetup } from '@/store'
const sessionDetailData=sessionDetailForSetup()
2024-01-22 08:49:34 +00:00
let controller = new AbortController()
2024-01-24 12:00:45 +00:00
const { sessionDetail:dataSources ,currentListUuid,gptMode} = storeToRefs(sessionDetailData)
2024-01-22 08:49:34 +00:00
const openLongReply = import.meta.env.VITE_GLOB_OPEN_LONG_REPLY === 'true'
const route = useRoute()
const dialog = useDialog()
const ms = useMessage()
const chatStore = useChatStore()
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 { uuid } = route.params
2024-01-24 12:00:45 +00:00
if (uuid){
currentListUuid.value=uuid
sessionDetailData.getSessionDetail()
}
const conversationList = computed(() => dataSources.value.filter(item => (!item.inversion && !!item.conversationOptions)))
2024-01-23 12:01:13 +00:00
const dataSessionDetail=ref([])
const prompt = ref('')
const loading = ref(false)
const inputRef = ref(null)
2024-01-22 08:49:34 +00:00
// 添加PromptStore
const promptStore = usePromptStore()
// 使用storeToRefs保证store修改后联想部分能够重新渲染
2024-01-23 12:01:13 +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-01-22 08:49:34 +00:00
if (item.loading)
updateChatSome(+uuid, index, { loading: false })
})
function handleSubmit() {
2024-01-24 12:00:45 +00:00
dataSources.value.push({
2024-01-23 12:01:13 +00:00
dateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
text: prompt.value,
inversion: true,
error: false,
2024-01-24 12:00:45 +00:00
fileList:fileList.value.map(x=>x.url)
2024-01-23 12:01:13 +00:00
})
sendDataStream()
/* onConversation() */
2024-01-22 08:49:34 +00:00
}
2024-01-23 12:01:13 +00:00
const API_URL = 'http://114.218.158.24:9020/chat/completion';
const createParams = () => {
2024-01-24 12:00:45 +00:00
const messages = dataSources.value.map((x) => {
return {
content:(()=>{
if (x.fileList?.length>0){
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'
}
});
2024-01-23 12:01:13 +00:00
return {
2024-01-24 12:00:45 +00:00
listUuid: currentListUuid.value,
2024-01-23 12:01:13 +00:00
messages,
frequency_penalty: 0,
max_tokens: 1000,
2024-01-24 12:00:45 +00:00
model: gptMode.value,
2024-01-23 12:01:13 +00:00
presence_penalty: 0,
stream: true,
temperature: 1,
top_p: 1
};
};
const handleResponseStream = async (reader) => {
const { done, value } = await reader.read();
if (!done) {
let decoded = new TextDecoder().decode(value);
let decodedArray = decoded.split("data: ");
decodedArray.forEach((decoded) => {
if (decoded !== "") {
if (decoded.trim() === "[DONE]") {
2024-01-24 12:00:45 +00:00
2024-01-23 12:01:13 +00:00
return;
} else {
2024-01-24 12:00:45 +00:00
console.log(decoded,'decoded')
2024-01-23 12:01:13 +00:00
const response = JSON.parse(decoded).choices[0].delta.content
? JSON.parse(decoded).choices[0].delta.content
: "";
2024-01-24 12:00:45 +00:00
dataSources.value[dataSources.value.length - 1].text += response;
2024-01-23 12:01:13 +00:00
}
}
});
await handleResponseStream(reader);
}
};
const sendDataStream = async () => {
2024-01-24 12:00:45 +00:00
const params = createParams();
fileList.value=[]
prompt.value=''
dataSources.value.push({
2024-01-23 12:01:13 +00:00
dateTime: dayjs().format('YYYY/MM/DD HH:mm:ss'),
text: '',
inversion: false,
error: 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: localStorage.getItem('token'),
},
});
2024-01-24 12:00:45 +00:00
console.log(dataSources.value,'dataSources.value')
2024-01-23 12:01:13 +00:00
const contentType = response.headers.get('Content-Type');
if (!contentType || !contentType.includes('application/json')) {
const reader = response.body.getReader();
await handleResponseStream(reader);
}
} catch (error) {
console.error('发生错误:', error);
}
};
2024-01-22 08:49:34 +00:00
async function onConversation() {
let message = prompt.value
if (loading.value)
return
if (!message || message.trim() === '')
return
controller = new AbortController()
addChat(
+uuid,
{
dateTime: new Date().toLocaleString(),
text: message,
inversion: true,
error: false,
conversationOptions: null,
requestOptions: { prompt: message, options: null },
},
)
scrollToBottom()
loading.value = true
prompt.value = ''
2024-01-23 12:01:13 +00:00
let options= {}
2024-01-22 08:49:34 +00:00
const lastContext = conversationList.value[conversationList.value.length - 1]?.conversationOptions
if (lastContext && usingContext.value)
options = { ...lastContext }
addChat(
+uuid,
{
dateTime: new Date().toLocaleString(),
text: t('chat.thinking'),
loading: true,
inversion: false,
error: false,
conversationOptions: null,
requestOptions: { prompt: message, options: { ...options } },
},
)
scrollToBottom()
try {
let lastText = ''
const fetchChatAPIOnce = async () => {
await fetchChatAPIProcess<Chat.ConversationResponse>({
prompt: message,
options,
signal: controller.signal,
onDownloadProgress: ({ event }) => {
const xhr = event.target
const { responseText } = xhr
// Always process the final line
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
let chunk = responseText
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
try {
const data = JSON.parse(chunk)
updateChat(
+uuid,
2024-01-24 12:00:45 +00:00
dataSources.value.length - 1,
2024-01-22 08:49:34 +00:00
{
dateTime: new Date().toLocaleString(),
text: lastText + (data.text ?? ''),
inversion: false,
error: false,
loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, options: { ...options } },
},
)
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
options.parentMessageId = data.id
lastText = data.text
message = ''
return fetchChatAPIOnce()
}
scrollToBottomIfAtBottom()
}
catch (error) {
//
}
},
})
2024-01-24 12:00:45 +00:00
updateChatSome(+uuid, dataSources.value.length - 1, { loading: false })
2024-01-22 08:49:34 +00:00
}
await fetchChatAPIOnce()
}
2024-01-23 12:01:13 +00:00
catch (error) {
2024-01-22 08:49:34 +00:00
const errorMessage = error?.message ?? t('common.wrong')
if (error.message === 'canceled') {
updateChatSome(
+uuid,
2024-01-24 12:00:45 +00:00
dataSources.value.length - 1,
2024-01-22 08:49:34 +00:00
{
loading: false,
},
)
scrollToBottomIfAtBottom()
return
}
2024-01-24 12:00:45 +00:00
const currentChat = getChatByUuidAndIndex(+uuid, dataSources.value.length - 1)
2024-01-22 08:49:34 +00:00
if (currentChat?.text && currentChat.text !== '') {
updateChatSome(
+uuid,
2024-01-24 12:00:45 +00:00
dataSources.value.length - 1,
2024-01-22 08:49:34 +00:00
{
text: `${currentChat.text}\n[${errorMessage}]`,
error: false,
loading: false,
},
)
return
}
updateChat(
+uuid,
2024-01-24 12:00:45 +00:00
dataSources.value.length - 1,
2024-01-22 08:49:34 +00:00
{
dateTime: new Date().toLocaleString(),
text: errorMessage,
inversion: false,
error: true,
loading: false,
conversationOptions: null,
requestOptions: { prompt: message, options: { ...options } },
},
)
scrollToBottomIfAtBottom()
}
finally {
loading.value = false
}
}
2024-01-24 12:00:45 +00:00
/* async function onRegenerate(index) {
2024-01-22 08:49:34 +00:00
if (loading.value)
return
controller = new AbortController()
2024-01-24 12:00:45 +00:00
const { requestOptions } = dataSources.value[index]
2024-01-22 08:49:34 +00:00
let message = requestOptions?.prompt ?? ''
2024-01-23 12:01:13 +00:00
let options = {}
2024-01-22 08:49:34 +00:00
if (requestOptions.options)
options = { ...requestOptions.options }
loading.value = true
updateChat(
+uuid,
index,
{
dateTime: new Date().toLocaleString(),
text: '',
inversion: false,
error: false,
loading: true,
conversationOptions: null,
requestOptions: { prompt: message, options: { ...options } },
},
)
try {
let lastText = ''
const fetchChatAPIOnce = async () => {
await fetchChatAPIProcess<Chat.ConversationResponse>({
prompt: message,
options,
signal: controller.signal,
onDownloadProgress: ({ event }) => {
const xhr = event.target
const { responseText } = xhr
// Always process the final line
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
let chunk = responseText
if (lastIndex !== -1)
chunk = responseText.substring(lastIndex)
try {
const data = JSON.parse(chunk)
updateChat(
+uuid,
index,
{
dateTime: new Date().toLocaleString(),
text: lastText + (data.text ?? ''),
inversion: false,
error: false,
loading: true,
conversationOptions: { conversationId: data.conversationId, parentMessageId: data.id },
requestOptions: { prompt: message, options: { ...options } },
},
)
if (openLongReply && data.detail.choices[0].finish_reason === 'length') {
options.parentMessageId = data.id
lastText = data.text
message = ''
return fetchChatAPIOnce()
}
}
catch (error) {
//
}
},
})
updateChatSome(+uuid, index, { loading: false })
}
await fetchChatAPIOnce()
}
2024-01-23 12:01:13 +00:00
catch (error) {
2024-01-22 08:49:34 +00:00
if (error.message === 'canceled') {
updateChatSome(
+uuid,
index,
{
loading: false,
},
)
return
}
const errorMessage = error?.message ?? t('common.wrong')
updateChat(
+uuid,
index,
{
dateTime: new Date().toLocaleString(),
text: errorMessage,
inversion: false,
error: true,
loading: false,
conversationOptions: null,
requestOptions: { prompt: message, options: { ...options } },
},
)
}
finally {
loading.value = false
}
2024-01-24 12:00:45 +00:00
} */
2024-01-22 08:49:34 +00:00
function handleExport() {
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')
2024-01-23 12:01:13 +00:00
const canvas = await html2canvas(ele, {
2024-01-22 08:49:34 +00:00
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()
}
2024-01-23 12:01:13 +00:00
catch (error) {
2024-01-22 08:49:34 +00:00
ms.error(t('chat.exportFailed'))
}
finally {
d.loading = false
}
},
})
}
2024-01-23 12:01:13 +00:00
function handleDelete(index) {
2024-01-22 08:49:34 +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)
},
})
}
function handleClear() {
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-23 12:01:13 +00:00
function handleEnter(event) {
2024-01-22 08:49:34 +00:00
if (!isMobile.value) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault()
handleSubmit()
}
}
else {
if (event.key === 'Enter' && event.ctrlKey) {
event.preventDefault()
handleSubmit()
}
}
}
function handleStop() {
if (loading.value) {
controller.abort()
loading.value = false
}
}
// 可优化部分
// 搜索选项计算这里使用value作为索引项所以当出现重复value时渲染异常(多项同时出现选中效果)
// 理想状态下其实应该是key作为索引项,但官方的renderOption会出现问题所以就需要value反renderLabel实现
const searchOptions = computed(() => {
if (prompt.value.startsWith('/')) {
2024-01-23 12:01:13 +00:00
return promptTemplate.value.filter((item) => item.key.toLowerCase().includes(prompt.value.substring(1).toLowerCase())).map((obj) => {
2024-01-22 08:49:34 +00:00
return {
label: obj.value,
value: obj.value,
}
})
}
else {
return []
}
})
// value反渲染key
2024-01-23 12:01:13 +00:00
const renderOption = (option) => {
2024-01-22 08:49:34 +00:00
for (const i of promptTemplate.value) {
if (i.value === option.label)
return [i.key]
}
return []
}
const placeholder = computed(() => {
if (isMobile.value)
return t('chat.placeholderMobile')
return t('chat.placeholder')
})
const buttonDisabled = computed(() => {
return loading.value || !prompt.value || prompt.value.trim() === ''
})
const footerClass = computed(() => {
let classes = ['p-4']
if (isMobile.value)
classes = ['sticky', 'left-0', 'bottom-0', 'right-0', 'p-2', 'pr-3', 'overflow-hidden']
return classes
})
onMounted(() => {
scrollToBottom()
if (inputRef.value && !isMobile.value)
inputRef.value?.focus()
})
2024-01-24 12:00:45 +00:00
const fileList = ref([
]);
2024-01-22 08:49:34 +00:00
onUnmounted(() => {
if (loading.value)
controller.abort()
})
2024-01-24 12:00:45 +00:00
function getBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
}
const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');
const handleCancel = () => {
previewVisible.value = false;
previewTitle.value = '';
};
const handlePreview = async (file) => {
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-23 12:01:13 +00:00
const value = ref('gpt-3.5-turbo');
2024-01-24 12:00:45 +00:00
const visible=ref(false)
2024-01-23 12:01:13 +00:00
const options=ref([{ label: 'GPT-3.5', value: 'gpt-3.5-turbo' },
{ label: 'GPT-4.0', value: 'gpt-4-1106-preview' },
{ label: 'GPT-V', value: 'gpt-4-vision-preview' }])
2024-01-24 12:00:45 +00:00
const removeImg=(data)=>{
fileList.value.splice(fileList.value.findIndex(x=>x.url===data.url),1)
}
watch(gptMode,()=>{
dataSources.value=[]
})
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
})
}
console.log(res,'res')
}
2024-01-23 12:01:13 +00:00
</script>
2024-01-22 08:49:34 +00:00
<template>
<div class="flex flex-col w-full h-full">
2024-01-23 12:01:13 +00:00
<div style="margin-top: 15px;margin-left: 15px">
<a-select
align="center"
2024-01-24 12:00:45 +00:00
v-model:value="gptMode"
2024-01-23 12:01:13 +00:00
style="width: 120px"
:dropdown-match-select-width="false"
>
<a-select-option align="center" v-for="(item,index) in options" :key="index" :value="item.value">{{item.label}}</a-select-option>
</a-select>
</div>
2024-01-22 08:49:34 +00:00
<HeaderComponent
v-if="isMobile"
:using-context="usingContext"
@export="handleExport"
@handle-clear="handleClear"
/>
<main class="flex-1 overflow-hidden">
<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>{{ t('chat.newChatTitle') }}</span>
</div>
</template>
<template v-else>
<div>
<Message
v-for="(item, index) of dataSources"
:key="index"
:date-time="item.dateTime"
:text="item.text"
2024-01-24 12:00:45 +00:00
:fileList="item.fileList"
2024-01-22 08:49:34 +00:00
:inversion="item.inversion"
:error="item.error"
:loading="item.loading"
@regenerate="onRegenerate(index)"
@delete="handleDelete(index)"
/>
<div class="sticky bottom-0 left-0 flex justify-center">
<NButton v-if="loading" type="warning" @click="handleStop">
<template #icon>
<SvgIcon icon="ri:stop-circle-line" />
</template>
{{ t('common.stopResponding') }}
</NButton>
</div>
</div>
</template>
</div>
</div>
</main>
<footer :class="footerClass">
<div class="w-full max-w-screen-xl m-auto">
2024-01-23 12:01:13 +00:00
<div class="flex items-center justify-between space-x-2" style="flex-wrap: initial">
2024-01-24 12:00:45 +00:00
<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 />
</span>
</HoverButton>
</a-popover>
<!-- <HoverButton v-if="!isMobile" @click="handleClear">
2024-01-22 08:49:34 +00:00
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:delete-bin-line" />
</span>
2024-01-24 12:00:45 +00:00
</HoverButton>-->
2024-01-22 08:49:34 +00:00
<HoverButton v-if="!isMobile" @click="handleExport">
<span class="text-xl text-[#4f555e] dark:text-white">
<SvgIcon icon="ri:download-2-line" />
</span>
</HoverButton>
2024-01-24 12:00:45 +00:00
<!-- <HoverButton @click="toggleUsingContext">
2024-01-22 08:49:34 +00:00
<span class="text-xl" :class="{ 'text-[#4b9e5f]': usingContext, 'text-[#a8071a]': !usingContext }">
<SvgIcon icon="ri:chat-history-line" />
</span>
2024-01-24 12:00:45 +00:00
</HoverButton>-->
2024-01-22 08:49:34 +00:00
<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>
<NButton type="primary" :disabled="buttonDisabled" @click="handleSubmit">
<template #icon>
<span class="dark:text-black">
<SvgIcon icon="ri:send-plane-fill" />
</span>
</template>
</NButton>
</div>
</div>
</footer>
</div>
</template>