From b5bef188761399ee465930cc2034c75a7a9cf6ab Mon Sep 17 00:00:00 2001 From: eryajf Date: Sun, 2 Jul 2023 22:18:18 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=A6=96=E6=AC=A1=E6=8F=90=E4=BA=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .github/ISSUE_TEMPLATE/question.md | 12 + .github/pull-request-template.md | 7 + .github/release-drafter.yml | 42 ++ .github/workflows/docker-image.yml | 80 +++ .github/workflows/go-binary-release.yml | 26 + .github/workflows/reademe-contributors.yml | 20 + .github/workflows/release.yml | 38 ++ .github/workflows/toc.yml | 11 + .gitignore | 25 + CONTRIBUTING.md | 24 + Dockerfile | 25 + LICENSE | 674 +++++++++++++++++++++ Makefile | 16 + README.md | 297 +++++++++ config.example.yml | 57 ++ config/config.go | 253 ++++++++ config/prompt.go | 30 + docker-compose.yml | 44 ++ docs/userGuide.md | 59 ++ go.mod | 71 +++ go.sum | 212 +++++++ main.go | 156 +++++ pkg/cache/user_base.go | 44 ++ pkg/cache/user_chatid.go | 22 + pkg/cache/user_context.go | 22 + pkg/cache/user_mode.go | 22 + pkg/cache/user_requese.go | 22 + pkg/chatgpt/LICENSE | 21 + pkg/chatgpt/README.md | 1 + pkg/chatgpt/chatgpt.go | 87 +++ pkg/chatgpt/chatgpt_test.go | 31 + pkg/chatgpt/context.go | 309 ++++++++++ pkg/chatgpt/context_test.go | 81 +++ pkg/chatgpt/errors.go | 12 + pkg/chatgpt/export.go | 81 +++ pkg/chatgpt/format.go | 12 + pkg/chatgpt/go.mod | 41 ++ pkg/chatgpt/go.sum | 73 +++ pkg/db/chat.go | 63 ++ pkg/db/sqlite.go | 47 ++ pkg/logger/logger.go | 42 ++ pkg/ops/opstools.go | 66 ++ pkg/process/process_request.go | 270 +++++++++ pkg/process/prompt.go | 27 + prompt.yml | 70 +++ public/balance.go | 110 ++++ public/chat.go | 20 + public/public.go | 26 + public/tools.go | 127 ++++ 49 files changed, 3928 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/question.md create mode 100644 .github/pull-request-template.md create mode 100644 .github/release-drafter.yml create mode 100644 .github/workflows/docker-image.yml create mode 100644 .github/workflows/go-binary-release.yml create mode 100644 .github/workflows/reademe-contributors.yml create mode 100644 .github/workflows/release.yml create mode 100644 .github/workflows/toc.yml create mode 100644 .gitignore create mode 100644 CONTRIBUTING.md create mode 100644 Dockerfile create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 config.example.yml create mode 100644 config/config.go create mode 100644 config/prompt.go create mode 100644 docker-compose.yml create mode 100644 docs/userGuide.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go create mode 100644 pkg/cache/user_base.go create mode 100644 pkg/cache/user_chatid.go create mode 100644 pkg/cache/user_context.go create mode 100644 pkg/cache/user_mode.go create mode 100644 pkg/cache/user_requese.go create mode 100644 pkg/chatgpt/LICENSE create mode 100644 pkg/chatgpt/README.md create mode 100644 pkg/chatgpt/chatgpt.go create mode 100644 pkg/chatgpt/chatgpt_test.go create mode 100644 pkg/chatgpt/context.go create mode 100644 pkg/chatgpt/context_test.go create mode 100644 pkg/chatgpt/errors.go create mode 100644 pkg/chatgpt/export.go create mode 100644 pkg/chatgpt/format.go create mode 100644 pkg/chatgpt/go.mod create mode 100644 pkg/chatgpt/go.sum create mode 100644 pkg/db/chat.go create mode 100644 pkg/db/sqlite.go create mode 100644 pkg/logger/logger.go create mode 100644 pkg/ops/opstools.go create mode 100644 pkg/process/process_request.go create mode 100644 pkg/process/prompt.go create mode 100644 prompt.yml create mode 100644 public/balance.go create mode 100644 public/chat.go create mode 100644 public/public.go create mode 100644 public/tools.go diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..c7ea774 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,12 @@ +--- +name: 🙋 问题交流 +about: 有任何问题,都可以在这里交流。 +title: "🙋 简明扼要起个标题" +labels: ["question"] +--- + +## 问题反馈 + +- 搜索打开和关闭的 [GitHub 问题](https://github.com/eryajf/chatgpt-wecom/issues),请勿重复提交issue。 + +**重要:提交问题时,请务必带上输出日志,以及个人排查的成果。** \ No newline at end of file diff --git a/.github/pull-request-template.md b/.github/pull-request-template.md new file mode 100644 index 0000000..7f39a68 --- /dev/null +++ b/.github/pull-request-template.md @@ -0,0 +1,7 @@ + +**在提出此拉取请求时,我确认了以下几点(请复选框):** + +- [ ] 我已阅读并理解[贡献者指南](https://github.com/eryajf/chatgpt-wecom/blob/main/CONTRIBUTING.md)。 +- [ ] 我已检查没有与此请求重复的拉取请求。 +- [ ] 我已经考虑过,并确认这份呈件对其他人很有价值。 +- [ ] 我接受此提交可能不会被使用,并根据维护人员的意愿关闭拉取请求。 \ No newline at end of file diff --git a/.github/release-drafter.yml b/.github/release-drafter.yml new file mode 100644 index 0000000..dd20abc --- /dev/null +++ b/.github/release-drafter.yml @@ -0,0 +1,42 @@ +# Configuration for Release Drafter: https://github.com/toolmantim/release-drafter +name-template: 'v$NEXT_PATCH_VERSION 🌈' +tag-template: 'v$NEXT_PATCH_VERSION' +version-template: $MAJOR.$MINOR.$PATCH +# Emoji reference: https://gitmoji.carloscuesta.me/ +categories: + - title: '🚀 Features' + labels: + - 'feature' + - 'enhancement' + - 'kind/feature' + - title: '🐛 Bug Fixes' + labels: + - 'fix' + - 'bugfix' + - 'bug' + - 'regression' + - 'kind/bug' + - title: 📝 Documentation updates + labels: + - 'doc' + - 'documentation' + - 'kind/doc' + - title: 👻 Maintenance + labels: + - chore + - dependencies + - 'kind/chore' + - 'kind/dep' + - title: 🚦 Tests + labels: + - test + - tests +exclude-labels: + - reverted + - no-changelog + - skip-changelog + - invalid +change-template: '* $TITLE (#$NUMBER) @$AUTHOR' +template: | + ## What’s Changed + $CHANGES \ No newline at end of file diff --git a/.github/workflows/docker-image.yml b/.github/workflows/docker-image.yml new file mode 100644 index 0000000..3c20a53 --- /dev/null +++ b/.github/workflows/docker-image.yml @@ -0,0 +1,80 @@ +# This is a basic workflow to help you get started with Actions + +name: build docker image + +# Controls when the action will run. +on: + push: + branches: + - main + release: + types: [created,published] # 表示在创建新的 Release 时触发 + +# Allows you to run this workflow manually from the Actions tab + # 可以手动触发 + workflow_dispatch: + inputs: + logLevel: + description: 'Log level' + required: true + default: 'warning' + tags: + description: 'Test scenario tags' + +jobs: + buildx: + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v2 + + - name: Inject slug/short variables + uses: rlespinasse/github-slug-action@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v1 + + - name: Set up Docker Buildx + id: buildx + uses: docker/setup-buildx-action@v1 + + - name: Available platforms + run: echo ${{ steps.buildx.outputs.platforms }} + + - name: Login to DockerHub + uses: docker/login-action@v1 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_TOKEN }} + + - name: Build and push to DockerHub + uses: docker/build-push-action@v2 + with: + context: . + file: ./Dockerfile + # 所需要的体系结构,可以在 Available platforms 步骤中获取所有的可用架构 + platforms: linux/amd64,linux/arm64/v8 + # 镜像推送时间 + push: ${{ github.event_name != 'pull_request' }} + # 给清单打上多个标签 + tags: | + ${{ secrets.DOCKERHUB_USERNAME }}/chatgpt-wecom:${{ env.GITHUB_REF_NAME }} + ${{ secrets.DOCKERHUB_USERNAME }}/chatgpt-wecom:latest + + # 镜像推送到 阿里云仓库 + - name: Login to the Ali Registry + uses: docker/login-action@v2 + with: + registry: registry.cn-hangzhou.aliyuncs.com + username: ${{ secrets.ALIHUB_USERNAME }} + password: ${{ secrets.ALIHUB_TOKEN }} + + - name: Build and push to Ali + uses: docker/build-push-action@v3 + with: + context: . + push: true + platforms: linux/amd64,linux/arm64 + tags: | + registry.cn-hangzhou.aliyuncs.com/${{ secrets.ALIHUB_USERNAME }}/chatgpt-wecom:${{ env.GITHUB_REF_NAME }} + registry.cn-hangzhou.aliyuncs.com/${{ secrets.ALIHUB_USERNAME }}/chatgpt-wecom:latest \ No newline at end of file diff --git a/.github/workflows/go-binary-release.yml b/.github/workflows/go-binary-release.yml new file mode 100644 index 0000000..4782cc3 --- /dev/null +++ b/.github/workflows/go-binary-release.yml @@ -0,0 +1,26 @@ +name: build + +on: + release: + types: [created,published] # 表示在创建新的 Release 时触发 + +jobs: + build-go-binary: + runs-on: ubuntu-latest + strategy: + matrix: + goos: [linux, windows, darwin] # 需要打包的系统 + goarch: [amd64, arm64] # 需要打包的架构 + exclude: # 排除某些平台和架构 + - goarch: arm64 + goos: windows + steps: + - uses: actions/checkout@v3 + - uses: wangyoucao577/go-release-action@v1.30 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} # 一个默认的变量,用来实现往 Release 中添加文件 + goos: ${{ matrix.goos }} + goarch: ${{ matrix.goarch }} + goversion: 1.18 # 可以指定编译使用的 Golang 版本 + binary_name: "chatgpt-wecom" # 可以指定二进制文件的名称 + extra_files: LICENSE config.example.yml prompt.yml README.md # 需要包含的额外文件 \ No newline at end of file diff --git a/.github/workflows/reademe-contributors.yml b/.github/workflows/reademe-contributors.yml new file mode 100644 index 0000000..e284a0d --- /dev/null +++ b/.github/workflows/reademe-contributors.yml @@ -0,0 +1,20 @@ +name: Generate a list of contributors + +on: + push: + branches: + - main + +jobs: + contrib-readme-en-job: + runs-on: ubuntu-latest + name: A job to automate contrib in readme + steps: + - name: Contribute List + uses: akhilmhdh/contributors-readme-action@v2.3.6 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + image_size: 75 + columns_per_row: 8 + commit_message: '🫶 更新贡献者列表' \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..98118db --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,38 @@ +name: Release Drafter + +on: + push: + # branches to consider in the event; optional, defaults to all + branches: + - main + # pull_request event is required only for autolabeler + pull_request: + # Only following types are handled by the action, but one can default to all as well + types: [opened, reopened, synchronize] + # pull_request_target event is required for autolabeler to support PRs from forks + # pull_request_target: + # types: [opened, reopened, synchronize] + +permissions: + contents: read + +jobs: + update_release_draft: + permissions: + contents: write # for release-drafter/release-drafter to create a github release + pull-requests: write # for release-drafter/release-drafter to add label to PR + runs-on: ubuntu-latest + steps: + # (Optional) GitHub Enterprise requires GHE_HOST variable set + #- name: Set GHE_HOST + # run: | + # echo "GHE_HOST=${GITHUB_SERVER_URL##https:\/\/}" >> $GITHUB_ENV + + # Drafts your next Release notes as Pull Requests are merged into "master" + - uses: release-drafter/release-drafter@v5 + # (Optional) specify config name to use, relative to .github/. Default: release-drafter.yml + # with: + # config-name: my-config.yml + # disable-autolabeler: true + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/toc.yml b/.github/workflows/toc.yml new file mode 100644 index 0000000..5425bbb --- /dev/null +++ b/.github/workflows/toc.yml @@ -0,0 +1,11 @@ +on: push +name: Automatic Generation TOC +jobs: + generateTOC: + name: TOC Generator + runs-on: ubuntu-latest + steps: + - uses: technote-space/toc-generator@v4 + with: + TOC_TITLE: "**目录**" + MAX_HEADER_LEVEL: 4 \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7fa97c2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,25 @@ +# Binaries for programs and plugins +*.exe +*.exe~ +*.dll +*.so +*.dylib +.idea/ +.vscode/ + +chatgpt-wecom + +# Test binary, built with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Dependency directories (remove the comment below to include it) +# vendor/ +config.yml +wecom.sqlite +tmp +test/ +images/ +data/ \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..84785ea --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# 贡献者指南 + +欢迎反馈、bug报告和拉取请求,可点击[issue](https://github.com/eryajf/chatgpt-wecom/issues) 提交. + +如果你是第一次进行GitHub的协作,可参阅: [协同开发流程](https://eryajf.github.io/HowToStartOpenSource/views/01-basic-content/03-collaborative-development-process.html) + +## 注意事项 + +- 如果你的变更中新增或者减少了配置,那么需要注意有这么几个地方需要同步调整: + + - [config.go](https://github.com/eryajf/chatgpt-wecom/blob/main/config/config.go) + - [config.example.yml](https://github.com/eryajf/chatgpt-wecom/blob/main/config.example.yml) + - [docker-compose.yml](https://github.com/eryajf/chatgpt-wecom/blob/main/docker-compose.yml) + - [README.md](https://github.com/eryajf/chatgpt-wecom/blob/main/README.md) + - docker [启动命令](https://github.com/eryajf/chatgpt-wecom/blob/main/README.md#docker%E9%83%A8%E7%BD%B2)中要添加。 + - [配置文件说明](https://github.com/eryajf/chatgpt-wecom/blob/main/README.md#%E9%85%8D%E7%BD%AE%E6%96%87%E4%BB%B6%E8%AF%B4%E6%98%8E)要添加。 + + 一定要检查这几个地方,而且注意务必加好注释,否则将会影响用户升级体验新功能。 + +- 关于配置管理还有一个很重要的点在于,`config.example.yml`中的配置务必配置为最大权限,以免出现用户首次部署就无法走到正常逻辑的情况。 + +- 请务必检查你的提交,是否包含secret,api_key之类的信息,如果要贴示例,注意数据脱敏。 + +- 如果新增了功能性的模板,则务必在[使用指南](./docs/userGuide.md)中添加对应说明文档。 \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..1efd4d9 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,25 @@ +FROM golang:1.18.10-alpine3.16 AS builder + +# ENV GOPROXY https://goproxy.io + +RUN mkdir /app +ADD . /app/ +WORKDIR /app +RUN go build -o chatgpt-wecom . + +FROM alpine:3.16 + +ARG TZ="Asia/Shanghai" + +ENV TZ ${TZ} + +RUN mkdir /app && apk upgrade \ + && apk add bash tzdata \ + && ln -sf /usr/share/zoneinfo/${TZ} /etc/localtime \ + && echo ${TZ} > /etc/timezone + +WORKDIR /app +COPY --from=builder /app/ . +RUN chmod +x chatgpt-wecom && cp config.example.yml config.yml + +CMD ./chatgpt-wecom \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..eb29eb4 --- /dev/null +++ b/Makefile @@ -0,0 +1,16 @@ +default: build + +run: + GIN_MODE=release go run main.go + +build: + go build -o chatgpt-wecom main.go + +build-linux: + CGO_ENABLED=0 GOARCH=amd64 GOOS=linux go build -o chatgpt-wecom main.go + +build-linux-arm: + CGO_ENABLED=0 GOARCH=arm64 GOOS=linux go build -o chatgpt-wecom main.go + +lint: + env GOGC=25 golangci-lint run --fix -j 8 -v ./... \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..00bee31 --- /dev/null +++ b/README.md @@ -0,0 +1,297 @@ +

+
+ 🚀 ChatGPT WeCom 🚀 +

+ +

🌉 基于GO语言实现的体验最好的企微应用集成ChatGPT项目 🌉

+ +
+ +[![Auth](https://img.shields.io/badge/Auth-eryajf-ff69b4)](https://github.com/eryajf) +[![Go Version](https://img.shields.io/github/go-mod/go-version/eryajf/chatgpt-wecom)](https://github.com/eryajf/chatgpt-wecom) +[![GitHub Pull Requests](https://img.shields.io/github/issues-pr/eryajf/chatgpt-wecom)](https://github.com/eryajf/chatgpt-wecom/pulls) +[![GitHub Pull Requests](https://img.shields.io/github/stars/eryajf/chatgpt-wecom)](https://github.com/eryajf/chatgpt-wecom/stargazers) +[![HitCount](https://views.whatilearened.today/views/github/eryajf/chatgpt-wecom.svg)](https://github.com/eryajf/chatgpt-wecom) +[![Docker Image Size (latest by date)](https://img.shields.io/docker/image-size/eryajf/chatgpt-wecom)](https://hub.docker.com/r/eryajf/chatgpt-wecom) +[![Docker Pulls](https://img.shields.io/docker/pulls/eryajf/chatgpt-wecom)](https://hub.docker.com/r/eryajf/chatgpt-wecom) +[![GitHub license](https://img.shields.io/github/license/eryajf/chatgpt-wecom)](https://github.com/eryajf/chatgpt-wecom/blob/main/LICENSE) + +
+ + +
+ + + + + + + +## 前言 + +本项目可以助你将GPT机器人集成到企微应用当中。当前默认模型为`gpt-3.5`,支持`gpt-4`,同时支持Azure-OpenAI。 + +>- `📢 注意`:当下部署以及配置流程都已非常成熟,文档和issue中基本都覆盖到了,因此不再回答任何项目安装部署与配置使用上的问题,如果完全不懂,可考虑通过 **[邮箱](mailto:eryajf@163.com)** 联系我进行付费的技术支持。 + + +🥳 **欢迎关注我的其他开源项目:** +> +> - [Go-Ldap-Admin](https://github.com/eryajf/go-ldap-admin):🌉 基于Go+Vue实现的openLDAP后台管理项目。 +> - [learning-weekly](https://github.com/eryajf/learning-weekly):📝 周刊内容以运维技术和Go语言周边为主,辅以GitHub上优秀项目或他人优秀经验。 +> - [HowToStartOpenSource](https://github.com/eryajf/HowToStartOpenSource):🌈 GitHub开源项目维护协同指南。 +> - [read-list](https://github.com/eryajf/read-list):📖 优质内容订阅,阅读方为根本 +> - [awesome-github-profile-readme-chinese](https://github.com/eryajf/awesome-github-profile-readme-chinese):🦩 优秀的中文区个人主页搜集 + +🚜 我还创建了一个项目 **[awesome-chatgpt-answer](https://github.com/eryajf/awesome-chatgpt-answer)** :记录那些问得好,答得妙的时刻,欢迎提交你与ChatGPT交互过程中遇到的那些精妙对话。 + +⚗️ openai官方提供了一个 **[状态页](https://status.openai.com/)** 来呈现当前openAI服务的状态,同时如果有问题发布公告也会在这个页面,如果你感觉它有问题了,可以在这个页面看看。 + +## 功能介绍 + +- [x] 🚀 帮助菜单:通过发送 `帮助` 将看到帮助列表 +- [x] 🙋 单聊模式:每次对话都是一次新的对话,没有历史聊天上下文联系 +- [x] 🗣 串聊模式:带上下文理解的对话模式 +- [x] 🎭 角色扮演:支持场景模式,通过 `#周报` 的方式触发内置prompt模板 +- [x] 🧑‍💻 频率限制:通过配置指定,自定义单个用户单日最大对话次数 +- [x] 🔗 自定义api域名:通过配置指定,解决国内服务器无法直接访问openai的问题 +- [x] 🪜 添加代理:通过配置指定,通过给应用注入代理解决国内服务器无法访问的问题 +- [x] 👐 默认模式:支持自定义默认的聊天模式,通过配置化指定 +- [x] 👹 白名单机制:通过配置指定,支持指定群组名称和用户名称作为白名单,从而实现可控范围与机器人对话 +- [x] 💂‍♀️ 管理员机制:通过配置指定管理员,部分敏感操作,以及一些应用配置,管理员有权限进行操作 +- [x] ㊙️ 敏感词过滤:通过配置指定敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 +- [ ] 🎨 图片生成:通过发送 `#图片`关键字开头的内容进行生成图片 +- [ ] 📝 查询对话:通过发送`#查对话 username:xxx`查询xxx的对话历史,可在线预览,可下载到本地 + +## 使用前提 + +* 有Openai账号,并且创建好`api_key`,关于这个的申请创建,这里不过多赘述。 +* 在企微开发者后台创建应用,需要如下五个配置信息: + * `corp_id:`企业ID + * `agent_id:` 应用ID + * `agent_secret:` 应用秘钥 + * `receive_msg_token:` API接收消息的token + * `receive_msg_key:` API接收消息的key + + +接下来跟随如下教程,保你一次配置成功。 + +## 使用教程 + +### 第一步,创建应用 + +1. [点我登陆](https://work.weixin.qq.com/wework_admin/frame)企业微信管理后台。 + + 此时点击我的企业可以获取到企业ID`corp_id`。 +
+ 🖼 点我查看示例图 + +
+ +2. 点击应用,创建一个新的应用。 + +
+ 🖼 点我查看示例图 + +
+ +3. 创建成功之后,能够获取到应用的`agent_id`与`agent_secret`。 + +
+ 🖼 点我查看示例图 + +
+ +4. 点击接收消息的`设置 API 接收`,进入回调地址配置页面,点击两个随机获取,可以获得`receive_msg_token`与`receive_msg_key`。 + +
+ 🖼 点我查看示例图 + +
+ +- `📢 注意:`此时点击保存会提示 `openapi回调地址请求不通过`,是因为保存配置的时候企微会向服务发送请求进行校验。所以此时这个页面先放这儿,去部署应用。应用部署起来之后,再回来保存配置就能成功了。 + + +### 第二步,部署项目 + +#### docker部署 + +推荐你使用docker-compose快速运行本项目。 + +```yaml +version: '3' +services: + chatgpt: + container_name: chatgpt + image: registry.cn-hangzhou.aliyuncs.com/ali_eryajf/chatgpt-wecom + restart: always + environment: + LOG_LEVEL: "info" # 应用的日志级别 info/debug + CORP_ID: "" # 企业ID + AGENT_ID: "" # 应用ID + AGENT_SECRET: "" # 应用秘钥 + RECEIVE_MSG_TOKEN: "" # API接收消息的token + RECEIVE_MSG_KEY: "" # API接收消息的key + APIKEY: xxxxxx # 你的 api_key + BASE_URL: "" # 如果你使用官方的接口地址 https://api.openai.com,则留空即可,如果你想指定请求url的地址,可通过这个参数进行配置,注意需要带上 http 协议 + MODEL: "gpt-3.5-turbo" # 指定模型,默认为 gpt-3.5-turbo , 可选参数有: "gpt-4-32k-0613", "gpt-4-32k-0314", "gpt-4-32k", "gpt-4-0613", "gpt-4-0314", "gpt-4", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-0301", "gpt-3.5-turbo",如果使用gpt-4,请确认自己是否有接口调用白名单,如果你是用的是azure,则该配置项可以留空或者直接忽略 + SESSION_TIMEOUT: 600 # 会话超时时间,默认600秒,在会话时间内所有发送给机器人的信息会作为上下文 + MAX_QUESTION_LEN: 2048 # 最大问题长度,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + MAX_ANSWER_LEN: 2048 # 最大回答长度,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + MAX_TEXT: 4096 # 最大文本 = 问题 + 回答, 接口限制,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + HTTP_PROXY: http://host.docker.internal:15777 # 指定请求时使用的代理,如果为空,则不使用代理,注意需要带上 http 协议 或 socks5 协议 + DEFAULT_MODE: "单聊" # 指定默认的对话模式,可根据实际需求进行自定义,如果不设置,默认为单聊,即无上下文关联的对话模式 + MAX_REQUEST: 0 # 单人单日请求次数上限,默认为0,即不限制 + PORT: 8090 # 指定服务启动端口,默认为 8090,容器化部署时,不需要调整,一般在二进制宿主机部署时,遇到端口冲突时使用,如果run_mode为stream模式,则可以忽略该配置项 + SERVICE_URL: "" # 指定服务的地址,就是当前服务可供外网访问的地址(或者直接理解为你配置在企微回调那里的地址),用于生成图片时给企微做渲染 + # 以下 ALLOW_USERS、DENY_USERS、VIP_USERS、ADMIN_USERS 配置中填写的是用户的userid + # 比如 ["1301691029702722","1301691029702733"],这个信息需要在企微管理后台的通讯录当中获取:hhttps://work.weixin.qq.com/wework_admin/frame#contacts + # 哪些用户可以进行对话,如果留空,则表示允许所有用户,如果要限制,则列表中写用户的userid + ALLOW_USERS: "" # 哪些用户可以进行对话,如果留空,则表示允许所有用户,如果要限制,则填写用户的userid + DENY_USERS: "" # 哪些用户不可以进行对话,如果留空,则表示允许所有用户(如allow_user有配置,需满足相应条件),如果要限制,则列表中写用户的userid,黑名单优先级高于白名单 + VIP_USERS: "" # 哪些用户可以进行无限对话,如果留空,则表示只允许管理员(如max_request配置为0,则允许所有人),如果要针对指定VIP用户放开限制(如max_request配置不为0),则列表中写用户的userid + ADMIN_USERS: "" # 指定哪些人为此系统的管理员,如果留空,则表示没有人是管理员,如果要限制,则列表中写用户的userid + SENSITIVE_WORDS: "" # 敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 + AZURE_ON: "false" # 是否走Azure OpenAi API, 默认false ,如果为true,则需要配置下边的四个参数 + AZURE_API_VERSION: "" # Azure OpenAi API 版本,比如 "2023-03-15-preview" + AZURE_RESOURCE_NAME: "" # Azure OpenAi API 资源名称,比如 "openai" + AZURE_DEPLOYMENT_NAME: "" # Azure OpenAi API 部署名称,比如 "openai" + AZURE_OPENAI_TOKEN: "" # Azure token + HELP: "Commands:\n\n=================================\n\n🙋 单聊 👉 单独聊天,缺省\n\n🗣 串聊 👉 带上下文聊天\n\n🔃 重置 👉 重置带上下文聊天\n\n🚀 帮助 👉 显示帮助信息\n\n=================================\n\n💪 Power By [eryajf/chatgpt-wecom](https://github.com/eryajf/chatgpt-wecom)" # 帮助信息,放在配置文件,可供自定义 + volumes: + - ./data:/app/data + ports: + - "8000:8000" + extra_hosts: + - host.docker.internal:host-gateway +``` + +启动服务: + +```sh +$ docker compose up -d +``` + +#### 二进制部署 + + +如果你想通过命令行直接部署,可以直接下载release中的[压缩包](https://github.com/eryajf/chatgpt-wecom/releases) ,请根据自己系统以及架构选择合适的压缩包,下载之后直接解压运行。 + +下载之后,在本地解压,即可看到可执行程序,与配置文件: + +```sh +$ tar xf chatgpt-wecom-v0.0.4-darwin-arm64.tar.gz +$ cd chatgpt-wecom-v0.0.4-darwin-arm64 +$ cp config.example.yml config.yml +$ ./chatgpt-wecom # 直接运行 + +# 如果要守护在后台运行 +$ nohup ./chatgpt-wecom &> run.log & +$ tail -f run.log +``` + + +### 第三步,完善企微配置 + +此时服务如正常启动,可再回到企微管理后台的配置页面,尝试保存配置。如果服务正常,应该就能保存成功了,从服务日志当中,也可以看到企微发起的回调: + +```sh +[GIN] 2023/07/02 - 21:33:53 | 200 | 78.469µs | 113.108.92.100 | GET "/ai/callback?msg_signature=fb23b8490965c74600dcb08b2e8b86d2aff664e4×tamp=1688304833&nonce=1688533588&echostr=I5D3M3C%2Fk7AqBFRkACk8eHZAzt%2Fjx14IKk8wXUpA85xsQ2aU67lxEhgHVudLSrCWEPRFapeQ3EcYbni0Bqj01Q%3D%3D" +``` + +此时还需要将部署服务的IP加入到企微的白名单当中: + +
+ 🖼 点我查看示例图 + +
+ +到这里配置步骤就完成了,可以尽情享用与智能机器人的交互了。 + +来到企业微信,点击工作台,然后可以看到我们添加的应用,点击应用,即可开始对话。 + +
+ 🖼 点我查看示例图 + +
+ +## 配置文件说明 + +```yaml +# 应用的日志级别,info or debug +log_level: "info" +# openai api_key,如果你是用的是azure,则该配置项可以留空或者直接忽略 +api_key: "xxxxxxxxx" +# 如果你使用官方的接口地址 https://api.openai.com,则留空即可,如果你想指定请求url的地址,可通过这个参数进行配置,注意需要带上 http 协议,如果你是用的是azure,则该配置项可以留空或者直接忽略 +base_url: "" +# 指定模型,默认为 gpt-3.5-turbo , 可选参数有: "gpt-4-32k-0613", "gpt-4-32k-0314", "gpt-4-32k", "gpt-4-0613", "gpt-4-0314", "gpt-4", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-0301", "gpt-3.5-turbo",如果使用gpt-4,请确认自己是否有接口调用白名单,如果你是用的是azure,则该配置项可以留空或者直接忽略 +model: "gpt-3.5-turbo" +# 会话超时时间,默认600秒,在会话时间内所有发送给机器人的信息会作为上下文 +session_timeout: 600 +# 最大问题长度 +max_question_len: 2048 +# 最大回答长度 +max_answer_len: 2048 +# 最大上下文文本长度,通常该参数可设置为与模型Token限制相同 +max_text: 4096 +# 指定请求时使用的代理,如果为空,则不使用代理,注意需要带上 http 协议 或 socks5 协议,如果你是用的是azure,则该配置项可以留空或者直接忽略 +http_proxy: "" +# 指定默认的对话模式,可根据实际需求进行自定义,如果不设置,默认为单聊,即无上下文关联的对话模式 +default_mode: "单聊" +# 单人单日请求次数上限,默认为0,即不限制 +max_request: 0 +# 指定服务启动端口,默认为 8090,一般在二进制宿主机部署时,遇到端口冲突时使用,如果run_mode为stream模式,则可以忽略该配置项 +port: "8090" +# 指定服务的地址,就是当前服务可供外网访问的地址(或者直接理解为你配置在企微回调那里的地址),用于生成图片时给企微做渲染,最新版本中将图片上传到了企微服务器,理论上你可以忽略该配置项,如果run_mode为stream模式,则可以忽略该配置项 +service_url: "http://xxxxxx" +# 以下 allow_users、deny_users、vip_users、admin_users 配置中填写的是用户的userid,outgoing机器人模式下不适用这些配置 +# 比如 ["1301691029702722","1301691029702733"],这个信息需要在企微管理后台的通讯录当中获取:https://oa.dingtalk.com/contacts.htm#/contacts +# 哪些用户可以进行对话,如果留空,则表示允许所有用户,如果要限制,则列表中写用户的userid +allow_users: [] +# 哪些用户不可以进行对话,如果留空,则表示允许所有用户(如allow_user有配置,需满足相应条件),如果要限制,则列表中写用户的userid,黑名单优先级高于白名单 +deny_users: [] +# 哪些用户可以进行无限对话,如果留空,则表示只允许管理员(如max_request配置为0,则允许所有人) +# 如果要针对指定VIP用户放开限制(如max_request配置不为0),则列表中写用户的userid +vip_users: [] +# 指定哪些人为此系统的管理员,如果留空,则表示没有人是管理员,如果要限制,则列表中写用户的userid +admin_users: [] +# 敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 +sensitive_words: [] +# 帮助信息,放在配置文件,可供自定义 +help: "Commands:\n\n=================================\n\n🙋 单聊 👉 单独聊天,缺省\n\n🗣 串聊 👉 带上下文聊天\n\n🔃 重置 👉 重置带上下文聊天\n\n🚀 帮助 👉 显示帮助信息\n\n=================================\n\n💪 Power By [eryajf/chatgpt-wecom](https://github.com/eryajf/chatgpt-wecom)" + +# Azure OpenAI 配置 +azure_on: false # 如果是true,则会走azure的openai接口 +azure_resource_name: "eryajf" # 对应你的主个性域名 +azure_deployment_name: "gpt-35-turbo" # 对应的是 /deployments/ 后边跟着的这个值 +azure_api_version: "2023-03-15-preview" # 对应的是请求中的 api-version 后边的值 +azure_openai_token: "xxxxxxx" +``` + +## 常见问题 + +- 企微只支持与应用一对一聊天,不支持群聊当中添加机器人的对话形式。 + +## 感谢 + +这个项目能够成立,离不开这些开源项目: + +- [go-resty/resty](https://github.com/go-resty/resty) +- [patrickmn/go-cache](https://github.com/patrickmn/go-cache) +- [solywsh/chatgpt](https://github.com/solywsh/chatgpt) +- [gin-gonic/gin](https://github.com/gin-gonic/gin) +- [avast/retry-go](https://github.com/avast/retry-go) +- [sashabaranov/go-openapi](https://github.com/sashabaranov/go-openai) +- [charmbracelet/log](https://github.com/charmbracelet/log) +- [xen0n/go-workwx](https://github.com/xen0n/go-workwx) + +## 赞赏 + +如果觉得这个项目对你有帮助,你可以请作者[喝杯咖啡 ☕️](https://wiki.eryajf.net/reward/) + +## 贡献者列表 + +
+ + +
+ diff --git a/config.example.yml b/config.example.yml new file mode 100644 index 0000000..9260fb5 --- /dev/null +++ b/config.example.yml @@ -0,0 +1,57 @@ +# 应用的日志级别,info or debug +log_level: "info" +# 企业ID +corp_id: "" +# 应用ID +agent_id: "" +# 应用秘钥 +agent_secret: "" +# API接收消息的token +receive_msg_token: "" +# API接收消息的key +receive_msg_key: "" +# openai api_key,如果你是用的是azure,则该配置项可以留空或者直接忽略 +api_key: "xxxxxxxxx" +# 如果你使用官方的接口地址 https://api.openai.com,则留空即可,如果你想指定请求url的地址,可通过这个参数进行配置,注意需要带上 http 协议,如果你是用的是azure,则该配置项可以留空或者直接忽略 +base_url: "" +# 指定模型,默认为 gpt-3.5-turbo , 可选参数有: "gpt-4-32k-0613", "gpt-4-32k-0314", "gpt-4-32k", "gpt-4-0613", "gpt-4-0314", "gpt-4", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-0301", "gpt-3.5-turbo",如果使用gpt-4,请确认自己是否有接口调用白名单,如果你是用的是azure,则该配置项可以留空或者直接忽略 +model: "gpt-3.5-turbo-0613" +# 会话超时时间,默认600秒,在会话时间内所有发送给机器人的信息会作为上下文 +session_timeout: 600 +# 最大问题长度 +max_question_len: 2048 +# 最大回答长度 +max_answer_len: 2048 +# 最大上下文文本长度,通常该参数可设置为与模型Token限制相同 +max_text: 4096 +# 指定请求时使用的代理,如果为空,则不使用代理,注意需要带上 http 协议 或 socks5 协议,如果你是用的是azure,则该配置项可以留空或者直接忽略 +http_proxy: "" +# 指定默认的对话模式,可根据实际需求进行自定义,如果不设置,默认为单聊,即无上下文关联的对话模式 +default_mode: "单聊" +# 单人单日请求次数上限,默认为0,即不限制 +max_request: 0 +# 指定服务启动端口,默认为 8090 +port: "8090" +# 指定服务的地址,就是当前服务可供外网访问的地址(或者直接理解为你配置在企微回调那里的地址),用于生成图片时给企微做渲染,最新版本中将图片上传到了企微服务器,理论上你可以忽略该配置项,如果run_mode为stream模式,则可以忽略该配置项 +service_url: "http://xxxxxx" +# 以下 allow_users、deny_users、vip_users、admin_users 配置中填写的是用户的userid,outgoing机器人模式下不适用这些配置 +# 比如 ["1301691029702722","1301691029702733"],这个信息需要在企微管理后台的通讯录当中获取:https://work.weixin.qq.com/wework_admin/frame#contacts +# 哪些用户可以进行对话,如果留空,则表示允许所有用户,如果要限制,则列表中写用户的userid +allow_users: [] +# 哪些用户不可以进行对话,如果留空,则表示允许所有用户(如allow_user有配置,需满足相应条件),如果要限制,则列表中写用户的userid,黑名单优先级高于白名单 +deny_users: [] +# 哪些用户可以进行无限对话,如果留空,则表示只允许管理员(如max_request配置为0,则允许所有人) +# 如果要针对指定VIP用户放开限制(如max_request配置不为0),则列表中写用户的userid +vip_users: [] +# 指定哪些人为此系统的管理员,如果留空,则表示没有人是管理员,如果要限制,则列表中写用户的userid +admin_users: [] +# 敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 +sensitive_words: [] +# 帮助信息,放在配置文件,可供自定义 +help: "Commands:\n\n=================================\n\n🙋 单聊 👉 单独聊天,缺省\n\n🗣 串聊 👉 带上下文聊天\n\n🔃 重置 👉 重置带上下文聊天\n\n🚀 帮助 👉 显示帮助信息\n\n=================================\n\n💪 Power By [eryajf/chatgpt-wecom](https://github.com/eryajf/chatgpt-wecom)" +# Azure OpenAI 配置 +azure_on: false # 如果是true,则会走azure的openai接口 +azure_resource_name: "eryajf" # 对应你的主个性域名 +azure_deployment_name: "gpt-35-turbo" # 对应的是 /deployments/ 后边跟着的这个值 +azure_api_version: "2023-03-15-preview" # 对应的是请求中的 api-version 后边的值 +azure_openai_token: "xxxxxxx" \ No newline at end of file diff --git a/config/config.go b/config/config.go new file mode 100644 index 0000000..b037b92 --- /dev/null +++ b/config/config.go @@ -0,0 +1,253 @@ +package config + +import ( + "fmt" + "io/ioutil" + "log" + "os" + "strconv" + "strings" + "sync" + "time" + + "github.com/eryajf/chatgpt-wecom/pkg/logger" + "gopkg.in/yaml.v2" +) + +// Configuration 项目配置 +type Configuration struct { + // 日志级别,info或者debug + LogLevel string `yaml:"log_level"` + // 企业ID + CorpId string `yaml:"corp_id"` + // 应用ID + AgentId int64 `yaml:"agent_id"` + // 应用秘钥 + AgentSecret string `yaml:"agent_secret"` + // API接收消息的token + ReceiveMsgToken string `yaml:"receive_msg_token"` + // API接收消息的key + ReceiveMsgKey string `yaml:"receive_msg_key"` + // gpt apikey + ApiKey string `yaml:"api_key"` + // 请求的 URL 地址 + BaseURL string `yaml:"base_url"` + // 使用模型 + Model string `yaml:"model"` + // 会话超时时间 + SessionTimeout time.Duration `yaml:"session_timeout"` + // 最大问题长度 + MaxQuestionLen int `yaml:"max_question_len"` + // 最大答案长度 + MaxAnswerLen int `yaml:"max_answer_len"` + // 最大文本 = 问题 + 回答, 接口限制 + MaxText int `yaml:"max_text"` + // 默认对话模式 + DefaultMode string `yaml:"default_mode"` + // 代理地址 + HttpProxy string `yaml:"http_proxy"` + // 用户单日最大请求次数 + MaxRequest int `yaml:"max_request"` + // 指定服务启动端口,默认为 8090 + Port string `yaml:"port"` + // 指定服务的地址,就是企微机器人配置的回调地址,比如: http://chat.eryajf.net + ServiceURL string `yaml:"service_url"` + // 哪些用户可以进行对话 + AllowUsers []string `yaml:"allow_users"` + // 哪些用户不可以进行对话 + DenyUsers []string `yaml:"deny_users"` + // 哪些Vip用户可以进行无限对话 + VipUsers []string `yaml:"vip_users"` + // 指定哪些人为此系统的管理员,必须指定,否则所有人都是 + AdminUsers []string `yaml:"admin_users"` + // 敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 + SensitiveWords []string `yaml:"sensitive_words"` + // 自定义帮助信息 + Help string `yaml:"help"` + // AzureOpenAI 配置 + AzureOn bool `yaml:"azure_on"` + AzureApiVersion string `yaml:"azure_api_version"` + AzureResourceName string `yaml:"azure_resource_name"` + AzureDeploymentName string `yaml:"azure_deployment_name"` + AzureOpenAIToken string `yaml:"azure_openai_token"` +} + +var config *Configuration +var once sync.Once + +// LoadConfig 加载配置 +func LoadConfig() *Configuration { + once.Do(func() { + // 从文件中读取 + config = &Configuration{} + data, err := ioutil.ReadFile("config.yml") + if err != nil { + log.Fatal(err) + } + err = yaml.Unmarshal(data, &config) + if err != nil { + log.Fatal(err) + } + + // 如果环境变量有配置,读取环境变量 + logLevel := os.Getenv("LOG_LEVEL") + if logLevel != "" { + config.LogLevel = logLevel + } + corpId := os.Getenv("CORP_ID") + if corpId != "" { + config.CorpId = corpId + } + agentId := os.Getenv("AGENT_ID") + if agentId != "" { + id, _ := strconv.ParseInt(agentId, 10, 64) + config.AgentId = id + } + agentSecret := os.Getenv("AGENT_SECRET") + if agentSecret != "" { + config.AgentSecret = agentSecret + } + receiveMsgToken := os.Getenv("RECEIVE_MSG_TOKEN") + if receiveMsgToken != "" { + config.ReceiveMsgToken = receiveMsgToken + } + receiveMsgKey := os.Getenv("RECEIVE_MSG_KEY") + if receiveMsgKey != "" { + config.ReceiveMsgKey = receiveMsgKey + } + apiKey := os.Getenv("APIKEY") + if apiKey != "" { + config.ApiKey = apiKey + } + baseURL := os.Getenv("BASE_URL") + if baseURL != "" { + config.BaseURL = baseURL + } + model := os.Getenv("MODEL") + if model != "" { + config.Model = model + } + sessionTimeout := os.Getenv("SESSION_TIMEOUT") + if sessionTimeout != "" { + duration, err := strconv.ParseInt(sessionTimeout, 10, 64) + if err != nil { + logger.Fatal(fmt.Sprintf("config session timeout err: %v ,get is %v", err, sessionTimeout)) + return + } + config.SessionTimeout = time.Duration(duration) * time.Second + } else { + config.SessionTimeout = time.Duration(config.SessionTimeout) * time.Second + } + maxQuestionLen := os.Getenv("MAX_QUESTION_LEN") + if maxQuestionLen != "" { + newLen, _ := strconv.Atoi(maxQuestionLen) + config.MaxQuestionLen = newLen + } + maxAnswerLen := os.Getenv("MAX_ANSWER_LEN") + if maxAnswerLen != "" { + newLen, _ := strconv.Atoi(maxAnswerLen) + config.MaxAnswerLen = newLen + } + maxText := os.Getenv("MAX_TEXT") + if maxText != "" { + newLen, _ := strconv.Atoi(maxText) + config.MaxText = newLen + } + defaultMode := os.Getenv("DEFAULT_MODE") + if defaultMode != "" { + config.DefaultMode = defaultMode + } + httpProxy := os.Getenv("HTTP_PROXY") + if httpProxy != "" { + config.HttpProxy = httpProxy + } + maxRequest := os.Getenv("MAX_REQUEST") + if maxRequest != "" { + newMR, _ := strconv.Atoi(maxRequest) + config.MaxRequest = newMR + } + port := os.Getenv("PORT") + if port != "" { + config.Port = port + } + serviceURL := os.Getenv("SERVICE_URL") + if serviceURL != "" { + config.ServiceURL = serviceURL + } + allowUsers := os.Getenv("ALLOW_USERS") + if allowUsers != "" { + config.AllowUsers = strings.Split(allowUsers, ",") + } + denyUsers := os.Getenv("DENY_USERS") + if denyUsers != "" { + config.DenyUsers = strings.Split(denyUsers, ",") + } + vipUsers := os.Getenv("VIP_USERS") + if vipUsers != "" { + config.VipUsers = strings.Split(vipUsers, ",") + } + adminUsers := os.Getenv("ADMIN_USERS") + if adminUsers != "" { + config.AdminUsers = strings.Split(adminUsers, ",") + } + sensitiveWords := os.Getenv("SENSITIVE_WORDS") + if sensitiveWords != "" { + config.SensitiveWords = strings.Split(sensitiveWords, ",") + } + help := os.Getenv("HELP") + if help != "" { + config.Help = help + } + azureOn := os.Getenv("AZURE_ON") + if azureOn != "" { + config.AzureOn = azureOn == "true" + } + azureApiVersion := os.Getenv("AZURE_API_VERSION") + if azureApiVersion != "" { + config.AzureApiVersion = azureApiVersion + } + azureResourceName := os.Getenv("AZURE_RESOURCE_NAME") + if azureResourceName != "" { + config.AzureResourceName = azureResourceName + } + azureDeploymentName := os.Getenv("AZURE_DEPLOYMENT_NAME") + if azureDeploymentName != "" { + config.AzureDeploymentName = azureDeploymentName + } + azureOpenaiToken := os.Getenv("AZURE_OPENAI_TOKEN") + if azureOpenaiToken != "" { + config.AzureOpenAIToken = azureOpenaiToken + } + + }) + + // 一些默认值 + if config.LogLevel == "" { + config.LogLevel = "info" + } + if config.Model == "" { + config.Model = "gpt-3.5-turbo" + } + if config.DefaultMode == "" { + config.DefaultMode = "单聊" + } + if config.Port == "" { + config.Port = "8090" + } + if config.ApiKey == "" { + logger.Fatal("config err: api key required") + } + if config.ServiceURL == "" { + logger.Fatal("config err: service url required") + } + if config.MaxQuestionLen == 0 { + config.MaxQuestionLen = 4096 + } + if config.MaxAnswerLen == 0 { + config.MaxAnswerLen = 4096 + } + if config.MaxText == 0 { + config.MaxText = 4096 + } + return config +} diff --git a/config/prompt.go b/config/prompt.go new file mode 100644 index 0000000..abded32 --- /dev/null +++ b/config/prompt.go @@ -0,0 +1,30 @@ +package config + +import ( + "io/ioutil" + "log" + + "gopkg.in/yaml.v2" +) + +type Prompt struct { + Title string `yaml:"title"` + Prefix string `yaml:"prefix"` + Suffix string `yaml:"suffix"` +} + +var prompTmp *[]Prompt + +// LoadPrompt 加载Prompt +func LoadPrompt() *[]Prompt { + data, err := ioutil.ReadFile("prompt.yml") + if err != nil { + log.Fatal(err) + } + + err = yaml.Unmarshal(data, &prompTmp) + if err != nil { + log.Fatal(err) + } + return prompTmp +} diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..e8c24e9 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,44 @@ +version: '3' + +services: + chatgpt: + container_name: chatgpt + image: registry.cn-hangzhou.aliyuncs.com/ali_eryajf/chatgpt-wecom + restart: always + environment: + LOG_LEVEL: "info" # 应用的日志级别 info/debug + CORP_ID: "" # 企业ID + AGENT_ID: "" # 应用ID + AGENT_SECRET: "" # 应用秘钥 + RECEIVE_MSG_TOKEN: "" # API接收消息的token + RECEIVE_MSG_KEY: "" # API接收消息的key + APIKEY: xxxxxx # 你的 api_key + BASE_URL: "" # 如果你使用官方的接口地址 https://api.openai.com,则留空即可,如果你想指定请求url的地址,可通过这个参数进行配置,注意需要带上 http 协议 + MODEL: "gpt-3.5-turbo-0613" # 指定模型,默认为 gpt-3.5-turbo , 可选参数有: "gpt-4-32k-0613", "gpt-4-32k-0314", "gpt-4-32k", "gpt-4-0613", "gpt-4-0314", "gpt-4", "gpt-3.5-turbo-16k-0613", "gpt-3.5-turbo-16k", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-0301", "gpt-3.5-turbo",如果使用gpt-4,请确认自己是否有接口调用白名单,如果你是用的是azure,则该配置项可以留空或者直接忽略 + SESSION_TIMEOUT: 600 # 会话超时时间,默认600秒,在会话时间内所有发送给机器人的信息会作为上下文 + MAX_QUESTION_LEN: 2048 # 最大问题长度,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + MAX_ANSWER_LEN: 2048 # 最大回答长度,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + MAX_TEXT: 4096 # 最大文本 = 问题 + 回答, 接口限制,默认4096 token,正常情况默认值即可,如果使用gpt4-8k或gpt4-32k,可根据模型token上限修改。 + HTTP_PROXY: http://host.docker.internal:15777 # 指定请求时使用的代理,如果为空,则不使用代理,注意需要带上 http 协议 或 socks5 协议 + DEFAULT_MODE: "单聊" # 指定默认的对话模式,可根据实际需求进行自定义,如果不设置,默认为单聊,即无上下文关联的对话模式 + MAX_REQUEST: 0 # 单人单日请求次数上限,默认为0,即不限制 + PORT: 8000 # 指定服务启动端口,默认为 8000,容器化部署时,不需要调整,一般在二进制宿主机部署时,遇到端口冲突时使用,如果run_mode为stream模式,则可以忽略该配置项 + SERVICE_URL: "" # 指定服务的地址,就是当前服务可供外网访问的地址(或者直接理解为你配置在企微回调那里的地址) + # 以下 ALLOW_USERS、DENY_USERS、VIP_USERS、ADMIN_USERS 配置中填写的是用户的userid 比如 ["1301691029702722","1301691029702733"],这个信息需要在企微管理后台的通讯录当中获取:https://work.weixin.qq.com/wework_admin/frame#contacts + ALLOW_USERS: "" # 哪些用户可以进行对话,如果留空,则表示允许所有用户,如果要限制,则填写用户的userid + DENY_USERS: "" # 哪些用户不可以进行对话,如果留空,则表示允许所有用户(如allow_user有配置,需满足相应条件),如果要限制,则列表中写用户的userid,黑名单优先级高于白名单 + VIP_USERS: "" # 哪些用户可以进行无限对话,如果留空,则表示只允许管理员(如max_request配置为0,则允许所有人),如果要针对指定VIP用户放开限制(如max_request配置不为0),则列表中写用户的userid + ADMIN_USERS: "" # 指定哪些人为此系统的管理员,如果留空,则表示没有人是管理员,如果要限制,则列表中写用户的userid + SENSITIVE_WORDS: "" # 敏感词,提问时触发,则不允许提问,回答的内容中触发,则以 🚫 代替 + AZURE_ON: "false" # 是否走Azure OpenAi API, 默认false ,如果为true,则需要配置下边的四个参数 + AZURE_API_VERSION: "" # Azure OpenAi API 版本,比如 "2023-03-15-preview" + AZURE_RESOURCE_NAME: "" # Azure OpenAi API 资源名称,比如 "openai" + AZURE_DEPLOYMENT_NAME: "" # Azure OpenAi API 部署名称,比如 "openai" + AZURE_OPENAI_TOKEN: "" # Azure token + HELP: "Commands:\n\n=================================\n\n🙋 单聊 👉 单独聊天,缺省\n\n🗣 串聊 👉 带上下文聊天\n\n🔃 重置 👉 重置带上下文聊天\n\n🚀 帮助 👉 显示帮助信息\n\n=================================\n\n💪 Power By [eryajf/chatgpt-wecom](https://github.com/eryajf/chatgpt-wecom)" # 帮助信息,放在配置文件,可供自定义 + volumes: + - ./data:/app/data + ports: + - "8000:8000" + extra_hosts: + - host.docker.internal:host-gateway diff --git a/docs/userGuide.md b/docs/userGuide.md new file mode 100644 index 0000000..0f0f0a4 --- /dev/null +++ b/docs/userGuide.md @@ -0,0 +1,59 @@ +本文是chatgpt-wecom项目的使用指南,该项目涉及的指令,以及特性,都会在本文呈现。 + +## 发送信息 + +若您想给机器人发送信息,有如下两种方式: + +1. **群聊:** 在机器人所在群里`@机器人` 后边跟着要提问的内容。 +2. **私聊:** 点击机器人的`头像`后,再点击`发消息`。 + +## 系统指令 + +系统指令是一些特殊的词语,当您向机器人发送这些词语时,会触发对应的功能。 + +**📢 注意:系统指令,即只发指令,没有特殊标识,也没有内容。** + +以下是系统指令详情: + + +| 指令 | 描述 | 示例 | 补充 | +| :--------: | :------------------------------------------: | :----------------------------------------------------------: | :--: | +| **单聊** | 每次对话都是一次新的对话,没有聊天上下文联系 |

点击查看

| | +| **串聊** | 带上下文联系的对话模式 |

点击查看

| | +| **重置** | 重置上下文模式,回归到默认模式 |

点击查看

| | +| **余额** | 查询机器人所用OpenAI账号的余额 |

点击查看

| | +| **模板** | 查看应用内置的prompt模板 |

点击查看

| | +| **图片** | 查看如何根据提示生成图片 |

点击查看

| | +| **查对话** | 获取指定人员的对话历史 |

点击查看

| | +| **帮助** | 获取帮助信息 |

点击查看

| | + +## 功能指令 + +除去系统指令,还有一些功能指令,功能指令是直接与应用交互,达到交互目的的一种指令。 + +**📢 注意:功能指令,一律以 #+关键字 为开头,通常需要在关键字后边加个空格,然后再写描述或参数。** + +以下是功能指令详情 + +| 指令 | 说明 | 示例 | 补充| +| :--: | :--: | :--: | :--: | +| **#图片** | 根据提示咒语生成对应图片 |

点击查看

| | +| **#域名** | 查询域名相关信息 |

点击查看

| | +| **#证书** | 查询域名证书相关信息 |

点击查看

| | +| **#Linux命令** | 根据自然语言描述生成对应命令 |

点击查看

| 此指令中的Linux开头字幕可以大写 | +| **#解释代码** | 分析一段代码的功能或含义 |

点击查看

| | +| **#正则** | 根据自然语言描述生成正则 |

点击查看

| | +| **#周报** | 应用周报的prompt |

点击查看

| | +| **#生成sql** | 根据自然语言描述生成sql语句 |

点击查看

| | + +如上大多数能力,都是依赖prompt模板实现,如果你有更好的prompt,欢迎提交PR。 + +## 友情提示 + +使用`串聊模式`会显著加快机器人所用账号的余额消耗速度,因此,若无保留上下文的需求,建议使用`单聊模式`。 + +即使有保留上下文的需求,也应适时使用`重置`指令来重置上下文。 + +## 项目地址 + +本项目已在GitHub开源,[查看源代码](https://github.com/eryajf/chatgpt-wecom)。 \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f104f43 --- /dev/null +++ b/go.mod @@ -0,0 +1,71 @@ +module github.com/eryajf/chatgpt-wecom + +go 1.18 + +require ( + github.com/charmbracelet/log v0.2.1 + github.com/gin-gonic/gin v1.9.0 + github.com/glebarez/sqlite v1.7.0 + github.com/go-resty/resty/v2 v2.7.0 + github.com/patrickmn/go-cache v2.1.0+incompatible + github.com/sashabaranov/go-openai v1.12.0 + github.com/sbzhu/weworkapi_golang v0.0.0-20210525081115-1799804a7c8d + github.com/solywsh/chatgpt v0.0.14 + github.com/xen0n/go-workwx v1.5.0 + gopkg.in/yaml.v2 v2.4.0 + gorm.io/gorm v1.24.6 +) + +require ( + github.com/avast/retry-go v3.0.0+incompatible // indirect + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/bytedance/sonic v1.8.0 // indirect + github.com/cenkalti/backoff/v4 v4.1.3 // indirect + github.com/charmbracelet/lipgloss v0.7.1 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect + github.com/dlclark/regexp2 v1.9.0 // indirect + github.com/dop251/goja v0.0.0-20230402114112-623f9dda9079 // indirect + github.com/dop251/goja_nodejs v0.0.0-20230322100729-2550c7b6c124 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/glebarez/go-sqlite v1.20.3 // indirect + github.com/go-logfmt/logfmt v0.6.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.11.2 // indirect + github.com/go-sourcemap/sourcemap v2.1.3+incompatible // indirect + github.com/goccy/go-json v0.10.0 // indirect + github.com/google/pprof v0.0.0-20230406165453-00490a63f317 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.0.9 // indirect + github.com/leodido/go-urn v1.2.1 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.18 // indirect + github.com/mattn/go-runewidth v0.0.14 // indirect + github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/muesli/reflow v0.3.0 // indirect + github.com/muesli/termenv v0.15.1 // indirect + github.com/pandodao/tokenizer-go v0.2.0 // indirect + github.com/pelletier/go-toml/v2 v2.0.6 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/rivo/uniseg v0.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.9 // indirect + golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect + golang.org/x/crypto v0.5.0 // indirect + golang.org/x/net v0.10.0 // indirect + golang.org/x/sys v0.8.0 // indirect + golang.org/x/text v0.9.0 // indirect + google.golang.org/protobuf v1.28.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + modernc.org/libc v1.22.3 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/sqlite v1.20.4 // indirect +) + +replace github.com/solywsh/chatgpt => ./pkg/chatgpt diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..a2c03fc --- /dev/null +++ b/go.sum @@ -0,0 +1,212 @@ +github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= +github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.8.0 h1:ea0Xadu+sHlu7x5O3gKhRpQ1IKiMrSiHttPF0ybECuA= +github.com/bytedance/sonic v1.8.0/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/cenkalti/backoff/v4 v4.1.3 h1:cFAlzYUlVYDysBEH2T5hyJZMh3+5+WCBvSnK6Q8UtC4= +github.com/cenkalti/backoff/v4 v4.1.3/go.mod h1:scbssz8iZGpm3xbr14ovlUdkxfGXNInqkPWOWmG2CLw= +github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E= +github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c= +github.com/charmbracelet/log v0.2.1 h1:1z7jpkk4yKyjwlmKmKMM5qnEDSpV32E7XtWhuv0mTZE= +github.com/charmbracelet/log v0.2.1/go.mod h1:GwFfjewhcVDWLrpAbY5A0Hin9YOlEn40eWT4PNaxFT4= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chzyer/logex v1.2.0/go.mod h1:9+9sk7u7pGNWYMkh0hdiL++6OeibzJccyQU4p4MedaY= +github.com/chzyer/readline v1.5.0/go.mod h1:x22KAscuvRqlLoK9CsoYsmxoXZMMFVyOl86cAH8qUic= +github.com/chzyer/test v0.0.0-20210722231415-061457976a23/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= +github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dlclark/regexp2 v1.4.1-0.20201116162257-a2a8dda75c91/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc= +github.com/dlclark/regexp2 v1.7.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dlclark/regexp2 v1.9.0 h1:pTK/l/3qYIKaRXuHnEnIf7Y5NxfRPfpb7dis6/gdlVI= +github.com/dlclark/regexp2 v1.9.0/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8= +github.com/dop251/goja v0.0.0-20211022113120-dc8c55024d06/go.mod h1:R9ET47fwRVRPZnOGvHxxhuZcbrMCuiqOz3Rlrh4KSnk= +github.com/dop251/goja v0.0.0-20221118162653-d4bf6fde1b86/go.mod h1:yRkwfj0CBpOGre+TwBsqPV0IH0Pk73e4PXJOeNDboGs= +github.com/dop251/goja v0.0.0-20230402114112-623f9dda9079 h1:xkbJGxVnk5sM8/LXeTKaBOfAZrI+iqvIPyH8oK1c6CQ= +github.com/dop251/goja v0.0.0-20230402114112-623f9dda9079/go.mod h1:QMWlm50DNe14hD7t24KEqZuUdC9sOTy8W6XbCU1mlw4= +github.com/dop251/goja_nodejs v0.0.0-20210225215109-d91c329300e7/go.mod h1:hn7BA7c8pLvoGndExHudxTDKZ84Pyvv+90pbBjbTz0Y= +github.com/dop251/goja_nodejs v0.0.0-20211022123610-8dd9abb0616d/go.mod h1:DngW8aVqWbuLRMHItjPUyqdj+HWPvnQe8V8y1nDpIbM= +github.com/dop251/goja_nodejs v0.0.0-20230322100729-2550c7b6c124 h1:QDuDMgEkC/lnmvk0d/fZfcUUml18uUbS9TY5QtbdFhs= +github.com/dop251/goja_nodejs v0.0.0-20230322100729-2550c7b6c124/go.mod h1:0tlktQL7yHfYEtjcRGi/eiOkbDR5XF7gyFFvbC5//E0= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.0 h1:OjyFBKICoexlu99ctXNR2gg+c5pKrKMuyjgARg9qeY8= +github.com/gin-gonic/gin v1.9.0/go.mod h1:W1Me9+hsUSyj3CePGrd1/QrKJMSJ1Tu/0hFEH89961k= +github.com/glebarez/go-sqlite v1.20.3 h1:89BkqGOXR9oRmG58ZrzgoY/Fhy5x0M+/WV48U5zVrZ4= +github.com/glebarez/go-sqlite v1.20.3/go.mod h1:u3N6D/wftiAzIOJtZl6BmedqxmmkDfH3q+ihjqxC9u0= +github.com/glebarez/sqlite v1.7.0 h1:A7Xj/KN2Lvie4Z4rrgQHY8MsbebX3NyWsL3n2i82MVI= +github.com/glebarez/sqlite v1.7.0/go.mod h1:PkeevrRlF/1BhQBCnzcMWzgrIk7IOop+qS2jUYLfHhk= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU= +github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s= +github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= +github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible h1:W1iEw64niKVGogNgBN3ePyLFfuisuzeidWPMPWmECqU= +github.com/go-sourcemap/sourcemap v2.1.3+incompatible/go.mod h1:F8jJfvm2KbVjc5NqelyYJmf/v5J0dwNLS2mL4sNA1Jg= +github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA= +github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/pprof v0.0.0-20230207041349-798e818bf904/go.mod h1:uglQLonpP8qtYCYyzA+8c/9qtqgA3qsXGYqCPKARAFg= +github.com/google/pprof v0.0.0-20230406165453-00490a63f317 h1:hFhpt7CTmR3DX+b4R19ydQFtofxT0Sv3QsKNMVQYTMQ= +github.com/google/pprof v0.0.0-20230406165453-00490a63f317/go.mod h1:79YE0hCXdHag9sBkw2o+N/YnZtTkXi0UT9Nnixa5eYk= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1 h1:EGx4pi6eqNxGaHF6qqu48+N2wcFQ5qg5FXgOdqsJ5d8= +github.com/ianlancetaylor/demangle v0.0.0-20220319035150-800ac71e25c2/go.mod h1:aYm2/VgdVmcIU8iMfdMvDMsRAQjcfZSKFby6HOFvi/w= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo= +github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= +github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= +github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= +github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= +github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= +github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= +github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= +github.com/pandodao/tokenizer-go v0.2.0 h1:NhfI8fGvQkDld2cZCag6NEU3pJ/ugU9zoY1R/zi9YCs= +github.com/pandodao/tokenizer-go v0.2.0/go.mod h1:t6qFbaleKxbv0KNio2XUN/mfGM5WKv4haPXDQWVDG00= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= +github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= +github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= +github.com/sashabaranov/go-openai v1.12.0 h1:aRNHH0gtVfrpIaEolD0sWrLLRnYQNK4cH/bIAHwL8Rk= +github.com/sashabaranov/go-openai v1.12.0/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= +github.com/sbzhu/weworkapi_golang v0.0.0-20210525081115-1799804a7c8d h1:XGmsfwnqoYU4PIcLFusOe6mJWb6p9iuj1OT7b1/9diY= +github.com/sbzhu/weworkapi_golang v0.0.0-20210525081115-1799804a7c8d/go.mod h1:gLXVYg36wlOl44Uh8Uw0aDiNMcZNnV+tzZq1FBj+f6A= +github.com/smartystreets/assertions v1.2.0 h1:42S6lae5dvLc7BrLu/0ugRtcFVjoJNMC/N3yZFZkDFs= +github.com/smartystreets/goconvey v1.7.2 h1:9RBaZCeXEQ3UselpuwUQHltGVXvdwm6cv1hgR6gDIPg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.9 h1:rmenucSohSTiyL09Y+l2OCk+FrMxGMzho2+tjr5ticU= +github.com/ugorji/go/codec v1.2.9/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/xen0n/go-workwx v1.5.0 h1:4WwzeSteHdum6nSTXgnbsQCSPDjANf835n6bd7FSZk8= +github.com/xen0n/go-workwx v1.5.0/go.mod h1:hetBTiAve66rjnkOviqbfZ8faeWQTj5JofqEvpX5YOw= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= +golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.4.0/go.mod h1:MBQ8lrhLObU/6UmLb4fmbmk5OcyYmqtbGd/9yIeKjEE= +golang.org/x/net v0.10.0 h1:X2//UzNDwYmtCLn7To6G58Wr6f5ahEAQgKNzv9Y951M= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0 h1:EBmGv8NaZBZTWvrbjNoL6HVt+IVy3QDQpJs7VRIw3tU= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0 h1:2sjJmO8cDvYveuX97RDLsxlyUxLl+GHoLxBiRdHllBE= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= +google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gorm.io/gorm v1.24.6 h1:wy98aq9oFEetsc4CAbKD2SoBCdMzsbSIvSUUFJuHi5s= +gorm.io/gorm v1.24.6/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= +modernc.org/libc v1.22.3 h1:D/g6O5ftAfavceqlLOFwaZuA5KYafKwmr30A6iSqoyY= +modernc.org/libc v1.22.3/go.mod h1:MQrloYP209xa2zHome2a8HLiLm6k0UT8CoHpV74tOFw= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/sqlite v1.20.4 h1:J8+m2trkN+KKoE7jglyHYYYiaq5xmz2HoHJIiBlRzbE= +modernc.org/sqlite v1.20.4/go.mod h1:zKcGyrICaxNTMEHSr1HQ2GUraP0j+845GYw37+EyT6A= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/main.go b/main.go new file mode 100644 index 0000000..285f2f3 --- /dev/null +++ b/main.go @@ -0,0 +1,156 @@ +package main + +import ( + "context" + "fmt" + "net/http" + "os" + "os/signal" + "strings" + "time" + + "github.com/eryajf/chatgpt-wecom/pkg/logger" + "github.com/eryajf/chatgpt-wecom/pkg/process" + "github.com/eryajf/chatgpt-wecom/public" + "github.com/gin-gonic/gin" + "github.com/sbzhu/weworkapi_golang/wxbizmsgcrypt" + "github.com/xen0n/go-workwx" +) + +var wxclient *workwx.WorkwxApp + +func init() { + // 初始化加载配置,数据库,模板等 + public.InitSvc() + // 指定日志等级 + logger.InitLogger(public.Config.LogLevel) + var wx = workwx.New(public.Config.CorpId) + + wxclient = wx.WithApp(public.Config.AgentSecret, public.Config.AgentId) + wxclient.SpawnAccessTokenRefresher() // 自动刷新token +} + +func main() { + StartHttp() +} + +type dummyRxMessageHandler struct{} + +var _ workwx.RxMessageHandler = dummyRxMessageHandler{} + +// OnIncomingMessage 一条消息到来时的回调。 +func (dummyRxMessageHandler) OnIncomingMessage(msg *workwx.RxMessage) error { + go DoRequest(msg) + return nil +} + +func StartHttp() { + app := gin.Default() + app.GET("/*path", func(c *gin.Context) { + // 获取到请求参数 + msgSignature := c.Query("msg_signature") + timestamp := c.Query("timestamp") + nonce := c.Query("nonce") + echostr := c.Query("echostr") + + // 调用企业微信官方提供的接口进行解析校验 + wxcpt := wxbizmsgcrypt.NewWXBizMsgCrypt(public.Config.ReceiveMsgToken, public.Config.ReceiveMsgKey, public.Config.CorpId, wxbizmsgcrypt.XmlType) + echoStr, cryptErr := wxcpt.VerifyURL(msgSignature, timestamp, nonce, echostr) + if nil != cryptErr { + fmt.Println("verifyUrl fail", cryptErr) + } + c.String(200, string(echoStr)) + }) + hh, err := workwx.NewHTTPHandler(public.Config.ReceiveMsgToken, public.Config.ReceiveMsgKey, dummyRxMessageHandler{}) + if err != nil { + logger.Fatal("init http handler failed: ", err) + } + + app.POST("/*path", gin.WrapH(hh)) + port := ":" + public.Config.Port + srv := &http.Server{ + Addr: port, + Handler: app, + } + + // Initializing the server in a goroutine so that + // it won't block the graceful shutdown handling below + go func() { + logger.Info("🚀 The HTTP Server is running on", port) + if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { + logger.Fatal("listen: %s\n", err) + } + }() + + // Wait for interrupt signal to gracefully shutdown the server with + // a timeout of 5 seconds. + quit := make(chan os.Signal, 1) + // kill (no param) default send syscall.SIGTERM + // kill -2 is syscall.SIGINT + // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it + // signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM) + signal.Notify(quit, os.Interrupt) + <-quit + logger.Info("Shutting down server...") + + // 5秒后强制退出 + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := srv.Shutdown(ctx); err != nil { + logger.Fatal("Server forced to shutdown:", err) + } + logger.Info("Server exiting!") +} + +func DoRequest(msgObj *workwx.RxMessage) { + var msgInfo string + resp := &workwx.Recipient{UserIDs: []string{msgObj.FromUserID}} + if content, ok := msgObj.Text(); ok { + msgInfo = content.GetContent() + } + // 再校验回调参数是否有价值 + if msgInfo == "" { + logger.Warning("回调过来的内容为空,根据过往的经验,或许重新创建一下机器人,能解决这个问题") + return + } + // 去除问题的前后空格 + msgInfo = strings.TrimSpace(msgInfo) + if public.JudgeSensitiveWord(msgInfo) { + logger.Info(fmt.Sprintf("🙋 %s提问的问题中包含敏感词汇,userid:%#v,消息: %#v", msgObj.FromUserID, msgObj.FromUserID, msgInfo)) + return + } + // 打印企微回调过来的请求明细,调试时打开 + logger.Debug(fmt.Sprintf("wecom callback parameters: %#v", msgObj)) + + if !public.JudgeUsers(msgObj.FromUserID) && !public.JudgeAdminUsers(msgObj.FromUserID) && msgObj.FromUserID != "" { + logger.Info(fmt.Sprintf("🙋 %s身份信息未被验证通过,userid:%#v,消息: %#v", msgObj.FromUserID, msgObj.FromUserID, msgInfo)) + return + } + if len(msgInfo) == 0 || msgInfo == "帮助" { + + // 欢迎信息 + err := wxclient.SendMarkdownMessage(resp, public.Config.Help, false) + if err != nil { + fmt.Printf("send err:%v", err) + } + } else { + logger.Info(fmt.Sprintf("🙋 %s发起的问题: %#v", msgObj.FromUserID, msgInfo)) + // 除去帮助之外的逻辑分流在这里处理 + switch { + default: + var err error + msgInfo, err = process.GeneratePrompt(msgInfo) + // err不为空:提示词之后没有文本 -> 直接返回提示词所代表的内容 + if err != nil { + _ = wxclient.SendMarkdownMessage(resp, msgInfo, false) + return + } + err = process.ProcessRequest(msgObj, wxclient) + if err != nil { + logger.Warning(fmt.Errorf("process request: %v", err)) + return + } + return + } + } +} diff --git a/pkg/cache/user_base.go b/pkg/cache/user_base.go new file mode 100644 index 0000000..8f019c4 --- /dev/null +++ b/pkg/cache/user_base.go @@ -0,0 +1,44 @@ +package cache + +import ( + "time" + + "github.com/eryajf/chatgpt-wecom/config" + "github.com/patrickmn/go-cache" +) + +// UserServiceInterface 用户业务接口 +type UserServiceInterface interface { + // 用户聊天模式 + GetUserMode(userId string) string + SetUserMode(userId, mode string) + ClearUserMode(userId string) + // 用户聊天上下文 + GetUserSessionContext(userId string) string + SetUserSessionContext(userId, content string) + ClearUserSessionContext(userId string) + // 用户请求次数 + SetUseRequestCount(userId string, current int) + GetUseRequestCount(uerId string) int + // 用户对话ID + SetAnswerID(userId, chattype string, current uint) + GetAnswerID(uerId, chattype string) uint + ClearAnswerID(userId, chattitle string) +} + +var _ UserServiceInterface = (*UserService)(nil) + +// UserService 用戶业务 +type UserService struct { + // 缓存 + cache *cache.Cache +} + +var Config *config.Configuration + +// NewUserService 创建新的业务层 +func NewUserService() UserServiceInterface { + // 加载配置 + Config = config.LoadConfig() + return &UserService{cache: cache.New(Config.SessionTimeout, time.Hour*1)} +} diff --git a/pkg/cache/user_chatid.go b/pkg/cache/user_chatid.go new file mode 100644 index 0000000..291546b --- /dev/null +++ b/pkg/cache/user_chatid.go @@ -0,0 +1,22 @@ +package cache + +import "time" + +// SetAnswerID 设置用户获得答案的ID +func (s *UserService) SetAnswerID(userId, chattitle string, current uint) { + s.cache.Set(userId+"_"+chattitle, current, time.Hour*24) +} + +// GetAnswerID 获取当前用户获得答案的ID +func (s *UserService) GetAnswerID(userId, chattitle string) uint { + sessionContext, ok := s.cache.Get(userId + "_" + chattitle) + if !ok { + return 0 + } + return sessionContext.(uint) +} + +// ClearUserSessionContext 清空GPT上下文,接收文本中包含 SessionClearToken +func (s *UserService) ClearAnswerID(userId, chattitle string) { + s.cache.Delete(userId + "_" + chattitle) +} diff --git a/pkg/cache/user_context.go b/pkg/cache/user_context.go new file mode 100644 index 0000000..b053d29 --- /dev/null +++ b/pkg/cache/user_context.go @@ -0,0 +1,22 @@ +package cache + +import "github.com/patrickmn/go-cache" + +// SetUserSessionContext 设置用户会话上下文文本,question用户提问内容,GPT回复内容 +func (s *UserService) SetUserSessionContext(userId string, content string) { + s.cache.Set(userId+"_content", content, cache.DefaultExpiration) +} + +// GetUserSessionContext 获取用户会话上下文文本 +func (s *UserService) GetUserSessionContext(userId string) string { + sessionContext, ok := s.cache.Get(userId + "_content") + if !ok { + return "" + } + return sessionContext.(string) +} + +// ClearUserSessionContext 清空GPT上下文,接收文本中包含 SessionClearToken +func (s *UserService) ClearUserSessionContext(userId string) { + s.cache.Delete(userId + "_content") +} diff --git a/pkg/cache/user_mode.go b/pkg/cache/user_mode.go new file mode 100644 index 0000000..dca62b2 --- /dev/null +++ b/pkg/cache/user_mode.go @@ -0,0 +1,22 @@ +package cache + +import "github.com/patrickmn/go-cache" + +// GetUserMode 获取当前对话模式 +func (s *UserService) GetUserMode(userId string) string { + sessionContext, ok := s.cache.Get(userId + "_mode") + if !ok { + return "" + } + return sessionContext.(string) +} + +// SetUserMode 设置用户对话模式 +func (s *UserService) SetUserMode(userId string, mode string) { + s.cache.Set(userId+"_mode", mode, cache.DefaultExpiration) +} + +// ClearUserMode 重置用户对话模式 +func (s *UserService) ClearUserMode(userId string) { + s.cache.Delete(userId + "_mode") +} diff --git a/pkg/cache/user_requese.go b/pkg/cache/user_requese.go new file mode 100644 index 0000000..0d92bda --- /dev/null +++ b/pkg/cache/user_requese.go @@ -0,0 +1,22 @@ +package cache + +import ( + "time" +) + +// SetUseRequestCount 设置用户请求次数 +func (s *UserService) SetUseRequestCount(userId string, current int) { + expiration := time.Now().Add(time.Hour * 24).Truncate(time.Hour * 24) + duration := expiration.Sub(time.Now()) + // 设置缓存失效时间为第二天零点 + s.cache.Set(userId+"_request", current, duration) +} + +// GetUseRequestCount 获取当前用户已请求次数 +func (s *UserService) GetUseRequestCount(userId string) int { + sessionContext, ok := s.cache.Get(userId + "_request") + if !ok { + return 0 + } + return sessionContext.(int) +} diff --git a/pkg/chatgpt/LICENSE b/pkg/chatgpt/LICENSE new file mode 100644 index 0000000..f47f42e --- /dev/null +++ b/pkg/chatgpt/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022 Shihao + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/pkg/chatgpt/README.md b/pkg/chatgpt/README.md new file mode 100644 index 0000000..a16226f --- /dev/null +++ b/pkg/chatgpt/README.md @@ -0,0 +1 @@ +> 因为三方包写死了很多参数,这里转到本地,便于二次改造。 感谢:https://github.com/solywsh/chatgpt diff --git a/pkg/chatgpt/chatgpt.go b/pkg/chatgpt/chatgpt.go new file mode 100644 index 0000000..67446fe --- /dev/null +++ b/pkg/chatgpt/chatgpt.go @@ -0,0 +1,87 @@ +package chatgpt + +import ( + "context" + "net/http" + "net/url" + "time" + + "github.com/eryajf/chatgpt-wecom/public" + openai "github.com/sashabaranov/go-openai" +) + +type ChatGPT struct { + client *openai.Client + ctx context.Context + userId string + maxQuestionLen int + maxText int + maxAnswerLen int + timeOut time.Duration // 超时时间, 0表示不超时 + doneChan chan struct{} + cancel func() + + ChatContext *ChatContext +} + +func New(userId string) *ChatGPT { + var ctx context.Context + var cancel func() + + ctx, cancel = context.WithTimeout(context.Background(), 600*time.Second) + timeOutChan := make(chan struct{}, 1) + go func() { + <-ctx.Done() + timeOutChan <- struct{}{} // 发送超时信号,或是提示结束,用于聊天机器人场景,配合GetTimeOutChan() 使用 + }() + + config := openai.DefaultConfig(public.Config.ApiKey) + if public.Config.AzureOn { + config = openai.DefaultAzureConfig( + public.Config.AzureOpenAIToken, + "https://"+public.Config.AzureResourceName+".openai."+ + "azure.com/", + ) + } else { + if public.Config.HttpProxy != "" { + config.HTTPClient.Transport = &http.Transport{ + // 设置代理 + Proxy: func(req *http.Request) (*url.URL, error) { + return url.Parse(public.Config.HttpProxy) + }} + } + if public.Config.BaseURL != "" { + config.BaseURL = public.Config.BaseURL + "/v1" + } + } + + return &ChatGPT{ + client: openai.NewClientWithConfig(config), + ctx: ctx, + userId: userId, + maxQuestionLen: public.Config.MaxQuestionLen, // 最大问题长度 + maxAnswerLen: public.Config.MaxAnswerLen, // 最大答案长度 + maxText: public.Config.MaxText, // 最大文本 = 问题 + 回答, 接口限制 + timeOut: public.Config.SessionTimeout, + doneChan: timeOutChan, + cancel: func() { + cancel() + }, + ChatContext: NewContext(), + } +} +func (c *ChatGPT) Close() { + c.cancel() +} + +func (c *ChatGPT) GetDoneChan() chan struct{} { + return c.doneChan +} + +func (c *ChatGPT) SetMaxQuestionLen(maxQuestionLen int) int { + if maxQuestionLen > c.maxText-c.maxAnswerLen { + maxQuestionLen = c.maxText - c.maxAnswerLen + } + c.maxQuestionLen = maxQuestionLen + return c.maxQuestionLen +} diff --git a/pkg/chatgpt/chatgpt_test.go b/pkg/chatgpt/chatgpt_test.go new file mode 100644 index 0000000..73c6760 --- /dev/null +++ b/pkg/chatgpt/chatgpt_test.go @@ -0,0 +1,31 @@ +package chatgpt + +import ( + "fmt" + "testing" +) + +func TestChatGPT_ChatWithContext(t *testing.T) { + chat := New("") + defer chat.Close() + //go func() { + // select { + // case <-chat.GetDoneChan(): + // fmt.Println("time out") + // } + //}() + question := "现在你是一只猫,接下来你只能用\"喵喵喵\"回答." + fmt.Printf("Q: %s\n", question) + answer, err := chat.ChatWithContext(question) + if err != nil { + fmt.Println(err) + } + fmt.Printf("A: %s\n", answer) + question = "你是一只猫吗?" + fmt.Printf("Q: %s\n", question) + answer, err = chat.ChatWithContext(question) + if err != nil { + fmt.Println(err) + } + fmt.Printf("A: %s\n", answer) +} diff --git a/pkg/chatgpt/context.go b/pkg/chatgpt/context.go new file mode 100644 index 0000000..ffa84ed --- /dev/null +++ b/pkg/chatgpt/context.go @@ -0,0 +1,309 @@ +package chatgpt + +import ( + "bytes" + "encoding/gob" + "strings" + + "github.com/pandodao/tokenizer-go" + + "github.com/eryajf/chatgpt-wecom/public" + openai "github.com/sashabaranov/go-openai" +) + +var ( + DefaultAiRole = "AI" + DefaultHumanRole = "Human" + + DefaultCharacter = []string{"helpful", "creative", "clever", "friendly", "lovely", "talkative"} + DefaultBackground = "The following is a conversation with AI assistant. The assistant is %s" + DefaultPreset = "\n%s: 你好,让我们开始愉快的谈话!\n%s: 我是 AI assistant ,请问你有什么问题?" +) + +type ( + ChatContext struct { + background string // 对话背景 + preset string // 预设对话 + maxSeqTimes int // 最大对话次数 + aiRole *role // AI角色 + humanRole *role // 人类角色 + + old []conversation // 旧对话 + restartSeq string // 重新开始对话的标识 + startSeq string // 开始对话的标识 + + seqTimes int // 对话次数 + + maintainSeqTimes bool // 是否维护对话次数 (自动移除旧对话) + } + + ChatContextOption func(*ChatContext) + + conversation struct { + Role *role + Prompt string + } + + role struct { + Name string + } +) + +func NewContext(options ...ChatContextOption) *ChatContext { + ctx := &ChatContext{ + aiRole: &role{Name: DefaultAiRole}, + humanRole: &role{Name: DefaultHumanRole}, + background: "", + maxSeqTimes: 1000, + preset: "", + old: []conversation{}, + seqTimes: 0, + restartSeq: "\n" + DefaultHumanRole + ": ", + startSeq: "\n" + DefaultAiRole + ": ", + maintainSeqTimes: false, + } + + for _, option := range options { + option(ctx) + } + return ctx +} + +// PollConversation 移除最旧的一则对话 +func (c *ChatContext) PollConversation() { + c.old = c.old[1:] + c.seqTimes-- +} + +// ResetConversation 重置对话 +func (c *ChatContext) ResetConversation(userid string) { + public.UserService.ClearUserSessionContext(userid) +} + +// SaveConversation 保存对话 +func (c *ChatContext) SaveConversation(userid string) error { + var buffer bytes.Buffer + enc := gob.NewEncoder(&buffer) + err := enc.Encode(c.old) + if err != nil { + return err + } + public.UserService.SetUserSessionContext(userid, buffer.String()) + return nil +} + +// LoadConversation 加载对话 +func (c *ChatContext) LoadConversation(userid string) error { + dec := gob.NewDecoder(strings.NewReader(public.UserService.GetUserSessionContext(userid))) + err := dec.Decode(&c.old) + if err != nil { + return err + } + c.seqTimes = len(c.old) + return nil +} + +func (c *ChatContext) SetHumanRole(role string) { + c.humanRole.Name = role + c.restartSeq = "\n" + c.humanRole.Name + ": " +} + +func (c *ChatContext) SetAiRole(role string) { + c.aiRole.Name = role + c.startSeq = "\n" + c.aiRole.Name + ": " +} + +func (c *ChatContext) SetMaxSeqTimes(times int) { + c.maxSeqTimes = times +} + +func (c *ChatContext) GetMaxSeqTimes() int { + return c.maxSeqTimes +} + +func (c *ChatContext) SetBackground(background string) { + c.background = background +} + +func (c *ChatContext) SetPreset(preset string) { + c.preset = preset +} + +func (c *ChatGPT) ChatWithContext(question string) (answer string, err error) { + question = question + "." + if tokenizer.MustCalToken(question) > c.maxQuestionLen { + return "", OverMaxQuestionLength + } + if c.ChatContext.seqTimes >= c.ChatContext.maxSeqTimes { + if c.ChatContext.maintainSeqTimes { + c.ChatContext.PollConversation() + } else { + return "", OverMaxSequenceTimes + } + } + var promptTable []string + promptTable = append(promptTable, c.ChatContext.background) + promptTable = append(promptTable, c.ChatContext.preset) + for _, v := range c.ChatContext.old { + if v.Role == c.ChatContext.humanRole { + promptTable = append(promptTable, "\n"+v.Role.Name+": "+v.Prompt) + } else { + promptTable = append(promptTable, v.Role.Name+": "+v.Prompt) + } + } + promptTable = append(promptTable, "\n"+c.ChatContext.restartSeq+question) + prompt := strings.Join(promptTable, "\n") + prompt += c.ChatContext.startSeq + // 删除对话,直到prompt的长度满足条件 + for tokenizer.MustCalToken(prompt) > c.maxText { + if len(c.ChatContext.old) > 1 { // 至少保留一条记录 + c.ChatContext.PollConversation() // 删除最旧的一条对话 + // 重新构建 prompt,计算长度 + promptTable = promptTable[1:] // 删除promptTable中对应的对话 + prompt = strings.Join(promptTable, "\n") + c.ChatContext.startSeq + } else { + break // 如果已经只剩一条记录,那么跳出循环 + } + } + // if tokenizer.MustCalToken(prompt) > c.maxText-c.maxAnswerLen { + // return "", OverMaxTextLength + // } + model := public.Config.Model + userId := c.userId + if public.Config.AzureOn { + userId = "" + } + if model == openai.GPT3Dot5Turbo || model == openai.GPT3Dot5Turbo0301 || model == openai.GPT3Dot5Turbo0613 || + model == openai.GPT3Dot5Turbo16K || model == openai.GPT3Dot5Turbo16K0613 || + model == openai.GPT4 || model == openai.GPT40314 || model == openai.GPT40613 || + model == openai.GPT432K || model == openai.GPT432K0314 || model == openai.GPT432K0613 { + req := openai.ChatCompletionRequest{ + Model: model, + Messages: []openai.ChatCompletionMessage{ + { + Role: "user", + Content: prompt, + }, + }, + MaxTokens: c.maxAnswerLen, + Temperature: 0.6, + User: userId, + } + resp, err := c.client.CreateChatCompletion(c.ctx, req) + if err != nil { + return "", err + } + resp.Choices[0].Message.Content = formatAnswer(resp.Choices[0].Message.Content) + c.ChatContext.old = append(c.ChatContext.old, conversation{ + Role: c.ChatContext.humanRole, + Prompt: question, + }) + c.ChatContext.old = append(c.ChatContext.old, conversation{ + Role: c.ChatContext.aiRole, + Prompt: resp.Choices[0].Message.Content, + }) + c.ChatContext.seqTimes++ + return resp.Choices[0].Message.Content, nil + } else { + req := openai.CompletionRequest{ + Model: model, + MaxTokens: c.maxAnswerLen, + Prompt: prompt, + Temperature: 0.6, + User: c.userId, + Stop: []string{c.ChatContext.aiRole.Name + ":", c.ChatContext.humanRole.Name + ":"}, + } + resp, err := c.client.CreateCompletion(c.ctx, req) + if err != nil { + return "", err + } + resp.Choices[0].Text = formatAnswer(resp.Choices[0].Text) + c.ChatContext.old = append(c.ChatContext.old, conversation{ + Role: c.ChatContext.humanRole, + Prompt: question, + }) + c.ChatContext.old = append(c.ChatContext.old, conversation{ + Role: c.ChatContext.aiRole, + Prompt: resp.Choices[0].Text, + }) + c.ChatContext.seqTimes++ + return resp.Choices[0].Text, nil + } +} + +// func (c *ChatGPT) GenreateImage(ctx context.Context, prompt string) (string, error) { +// model := public.Config.Model +// if model == openai.GPT3Dot5Turbo || model == openai.GPT3Dot5Turbo0301 || model == openai.GPT3Dot5Turbo0613 || +// model == openai.GPT3Dot5Turbo16K || model == openai.GPT3Dot5Turbo16K0613 || +// model == openai.GPT4 || model == openai.GPT40314 || model == openai.GPT40613 || +// model == openai.GPT432K || model == openai.GPT432K0314 || model == openai.GPT432K0613 { +// req := openai.ImageRequest{ +// Prompt: prompt, +// Size: openai.CreateImageSize1024x1024, +// ResponseFormat: openai.CreateImageResponseFormatB64JSON, +// N: 1, +// User: c.userId, +// } +// respBase64, err := c.client.CreateImage(c.ctx, req) +// if err != nil { +// return "", err +// } +// imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON) +// if err != nil { +// return "", err +// } + +// r := bytes.NewReader(imgBytes) +// imgData, err := png.Decode(r) +// if err != nil { +// return "", err +// } + +// imageName := time.Now().Format("20060102-150405") + ".png" +// clientId, _ := ctx.Value(public.DingTalkClientIdKeyName).(string) +// client := public.DingTalkClientManager.GetClientByOAuthClientID(clientId) +// mediaResult, uploadErr := &dingbot.MediaUploadResult{}, errors.New(fmt.Sprintf("unknown clientId: %s", clientId)) +// if client != nil { +// mediaResult, uploadErr = client.UploadMedia(imgBytes, imageName, dingbot.MediaTypeImage, dingbot.MimeTypeImagePng) +// } + +// err = os.MkdirAll("data/images", 0755) +// if err != nil { +// return "", err +// } +// file, err := os.Create("data/images/" + imageName) +// if err != nil { +// return "", err +// } +// defer file.Close() + +// if err := png.Encode(file, imgData); err != nil { +// return "", err +// } +// if uploadErr == nil { +// return mediaResult.MediaID, nil +// } else { +// return public.Config.ServiceURL + "/images/" + imageName, nil +// } +// } +// return "", nil +// } + +func WithMaxSeqTimes(times int) ChatContextOption { + return func(c *ChatContext) { + c.SetMaxSeqTimes(times) + } +} + +// WithOldConversation 从文件中加载对话 +func WithOldConversation(userid string) ChatContextOption { + return func(c *ChatContext) { + _ = c.LoadConversation(userid) + } +} + +func WithMaintainSeqTimes(maintain bool) ChatContextOption { + return func(c *ChatContext) { + c.maintainSeqTimes = maintain + } +} diff --git a/pkg/chatgpt/context_test.go b/pkg/chatgpt/context_test.go new file mode 100644 index 0000000..36e6d1a --- /dev/null +++ b/pkg/chatgpt/context_test.go @@ -0,0 +1,81 @@ +package chatgpt + +import ( + "os" + "testing" +) + +func TestOfflineContext(t *testing.T) { + key := os.Getenv("CHATGPT_API_KEY") + if key == "" { + t.Skip("CHATGPT_API_KEY is not set") + } + cli := New("") + reply, err := cli.ChatWithContext("我叫老三,你是?") + if err != nil { + t.Fatal(err) + } + + t.Logf("我叫老三,你是? => %s", reply) + + err = cli.ChatContext.SaveConversation("test.conversation") + if err != nil { + t.Fatalf("储存对话记录失败: %v", err) + } + cli.ChatContext.ResetConversation("") + + reply, err = cli.ChatWithContext("你知道我是谁吗?") + if err != nil { + t.Fatal(err) + } + + t.Logf("你知道我是谁吗? => %s", reply) + // assert.NotContains(t, reply, "老三") + + err = cli.ChatContext.LoadConversation("test.conversation") + if err != nil { + t.Fatalf("读取对话记录失败: %v", err) + } + + reply, err = cli.ChatWithContext("你知道我是谁吗?") + if err != nil { + t.Fatal(err) + } + + t.Logf("你知道我是谁吗? => %s", reply) + + // AI 理应知道他叫老三 + // assert.Contains(t, reply, "老三") +} + +func TestMaintainContext(t *testing.T) { + key := os.Getenv("CHATGPT_API_KEY") + if key == "" { + t.Skip("CHATGPT_API_KEY is not set") + } + cli := New("") + cli.ChatContext = NewContext( + WithMaxSeqTimes(1), + WithMaintainSeqTimes(true), + ) + + reply, err := cli.ChatWithContext("我叫老三,你是?") + if err != nil { + t.Fatal(err) + } + t.Logf("我叫老三,你是? => %s", reply) + + reply, err = cli.ChatWithContext("你知道我是谁吗?") + if err != nil { + t.Fatal(err) + } + t.Logf("你知道我是谁吗? => %s", reply) + + // 对话次数已经超过 1 次,因此最先前的对话已被移除,AI 理应不知道他叫老三 + // assert.NotContains(t, reply, "老三") +} + +func init() { + // 本地加载适用于本地测试,如果要在github进行测试,可以透过传入 secrets 到环境参数 + // _ = godotenv.Load(".env.local") +} diff --git a/pkg/chatgpt/errors.go b/pkg/chatgpt/errors.go new file mode 100644 index 0000000..8c5713f --- /dev/null +++ b/pkg/chatgpt/errors.go @@ -0,0 +1,12 @@ +package chatgpt + +import "errors" + +// OverMaxSequenceTimes 超过最大对话时间 +var OverMaxSequenceTimes = errors.New("maximum conversation times exceeded") + +// OverMaxTextLength 超过最大文本长度 +var OverMaxTextLength = errors.New("maximum text length exceeded") + +// OverMaxQuestionLength 超过最大问题长度 +var OverMaxQuestionLength = errors.New("maximum question length exceeded") diff --git a/pkg/chatgpt/export.go b/pkg/chatgpt/export.go new file mode 100644 index 0000000..cad31aa --- /dev/null +++ b/pkg/chatgpt/export.go @@ -0,0 +1,81 @@ +package chatgpt + +import ( + "time" + + "github.com/avast/retry-go" + "github.com/eryajf/chatgpt-wecom/pkg/logger" + "github.com/eryajf/chatgpt-wecom/public" +) + +// SingleQa 单聊 +func SingleQa(question, userId string) (answer string, err error) { + chat := New(userId) + defer chat.Close() + // 定义一个重试策略 + retryStrategy := []retry.Option{ + retry.Delay(100 * time.Millisecond), + retry.Attempts(3), + retry.LastErrorOnly(true), + } + // 使用重试策略进行重试 + err = retry.Do( + func() error { + answer, err = chat.ChatWithContext(question) + if err != nil { + return err + } + return nil + }, + retryStrategy...) + return +} + +// ContextQa 串聊 +func ContextQa(question, userId string) (chat *ChatGPT, answer string, err error) { + chat = New(userId) + if public.UserService.GetUserSessionContext(userId) != "" { + err := chat.ChatContext.LoadConversation(userId) + if err != nil { + logger.Warning("load station failed: %v\n", err) + } + } + retryStrategy := []retry.Option{ + retry.Delay(100 * time.Millisecond), + retry.Attempts(3), + retry.LastErrorOnly(true)} + // 使用重试策略进行重试 + err = retry.Do( + func() error { + answer, err = chat.ChatWithContext(question) + if err != nil { + return err + } + return nil + }, + retryStrategy...) + return +} + +// ImageQa 生成图片 +// func ImageQa(ctx context.Context, question, userId string) (answer string, err error) { +// chat := New(userId) +// defer chat.Close() +// // 定义一个重试策略 +// retryStrategy := []retry.Option{ +// retry.Delay(100 * time.Millisecond), +// retry.Attempts(3), +// retry.LastErrorOnly(true), +// } +// // 使用重试策略进行重试 +// err = retry.Do( +// func() error { +// answer, err = chat.GenreateImage(ctx, question) +// if err != nil { +// return err +// } +// return nil +// }, +// retryStrategy...) +// return +// } diff --git a/pkg/chatgpt/format.go b/pkg/chatgpt/format.go new file mode 100644 index 0000000..492e5e2 --- /dev/null +++ b/pkg/chatgpt/format.go @@ -0,0 +1,12 @@ +package chatgpt + +func formatAnswer(answer string) string { + for len(answer) > 0 { + if answer[:1] == "\n" || answer[0] == ' ' { + answer = answer[1:] + } else { + break + } + } + return answer +} diff --git a/pkg/chatgpt/go.mod b/pkg/chatgpt/go.mod new file mode 100644 index 0000000..a900b85 --- /dev/null +++ b/pkg/chatgpt/go.mod @@ -0,0 +1,41 @@ +module chatgpt + +go 1.18 + +require ( + github.com/avast/retry-go v3.0.0+incompatible + github.com/eryajf/chatgpt-wecom v1.0.11 + github.com/sashabaranov/go-openai v1.6.1 +) + +replace github.com/eryajf/chatgpt-wecom v1.0.11 => ../.. + +require ( + github.com/aymanbagabas/go-osc52/v2 v2.0.1 // indirect + github.com/charmbracelet/lipgloss v0.7.1 // indirect + github.com/charmbracelet/log v0.2.1 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/glebarez/go-sqlite v1.20.3 // indirect + github.com/glebarez/sqlite v1.7.0 // indirect + github.com/go-logfmt/logfmt v0.6.0 // indirect + github.com/go-resty/resty/v2 v2.7.0 // indirect + github.com/google/uuid v1.3.0 // indirect + github.com/jinzhu/inflection v1.0.0 // indirect + github.com/jinzhu/now v1.1.5 // indirect + github.com/lucasb-eyer/go-colorful v1.2.0 // indirect + github.com/mattn/go-isatty v0.0.18 // indirect + github.com/mattn/go-runewidth v0.0.14 // indirect + github.com/muesli/reflow v0.3.0 // indirect + github.com/muesli/termenv v0.15.1 // indirect + github.com/patrickmn/go-cache v2.1.0+incompatible // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578 // indirect + github.com/rivo/uniseg v0.2.0 // indirect + golang.org/x/net v0.0.0-20211029224645-99673261e6eb // indirect + golang.org/x/sys v0.6.0 // indirect + gopkg.in/yaml.v2 v2.4.0 // indirect + gorm.io/gorm v1.24.6 // indirect + modernc.org/libc v1.22.2 // indirect + modernc.org/mathutil v1.5.0 // indirect + modernc.org/memory v1.5.0 // indirect + modernc.org/sqlite v1.20.3 // indirect +) diff --git a/pkg/chatgpt/go.sum b/pkg/chatgpt/go.sum new file mode 100644 index 0000000..839c03e --- /dev/null +++ b/pkg/chatgpt/go.sum @@ -0,0 +1,73 @@ +github.com/avast/retry-go v3.0.0+incompatible h1:4SOWQ7Qs+oroOTQOYnAHqelpCO0biHSxpiH9JdtuBj0= +github.com/avast/retry-go v3.0.0+incompatible/go.mod h1:XtSnn+n/sHqQIpZ10K1qAevBhOOCWBLXXy3hyiqqBrY= +github.com/aymanbagabas/go-osc52/v2 v2.0.1 h1:HwpRHbFMcZLEVr42D4p7XBqjyuxQH5SMiErDT4WkJ2k= +github.com/aymanbagabas/go-osc52/v2 v2.0.1/go.mod h1:uYgXzlJ7ZpABp8OJ+exZzJJhRNQ2ASbcXHWsFqH8hp8= +github.com/charmbracelet/lipgloss v0.7.1 h1:17WMwi7N1b1rVWOjMT+rCh7sQkvDU75B2hbZpc5Kc1E= +github.com/charmbracelet/lipgloss v0.7.1/go.mod h1:yG0k3giv8Qj8edTCbbg6AlQ5e8KNWpFujkNawKNhE2c= +github.com/charmbracelet/log v0.2.1 h1:1z7jpkk4yKyjwlmKmKMM5qnEDSpV32E7XtWhuv0mTZE= +github.com/charmbracelet/log v0.2.1/go.mod h1:GwFfjewhcVDWLrpAbY5A0Hin9YOlEn40eWT4PNaxFT4= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/glebarez/go-sqlite v1.20.3 h1:89BkqGOXR9oRmG58ZrzgoY/Fhy5x0M+/WV48U5zVrZ4= +github.com/glebarez/go-sqlite v1.20.3/go.mod h1:u3N6D/wftiAzIOJtZl6BmedqxmmkDfH3q+ihjqxC9u0= +github.com/glebarez/sqlite v1.7.0 h1:A7Xj/KN2Lvie4Z4rrgQHY8MsbebX3NyWsL3n2i82MVI= +github.com/glebarez/sqlite v1.7.0/go.mod h1:PkeevrRlF/1BhQBCnzcMWzgrIk7IOop+qS2jUYLfHhk= +github.com/go-logfmt/logfmt v0.6.0 h1:wGYYu3uicYdqXVgoYbvnkrPVXkuLM1p1ifugDMEdRi4= +github.com/go-logfmt/logfmt v0.6.0/go.mod h1:WYhtIu8zTZfxdn5+rREduYbwxfcBr/Vr6KEVveWlfTs= +github.com/go-resty/resty/v2 v2.7.0 h1:me+K9p3uhSmXtrBZ4k9jcEAfJmuC8IivWHwaLZwPrFY= +github.com/go-resty/resty/v2 v2.7.0/go.mod h1:9PWDzw47qPphMRFfhsyk0NnSgvluHcljSMVIq3w7q0I= +github.com/google/pprof v0.0.0-20221118152302-e6195bd50e26 h1:Xim43kblpZXfIBQsbuBVKCudVG457BR2GZFIz3uw3hQ= +github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I= +github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E= +github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc= +github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ= +github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8= +github.com/lucasb-eyer/go-colorful v1.2.0 h1:1nnpGOrhyZZuNyfu1QjKiUICQ74+3FNCN69Aj6K7nkY= +github.com/lucasb-eyer/go-colorful v1.2.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0= +github.com/mattn/go-isatty v0.0.18 h1:DOKFKCQ7FNG2L1rbrmstDN4QVRdS89Nkh85u68Uwp98= +github.com/mattn/go-isatty v0.0.18/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk= +github.com/mattn/go-runewidth v0.0.14 h1:+xnbZSEeDbOIg5/mE6JF0w6n9duR1l3/WmbinWVwUuU= +github.com/mattn/go-runewidth v0.0.14/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w= +github.com/muesli/reflow v0.3.0 h1:IFsN6K9NfGtjeggFP+68I4chLZV2yIKsXJFNZ+eWh6s= +github.com/muesli/reflow v0.3.0/go.mod h1:pbwTDkVPibjO2kyvBQRBxTWEEGDGq0FlB1BIKtnHY/8= +github.com/muesli/termenv v0.15.1 h1:UzuTb/+hhlBugQz28rpzey4ZuKcZ03MeKsoG7IJZIxs= +github.com/muesli/termenv v0.15.1/go.mod h1:HeAQPTzpfs016yGtA4g00CsdYnVLJvxsS4ANqrZs2sQ= +github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc= +github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/remyoudompheng/bigfft v0.0.0-20200410134404-eec4a21b6bb0/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578 h1:VstopitMQi3hZP0fzvnsLmzXZdQGc4bEcgu24cp+d4M= +github.com/remyoudompheng/bigfft v0.0.0-20230126093431-47fa9a501578/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY= +github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc= +github.com/sashabaranov/go-openai v1.6.1 h1:cALA9G00gPapNqun8vVBFGsDssywpU6wys4BpQ0bWqY= +github.com/sashabaranov/go-openai v1.6.1/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg= +github.com/stretchr/testify v1.8.2 h1:+h33VjcLVPDHtOdpUCuF+7gSuG3yGIftsP1YvFihtJ8= +golang.org/x/net v0.0.0-20211029224645-99673261e6eb h1:pirldcYWx7rx7kE5r+9WsOXPXK0+WH5+uZ7uPmJ44uM= +golang.org/x/net v0.0.0-20211029224645-99673261e6eb/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.6.0 h1:MVltZSvRTcU2ljQOhs94SXPftV6DCNnZViHeQps87pQ= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= +gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gorm.io/gorm v1.24.6 h1:wy98aq9oFEetsc4CAbKD2SoBCdMzsbSIvSUUFJuHi5s= +gorm.io/gorm v1.24.6/go.mod h1:L4uxeKpfBml98NYqVqwAdmV1a2nBtAec/cf3fpucW/k= +modernc.org/libc v1.22.2 h1:4U7v51GyhlWqQmwCHj28Rdq2Yzwk55ovjFrdPjs8Hb0= +modernc.org/libc v1.22.2/go.mod h1:uvQavJ1pZ0hIoC/jfqNoMLURIMhKzINIWypNM17puug= +modernc.org/mathutil v1.5.0 h1:rV0Ko/6SfM+8G+yKiyI830l3Wuz1zRutdslNoQ0kfiQ= +modernc.org/mathutil v1.5.0/go.mod h1:mZW8CKdRPY1v87qxC/wUdX5O1qDzXMP5TH3wjfpga6E= +modernc.org/memory v1.5.0 h1:N+/8c5rE6EqugZwHii4IFsaJ7MUhoWX07J5tC/iI5Ds= +modernc.org/memory v1.5.0/go.mod h1:PkUhL0Mugw21sHPeskwZW4D6VscE/GQJOnIpCnW6pSU= +modernc.org/sqlite v1.20.3 h1:SqGJMMxjj1PHusLxdYxeQSodg7Jxn9WWkaAQjKrntZs= +modernc.org/sqlite v1.20.3/go.mod h1:zKcGyrICaxNTMEHSr1HQ2GUraP0j+845GYw37+EyT6A= diff --git a/pkg/db/chat.go b/pkg/db/chat.go new file mode 100644 index 0000000..76d48d6 --- /dev/null +++ b/pkg/db/chat.go @@ -0,0 +1,63 @@ +package db + +import ( + "errors" + "strings" + + "gorm.io/gorm" +) + +type ChatType uint + +const Q ChatType = 1 +const A ChatType = 2 + +type Chat struct { + gorm.Model + Username string `gorm:"type:varchar(50);not null;comment:'用户名'" json:"username"` // 用户名 + Source string `gorm:"type:varchar(50);comment:'用户来源:群聊名字,私聊'" json:"source"` // 对话来源 + ChatType ChatType `gorm:"type:tinyint(1);default:1;comment:'类型:1问, 2答'" json:"chat_type"` // 状态 + ParentContent uint `gorm:"default:0;comment:'父消息编号(编号为0时表示为首条)'" json:"parent_content"` + Content string `gorm:"type:varchar(128);comment:'内容'" json:"content"` // 问题或回答的内容 +} + +type ChatListReq struct { + Username string `json:"username" form:"username"` + Source string `json:"source" form:"source"` +} + +// Add 添加资源 +func (c Chat) Add() (uint, error) { + err := DB.Create(&c).Error + return c.ID, err +} + +// Find 获取单个资源 +func (c Chat) Find(filter map[string]interface{}, data *Chat) error { + return DB.Where(filter).First(&data).Error +} + +// List 获取数据列表 +func (c Chat) List(req ChatListReq) ([]*Chat, error) { + var list []*Chat + db := DB.Model(&Chat{}).Order("created_at ASC") + + userName := strings.TrimSpace(req.Username) + if userName != "" { + db = db.Where("username = ?", userName) + } + source := strings.TrimSpace(req.Source) + if source != "" { + db = db.Where("source = ?", source) + } + + err := db.Find(&list).Error + return list, err +} + +// Exist 判断资源是否存在 +func (c Chat) Exist(filter map[string]interface{}) bool { + var dataObj Chat + err := DB.Where(filter).First(&dataObj).Error + return !errors.Is(err, gorm.ErrRecordNotFound) +} diff --git a/pkg/db/sqlite.go b/pkg/db/sqlite.go new file mode 100644 index 0000000..d7de97d --- /dev/null +++ b/pkg/db/sqlite.go @@ -0,0 +1,47 @@ +package db + +import ( + "os" + + "github.com/eryajf/chatgpt-wecom/pkg/logger" + "github.com/glebarez/sqlite" + "gorm.io/gorm" +) + +// 全局数据库对象 +var DB *gorm.DB + +// 初始化数据库 +func InitDB() { + DB = ConnSqlite() + + dbAutoMigrate() +} + +// 自动迁移表结构 +func dbAutoMigrate() { + _ = DB.AutoMigrate( + Chat{}, + ) +} + +func ConnSqlite() *gorm.DB { + err := os.MkdirAll("data", 0755) + if err != nil { + return nil + } + db, err := gorm.Open(sqlite.Open("data/wecom.sqlite"), &gorm.Config{ + // 禁用外键(指定外键时不会在mysql创建真实的外键约束) + DisableForeignKeyConstraintWhenMigrating: true, + }) + if err != nil { + logger.Fatal("failed to connect sqlite3: %v", err) + } + dbObj, err := db.DB() + if err != nil { + logger.Fatal("failed to get sqlite3 obj: %v", err) + } + // 参见: https://github.com/glebarez/sqlite/issues/52 + dbObj.SetMaxOpenConns(1) + return db +} diff --git a/pkg/logger/logger.go b/pkg/logger/logger.go new file mode 100644 index 0000000..fc65532 --- /dev/null +++ b/pkg/logger/logger.go @@ -0,0 +1,42 @@ +package logger + +import ( + "os" + "sync" + + "github.com/charmbracelet/log" +) + +var Logger *log.Logger +var once sync.Once + +func InitLogger(level string) { + once.Do(func() { + Logger = log.NewWithOptions(os.Stderr, log.Options{ReportTimestamp: true}) + }) + if level == "debug" { + Logger.SetLevel(log.DebugLevel) + } else { + Logger.SetLevel(log.InfoLevel) + } +} + +func Info(args ...interface{}) { + Logger.Info(args) +} + +func Warning(args ...interface{}) { + Logger.Warn(args) +} + +func Debug(args ...interface{}) { + Logger.Debug(args) +} + +func Error(args ...interface{}) { + Logger.Error(args) +} + +func Fatal(args ...interface{}) { + Logger.Fatal(args) +} diff --git a/pkg/ops/opstools.go b/pkg/ops/opstools.go new file mode 100644 index 0000000..b140e35 --- /dev/null +++ b/pkg/ops/opstools.go @@ -0,0 +1,66 @@ +package ops + +import ( + "crypto/tls" + "net" + "regexp" + "strings" + "time" +) + +// 域名信息 +type DomainMsg struct { + CreateDate string `json:"create_date"` + ExpiryDate string `json:"expiry_date"` + Registrar string `json:"registrar"` +} + +// GetDomainMsg 获取域名信息 +func GetDomainMsg(domain string) (dm DomainMsg, err error) { + var conn net.Conn + conn, err = net.Dial("tcp", "whois.verisign-grs.com:43") + if err != nil { + return + } + defer conn.Close() + + _, err = conn.Write([]byte(domain + "\r\n")) + if err != nil { + return + } + buf := make([]byte, 1024) + var num int + num, err = conn.Read(buf) + if err != nil { + return + } + response := string(buf[:num]) + re := regexp.MustCompile(`Creation Date: (.*)\n.*Expiry Date: (.*)\n.*Registrar: (.*)`) + match := re.FindStringSubmatch(response) + if len(match) > 3 { + dm.CreateDate = strings.TrimSpace(strings.Split(match[1], "Creation Date:")[0]) + dm.ExpiryDate = strings.TrimSpace(strings.Split(match[2], "Expiry Date:")[0]) + dm.Registrar = strings.TrimSpace(strings.Split(match[3], "Registrar:")[0]) + } + return +} + +// GetDomainCertMsg 获取域名证书信息 +func GetDomainCertMsg(domain string) (cm tls.ConnectionState, err error) { + var conn net.Conn + conn, err = net.DialTimeout("tcp", domain+":443", time.Second*10) + if err != nil { + return + } + defer conn.Close() + tlsConn := tls.Client(conn, &tls.Config{ + ServerName: domain, + }) + defer tlsConn.Close() + err = tlsConn.Handshake() + if err != nil { + return + } + cm = tlsConn.ConnectionState() + return +} diff --git a/pkg/process/process_request.go b/pkg/process/process_request.go new file mode 100644 index 0000000..afe111c --- /dev/null +++ b/pkg/process/process_request.go @@ -0,0 +1,270 @@ +package process + +import ( + "fmt" + "html" + "strings" + "time" + + "github.com/eryajf/chatgpt-wecom/pkg/db" + "github.com/eryajf/chatgpt-wecom/pkg/logger" + "github.com/eryajf/chatgpt-wecom/public" + "github.com/solywsh/chatgpt" + "github.com/xen0n/go-workwx" +) + +// ProcessRequest 分析处理请求逻辑 +func ProcessRequest(rmsg *workwx.RxMessage, wxclient *workwx.WorkwxApp) error { + var msgInfo string + resp := &workwx.Recipient{UserIDs: []string{rmsg.FromUserID}} + if content, ok := rmsg.Text(); ok { + msgInfo = content.GetContent() + } + if CheckRequestTimes(rmsg, wxclient) { + content := strings.TrimSpace(msgInfo) + timeoutStr := "" + if content != public.Config.DefaultMode { + timeoutStr = fmt.Sprintf("\n\n>%s 后将恢复默认聊天模式:%s", FormatTimeDuation(public.Config.SessionTimeout), public.Config.DefaultMode) + } + switch content { + case "单聊": + public.UserService.SetUserMode(rmsg.FromUserID, content) + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("**[Concentrate] 现在进入与 %s 的单聊模式**%s", rmsg.FromUserID, timeoutStr), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + } + case "串聊": + public.UserService.SetUserMode(rmsg.FromUserID, content) + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("**[Concentrate] 现在进入与 %s 的串聊模式**%s", rmsg.FromUserID, timeoutStr), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + } + case "重置", "退出", "结束": + // 重置用户对话模式 + public.UserService.ClearUserMode(rmsg.FromUserID) + // 清空用户对话上下文 + public.UserService.ClearUserSessionContext(rmsg.FromUserID) + // 清空用户对话的答案ID + public.UserService.ClearAnswerID(rmsg.FromUserID, rmsg.FromUserID) + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[RecyclingSymbol]已重置与**%s** 的对话模式\n\n> 可以开始新的对话 [Bubble]", rmsg.FromUserID), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + } + case "模板": + var title string + for _, v := range *public.Prompt { + title = title + v.Title + " | " + } + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("%s 您好,当前程序内置集成了这些提示词:\n\n-----\n\n| %s \n\n-----\n\n您可以选择某个提示词作为对话内容的开头。\n\n以周报为例,可发送\"#周报 我本周用Go写了一个企微集成ChatGPT的聊天应用\",可将工作内容填充为一篇完整的周报。\n\n-----\n\n若您不清楚某个提示词的所代表的含义,您可以直接发送提示词,例如直接发送\"#周报\"", rmsg.FromUserID, title), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + } + default: + if public.FirstCheck(rmsg.FromUserID) { + return Do("串聊", rmsg, wxclient) + } else { + return Do("单聊", rmsg, wxclient) + } + } + } + return nil +} + +// 执行处理请求 +func Do(mode string, rmsg *workwx.RxMessage, wxclient *workwx.WorkwxApp) error { + var msgInfo string + resp := &workwx.Recipient{UserIDs: []string{rmsg.FromUserID}} + if content, ok := rmsg.Text(); ok { + msgInfo = content.GetContent() + } + // 先把模式注入 + public.UserService.SetUserMode(rmsg.FromUserID, mode) + switch mode { + case "单聊": + qObj := db.Chat{ + Username: rmsg.FromUserID, + Source: rmsg.FromUserID, + ChatType: db.Q, + ParentContent: 0, + Content: msgInfo, + } + qid, err := qObj.Add() + if err != nil { + logger.Error("往MySQL新增数据失败,错误信息:", err) + } + reply, err := chatgpt.SingleQa(msgInfo, rmsg.FromUserID) + if err != nil { + logger.Info(fmt.Errorf("gpt request error: %v", err)) + if strings.Contains(fmt.Sprintf("%v", err), "maximum question length exceeded") { + public.UserService.ClearUserSessionContext(rmsg.FromUserID) + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[Wrong] 请求 OpenAI 失败了\n\n> 错误信息:%v\n\n> 已超过最大文本限制,请缩短提问文字的字数。", err), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + } else { + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[Wrong] 请求 OpenAI 失败了\n\n> 错误信息:%v", err), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + } + } + if reply == "" { + logger.Warning(fmt.Errorf("get gpt result falied: %v", err)) + return nil + } else { + reply = strings.TrimSpace(reply) + reply = strings.Trim(reply, "\n") + aObj := db.Chat{ + Username: rmsg.FromUserID, + Source: rmsg.FromUserID, + ChatType: db.A, + ParentContent: qid, + Content: reply, + } + _, err := aObj.Add() + if err != nil { + logger.Error("往MySQL新增数据失败,错误信息:", err) + } + logger.Info(fmt.Sprintf("🤖 %s得到的答案: %#v", rmsg.FromUserID, reply)) + if public.JudgeSensitiveWord(reply) { + reply = public.SolveSensitiveWord(reply) + } + // 回复@我的用户 + err = wxclient.SendMarkdownMessage(resp, FormatMarkdown(reply), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + } + case "串聊": + lastAid := public.UserService.GetAnswerID(rmsg.FromUserID, rmsg.FromUserID) + qObj := db.Chat{ + Username: rmsg.FromUserID, + Source: rmsg.FromUserID, + ChatType: db.Q, + ParentContent: lastAid, + Content: msgInfo, + } + qid, err := qObj.Add() + if err != nil { + logger.Error("往MySQL新增数据失败,错误信息:", err) + } + cli, reply, err := chatgpt.ContextQa(msgInfo, rmsg.FromUserID) + if err != nil { + logger.Info(fmt.Sprintf("gpt request error: %v", err)) + if strings.Contains(fmt.Sprintf("%v", err), "maximum text length exceeded") { + public.UserService.ClearUserSessionContext(rmsg.FromUserID) + err = wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[Wrong] 请求 OpenAI 失败了\n\n> 错误信息:%v\n\n> 串聊已超过最大文本限制,对话已重置,请重新发起。", err), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + } else { + err = wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[Wrong] 请求 OpenAI 失败了\n\n> 错误信息:%v", err), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + } + } + if reply == "" { + logger.Warning(fmt.Errorf("get gpt result falied: %v", err)) + return nil + } else { + reply = strings.TrimSpace(reply) + reply = strings.Trim(reply, "\n") + aObj := db.Chat{ + Username: rmsg.FromUserID, + Source: rmsg.FromUserID, + ChatType: db.A, + ParentContent: qid, + Content: reply, + } + aid, err := aObj.Add() + if err != nil { + logger.Error("往MySQL新增数据失败,错误信息:", err) + } + // 将当前回答的ID放入缓存 + public.UserService.SetAnswerID(rmsg.FromUserID, string(rmsg.MsgType), aid) + logger.Info(fmt.Sprintf("🤖 %s得到的答案: %#v", rmsg.FromUserID, reply)) + if public.JudgeSensitiveWord(reply) { + reply = public.SolveSensitiveWord(reply) + } + // 回复@我的用户 + err = wxclient.SendMarkdownMessage(resp, FormatMarkdown(reply), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + return err + } + _ = cli.ChatContext.SaveConversation(rmsg.FromUserID) + } + default: + + } + return nil +} + +// FormatTimeDuation 格式化时间 +// 主要提示单聊/群聊切换时多久后恢复默认聊天模式 +func FormatTimeDuation(duration time.Duration) string { + minutes := int64(duration.Minutes()) + seconds := int64(duration.Seconds()) - minutes*60 + var timeoutStr string + if seconds == 0 { + timeoutStr = fmt.Sprintf("%d分钟", minutes) + } else { + timeoutStr = fmt.Sprintf("%d分%d秒", minutes, seconds) + } + return timeoutStr +} + +// FormatMarkdown 格式化Markdown +// 主要修复ChatGPT返回多行代码块,企微会将代码块中的#当作Markdown语法里的标题来处理,进行转义;如果Markdown格式内存在html,将Markdown中的html标签转义 +// 代码块缩进问题暂无法解决,因不管是四个空格,还是Tab,在企微上均会顶格显示,建议复制代码后用IDE进行代码格式化,针对缩进严格的语言,例如Python,不确定的建议手机端查看下代码块的缩进 +func FormatMarkdown(md string) string { + lines := strings.Split(md, "\n") + codeblock := false + existHtml := strings.Contains(md, "<") + + for i, line := range lines { + if strings.HasPrefix(line, "```") { + codeblock = !codeblock + } + if codeblock { + lines[i] = strings.ReplaceAll(line, "#", "\\#") + } else if existHtml { + lines[i] = html.EscapeString(line) + } + } + + return strings.Join(lines, "\n") +} + +// CheckRequestTimes 分析处理请求逻辑 +// 主要提供单日请求限额的功能 +func CheckRequestTimes(rmsg *workwx.RxMessage, wxclient *workwx.WorkwxApp) bool { + resp := &workwx.Recipient{UserIDs: []string{rmsg.FromUserID}} + if public.Config.MaxRequest == 0 { + return true + } + count := public.UserService.GetUseRequestCount(rmsg.FromUserID) + // 用户是管理员或VIP用户,不判断访问次数是否超过限制 + if public.JudgeAdminUsers(rmsg.FromUserID) || public.JudgeVipUsers(rmsg.FromUserID) { + return true + } else { + // 用户不是管理员和VIP用户,判断访问次数是否超过限制 + if count >= public.Config.MaxRequest { + logger.Info(fmt.Sprintf("亲爱的: %s,您今日请求次数已达上限,请明天再来,交互发问资源有限,请务必斟酌您的问题,给您带来不便,敬请谅解!", rmsg.FromUserID)) + err := wxclient.SendMarkdownMessage(resp, fmt.Sprintf("[Staple] **一个好的问题,胜过十个好的答案!** \n\n亲爱的%s:\n\n您今日请求次数已达上限,请明天再来,交互发问资源有限,请务必斟酌您的问题,给您带来不便,敬请谅解!\n\n如有需要,可联系管理员升级为VIP用户。", rmsg.FromUserID), false) + if err != nil { + logger.Warning(fmt.Errorf("send message error: %v", err)) + } + return false + } + } + // 访问次数未超过限制,将计数加1 + public.UserService.SetUseRequestCount(rmsg.FromUserID, count+1) + return true +} diff --git a/pkg/process/prompt.go b/pkg/process/prompt.go new file mode 100644 index 0000000..cf9cd42 --- /dev/null +++ b/pkg/process/prompt.go @@ -0,0 +1,27 @@ +package process + +import ( + "errors" + "fmt" + "strings" + + "github.com/eryajf/chatgpt-wecom/public" +) + +// GeneratePrompt 生成当次请求的 Prompt +func GeneratePrompt(msg string) (rst string, err error) { + for _, prompt := range *public.Prompt { + if strings.HasPrefix(msg, prompt.Title) { + if strings.TrimSpace(msg) == prompt.Title { + rst = fmt.Sprintf("%s:\n%s___输入内容___%s", prompt.Title, prompt.Prefix, prompt.Suffix) + err = errors.New("消息内容为空") // 当提示词之后没有文本,抛出异常,以便直接返回Prompt所代表的内容 + } else { + rst = prompt.Prefix + strings.TrimSpace(strings.Replace(msg, prompt.Title, "", -1)) + prompt.Suffix + } + return + } else { + rst = msg + } + } + return +} diff --git a/prompt.yml b/prompt.yml new file mode 100644 index 0000000..4bb3172 --- /dev/null +++ b/prompt.yml @@ -0,0 +1,70 @@ +# 可在此处提交你认为不错的 prompt, 注意保持格式一致,prefix为内容前缀,suffix是内容后缀,如果文本中间有双引号,那么就去掉最外层的双引号即可 +- title: "#周报" + prefix: "请帮我把以下的工作内容填充为一篇完整的周报,用 markdown 格式以分点叙述的形式输出:" + suffix: "" +- title: "#前端" + prefix: "我想让你充当前端开发专家。我将提供一些关于 Js、Node 等前端代码问题的具体信息,而你的工作就是想出为我解决问题的策略。这可能包括建议代码、代码逻辑思路策略。我的第一个请求是:" + suffix: "" +- title: "#架构师" + prefix: "我希望你担任 IT 架构师。我将提供有关应用程序或其他数字产品功能的一些详细信息,而您的工作是想出将其集成到 IT 环境中的方法。这可能涉及分析业务需求、执行差距分析以及将新系统的功能映射到现有 IT 环境。接下来的步骤是创建解决方案设计、物理网络蓝图、系统集成接口定义和部署环境蓝图。我的第一个请求是:" + suffix: "" +- title: "#产品经理" + prefix: "请确认我的以下请求。请您作为产品经理回复我。我将会提供一个主题,您将帮助我编写一份包括以下章节标题的 PRD 文档:主题、简介、问题陈述、目标与目的、用户故事、技术要求、收益、KPI 指标、开发风险以及结论。在我要求具体主题、功能或开发的 PRD 之前,请不要先写任何一份 PRD 文档。" + suffix: "" +- title: "#网络安全" + prefix: "我想让你充当网络安全专家。我将提供一些关于如何存储和共享数据的具体信息,而你的工作就是想出保护这些数据免受恶意行为者攻击的策略。这可能包括建议加密方法、创建防火墙或实施将某些活动标记为可疑的策略。我的第一个请求是:" + suffix: "" +- title: "#正则" + prefix: "我希望你充当正则表达式生成器。您的角色是生成匹配文本中特定模式的正则表达式。您应该以一种可以轻松复制并粘贴到支持正则表达式的文本编辑器或编程语言中的格式提供正则表达式。不要写正则表达式如何工作的解释或例子;只需提供正则表达式本身。我的第一个提示是:" + suffix: "" +- title: "#招聘" + prefix: "我想让你担任招聘人员。我将提供一些关于职位空缺的信息,而你的工作是制定寻找合格申请人的策略。这可能包括通过社交媒体、社交活动甚至参加招聘会接触潜在候选人,以便为每个职位找到最合适的人选。我的第一个请求是:" + suffix: "" +- title: "#知乎" + prefix: 知乎的风格是:用"谢邀"开头,用很多学术语言,引用很多名言,做大道理的论述,提到自己很厉害的教育背景并且经验丰富,最后还要引用一些论文。请用知乎风格: + suffix: "" +- title: "#翻译" + prefix: 下面我让你来充当翻译家,你的目标是把任何语言翻译成中文,请翻译时不要带翻译腔,而是要翻译得自然、流畅和地道,最重要的是要简明扼要。请翻译下面这句话: + suffix: "" +- title: "#小红书" + prefix: "小红书的风格是:很吸引眼球的标题,每个段落都加 emoji, 最后加一些 tag。请用小红书风格:" + suffix: "" +- title: "#解梦" + prefix: "我要你充当解梦师。我会给你描述我的梦,你会根据梦中出现的符号和主题提供解释。不要提供关于梦者的个人意见或假设。仅根据所提供的信息提供事实解释。我的梦是:" + suffix: "" +- title: "#linux命令" + prefix: "我希望你只用 linux 命令回复。不要写解释。我想:" + suffix: "" +- title: "#英语学术润色" + prefix: "Below is a paragraph from an academic paper. Polish the writing to meet the academic style, improve the spelling, grammar, clarity, concision and overall readability. When neccessary, rewrite the whole sentence. Furthermore, list all modification and explain the reasons to do so in markdown table.\n" + suffix: "" +- title: "#中文学术润色" + prefix: "作为一名中文学术论文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性,同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请编辑以下文本:" + suffix: "" +- title: "#查找语法错误" + prefix: "Below is a paragraph from an academic paper. Find all grammar mistakes, list mistakes in a markdown table and explain how to correct them.\n" + suffix: "" +- title: "#中译英" + prefix: "Please translate following sentence to English: \n" + suffix: "" +- title: "#学术中译英" + prefix: "Please translate following sentence to English with academic writing, and provide some related authoritative examples: \n" + suffix: "" +- title: "#英译中" + prefix: "下面我让你来充当翻译家,你的目标是把任何语言翻译成中文,翻译时请不要带翻译腔,而是要翻译得自然、流畅和地道,使用优美和高雅的表达方式。请翻译:" + suffix: "" +- title: "#解释代码" + prefix: "请解释以下代码:\n```\n" + suffix: "\n```" +- title: "#生成域名" + prefix: "I want you to act as a smart domain name generator. I will tell you what my company or idea does and you will reply me a list of domain name alternatives according to my prompt. You will only reply the domain list, and nothing else. Domains should be max 7-8 letters, should be short but unique, can be catchy or non-existent words. Do not write explanations. Reply 'OK' to confirm." + suffix: "" +- title: "#生成sql" + prefix: "我希望你能成为数据库方面的专家。当我问你与SQL相关的问题时,我需要你把它们翻译成标准的SQL语句。如果我的描述不够准确,请提供适当的反馈." + suffix: "" +- title: "#编程问题" + prefix: "我想让你充当 stackoverflow 的帖子。我会问编程相关的问题,你会回答应该是什么答案。我希望你只回答给定的答案,并在不够详细的时候写解释。不要写解释。当我需要用英语告诉你一些事情时,我会把文字放在大括号内{like this}。我的第一个问题是:" + suffix: "" +- title: "#画图" + prefix: "system: 助手善于判断用户意图,当确定需要提供图片时,助手会变得沉默寡言,只使用以下格式输出markdown图片:![描述](https://image.pollinations.ai/prompt/描述),因为这个语法可以自动按照提示生成并渲染图片。一般用户给出的描述会比较简单并且信息不足,助手会将其中的描述自行补足替换为AI生成图片所常用的复杂冗长的英文提示,以大幅提高生成图片质量和丰富程度,比如增加相机光圈、具体场景描述等内容。助手会避免用代码块或原始块包围markdown标记,因为那样只会渲染出代码块或原始块而不是图片。\nuser: Can you draw some pictures for me?\nassistant: Sure, what do you want me to draw?\nuser: " + suffix: "" \ No newline at end of file diff --git a/public/balance.go b/public/balance.go new file mode 100644 index 0000000..bb24962 --- /dev/null +++ b/public/balance.go @@ -0,0 +1,110 @@ +package public + +import ( + "encoding/json" + "fmt" + "time" + + "github.com/go-resty/resty/v2" +) + +func InitAiCli() *resty.Client { + if Config.HttpProxy != "" { + return resty.New().SetTimeout(10*time.Second).SetHeader("Authorization", fmt.Sprintf("Bearer %s", Config.ApiKey)).SetProxy(Config.HttpProxy).SetRetryCount(3).SetRetryWaitTime(2 * time.Second) + } + return resty.New().SetTimeout(10*time.Second).SetHeader("Authorization", fmt.Sprintf("Bearer %s", Config.ApiKey)).SetRetryCount(3).SetRetryWaitTime(2 * time.Second) +} + +type Bill struct { + Object string `json:"object"` + DailyCosts []DailyCost `json:"daily_costs"` + TotalUsage float64 `json:"total_usage"` +} + +type DailyCost struct { + Timestamp float64 `json:"timestamp"` + LineItems []LineItem `json:"line_items"` +} + +type LineItem struct { + Name string `json:"name"` + Cost float64 `json:"cost"` +} + +// GetBalance 获取账号余额 +func GetBalance() (string, error) { + var data Bill + path := "/v1/dashboard/billing/usage" + var url string = "https://api.openai.com" + path + if Config.BaseURL != "" { + url = Config.BaseURL + path + } + d, _ := time.ParseDuration("-24h") + resp, err := InitAiCli().R().SetQueryParams(map[string]string{ + "start_date": time.Now().Add(d * 90).Format("2006-01-02"), + "end_date": time.Now().Format("2006-01-02"), + }).Get(url) + if err != nil { + return "", err + } + err = json.Unmarshal(resp.Body(), &data) + if err != nil { + return "", err + } + sub, err := GetSub() + if err != nil { + return "", err + } + expireDate := time.Unix(sub.AccessUntil, 0).Format("2006-01-02 15:04:05") + used := data.TotalUsage / 100 + totalAvailable := sub.HardLimitUsd - used + msg := fmt.Sprintf("💵 已用: 💲%v\n💵 剩余: 💲%v\n🕰 到期时间: %v", fmt.Sprintf("%.2f", used), fmt.Sprintf("%.2f", totalAvailable), expireDate) + // 放入缓存 + UserService.SetUserMode("system_balance", msg) + return msg, nil +} + +type Subscription struct { + Object string `json:"object"` + HasPaymentMethod bool `json:"has_payment_method"` + Canceled bool `json:"canceled"` + CanceledAt interface{} `json:"canceled_at"` + Delinquent interface{} `json:"delinquent"` + AccessUntil int64 `json:"access_until"` + SoftLimit int64 `json:"soft_limit"` + HardLimit int64 `json:"hard_limit"` + SystemHardLimit int64 `json:"system_hard_limit"` + SoftLimitUsd float64 `json:"soft_limit_usd"` + HardLimitUsd float64 `json:"hard_limit_usd"` + SystemHardLimitUsd float64 `json:"system_hard_limit_usd"` + Plan Plan `json:"plan"` + AccountName string `json:"account_name"` + PoNumber interface{} `json:"po_number"` + BillingEmail interface{} `json:"billing_email"` + TaxIDS interface{} `json:"tax_ids"` + BillingAddress interface{} `json:"billing_address"` + BusinessAddress interface{} `json:"business_address"` +} + +type Plan struct { + Title string `json:"title"` + ID string `json:"id"` +} + +func GetSub() (Subscription, error) { + var data Subscription + path := "/v1/dashboard/billing/subscription" + var url string = "https://api.openai.com" + path + if Config.BaseURL != "" { + url = Config.BaseURL + path + } + resp, err := InitAiCli().R().Get(url) + if err != nil { + return data, err + } + err = json.Unmarshal(resp.Body(), &data) + if err != nil { + return data, err + } + return data, nil +} diff --git a/public/chat.go b/public/chat.go new file mode 100644 index 0000000..8ee73a7 --- /dev/null +++ b/public/chat.go @@ -0,0 +1,20 @@ +package public + +import ( + "strings" +) + +func FirstCheck(userid string) bool { + lc := UserService.GetUserMode(userid) + if lc == "" { + if Config.DefaultMode == "串聊" { + return true + } else { + return false + } + } + if lc != "" && strings.Contains(lc, "串聊") { + return true + } + return false +} diff --git a/public/public.go b/public/public.go new file mode 100644 index 0000000..ae794b1 --- /dev/null +++ b/public/public.go @@ -0,0 +1,26 @@ +package public + +import ( + "github.com/eryajf/chatgpt-wecom/config" + "github.com/eryajf/chatgpt-wecom/pkg/cache" + "github.com/eryajf/chatgpt-wecom/pkg/db" +) + +var UserService cache.UserServiceInterface +var Config *config.Configuration +var Prompt *[]config.Prompt + +func InitSvc() { + // 加载配置 + Config = config.LoadConfig() + // 加载prompt + Prompt = config.LoadPrompt() + // 初始化缓存 + UserService = cache.NewUserService() + // 初始化数据库 + db.InitDB() + // 暂时不在初始化时获取余额 + // if Config.Model == openai.GPT3Dot5Turbo0613 || Config.Model == openai.GPT3Dot5Turbo0301 || Config.Model == openai.GPT3Dot5Turbo { + // _, _ = GetBalance() + // } +} diff --git a/public/tools.go b/public/tools.go new file mode 100644 index 0000000..b2e6643 --- /dev/null +++ b/public/tools.go @@ -0,0 +1,127 @@ +package public + +import ( + "io/ioutil" + "os" + "strings" + "time" + "unicode/utf8" +) + +// 将内容写入到文件,如果文件名带路径,则会判断路径是否存在,不存在则创建 +func WriteToFile(path string, data []byte) error { + tmp := strings.Split(path, "/") + if len(tmp) > 0 { + tmp = tmp[:len(tmp)-1] + } + + err := os.MkdirAll(strings.Join(tmp, "/"), os.ModePerm) + if err != nil { + return err + } + err = ioutil.WriteFile(path, data, 0755) + if err != nil { + return err + } + return nil +} + +// JudgeUsers 判断用户是否在白名单 +func JudgeUsers(s string) bool { + // 优先判断黑名单,黑名单用户返回:不在白名单 + if len(Config.DenyUsers) != 0 { + for _, v := range Config.DenyUsers { + if v == s { + return false + } + } + } + // 白名单配置逻辑处理 + if len(Config.AllowUsers) == 0 { + return true + } + for _, v := range Config.AllowUsers { + if v == s { + return true + } + } + return false +} + +// JudgeAdminUsers 判断用户是否为系统管理员 +func JudgeAdminUsers(s string) bool { + // 如果secret或者用户的userid都为空的话,那么默认没有管理员 + if s == "" { + return false + } + // 如果没有指定,则没有人是管理员 + if len(Config.AdminUsers) == 0 { + return false + } + for _, v := range Config.AdminUsers { + if v == s { + return true + } + } + return false +} + +// JudgeVipUsers 判断用户是否为VIP用户 +func JudgeVipUsers(s string) bool { + // 如果secret或者用户的userid都为空的话,那么默认不是VIP用户 + if s == "" { + return false + } + // 管理员默认是VIP用户 + for _, v := range Config.AdminUsers { + if v == s { + return true + } + } + // 如果没有指定,则没有人是VIP用户 + if len(Config.VipUsers) == 0 { + return false + } + for _, v := range Config.VipUsers { + if v == s { + return true + } + } + return false +} + +func GetReadTime(t time.Time) string { + return t.Format("2006-01-02 15:04:05") +} + +// JudgeSensitiveWord 判断内容是否包含敏感词 +func JudgeSensitiveWord(s string) bool { + if len(Config.SensitiveWords) == 0 { + return false + } + for _, v := range Config.SensitiveWords { + if strings.Contains(s, v) { + return true + } + } + return false +} + +// SolveSensitiveWord 将敏感词用 🚫 占位 +func SolveSensitiveWord(s string) string { + for _, v := range Config.SensitiveWords { + if strings.Contains(s, v) { + return strings.Replace(s, v, printStars(utf8.RuneCountInString(v)), -1) + } + } + return s +} + +// 将对应敏感词替换为 🚫 +func printStars(num int) string { + s := "" + for i := 0; i < num; i++ { + s += "🚫" + } + return s +}