This commit is contained in:
AceDataCloud committed 2023-04-12 01:21:07 +08:00
1 parent 5400cc08de
commit ca5f39b3fa
16 files changed
+244 -113

No files matched your search

+7 -2
View File
@@ -13,6 +13,8 @@
/> />
</div> </div>
<div class="operators"> <div class="operators">
<navigator-item icon="fa-solid fa-gear" :title="$t('common.nav.setting')" @click="setting = true" />
<setting-panel :visible="setting" @close="setting = false" />
<navigator-item <navigator-item
v-show="!confirming" v-show="!confirming"
icon="fa-solid fa-trash" icon="fa-solid fa-trash"
@@ -36,16 +38,19 @@ import { defineComponent } from 'vue';
import NavigatorItem from './NavigatorItem.vue'; import NavigatorItem from './NavigatorItem.vue';
import ConversationNavigatorItem from '../conversation/ConversationNavigatorItem.vue'; import ConversationNavigatorItem from '../conversation/ConversationNavigatorItem.vue';
import { IConversation } from '@/operators/conversation/models'; import { IConversation } from '@/operators/conversation/models';
import SettingPanel from './SettingPanel.vue';
export default defineComponent({ export default defineComponent({
name: 'LeftNavigator', name: 'LeftNavigator',
components: { components: {
NavigatorItem, NavigatorItem,
ConversationNavigatorItem ConversationNavigatorItem,
SettingPanel
}, },
data() { data() {
return { return {
confirming: false confirming: false,
setting: false
}; };
}, },
computed: { computed: {
+74
View File
@@ -0,0 +1,74 @@
<template>
<el-dialog :model-value="visible" @close="$emit('close')">
<h2 class="title">{{ $t('common.nav.setting') }}</h2>
<el-form label-width="120px">
<el-form-item :label="$t('setting.field.stream')">
<el-switch v-model="stream" />
</el-form-item>
<el-form-item :label="$t('setting.field.endpoint')">
<el-select v-model="endpoint">
<el-option v-for="(item, itemIndex) in endpoints" :key="itemIndex" :value="item" />
</el-select>
</el-form-item>
</el-form>
</el-dialog>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElDialog, ElForm, ElFormItem, ElOption, ElSelect, ElSwitch } from 'element-plus';
import { ENDPOINT, ENDPOINT2 } from '@/constants/endpoint';
export default defineComponent({
name: 'SettingPanel',
components: {
ElDialog,
ElForm,
ElFormItem,
ElOption,
ElSelect,
ElSwitch
},
props: {
visible: {
type: Boolean,
required: true
}
},
emits: ['close'],
data() {
return {
endpoints: [ENDPOINT, ENDPOINT2]
};
},
computed: {
stream: {
get() {
return this.$store.getters.setting.stream;
},
set(value: boolean) {
this.$store.dispatch('setSetting', {
stream: value
});
}
},
endpoint: {
get() {
return this.$store.getters.setting.endpoint;
},
set(value: string) {
this.$store.dispatch('setSetting', {
endpoint: value
});
}
}
}
});
</script>
<style lang="scss" scoped>
.title {
font-size: 20px;
text-align: center;
margin-bottom: 20px;
}
</style>
+1 -1
View File
@@ -60,7 +60,7 @@ export default defineComponent({
} }
} }
}, },
emits: ['stop'], emits: ['stop'],
data(): IData { data(): IData {
return { return {
copied: false copied: false
+13 -15
View File
@@ -4,7 +4,7 @@
v-model="value" v-model="value"
type="textarea" type="textarea"
resize="none" resize="none"
:disabled="!application || answering" :disabled="initializing || !application || answering"
class="new-message-input" class="new-message-input"
:placeholder="$t('conversation.message.newMessagePlaceholder')" :placeholder="$t('conversation.message.newMessagePlaceholder')"
@keydown.enter.exact.prevent="$emit('send')" @keydown.enter.exact.prevent="$emit('send')"
@@ -15,19 +15,17 @@
<voice-recognition v-if="false" class="mr-1" @finished="value = $event" /> <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')" /> <font-awesome-icon icon="fa-regular fa-paper-plane" class="icon-send" @click="$emit('send')" />
</div> </div>
<div v-if="!application" class="new-message-apply"> <div v-if="initializing" class="new-message-apply">
<div v-if="!initializing"> <span class="ml-1">{{ $t('conversation.message.initializing') }}</span>
<span class="mr-2">{{ $t('conversation.message.apiInfo') }}</span> </div>
<span> <div v-else-if="!application" class="new-message-apply">
<el-button type="primary" size="small" @click="confirming = true"> <span class="mr-2">{{ $t('conversation.message.apiInfo') }}</span>
{{ $t('common.button.apply') }} <span>
</el-button> <el-button type="primary" size="small" @click="confirming = true">
</span> {{ $t('common.button.apply') }}
<span class="ml-1">{{ $t('conversation.message.tryForFree') }}</span> </el-button>
</div> </span>
<div v-else> <span class="ml-1">{{ $t('conversation.message.tryForFree') }}</span>
<span class="ml-1">{{ $t('conversation.message.initializing') }}</span>
</div>
</div> </div>
</div> </div>
<application-confirm <application-confirm
@@ -41,7 +39,7 @@
<script lang="ts"> <script lang="ts">
import { defineComponent } from 'vue'; import { defineComponent } from 'vue';
import { ElInput, ElButton, ElText } from 'element-plus'; import { ElInput, ElButton } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome'; import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { IApi, IApplication } from '@/operators'; import { IApi, IApplication } from '@/operators';
import { IApplicationType } from '@/operators'; import { IApplicationType } from '@/operators';
+2
View File
@@ -0,0 +1,2 @@
export const ENDPOINT = 'https://api.zhishuyun.com';
export const ENDPOINT2 = 'https://api2.zhishuyun.com';
+2
View File
@@ -1,2 +1,4 @@
export * from './errorCode'; export * from './errorCode';
export * from './env'; export * from './env';
export * from './endpoint';
export * from './image';
+1 -1
View File
@@ -17,5 +17,5 @@ export default {
rotateCredentialSuccessfully: '密钥重置成功', rotateCredentialSuccessfully: '密钥重置成功',
rotateCredentialFailed: '密钥重置失败,请联系客服处理', rotateCredentialFailed: '密钥重置失败,请联系客服处理',
updateFailed: '修改失败', updateFailed: '修改失败',
updateSuccessfully: '修改成功', updateSuccessfully: '修改成功'
}; };
+1
View File
@@ -1,5 +1,6 @@
export default { export default {
editor: '编辑器', editor: '编辑器',
setting: '设置',
home: '首页', home: '首页',
content: '内容', content: '内容',
platform: '平台', platform: '平台',
+1 -1
View File
@@ -5,7 +5,7 @@ export default {
apiInfo: '本服务由「知数云」提供技术支持', apiInfo: '本服务由「知数云」提供技术支持',
tryForFree: '免费使用', tryForFree: '免费使用',
initializing: '初始化中,请稍后...', initializing: '初始化中,请稍后...',
writeCode: '写一段 JavaScript 代码,发送HTTP请求', writeCode: '写一段 JavaScript 代码,输出 Hello World',
writeEmail: '写一封邮件给 Bob,告诉他我刚刚搬家了', writeEmail: '写一封邮件给 Bob,告诉他我刚刚搬家了',
explainDefinition: '用简单的术语解释量子计算', explainDefinition: '用简单的术语解释量子计算',
rememberHistory: '可以记住用户说过的话', rememberHistory: '可以记住用户说过的话',
+3 -1
View File
@@ -3,11 +3,13 @@ import auth from './auth';
import conversation from './conversation'; import conversation from './conversation';
import application from './application'; import application from './application';
import api from './api'; import api from './api';
import setting from './setting';
export default { export default {
common, common,
conversation, conversation,
auth, auth,
application, application,
api api,
setting
}; };
+4
View File
@@ -0,0 +1,4 @@
export default {
stream: '流式传输',
endpoint: '服务端点'
};
+3
View File
@@ -0,0 +1,3 @@
import field from './field';
export default { field };
+1 -4
View File
@@ -5,14 +5,11 @@ export interface IQuery {
token: string; token: string;
} }
const baseUrl = 'https://api.zhishuyun.com';
class ChatGPTOperator { class ChatGPTOperator {
async post(data: IRequest, query: IQuery, config?: AxiosRequestConfig): Promise<AxiosResponse<IResponse>> { async post(data: IRequest, query: IQuery, config?: AxiosRequestConfig): Promise<AxiosResponse<IResponse>> {
return await axios.post(`/chatgpt`, data, { return await axios.post(`/chatgpt`, data, {
...config, ...config,
params: query, params: query
baseURL: baseUrl
}); });
} }
} }
+105 -87
View File
@@ -63,14 +63,22 @@ import {
IApplication, IApplication,
IApplicationDetailResponse, IApplicationDetailResponse,
IApplicationListResponse, IApplicationListResponse,
IApplicationType IApplicationType,
userOperator
} from '@/operators'; } from '@/operators';
import { ROUTE_AUTH_LOGIN, ROUTE_CONVERSATION_DETAIL } from '@/router/constants'; import { ROUTE_AUTH_LOGIN, ROUTE_CONVERSATION_DETAIL } from '@/router/constants';
import { ERROR_CODE_CANCELED, ERROR_CODE_DUPLICATION, ERROR_CODE_UNKNOWN, ERROR_CODE_UNVERIFIED } from '@/constants'; import {
ENDPOINT,
ERROR_CODE_CANCELED,
ERROR_CODE_DUPLICATION,
ERROR_CODE_UNKNOWN,
ERROR_CODE_UNVERIFIED
} from '@/constants';
import { getVerificationUrl } from '@/utils'; import { getVerificationUrl } from '@/utils';
import { IConversation } from '@/operators/conversation/models'; import { IConversation } from '@/operators/conversation/models';
import Introduction from '@/components/conversation/Introduction.vue'; import Introduction from '@/components/conversation/Introduction.vue';
import axios from 'axios'; import axios from 'axios';
import { IResponse } from '@/operators/api/chatgpt/models';
export interface IData { export interface IData {
input: string; input: string;
@@ -81,6 +89,7 @@ export interface IData {
api: IApi | undefined; api: IApi | undefined;
application: IApplication | undefined; application: IApplication | undefined;
canceler: AbortController | undefined; canceler: AbortController | undefined;
api_id: string;
} }
export default defineComponent({ export default defineComponent({
@@ -101,7 +110,8 @@ export default defineComponent({
token: undefined, token: undefined,
api: undefined, api: undefined,
application: undefined, application: undefined,
canceler: undefined canceler: undefined,
api_id: '1d58971c-e3cd-4713-a3ce-854a731adb14'
}; };
}, },
computed: { computed: {
@@ -110,6 +120,9 @@ export default defineComponent({
}, },
user() { user() {
return this.$store.getters.user; return this.$store.getters.user;
},
setting() {
return this.$store.getters.setting;
} }
}, },
watch: { watch: {
@@ -127,8 +140,14 @@ export default defineComponent({
}); });
} else { } else {
this.restoreMessages(); this.restoreMessages();
await this.onGetApiInfo(); this.loading = true;
await this.onCheckApplication(); Promise.all([this.onGetApiInfo(), this.onCheckApplication()])
.then(() => {
this.loading = false;
})
.catch(() => {
this.loading = false;
});
} }
}, },
methods: { methods: {
@@ -148,47 +167,30 @@ export default defineComponent({
this.messages = []; this.messages = [];
} }
}, },
async onGetApiInfo() { async onGetApiInfo(): Promise<void> {
return new Promise((resolve, reject) => { const { data } = await apiOperator.get(this.api_id);
const id = '1d58971c-e3cd-4713-a3ce-854a731adb14'; this.api = data;
apiOperator
.get(id)
.then(({ data: data }: { data: IApiDetailResponse }) => {
this.api = data;
resolve(data);
})
.catch((error) => {
reject(error);
});
});
}, },
async onStop() { async onStop() {
this.canceler?.abort(); this.canceler?.abort();
}, },
async onCheckApplication() { async onCheckApplication(): Promise<void> {
if (!this.user) { if (!this.user) {
return; const user = await userOperator.getMe();
await this.$store.dispatch('setUser', user);
}
const { data } = await applicationOperator.getAll({
user_id: this.user.id,
api_id: this.api_id
});
if (data.items?.length > 0) {
const application = data.items[0];
this.application = application;
const token = application.credential?.token;
if (token) {
this.token = token;
}
} }
this.loading = true;
applicationOperator
.getAll({
user_id: this.user.id,
api_id: this.api?.id
})
.then(({ data: data }: { data: IApplicationListResponse }) => {
if (data.items?.length > 0) {
const application = data.items[0];
this.application = application;
const token = application.credential?.token;
if (token) {
this.token = token;
}
}
this.loading = false;
})
.catch(() => {
this.loading = false;
});
}, },
onApply() { onApply() {
applicationOperator applicationOperator
@@ -220,6 +222,48 @@ export default defineComponent({
onDraft(content: string) { onDraft(content: string) {
this.input = content; 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() { onSend() {
if (this.answering) { if (this.answering) {
return; return;
@@ -277,63 +321,37 @@ export default defineComponent({
}, },
{ {
headers: { headers: {
accept: 'application/x-ndjson', accept: this.setting?.stream ? 'application/x-ndjson' : 'application/json',
'content-type': 'application/json' 'content-type': 'application/json'
}, },
baseURL: this.$store.getters.endpoint || ENDPOINT,
signal: this.canceler.signal, signal: this.canceler.signal,
responseType: 'stream', // only enable for stream mode
onDownloadProgress: (event) => { ...(this.setting?.stream
const response = event.target.response; ? {
const lines = response.split('\r\n').filter((line: string) => !!line); responseType: 'stream',
const lastLine = lines[lines.length - 1]; onDownloadProgress: (event) => {
if (lastLine) { const response = event.target.response;
const jsonData = JSON.parse(lastLine); const lines = response.split('\r\n').filter((line: string) => !!line);
const answer = jsonData.answer; const lastLine = lines[lines.length - 1];
const conversationId = jsonData.conversation_id; if (lastLine) {
if (conversationId && this.$route.name !== ROUTE_CONVERSATION_DETAIL) { const jsonData = JSON.parse(lastLine);
this.$router.push({ this.onProcessResponse(jsonData);
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;
}
}
}
} }
) )
.then(() => { .then(async ({ data }: { data: IResponse }) => {
if (!this.setting.stream) {
await this.onProcessResponse(data);
}
this.answering = false; this.answering = false;
if (this.messages && this.messages.length > 0) { if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].state = IMessageState.FINISHED; this.messages[this.messages.length - 1].state = IMessageState.FINISHED;
} }
const conversations: IConversation[] = this.$store.getters.conversations; this.onProcessConversation();
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);
}
}) })
.catch((error) => { .catch((error) => {
this.answering = false; this.answering = false;
@@ -344,7 +362,7 @@ export default defineComponent({
this.messages[this.messages.length - 1].error = { this.messages[this.messages.length - 1].error = {
code: ERROR_CODE_CANCELED code: ERROR_CODE_CANCELED
}; };
} else if (error?.response?.data) { } else if (error?.response?.data && error?.response?.data.code) {
const data = error?.response?.data; const data = error?.response?.data;
if (this.messages && this.messages.length > 0) { if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].error = data; this.messages[this.messages.length - 1].error = data;
+2
View File
@@ -9,6 +9,7 @@ import {
import { import {
faMicrophone as faSolidMicrophone, faMicrophone as faSolidMicrophone,
faStop as faSolidStop, faStop as faSolidStop,
faGear as faSolidGear,
faRotateRight as faSolidRotateRight, faRotateRight as faSolidRotateRight,
faCheck as faSolidCheck, faCheck as faSolidCheck,
faPlus as faSolidPlus, faPlus as faSolidPlus,
@@ -30,6 +31,7 @@ library.add(faSolidCheck);
library.add(faRegularUser); library.add(faRegularUser);
library.add(faRegularSun); library.add(faRegularSun);
library.add(faSolidBolt); library.add(faSolidBolt);
library.add(faSolidGear);
library.add(faSolidMicrophone); library.add(faSolidMicrophone);
library.add(faSolidPlus); library.add(faSolidPlus);
library.add(faSolidQuestion); library.add(faSolidQuestion);
+24 -1
View File
@@ -3,12 +3,19 @@ import createPersistedState from 'vuex-persistedstate';
import { userOperator, IUser } from '@/operators'; import { userOperator, IUser } from '@/operators';
import { removeCookies } from '@/utils/cookie'; import { removeCookies } from '@/utils/cookie';
import { IConversation } from '@/operators/conversation/models'; import { IConversation } from '@/operators/conversation/models';
import { ENDPOINT } from '@/constants';
export interface ISetting {
stream?: boolean;
endpoint?: string;
}
export interface IState { export interface IState {
accessToken: string | undefined; accessToken: string | undefined;
refreshToken: string | undefined; refreshToken: string | undefined;
user: IUser | undefined; user: IUser | undefined;
conversations: IConversation[]; conversations: IConversation[];
setting: ISetting;
} }
const store = createStore({ const store = createStore({
@@ -17,7 +24,11 @@ const store = createStore({
accessToken: undefined, accessToken: undefined,
refreshToken: undefined, refreshToken: undefined,
user: undefined, user: undefined,
conversations: [] conversations: [],
setting: {
endpoint: ENDPOINT,
stream: false
}
}; };
}, },
mutations: { mutations: {
@@ -30,6 +41,12 @@ const store = createStore({
setUser(state: IState, payload: IUser): void { setUser(state: IState, payload: IUser): void {
state.user = payload; state.user = payload;
}, },
setSetting(state: IState, payload: ISetting): void {
state.setting = {
...state.setting,
...payload
};
},
setConversations(state: IState, payload: IConversation[]): void { setConversations(state: IState, payload: IConversation[]): void {
state.conversations = payload; state.conversations = payload;
} }
@@ -50,6 +67,9 @@ const store = createStore({
setUser({ commit }: ActionContext<IState, IState>, payload: IUser) { setUser({ commit }: ActionContext<IState, IState>, payload: IUser) {
commit('setUser', payload); commit('setUser', payload);
}, },
setSetting({ commit }: ActionContext<IState, IState>, payload: ISetting) {
commit('setSetting', payload);
},
setConversations({ commit }: ActionContext<IState, IState>, payload: IConversation[]) { setConversations({ commit }: ActionContext<IState, IState>, payload: IConversation[]) {
commit('setConversations', payload); commit('setConversations', payload);
}, },
@@ -77,6 +97,9 @@ const store = createStore({
user(state): IUser | undefined { user(state): IUser | undefined {
return state.user; return state.user;
}, },
setting(state): ISetting | undefined {
return state.setting;
},
conversations(state): IConversation[] { conversations(state): IConversation[] {
return state.conversations || []; return state.conversations || [];
} }