Compare commits
No commits in common. 'main' and 'daima' have entirely different histories.
@ -1,2 +0,0 @@
|
||||
VITE_GLOB_API_URL=/api
|
||||
VITE_APP_API_BASE_URL=http://127.0.0.1:3002/
|
||||
@ -1,35 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.localnode_modules
|
||||
dist
|
||||
dist-ssr
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Project specifies
|
||||
*.pem
|
||||
*.crx
|
||||
|
||||
.history
|
||||
|
||||
.env.production
|
||||
.vercel
|
||||
@ -1,54 +0,0 @@
|
||||
# build front-end
|
||||
FROM node:lts-alpine AS frontend
|
||||
|
||||
RUN npm install npm -g
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY ./package.json /app
|
||||
|
||||
RUN npm install
|
||||
|
||||
COPY . /app
|
||||
|
||||
RUN npm run build
|
||||
|
||||
# build backend
|
||||
FROM node:lts-alpine as backend
|
||||
|
||||
RUN npm install pnpm -g
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY /service/package.json /app
|
||||
|
||||
COPY /service/pnpm-lock.yaml /app
|
||||
|
||||
RUN pnpm install
|
||||
|
||||
COPY /service /app
|
||||
|
||||
RUN pnpm build
|
||||
|
||||
# service
|
||||
FROM node:lts-alpine
|
||||
|
||||
RUN npm install pnpm -g
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY /service/package.json /app
|
||||
|
||||
COPY /service/pnpm-lock.yaml /app
|
||||
|
||||
RUN pnpm install --production && rm -rf /root/.npm /root/.pnpm-store /usr/local/share/.cache /tmp/*
|
||||
|
||||
COPY /service /app
|
||||
|
||||
COPY --from=frontend /app/dist /app/public
|
||||
|
||||
COPY --from=backend /app/build /app/build
|
||||
|
||||
EXPOSE 3002
|
||||
|
||||
CMD ["pnpm", "run", "prod"]
|
||||
@ -1,201 +0,0 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@ -1,21 +0,0 @@
|
||||
// generated by unplugin-vue-components
|
||||
// We suggest you to commit this file into source control
|
||||
// Read more: https://github.com/vuejs/core/pull/3399
|
||||
import '@vue/runtime-core'
|
||||
|
||||
export {}
|
||||
|
||||
declare module '@vue/runtime-core' {
|
||||
export interface GlobalComponents {
|
||||
ACol: typeof import('ant-design-vue/es')['Col']
|
||||
ACollapse: typeof import('ant-design-vue/es')['Collapse']
|
||||
ACollapsePanel: typeof import('ant-design-vue/es')['CollapsePanel']
|
||||
AInput: typeof import('ant-design-vue/es')['Input']
|
||||
ARow: typeof import('ant-design-vue/es')['Row']
|
||||
ATag: typeof import('ant-design-vue/es')['Tag']
|
||||
ContentOutput: typeof import('./src/components/gpt-terminal/ContentOutput.vue')['default']
|
||||
GptTerminal: typeof import('./src/components/gpt-terminal/GptTerminal.vue')['default']
|
||||
RouterLink: typeof import('vue-router')['RouterLink']
|
||||
RouterView: typeof import('vue-router')['RouterView']
|
||||
}
|
||||
}
|
||||
@ -1,28 +0,0 @@
|
||||
const { Configuration, OpenAIApi } = require("openai");
|
||||
|
||||
const configuration = new Configuration({
|
||||
apiKey: "",
|
||||
});
|
||||
const openai = new OpenAIApi(configuration);
|
||||
|
||||
async function createChatCompletion(messages) {
|
||||
const response = await openai.createChatCompletion({
|
||||
model: "gpt-3.5-turbo",
|
||||
messages,
|
||||
});
|
||||
if (response.data.choices.length) {
|
||||
const firstMessage = response.data.choices[0].message;
|
||||
if (firstMessage) {
|
||||
return firstMessage.content;
|
||||
}
|
||||
}
|
||||
throw new Error("Failed to get response from OpenAI service.");
|
||||
}
|
||||
|
||||
createChatCompletion([{ role: "user", content: "Hello world" }])
|
||||
.then(result => {
|
||||
console.log("result:", result);
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error);
|
||||
});
|
||||
@ -1,125 +0,0 @@
|
||||
{
|
||||
"name": "gpt-test",
|
||||
"version": "1.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gpt-test",
|
||||
"version": "1.0.0",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"axios": "^1.4.0",
|
||||
"openai": "^3.2.1"
|
||||
},
|
||||
"devDependencies": {}
|
||||
},
|
||||
"node_modules/asynckit": {
|
||||
"version": "0.4.0",
|
||||
"resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
|
||||
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.4.0.tgz",
|
||||
"integrity": "sha512-S4XCWMEmzvo64T9GfvQDOXgYRDJ/wsSZc7Jvdgx5u1sd0JwsuPLqb3SYmusag+edF6ziyMensPVqLTSc1PiSEA==",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.0",
|
||||
"form-data": "^4.0.0",
|
||||
"proxy-from-env": "^1.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/combined-stream": {
|
||||
"version": "1.0.8",
|
||||
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
|
||||
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
|
||||
"dependencies": {
|
||||
"delayed-stream": "~1.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.8"
|
||||
}
|
||||
},
|
||||
"node_modules/delayed-stream": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
|
||||
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
|
||||
"engines": {
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/follow-redirects": {
|
||||
"version": "1.15.2",
|
||||
"resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.2.tgz",
|
||||
"integrity": "sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "individual",
|
||||
"url": "https://github.com/sponsors/RubenVerborgh"
|
||||
}
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=4.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"debug": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/form-data": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz",
|
||||
"integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==",
|
||||
"dependencies": {
|
||||
"asynckit": "^0.4.0",
|
||||
"combined-stream": "^1.0.8",
|
||||
"mime-types": "^2.1.12"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-types": {
|
||||
"version": "2.1.35",
|
||||
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
|
||||
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
|
||||
"dependencies": {
|
||||
"mime-db": "1.52.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/openai": {
|
||||
"version": "3.2.1",
|
||||
"resolved": "https://registry.npmjs.org/openai/-/openai-3.2.1.tgz",
|
||||
"integrity": "sha512-762C9BNlJPbjjlWZi4WYK9iM2tAVAv0uUp1UmI34vb0CN5T2mjB/qM6RYBmNKMh/dN9fC+bxqPwWJZUTWW052A==",
|
||||
"dependencies": {
|
||||
"axios": "^0.26.0",
|
||||
"form-data": "^4.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/openai/node_modules/axios": {
|
||||
"version": "0.26.1",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz",
|
||||
"integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.14.8"
|
||||
}
|
||||
},
|
||||
"node_modules/proxy-from-env": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
|
||||
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
{
|
||||
"name": "gpt-test",
|
||||
"version": "1.0.0",
|
||||
"main": "index.js",
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"axios": "^1.4.0",
|
||||
"openai": "^3.2.1"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "node index.js"
|
||||
},
|
||||
"description": ""
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>GPT 终端 | 程序员方式打开 GPT | By 周三不Coding</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,59 +0,0 @@
|
||||
{
|
||||
"name": "gpt-web-terminal",
|
||||
"description": "专属于你的GPT终端",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"dev:crx": "cross-env BUILD_CRX=1 vite build --watch",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"build:crx": "cross-env BUILD_CRX=1 vite build",
|
||||
"preview": "vite preview",
|
||||
"tsc": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"ant-design-vue": "^3.2.10",
|
||||
"axios": "^1.3.4",
|
||||
"dayjs": "^1.11.3",
|
||||
"getopts": "^2.3.0",
|
||||
"highlight.js": "^11.8.0",
|
||||
"hljs": "^6.2.3",
|
||||
"lodash": "^4.17.21",
|
||||
"marked": "^5.1.0",
|
||||
"openai": "^3.2.1",
|
||||
"pinia": "^2.0.14",
|
||||
"pinia-plugin-persistedstate": "^1.6.1",
|
||||
"vue": "^3.2.25",
|
||||
"vue-router": "4",
|
||||
"xterm": "^4.19.0",
|
||||
"xterm-addon-fit": "^0.5.0",
|
||||
"xterm-addon-web-links": "^0.6.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/lodash": "^4.14.182",
|
||||
"@types/marked": "^5.0.0",
|
||||
"@types/node": "^18.6.4",
|
||||
"@typescript-eslint/eslint-plugin": "^5.23.0",
|
||||
"@typescript-eslint/parser": "^5.23.0",
|
||||
"@vitejs/plugin-vue": "^4.0.0",
|
||||
"consola": "^2.15.3",
|
||||
"cross-env": "^7.0.3",
|
||||
"crx": "^5.0.1",
|
||||
"eslint": "^8.15.0",
|
||||
"eslint-config-prettier": "^8.5.0",
|
||||
"eslint-config-standard": "^17.0.0",
|
||||
"eslint-plugin-import": "^2.26.0",
|
||||
"eslint-plugin-n": "^15.2.0",
|
||||
"eslint-plugin-prettier": "^4.0.0",
|
||||
"eslint-plugin-promise": "^6.0.0",
|
||||
"eslint-plugin-vue": "^8.7.1",
|
||||
"npm-run-all": "^4.1.5",
|
||||
"ora": "5",
|
||||
"prettier": "^2.7.1",
|
||||
"typescript": "^4.6.4",
|
||||
"unplugin-vue-components": "^0.21.1",
|
||||
"vite": "^4.2.0",
|
||||
"vite-plugin-pwa": "^0.14.4",
|
||||
"vue-tsc": "^0.38.4"
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 7.2 KiB |
@ -1,45 +0,0 @@
|
||||
# OpenAI API Key - https://platform.openai.com/overview
|
||||
OPENAI_API_KEY=model_credential.get('api_key'),
|
||||
**optional_params
|
||||
|
||||
# change this to an `accessToken` extracted from the ChatGPT site's `https://chat.openai.com/api/auth/session` response
|
||||
OPENAI_ACCESS_TOKEN=
|
||||
|
||||
# OpenAI API Base URL - https://api.openai.com
|
||||
OPENAI_API_BASE_URL=
|
||||
|
||||
# OpenAI API Model - https://platform.openai.com/docs/models
|
||||
OPENAI_API_MODEL=
|
||||
|
||||
# set `true` to disable OpenAI API debug log
|
||||
OPENAI_API_DISABLE_DEBUG=
|
||||
|
||||
# Reverse Proxy - Available on accessToken
|
||||
# Default: https://ai.fakeopen.com/api/conversation
|
||||
# More: https://github.com/transitive-bullshit/chatgpt-api#reverse-proxy
|
||||
API_REVERSE_PROXY=
|
||||
|
||||
# timeout
|
||||
TIMEOUT_MS=100000
|
||||
|
||||
# Rate Limit
|
||||
MAX_REQUEST_PER_HOUR=
|
||||
|
||||
# Secret key
|
||||
AUTH_SECRET_KEY=
|
||||
|
||||
# Socks Proxy Host
|
||||
SOCKS_PROXY_HOST=
|
||||
|
||||
# Socks Proxy Port
|
||||
SOCKS_PROXY_PORT=
|
||||
|
||||
# Socks Proxy Username
|
||||
SOCKS_PROXY_USERNAME=
|
||||
|
||||
# Socks Proxy Password
|
||||
SOCKS_PROXY_PASSWORD=
|
||||
|
||||
# HTTPS PROXY
|
||||
HTTPS_PROXY=
|
||||
|
||||
@ -1,5 +0,0 @@
|
||||
{
|
||||
"root": true,
|
||||
"ignorePatterns": ["build"],
|
||||
"extends": ["@antfu"]
|
||||
}
|
||||
@ -1,31 +0,0 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
.DS_Store
|
||||
dist
|
||||
dist-ssr
|
||||
coverage
|
||||
*.local
|
||||
|
||||
/cypress/videos/
|
||||
/cypress/screenshots/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
build
|
||||
@ -1 +0,0 @@
|
||||
enable-pre-post-scripts=true
|
||||
@ -1,3 +0,0 @@
|
||||
{
|
||||
"recommendations": ["dbaeumer.vscode-eslint"]
|
||||
}
|
||||
@ -1,22 +0,0 @@
|
||||
{
|
||||
"prettier.enable": false,
|
||||
"editor.formatOnSave": false,
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.eslint": true
|
||||
},
|
||||
"eslint.validate": [
|
||||
"javascript",
|
||||
"typescript",
|
||||
"json",
|
||||
"jsonc",
|
||||
"json5",
|
||||
"yaml"
|
||||
],
|
||||
"cSpell.words": [
|
||||
"antfu",
|
||||
"chatgpt",
|
||||
"esno",
|
||||
"GPTAPI",
|
||||
"OPENAI"
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,47 +0,0 @@
|
||||
{
|
||||
"name": "chatgpt-web-service",
|
||||
"version": "1.0.0",
|
||||
"private": false,
|
||||
"description": "ChatGPT Web Service",
|
||||
"author": "ChenZhaoYu <chenzhaoyu1994@gmail.com>",
|
||||
"keywords": [
|
||||
"chatgpt-web",
|
||||
"chatgpt",
|
||||
"chatbot",
|
||||
"express"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^16 || ^18 || ^19"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "esno ./src/index.ts",
|
||||
"dev": "esno watch ./src/index.ts",
|
||||
"prod": "node ./build/index.mjs",
|
||||
"build": "pnpm clean && tsup",
|
||||
"clean": "rimraf build",
|
||||
"lint": "eslint .",
|
||||
"lint:fix": "eslint . --fix",
|
||||
"common:cleanup": "rimraf node_modules && rimraf pnpm-lock.yaml"
|
||||
},
|
||||
"dependencies": {
|
||||
"axios": "^1.3.4",
|
||||
"chatgpt": "^5.1.2",
|
||||
"dotenv": "^16.0.3",
|
||||
"esno": "^0.16.3",
|
||||
"express": "^4.18.2",
|
||||
"express-rate-limit": "^6.7.0",
|
||||
"https-proxy-agent": "^5.0.1",
|
||||
"isomorphic-fetch": "^3.0.0",
|
||||
"node-fetch": "^3.3.0",
|
||||
"socks-proxy-agent": "^7.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@antfu/eslint-config": "^0.35.3",
|
||||
"@types/express": "^4.17.17",
|
||||
"@types/node": "^18.14.6",
|
||||
"eslint": "^8.35.0",
|
||||
"rimraf": "^4.3.0",
|
||||
"tsup": "^6.6.3",
|
||||
"typescript": "^4.9.5"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@ -1,226 +0,0 @@
|
||||
import * as dotenv from 'dotenv'
|
||||
import 'isomorphic-fetch'
|
||||
import type { ChatGPTAPIOptions, ChatMessage, SendMessageOptions } from 'chatgpt'
|
||||
import { ChatGPTAPI, ChatGPTUnofficialProxyAPI } from 'chatgpt'
|
||||
import { SocksProxyAgent } from 'socks-proxy-agent'
|
||||
import httpsProxyAgent from 'https-proxy-agent'
|
||||
import fetch from 'node-fetch'
|
||||
import { sendResponse } from '../utils'
|
||||
import { isNotEmptyString } from '../utils/is'
|
||||
import type { ApiModel, ChatContext, ChatGPTUnofficialProxyAPIOptions, ModelConfig } from '../types'
|
||||
import type { RequestOptions, SetProxyOptions, UsageResponse } from './types'
|
||||
|
||||
const { HttpsProxyAgent } = httpsProxyAgent
|
||||
|
||||
dotenv.config()
|
||||
|
||||
const ErrorCodeMessage: Record<string, string> = {
|
||||
401: '[OpenAI] 提供错误的API密钥 | Incorrect API key provided',
|
||||
403: '[OpenAI] 服务器拒绝访问,请稍后再试 | Server refused to access, please try again later',
|
||||
502: '[OpenAI] 错误的网关 | Bad Gateway',
|
||||
503: '[OpenAI] 服务器繁忙,请稍后再试 | Server is busy, please try again later',
|
||||
504: '[OpenAI] 网关超时 | Gateway Time-out',
|
||||
500: '[OpenAI] 服务器繁忙,请稍后再试 | Internal Server Error',
|
||||
}
|
||||
|
||||
const timeoutMs: number = !isNaN(+process.env.TIMEOUT_MS) ? +process.env.TIMEOUT_MS : 100 * 1000
|
||||
const disableDebug: boolean = process.env.OPENAI_API_DISABLE_DEBUG === 'true'
|
||||
|
||||
let apiModel: ApiModel
|
||||
const model = isNotEmptyString(process.env.OPENAI_API_MODEL) ? process.env.OPENAI_API_MODEL : 'gpt-3.5-turbo'
|
||||
|
||||
if (!isNotEmptyString(process.env.OPENAI_API_KEY) && !isNotEmptyString(process.env.OPENAI_ACCESS_TOKEN))
|
||||
throw new Error('Missing OPENAI_API_KEY or OPENAI_ACCESS_TOKEN environment variable')
|
||||
|
||||
let api: ChatGPTAPI | ChatGPTUnofficialProxyAPI
|
||||
|
||||
(async () => {
|
||||
// More Info: https://github.com/transitive-bullshit/chatgpt-api
|
||||
|
||||
if (isNotEmptyString(process.env.OPENAI_API_KEY)) {
|
||||
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
||||
|
||||
const options: ChatGPTAPIOptions = {
|
||||
apiKey: process.env.OPENAI_API_KEY,
|
||||
completionParams: { model },
|
||||
debug: !disableDebug,
|
||||
}
|
||||
|
||||
// increase max token limit if use gpt-4
|
||||
if (model.toLowerCase().includes('gpt-4')) {
|
||||
// if use 32k model
|
||||
if (model.toLowerCase().includes('32k')) {
|
||||
options.maxModelTokens = 32768
|
||||
options.maxResponseTokens = 8192
|
||||
}
|
||||
else {
|
||||
options.maxModelTokens = 8192
|
||||
options.maxResponseTokens = 2048
|
||||
}
|
||||
}
|
||||
else if (model.toLowerCase().includes('gpt-3.5')) {
|
||||
if (model.toLowerCase().includes('16k')) {
|
||||
options.maxModelTokens = 16384
|
||||
options.maxResponseTokens = 4096
|
||||
}
|
||||
}
|
||||
|
||||
if (isNotEmptyString(OPENAI_API_BASE_URL))
|
||||
options.apiBaseUrl = `${OPENAI_API_BASE_URL}/v1`
|
||||
|
||||
setupProxy(options)
|
||||
|
||||
api = new ChatGPTAPI({ ...options })
|
||||
apiModel = 'ChatGPTAPI'
|
||||
}
|
||||
else {
|
||||
const options: ChatGPTUnofficialProxyAPIOptions = {
|
||||
accessToken: process.env.OPENAI_ACCESS_TOKEN,
|
||||
apiReverseProxyUrl: isNotEmptyString(process.env.API_REVERSE_PROXY) ? process.env.API_REVERSE_PROXY : 'https://ai.fakeopen.com/api/conversation',
|
||||
model,
|
||||
debug: !disableDebug,
|
||||
}
|
||||
|
||||
setupProxy(options)
|
||||
|
||||
api = new ChatGPTUnofficialProxyAPI({ ...options })
|
||||
apiModel = 'ChatGPTUnofficialProxyAPI'
|
||||
}
|
||||
})()
|
||||
|
||||
async function chatReplyProcess(options: RequestOptions) {
|
||||
const { message, lastContext, process, systemMessage, temperature, top_p } = options
|
||||
try {
|
||||
let options: SendMessageOptions = { timeoutMs }
|
||||
globalThis.console.log(systemMessage)
|
||||
if (apiModel === 'ChatGPTAPI') {
|
||||
if (isNotEmptyString(systemMessage)) {
|
||||
options.systemMessage = systemMessage
|
||||
globalThis.console.log(systemMessage)
|
||||
}
|
||||
options.completionParams = { model, temperature, top_p }
|
||||
}
|
||||
|
||||
if (lastContext != null) {
|
||||
if (apiModel === 'ChatGPTAPI')
|
||||
options.parentMessageId = lastContext.parentMessageId
|
||||
else
|
||||
options = { ...lastContext }
|
||||
}
|
||||
|
||||
const response = await api.sendMessage(message, {
|
||||
...options,
|
||||
onProgress: (partialResponse) => {
|
||||
process?.(partialResponse)
|
||||
},
|
||||
})
|
||||
|
||||
return sendResponse({ type: 'Success', data: response })
|
||||
}
|
||||
catch (error: any) {
|
||||
const code = error.statusCode
|
||||
global.console.log(error)
|
||||
if (Reflect.has(ErrorCodeMessage, code))
|
||||
return sendResponse({ type: 'Fail', message: ErrorCodeMessage[code] })
|
||||
return sendResponse({ type: 'Fail', message: error.message ?? 'Please check the back-end console' })
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchUsage() {
|
||||
const OPENAI_API_KEY = process.env.OPENAI_API_KEY
|
||||
const OPENAI_API_BASE_URL = process.env.OPENAI_API_BASE_URL
|
||||
|
||||
if (!isNotEmptyString(OPENAI_API_KEY))
|
||||
return Promise.resolve('-')
|
||||
|
||||
const API_BASE_URL = isNotEmptyString(OPENAI_API_BASE_URL)
|
||||
? OPENAI_API_BASE_URL
|
||||
: 'https://api.openai.com'
|
||||
|
||||
const [startDate, endDate] = formatDate()
|
||||
|
||||
// 每月使用量
|
||||
const urlUsage = `${API_BASE_URL}/v1/dashboard/billing/usage?start_date=${startDate}&end_date=${endDate}`
|
||||
|
||||
const headers = {
|
||||
'Authorization': `Bearer ${OPENAI_API_KEY}`,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
const options = {} as SetProxyOptions
|
||||
|
||||
setupProxy(options)
|
||||
|
||||
try {
|
||||
// 获取已使用量
|
||||
const useResponse = await options.fetch(urlUsage, { headers })
|
||||
if (!useResponse.ok)
|
||||
throw new Error('获取使用量失败')
|
||||
const usageData = await useResponse.json() as UsageResponse
|
||||
const usage = Math.round(usageData.total_usage) / 100
|
||||
return Promise.resolve(usage ? `$${usage}` : '-')
|
||||
}
|
||||
catch (error) {
|
||||
global.console.log(error)
|
||||
return Promise.resolve('-')
|
||||
}
|
||||
}
|
||||
|
||||
function formatDate(): string[] {
|
||||
const today = new Date()
|
||||
const year = today.getFullYear()
|
||||
const month = today.getMonth() + 1
|
||||
const lastDay = new Date(year, month, 0)
|
||||
const formattedFirstDay = `${year}-${month.toString().padStart(2, '0')}-01`
|
||||
const formattedLastDay = `${year}-${month.toString().padStart(2, '0')}-${lastDay.getDate().toString().padStart(2, '0')}`
|
||||
return [formattedFirstDay, formattedLastDay]
|
||||
}
|
||||
|
||||
async function chatConfig() {
|
||||
const usage = await fetchUsage()
|
||||
const reverseProxy = process.env.API_REVERSE_PROXY ?? '-'
|
||||
const httpsProxy = (process.env.HTTPS_PROXY || process.env.ALL_PROXY) ?? '-'
|
||||
const socksProxy = (process.env.SOCKS_PROXY_HOST && process.env.SOCKS_PROXY_PORT)
|
||||
? (`${process.env.SOCKS_PROXY_HOST}:${process.env.SOCKS_PROXY_PORT}`)
|
||||
: '-'
|
||||
return sendResponse<ModelConfig>({
|
||||
type: 'Success',
|
||||
data: { apiModel, reverseProxy, timeoutMs, socksProxy, httpsProxy, usage },
|
||||
})
|
||||
}
|
||||
|
||||
function setupProxy(options: SetProxyOptions) {
|
||||
if (isNotEmptyString(process.env.SOCKS_PROXY_HOST) && isNotEmptyString(process.env.SOCKS_PROXY_PORT)) {
|
||||
const agent = new SocksProxyAgent({
|
||||
hostname: process.env.SOCKS_PROXY_HOST,
|
||||
port: process.env.SOCKS_PROXY_PORT,
|
||||
userId: isNotEmptyString(process.env.SOCKS_PROXY_USERNAME) ? process.env.SOCKS_PROXY_USERNAME : undefined,
|
||||
password: isNotEmptyString(process.env.SOCKS_PROXY_PASSWORD) ? process.env.SOCKS_PROXY_PASSWORD : undefined,
|
||||
})
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
else if (isNotEmptyString(process.env.HTTPS_PROXY) || isNotEmptyString(process.env.ALL_PROXY)) {
|
||||
const httpsProxy = process.env.HTTPS_PROXY || process.env.ALL_PROXY
|
||||
if (httpsProxy) {
|
||||
const agent = new HttpsProxyAgent(httpsProxy)
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { agent, ...options })
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
options.fetch = (url, options) => {
|
||||
return fetch(url, { ...options })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function currentModel(): ApiModel {
|
||||
return apiModel
|
||||
}
|
||||
|
||||
export type { ChatContext, ChatMessage }
|
||||
|
||||
export { chatReplyProcess, chatConfig, currentModel }
|
||||
@ -1,23 +0,0 @@
|
||||
import type { ChatMessage } from 'chatgpt'
|
||||
import type fetch from 'node-fetch'
|
||||
|
||||
export interface RequestOptions {
|
||||
message: string
|
||||
lastContext?: { conversationId?: string; parentMessageId?: string }
|
||||
process?: (chat: ChatMessage) => void
|
||||
systemMessage?: string
|
||||
temperature?: number
|
||||
top_p?: number
|
||||
}
|
||||
|
||||
export interface ImageRequestOptions {
|
||||
|
||||
}
|
||||
|
||||
export interface SetProxyOptions {
|
||||
fetch?: typeof fetch
|
||||
}
|
||||
|
||||
export interface UsageResponse {
|
||||
total_usage: number
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
import express from 'express'
|
||||
import type { RequestProps } from './types'
|
||||
import type { ChatMessage } from './chatgpt'
|
||||
import { chatConfig, chatReplyProcess, currentModel } from './chatgpt'
|
||||
import { limiter } from './middleware/limiter'
|
||||
import { isNotEmptyString } from './utils/is'
|
||||
|
||||
const app = express()
|
||||
const router = express.Router()
|
||||
|
||||
app.use(express.static('public'))
|
||||
app.use(express.json())
|
||||
|
||||
app.all('*', (_, res, next) => {
|
||||
res.header('Access-Control-Allow-Origin', '*')
|
||||
res.header('Access-Control-Allow-Headers', 'authorization, Content-Type')
|
||||
res.header('Access-Control-Allow-Methods', '*')
|
||||
next()
|
||||
})
|
||||
|
||||
router.post('/chat-process', [limiter], async (req, res) => {
|
||||
res.setHeader('Content-type', 'application/octet-stream')
|
||||
|
||||
try {
|
||||
const { prompt, options = {}, systemMessage, temperature, top_p } = req.body as RequestProps
|
||||
let firstChunk = true
|
||||
await chatReplyProcess({
|
||||
message: prompt,
|
||||
lastContext: options,
|
||||
process: (chat: ChatMessage) => {
|
||||
res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
|
||||
firstChunk = false
|
||||
},
|
||||
systemMessage,
|
||||
temperature,
|
||||
top_p,
|
||||
})
|
||||
}
|
||||
catch (error) {
|
||||
res.write(JSON.stringify(error))
|
||||
}
|
||||
finally {
|
||||
res.end()
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/config', async (req, res) => {
|
||||
try {
|
||||
const response = await chatConfig()
|
||||
res.send(response)
|
||||
}
|
||||
catch (error) {
|
||||
res.send(error)
|
||||
}
|
||||
})
|
||||
|
||||
app.use('', router)
|
||||
app.use('/api', router)
|
||||
app.set('trust proxy', 1)
|
||||
|
||||
app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
|
||||
@ -1,34 +0,0 @@
|
||||
import type { FetchFn } from 'chatgpt'
|
||||
|
||||
export interface RequestProps {
|
||||
prompt: string
|
||||
options?: ChatContext
|
||||
systemMessage: string
|
||||
temperature?: number
|
||||
top_p?: number
|
||||
}
|
||||
|
||||
export interface ChatContext {
|
||||
conversationId?: string
|
||||
parentMessageId?: string
|
||||
}
|
||||
|
||||
export interface ChatGPTUnofficialProxyAPIOptions {
|
||||
accessToken: string
|
||||
apiReverseProxyUrl?: string
|
||||
model?: string
|
||||
debug?: boolean
|
||||
headers?: Record<string, string>
|
||||
fetch?: FetchFn
|
||||
}
|
||||
|
||||
export interface ModelConfig {
|
||||
apiModel?: ApiModel
|
||||
reverseProxy?: string
|
||||
timeoutMs?: number
|
||||
socksProxy?: string
|
||||
httpsProxy?: string
|
||||
usage?: string
|
||||
}
|
||||
|
||||
export type ApiModel = 'ChatGPTAPI' | 'ChatGPTUnofficialProxyAPI' | undefined
|
||||
@ -1,22 +0,0 @@
|
||||
interface SendResponseOptions<T = any> {
|
||||
type: 'Success' | 'Fail'
|
||||
message?: string
|
||||
data?: T
|
||||
}
|
||||
|
||||
export function sendResponse<T>(options: SendResponseOptions<T>) {
|
||||
if (options.type === 'Success') {
|
||||
return Promise.resolve({
|
||||
message: options.message ?? null,
|
||||
data: options.data ?? null,
|
||||
status: options.type,
|
||||
})
|
||||
}
|
||||
|
||||
// eslint-disable-next-line prefer-promise-reject-errors
|
||||
return Promise.reject({
|
||||
message: options.message ?? 'Failed',
|
||||
data: options.data ?? null,
|
||||
status: options.type,
|
||||
})
|
||||
}
|
||||
@ -1,19 +0,0 @@
|
||||
export function isNumber<T extends number>(value: T | unknown): value is number {
|
||||
return Object.prototype.toString.call(value) === '[object Number]'
|
||||
}
|
||||
|
||||
export function isString<T extends string>(value: T | unknown): value is string {
|
||||
return Object.prototype.toString.call(value) === '[object String]'
|
||||
}
|
||||
|
||||
export function isNotEmptyString(value: any): boolean {
|
||||
return typeof value === 'string' && value.length > 0
|
||||
}
|
||||
|
||||
export function isBoolean<T extends boolean>(value: T | unknown): value is boolean {
|
||||
return Object.prototype.toString.call(value) === '[object Boolean]'
|
||||
}
|
||||
|
||||
export function isFunction<T extends (...args: any[]) => any | void | never>(value: T | unknown): value is T {
|
||||
return Object.prototype.toString.call(value) === '[object Function]'
|
||||
}
|
||||
@ -1,27 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "es2020",
|
||||
"lib": [
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"strict": false,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"esModuleInterop": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"baseUrl": ".",
|
||||
"outDir": "build",
|
||||
"noEmit": true
|
||||
},
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"build"
|
||||
],
|
||||
"include": [
|
||||
"**/*.ts"
|
||||
]
|
||||
}
|
||||
@ -1,13 +0,0 @@
|
||||
import { defineConfig } from 'tsup'
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
outDir: 'build',
|
||||
target: 'es2020',
|
||||
format: ['esm'],
|
||||
splitting: false,
|
||||
sourcemap: true,
|
||||
minify: false,
|
||||
shims: true,
|
||||
dts: false,
|
||||
})
|
||||
@ -1,11 +0,0 @@
|
||||
<template>
|
||||
<router-view />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts"></script>
|
||||
|
||||
<style>
|
||||
body {
|
||||
margin: 0;
|
||||
}
|
||||
</style>
|
||||
|
Before Width: | Height: | Size: 6.7 KiB |
@ -1,76 +0,0 @@
|
||||
<template>
|
||||
<div class="content-output">
|
||||
<template v-if="output.type === 'text'">
|
||||
<a-tag v-if="outputTagColor" :color="outputTagColor"
|
||||
>{{ output.status }}
|
||||
</a-tag>
|
||||
<span v-if="output.type === 'text'" v-html="smartText(output.text)" />
|
||||
</template>
|
||||
<component
|
||||
@start="handleStart"
|
||||
@finish="handleFinish"
|
||||
@failed="handleFailed"
|
||||
:is="output.component"
|
||||
v-if="output.type === 'component'"
|
||||
v-bind="output.props ?? {}"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import smartText from "../../utils/smartText";
|
||||
import OutputType = GptTerminal.OutputType;
|
||||
import { computed, toRefs, defineEmits } from "vue";
|
||||
|
||||
interface OutputProps {
|
||||
output: OutputType;
|
||||
}
|
||||
|
||||
const props = defineProps<OutputProps>();
|
||||
const { output } = toRefs(props);
|
||||
const outputTagColor = computed((): string => {
|
||||
if (!output.value.status) {
|
||||
return "";
|
||||
}
|
||||
switch (output.value.status) {
|
||||
case "info":
|
||||
return "dodgerblue";
|
||||
case "success":
|
||||
return "limegreen";
|
||||
case "warning":
|
||||
return "darkorange";
|
||||
case "error":
|
||||
return "#c0300f";
|
||||
case "system":
|
||||
return "#bfc4c9";
|
||||
case "loading":
|
||||
return "#ead029"
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
});
|
||||
|
||||
const emit = defineEmits(['start', 'finish', 'failed'])
|
||||
|
||||
// gpt 输出开始时的回调
|
||||
const handleStart = () => {
|
||||
emit('start')
|
||||
}
|
||||
|
||||
// gpt 输出结束后的回调
|
||||
const handleFinish = () => {
|
||||
emit('finish')
|
||||
}
|
||||
|
||||
const handleFailed = () => {
|
||||
emit('failed')
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.content-output :deep(.ant-tag) {
|
||||
border-radius: 0;
|
||||
font-size: 16px;
|
||||
border: none;
|
||||
}
|
||||
</style>
|
||||
@ -1,55 +0,0 @@
|
||||
import { ref } from "vue";
|
||||
import { getUsageStr } from "../../core/commands/terminal/help/helpUtils";
|
||||
import { commandMap } from "../../core/commandRegister";
|
||||
import _, { trim } from "lodash";
|
||||
|
||||
/**
|
||||
* 命令提示功能
|
||||
* @author yupi
|
||||
*/
|
||||
const useHint = () => {
|
||||
const hint = ref("");
|
||||
const setHint = (inputText: string) => {
|
||||
if (!inputText) {
|
||||
hint.value = "";
|
||||
return;
|
||||
}
|
||||
const args = trim(inputText).split(" ");
|
||||
// 大小写无关
|
||||
let func = args[0].toLowerCase();
|
||||
// 前缀匹配
|
||||
const likeKey = Object.keys(commandMap).filter((key) =>
|
||||
key.startsWith(func)
|
||||
)[0];
|
||||
let command = commandMap[likeKey];
|
||||
if (!command) {
|
||||
hint.value = "";
|
||||
return;
|
||||
}
|
||||
// 子命令提示
|
||||
if (
|
||||
command.subCommands &&
|
||||
Object.keys(command.subCommands).length > 0 &&
|
||||
args.length > 1
|
||||
) {
|
||||
hint.value = getUsageStr(command.subCommands[args[1]], command);
|
||||
} else {
|
||||
hint.value = getUsageStr(command);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* 输入提示防抖
|
||||
*/
|
||||
const debounceSetHint = _.debounce(function (inputText: string) {
|
||||
setHint(inputText);
|
||||
}, 100);
|
||||
|
||||
return {
|
||||
hint,
|
||||
setHint,
|
||||
debounceSetHint,
|
||||
};
|
||||
};
|
||||
|
||||
export default useHint;
|
||||
@ -1,50 +0,0 @@
|
||||
import { Ref, ref } from "vue";
|
||||
import CommandOutputType = GptTerminal.CommandOutputType;
|
||||
import CommandInputType = GptTerminal.CommandInputType;
|
||||
|
||||
/**
|
||||
* 查看历史功能
|
||||
* @param commandList
|
||||
* @param inputCommand
|
||||
*/
|
||||
const useHistory = (
|
||||
commandList: CommandOutputType[],
|
||||
inputCommand: Ref<CommandInputType>
|
||||
) => {
|
||||
/**
|
||||
* 当前查看的命令位置
|
||||
*/
|
||||
const commandHistoryPos = ref(commandList.length);
|
||||
|
||||
const listCommandHistory = () => {
|
||||
return commandList;
|
||||
};
|
||||
|
||||
const showNextCommand = () => {
|
||||
console.log(commandHistoryPos.value, commandList, inputCommand);
|
||||
if (commandHistoryPos.value < commandList.length - 1) {
|
||||
commandHistoryPos.value++;
|
||||
inputCommand.value.text = commandList[commandHistoryPos.value].text;
|
||||
} else if (commandHistoryPos.value === commandList.length - 1) {
|
||||
commandHistoryPos.value++;
|
||||
inputCommand.value.text = "";
|
||||
}
|
||||
};
|
||||
|
||||
const showPrevCommand = () => {
|
||||
console.log(commandHistoryPos.value, commandList, inputCommand);
|
||||
if (commandHistoryPos.value >= 1) {
|
||||
commandHistoryPos.value--;
|
||||
inputCommand.value.text = commandList[commandHistoryPos.value].text;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
commandHistoryPos,
|
||||
listCommandHistory,
|
||||
showNextCommand,
|
||||
showPrevCommand,
|
||||
};
|
||||
};
|
||||
|
||||
export default useHistory;
|
||||
@ -1,135 +0,0 @@
|
||||
/**
|
||||
* 快捷键系统
|
||||
* @author yupi
|
||||
*/
|
||||
import TerminalType = GptTerminal.TerminalType;
|
||||
|
||||
/**
|
||||
* 注册快捷键
|
||||
* @param terminal
|
||||
*/
|
||||
export const registerShortcuts = (terminal: TerminalType) => {
|
||||
document.onkeydown = (e) => {
|
||||
// console.log(e);
|
||||
let key = e.key;
|
||||
// 自动聚焦输入框
|
||||
if (key >= "a" && key <= "z" && !e.metaKey && !e.shiftKey && !e.ctrlKey) {
|
||||
terminal.focusInput();
|
||||
return;
|
||||
}
|
||||
// 匹配快捷键
|
||||
let code = e.code;
|
||||
for (const shortcut of shortcutList) {
|
||||
if (
|
||||
code === shortcut.code &&
|
||||
e.ctrlKey == !!shortcut.ctrlKey &&
|
||||
e.metaKey == !!shortcut.metaKey &&
|
||||
e.shiftKey == !!shortcut.shiftKey
|
||||
) {
|
||||
shortcut.action(e, terminal);
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
/**
|
||||
* 快捷键类型
|
||||
*/
|
||||
interface ShortcutType {
|
||||
code: string; // 按键码
|
||||
desc?: string; // 功能描述
|
||||
keyDesc?: string; // 按键描述
|
||||
ctrlKey?: boolean;
|
||||
metaKey?: boolean;
|
||||
shiftKey?: boolean;
|
||||
action: (e: Event, terminal: TerminalType) => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 快捷键列表
|
||||
*/
|
||||
export const shortcutList: ShortcutType[] = [
|
||||
{
|
||||
desc: "清屏",
|
||||
code: "KeyL",
|
||||
keyDesc: "Ctrl + L",
|
||||
ctrlKey: true,
|
||||
action(e, terminal) {
|
||||
e.preventDefault();
|
||||
terminal.clear();
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "折叠",
|
||||
code: "KeyO",
|
||||
keyDesc: "Ctrl + O",
|
||||
ctrlKey: true,
|
||||
action(e, terminal) {
|
||||
e.preventDefault();
|
||||
terminal.toggleAllCollapse();
|
||||
},
|
||||
},
|
||||
// {
|
||||
// desc: "粘贴",
|
||||
// code: "KeyV",
|
||||
// keyDesc: "Ctrl + V",
|
||||
// metaKey: true,
|
||||
// action(e, terminal) {
|
||||
// terminal.focusInput();
|
||||
// },
|
||||
// },
|
||||
{
|
||||
desc: "终止命令",
|
||||
code: "KeyC",
|
||||
keyDesc: "Ctrl + C",
|
||||
ctrlKey: true,
|
||||
action(e, terminal) {
|
||||
terminal.terminateCurrentCommand();
|
||||
}
|
||||
},
|
||||
{
|
||||
code: "Tab",
|
||||
action(e, terminal) {
|
||||
e.preventDefault();
|
||||
if (terminal.isInputFocused()) {
|
||||
terminal.setTabCompletion();
|
||||
} else {
|
||||
terminal.focusInput();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
code: "Backspace",
|
||||
action(e, terminal) {
|
||||
terminal.focusInput();
|
||||
},
|
||||
},
|
||||
{
|
||||
code: "Enter",
|
||||
action(e, terminal) {
|
||||
terminal.focusInput();
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "查看上一条命令",
|
||||
code: "ArrowUp",
|
||||
keyDesc: "↑",
|
||||
action(e, terminal) {
|
||||
e.preventDefault();
|
||||
if (!terminal.isRunning) {
|
||||
terminal.showPrevCommand();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
desc: "查看下一条命令",
|
||||
code: "ArrowDown",
|
||||
keyDesc: "↓",
|
||||
action(e, terminal) {
|
||||
e.preventDefault();
|
||||
if (!terminal.isRunning) {
|
||||
terminal.showNextCommand();
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
@ -1,6 +0,0 @@
|
||||
import { RouteRecordRaw } from "vue-router";
|
||||
import IndexPage from "../pages/IndexPage.vue";
|
||||
|
||||
const route: RouteRecordRaw[] = [{ path: "/", component: IndexPage }];
|
||||
|
||||
export default route;
|
||||
@ -1,48 +0,0 @@
|
||||
import { ParsedOptions } from "getopts";
|
||||
import TerminalType = GptTerminal.TerminalType;
|
||||
|
||||
// 命令类型
|
||||
interface CommandType {
|
||||
func: string; // 唯一命令英文
|
||||
name: string; // 命令名称
|
||||
desc?: string; // 命令描述
|
||||
alias?: string[]; // 命令别名
|
||||
params?: CommandParamsType[]; // 参数配置
|
||||
options: CommandOptionType[]; // 选项配置
|
||||
subCommands?: Record<string, CommandType>; // 子命令
|
||||
// 执行功能
|
||||
action: (
|
||||
options: ParsedOptions,
|
||||
terminal: TerminalType,
|
||||
parentCommand?: CommandType
|
||||
) => void;
|
||||
// 执行子功能
|
||||
subAction?: (
|
||||
options?: ParsedOptions,
|
||||
terminal: TerminalType,
|
||||
params?: Record<string, T>,
|
||||
parentCommand?: CommandType,
|
||||
) => void;
|
||||
// 结果是否允许折叠
|
||||
collapsible?: boolean;
|
||||
// 是否需要用户登录下才可访问
|
||||
requireAuth?: boolean | false;
|
||||
}
|
||||
|
||||
// 命令参数类型
|
||||
interface CommandParamsType {
|
||||
key: string; // 参数名
|
||||
desc?: string; // 参数描述
|
||||
defaultValue?: string | boolean; // 默认值
|
||||
required?: boolean; // 是否必填
|
||||
}
|
||||
|
||||
// 命令选项类型
|
||||
interface CommandOptionType {
|
||||
key: string; // 参数名
|
||||
alias?: string[]; // 别名
|
||||
desc?: string; // 描述
|
||||
type: "string" | "boolean";
|
||||
defaultValue?: string | boolean; // 默认值
|
||||
required?: boolean; // 是否必填
|
||||
}
|
||||
@ -1,21 +0,0 @@
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
interface ConfigType {
|
||||
model: string;
|
||||
}
|
||||
|
||||
export const useConfigStore = defineStore("config", {
|
||||
state: () => ({
|
||||
config: {} as ConfigType,
|
||||
}),
|
||||
getters: {},
|
||||
persist: {
|
||||
key: "gpt-config",
|
||||
storage: window.localStorage,
|
||||
},
|
||||
actions: {
|
||||
changeModel(model: string) {
|
||||
this.config.model = model;
|
||||
},
|
||||
},
|
||||
});
|
||||
@ -1,41 +0,0 @@
|
||||
import { CommandType } from "../../command";
|
||||
import chatCommand from "./subCommands/chat/chatCommand";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
import roleCommand from "./subCommands/role/roleCommand";
|
||||
import historyCommand from "./subCommands/history/historyCommand";
|
||||
import diyCommand from "./subCommands/diy/diyCommand";
|
||||
import imageCommand from "./subCommands/image/imageCommand";
|
||||
import modelCommand from "./subCommands/model/modelCommand";
|
||||
|
||||
/**
|
||||
* gpt命令
|
||||
*/
|
||||
const gptCommand: CommandType = {
|
||||
func: "gpt",
|
||||
name: "gpt 机器人",
|
||||
alias: [],
|
||||
subCommands: {
|
||||
chat: chatCommand,
|
||||
role: roleCommand,
|
||||
history: historyCommand,
|
||||
diy: diyCommand,
|
||||
// image: imageCommand,
|
||||
// model: modelCommand
|
||||
},
|
||||
options: [],
|
||||
async action(options, terminal) {
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(
|
||||
() => import("./subCommands/chat/ChatBox.vue")
|
||||
),
|
||||
props: {
|
||||
message: "您好,我是 「GPT Terminal」 机器人,请问我能为您做些什么呢?",
|
||||
},
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
},
|
||||
};
|
||||
|
||||
export default [gptCommand];
|
||||
@ -1,59 +0,0 @@
|
||||
import { defineStore } from "pinia";
|
||||
|
||||
export const useMessagesStore = defineStore("messages", {
|
||||
state: () => ({
|
||||
messages: [
|
||||
{
|
||||
roleKeyword: "default",
|
||||
roleName: "ChatGPT",
|
||||
roleDesc: "默认角色",
|
||||
systemMessage: "",
|
||||
parentMessageId: "",
|
||||
messageElements: [],
|
||||
},
|
||||
] as Gpt.MessageType[],
|
||||
}),
|
||||
getters: {},
|
||||
persist: {
|
||||
key: "gpt-messages",
|
||||
storage: window.localStorage,
|
||||
},
|
||||
actions: {
|
||||
addRole(
|
||||
roleKeyword: string,
|
||||
roleName: string,
|
||||
roleDesc: string,
|
||||
systemMessage: string
|
||||
) {
|
||||
const { messages } = this.$state;
|
||||
messages.push({
|
||||
roleKeyword,
|
||||
roleName,
|
||||
roleDesc,
|
||||
systemMessage,
|
||||
parentMessageId: "",
|
||||
messageElements: [],
|
||||
});
|
||||
},
|
||||
addMessage(
|
||||
msg: Gpt.MessageElement,
|
||||
roleKeyword: string | "default",
|
||||
parentMessageId: string
|
||||
) {
|
||||
const { messages } = this.$state;
|
||||
messages.forEach((m) => {
|
||||
if (m.roleKeyword == roleKeyword) {
|
||||
// 表示已找到
|
||||
m.parentMessageId = parentMessageId;
|
||||
if (m.messageElements.length >= 20) {
|
||||
m.messageElements.shift();
|
||||
}
|
||||
m.messageElements.push(msg);
|
||||
}
|
||||
});
|
||||
},
|
||||
clearMessages() {
|
||||
this.$state.messages = [];
|
||||
},
|
||||
},
|
||||
});
|
||||
@ -1,207 +0,0 @@
|
||||
<template>
|
||||
<div v-html="result" class="chat-box"></div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, toRefs, ref, defineEmits, Ref } from "vue";
|
||||
import { marked } from 'marked'
|
||||
import hljs from "highlight.js";
|
||||
import { useMessagesStore } from "../../messagesStore"
|
||||
import { useConfigStore } from "../../configStore"
|
||||
import { storeToRefs } from "pinia";
|
||||
import { fetchChatAPIProcess } from './chatApi'
|
||||
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer,
|
||||
gfm: true,
|
||||
async: false,
|
||||
highlight(code: string): string {
|
||||
return hljs.highlightAuto(code).value
|
||||
},
|
||||
})
|
||||
|
||||
interface ChatBoxProps {
|
||||
message: string;
|
||||
role: string;
|
||||
temperature: number;
|
||||
}
|
||||
|
||||
interface MessageElement {
|
||||
role: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface MessageType {
|
||||
roleKeyword: string | "default";
|
||||
roleName: string;
|
||||
roleDesc: string;
|
||||
systemMessage: string;
|
||||
parentMessageId: string;
|
||||
messageElements: MessageElement[];
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<ChatBoxProps>(), {});
|
||||
const { message, role, temperature } = toRefs(props);
|
||||
|
||||
// 历史消息
|
||||
const messagesStore = useMessagesStore();
|
||||
const { messages } = storeToRefs(messagesStore);
|
||||
|
||||
// GPT 配置
|
||||
const configStore = useConfigStore();
|
||||
const { config } = storeToRefs(configStore);
|
||||
|
||||
const output = ref("正在加载内容中...")
|
||||
|
||||
const result = computed(() => {
|
||||
console.log("output -", output.value)
|
||||
console.log("marked output -", marked(output.value))
|
||||
return marked(output.value)
|
||||
})
|
||||
|
||||
const emit = defineEmits(['start', 'finish']);
|
||||
|
||||
const flag = ref(false)
|
||||
|
||||
interface ConversationResponse {
|
||||
conversationId: string
|
||||
detail: {
|
||||
choices: { finish_reason: string; index: number; logprobs: any; text: string }[]
|
||||
created: number
|
||||
id: string
|
||||
model: string
|
||||
object: string
|
||||
usage: { completion_tokens: number; prompt_tokens: number; total_tokens: number }
|
||||
}
|
||||
id: string
|
||||
parentMessageId: string
|
||||
role: string
|
||||
text: string
|
||||
}
|
||||
|
||||
let controller = new AbortController()
|
||||
|
||||
const getGptOutput = async (flag: Ref<Boolean>, messageParams: MessageType, loadingInterval: any) => {
|
||||
let options = { parentMessageId: messageParams.parentMessageId }
|
||||
let parentMessageId = ''
|
||||
await fetchChatAPIProcess<ConversationResponse>({
|
||||
prompt: message.value,
|
||||
signal: controller.signal,
|
||||
options,
|
||||
systemMessage: messageParams.systemMessage,
|
||||
temperature: temperature.value,
|
||||
onDownloadProgress: ({ event }) => {
|
||||
clearInterval(loadingInterval)
|
||||
const xhr = event.target
|
||||
const { responseText } = xhr
|
||||
const lastIndex = responseText.lastIndexOf('\n', responseText.length - 2)
|
||||
let chunk = responseText
|
||||
if (lastIndex !== -1) {
|
||||
chunk = responseText.substring(lastIndex)
|
||||
}
|
||||
try {
|
||||
const data = JSON.parse(chunk)
|
||||
output.value = (data.text ?? '')
|
||||
parentMessageId = data.parentMessageId
|
||||
} catch (error) {
|
||||
//
|
||||
}
|
||||
}
|
||||
}).catch((error) => {
|
||||
output.value = (error.message)
|
||||
})
|
||||
|
||||
|
||||
messagesStore.addMessage(
|
||||
{ role: 'user', content: message.value },
|
||||
messageParams.roleKeyword,
|
||||
parentMessageId
|
||||
)
|
||||
messagesStore.addMessage(
|
||||
{ role: 'assistant', content: output.value },
|
||||
messageParams.roleKeyword,
|
||||
parentMessageId
|
||||
)
|
||||
|
||||
// 关闭延时器
|
||||
flag.value = true
|
||||
emit('finish')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
console.log("message -", message)
|
||||
console.log("role -", role)
|
||||
|
||||
// 定时器 loading 效果
|
||||
let count = 0;
|
||||
let loadingInterval = setInterval(() => {
|
||||
count++;
|
||||
if (count > 3) {
|
||||
count = 0;
|
||||
}
|
||||
switch (count) {
|
||||
case 0:
|
||||
output.value = "正在加载内容中";
|
||||
break;
|
||||
case 1:
|
||||
output.value = "正在加载内容中.";
|
||||
break;
|
||||
case 2:
|
||||
output.value = "正在加载内容中..";
|
||||
break;
|
||||
case 3:
|
||||
output.value = "正在加载内容中...";
|
||||
break;
|
||||
}
|
||||
}, 500)
|
||||
|
||||
|
||||
emit('start')
|
||||
|
||||
// 延时器
|
||||
let timeoutTimer = setTimeout(() => {
|
||||
clearInterval(loadingInterval)
|
||||
clearTimeout(timeoutTimer)
|
||||
if (!flag.value) {
|
||||
emit('finish')
|
||||
output.value = "请求超时,请检查您的网络环境是否配置正确 或 后端是否启动~"
|
||||
}
|
||||
}, 35000)
|
||||
|
||||
let messageType: MessageType = {
|
||||
roleKeyword: '',
|
||||
roleName: '',
|
||||
roleDesc: '',
|
||||
systemMessage: '',
|
||||
parentMessageId: '',
|
||||
messageElements: [],
|
||||
}
|
||||
let hasRole = false
|
||||
messages.value.forEach(m => {
|
||||
if (m.roleKeyword == role.value) {
|
||||
messageType = m
|
||||
hasRole = true
|
||||
return
|
||||
}
|
||||
})
|
||||
|
||||
// 存在角色 直接发送请求
|
||||
if (hasRole) {
|
||||
// 角色对应的历史聊天记录
|
||||
await getGptOutput(flag, messageType, loadingInterval)
|
||||
} else {
|
||||
output.value = "该角色不存在~"
|
||||
flag.value = true
|
||||
clearInterval(loadingInterval)
|
||||
emit('finish')
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chat-box {
|
||||
background-color: #292421;
|
||||
margin: 10px 0 10px 0;
|
||||
padding: 20px 20px 5px 20px;
|
||||
}
|
||||
</style>
|
||||
@ -1,31 +0,0 @@
|
||||
import type { AxiosProgressEvent, GenericAbortSignal } from "axios";
|
||||
import { post } from "../../../../../utils/request";
|
||||
import myAxios from "../../../../../plugins/myAxios";
|
||||
|
||||
export const getRoleElementsByKeyword = async (keyword: string) => {
|
||||
return myAxios.post("/role/getRoleElementsByKeyword", {
|
||||
keyword,
|
||||
});
|
||||
};
|
||||
|
||||
export function fetchChatAPIProcess<T = any>(params: {
|
||||
prompt: string;
|
||||
options?: { conversationId?: string; parentMessageId?: string };
|
||||
signal?: GenericAbortSignal;
|
||||
systemMessage?: string;
|
||||
temperature?: number;
|
||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void;
|
||||
}) {
|
||||
let data: Record<string, any> = {
|
||||
prompt: params.prompt,
|
||||
options: params.options,
|
||||
systemMessage: params.systemMessage,
|
||||
temperature: params.temperature
|
||||
};
|
||||
return post<T>({
|
||||
url: "/chat-process",
|
||||
data,
|
||||
signal: params.signal,
|
||||
onDownloadProgress: params.onDownloadProgress,
|
||||
});
|
||||
}
|
||||
@ -1,61 +0,0 @@
|
||||
import { CommandType } from "../../../../command";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
|
||||
const diyCommand: CommandType = {
|
||||
func: "diy",
|
||||
name: "自定义 GPT 角色",
|
||||
params: [],
|
||||
requireAuth: true,
|
||||
options: [
|
||||
{
|
||||
key: "keyword",
|
||||
desc: "GPT 角色唯一标识",
|
||||
alias: ["k"],
|
||||
type: "string",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: "name",
|
||||
desc: "GPT 角色名",
|
||||
alias: ["n"],
|
||||
type: "string",
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
key: "desc",
|
||||
desc: "GPT 角色描述",
|
||||
alias: ["d"],
|
||||
type: "string",
|
||||
required: true,
|
||||
},
|
||||
],
|
||||
async action(options, terminal) {
|
||||
const { keyword, name, desc } = options;
|
||||
// TODO:用户自定义角色后,需要包含进来
|
||||
if (!keyword) {
|
||||
terminal.writeTextErrorResult("角色唯一标识必填");
|
||||
return;
|
||||
}
|
||||
if (!name) {
|
||||
terminal.writeTextErrorResult("角色名称必填");
|
||||
return;
|
||||
}
|
||||
if (!desc) {
|
||||
terminal.writeTextErrorResult("角色描述必填");
|
||||
return;
|
||||
}
|
||||
const diyBox: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./DiyBox.vue")),
|
||||
props: {
|
||||
keyword: keyword,
|
||||
name: name,
|
||||
description: desc,
|
||||
},
|
||||
};
|
||||
terminal.writeResult(diyBox);
|
||||
},
|
||||
};
|
||||
|
||||
export default diyCommand;
|
||||
@ -1,46 +0,0 @@
|
||||
<template>
|
||||
<div>🙋 {{ gptCommand }}</div>
|
||||
<div v-html="result" class="chat-box"></div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, toRefs } from "vue";
|
||||
import { marked } from 'marked'
|
||||
import hljs from "highlight.js";
|
||||
|
||||
marked.setOptions({
|
||||
renderer: new marked.Renderer,
|
||||
gfm: true,
|
||||
async: false,
|
||||
highlight(code: string): string {
|
||||
return hljs.highlightAuto(code).value
|
||||
},
|
||||
})
|
||||
|
||||
interface RecordProps {
|
||||
gptCommand: string;
|
||||
gptOutput: string;
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<RecordProps>(), {});
|
||||
const { gptCommand, gptOutput } = toRefs(props);
|
||||
|
||||
|
||||
const result = computed(() => {
|
||||
console.log("gptCommand -", gptOutput)
|
||||
console.log("gptOutput -", marked(gptOutput.value))
|
||||
return marked(gptOutput.value)
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chat-box {
|
||||
background-color: #292421;
|
||||
margin: 10px 0 10px 0;
|
||||
padding: 20px 20px 5px 20px;
|
||||
}
|
||||
</style>
|
||||
@ -1,78 +0,0 @@
|
||||
<template>
|
||||
<div class="image-box">
|
||||
<span v-if="flag">{{ loading }}</span>
|
||||
<div v-else>
|
||||
<a-row :gutter="[0, 40]">
|
||||
<a-col :span="4" v-for="(item, index) in imageUrlList" :key="index">
|
||||
<a-image :src="item.url" />
|
||||
</a-col>
|
||||
</a-row>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, toRefs, ref, defineEmits, Ref } from "vue";
|
||||
import { getImage } from "./imageApi";
|
||||
|
||||
interface ImageBoxProps {
|
||||
prompt: string;
|
||||
number: number;
|
||||
size: string
|
||||
}
|
||||
|
||||
const props = withDefaults(defineProps<ImageBoxProps>(), {});
|
||||
const { prompt, number, size } = toRefs(props);
|
||||
|
||||
const flag = ref(true)
|
||||
const emit = defineEmits(['start', 'finish']);
|
||||
const loading = ref("图片内容较大,正在加载中...")
|
||||
|
||||
const imageUrlList = ref<any>([])
|
||||
|
||||
onMounted(async () => {
|
||||
// 定时器 loading 效果
|
||||
let count = 0
|
||||
let loadingInterval = setInterval(() => {
|
||||
if (count > 3) {
|
||||
count = 0;
|
||||
}
|
||||
switch (count) {
|
||||
case 0:
|
||||
loading.value = "图片内容较大,正在加载中";
|
||||
break;
|
||||
case 1:
|
||||
loading.value = "图片内容较大,正在加载中.";
|
||||
break;
|
||||
case 2:
|
||||
loading.value = "图片内容较大,正在加载中..";
|
||||
break;
|
||||
case 3:
|
||||
loading.value = "图片内容较大,正在加载中...";
|
||||
break;
|
||||
}
|
||||
count++;
|
||||
}, 500)
|
||||
emit('start')
|
||||
const res: any = await getImage(prompt.value, number.value, size.value)
|
||||
if (res?.code !== 0) {
|
||||
loading.value = res?.msg ? res.msg : "服务端请求异常"
|
||||
emit('finish')
|
||||
clearInterval(loadingInterval)
|
||||
return;
|
||||
}
|
||||
flag.value = false
|
||||
clearInterval(loadingInterval)
|
||||
loading.value = ''
|
||||
imageUrlList.value = res.data
|
||||
emit('finish')
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.image-box {
|
||||
background-color: #292421;
|
||||
margin: 10px 0 10px 0;
|
||||
padding: 20px 20px 20px 20px;
|
||||
}
|
||||
</style>
|
||||
@ -1,13 +0,0 @@
|
||||
import myAxios from "../../../../../plugins/myAxios";
|
||||
|
||||
export const getImage = async (
|
||||
prompt: string,
|
||||
number: number,
|
||||
size: string
|
||||
) => {
|
||||
return await myAxios.post("/gpt/getImage", {
|
||||
prompt,
|
||||
number,
|
||||
size,
|
||||
});
|
||||
};
|
||||
@ -1,73 +0,0 @@
|
||||
<template>
|
||||
<div v-if="!isSet" @keydown="handleKeyDown" class="select-box">
|
||||
<div>Current Model: <span style="color: #dae52e">{{ config.model }}</span></div>
|
||||
<div v-for="(item, index) in models" :key="index">
|
||||
<span v-if="current == index" style="color: dodgerblue;">> </span>
|
||||
<span v-else> </span>
|
||||
<span :style="current == index ? { color: 'dodgerblue' } : {}">{{ item.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else>✅ Set GPT Model successfully!</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref, onUnmounted } from 'vue'
|
||||
import { modelList, Model } from './models'
|
||||
import { useConfigStore } from "../../configStore"
|
||||
import { storeToRefs } from "pinia";
|
||||
|
||||
const emit = defineEmits(['start', 'finish']);
|
||||
|
||||
const isSet = ref<boolean>(false)
|
||||
|
||||
const models = ref<Model[]>(modelList)
|
||||
|
||||
const current = ref<number>(0)
|
||||
|
||||
const configStore = useConfigStore();
|
||||
const { config } = storeToRefs(configStore);
|
||||
|
||||
const handleKeyDown = (e: any) => {
|
||||
if (e.key == 'ArrowUp' || e.key == 'ArrowDown') {
|
||||
handleCurrent(e.key)
|
||||
} else if (e.key == 'Enter') {
|
||||
handleSubmit()
|
||||
}
|
||||
}
|
||||
|
||||
const handleSubmit = () => {
|
||||
console.log('current', current.value)
|
||||
configStore.changeModel(models.value[current.value].name)
|
||||
isSet.value = true
|
||||
emit('finish')
|
||||
window.removeEventListener('keydown', handleKeyDown)
|
||||
}
|
||||
|
||||
const handleCurrent = (key: string) => {
|
||||
if (key == 'ArrowUp') {
|
||||
if (current.value == 0) {
|
||||
current.value = models.value.length - 1
|
||||
} else {
|
||||
current.value -= 1
|
||||
}
|
||||
} else if (key == 'ArrowDown') {
|
||||
if (current.value == models.value.length - 1) {
|
||||
current.value = 0
|
||||
} else {
|
||||
current.value += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
emit('start')
|
||||
window.addEventListener('keydown', handleKeyDown)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.select-box {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
</style>
|
||||
@ -1,20 +0,0 @@
|
||||
import { CommandType } from "../../../../command";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
|
||||
const modelCommand: CommandType = {
|
||||
func: "model",
|
||||
name: "选择并设置 GPT 模型",
|
||||
params: [],
|
||||
options: [],
|
||||
async action(options, terminal) {
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./ModelSelectBox.vue")),
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
export default modelCommand;
|
||||
@ -1,35 +0,0 @@
|
||||
export interface Model {
|
||||
key: string;
|
||||
name: string;
|
||||
}
|
||||
|
||||
export const modelList: Model[] = [
|
||||
{
|
||||
key: "gpt-3.5-turbo",
|
||||
name: "gpt-3.5-turbo",
|
||||
},
|
||||
{
|
||||
key: "gpt-3.5-turbo-16k",
|
||||
name: "gpt-3.5-turbo-16k",
|
||||
},
|
||||
{
|
||||
key: "gpt-3.5-turbo-0613",
|
||||
name: "gpt-3.5-turbo-0613",
|
||||
},
|
||||
{
|
||||
key: "gpt-3.5-turbo-16k-0613",
|
||||
name: "gpt-3.5-turbo-16k-0613",
|
||||
},
|
||||
{
|
||||
key: "gpt-4-0613",
|
||||
name: "gpt-4-0613",
|
||||
},
|
||||
{
|
||||
key: "gpt-4-32k",
|
||||
name: "gpt-4-32k",
|
||||
},
|
||||
{
|
||||
key: "gpt-4-32k-0613",
|
||||
name: "gpt-4-32k-0613",
|
||||
}
|
||||
]
|
||||
@ -1,108 +0,0 @@
|
||||
<template>
|
||||
<!-- <div v-for="role in roles" :key="role.keyword">
|
||||
{{ role.keyword }} - {{ role.name }} - {{ role.desc }}
|
||||
</div> -->
|
||||
<div style="padding: 15px;">
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>keyword</th>
|
||||
<th>名称</th>
|
||||
<th>简介</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="role in roles" :key="role.keyword">
|
||||
<td>{{ role.keyword }}</td>
|
||||
<td>{{ role.name }}</td>
|
||||
<td>{{ role.desc }}</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useMessagesStore } from "../../messagesStore"
|
||||
|
||||
const messagesStore = useMessagesStore();
|
||||
const { messages } = storeToRefs(messagesStore);
|
||||
|
||||
interface Role {
|
||||
keyword?: string
|
||||
name: string
|
||||
desc: string
|
||||
}
|
||||
|
||||
interface Columns {
|
||||
title: string
|
||||
dataIndex: string
|
||||
key: string
|
||||
}
|
||||
|
||||
const roles = ref<Role[]>([])
|
||||
const columns = ref<Columns[]>([])
|
||||
|
||||
columns.value = [
|
||||
{
|
||||
title: 'keyword',
|
||||
dataIndex: 'keyword',
|
||||
key: 'keyword',
|
||||
},
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
},
|
||||
{
|
||||
title: '简介',
|
||||
dataIndex: 'desc',
|
||||
key: 'desc',
|
||||
},
|
||||
],
|
||||
|
||||
onMounted(async () => {
|
||||
messages.value.forEach((m) => {
|
||||
roles.value.push({
|
||||
keyword: m.roleKeyword,
|
||||
name: m.roleName,
|
||||
desc: m.roleDesc
|
||||
})
|
||||
})
|
||||
});
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.chat-box {
|
||||
background-color: #292421;
|
||||
margin: 10px 0 10px 0;
|
||||
padding: 20px 20px 5px 20px;
|
||||
}
|
||||
|
||||
table,
|
||||
th,
|
||||
td {
|
||||
border: 1px solid black;
|
||||
}
|
||||
|
||||
tr {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
th {
|
||||
height: 10px;
|
||||
}
|
||||
|
||||
td {
|
||||
text-align: left;
|
||||
height: 10px;
|
||||
vertical-align: bottom;
|
||||
}
|
||||
</style>
|
||||
@ -1,20 +0,0 @@
|
||||
import { CommandType } from "../../../../command";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
|
||||
const roleCommand: CommandType = {
|
||||
func: "role",
|
||||
name: "查看所有 GPT 角色",
|
||||
params: [],
|
||||
options: [],
|
||||
async action(options, terminal) {
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./RoleBox.vue")),
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
return;
|
||||
},
|
||||
};
|
||||
|
||||
export default roleCommand;
|
||||
@ -1,42 +0,0 @@
|
||||
interface Role {
|
||||
name: string;
|
||||
desc: string;
|
||||
}
|
||||
|
||||
export const roleMap: Map<string, Role> = new Map([
|
||||
[
|
||||
"default",
|
||||
{
|
||||
name: "默认角色",
|
||||
desc: "无任何定制的普通 GPT 聊天机器人",
|
||||
},
|
||||
],
|
||||
[
|
||||
"cli",
|
||||
{
|
||||
name: "命令行翻译角色",
|
||||
desc: "将你的自然语言指令翻译为 Window/Unix 终端命令",
|
||||
},
|
||||
],
|
||||
[
|
||||
"translator",
|
||||
{
|
||||
name: "中英文互译角色",
|
||||
desc: "将你所发的内容进行中英文互译",
|
||||
},
|
||||
],
|
||||
[
|
||||
"sql",
|
||||
{
|
||||
name: "SQL 翻译角色",
|
||||
desc: "将你的自然语言指令翻译为 SQL 代码",
|
||||
},
|
||||
],
|
||||
[
|
||||
"ikun",
|
||||
{
|
||||
name: "忠实的 IKun",
|
||||
desc: "小黑子~"
|
||||
}
|
||||
]
|
||||
]);
|
||||
@ -1,15 +0,0 @@
|
||||
declare namespace Gpt {
|
||||
interface MessageElement {
|
||||
role: string;
|
||||
content: string;
|
||||
}
|
||||
|
||||
interface MessageType {
|
||||
roleKeyword: string | "default";
|
||||
roleName: string;
|
||||
roleDesc: string;
|
||||
systemMessage: string;
|
||||
parentMessageId: string;
|
||||
messageElements: MessageElement[];
|
||||
}
|
||||
}
|
||||
@ -1,15 +0,0 @@
|
||||
import { CommandType } from "../../command";
|
||||
|
||||
const clearCommand: CommandType = {
|
||||
func: "clear",
|
||||
name: "清屏",
|
||||
alias: ["cl"],
|
||||
options: [],
|
||||
action(options, termial): void {
|
||||
setTimeout(() => {
|
||||
termial.clear();
|
||||
}, 100);
|
||||
},
|
||||
};
|
||||
|
||||
export default clearCommand;
|
||||
@ -1,58 +0,0 @@
|
||||
import { CommandType } from "../../../command";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import { commandMap } from "../../../commandRegister";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
|
||||
/**
|
||||
* 帮助命令
|
||||
* @author yupi
|
||||
*/
|
||||
const helpCommand: CommandType = {
|
||||
func: "help",
|
||||
name: "查看帮助",
|
||||
alias: ["man"],
|
||||
params: [
|
||||
{
|
||||
key: "commandName",
|
||||
desc: "命令英文名称",
|
||||
},
|
||||
],
|
||||
options: [],
|
||||
collapsible: true,
|
||||
action(options, terminal, parentCommand): void {
|
||||
const { _ } = options;
|
||||
if (_.length < 1) {
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./HelpBox.vue")),
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
return;
|
||||
}
|
||||
const commandName = _[0];
|
||||
let commands = commandMap;
|
||||
if (
|
||||
parentCommand &&
|
||||
parentCommand.subCommands &&
|
||||
Object.keys(parentCommand.subCommands).length > 0
|
||||
) {
|
||||
commands = parentCommand.subCommands;
|
||||
}
|
||||
const command = commands[commandName];
|
||||
if (!command) {
|
||||
terminal.writeTextErrorResult("找不到指定命令");
|
||||
return;
|
||||
}
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./CommandHelpBox.vue")),
|
||||
props: {
|
||||
command,
|
||||
parentCommand,
|
||||
},
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
},
|
||||
};
|
||||
|
||||
export default helpCommand;
|
||||
@ -1,83 +0,0 @@
|
||||
import { CommandOptionType, CommandType } from "../../../command";
|
||||
|
||||
export const getUsageStr = (
|
||||
command: CommandType,
|
||||
parentCommand?: CommandType
|
||||
) => {
|
||||
if (!command) {
|
||||
return "";
|
||||
}
|
||||
let str = "";
|
||||
if (parentCommand) {
|
||||
str = parentCommand.func + " ";
|
||||
}
|
||||
str += command.func;
|
||||
if (command.params && command.params.length > 0) {
|
||||
const paramsStrList: string[] = command.params.map((param) => {
|
||||
let word = param.key;
|
||||
if (param.desc) {
|
||||
word = param.desc;
|
||||
}
|
||||
if (param.required) {
|
||||
return `<${word}>`;
|
||||
} else {
|
||||
return `[${word}]`;
|
||||
}
|
||||
});
|
||||
str += " " + paramsStrList.join(" ");
|
||||
}
|
||||
if (command.options?.length > 0) {
|
||||
const optionStrList: string[] = command.options.map((option) => {
|
||||
const optionKey = getOptionKey(option);
|
||||
if (option.type === "boolean") {
|
||||
let word = optionKey;
|
||||
if (option.desc) {
|
||||
word += ` ${option.desc}`;
|
||||
}
|
||||
if (option.required) {
|
||||
return `<${word}>`;
|
||||
} else {
|
||||
return `[${word}]`;
|
||||
}
|
||||
} else {
|
||||
let word = option.key;
|
||||
if (option.desc) {
|
||||
word = option.desc;
|
||||
}
|
||||
if (option.required) {
|
||||
return `<${optionKey} ${word}>`;
|
||||
} else {
|
||||
return `[${optionKey} ${word}]`;
|
||||
}
|
||||
}
|
||||
});
|
||||
str += " " + optionStrList.join(" ");
|
||||
}
|
||||
return str;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取选项关键词
|
||||
* @param option
|
||||
*/
|
||||
export const getOptionKey = (option: CommandOptionType) => {
|
||||
// 优先用简写
|
||||
if (option.alias && option.alias.length > 0) {
|
||||
return "-" + option.alias[0];
|
||||
}
|
||||
return "--" + option.key;
|
||||
};
|
||||
|
||||
/**
|
||||
* 获取选项关键词列表
|
||||
* @param option
|
||||
*/
|
||||
export const getOptionKeyList = (option: CommandOptionType) => {
|
||||
const list = [];
|
||||
// 优先用简写
|
||||
if (option.alias && option.alias.length > 0) {
|
||||
list.push("-" + option.alias[0]);
|
||||
}
|
||||
list.push("--" + option.key);
|
||||
return list;
|
||||
};
|
||||
@ -1,17 +0,0 @@
|
||||
import { CommandType } from "../../command";
|
||||
|
||||
const historyCommand: CommandType = {
|
||||
func: "history",
|
||||
name: "查看执行历史",
|
||||
alias: ["h"],
|
||||
options: [],
|
||||
collapsible: true,
|
||||
action(options, terminal): void {
|
||||
const commandOutputTypes = terminal.listCommandHistory();
|
||||
commandOutputTypes.forEach((command, index) => {
|
||||
terminal.writeTextResult(`${index + 1} ${command.text}`);
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default historyCommand;
|
||||
@ -1,26 +0,0 @@
|
||||
import { CommandType } from "../../../command";
|
||||
import { defineAsyncComponent } from "vue";
|
||||
import ComponentOutputType = GptTerminal.ComponentOutputType;
|
||||
|
||||
/**
|
||||
* 快捷键命令
|
||||
* @author yupi
|
||||
*/
|
||||
const shortcutCommand: CommandType = {
|
||||
func: "shortcut",
|
||||
name: "快捷键",
|
||||
desc: "查看快捷键",
|
||||
alias: [],
|
||||
params: [],
|
||||
options: [],
|
||||
collapsible: true,
|
||||
action(options, terminal): void {
|
||||
const output: ComponentOutputType = {
|
||||
type: "component",
|
||||
component: defineAsyncComponent(() => import("./ShortcutBox.vue")),
|
||||
};
|
||||
terminal.writeResult(output);
|
||||
},
|
||||
};
|
||||
|
||||
export default shortcutCommand;
|
||||
@ -1,8 +0,0 @@
|
||||
/// <reference types="vite/client" />
|
||||
|
||||
declare module '*.vue' {
|
||||
import type { DefineComponent } from 'vue'
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/ban-types
|
||||
const component: DefineComponent<{}, {}, any>
|
||||
export default component
|
||||
}
|
||||
@ -1,23 +0,0 @@
|
||||
import { createApp } from "vue";
|
||||
import App from "./App.vue";
|
||||
import * as VueRouter from "vue-router";
|
||||
import routes from "./configs/routes";
|
||||
import { createPinia } from "pinia";
|
||||
import piniaPluginPersistedstate from "pinia-plugin-persistedstate";
|
||||
import 'highlight.js/styles/github.css'
|
||||
|
||||
const app = createApp(App);
|
||||
|
||||
// 路由
|
||||
const router = VueRouter.createRouter({
|
||||
history: VueRouter.createWebHashHistory(),
|
||||
routes,
|
||||
});
|
||||
app.use(router);
|
||||
|
||||
// 状态管理
|
||||
const pinia = createPinia();
|
||||
pinia.use(piniaPluginPersistedstate);
|
||||
app.use(pinia);
|
||||
|
||||
app.mount("#app");
|
||||
@ -1,33 +0,0 @@
|
||||
<template>
|
||||
<gpt-terminal ref="terminalRef" full-screen :on-submit-command="onSubmitCommand" />
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { doCommandExecute } from "../core/commandExecutor";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { storeToRefs } from "pinia";
|
||||
import { useConfigStore } from "../core/commands/gpt/configStore";
|
||||
|
||||
const terminalRef = ref();
|
||||
|
||||
const onSubmitCommand = async (inputText: string) => {
|
||||
if (!inputText) {
|
||||
return;
|
||||
}
|
||||
const terminal = terminalRef.value.terminal;
|
||||
await doCommandExecute(inputText, terminal);
|
||||
};
|
||||
|
||||
|
||||
|
||||
const configStore = useConfigStore();
|
||||
const { config } = storeToRefs(configStore);
|
||||
|
||||
onMounted(() => {
|
||||
if (!config.value.model) {
|
||||
configStore.changeModel("gpt-3.5-turbo");
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<style></style>
|
||||
@ -1,29 +0,0 @@
|
||||
import axios from "axios";
|
||||
|
||||
let serverAddress = import.meta.env.VITE_SERVER_ADDRESS
|
||||
|
||||
const myAxios = axios.create({
|
||||
baseURL: `http://${serverAddress}/api`,
|
||||
});
|
||||
|
||||
myAxios.defaults.withCredentials = true;
|
||||
|
||||
myAxios.interceptors.request.use(
|
||||
function (config) {
|
||||
return config;
|
||||
},
|
||||
function (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
myAxios.interceptors.response.use(
|
||||
function (response) {
|
||||
return response.data;
|
||||
},
|
||||
function (error) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
);
|
||||
|
||||
export default myAxios;
|
||||
@ -1,32 +0,0 @@
|
||||
import axios, { type AxiosResponse } from 'axios'
|
||||
// import { useAuthStore } from '@/store'
|
||||
|
||||
const service = axios.create({
|
||||
baseURL: "/api",
|
||||
})
|
||||
|
||||
service.interceptors.request.use(
|
||||
(config) => {
|
||||
// const token = useAuthStore().token
|
||||
// if (token)
|
||||
// config.headers.Authorization = `Bearer ${token}`
|
||||
return config;
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error.response)
|
||||
},
|
||||
)
|
||||
|
||||
service.interceptors.response.use(
|
||||
(response: AxiosResponse): AxiosResponse => {
|
||||
if (response.status === 200)
|
||||
return response
|
||||
|
||||
throw new Error(response.status.toString())
|
||||
},
|
||||
(error) => {
|
||||
return Promise.reject(error)
|
||||
},
|
||||
)
|
||||
|
||||
export default service
|
||||
@ -1,81 +0,0 @@
|
||||
import type { AxiosProgressEvent, AxiosResponse, GenericAbortSignal } from 'axios'
|
||||
import request from './axios'
|
||||
|
||||
export interface HttpOption {
|
||||
url: string
|
||||
data?: any
|
||||
method?: string
|
||||
headers?: any
|
||||
onDownloadProgress?: (progressEvent: AxiosProgressEvent) => void
|
||||
signal?: GenericAbortSignal
|
||||
beforeRequest?: () => void
|
||||
afterRequest?: () => void
|
||||
}
|
||||
|
||||
export interface Response<T = any> {
|
||||
data: T
|
||||
message: string | null
|
||||
status: string
|
||||
}
|
||||
|
||||
function http<T = any>(
|
||||
{ url, data, method, headers, onDownloadProgress, signal, beforeRequest, afterRequest }: HttpOption,
|
||||
) {
|
||||
const successHandler = (res: AxiosResponse<Response<T>>) => {
|
||||
|
||||
if (res.data.status === 'Success' || typeof res.data === 'string')
|
||||
return res.data
|
||||
|
||||
if (res.data.status === 'Unauthorized') {
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
return Promise.reject(res.data)
|
||||
}
|
||||
|
||||
const failHandler = (error: Response<Error>) => {
|
||||
afterRequest?.()
|
||||
throw new Error(error?.message || 'Error')
|
||||
}
|
||||
|
||||
beforeRequest?.()
|
||||
|
||||
method = method || 'GET'
|
||||
|
||||
const params = Object.assign(typeof data === 'function' ? data() : data ?? {}, {})
|
||||
|
||||
return method === 'GET'
|
||||
? request.get(url, { params, signal, onDownloadProgress }).then(successHandler, failHandler)
|
||||
: request.post(url, params, { headers, signal, onDownloadProgress }).then(successHandler, failHandler)
|
||||
}
|
||||
|
||||
export function get<T = any>(
|
||||
{ url, data, method = 'GET', onDownloadProgress, signal, beforeRequest, afterRequest }: HttpOption,
|
||||
): Promise<Response<T>> {
|
||||
return http<T>({
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
onDownloadProgress,
|
||||
signal,
|
||||
beforeRequest,
|
||||
afterRequest,
|
||||
})
|
||||
}
|
||||
|
||||
export function post<T = any>(
|
||||
{ url, data, method = 'POST', headers, onDownloadProgress, signal, beforeRequest, afterRequest }: HttpOption,
|
||||
): Promise<Response<T>> {
|
||||
return http<T>({
|
||||
url,
|
||||
method,
|
||||
data,
|
||||
headers,
|
||||
onDownloadProgress,
|
||||
signal,
|
||||
beforeRequest,
|
||||
afterRequest,
|
||||
})
|
||||
}
|
||||
|
||||
export default post
|
||||
@ -1,19 +0,0 @@
|
||||
/**
|
||||
* 匹配网址正则
|
||||
*/
|
||||
const URL_REG =
|
||||
/(((https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/;
|
||||
|
||||
/**
|
||||
* 识别文本中的超链接
|
||||
* @param text
|
||||
*/
|
||||
const smartText = (text?: string) => {
|
||||
if (!text) {
|
||||
return text;
|
||||
}
|
||||
const reg = new RegExp(URL_REG, "gi");
|
||||
return text.replaceAll(reg, "<a href='$1' target='_blank'>$1</a>");
|
||||
};
|
||||
|
||||
export default smartText;
|
||||
@ -1,18 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "esnext",
|
||||
"useDefineForClassFields": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"strict": true,
|
||||
"jsx": "preserve",
|
||||
"sourceMap": true,
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"esModuleInterop": true,
|
||||
"lib": ["esnext", "dom"],
|
||||
"skipLibCheck": true
|
||||
},
|
||||
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
|
||||
"references": [{ "path": "./tsconfig.node.json" }]
|
||||
}
|
||||
@ -1,8 +0,0 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"composite": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node"
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@ -1,9 +0,0 @@
|
||||
{
|
||||
"version": 2,
|
||||
"builds": [
|
||||
{
|
||||
"src": "package.json",
|
||||
"use": "@vercel/static-build"
|
||||
}
|
||||
]
|
||||
}
|
||||
@ -1,32 +0,0 @@
|
||||
import { defineConfig, loadEnv } from "vite";
|
||||
import vue from "@vitejs/plugin-vue";
|
||||
// @ts-ignore
|
||||
import Components from "unplugin-vue-components/vite";
|
||||
// @ts-ignore
|
||||
import { AntDesignVueResolver } from "unplugin-vue-components/resolvers";
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig((env) => {
|
||||
const viteEnv = loadEnv(env.mode, process.cwd())
|
||||
return {
|
||||
plugins: [
|
||||
vue(),
|
||||
// 按需加载 ant-design-vue
|
||||
Components({
|
||||
resolvers: [AntDesignVueResolver()],
|
||||
}),
|
||||
].filter(Boolean),
|
||||
server: {
|
||||
host: '0.0.0.0',
|
||||
port: 3001,
|
||||
open: false,
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: viteEnv.VITE_APP_API_BASE_URL,
|
||||
changeOrigin: true, // 允许跨域
|
||||
rewrite: path => path.replace('/api/', '/'),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
Loading…
Reference in new issue