This commit is contained in:
AceDataCloud committed 2023-12-11 01:39:36 +08:00
1 parent cea31c5011
commit 297dd3ef2f
30 files changed
+55 -1386

No files matched your search

+2 -3
View File
@@ -29,9 +29,8 @@
import { defineComponent } from 'vue';
import { ElTooltip, ElButton, ElSkeleton } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { ROUTE_CHAT_CONVERSATION, ROUTE_CHAT_INDEX } from '@/router/constants';
import { apiUsageOperator, midjourneyOperator, MidjourneyImagineState, IApplication, chatOperator } from '@/operators';
import { chatgptOperator } from '@/operators/api/chatgpt/operator';
import { ROUTE_CHAT_CONVERSATION } from '@/router/constants';
import { apiUsageOperator, IApplication, chatOperator } from '@/operators';
import { IChatConversation } from '@/operators/chat/models';
interface IData {
+2 -2
View File
@@ -1,8 +1,8 @@
<template>
<div v-if="application" class="status">
<span class="info">
{{ $t('conversation.message.usedCount') }}: {{ application?.used_amount }}
{{ $t('conversation.message.remainingCount') }}: {{ application?.remaining_amount }}
{{ $t('common.message.usedCount') }}: {{ application?.used_amount }} {{ $t('common.message.remainingCount') }}:
{{ application?.remaining_amount }}
</span>
<span class="actions">
<el-button size="small" type="primary" @click="onBuy">{{ $t('common.button.buyMore') }}</el-button>
@@ -1,40 +0,0 @@
<template>
<div class="box"></div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'AnwseringMark',
data() {
return {};
},
computed: {
conversationId() {
return this.$route.params?.id?.toString();
}
}
});
</script>
<style lang="scss">
@keyframes blink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.box {
width: 5px;
height: 20px;
margin-top: 3px;
background-color: black;
animation: blink 1s infinite;
}
</style>
@@ -1,117 +0,0 @@
<template>
<div class="navigation-item">
<div class="icon">
<font-awesome-icon :icon="icon" class="icon-rotate" />
</div>
<div v-if="!editing && !deleting" class="title">
{{ title }}
</div>
<div v-if="deleting && !editing" class="title">
{{ `${$t('conversation.message.confirmDelete')}"${title}"?` }}
</div>
<div v-if="editing && !deleting" class="title">
<el-input v-model="newTitle" @keydown.enter="onConfirm" />
</div>
<div v-if="!editing && !deleting" class="edit">
<font-awesome-icon icon="fa-solid fa-pen-to-square" class="icon-edit" @click="editing = true" />
</div>
<div v-if="!editing && !deleting" class="delete">
<font-awesome-icon icon="fa-solid fa-trash" class="icon-delete" @click="deleting = true" />
</div>
<div v-if="editing || deleting" class="confirm">
<font-awesome-icon icon="fa-solid fa-check" class="icon-confirm" @click="onConfirm" />
</div>
<div v-if="editing || deleting" class="cancel">
<font-awesome-icon icon="fa-solid fa-xmark" class="icon-cancel" @click="onCancel" />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { ElInput } from 'element-plus';
export default defineComponent({
name: 'ConversationNavigatorItem',
components: {
FontAwesomeIcon,
ElInput
},
props: {
icon: {
type: String,
required: true
},
title: {
type: String,
required: true
}
},
emits: ['update:title', 'delete'],
data() {
return {
deleting: false,
editing: false,
newTitle: this.title
};
},
methods: {
onChangeTitle(val: string) {
this.newTitle = val;
},
onConfirm() {
if (this.editing) {
this.$emit('update:title', this.newTitle);
this.editing = false;
} else if (this.deleting) {
this.$emit('delete');
this.deleting = false;
}
},
onCancel() {
if (this.editing) {
this.editing = false;
} else if (this.deleting) {
this.deleting = false;
}
}
}
});
</script>
<style lang="scss">
.navigation-item {
display: flex;
flex-direction: row;
cursor: pointer;
height: 44px;
margin-top: 5px;
padding: 0 15px;
line-height: 44px;
border-radius: 3px;
&:hover {
background-color: hsla(240, 9%, 59%, 0.1);
}
.icon {
width: 30px;
height: 30px;
min-width: 30px;
}
.title {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.edit,
.delete,
.confirm,
.cancel {
width: 25px;
height: 30px;
min-width: 25px;
text-align: right;
}
}
</style>
@@ -1,110 +0,0 @@
<template>
<div class="introduction">
<h2 class="title">ChatGPT</h2>
<el-row class="introduction-items" justify="center" :gutter="15">
<el-col :md="8" :sm="24" :xs="24">
<div class="text-center">
<font-awesome-icon icon="fa-regular fa-sun" class="icon icon-rotate" />
</div>
<h3 class="subtitle">{{ $t('conversation.title.example') }}</h3>
<introduction-item
:content="$t('conversation.message.writeCode')"
class="cursor-pointer"
@click="$emit('draft', $t('conversation.message.writeCode'))"
/>
<introduction-item
:content="$t('conversation.message.writeEmail')"
class="cursor-pointer"
@click="$emit('draft', $t('conversation.message.writeEmail'))"
/>
<introduction-item
:content="$t('conversation.message.explainDefinition')"
class="cursor-pointer"
@click="$emit('draft', $t('conversation.message.explainDefinition'))"
/>
</el-col>
<el-col :md="8" :sm="24" :xs="24">
<div class="text-center">
<font-awesome-icon icon="fa-solid fa-bolt" class="icon icon-rotate" />
</div>
<h3 class="subtitle">{{ $t('conversation.title.capabilities') }}</h3>
<introduction-item :content="$t('conversation.message.rememberHistory')" />
<introduction-item :content="$t('conversation.message.supportStream')" />
<introduction-item :content="$t('conversation.message.rejectInvalidPrompt')" />
</el-col>
<el-col :md="8" :sm="24" :xs="24">
<div class="text-center">
<font-awesome-icon icon="fa-solid fa-triangle-exclamation" class="icon icon-rotate" />
</div>
<h3 class="subtitle">{{ $t('conversation.title.limitations') }}</h3>
<introduction-item :content="$t('conversation.message.generateInCorrect')" />
<introduction-item :content="$t('conversation.message.generateHarmfulInfo')" />
<introduction-item :content="$t('conversation.message.onlyKnowBefore2021')" />
</el-col>
</el-row>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import IntroductionItem from './IntroductionItem.vue';
import { ElRow, ElCol } from 'element-plus';
export default defineComponent({
name: 'ConversationIntroduction',
components: {
FontAwesomeIcon,
IntroductionItem,
ElRow,
ElCol
},
emits: ['draft'],
data() {
return {};
},
computed: {}
});
</script>
<style lang="scss" scoped>
.introduction {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
.title {
height: 70px;
text-align: center;
display: block;
font-size: 36px;
font-weight: 600;
margin-bottom: 50px;
}
.introduction-items {
height: fit-content;
margin-bottom: 100px;
.icon {
font-size: 20px;
margin-bottom: 10px;
}
.subtitle {
text-align: center;
font-size: 18px;
margin-bottom: 20px;
}
.introduction-item {
margin-bottom: 15px;
}
}
}
@media (max-width: 767px) {
.introduction {
width: 90%;
left: 5%;
transform: translateY(-50%);
}
}
</style>
@@ -1,32 +0,0 @@
<template>
<div class="introduction-item">
{{ content }}
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'ConversationIntroductionItem',
props: {
content: {
type: String,
required: true
}
},
data() {
return {};
},
computed: {}
});
</script>
<style lang="scss" scoped>
.introduction-item {
font-size: 14px;
background-color: #eee;
color: #333;
padding: 10px 20px;
}
</style>
-125
View File
@@ -1,125 +0,0 @@
<template>
<div class="message">
<el-image :src="author.avatar" class="icon" />
<message-content :content="content" class="content" :error="error" :state="state" />
</div>
<div class="operations">
<el-button v-if="author.type === 'bot' && content.value" class="operation" size="small" @click="onCopy">
<font-awesome-icon icon="fa-regular fa-copy" class="icon-copy" />
{{ $t('common.button.copy') }}
</el-button>
<el-button
v-if="author.type === 'bot' && (state === messageState.ANSWERING || state === messageState.PENDING)"
class="operation"
size="small"
@click="onStop"
>
<font-awesome-icon icon="fa-solid fa-stop" class="icon-stop" />
{{ $t('common.button.stop') }}
</el-button>
</div>
</template>
<script lang="ts">
import { IBot, IUser } from '@/operators';
import { IContent, IError, IMessageState } from '@/operators/message/models';
import { defineComponent } from 'vue';
import MessageContent from './MessageContent.vue';
import { ElImage, ElButton } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import copy from 'copy-to-clipboard';
interface IData {
copied: boolean;
messageState: typeof IMessageState;
}
export default defineComponent({
name: 'Message',
components: {
MessageContent,
ElImage,
ElButton,
FontAwesomeIcon
},
props: {
content: {
type: Object as () => IContent,
required: true
},
author: {
type: Object as () => IUser | IBot,
required: true
},
error: {
type: Object as () => IError | undefined,
required: false,
default() {
return undefined;
}
},
state: {
type: Object as () => IMessageState,
required: false,
default() {
return IMessageState.FINISHED;
}
}
},
emits: ['stop'],
data(): IData {
return {
copied: false,
messageState: IMessageState
};
},
computed: {
conversationId() {
return this.$route.params?.id?.toString();
}
},
methods: {
onCopy() {
copy(this.content.value, {
debug: true
});
this.copied = true;
setTimeout(() => {
this.copied = false;
}, 3000);
},
onStop() {
this.$emit('stop');
}
}
});
</script>
<style lang="scss" scoped>
.message {
display: flex;
flex-direction: row;
.icon {
width: 30px;
height: 30px;
margin-right: 20px;
border-radius: 3px;
min-width: 30px;
}
.content {
flex: 1;
}
}
.operations {
width: fit-content;
margin: auto;
.operation {
margin-top: 15px;
}
.fa-copy,
.fa-stop {
margin-right: 5px;
}
}
</style>
@@ -1,107 +0,0 @@
<template>
<markdown-renderer :content="content?.value" class="content" />
<answering-mark v-if="shouldShowAnsweringMark" />
<div class="alerts">
<el-alert v-if="errorText" :title="errorText" type="error" :closable="false" />
</div>
<div class="operations pt-2 ml-2">
<el-button v-if="shouldBuyMore" type="primary" size="small" @click="onBuyMore">{{
$t('common.button.buyMore')
}}</el-button>
</div>
</template>
<script lang="ts">
import { IContent, IError, IMessageState } from '@/operators/message/models';
import { defineComponent } from 'vue';
import MarkdownRenderer from '@/components/common/MarkdownRenderer.vue';
import { ElAlert, ElButton } from 'element-plus';
import {
ERROR_CODE_API_ERROR,
ERROR_CODE_BUSY,
ERROR_CODE_BAD_REQUEST,
ERROR_CODE_NO_CONVERSATION,
ERROR_CODE_USED_UP,
ERROR_CODE_UNKNOWN,
ERROR_CODE_TIMEOUT
} from '@/constants';
import AnsweringMark from './AnsweringMark.vue';
export default defineComponent({
name: 'MessageContent',
components: {
MarkdownRenderer,
ElAlert,
AnsweringMark,
ElButton
},
props: {
content: {
type: Object as () => IContent,
required: true
},
error: {
type: Object as () => IError | undefined,
required: false,
default() {
return undefined;
}
},
state: {
type: Object as () => IMessageState,
required: false,
default() {
return IMessageState.FINISHED;
}
}
},
computed: {
conversationId() {
return this.$route.params?.id?.toString();
},
shouldShowAnsweringMark() {
// @ts-ignore
return this.state === IMessageState.PENDING;
},
shouldBuyMore() {
// @ts-ignore
return this.error?.code === ERROR_CODE_USED_UP;
},
errorText() {
if (this.error?.code === ERROR_CODE_USED_UP) {
return this.$t('conversation.message.errorUsedUp');
}
if (this.error?.code === ERROR_CODE_BUSY) {
return this.$t('conversation.message.errorBusy');
}
if (this.error?.code === ERROR_CODE_API_ERROR) {
return this.$t('conversation.message.errorApiError');
}
if (this.error?.code === ERROR_CODE_BAD_REQUEST) {
return this.$t('conversation.message.errorBadRequest');
}
if (this.error?.code === ERROR_CODE_NO_CONVERSATION) {
return this.$t('conversation.message.errorNoConversation');
}
if (this.error?.code === ERROR_CODE_UNKNOWN) {
return this.$t('conversation.message.errorUnknown');
}
if (this.error?.code === ERROR_CODE_TIMEOUT) {
return this.$t('conversation.message.errorTimeout');
}
return undefined;
}
},
methods: {
onBuyMore() {
window.open('https://data.zhishuyun.com/services/b1fbcc32-e218-4253-9dc3-4fe600a1bfb9', '_blank');
}
}
});
</script>
<style lang="scss">
.content {
overflow-x: hidden;
}
</style>
@@ -1,176 +0,0 @@
<template>
<div class="new-message-box">
<span v-if="application" class="new-message-box-usage-info">
{{ $t('conversation.message.usedCount') }}: {{ application?.used_amount }}
{{ $t('conversation.message.remainingCount') }}: {{ application?.remaining_amount }}
</span>
<div class="flex">
<div class="new-message-input-box">
<el-input
v-model="value"
type="textarea"
resize="none"
:disabled="initializing || !application || answering"
class="new-message-input"
:placeholder="$t('conversation.message.newMessagePlaceholder')"
@keydown.enter.exact.prevent="$emit('send')"
>
</el-input>
<span class="new-message-info-input">{{ $t('conversation.message.howToBreakLine') }}</span>
<div class="new-message-operations">
<voice-recognition v-if="false" class="mr-1" @finished="value = $event" />
<font-awesome-icon icon="fa-regular fa-paper-plane" class="icon-send" @click="$emit('send')" />
</div>
<div v-if="initializing" class="new-message-apply">
<span class="ml-1">{{ $t('conversation.message.initializing') }}</span>
</div>
<div v-else-if="!application" class="new-message-apply">
<span class="mr-2">{{ $t('conversation.message.apiInfo') }}</span>
<span>
<el-button type="primary" size="small" @click="confirming = true">
{{ $t('common.button.apply') }}
</el-button>
</span>
<span class="ml-1">{{ $t('conversation.message.tryForFree') }}</span>
</div>
</div>
</div>
</div>
<application-confirm
v-if="api"
v-model.visible="confirming"
:object="api"
:type="applicationType.API"
@apply="$emit('apply')"
/>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElInput, ElButton, ElSelect, ElOption } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { IApi, IApplication } from '@/operators';
import { IApplicationType } from '@/operators';
import ApplicationConfirm from '@/components/application/Confirm.vue';
import VoiceRecognition from './VoiceRecognition.vue';
import { APIS } from '@/constants/api';
interface IData {
applicationType: typeof IApplicationType;
value: string;
confirming: boolean;
}
export default defineComponent({
name: 'NewMessageBox',
components: {
ElInput,
ElButton,
FontAwesomeIcon,
ApplicationConfirm,
VoiceRecognition
},
props: {
initializing: {
type: Boolean,
required: false,
default: false
},
answering: {
type: Boolean,
required: false,
default: false
},
modelValue: {
type: String,
required: true
},
api: {
type: Object as () => IApi | undefined,
required: true
},
application: {
type: Object as () => IApplication | undefined,
required: true
}
},
emits: ['send', 'update:modelValue', 'apply'],
data(): IData {
return {
applicationType: IApplicationType,
value: this.modelValue,
confirming: false
};
},
computed: {
conversationId() {
return this.$route.params?.id?.toString();
},
activeApiId() {
return this.$store.getters.activeApiId;
}
},
watch: {
value(val) {
this.$emit('update:modelValue', val);
},
modelValue(val) {
if (val !== this.value) {
this.value = val;
}
}
},
methods: {}
});
</script>
<style lang="scss" scoped>
.new-message-box {
position: relative;
margin-bottom: 40px;
.new-message-input-box {
position: relative;
width: 100%;
height: 100%;
.new-message-input {
height: 50px;
}
.new-message-info-input {
position: absolute;
bottom: -25px;
left: 5px;
font-size: 12px;
color: var(--el-text-color-regular);
}
.new-message-operations {
position: absolute;
bottom: 12px;
right: 10px;
color: var(--el-text-color-regular);
.icon-send {
cursor: pointer;
}
}
.new-message-apply {
position: absolute;
top: 50%;
left: 50%;
width: 100%;
text-align: center;
transform: translate(-50%, -50%);
font-size: 12px;
color: #666;
}
}
.new-message-box-usage-info {
color: #999;
font-size: 12px;
text-align: center;
display: block;
margin-bottom: 3px;
}
}
</style>
Whitespace-only changes.
@@ -1,81 +0,0 @@
<template>
<font-awesome-icon icon="fa-solid fa-microphone" class="icon-edit" @click="onToggleRecognition" />
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
export default defineComponent({
name: 'VoiceRecognition',
components: {
FontAwesomeIcon
},
emits: ['finished'],
data() {
return {
supported: false,
recognition: undefined,
started: false,
result: ''
};
},
mounted() {
if ('SpeechRecognition' in window || 'webkitSpeechRecognition' in window) {
this.supported = true;
// @ts-ignore
this.recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
if (this.recognition) {
// @ts-ignore
this.recognition.lang = 'zh-CN';
}
}
// @ts-ignore
this.recognition?.addEventListener('result', (event) => {
const transcript = event.results[0][0].transcript;
this.result = transcript;
console.log('result', this.result);
});
// @ts-ignore
this.recognition?.addEventListener('error', (event) => {
console.log('Recognition error:', event.error);
});
// @ts-ignore
this.recognition?.addEventListener('end', () => {
console.log('Recognition ended');
console.log('result', this.result);
this.$emit('finished', this.result);
});
},
methods: {
startRecognition() {
// @ts-ignore
this.recognition?.start();
this.started = true;
},
stopRecognition() {
// @ts-ignore
this.recognition?.stop();
this.started = true;
},
onToggleRecognition() {
if (!this.started) {
this.startRecognition();
} else {
this.stopRecognition();
}
}
}
});
</script>
<style lang="scss" scoped>
.introduction-item {
font-size: 14px;
background-color: #eee;
color: #333;
padding: 10px 20px;
}
</style>
-5
View File
@@ -1,5 +0,0 @@
export default {
scanToLogin: '使用微信扫码关注公众号「知数云」即可登录/注册',
needVerification: '由于您尚未完成实名认证,所以无法查看课程。',
goVerification: '去实名认证'
};
-3
View File
@@ -1,3 +0,0 @@
export default {
wechatLogin: '微信登录'
};
@@ -1,7 +1,4 @@
import title from './title';
import message from './message';
import title from './title';
export default {
title,
message
};
export default { message, title };
+28
View File
@@ -0,0 +1,28 @@
export default {
startNewChat: '开始新的聊天',
noToken: '请先申请对应服务',
newMessagePlaceholder: '请输入你的问题...',
noInput: '问题不能为空',
apiInfo: '本服务由「知数云」提供技术支持',
tryForFree: '免费使用',
initializing: '初始化中,请稍后...',
writeCode: '写一段 JavaScript 代码,输出 Hello World',
writeEmail: '写一封邮件给 Bob,告诉他我刚刚搬家了',
explainDefinition: '用简单的术语解释量子计算',
rememberHistory: '可以记住用户说过的话',
supportStream: '支持流式数据传输',
rejectInvalidPrompt: '可以拒绝回答不恰当的提问',
generateInCorrect: '可能偶尔产生不正确的信息',
generateHarmfulInfo: '可能偶尔产生有害的指令或有偏见的内容',
onlyKnowBefore2021: '对2021年之后的世界和事件了解有限',
errorBusy: 'Worker正在忙碌中,请稍后重试',
errorApiError: '回答失败,请稍后重试',
errorBadRequest: '请求内容不规范,请重新提问',
errorNoConversation: '对话内容不存在或者已经过期,请发起新的会话',
confirmDelete: '确定删除',
errorUsedUp: '您的套餐次数已经用完,请购买更多次数继续使用',
errorUnknown: '服务器出现未知错误,请稍后重试或联系客服',
errorTimeout: '回答问题超时,请稍后重试',
howToBreakLine: '按 Shift+Enter 键可以换行',
};
+6
View File
@@ -0,0 +1,6 @@
export default {
chat: 'AI问答',
example: '样例',
capabilities: '功能',
limitations: '限制'
};
+1 -1
View File
@@ -2,8 +2,8 @@ export default {
setup: '配置',
edit: '编辑',
login: '登录',
logout: '退出登录',
new: '新建',
logout: '退出登录',
delete: '删除',
confirm: '确定',
cancel: '取消',
+3 -1
View File
@@ -5,5 +5,7 @@ export default {
info: '温馨提示',
free: '免费',
startPrice: '起',
helpWechat: '客服微信'
helpWechat: '客服微信',
remainingCount: '剩余次数',
usedCount: '使用次数'
};
+2 -4
View File
@@ -1,15 +1,13 @@
import common from './common';
import auth from './auth';
import conversation from './conversation';
import application from './application';
import api from './api';
import setting from './setting';
import midjourney from './midjourney';
import chat from './chat';
export default {
chat,
common,
conversation,
auth,
application,
api,
setting,
-10
View File
@@ -1,10 +0,0 @@
export interface IRequest {
question: string;
stateful?: boolean;
conversation_id?: string;
}
export interface IResponse {
answer: string;
conversation_id?: string;
}
-28
View File
@@ -1,28 +0,0 @@
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { IRequest, IResponse } from './models';
export interface IQuery {
token: string;
}
class ChatGPTOperator {
async post(data: IRequest, query: IQuery, config?: AxiosRequestConfig): Promise<AxiosResponse<IResponse>> {
return await axios.post(`/chatgpt`, data, {
...config,
params: query
});
}
}
export const chatgptOperator = new ChatGPTOperator();
class ChatGPT4Operator {
async post(data: IRequest, query: IQuery, config?: AxiosRequestConfig): Promise<AxiosResponse<IResponse>> {
return await axios.post(`/chatgpt4`, data, {
...config,
params: query
});
}
}
export const chatgpt4Operator = new ChatGPT4Operator();
+1
View File
@@ -73,6 +73,7 @@ export interface IChatAskResponse {
export enum IChatConversationAction {
RETRIEVE = 'retrieve',
UPDATE = 'update',
DELETE = 'delete',
RETRIEVE_BATCH = 'retrieve_batch'
}
-5
View File
@@ -3,14 +3,9 @@ import {
IChatAskOptions,
IChatAskRequest,
IChatAskResponse,
IChatConversationRequest,
IChatConversationOptions,
IChatConversationResponse,
IChatConversation,
IChatConversationAction
} from './models';
import { IApplication } from '../application';
import { IApi } from '../api';
import { ENDPOINT_API } from '../common/contants';
class ChatOperator {
-7
View File
@@ -1,7 +0,0 @@
import { IMessage } from '../message/models';
export interface IConversation {
messages: IMessage[];
title: string;
id: string;
}
-1
View File
@@ -1,7 +1,6 @@
export * from './instance';
export * from './application';
export * from './user';
export * from './api';
export * from './chat';
export * from './midjourney';
export * from './usage';
-30
View File
@@ -1,30 +0,0 @@
import { IUser, IBot } from '../user';
export interface IContent {
value: string;
type?: string;
}
export interface IError {
code: string;
detail?: string;
}
export enum IMessageState {
PENDING = 'pending',
ANSWERING = 'answering',
FINISHED = 'finished',
FAILED = 'failed'
}
export const ROLE_SYSTEM = 'system';
export const ROLE_ASSISTANT = 'assistant';
export const ROLE_USER = 'user';
export interface IMessage {
state?: IMessageState;
content: string;
author?: IUser | IBot;
role?: typeof ROLE_SYSTEM | typeof ROLE_ASSISTANT | typeof ROLE_USER;
error?: IError;
}
+4 -3
View File
@@ -20,10 +20,11 @@
</template>
<script lang="ts">
import { ROLE_ASSISTANT, ROLE_USER } from '@/operators/message/models';
import { defineComponent } from 'vue';
import Message from '@/components/chat/Message.vue';
import {
ROLE_ASSISTANT,
ROLE_USER,
IChatModel,
IChatMessage,
CHAT_MODEL_CHATGPT,
@@ -34,11 +35,11 @@ import {
CHAT_MODEL_CHATGPT_16K,
CHAT_MODEL_CHATGPT_BROWSING,
CHAT_MODEL_CHATGPT4,
CHAT_MODEL_CHATGPT4_BROWSING
CHAT_MODEL_CHATGPT4_BROWSING,
chatOperator
} from '@/operators';
import InputBox from '@/components/chat/InputBox.vue';
import ModelSelector from '@/components/chat/ModelSelector.vue';
import { chatOperator } from '@/operators';
import { ERROR_CODE_CANCELED, ERROR_CODE_UNKNOWN } from '@/constants/errorCode';
import axios from 'axios';
import ApiStatus from '@/components/common/ApiStatus.vue';
+4 -4
View File
@@ -3,9 +3,9 @@
<sidebar class="left" :applications="applications" />
<div class="main">
<div class="card">
<h2 class="title">Chat</h2>
<p class="description">Click to start a new chat</p>
<el-button type="primary" @click="onStart">New</el-button>
<h2 class="title">{{ $t('chat.title.chat') }}</h2>
<p class="description">{{ $t('chat.message.startNewChat') }}</p>
<el-button type="primary" @click="onStart">{{ $t('common.button.new') }}</el-button>
</div>
</div>
</div>
@@ -13,7 +13,7 @@
<script lang="ts">
import { defineComponent } from 'vue';
import { ElMain, ElAside, ElButton, ElDrawer } from 'element-plus';
import { ElButton } from 'element-plus';
import Sidebar from '@/components/chat/Sidebar.vue';
import { ROUTE_CHAT_CONVERSATION_NEW } from '@/router/constants';
import { IApplication } from '@/operators/application/models';
-468
View File
@@ -1,468 +0,0 @@
<template>
<div class="conversation">
<div class="selection">
<el-select :model-value="activeApiId" @change="onSwitchApi">
<el-option v-for="item in apis" :key="item.id" :label="item.name" :value="item.id" />
</el-select>
</div>
<el-row v-if="!messages || messages.length === 0" class="introduction-wrapper" justify="center">
<el-col :md="14" :sm="22" :xs="22">
<introduction @draft="onDraft" />
</el-col>
</el-row>
<div v-else class="messages-wrapper">
<div
v-for="(message, messageIndex) in messages"
:key="messageIndex"
:class="{
'message-wrapper': true,
user: message.author.type === 'user',
bot: message.author.type === 'bot'
}"
>
<el-row justify="center">
<el-col :md="14" :sm="22" :xs="22">
<message
:content="message.content"
:author="message.author"
:error="message.error"
:state="message.state"
@stop="onStop"
/>
</el-col>
</el-row>
</div>
</div>
<div class="footer">
<el-row justify="center">
<el-col :md="14" :sm="22" :xs="22">
<new-message-box
v-model="input"
:initializing="loading"
:answering="answering"
class="new-message"
:api="api"
:application="application"
@send="onSend"
@apply="onApply"
@switch-api="onSwitchApi"
/>
</el-col>
</el-row>
</div>
</div>
</template>
<script lang="ts">
import { IMessage, IMessageState } from '@/operators/message/models';
import { defineComponent } from 'vue';
import { ElRow, ElCol, ElMessage, ElSelect, ElOption } from 'element-plus';
import Message from '@/components/conversation/Message.vue';
import { chatgpt4Operator, chatgptOperator } from '@/operators/api/chatgpt/operator';
import NewMessageBox from '@/components/conversation/NewMessageBox.vue';
import { chatgptAvatar, userAvatar } from '@/constants/image';
import {
apiOperator,
applicationOperator,
IApi,
IApplication,
IApplicationDetailResponse,
IApplicationType,
userOperator
} from '@/operators';
import { ROUTE_AUTH_LOGIN, ROUTE_CONVERSATION_DETAIL, ROUTE_CONVERSATION_NEW } from '@/router/constants';
import {
APIS,
API_ID_CHATGPT,
DEFAULT_API,
ENDPOINT,
ERROR_CODE_CANCELED,
ERROR_CODE_DUPLICATION,
ERROR_CODE_UNKNOWN,
ERROR_CODE_UNVERIFIED
} from '@/constants';
import { getVerificationUrl } from '@/utils';
import { IConversation } from '@/operators/conversation/models';
import Introduction from '@/components/conversation/Introduction.vue';
import axios from 'axios';
import { IResponse } from '@/operators/api/chatgpt/models';
export interface IData {
input: string;
messages: IMessage[];
loading: boolean;
answering: boolean;
token: string | undefined;
api: IApi | undefined;
application: IApplication | undefined;
canceler: AbortController | undefined;
apis: { id: string; name: string }[];
}
export default defineComponent({
name: 'ChatDetail',
components: {
Introduction,
Message,
ElRow,
ElCol,
ElSelect,
ElOption,
NewMessageBox
},
data(): IData {
return {
input: '',
loading: false,
answering: false,
messages: [],
token: undefined,
api: undefined,
application: undefined,
canceler: undefined,
apis: APIS
};
},
computed: {
conversationId() {
return this.$route.params?.id?.toString();
},
user() {
return this.$store.getters.user;
},
setting() {
return this.$store.getters.setting;
},
activeApiId() {
return this.$store.getters.activeApiId;
}
},
watch: {
conversationId: {
handler() {
this.restoreMessages();
}
}
},
async mounted() {
if (!this.$store.getters.authenticated) {
this.$router.push({
name: ROUTE_AUTH_LOGIN,
query: { redirect: this.$route.fullPath }
});
} else {
this.restoreMessages();
this.onInitialize();
}
},
methods: {
onInitialize() {
this.loading = true;
Promise.all([this.onGetApiInfo(), this.onCheckApplication()])
.then(() => {
this.loading = false;
})
.catch(() => {
this.loading = false;
});
},
scrollDown() {
const container = document.querySelector('.main') as HTMLDivElement;
container.scrollTop = container.scrollHeight;
},
restoreMessages() {
if (this.conversationId) {
const conversations = this.$store.getters.conversations;
const hitConversations = conversations.filter((c: IConversation) => c.id === this.conversationId);
if (hitConversations && hitConversations.length > 0) {
const hitConversation = hitConversations[0];
this.messages = hitConversation.messages;
}
} else {
this.messages = [];
}
},
async onGetApiInfo(): Promise<void> {
const { data } = await apiOperator.get(this.activeApiId);
this.api = data;
},
async onStop() {
this.canceler?.abort();
},
async onCheckApplication(): Promise<void> {
if (!this.user) {
const { data: user } = await userOperator.getMe();
await this.$store.dispatch('setUser', user);
}
const { data } = await applicationOperator.getAll({
user_id: this.user.id,
api_id: this.activeApiId
});
if (data.items?.length > 0) {
const application = data.items[0];
this.application = application;
const token = application.credential?.token;
if (token) {
this.token = token;
}
}
},
async onSwitchApi(id: string) {
await this.$store.dispatch('setActiveApiId', id);
this.api = undefined;
this.application = undefined;
this.onInitialize();
this.$router.push({
name: ROUTE_CONVERSATION_NEW
});
},
onApply() {
applicationOperator
.create({
type: IApplicationType.API,
api_id: this.api?.id
})
.then(({ data: data }: { data: IApplicationDetailResponse }) => {
this.application = data;
ElMessage.success(this.$t('application.message.applySuccessfully'));
})
.catch((error) => {
if (error?.response?.data?.code === ERROR_CODE_DUPLICATION) {
ElMessage.error(this.$t('application.message.alreadyApplied'));
}
if (error?.response?.data?.code === ERROR_CODE_UNVERIFIED) {
ElMessage({
dangerouslyUseHTMLString: true,
duration: 0,
showClose: true,
message: `${this.$t(
'application.message.unverified'
)} <a class="underline" href="${getVerificationUrl()}">${this.$t('application.message.goVerify')}</a>`,
type: 'warning'
});
}
});
},
onDraft(content: string) {
this.input = content;
},
async onProcessConversation() {
const conversations: IConversation[] = this.$store.getters.conversations;
const hitConversations = conversations.filter((c: IConversation) => c.id === this.conversationId);
if (!hitConversations || hitConversations.length === 0) {
// append a new conversation to conversations
const newConversations = [
...conversations,
{
id: this.conversationId,
messages: this.messages,
title: this.conversationId
}
];
this.$store.dispatch('setConversations', newConversations);
} else {
// update one of existing conversations
conversations.forEach((conversation: IConversation) => {
if (conversation.id === this.conversationId) {
conversation.messages = this.messages;
}
});
this.$store.dispatch('setConversations', conversations);
}
},
async onProcessResponse(jsonData: IResponse) {
const answer = jsonData.answer;
const conversationId = jsonData.conversation_id;
// if this new conversation, just switch to a single conversation
if (conversationId && this.$route.name !== ROUTE_CONVERSATION_DETAIL) {
await this.$router.push({
name: ROUTE_CONVERSATION_DETAIL,
params: {
id: conversationId
}
});
}
if (this.conversationId === conversationId) {
this.scrollDown();
this.messages[this.messages.length - 1].content.value = answer;
this.messages[this.messages.length - 1].state = IMessageState.ANSWERING;
}
},
onSend() {
if (this.answering) {
return;
}
if (!this.input.trim()) {
ElMessage.error(this.$t('conversation.message.noInput'));
return;
}
if (!this.token) {
ElMessage.error(this.$t('conversation.message.noToken'));
return;
}
const input = this.input;
this.messages.push({
content: {
value: input
},
author: {
...this.user,
avatar: this.user?.avatar || userAvatar,
type: 'user'
},
state: IMessageState.FINISHED
});
this.messages.push({
content: {
value: ''
},
author: {
type: 'bot',
nickname: 'ChatGPT',
avatar: chatgptAvatar
},
state: IMessageState.PENDING
});
this.answering = true;
this.input = '';
setTimeout(() => {
this.scrollDown();
}, 100);
this.canceler = new AbortController();
const operator = this.activeApiId === API_ID_CHATGPT ? chatgptOperator : chatgpt4Operator;
operator
.post(
{
question: input,
stateful: true,
...(this.conversationId
? {
conversation_id: this.conversationId
}
: {})
},
{
token: this.token
},
{
headers: {
accept: this.setting?.stream ? 'application/x-ndjson' : 'application/json',
'content-type': 'application/json'
},
baseURL: this.setting.endpoint || ENDPOINT,
signal: this.canceler.signal,
// only enable for stream mode
...(this.setting?.stream
? {
responseType: 'stream',
onDownloadProgress: (event) => {
const response = event.target.response;
const lines = response.split('\r\n').filter((line: string) => !!line);
const lastLine = lines[lines.length - 1];
if (lastLine) {
const jsonData = JSON.parse(lastLine);
this.onProcessResponse(jsonData);
}
}
}
: {})
}
)
.then(async ({ data }: { data: IResponse }) => {
if (!this.setting.stream) {
await this.onProcessResponse(data);
}
this.answering = false;
if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].state = IMessageState.FINISHED;
}
this.onProcessConversation();
this.onCheckApplication();
})
.catch((error) => {
this.answering = false;
if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].state = IMessageState.FAILED;
}
if (axios.isCancel(error)) {
this.messages[this.messages.length - 1].error = {
code: ERROR_CODE_CANCELED
};
} else if (error?.response?.data && error?.response?.data.code) {
const data = error?.response?.data;
if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].error = data;
}
} else {
if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].error = {
code: ERROR_CODE_UNKNOWN
};
}
}
});
}
}
});
</script>
<style lang="scss" scoped>
.conversation {
min-height: 100vh;
position: relative;
flex-direction: column;
display: flex;
.selection {
position: fixed;
top: 10px;
text-align: center;
left: 300px;
width: calc(100% - 300px);
z-index: 1000;
}
@media (max-width: 767px) {
.selection {
left: 0px;
width: calc(100%);
}
}
.messages-wrapper {
margin-bottom: 120px;
padding-top: 50px;
}
.introduction-wrapper {
flex: 1;
}
.message-wrapper {
border-color: rgba(0, 0, 0, 0.1);
border-bottom-width: 1px;
padding-bottom: 1.5rem;
padding-top: 1.5rem;
&:first-child {
border-top-width: 1px;
}
&.bot {
background-color: #f7f7f8;
}
&.user {
background-color: #ffffff;
}
}
.footer {
background-image: linear-gradient(180deg, hsla(0, 0%, 100%, 0) 13.94%, #fff 54.73%);
position: fixed;
left: 300px;
bottom: 0;
width: calc(100% - 300px);
}
@media (max-width: 767px) {
.footer {
left: 0px;
width: calc(100%);
}
}
}
</style>
-18
View File
@@ -1,18 +0,0 @@
import { ROUTE_CONVERSATION_DETAIL, ROUTE_CONVERSATION_NEW } from './constants';
export default {
path: '/conversations',
component: () => import('@/layouts/Conversation.vue'),
children: [
{
path: '',
name: ROUTE_CONVERSATION_NEW,
component: () => import('@/pages/conversation/Main.vue')
},
{
path: ':id',
name: ROUTE_CONVERSATION_DETAIL,
component: () => import('@/pages/conversation/Main.vue')
}
]
};