Merge pull request #2 from ZhiShuYun/germey/resolve

Apply latest feature changes
This commit is contained in:
AceDataCloud committed 2024-02-27 00:25:42 +08:00
commit f13ca37d63
53 files changed
+2904 -36

No files matched your search

+2 -1
View File
@@ -71,5 +71,6 @@
},
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
},
"cSpell.words": ["Chatdoc"]
}
+37 -7
View File
@@ -2,16 +2,46 @@
"name": "@acedatacloud/hub",
"entries": [
{
"date": "Tue, 09 Jan 2024 19:15:08 GMT",
"version": "0.12.2",
"tag": "@acedatacloud/hub_v0.12.2",
"date": "Mon, 29 Jan 2024 16:17:58 GMT",
"version": "1.0.1",
"tag": "@zhishuyun/hub_v1.0.1",
"comments": {
"patch": [
{
"author": "germey@acedata.cloud",
"package": "@acedatacloud/hub",
"commit": "f64be98a29b799cbce18c8b7c13e3385c7d065b3",
"comment": "migrate to acedata"
"author": "cqc@germey.cn",
"package": "@zhishuyun/hub",
"commit": "5c925f97128e2fa12efe0e9f8d151419d1203dc3",
"comment": "fix chatdoc upload issue"
}
]
}
},
{
"date": "Sun, 28 Jan 2024 07:24:49 GMT",
"version": "1.0.0",
"tag": "@zhishuyun/hub_v1.0.0",
"comments": {
"major": [
{
"author": "cqc@germey.cn",
"package": "@zhishuyun/hub",
"commit": "1a7fc4a59a1eeb11bbcdd668ff7fc325f940f5f0",
"comment": "add chatdoc feature"
}
]
}
},
{
"date": "Sun, 21 Jan 2024 03:37:14 GMT",
"version": "0.12.2",
"tag": "@zhishuyun/hub_v0.12.2",
"comments": {
"patch": [
{
"author": "cqc@cuiqingcai.com",
"package": "@zhishuyun/hub",
"commit": "1dc324c35c1c9cf9b533a9e75eff8a25fda59f95",
"comment": "add docs for docker deploy"
}
]
}
+20 -4
View File
@@ -1,16 +1,32 @@
# Change Log - @acedatacloud/hub
This log was last generated on Tue, 09 Jan 2024 19:15:08 GMT and should not be manually modified.
This log was last generated on Mon, 29 Jan 2024 16:17:58 GMT and should not be manually modified.
<!-- Start content -->
## 0.12.2
## 1.0.1
Tue, 09 Jan 2024 19:15:08 GMT
Mon, 29 Jan 2024 16:17:58 GMT
### Patches
- migrate to acedata (germey@acedata.cloud)
- fix chatdoc upload issue (cqc@germey.cn)
## 1.0.0
Sun, 28 Jan 2024 07:24:49 GMT
### Major changes
- add chatdoc feature (cqc@germey.cn)
## 0.12.2
Sun, 21 Jan 2024 03:37:14 GMT
### Patches
- add docs for docker deploy (cqc@cuiqingcai.com)
## 0.12.1
+109
View File
@@ -0,0 +1,109 @@
# Docker Deployment
## Requirements
Install [Docker](https://www.docker.com/), to ensure you can execute `docker` command:
```
$ docker
Usage: docker [OPTIONS] COMMAND
A self-sufficient runtime for containers
Common Commands:
run Create and run a new container from an image
exec Execute a command in a running container
ps List containers
build Build an image from a Dockerfile
pull Download an image from a registry
push Upload an image to a registry
...
```
## Login to Docker
Register an account in [Docker Hub](https://hub.docker.com/), then use command to login:
```
docker login
```
Then enter your username and password to login, then you will see like:
```
Login Succeeded
```
## Build with Docker
```
docker build -t <username>/<image> .
```
Replace `<username>` to your username in Docker Hub, and replace `<image>` with any name you want as the image name, like:
```
docker build -t foobar/hub .
```
Then you will see like this:
```
[+] Building 5.9s (8/16) docker:desktop-linux
=> [build-stage 1/6] FROM docker.io/library/node:18@sha256:995a5f4314885452a4a785abc25a0fec40e26c346559e11e709d58bb7a927c 2.0s
=> => resolve docker.io/library/node:18@sha256:995a5f4314885452a4a785abc25a0fec40e26c346559e11e709d58bb7a927cf4 0.0s
=> => sha256:30d85599795460b2d9d24c6b87c53ec60555b601705cc83bea31632240500980 0B / 64.14MB 2.0s
=> => sha256:995a5f4314885452a4a785abc25a0fec40e26c346559e11e709d58bb7a927cf4 1.21kB / 1.21kB 0.0s
=> => sha256:084b3c822003a20d41f793237286e112d1b5a1c0c7b8b04cb53a17a963a76ed7 2.00kB / 2.00kB 0.0s
=> => sha256:ef847f8b5ae3554df13851034f22683a8b9aef31b3659033211775d8d6cb6b79 7.34kB / 7.34kB
...
=> [build-stage 4/6] RUN yarn 83.5s
=> [build-stage 5/6] COPY . . 0.3s
=> [build-stage 6/6] RUN yarn build 16.3s
=> [production-stage 2/3] COPY --from=build-stage /app/dist /usr/share/nginx/html 0.0s
=> [production-stage 3/3] COPY nginx.conf /etc/nginx/conf.d/default.conf 0.0s
=> exporting to image 0.0s
=> => exporting layers 0.0s
=> => writing image sha256:f4e06895b43560b3cd43970c8942f35d56643959de5272eebee1a887a1b7798a 0.0s
=> => naming to docker.io/germey/hub
```
## Push Docker
```
docker push <username>/<image>
```
Now you have pushed your image to Docker Hub, then you can deploy this image to any server.
## Deploy Docker
In your server machine, you can then pull this image and then run it
```
docker run -d -p 8000:80 <username>/<image>
```
Then visit [http://localhost:8000](http://localhost:8000) you will see it.
## Configure HTTPS
If you want to configure HTTPS and domain, like example.abc.com, you can install Nginx to forward the traffic from Docker:
Apply the HTTPS cert for your domain, you will have 2 files, one is cert, the other is private key, like `example.abc.com.pem` and `example.abc.com.key`, change the nginx conf file as below:
```
server {
listen 443;
server_name example.abc.com;
ssl_certificate /path/to/your/example.abc.com.pem;
ssl_certificate_key /path/to/your/example.abc.com.key;
location / {
proxy_pass http://127.0.0.1:8000;
}
}
```
Also please set the Domain to server's ip address, then restart nginx, it will work.
+3 -5
View File
@@ -33,7 +33,7 @@ import AnsweringMark from './AnsweringMark.vue';
import copy from 'copy-to-clipboard';
import { ElAlert, ElButton } from 'element-plus';
import MarkdownRenderer from '@/components/common/MarkdownRenderer.vue';
import { IApplication, IChatMessage, IChatMessageState, ROLE_ASSISTANT } from '@/operators';
import { IApplication, IChatMessage, IChatMessageState } from '@/operators';
import CopyToClipboard from '../common/CopyToClipboard.vue';
import {
ERROR_CODE_API_ERROR,
@@ -43,7 +43,8 @@ import {
ERROR_CODE_TIMEOUT,
ERROR_CODE_TOO_MANY_REQUESTS,
ERROR_CODE_UNKNOWN,
ERROR_CODE_USED_UP
ERROR_CODE_USED_UP,
ROLE_ASSISTANT
} from '@/constants';
import message from '@/i18n/zh/common/message';
import { ROUTE_CONSOLE_APPLICATION_BUY } from '@/router';
@@ -125,9 +126,6 @@ export default defineComponent({
}
});
}
// onStop() {
// this.$emit('stop');
// }
}
});
</script>
+40
View File
@@ -0,0 +1,40 @@
<template>
<div class="box"></div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'AnsweringMark',
data() {
return {};
},
computed: {
conversationId() {
return this.$route.params?.conversationId?.toString();
}
}
});
</script>
<style lang="scss">
@keyframes blink {
0% {
opacity: 1;
}
50% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.box {
width: 2px;
height: 16px;
margin-top: 3px;
background-color: var(--el-color-black);
animation: blink 1s infinite;
}
</style>
+198
View File
@@ -0,0 +1,198 @@
<template>
<div class="panel">
<el-skeleton v-if="loading && conversations === undefined" />
<div v-else class="conversations">
<div class="conversation" @click="onNewConversation">
<div class="icons">
<font-awesome-icon icon="fa-solid fa-plus" class="icon" />
</div>
<div class="title">
{{ $t('chatdoc.message.startNewChat') }}
</div>
</div>
<div
v-for="(conversation, conversationIndex) in conversations"
:key="conversationIndex"
:class="{ conversation: true, active: conversation.id === conversationId }"
@click="onClick(conversation.id)"
>
<div class="icons">
<font-awesome-icon icon="fa-regular fa-comment" class="icon" />
</div>
<div class="title">
<span v-if="conversation?.deleting">
{{ `${$t('chatdoc.message.confirmDelete')}?` }}
</span>
<span v-else-if="conversation?.editing">
<el-input v-model="conversation.title" @keydown.enter="onConfirm(conversation)" />
</span>
<span v-else-if="conversation?.title || conversation?.messages">{{
conversation?.title || conversation?.messages[conversation?.messages.length - 1]?.content
}}</span>
</div>
<div class="operations">
<font-awesome-icon
v-if="!conversation?.editing && !conversation.deleting"
icon="fa-solid fa-edit"
class="icon icon-edit"
@click.stop="conversation.editing = true"
/>
<font-awesome-icon
v-if="!conversation?.editing && !conversation.deleting"
icon="fa-solid fa-trash"
class="icon icon-delete"
@click.stop="conversation.deleting = true"
/>
<font-awesome-icon
v-if="conversation?.editing || conversation.deleting"
icon="fa-solid fa-check"
class="icon icon-confirm"
@click.stop="onConfirm(conversation)"
/>
<font-awesome-icon
v-if="conversation?.editing || conversation.deleting"
icon="fa-solid fa-xmark"
class="icon icon-cancel"
@click.stop="
conversation.editing = false;
conversation.deleting = false;
"
/>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElSkeleton, ElInput } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { ROUTE_CHATDOC_CONVERSATION, ROUTE_CHATDOC_CONVERSATION_NEW } from '@/router/constants';
import { IChatdocRepository, chatdocOperator, IChatdocConversation } from '@/operators';
export default defineComponent({
name: 'SidePanel',
components: {
ElInput,
FontAwesomeIcon,
ElSkeleton
},
props: {},
emits: ['click'],
computed: {
repositoryId() {
return this.$route.params?.repositoryId?.toString();
},
conversationId() {
return this.$route.params?.conversationId?.toString();
},
repository(): IChatdocRepository | undefined {
return this.$store.state?.chatdoc?.repositories?.find((repository) => repository.id === this.repositoryId);
},
conversations() {
return this.repository?.conversations;
},
applications() {
return this.$store.state.chatdoc.applications;
}
},
methods: {
async onNewConversation() {
this.$router.push({
name: ROUTE_CHATDOC_CONVERSATION_NEW,
params: {
repositoryId: this.repositoryId
}
});
},
async onConfirm(conversation: IChatdocConversation) {
if (conversation?.deleting) {
await chatdocOperator.deleteConversation(conversation.id);
await this.$store.dispatch('chat/getConversations');
} else if (conversation?.editing) {
await chatdocOperator.updateConversation(conversation);
await this.$store.dispatch('chat/getConversations');
} else {
conversation.editing = true;
}
},
onClick(id: string) {
if (!id) {
return;
}
this.$router.push({
name: ROUTE_CHATDOC_CONVERSATION,
params: {
repositoryId: this.repositoryId,
conversationId: id
}
});
this.$emit('click', id);
}
}
});
</script>
<style lang="scss" scoped>
.panel {
display: flex;
flex-direction: column;
align-items: flex-end;
padding: 15px;
width: 300px;
height: 100%;
border-right: 1px solid #eee;
overflow-y: scroll;
.conversations {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
.conversation {
width: 100%;
height: 55px;
display: flex;
flex-direction: row;
padding: 10px;
margin-bottom: 5px;
border: 1px dashed hsl(0, 0%, 93%);
line-height: 30px;
border-radius: 10px;
color: #666;
cursor: pointer;
&.active,
&:hover {
background-color: #eee;
}
.icons {
width: 30px;
padding-left: 10px;
.icon {
font-size: 14px;
}
}
.title {
flex: 1;
font-size: 14px;
line-height: 32px;
overflow: hidden;
text-overflow: ellipsis;
padding-right: 8px;
color: #666;
}
.operations {
width: 40px;
.icon {
cursor: pointer;
font-size: 14px;
margin-right: 6px;
}
}
}
}
}
</style>
@@ -0,0 +1,98 @@
<template>
<el-dialog v-model="dialogVisible" width="500px">
<el-form ref="form" label-width="60px">
<el-form-item :label="$t('chatdoc.field.name')" :prop="form.name">
<el-input v-model="form.name" />
</el-form-item>
<el-form-item :label="$t('chatdoc.field.description')" :prop="form.description">
<el-input v-model="form.description" />
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">{{ $t('common.button.create') }}</el-button>
</el-form-item>
</el-form>
</el-dialog>
<button class="btn btn-create" @click="dialogVisible = true">
<font-awesome-icon :icon="['fas', 'plus']" />
</button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElButton, ElDialog, ElMessage, ElForm, ElFormItem, ElInput } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
interface IData {
dialogVisible: boolean;
creating: boolean;
form: {
name: string;
description: string;
};
}
export default defineComponent({
name: 'UploadDocument',
components: {
ElButton,
ElDialog,
ElForm,
ElFormItem,
ElInput,
FontAwesomeIcon
},
data(): IData {
return {
dialogVisible: false,
creating: false,
form: {
name: '',
description: ''
}
};
},
computed: {},
methods: {
async onSubmit() {
if (!this.form.name) {
ElMessage.error(this.$t('chatdoc.message.nameRequired'));
return;
}
this.creating = true;
this.$store
.dispatch('chatdoc/createRepository', {
name: this.form.name,
description: this.form.description
})
.then(() => {
this.creating = false;
ElMessage.success(this.$t('chatdoc.message.createDocumentSuccess'));
this.dialogVisible = false;
this.$store.dispatch('chatdoc/getRepositories');
})
.catch(() => {
this.creating = false;
ElMessage.error(this.$t('chatdoc.message.createRepositoryFailed'));
});
}
}
});
</script>
<style scoped lang="scss">
.btn.btn-create {
text-align: center;
cursor: pointer;
border: none;
width: 50px;
height: 50px;
border-radius: 50%;
margin-top: 5px;
background-color: #eee;
margin-bottom: 0;
}
.el-button {
border-radius: 20px;
}
</style>
+155
View File
@@ -0,0 +1,155 @@
<template>
<div class="input-box">
<span
:class="{
btn: true,
'btn-send': true,
disabled: !question
}"
@click="onSubmit"
>
<font-awesome-icon icon="fa-solid fa-location-arrow" class="icon icon-send" />
</span>
<el-input
v-model="questionValue"
:rows="1"
:disabled="disabled"
class="input"
type="textarea"
:placeholder="$t('chat.message.newMessagePlaceholder')"
@keydown.enter.exact.prevent="onSubmit"
>
</el-input>
<p class="info">{{ $t('chat.message.howToUse') }}</p>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElInput, ElMessage, ElTooltip, ElUpload } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { CHAT_MODEL_CHATGPT4_VISION, IChatModel } from '@/operators';
export default defineComponent({
name: 'InputBox',
components: {
ElInput,
FontAwesomeIcon
},
props: {
disabled: {
type: Boolean,
required: false,
default: false
},
question: {
type: String,
required: true
}
},
emits: ['update:question', 'submit'],
data() {
return {
questionValue: this.question,
fileList: []
};
},
computed: {
model(): IChatModel {
return this.$store.state.chat.model;
}
},
watch: {
questionValue(val: string) {
this.$emit('update:question', val);
},
question(val: string) {
if (val !== this.questionValue) {
this.questionValue = val;
}
},
references(val: string[]) {
if (val.length === 0) {
this.fileList = [];
}
}
},
methods: {
onSubmit() {
if (!this.question) {
return;
}
this.$emit('submit');
}
}
});
</script>
<style lang="scss">
.input-box {
.input {
textarea {
border: none;
background: none;
box-shadow: none;
resize: none;
line-height: 30px;
height: 40px;
}
}
.el-upload-list {
position: absolute;
width: 400px;
bottom: 45px;
}
.el-textarea.is-disabled .el-textarea__inner {
background-color: initial;
}
}
</style>
<style lang="scss" scoped>
.input-box {
position: relative;
width: 100%;
border: 1px solid #eee;
border-radius: 10px;
background: none;
box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.1);
top: 30px;
.input {
border: none;
width: calc(100% - 80px);
margin-left: 5px;
}
.info {
display: block;
position: absolute;
font-size: 12px;
color: #666;
margin-top: 5px;
margin-left: 3px;
}
.btn {
display: block;
z-index: 100;
cursor: pointer;
position: absolute;
top: 7px;
&.btn-send {
right: 15px;
&.disabled {
.icon-send {
color: #eee;
}
cursor: not-allowed;
}
.icon-send {
font-size: 16px;
color: #666;
}
}
}
}
</style>
+175
View File
@@ -0,0 +1,175 @@
<template>
<div
:class="{
message: true,
[message.role as string]: true,
hidden: errorText && message.role === 'assistant'
}"
:role="message.role"
>
<div class="content">
<markdown-renderer :content="message?.content" />
<answering-mark v-if="message.state === messageState.PENDING" />
</div>
<div class="operations">
<copy-to-clipboard :content="message.content!" class="btn-copy" />
</div>
</div>
<el-alert v-if="errorText" class="error" :title="errorText" type="error" :closable="false" />
<el-button v-if="showBuyMore" type="primary" class="btn btn-buy" size="small" @click="onBuyMore">
{{ $t('common.button.buyMore') }}
</el-button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import AnsweringMark from './AnsweringMark.vue';
import copy from 'copy-to-clipboard';
import { ElAlert, ElButton } from 'element-plus';
import MarkdownRenderer from '@/components/common/MarkdownRenderer.vue';
import { IChatdocMessage, IChatdocMessageState } from '@/operators';
import CopyToClipboard from '../common/CopyToClipboard.vue';
import {
ERROR_CODE_API_ERROR,
ERROR_CODE_BAD_REQUEST,
ERROR_CODE_CONTENT_TOO_LARGE,
ERROR_CODE_NOT_APPLIED,
ERROR_CODE_TIMEOUT,
ERROR_CODE_TOO_MANY_REQUESTS,
ERROR_CODE_UNKNOWN,
ERROR_CODE_USED_UP,
ROLE_ASSISTANT
} from '@/constants';
import message from '@/i18n/zh/common/message';
interface IData {
copied: boolean;
messageState: typeof IChatdocMessageState;
}
export default defineComponent({
name: 'Message',
components: {
CopyToClipboard,
AnsweringMark,
MarkdownRenderer,
ElAlert,
ElButton
},
props: {
message: {
type: Object as () => IChatdocMessage,
required: true
}
},
emits: ['stop'],
data(): IData {
return {
copied: false,
messageState: IChatdocMessageState
};
},
computed: {
errorText() {
if (!this.message.error || !this.message.error?.code) {
return undefined;
}
switch (this.message.error?.code) {
case ERROR_CODE_USED_UP:
return this.$t('chatdoc.message.errorUsedUp');
case ERROR_CODE_API_ERROR:
return this.$t('chatdoc.message.errorApiError');
case ERROR_CODE_BAD_REQUEST:
return this.$t('chatdoc.message.errorBadRequest');
case ERROR_CODE_TIMEOUT:
return this.$t('chatdoc.message.errorTimeout');
case ERROR_CODE_TOO_MANY_REQUESTS:
return this.$t('chatdoc.message.errorTooManyRequests');
case ERROR_CODE_CONTENT_TOO_LARGE:
return this.$t('chatdoc.message.errorContentTooLarge');
case ERROR_CODE_NOT_APPLIED:
return this.$t('chatdoc.message.errorNotApplied');
case ERROR_CODE_UNKNOWN:
default:
return this.$t('chatdoc.message.errorUnknown');
}
},
showBuyMore() {
return this.message.role === ROLE_ASSISTANT && this.message.error?.code === ERROR_CODE_USED_UP;
}
},
methods: {
onCopy() {
copy(this.message.content!.toString(), {
debug: true
});
this.copied = true;
setTimeout(() => {
this.copied = false;
}, 3000);
},
onBuyMore() {}
}
});
</script>
<style lang="scss" scoped>
.error {
width: fit-content;
padding: 10px 5px 8px 5px;
height: 45px;
border-radius: 10px;
border-bottom-left-radius: 0;
}
.btn-buy {
margin: 10px auto;
border-radius: 20px;
}
.message {
display: flex;
flex-direction: column;
margin-bottom: 15px;
&[role='system'] {
display: none;
}
&.hidden {
display: none;
}
&.assistant {
align-items: start;
.content {
background-color: var(--el-bg-color-page);
color: var(--el-color-black);
border-bottom-left-radius: 0;
}
}
&.user {
align-items: end;
.content {
background-color: var(--el-color-primary);
color: var(--el-color-white);
border-bottom-right-radius: 0;
}
}
.content {
border-radius: 10px;
padding: 8px 15px;
max-width: 800px;
.image {
max-width: 100%;
max-height: 300px;
margin: 5px 0;
border-radius: 10px;
}
}
.operations {
display: block;
.btn-copy {
color: var(--el-text-color-regular);
font-size: 14px;
}
}
}
</style>
+192
View File
@@ -0,0 +1,192 @@
<template>
<div class="panel">
<el-skeleton v-if="loading && repositories === undefined" />
<div v-else class="repositories">
<div class="repository" @click="onNewRepository">
<div class="icons">
<font-awesome-icon icon="fa-solid fa-plus" class="icon" />
</div>
<div class="title">
{{ $t('chatdoc.message.startNewChat') }}
</div>
</div>
<div
v-for="(repository, repositoryIndex) in repositories"
:key="repositoryIndex"
:class="{ repository: true, active: repository.id === repositoryId }"
@click="onClick(repository.id)"
>
<div class="icons">
<font-awesome-icon icon="fa-regular fa-comment" class="icon" />
</div>
<div class="title">
<span v-if="repository?.deleting">
{{ `${$t('chatdoc.message.confirmDelete')}?` }}
</span>
<span v-else-if="repository?.editing">
<el-input v-model="repository.title" @keydown.enter="onConfirm(repository)" />
</span>
<span v-else-if="repository?.title || repository?.messages">{{
repository?.title || repository?.messages[repository?.messages.length - 1]?.content
}}</span>
</div>
<div class="operations">
<font-awesome-icon
v-if="!repository?.editing && !repository.deleting"
icon="fa-solid fa-edit"
class="icon icon-edit"
@click.stop="repository.editing = true"
/>
<font-awesome-icon
v-if="!repository?.editing && !repository.deleting"
icon="fa-solid fa-trash"
class="icon icon-delete"
@click.stop="repository.deleting = true"
/>
<font-awesome-icon
v-if="repository?.editing || repository.deleting"
icon="fa-solid fa-check"
class="icon icon-confirm"
@click.stop="onConfirm(repository)"
/>
<font-awesome-icon
v-if="repository?.editing || repository.deleting"
icon="fa-solid fa-xmark"
class="icon icon-cancel"
@click.stop="
repository.editing = false;
repository.deleting = false;
"
/>
</div>
</div>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElSkeleton, ElInput } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import { ROUTE_CHAT_CONVERSATION, ROUTE_CHAT_CONVERSATION_NEW } from '@/router/constants';
import { chatdocOperator, IChatdocRepository } from '@/operators';
import { Status } from '@/store/common/models';
export default defineComponent({
name: 'SidePanel',
components: {
ElInput,
FontAwesomeIcon,
ElSkeleton
},
props: {},
emits: ['click'],
computed: {
repositoryId() {
return this.$route.params?.id?.toString();
},
repositories() {
return this.$store.state.chatdoc.repositories;
},
applications() {
return this.$store.state.chatdoc.applications;
},
loading() {
return this.$store.state.chatdoc.getRepositoriesStatus === Status.Request;
}
},
methods: {
async onNewRepository() {
this.$router.push({
name: ROUTE_CHAT_CONVERSATION_NEW
});
},
async onConfirm(repository: IChatdocRepository) {
// if (repository?.deleting) {
// await chatdocOperator.deleteRepository(repository.id);
// await this.$store.dispatch('chatdoc/getRepositories');
// } else if (repository?.editing) {
// await chatdocOperator.updateRepository(repository);
// await this.$store.dispatch('chatdoc/getRepositories');
// } else {
// repository.editing = true;
// }
},
onClick(id: string) {
if (!id) {
return;
}
this.$router.push({
name: ROUTE_CHAT_CONVERSATION_NEW,
params: {
repositoryId: this.repositoryId
}
});
this.$emit('click', id);
}
}
});
</script>
<style lang="scss" scoped>
.panel {
display: flex;
flex-direction: column;
align-items: flex-end;
padding: 15px;
width: 300px;
height: 100%;
border-right: 1px solid #eee;
overflow-y: scroll;
.repositories {
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
.repository {
width: 100%;
height: 55px;
display: flex;
flex-direction: row;
padding: 10px;
margin-bottom: 5px;
border: 1px dashed hsl(0, 0%, 93%);
line-height: 30px;
border-radius: 10px;
color: #666;
cursor: pointer;
&.active,
&:hover {
background-color: #eee;
}
.icons {
width: 30px;
padding-left: 10px;
.icon {
font-size: 14px;
}
}
.title {
flex: 1;
font-size: 14px;
line-height: 32px;
overflow: hidden;
text-overflow: ellipsis;
padding-right: 8px;
color: #666;
}
.operations {
width: 40px;
.icon {
cursor: pointer;
font-size: 14px;
margin-right: 6px;
}
}
}
}
}
</style>
+108
View File
@@ -0,0 +1,108 @@
<template>
<el-dialog v-model="dialogVisible">
<el-upload
v-model:file-list="fileList"
accept=".docx,.doc,.pdf,.txt,.csv,.enex,.epub,.eml,.html,.htm,.shtml,.md,.odt,.ppt,.pptx,.txt"
drag
:class="{
upload: true
}"
name="file"
:show-file-list="true"
:limit="1"
:multiple="false"
:action="uploadUrl"
:on-exceed="onExceed"
:on-error="onError"
:on-success="onSuccess"
:headers="headers"
>
<el-icon v-if="!learning" class="el-icon--upload"><upload-filled /></el-icon>
<div v-if="!learning" class="el-upload__text">{{ $t('chatdoc.message.dragOrClickToUpload') }}</div>
<div v-if="learning">{{ $t('chatdoc.message.learningDocument') }}</div>
</el-upload>
</el-dialog>
<el-button type="primary" @click="dialogVisible = true">{{ $t('chatdoc.button.uploadDocuments') }}</el-button>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElButton, ElDialog, ElUpload, ElIcon, ElMessage, UploadFiles } from 'element-plus';
import { UploadFilled } from '@element-plus/icons-vue';
import { getBaseUrlData } from '@/utils';
interface IData {
dialogVisible: boolean;
fileList: UploadFiles;
learning: boolean;
uploadUrl: string;
}
export default defineComponent({
name: 'UploadDocument',
components: {
ElButton,
ElDialog,
ElUpload,
ElIcon,
UploadFilled
},
data(): IData {
return {
dialogVisible: false,
fileList: [],
learning: false,
uploadUrl: getBaseUrlData() + '/api/v1/files/'
};
},
computed: {
headers() {
return {
Authorization: `Bearer ${this.$store.state.token.access}`
};
},
urls(): string[] {
// @ts-ignore
return this.fileList.map((file: UploadFile) => file?.response?.file_url);
}
},
async mounted() {},
methods: {
onExceed() {
ElMessage.warning(this.$t('chatdoc.message.uploadDocumentsExceed'));
},
onError() {
ElMessage.error(this.$t('chatdoc.message.uploadDocumentsError'));
},
async onSuccess() {
ElMessage.success(this.$t('chatdoc.message.uploadDocumentsSuccess'));
ElMessage.info(this.$t('chatdoc.message.startCreateDocument'));
this.learning = true;
this.$store
.dispatch('chatdoc/createDocument', {
repositoryId: this.$route.params.repositoryId,
fileUrl: this.urls[0],
fileName: this.fileList[0].name
})
.then(() => {
ElMessage.success(this.$t('chatdoc.message.createDocumentSuccess'));
this.dialogVisible = false;
this.$store.dispatch('chatdoc/getDocuments', { repositoryId: this.$route.params.repositoryId });
})
.catch(() => {
ElMessage.error(this.$t('chatdoc.message.createDocumentError'));
})
.finally(() => {
this.fileList = [];
this.learning = false;
});
}
}
});
</script>
<style scoped lang="scss">
.el-button {
border-radius: 20px;
}
</style>
+16 -2
View File
@@ -76,6 +76,10 @@ import { defineComponent } from 'vue';
import { ElButton, ElTooltip, ElMenu, ElMenuItem } from 'element-plus';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import {
ROUTE_CHATDOC_INDEX,
ROUTE_CHATDOC_CONVERSATION,
ROUTE_CHATDOC_MANAGE,
ROUTE_CHATDOC_SETTING,
ROUTE_CHAT_CONVERSATION,
ROUTE_CHAT_CONVERSATION_NEW,
ROUTE_CONSOLE_ROOT,
@@ -106,7 +110,6 @@ export default defineComponent({
},
displayName: this.$t('common.nav.chat'),
icon: 'fa-regular fa-comment',
image: 'https://cdn.acedata.cloud/9ad12c99b2.png/thumb_100x100',
routes: [ROUTE_CHAT_CONVERSATION, ROUTE_CHAT_CONVERSATION_NEW]
});
}
@@ -117,11 +120,21 @@ export default defineComponent({
},
displayName: this.$t('common.nav.midjourney'),
icon: 'fa-solid fa-palette',
image: 'https://cdn.acedata.cloud/83ee211091.png/thumb_100x100',
routes: [ROUTE_MIDJOURNEY_INDEX, ROUTE_MIDJOURNEY_HISTORY]
});
}
if (this.$config.navigation?.chatdoc) {
links.push({
route: {
name: ROUTE_CHATDOC_INDEX
},
displayName: this.$t('common.nav.chatdoc'),
icon: 'fa-solid fa-file-lines',
routes: [ROUTE_CHATDOC_INDEX, ROUTE_CHATDOC_CONVERSATION, ROUTE_CHATDOC_MANAGE, ROUTE_CHATDOC_SETTING]
});
}
return {
links,
activeIndex: this.$route.name as string
@@ -173,6 +186,7 @@ export default defineComponent({
await this.$store.dispatch('resetAll');
await this.$store.dispatch('chat/resetAll');
await this.$store.dispatch('midjourney/resetAll');
await this.$store.dispatch('chatdoc/resetAll');
},
onConsole() {
this.$router.push({ name: ROUTE_CONSOLE_ROOT });
+5
View File
@@ -43,6 +43,11 @@ export default {
*/
midjourney: true,
/**
* Show chatdoc entry in left navigation.
*/
chatdoc: true,
/**
* Show console entry in left navigation.
*/
+6
View File
@@ -0,0 +1,6 @@
export const ACTION_CREATE = 'create';
export const ACTION_UPDATE = 'update';
export const ACTION_DELETE = 'delete';
export const ACTION_RETRIEVE = 'retrieve';
export const ACTION_RETRIEVE_BATCH = 'retrieve_batch';
export const ACTION_RETRIEVE_ALL = 'retrieve_all';
+2
View File
@@ -1,2 +1,4 @@
export * from './errorCode';
export * from './endpoint';
export * from './role';
export * from './action';
+3
View File
@@ -0,0 +1,3 @@
export const ROLE_SYSTEM = 'system';
export const ROLE_ASSISTANT = 'assistant';
export const ROLE_USER = 'user';
+3
View File
@@ -0,0 +1,3 @@
export default {
uploadDocuments: '上传文档'
};
+13
View File
@@ -0,0 +1,13 @@
export default {
fileName: '文件名',
createdAt: '创建时间',
fileExtension: '文件类型',
fileUrl: '文件链接',
fileSize: '文件大小',
state: '状态',
stateProcessing: '学习中',
stateCompleted: '学习完成',
stateFailed: '学习失败',
name: '名称',
description: '描述'
};
+7
View File
@@ -0,0 +1,7 @@
import message from './message';
import title from './title';
import nav from './nav';
import field from './field';
import button from './button';
export default { message, title, nav, field, button };
+31
View File
@@ -0,0 +1,31 @@
export default {
introductionForKnowledge: '知识库中可添加文档,在机器人回答时,可运用库中的知识进行回复。',
introductionForRepository:
'知识库是一组文档的集合,您可以在知识库中添加文档,机器人在回答时,会从知识库中的文档中进行回复。',
uploadDocumentsExceed: '上传文档数量超过限制',
uploadDocumentsError: '上传文档失败',
uploadDocumentsSuccess: '上传文档成功',
createDocumentSuccess: '学习文档成功',
startCreateDocument: '开始学习文档...',
createDocumentError: '学习文档失败',
dragOrClickToUpload: '拖拽或点击上传文档',
learningDocument: '学习中,请稍后...',
startNewChat: '开始新会话',
errorApiError: '回答失败,请稍后重试',
errorBadRequest: '请求内容不规范,请重新提问',
errorNoConversation: '对话内容不存在或者已经过期,请发起新的会话',
errorContentTooLarge: '问题内容过长,请缩短后重试',
errorTooManyRequests: '您的操作过于频繁,请稍后重试',
errorUsedUp: '您的套餐次数已经用完,请购买更多次数继续使用',
errorUnknown: '服务器出现未知错误,请稍后重试或联系客服',
errorTimeout: '回答问题超时,请稍后重试',
errorNotApplied: '您尚未申请该服务,请先申请再继续提问',
confirmDelete: '确定删除',
howToUse: '按 Shift+Enter 键可以换行',
createRepositorySuccess: '创建知识库成功',
createRepositoryFailed: '创建知识库失败',
deleteRepositorySuccess: '删除知识库成功',
deleteDocumentSuccess: '删除文档成功',
currentRepository: '当前知识库',
nameRequired: '名称不能为空'
};
+5
View File
@@ -0,0 +1,5 @@
export default {
chat: '对话',
setting: '设置',
manage: '管理'
};
+5
View File
@@ -0,0 +1,5 @@
export default {
manage: '管理知识库',
createRepository: '创建知识库',
repositories: '知识库列表'
};
+2 -1
View File
@@ -29,5 +29,6 @@ export default {
buyMore: '购买更多',
update: '更新',
copy: '复制',
stop: '停止'
stop: '停止',
create: '创建'
};
+2 -1
View File
@@ -15,5 +15,6 @@ export default {
console: '控制台',
newChat: '新建对话',
logOut: '退出登录',
distribution: '分销赚钱'
distribution: '分销赚钱',
chatdoc: 'AI 知识库'
};
+2
View File
@@ -8,9 +8,11 @@ import console from './console';
import order from './order';
import distribution from './distribution';
import user from './user';
import chatdoc from './chatdoc';
export default {
chat,
chatdoc,
user,
order,
console,
+146
View File
@@ -0,0 +1,146 @@
<template>
<div class="main">
<el-menu v-if="repositoryId" :default-active="activeMenu" mode="horizontal" :ellipsis="false" class="menu">
<div class="repository">
<font-awesome-icon class="mr-2" :icon="['fas', 'book']" />
<span>{{ repository?.name }}</span>
</div>
<el-menu-item
v-for="(menuItem, menuItemIndex) in menuItems"
:key="menuItemIndex"
:index="menuItem.index"
@click="onClickMenu(menuItem)"
>
{{ menuItem.title }}
</el-menu-item>
</el-menu>
<div class="chatdoc">
<slot name="chatdoc" />
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { ElMenu, ElMenuItem } from 'element-plus';
import { ROUTE_CHATDOC_CONVERSATION_NEW, ROUTE_CHATDOC_MANAGE } from '@/router';
import { RouteLocationRaw } from 'vue-router';
import { IChatdocRepository } from '@/operators';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
interface IMenuItem {
index: string;
title: string;
route?: RouteLocationRaw;
}
interface IData {
repositoryId: string;
drawer: boolean;
menuItems: IMenuItem[];
}
export default defineComponent({
name: 'LayoutChatdoc',
components: {
ElMenu,
ElMenuItem,
FontAwesomeIcon
},
data(): IData {
return {
repositoryId: this.$route.params?.repositoryId?.toString(),
drawer: false,
menuItems: [
{
index: 'chat',
title: this.$t('chatdoc.nav.chat'),
route: {
name: ROUTE_CHATDOC_CONVERSATION_NEW
}
},
/*
{
index: 'setting',
title: this.$t('chatdoc.nav.setting'),
route: {
name: ROUTE_CHATDOC_SETTING
}
},
*/
{
index: 'manage',
title: this.$t('chatdoc.nav.manage'),
route: {
name: ROUTE_CHATDOC_MANAGE
}
}
]
};
},
computed: {
activeMenu() {
// @ts-ignore
const filterResult = this.menuItems.filter((menuItem) => menuItem.route?.name === this.$route.name);
if (filterResult) {
return filterResult[0]?.index;
}
return undefined;
},
repository(): IChatdocRepository | undefined {
return this.$store.state?.chatdoc?.repositories?.find((repository) => repository.id === this.repositoryId);
}
},
async mounted() {
await this.onGetApplications();
await this.onGetRepositories();
},
methods: {
async onGetApplications() {
await this.$store.dispatch('chatdoc/getApplications');
},
async onGetRepositories() {
await this.$store.dispatch('chatdoc/getRepositories');
},
async onClickMenu(menuItem: IMenuItem) {
this.activeMenu = menuItem.index;
if (menuItem.route) {
await this.$router.push({
// @ts-ignore
...menuItem.route,
params: {
id: this.repositoryId
}
});
}
}
}
});
</script>
<style lang="scss" scoped>
.main {
flex: 1;
display: flex;
flex-direction: column;
position: relative;
height: 100%;
.repository {
position: absolute;
left: 50px;
top: 20px;
font-weight: bold;
}
.menu {
width: 100%;
justify-content: center;
}
.chatdoc {
height: 100%;
width: 100%;
}
}
</style>
-4
View File
@@ -1,9 +1,5 @@
import { IChatModel } from './models';
export const ROLE_SYSTEM = 'system';
export const ROLE_ASSISTANT = 'assistant';
export const ROLE_USER = 'user';
export const CHAT_MODEL_NAME_CHATGPT = 'chatgpt';
export const CHAT_MODEL_NAME_CHATGPT4 = 'chatgpt4';
export const CHAT_MODEL_NAME_CHATGPT_16K = 'chatgpt-16k';
+3 -5
View File
@@ -1,13 +1,11 @@
import { ROLE_ASSISTANT, ROLE_SYSTEM, ROLE_USER } from '@/constants';
import {
CHAT_MODEL_NAME_CHATGPT,
CHAT_MODEL_NAME_CHATGPT4,
CHAT_MODEL_NAME_CHATGPT4_BROWSING,
CHAT_MODEL_NAME_CHATGPT4_VISION,
CHAT_MODEL_NAME_CHATGPT_16K,
CHAT_MODEL_NAME_CHATGPT_BROWSING,
ROLE_ASSISTANT,
ROLE_SYSTEM,
ROLE_USER
CHAT_MODEL_NAME_CHATGPT_BROWSING
} from './constants';
export type IChatModelName =
@@ -25,7 +23,7 @@ export interface IChatModel {
description: string;
}
export interface IError {
interface IError {
code: string;
detail?: string;
}
+4
View File
@@ -0,0 +1,4 @@
export const API_ID_CHATDOC_REPOSITORIES = 'e22e9e3f-5594-4c48-9284-c1847c22c65f';
export const API_ID_CHATDOC_DOCUMENTS = 'afc7917f-d89f-4dc9-95c2-863936b02cad';
export const API_ID_CHATDOC_CONVERSATIONS = 'afc7917f-d89f-4dc9-95c2-863936b02cad';
export const API_ID_CHATDOC_CHAT = '099eafc8-8167-4557-b8f2-47867ca76e24';
+2
View File
@@ -0,0 +1,2 @@
export * from './models';
export * from './operator';
+76
View File
@@ -0,0 +1,76 @@
import { ACTION_CREATE, ACTION_DELETE, ACTION_UPDATE, ROLE_ASSISTANT, ROLE_SYSTEM, ROLE_USER } from '@/constants';
export interface IError {
code: string;
detail?: string;
}
export interface IChatdocRepository {
id: string;
name?: string;
description?: string;
deleting?: boolean;
editing?: boolean;
documents?: IChatdocDocument[];
conversations?: IChatdocConversation[];
}
export interface IChatdocDocument {
id: string;
repository_id: string;
file_url: string;
file_name: string;
}
export interface IChatdocConversation {
id: string;
repository_id: string;
messages: IChatdocMessage[];
editing?: boolean;
deleting?: boolean;
}
export interface IChatdocMessage {
content?: string;
error?: IError;
state?: IChatdocMessageState;
role?: typeof ROLE_SYSTEM | typeof ROLE_ASSISTANT | typeof ROLE_USER;
}
export enum IChatdocMessageState {
PENDING = 'pending',
ANSWERING = 'answering',
FINISHED = 'finished',
FAILED = 'failed'
}
export interface IChatdocChatRequest {
repository_id: string;
messages: IChatdocMessage[];
temperature?: number;
knowledge_fallback?: boolean;
}
export interface IChatdocDocumentRequest extends IChatdocDocument {
action: typeof ACTION_CREATE | typeof ACTION_UPDATE | typeof ACTION_DELETE;
callback_url?: string;
}
export interface IChatdocDocumentResponse extends IChatdocDocument {}
export type IChatdocConversationsResponse = IChatdocConversation[];
export interface IChatdocRepositoryRequest extends IChatdocRepository {
action: typeof ACTION_CREATE | typeof ACTION_UPDATE | typeof ACTION_DELETE;
}
export interface IChatdocRepositoryResponse extends IChatdocRepository {}
export type IChatdocRepositoriesResponse = IChatdocRepository[];
export type IChatdocDocumentsResponse = IChatdocDocument[];
export interface IChatdocChatResponse {
answer: string;
delta_answer: string;
repository_id?: string;
conversation_id?: string;
}
+300
View File
@@ -0,0 +1,300 @@
import axios, { AxiosProgressEvent, AxiosResponse } from 'axios';
import {
IChatdocChatResponse,
IChatdocConversation,
IChatdocConversationsResponse,
IChatdocDocumentResponse,
IChatdocDocumentsResponse,
IChatdocRepositoriesResponse,
IChatdocRepositoryResponse
} from './models';
import { ACTION_RETRIEVE_ALL, ACTION_UPDATE, BASE_URL_API } from '@/constants';
import { ACTION_CREATE, ACTION_DELETE, ACTION_RETRIEVE, ACTION_RETRIEVE_BATCH } from '@/constants';
class ChatdocOperator {
async createRepository(
payload: {
name: string;
description?: string;
},
options: { token: string }
): Promise<AxiosResponse<IChatdocRepositoryResponse>> {
return await axios.post(
`/chatdoc/repositories`,
{
action: ACTION_CREATE,
name: payload.name,
description: payload.description
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async deleteRepository(id: string, options: { token: string }): Promise<AxiosResponse<IChatdocRepositoryResponse>> {
return await axios.post(
`/chatdoc/repositories`,
{
action: ACTION_DELETE,
id
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async getRepository(id: string, options: { token: string }): Promise<AxiosResponse<IChatdocRepositoryResponse>> {
return await axios.post(
`/chatdoc/repositories`,
{
action: ACTION_RETRIEVE,
id
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async getAllRepositories(options: { token: string }): Promise<AxiosResponse<IChatdocRepositoriesResponse>> {
return await axios.post(
`/chatdoc/repositories`,
{
action: ACTION_RETRIEVE_ALL
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async getAllDocuments(
repositoryId: string,
options: { token: string }
): Promise<AxiosResponse<IChatdocDocumentsResponse>> {
return await axios.post(
`/chatdoc/documents`,
{
action: ACTION_RETRIEVE_ALL,
repository_id: repositoryId
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async getAllConversations(repositoryId: string): Promise<AxiosResponse<IChatdocConversationsResponse>> {
return await axios.post(
`/chatdoc/conversations`,
{
action: ACTION_RETRIEVE_ALL,
repository_id: repositoryId
},
{
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async getRepositories(ids: string[]): Promise<AxiosResponse<IChatdocRepositoriesResponse>> {
return await axios.post(
`/chatdoc/repositories`,
{
action: ACTION_RETRIEVE_BATCH,
ids
},
{
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async createDocument(
payload: {
repositoryId: string;
fileUrl: string;
fileName: string;
},
options: { token: string }
): Promise<AxiosResponse<IChatdocDocumentResponse>> {
return await axios.post(
`/chatdoc/documents`,
{
action: ACTION_CREATE,
repository_id: payload.repositoryId,
file_url: payload.fileUrl,
file_name: payload.fileName
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async retrieveDocument(id: string, options: { token: string }): Promise<AxiosResponse<IChatdocDocumentResponse>> {
return await axios.post(
`/chatdoc/documents`,
{
action: ACTION_RETRIEVE,
id
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async retrieveConversation(id: string, options: { token: string }): Promise<AxiosResponse<IChatdocDocumentResponse>> {
return await axios.post(
`/chatdoc/conversations`,
{
action: ACTION_RETRIEVE,
id
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async deleteDocument(id: string, options: { token: string }): Promise<AxiosResponse<IChatdocDocumentResponse>> {
return await axios.post(
`/chatdoc/documents`,
{
action: ACTION_DELETE,
id
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async updateConversation(payload: IChatdocConversation) {
return await axios.post(
`/chatdoc/conversations`,
{
action: ACTION_UPDATE,
id: payload.id,
messages: payload.messages
},
{
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async deleteConversation(id: string): Promise<AxiosResponse<IChatdocDocumentResponse>> {
return await axios.post(
`/chatdoc/conversations`,
{
action: ACTION_DELETE,
id
},
{
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
baseURL: BASE_URL_API
}
);
}
async chat(
payload: { repositoryId: string; question: string; conversationId?: string; knowledgeFallback?: boolean },
options: { token: string; stream: (response: IChatdocChatResponse) => void }
): Promise<AxiosResponse<IChatdocChatResponse>> {
return await axios.post(
`/chatdoc/chat`,
{
repository_id: payload.repositoryId,
question: payload.question,
conversation_id: payload.conversationId,
stateful: true
},
{
headers: {
authorization: `Bearer ${options.token}`,
accept: 'application/x-ndjson',
'content-type': 'application/json'
},
baseURL: BASE_URL_API,
responseType: 'stream',
onDownloadProgress: ({ event }: AxiosProgressEvent) => {
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);
if (options?.stream) {
options?.stream(jsonData as IChatdocChatResponse);
}
}
}
}
);
}
}
export const chatdocOperator = new ChatdocOperator();
+1
View File
@@ -7,3 +7,4 @@ export * from './usage';
export * from './api';
export * from './order';
export * from './distribution';
export * from './chatdoc';
+2 -2
View File
@@ -1,4 +1,4 @@
import axios, { AxiosResponse } from 'axios';
import axios, { AxiosProgressEvent, AxiosResponse } from 'axios';
import { IMidjourneyImagineRequest, IMidjourneyImagineResponse, IMidjourneyImagineTask } from './models';
import { BASE_URL_API } from '@/constants';
@@ -54,7 +54,7 @@ class MidjourneyOperator {
},
baseURL: options.endpoint,
responseType: 'stream',
onDownloadProgress: (event) => {
onDownloadProgress: ({ event }: AxiosProgressEvent) => {
const response = event.target.response;
const lines = response.split('\r\n').filter((line: string) => !!line);
const lastLine = lines[lines.length - 1];
+1 -2
View File
@@ -39,9 +39,8 @@
import axios from 'axios';
import { defineComponent } from 'vue';
import Message from '@/components/chat/Message.vue';
import { ROLE_ASSISTANT, ROLE_USER } from '@/constants';
import {
ROLE_ASSISTANT,
ROLE_USER,
IChatModel,
IApplication,
IChatMessageState,
+291
View File
@@ -0,0 +1,291 @@
<template>
<layout>
<template #chatdoc>
<div class="wrapper">
<conversations class="side" />
<div class="chat">
<div class="status">
<api-status
:initializing="initializing"
:application="application"
:need-apply="needApply"
:api-id="apiId"
@refresh="$store.dispatch('chatdoc/getApplications')"
/>
</div>
<div class="dialogue">
<div class="messages">
<message
v-for="(message, messageIndex) in messages"
:key="messageIndex"
:message="message"
class="message"
/>
</div>
</div>
<div class="bottom">
<input-box
:disabled="answering"
:question="question"
@update:question="question = $event"
@submit="onSubmit"
/>
</div>
</div>
</div>
</template>
</layout>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import Layout from '@/layouts/Chatdoc.vue';
import {
IApplication,
IChatdocChatResponse,
IChatdocConversation,
IChatdocMessageState,
IChatdocRepository,
chatdocOperator
} from '@/operators';
import Conversations from '@/components/chatdoc/Conversations.vue';
import Message from '@/components/chatdoc/Message.vue';
import InputBox from '@/components/chatdoc/InputBox.vue';
import {
ERROR_CODE_CANCELED,
ERROR_CODE_NOT_APPLIED,
ERROR_CODE_UNKNOWN,
ROLE_ASSISTANT,
ROLE_USER
} from '@/constants';
import { API_ID_CHATDOC_CHAT } from '@/operators/chatdoc/constants';
import { log } from '@/utils';
import { ROUTE_CHATDOC_CONVERSATION } from '@/router';
import axios from 'axios';
import { isJSONString } from '@/utils/is';
import { Status } from '@/store/common/models';
import ApiStatus from '@/components/common/ApiStatus.vue';
export default defineComponent({
name: 'ChatdocChat',
components: {
Layout,
Conversations,
Message,
InputBox,
ApiStatus
},
data() {
return {
loading: false,
repositoryId: this.$route.params.repositoryId.toString(),
answering: false,
question: ''
// references: []
};
},
computed: {
messages: {
get() {
return (
this.conversations?.find(
(conversation: IChatdocConversation) => conversation.id === this.$route.params.conversationId?.toString()
)?.messages || []
);
},
set(messages: any[]) {
console.log('set messages', messages);
}
},
repository(): IChatdocRepository | undefined {
return this.$store.state?.chatdoc?.repositories?.find((repository) => repository.id === this.repositoryId);
},
conversations() {
return this.repository?.conversations;
},
conversationId(): string | undefined {
return this.$route.params.conversationId?.toString();
},
application() {
return this.applications?.find((application: IApplication) => application.api?.id === API_ID_CHATDOC_CHAT);
},
applications() {
return this.$store.state.chatdoc.applications;
},
needApply() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Success && !this.application;
},
initializing() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Request;
},
apiId() {
return API_ID_CHATDOC_CHAT;
}
},
async mounted() {
console.log('start get conversations');
this.loading = true;
this.$store
.dispatch('chatdoc/getConversations', { repositoryId: this.repositoryId })
.then(() => {
this.loading = false;
})
.catch(() => {
this.loading = false;
});
},
methods: {
async onSubmit() {
this.messages.push({
content: this.question,
role: ROLE_USER
});
console.debug('onSubmit', this.question);
await this.onFetchAnswer();
},
async onScrollDown() {
setTimeout(() => {
const container = document.querySelector('.dialogue') as HTMLDivElement;
if (!container || !this.messages || this.messages.length === 0) {
return;
}
container.scrollTop = container?.scrollHeight;
}, 0);
},
async onFetchAnswer() {
const token = this.application?.credential?.token;
const endpoint = this.application?.api?.endpoint;
const path = this.application?.api?.path;
const question = this.question;
log(this.onFetchAnswer, 'validated', question);
// reset question and references
this.question = '';
if (!token || !endpoint || !question || !path) {
console.error('no token or endpoint or question');
this.messages.push({
error: {
code: ERROR_CODE_NOT_APPLIED
},
role: ROLE_ASSISTANT,
state: IChatdocMessageState.FAILED
});
return;
}
let conversationId = this.conversationId;
this.messages.push({
content: '',
role: ROLE_ASSISTANT,
state: IChatdocMessageState.PENDING
});
log(this.onFetchAnswer, 'start to get answer', this.messages);
this.onScrollDown();
// request server to get answer
this.answering = true;
chatdocOperator
.chat(
{
repositoryId: this.repositoryId,
question,
conversationId: this.conversationId
},
{
token,
stream: (response: IChatdocChatResponse) => {
this.messages[this.messages.length - 1] = {
role: ROLE_ASSISTANT,
content: response.answer,
state: IChatdocMessageState.ANSWERING
};
conversationId = response.conversation_id;
this.onScrollDown();
}
}
)
.then(async () => {
log(this.onFetchAnswer, 'finished fetch answer');
this.messages[this.messages.length - 1].state = IChatdocMessageState.FINISHED;
await this.$store.dispatch('chatdoc/setConversation', {
id: conversationId,
messages: this.messages
});
this.answering = false;
if (!this.conversationId) {
await this.$router.push({
name: ROUTE_CHATDOC_CONVERSATION,
params: {
conversationId: this.conversationId,
repositoryId: this.repositoryId
}
});
}
this.onScrollDown();
await this.$store.dispatch('chatdoc/getConversations', { repositoryId: this.repositoryId });
})
.catch((error) => {
if (this.messages && this.messages.length > 0) {
this.messages[this.messages.length - 1].state = IChatdocMessageState.FAILED;
}
console.error(error);
if (axios.isCancel(error)) {
this.messages[this.messages.length - 1].error = {
code: ERROR_CODE_CANCELED
};
} else if (error?.response?.data) {
let data = error?.response?.data;
if (isJSONString(data)) {
data = JSON.parse(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
};
}
}
this.answering = false;
});
}
}
});
</script>
<style lang="scss" scoped>
.wrapper {
display: flex;
flex-direction: row;
height: 100%;
width: 100%;
}
.chat {
flex: 1;
width: calc(100% - 300px);
padding: 15px;
flex-direction: column;
height: 100%;
display: flex;
.status {
margin-bottom: 10px;
}
.dialogue {
flex: 1;
overflow-y: scroll;
margin: 20px 0;
position: relative;
.messages {
padding-top: 30px;
.message {
margin-bottom: 15px;
}
}
}
.bottom {
width: 100%;
height: 90px;
}
}
</style>
+196
View File
@@ -0,0 +1,196 @@
<template>
<layout>
<template #chatdoc>
<div class="wrapper">
<div class="title">
{{ $t('chatdoc.title.repositories') }}
</div>
<div class="introduction">
{{ $t('chatdoc.message.introductionForRepository') }}
</div>
<div class="status">
<api-status
:initializing="initializing"
:application="application"
:need-apply="needApply"
:api-id="apiId"
@refresh="$store.dispatch('chatdoc/getApplications')"
/>
</div>
<el-row class="repositories" :gutter="15">
<el-col :xl="4" :md="6" :sm="12" :xs="24">
<el-card class="repository text-center" shadow="hover" @click="onCreate">
<create-repository />
<p class="operation">{{ $t('chatdoc.title.createRepository') }}</p>
</el-card>
</el-col>
<el-col
v-for="(repository, repositoryIndex) in repositories"
:key="repositoryIndex"
:xl="4"
:md="6"
:sm="12"
:xs="24"
>
<el-card class="repository" shadow="hover" @click="onClick(repository)">
<el-dropdown v-if="false">
<font-awesome-icon class="more" :icon="['fas', 'book']" />
<template #dropdown>
<el-dropdown-menu>
<el-dropdown-item @click="onDelete(repository.id)">{{
$t('common.button.delete')
}}</el-dropdown-item>
</el-dropdown-menu>
</template>
</el-dropdown>
<h2 class="name">{{ repository.name }}</h2>
<p class="id">
<font-awesome-icon :icon="['fas', 'book']" />
ID: {{ repository.id }}
</p>
<p class="description">
{{ repository.description }}
</p>
</el-card>
</el-col>
</el-row>
</div>
</template>
</layout>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import Layout from '@/layouts/Chatdoc.vue';
import { ElCard, ElRow, ElCol, ElDropdown, ElDropdownItem, ElDropdownMenu, ElMessage } from 'element-plus';
import { IApplication, IChatdocRepository } from '@/operators';
import { ROUTE_CHATDOC_MANAGE } from '@/router';
import CreateRepository from '@/components/chatdoc/CreateRepository.vue';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
import ApiStatus from '@/components/common/ApiStatus.vue';
import { Status } from '@/store/common/models';
import { API_ID_CHATDOC_REPOSITORIES } from '@/operators/chatdoc/constants';
export default defineComponent({
name: 'ChatdocKnowledge',
components: {
Layout,
ElCard,
ElRow,
ElCol,
CreateRepository,
FontAwesomeIcon,
ElDropdown,
ElDropdownItem,
ElDropdownMenu,
ApiStatus
},
data() {
return {};
},
computed: {
apiId() {
return API_ID_CHATDOC_REPOSITORIES;
},
repositories() {
return this.$store.state.chatdoc.repositories;
},
needApply() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Success && !this.application;
},
applications() {
return this.$store.state.chatdoc.applications;
},
application() {
return this.applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_REPOSITORIES
);
},
initializing() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Request;
}
},
async mounted() {},
methods: {
onCreate() {
console.log('onCreate');
},
onClick(repository: IChatdocRepository) {
this.$router.push({
name: ROUTE_CHATDOC_MANAGE,
params: {
repositoryId: repository.id
}
});
},
onDelete(id: string) {
this.$store.dispatch('chatdoc/deleteRepository', { id }).then(() => {
ElMessage.success(this.$t('chatdoc.message.deleteRepositorySuccess'));
this.$store.dispatch('chatdoc/getRepositories');
});
}
}
});
</script>
<style lang="scss" scoped>
.wrapper {
width: 100%;
height: 100%;
padding: 20px;
background-color: #f2f3f5;
}
.title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
}
.introduction {
margin-bottom: 20px;
font-size: 14px;
color: #666;
}
.status {
margin-bottom: 10px;
width: fit-content;
}
.repository {
width: 100%;
height: 150px;
margin-bottom: 20px;
cursor: pointer;
position: relative;
.el-dropdown {
position: absolute;
right: 20px;
top: 20px;
}
.operation {
font-size: 16px;
font-weight: bold;
margin-bottom: 10px;
}
.name {
font-size: 16px;
font-weight: bold;
margin-bottom: 10px;
}
.id {
font-size: 12px;
color: #333;
}
.description {
font-size: 12px;
color: #666;
}
}
</style>
+175
View File
@@ -0,0 +1,175 @@
<template>
<layout>
<template #chatdoc>
<div class="wrapper">
<div class="title">
{{ $t('chatdoc.title.manage') }}
</div>
<div class="introduction">
{{ $t('chatdoc.message.introductionForKnowledge') }}
</div>
<div class="status">
<api-status
:initializing="initializing"
:application="application"
:need-apply="needApply"
:api-id="apiId"
@refresh="$store.dispatch('chatdoc/getApplications')"
/>
</div>
<div class="operations">
<upload-document />
</div>
<div class="documents">
<el-table :data="documents" border>
<el-table-column prop="id" label="ID" />
<el-table-column prop="file_name" :label="$t('chatdoc.field.fileName')" />
<el-table-column :label="$t('chatdoc.field.fileExtension')">
<template #default="scope">
{{ scope.row.file_name.split('.').pop() }}
</template>
</el-table-column>
<el-table-column :label="$t('chatdoc.field.createdAt')">
<template #default="scope">
{{ scope.row.created_at ? $dayjs.format(scope.row.created_at) : '' }}
</template>
</el-table-column>
<el-table-column :label="$t('chatdoc.field.state')">
<template #default="scope">
<el-tag v-if="scope.row.state === 'processing'" type="info">
{{ $t('chatdoc.field.stateProcessing') }}
</el-tag>
<el-tag v-if="scope.row.state === 'failed'" type="danger">
{{ $t('chatdoc.field.stateFailed') }}
</el-tag>
<el-tag v-if="scope.row.state === 'completed'" type="success">
{{ $t('chatdoc.field.stateCompleted') }}
</el-tag>
</template>
</el-table-column>
<el-table-column>
<template #default="scope">
<el-button type="danger" @click="onDelete(scope.row.id)">
{{ $t('common.button.delete') }}
</el-button>
</template>
</el-table-column>
</el-table>
</div>
</div>
</template>
</layout>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import Layout from '@/layouts/Chatdoc.vue';
import { IApplication, IChatdocRepository } from '@/operators';
import { ElButton, ElTag, ElTable, ElTableColumn, ElMessage } from 'element-plus';
import UploadDocument from '@/components/chatdoc/UploadDocument.vue';
import { Status } from '@/store/common/models';
import { API_ID_CHATDOC_DOCUMENTS } from '@/operators/chatdoc/constants';
import ApiStatus from '@/components/common/ApiStatus.vue';
export default defineComponent({
name: 'ChatdocKnowledge',
components: {
Layout,
ElButton,
ElTable,
ElTag,
ApiStatus,
ElTableColumn,
UploadDocument
},
data() {
return {
loading: false,
repositoryId: this.$route.params.repositoryId.toString()
};
},
computed: {
repository(): IChatdocRepository | undefined {
return this.$store.state?.chatdoc?.repositories?.find((repository) => repository.id === this.repositoryId);
},
documents() {
return this.repository?.documents;
},
needApply() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Success && !this.application;
},
applications() {
return this.$store.state.chatdoc.applications;
},
application() {
return this.applications?.find((application: IApplication) => application.api?.id === API_ID_CHATDOC_DOCUMENTS);
},
initializing() {
return this.$store.state.chatdoc.getApplicationsStatus === Status.Request;
},
apiId() {
return API_ID_CHATDOC_DOCUMENTS;
}
},
async mounted() {
console.log('start get documents');
this.loading = true;
this.$store
.dispatch('chatdoc/getDocuments', { repositoryId: this.repositoryId })
.then(() => {
this.loading = false;
})
.catch(() => {
this.loading = false;
});
},
methods: {
onDelete(id: string) {
this.$store.dispatch('chatdoc/deleteDocument', { id }).then(() => {
ElMessage.success(this.$t('chatdoc.message.deleteDocumentSuccess'));
this.$store.dispatch('chatdoc/getDocuments', {
repositoryId: this.repositoryId
});
});
}
}
});
</script>
<style lang="scss" scoped>
.wrapper {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
padding: 30px;
}
.el-button {
border-radius: 20px;
}
.title {
font-size: 20px;
font-weight: bold;
margin-bottom: 20px;
}
.introduction {
margin-bottom: 20px;
font-size: 14px;
color: #666;
}
.operations {
margin-bottom: 20px;
}
.documents {
width: 100%;
}
.status {
margin-bottom: 10px;
width: fit-content;
}
</style>
+22
View File
@@ -0,0 +1,22 @@
<template>
<layout>
<template #chatdoc> Setting </template>
</layout>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import Layout from '@/layouts/Chatdoc.vue';
export default defineComponent({
name: 'ChatdocSetting',
components: {
Layout
},
data() {
return {};
},
async mounted() {},
methods: {}
});
</script>
+3
View File
@@ -51,13 +51,16 @@ import {
faCube as faSolidCube,
faShieldHalved as faSolidShieldHalved,
faCubes as faSolidCubes,
faFileLines as faSolidFileLines,
faLink as faSolidLink,
faWandMagic as faSolidWandMagic
} from '@fortawesome/free-solid-svg-icons';
library.add(faRegularCopy);
library.add(faSolidStore);
library.add(faSolidChevronRight);
library.add(faSolidCube);
library.add(faSolidFileLines);
library.add(faSolidCompass);
library.add(faSolidPaperclip);
library.add(faSolidXmark);
+42
View File
@@ -0,0 +1,42 @@
import {
ROUTE_CHATDOC_CONVERSATION,
ROUTE_CHATDOC_CONVERSATION_NEW,
ROUTE_CHATDOC_INDEX,
ROUTE_CHATDOC_MANAGE,
ROUTE_CHATDOC_SETTING
} from './constants';
export default {
path: '/chatdoc',
meta: {
auth: true
},
component: () => import('@/layouts/Main.vue'),
children: [
{
path: '',
name: ROUTE_CHATDOC_INDEX,
component: () => import('@/pages/chatdoc/Index.vue')
},
{
path: 'repository/:repositoryId/conversation',
name: ROUTE_CHATDOC_CONVERSATION_NEW,
component: () => import('@/pages/chatdoc/Conversation.vue')
},
{
path: 'repository/:repositoryId/conversation/:conversationId',
name: ROUTE_CHATDOC_CONVERSATION,
component: () => import('@/pages/chatdoc/Conversation.vue')
},
{
path: 'repository/:repositoryId/manage',
name: ROUTE_CHATDOC_MANAGE,
component: () => import('@/pages/chatdoc/Manage.vue')
},
{
path: 'repository/:repositoryId',
name: ROUTE_CHATDOC_SETTING,
component: () => import('@/pages/chatdoc/Setting.vue')
}
]
};
+6
View File
@@ -9,6 +9,12 @@ export const ROUTE_CHAT_CONVERSATION_NEW = 'chat-conversation-new';
export const ROUTE_MIDJOURNEY_INDEX = 'midjourney-index';
export const ROUTE_MIDJOURNEY_HISTORY = 'midjourney-history';
export const ROUTE_CHATDOC_INDEX = 'chatdoc-index';
export const ROUTE_CHATDOC_CONVERSATION = 'chatdoc-conversation';
export const ROUTE_CHATDOC_CONVERSATION_NEW = 'chatdoc-conversation-new';
export const ROUTE_CHATDOC_SETTING = 'chatdoc-setting';
export const ROUTE_CHATDOC_MANAGE = 'chatdoc-knowledge';
export const ROUTE_CONSOLE_ROOT = 'console-root';
export const ROUTE_CONSOLE_ORDER_LIST = 'console-order-list';
export const ROUTE_CONSOLE_ORDER_DETAIL = 'console-order-detail';
+2
View File
@@ -4,6 +4,7 @@ import console from './console';
import chat from './chat';
import midjourney from './midjourney';
import distribution from './distribution';
import chatdoc from './chatdoc';
import { ROUTE_CHAT_CONVERSATION_NEW, ROUTE_INDEX } from './constants';
@@ -16,6 +17,7 @@ const routes = [
}
},
console,
chatdoc,
auth,
chat,
midjourney,
+3
View File
@@ -2,6 +2,9 @@ import { ROUTE_MIDJOURNEY_HISTORY, ROUTE_MIDJOURNEY_INDEX } from './constants';
export default {
path: '/midjourney',
meta: {
auth: true
},
component: () => import('@/layouts/Main.vue'),
children: [
{
+274
View File
@@ -0,0 +1,274 @@
import { IApplication, apiUsageOperator, applicationOperator } from '@/operators';
import { IRootState, Status } from '../common/models';
import { ActionContext } from 'vuex';
import { log } from '@/utils/log';
import { IChatdocState } from './models';
import { IChatdocConversation, IChatdocDocument, IChatdocRepository } from '@/operators/chatdoc/models';
import { chatdocOperator } from '@/operators/chatdoc/operator';
import {
API_ID_CHATDOC_CHAT,
API_ID_CHATDOC_DOCUMENTS,
API_ID_CHATDOC_REPOSITORIES
} from '@/operators/chatdoc/constants';
export const setApplications = async ({ commit }: any, payload: IApplication[]): Promise<void> => {
commit('setApplications', payload);
};
export const setRepository = async ({ commit }: any, payload: { repository: IChatdocRepository }): Promise<void> => {
commit('setRepository', payload);
};
export const getApplications = async ({
commit,
rootState
}: ActionContext<IChatdocState, IRootState>): Promise<IApplication[]> => {
log(getApplications, 'start to get application for chat');
commit('setGetApplicationsStatus', Status.Request);
const { data: applications } = await applicationOperator.getAll({
user_id: rootState.user.id,
api_id: [API_ID_CHATDOC_REPOSITORIES, API_ID_CHATDOC_CHAT, API_ID_CHATDOC_DOCUMENTS]
});
log(getApplications, 'get application for chat success', applications);
commit('setGetApplicationsStatus', Status.Success);
commit('setApplications', applications?.items);
return applications.items;
};
export const resetAll = ({ commit }: ActionContext<IChatdocState, IRootState>): void => {
commit('resetAll');
};
export const getRepositories = async ({
commit,
state
}: ActionContext<IChatdocState, IRootState>): Promise<IChatdocRepository[]> => {
log(getRepositories, 'start to get repositories');
commit('setGetRepositoriesStatus', Status.Request);
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_REPOSITORIES
);
console.log('application', application);
const token = application?.credential?.token;
if (!token) {
commit('setRepositories', undefined);
return [];
}
const repositories = (
await chatdocOperator.getAllRepositories({
token
})
).data;
commit('setGetRepositoriesStatus', Status.Success);
log(getRepositories, 'get repositories success', repositories);
commit('setRepositories', repositories);
return repositories;
};
export const deleteRepository = async (
{ state }: ActionContext<IChatdocState, IRootState>,
payload: {
id: string;
}
): Promise<IChatdocRepository> => {
log(deleteRepository, 'start to delete repository');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_REPOSITORIES
);
console.log('application', application);
const token = application?.credential?.token;
if (!token) {
return Promise.reject('no token');
}
const repository = (
await chatdocOperator.deleteRepository(payload.id, {
token
})
).data;
log(deleteRepository, 'delete repository success', repository);
return repository;
};
export const deleteDocument = async (
{ state }: ActionContext<IChatdocState, IRootState>,
payload: {
id: string;
}
): Promise<IChatdocDocument> => {
log(deleteDocument, 'start to delete document');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_DOCUMENTS
);
console.log('application', application);
const token = application?.credential?.token;
if (!token) {
return Promise.reject('no token');
}
const document = (
await chatdocOperator.deleteDocument(payload.id, {
token
})
).data;
log(deleteRepository, 'delete document success', document);
return document;
};
export const createRepository = async (
{ state }: ActionContext<IChatdocState, IRootState>,
payload: {
name: string;
description?: string;
}
): Promise<IChatdocRepository> => {
log(createRepository, 'start to create repository');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_REPOSITORIES
);
console.log('application', application);
const token = application?.credential?.token;
if (!token) {
return Promise.reject('no token');
}
const repository = (
await chatdocOperator.createRepository(payload, {
token
})
).data;
log(createRepository, 'create repository success', repository);
return repository;
};
export const createDocument = async (
{ state }: ActionContext<IChatdocState, IRootState>,
payload: {
repositoryId: string;
fileUrl: string;
fileName: string;
}
): Promise<IChatdocDocument> => {
log(createDocument, 'start to create document');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_DOCUMENTS
);
console.log('application', application);
const token = application?.credential?.token;
if (!token) {
return Promise.reject('no token');
}
const document = (
await chatdocOperator.createDocument(payload, {
token
})
).data;
log(createDocument, 'create document success', document);
return document;
};
export const getDocuments = async (
{ commit, state }: ActionContext<IChatdocState, IRootState>,
payload: { repositoryId: string }
): Promise<IChatdocDocument[]> => {
log(getRepositories, 'start to get documents');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_DOCUMENTS
);
console.log('application for getDocuments', application);
const token = application?.credential?.token;
if (!token) {
commit('setRepository', {
id: payload.repositoryId,
documents: []
});
return [];
}
const documents = (
await chatdocOperator.getAllDocuments(payload.repositoryId, {
token
})
).data;
log(getRepositories, 'get documents success', documents);
commit('setRepository', {
id: payload.repositoryId,
documents: documents
});
return documents;
};
export const getConversations = async (
{ commit, state }: ActionContext<IChatdocState, IRootState>,
payload: { repositoryId: string }
): Promise<IChatdocConversation[]> => {
log(getConversations, 'start to get conversations');
const applications = state.applications;
console.log('applications', applications);
const application = applications?.find((application: IApplication) => application.api?.id === API_ID_CHATDOC_CHAT);
console.log('application for getConversations', application);
const token = application?.credential?.token;
if (!token) {
commit('setRepository', {
id: payload.repositoryId,
conversations: []
});
return [];
}
const conversations = (await chatdocOperator.getAllConversations(payload.repositoryId)).data;
log(getConversations, 'get conversations success', conversations);
commit('setRepository', {
id: payload.repositoryId,
conversations: conversations
});
return conversations;
};
export const getRepository = async (
{ commit, state }: ActionContext<IChatdocState, IRootState>,
payload: { id: string }
): Promise<IChatdocRepository> => {
log(getRepository, 'start to get repository');
// commit('setGetRepositoryStatus', Status.Request);
const applications = state.applications;
const application = applications?.find(
(application: IApplication) => application.api?.id === API_ID_CHATDOC_REPOSITORIES
);
const token = application?.credential?.token;
if (!token) {
commit('setRepository', { id: payload.id });
return Promise.reject('no token');
}
const repository = (
await chatdocOperator.getRepository(payload.id, {
token
})
).data;
// commit('setGetRepositoryStatus', Status.Success);
log(getRepository, 'get repository success', repository);
commit('setRepository', repository);
return repository;
};
export default {
createRepository,
setApplications,
getApplications,
getRepositories,
deleteRepository,
getRepository,
setRepository,
getConversations,
getDocuments,
resetAll,
createDocument,
deleteDocument
};
+14
View File
@@ -0,0 +1,14 @@
import { Module } from 'vuex';
import actions from './actions';
import mutations from './mutations';
import state from './state';
import { IChatdocState } from './models';
export const chatdoc: Module<IChatdocState, any> = {
namespaced: true,
state,
mutations,
actions
};
export default chatdoc;
+10
View File
@@ -0,0 +1,10 @@
import { IApplication } from '@/operators';
import { Status } from '../common/models';
import { IChatdocRepository } from '@/operators/chatdoc/models';
export interface IChatdocState {
applications: IApplication[] | undefined;
getApplicationsStatus: Status | undefined;
repositories: IChatdocRepository[] | undefined;
getRepositoriesStatus: Status | undefined;
}
+74
View File
@@ -0,0 +1,74 @@
import { IApplication, IChatConversation, IChatModel } from '@/operators';
import { IChatdocState } from './models';
import { Status } from '../common/models';
import { IChatdocRepository } from '@/operators/chatdoc/models';
import { log } from '@/utils';
export const resetAll = (state: IChatdocState): void => {
state.applications = [];
state.getApplicationsStatus = Status.None;
state.repositories = [];
};
export const setApplications = (state: IChatdocState, payload: IApplication[]): void => {
state.applications = payload;
};
export const setGetApplicationsStatus = (state: IChatdocState, payload: Status): void => {
state.getApplicationsStatus = payload;
};
export const setRepositories = (state: IChatdocState, payload: IChatdocRepository[]): void => {
const currentRepositories = state.repositories;
if (currentRepositories) {
// merge current repositories into payload
payload.forEach((repository: IChatdocRepository) => {
const index = currentRepositories.findIndex((item: IChatdocRepository) => item.id === repository.id);
if (index !== -1) {
payload[index] = {
...currentRepositories[index],
...repository
};
}
});
state.repositories = payload;
return;
} else {
// set the repositories
state.repositories = payload;
}
};
export const setRepository = (state: IChatdocState, payload: IChatdocRepository): void => {
log(setRepository, 'mutation', payload);
// find the repository and set it
const repository = payload;
const repositories = state.repositories;
if (!repositories) {
log(setRepository, 'no repositories');
return;
}
const index = repositories.findIndex((item: IChatdocRepository) => item.id === repository.id);
if (index === -1) {
log(setRepository, 'no repository found');
return;
}
log(setRepository, 'set repository for index', index, repository);
repositories[index] = {
...repositories[index],
...repository
};
};
export const setGetRepositoriesStatus = (state: IChatdocState, payload: Status): void => {
state.getRepositoriesStatus = payload;
};
export default {
setApplications,
setGetApplicationsStatus,
setRepositories,
setRepository,
setGetRepositoriesStatus,
resetAll
};
+1
View File
@@ -0,0 +1 @@
export default ['chatdoc.repositories', 'chatdoc.applications'];
+10
View File
@@ -0,0 +1,10 @@
import { IChatdocState } from './models';
export default (): IChatdocState => {
return {
applications: undefined,
getApplicationsStatus: undefined,
repositories: undefined,
getRepositoriesStatus: undefined
};
};
+2
View File
@@ -1,6 +1,7 @@
import { IUser } from '@/operators';
import { IMidjourneyState } from '../midjourney/models';
import { IChatState } from '../chat/models';
import { IChatdocState } from '../chatdoc/models';
export enum Status {
Request = 'Request',
@@ -28,4 +29,5 @@ export interface ICommonState {
export interface IRootState extends ICommonState {
midjourney: IMidjourneyState;
chat: IChatState;
chatdoc: IChatdocState;
}
+5 -2
View File
@@ -2,20 +2,23 @@ import { createStore } from 'vuex';
import createPersistedState from 'vuex-persistedstate';
import midjourney from './midjourney';
import chat from './chat';
import chatdoc from './chatdoc';
import root from './common';
import persistChat from './chat/persist';
import persistMidjourney from './midjourney/persist';
import persistChatdoc from './chatdoc/persist';
import persistRoot from './common/persist';
const store = createStore({
...root,
modules: {
midjourney,
chat
chat,
chatdoc
},
plugins: [
createPersistedState({
paths: [...persistRoot, ...persistChat, ...persistMidjourney]
paths: [...persistRoot, ...persistChat, ...persistMidjourney, ...persistChatdoc]
})
]
});