diff --git a/.env b/.env new file mode 100644 index 0000000000000000000000000000000000000000..14692d266e45d20bcc280250b27b83d6fac28f4b --- /dev/null +++ b/.env @@ -0,0 +1,54 @@ +#基础部分 +#设置一个你自己的访问密码 +PASSWORD=123 +#配置时区 +TZ=Asia/Shanghai + +#ai studio部分 + +#将key1,key2,key3等替换为你真正拥有的gemini api key +GEMINI_API_KEYS=key1,key2,key3 + +#每分钟最大请求数 +MAX_REQUESTS_PER_MINUTE=30 + +#每天每个 IP 最大请求数 +MAX_REQUESTS_PER_DAY_PER_IP=600 + +#是否启用假流式传输 +FAKE_STREAMING=true + +#单api 24小时最大使用次数 +API_KEY_DAILY_LIMIT=100 + +#空响应重试次数 +MAX_EMPTY_RESPONSES=5 + +#是否启用伪装信息 +RANDOM_STRING=true + +#伪装信息长度 +RANDOM_STRING_LENGTH=5 + +#默认的并发请求数 +CONCURRENT_REQUESTS=1 + +#当请求失败时增加的并发请求数 +INCREASE_CONCURRENT_ON_FAILURE=0 + +允许的最大并发请求数 +MAX_CONCURRENT_REQUESTS=3 + +#是否启用联网模式(联网模式有严格的审核) +SEARCH_MODE=false + +#联网模式提示词(用英文单引号包裹提示词) +SEARCH_PROMPT='(使用搜索工具联网搜索,需要在content中结合搜索内容)' + +#vertex部分(如果您不需要vertex或不知道vertex是什么,无需配置这些内容) + +#是否启用vertex +ENABLE_VERTEX=false + +#vertex ai 凭证 +GOOGLE_CREDENTIALS_JSON='' \ No newline at end of file diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..351912e2339b63a6b7e322c34f4c90655249f6f2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,11 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +wiki/img/claw/1.png filter=lfs diff=lfs merge=lfs -text +wiki/img/claw/3.png filter=lfs diff=lfs merge=lfs -text +wiki/img/files.png filter=lfs diff=lfs merge=lfs -text +wiki/img/settings.png filter=lfs diff=lfs merge=lfs -text +wiki/img/spaces.png filter=lfs diff=lfs merge=lfs -text +wiki/img/vertex/index.png filter=lfs diff=lfs merge=lfs -text +wiki/img/zeabur/6.png filter=lfs diff=lfs merge=lfs -text +wiki/img/zeabur/7.png filter=lfs diff=lfs merge=lfs -text diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 0000000000000000000000000000000000000000..3301397ea15e3853b5299c338279f436186f4396 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,53 @@ +name: "问题反馈" +description: Bug report +labels: [bug] +body: + - type: markdown + attributes: + value: | + 感谢您花时间填写此错误报告,请**务必确认您的issue不是重复的且不是因为您的操作或版本问题** + + - type: checkboxes + attributes: + label: Please make sure of the following things + description: | + 您必须勾选以下所有内容,否则您的issue可能会被直接关闭。 + options: + - label: | + 我已经阅读了[错误自查](./wiki/error.md)。 + - label: | + 我确定没有重复的issue或讨论。 + - label: | + 我确定是`Hajimi`自身的问题,而不是酒馆等三方件的原因。 + - label: | + 我确定这个问题在最新版本中没有被修复。 + + - type: input + id: version + attributes: + label: hajimi版本 + description: | + 您使用的是哪个版本的程序?请不要使用`latest`作为答案。 + placeholder: v0.x.x + validations: + required: true + - type: textarea + id: bug-description + attributes: + label: 问题描述 + validations: + required: true + - type: textarea + id: reproduction + attributes: + label: 复现方法 + description: | + 请提供能复现此问题的方法以方便开发者定问题,请知悉如果不提供它你的issue可能会被直接关闭。 + validations: + required: true + - type: textarea + id: logs + attributes: + label: Logs / 日志 + description: | + 请复制粘贴错误日志,或者截图 \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec4bb386bcf8a4946923eff961cc7cdf70c0aedf --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1 @@ +blank_issues_enabled: false \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 0000000000000000000000000000000000000000..31f98ffdd4627a1fffd78790eb5b5af0449563f9 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,32 @@ +name: "功能请求" +description: Feature request +labels: [enhancement] +body: + - type: checkboxes + attributes: + label: 请确认以下事项 + description: 您可以选择多项,甚至全部。 + options: + - label: 我已阅读了[更新日志](./update.md)。 + - label: 我确定没有重复的议题或讨论。 + - label: 我确定此功能尚未实现。 + - label: 我确定这是一个合理且普遍的需求。 + - type: textarea + id: feature-description + attributes: + label: 功能描述 + validations: + required: true + - type: textarea + id: suggested-solution + attributes: + label: 建议的解决方案 + description: | + 实现此需求的解决思路。 + - type: textarea + id: additional-context + attributes: + label: 附加信息 + description: | + 关于此功能请求的任何其他上下文或截图,或者您觉得有帮助的信息。 + 相关的任何其他上下文或截图,或者你觉得有帮助的信息 diff --git a/.github/workflows/issues-duplicate.yml b/.github/workflows/issues-duplicate.yml new file mode 100644 index 0000000000000000000000000000000000000000..24238daa35e9e97854668c447f87a2b7597bf13d --- /dev/null +++ b/.github/workflows/issues-duplicate.yml @@ -0,0 +1,25 @@ +name: Issue Duplicate + +on: + issues: + types: [labeled] + +jobs: + create-comment: + runs-on: ubuntu-latest + if: github.event.label.name == 'duplicate' + steps: + - name: Create comment + uses: actions-cool/issues-helper@v3 + with: + actions: 'create-comment' + token: ${{ secrets.GITHUB_TOKEN }} + issue-number: ${{ github.event.issue.number }} + body: | + Hello @${{ github.event.issue.user.login }}, your issue is a duplicate and will be closed. + 你好 @${{ github.event.issue.user.login }},你的issue是重复的,将被关闭。 + - name: Close issue + uses: actions-cool/issues-helper@v3 + with: + actions: 'close-issue' + token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml new file mode 100644 index 0000000000000000000000000000000000000000..f929809f9876c474ddeeb0352831398cd38d1560 --- /dev/null +++ b/.github/workflows/main.yml @@ -0,0 +1,45 @@ +name: GHCR CI + +on: + push: + branches: [main] + workflow_dispatch: + +jobs: + build-and-push: + runs-on: ubuntu-latest + permissions: + contents: read + packages: write + + steps: + - name: lowercase repository name + run: echo "IMAGE_NAME=${GITHUB_REPOSITORY@L}" >> ${GITHUB_ENV} + + - name: Checkout repository + uses: actions/checkout@v4 + + - name: Read version from file + id: version + run: echo "VERSION=$(cat version.txt | grep version= | cut -d= -f2)" >> $GITHUB_OUTPUT + + - name: Log in to the GitHub Container Registry + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Build and push Docker image + uses: docker/build-push-action@v6 + with: + context: . + push: true + tags: | + ghcr.io/${{ env.IMAGE_NAME }}:latest + ghcr.io/${{ env.IMAGE_NAME }}:${{ steps.version.outputs.VERSION }} + cache-from: type=gha + cache-to: type=gha,mode=max diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ba0430d26c996e7f078385407f959c96c271087c --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ \ No newline at end of file diff --git a/.python-version b/.python-version new file mode 100644 index 0000000000000000000000000000000000000000..e4fba2183587225f216eeada4c78dfab6b2e65f5 --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.12 diff --git a/Dockerfile b/Dockerfile index ddcf3baad5bd0f8c2a94642b38d7c74544721612..06fd6f9ab99fee767b547f204fe2e9654b8754bb 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,20 +1,12 @@ -FROM python:3.11-slim +FROM python:3.12-slim WORKDIR /app -# 安装 unzip 工具 -RUN apt-get update && apt-get install -y unzip && rm -rf /var/lib/apt/lists/* +COPY . . -COPY app.zip . -COPY requirements.txt . -COPY version.txt . -RUN mkdir -p app -# 解压 app.zip 文件 -RUN unzip app.zip -d app && rm app.zip +RUN pip install uv +RUN uv pip install --system --no-cache-dir -r requirements.txt -RUN pip install --no-cache-dir -r requirements.txt +EXPOSE 7860 -# 环境变量 (在 Hugging Face Spaces 中设置) -# ENV GEMINI_API_KEYS=your_key_1,your_key_2,your_key_3 - -CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"] \ No newline at end of file +CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "7860"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..12d4ca74d98cfb36269464dced75e9441b7bf645 --- /dev/null +++ b/LICENSE @@ -0,0 +1,407 @@ +Attribution-NonCommercial 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution-NonCommercial 4.0 International Public +License + +By exercising the Licensed Rights (defined below), You accept and agree +to be bound by the terms and conditions of this Creative Commons +Attribution-NonCommercial 4.0 International Public License ("Public +License"). To the extent this Public License may be interpreted as a +contract, You are granted the Licensed Rights in consideration of Your +acceptance of these terms and conditions, and the Licensor grants You +such rights in consideration of benefits the Licensor receives from +making the Licensed Material available under these terms and +conditions. + + +Section 1 -- Definitions. + + a. Adapted Material means material subject to Copyright and Similar + Rights that is derived from or based upon the Licensed Material + and in which the Licensed Material is translated, altered, + arranged, transformed, or otherwise modified in a manner requiring + permission under the Copyright and Similar Rights held by the + Licensor. For purposes of this Public License, where the Licensed + Material is a musical work, performance, or sound recording, + Adapted Material is always produced where the Licensed Material is + synched in timed relation with a moving image. + + b. Adapter's License means the license You apply to Your Copyright + and Similar Rights in Your contributions to Adapted Material in + accordance with the terms and conditions of this Public License. + + c. Copyright and Similar Rights means copyright and/or similar rights + closely related to copyright including, without limitation, + performance, broadcast, sound recording, and Sui Generis Database + Rights, without regard to how the rights are labeled or + categorized. For purposes of this Public License, the rights + specified in Section 2(b)(1)-(2) are not Copyright and Similar + Rights. + d. Effective Technological Measures means those measures that, in the + absence of proper authority, may not be circumvented under laws + fulfilling obligations under Article 11 of the WIPO Copyright + Treaty adopted on December 20, 1996, and/or similar international + agreements. + + e. Exceptions and Limitations means fair use, fair dealing, and/or + any other exception or limitation to Copyright and Similar Rights + that applies to Your use of the Licensed Material. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. Licensed Rights means the rights granted to You subject to the + terms and conditions of this Public License, which are limited to + all Copyright and Similar Rights that apply to Your use of the + Licensed Material and that the Licensor has authority to license. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. NonCommercial means not primarily intended for or directed towards + commercial advantage or monetary compensation. For purposes of + this Public License, the exchange of the Licensed Material for + other material subject to Copyright and Similar Rights by digital + file-sharing or similar means is NonCommercial provided there is + no payment of monetary compensation in connection with the + exchange. + + j. Share means to provide material to the public by any means or + process that requires permission under the Licensed Rights, such + as reproduction, public display, public performance, distribution, + dissemination, communication, or importation, and to make material + available to the public including in ways that members of the + public may access the material from a place and at a time + individually chosen by them. + + k. Sui Generis Database Rights means rights other than copyright + resulting from Directive 96/9/EC of the European Parliament and of + the Council of 11 March 1996 on the legal protection of databases, + as amended and/or succeeded, as well as other essentially + equivalent rights anywhere in the world. + + l. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. Subject to the terms and conditions of this Public License, + the Licensor hereby grants You a worldwide, royalty-free, + non-sublicensable, non-exclusive, irrevocable license to + exercise the Licensed Rights in the Licensed Material to: + + a. reproduce and Share the Licensed Material, in whole or + in part, for NonCommercial purposes only; and + + b. produce, reproduce, and Share Adapted Material for + NonCommercial purposes only. + + 2. Exceptions and Limitations. For the avoidance of doubt, where + Exceptions and Limitations apply to Your use, this Public + License does not apply, and You do not need to comply with + its terms and conditions. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. Media and formats; technical modifications allowed. The + Licensor authorizes You to exercise the Licensed Rights in + all media and formats whether now known or hereafter created, + and to make technical modifications necessary to do so. The + Licensor waives and/or agrees not to assert any right or + authority to forbid You from making technical modifications + necessary to exercise the Licensed Rights, including + technical modifications necessary to circumvent Effective + Technological Measures. For purposes of this Public License, + simply making modifications authorized by this Section 2(a) + (4) never produces Adapted Material. + + 5. Downstream recipients. + + a. Offer from the Licensor -- Licensed Material. Every + recipient of the Licensed Material automatically + receives an offer from the Licensor to exercise the + Licensed Rights under the terms and conditions of this + Public License. + + b. No downstream restrictions. You may not offer or impose + any additional or different terms or conditions on, or + apply any Effective Technological Measures to, the + Licensed Material if doing so restricts exercise of the + Licensed Rights by any recipient of the Licensed + Material. + + 6. No endorsement. Nothing in this Public License constitutes or + may be construed as permission to assert or imply that You + are, or that Your use of the Licensed Material is, connected + with, or sponsored, endorsed, or granted official status by, + the Licensor or others designated to receive attribution as + provided in Section 3(a)(1)(A)(i). + + b. Other rights. + + 1. Moral rights, such as the right of integrity, are not + licensed under this Public License, nor are publicity, + privacy, and/or other similar personality rights; however, to + the extent possible, the Licensor waives and/or agrees not to + assert any such rights held by the Licensor to the limited + extent necessary to allow You to exercise the Licensed + Rights, but not otherwise. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. To the extent possible, the Licensor waives any right to + collect royalties from You for the exercise of the Licensed + Rights, whether directly or through a collecting society + under any voluntary or waivable statutory or compulsory + licensing scheme. In all other cases the Licensor expressly + reserves any right to collect such royalties, including when + the Licensed Material is used other than for NonCommercial + purposes. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. identification of the creator(s) of the Licensed + Material and any others designated to receive + attribution, in any reasonable manner requested by + the Licensor (including by pseudonym if + designated); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. You may satisfy the conditions in Section 3(a)(1) in any + reasonable manner based on the medium, means, and context in + which You Share the Licensed Material. For example, it may be + reasonable to satisfy the conditions by providing a URI or + hyperlink to a resource that includes the required + information. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. If You Share Adapted Material You produce, the Adapter's + License You apply must not prevent recipients of the Adapted + Material from complying with this Public License. + + +Section 4 -- Sui Generis Database Rights. + +Where the Licensed Rights include Sui Generis Database Rights that +apply to Your use of the Licensed Material: + + a. for the avoidance of doubt, Section 2(a)(1) grants You the right + to extract, reuse, reproduce, and Share all or a substantial + portion of the contents of the database for NonCommercial purposes + only; + + b. if You include all or a substantial portion of the database + contents in a database in which You have Sui Generis Database + Rights, then the database in which You have Sui Generis Database + Rights (but not its individual contents) is Adapted Material; and + + c. You must comply with the conditions in Section 3(a) if You Share + all or a substantial portion of the contents of the database. + +For the avoidance of doubt, this Section 4 supplements and does not +replace Your obligations under this Public License where the Licensed +Rights include other Copyright and Similar Rights. + + +Section 5 -- Disclaimer of Warranties and Limitation of Liability. + + a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE + EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS + AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF + ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS, + IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION, + WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR + PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS, + ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT + KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT + ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU. + + b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE + TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION, + NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT, + INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES, + COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR + USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR + DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR + IN PART, THIS LIMITATION MAY NOT APPLY TO YOU. + + c. The disclaimer of warranties and limitation of liability provided + above shall be interpreted in a manner that, to the extent + possible, most closely approximates an absolute disclaimer and + waiver of all liability. + + +Section 6 -- Term and Termination. + + a. This Public License applies for the term of the Copyright and + Similar Rights licensed here. However, if You fail to comply with + this Public License, then Your rights under this Public License + terminate automatically. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. upon express reinstatement by the Licensor. + + For the avoidance of doubt, this Section 6(b) does not affect any + right the Licensor may have to seek remedies for Your violations + of this Public License. + + c. For the avoidance of doubt, the Licensor may also offer the + Licensed Material under separate terms or conditions or stop + distributing the Licensed Material at any time; however, doing so + will not terminate this Public License. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. Any arrangements, understandings, or agreements regarding the + Licensed Material not stated herein are separate from and + independent of the terms and conditions of this Public License. + + +Section 8 -- Interpretation. + + a. For the avoidance of doubt, this Public License does not, and + shall not be interpreted to, reduce, limit, restrict, or impose + conditions on any use of the Licensed Material that could lawfully + be made without permission under this Public License. + + b. To the extent possible, if any provision of this Public License is + deemed unenforceable, it shall be automatically reformed to the + minimum extent necessary to make it enforceable. If the provision + cannot be reformed, it shall be severed from this Public License + without affecting the enforceability of the remaining terms and + conditions. + + c. No term or condition of this Public License will be waived and no + failure to comply consented to unless expressly agreed to by the + Licensor. + + d. Nothing in this Public License constitutes or may be interpreted + as a limitation upon, or waiver of, any privileges and immunities + that apply to the Licensor or You, including from the legal + processes of any jurisdiction or authority. + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. \ No newline at end of file diff --git a/README.md b/README.md index d2ba06da71e52b67108a08d988b4f3e236d0845c..202365d1781d7e343a4a6cc2e52675c0a9034bfb 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,144 @@ ---- -title: '808' -emoji: ⚡ -colorFrom: indigo -colorTo: yellow -sdk: docker -pinned: false ---- - -Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference +# 🚀 HAJIMI Gemini API Proxy + +- 这是一个基于 FastAPI 构建的 Gemini API 代理,旨在提供一个简单、安全且可配置的方式来访问 Google 的 Gemini 模型。适用于在 Hugging Face Spaces 上部署,并支持openai api格式的工具集成。 + +## 项目采用动态更新,随时会有一些小更新同步到主仓库且会自动构建镜像,如果反馈的bug开发者说修了但是版本号没变是正常现象,~~记得勤更新镜像哦~~ + +# 本项目基于CC BY-NC 4.0许可开源,需遵守以下规则 +- 您必须给出适当的署名,提供指向本协议的链接,并指明是否(对原作)作了修改。您可以以任何合理方式进行,但不得以任何方式暗示许可方认可您或您的使用。 +- 您不得将本作品用于商业目的,包括但不限于任何形式的商业倒卖、SaaS、API 付费接口、二次销售、打包出售、收费分发或其他直接或间接盈利行为。 + +### 如需商业授权,请联系原作者获得书面许可。违者将承担相应法律责任。 + +### 感谢[@warming-afternoon](https://github.com/warming-afternoon),[@任梓樂](https://github.com/rzline)在技术上的大力支持 + +### 错误自查 + +遇到问题请先查看以下的 **错误自查** 文档,确保已尝试按照其上的指示进行了相应的排查与处理。 + +- [错误自查](./wiki/error.md) +### 使用文档 +- [huggingface 部署的使用文档(复活?!)(推荐,免费,手机电脑均可使用)](./wiki/huggingface.md) +- [上面看不到图的看这里](https://blog.rzline.eu.org/2025/04/29/HuggingFace%E9%83%A8%E7%BD%B2Gemini%E8%BD%AE%E8%AF%A2%E9%A1%B9%E7%9B%AEHajimi) + +- [Claw Cloud部署的使用文档(推荐,免费,手机电脑均可使用)](./wiki/claw.md) 感谢[@IDeposit](https://github.com/IDeposit)编写 +- [同上,看不到的看这里](https://blog.rzline.eu.org/2025/04/29/Claw%20Cloud%E9%83%A8%E7%BD%B2Gemini%E8%BD%AE%E8%AF%A2%E9%A1%B9%E7%9B%AEHajimi) + +- [docker部署的使用文档(服务器自建使用)](./wiki/docker.md) 感谢[@北极星星](https://github.com/beijixingxing)编写 + +- [termux部署的使用文档(手机使用)](./wiki/Termux.md) 感谢[@天命不又](https://github.com/tmby)编写 + +- ~~[zeabur部署的使用文档(需付费)](./wiki/zeabur.md) 感谢**墨舞ink**编写~~(已过时且暂时无人更新,欢迎提交pull requests) + +- [vertex模式的使用文档](./wiki/vertex.md) + +### 更新日志 +* v0.2.5 + * 警告,本次新增了openai依赖库,非容器部署请拉取安装依赖库 + * 首发适配vertex快速模式,在配置key后,访问支持快速模式的模型时,将首先使用快速模式的key访问 + * 快速模式仅支持gemini-2.0-flash-001,gemini-2.0-flash-lite-001,gemini-2.5-pro-preview-03-25,gemini-2.5-flash-preview-04-17 + * 更新vertex模式ui,前端界面现在可以开启关闭假流式,快速模式与替换快速模式key + * 新增环境变量`VERTEX_EXPRESS_API_KEY`,为快速模式key + * 修复若干bug,提高系统稳定性 + +* v0.2.4 + * 为vertex模式适配gemini-2.5-pro-preview-05-06 + * 修复负载均衡模式bug + * 优化统计相关计算,占用性能更少 + * 修复若干bug,提高系统稳定性 + +* 历史版本更新日志请查看[update](./update.md) + +## ✨ 主要功能: + +### 🔑 API 密钥轮询和管理 + +### 📑 模型列表接口 + +### 💬 聊天补全接口: + +* 提供 `/v1/chat/completions` 接口,支持流式和非流式响应,支持函数调用,与 OpenAI API 格式兼容。 +* 支持的输入内容: 文本、文件、图像 +* 自动将 OpenAI 格式的请求转换为 Gemini 格式。 + +### 🔒 密码保护(可选): + +* 通过 `PASSWORD` 环境变量设置密码。 +* 提供默认密码 `"123"`。 + +### 🚦 速率限制和防滥用: + +* 通过环境变量自定义限制: + * `MAX_REQUESTS_PER_MINUTE`:每分钟最大请求数(默认 30)。 + * `MAX_REQUESTS_PER_DAY_PER_IP`:每天每个 IP 最大请求数(默认 600)。 +* 超过速率限制时返回 429 错误。 + +### 🧩 服务兼容 + +* 提供的接口与 OpenAI API 格式兼容,便于接入各种服务 + +## ⚠️ 注意事项: + +* **强烈建议在生产环境中设置 `PASSWORD` 环境变量,并使用强密码。** +* 根据你的使用情况调整速率限制相关的环境变量。 +* 确保你的 Gemini API 密钥具有足够的配额。 + + +## ⚙️ 特色功能: + +### 🎭 假流式传输 + +* **作用:** 解决部分网络环境下客户端通过非流式请求 Gemini 时可能遇到的断连问题。**默认开启**。 + +* **原理简述:** 当客户端请求流式响应时,本代理会每隔一段时间向客户端发出一个空信息以维持连接,同时在后台向 Gemini 发起一个完整的、非流式的请求。等 Gemini 返回完整响应后,再一次性将响应发回给客户端。 + +* **如何配置:** + * `FAKE_STREAMING`: 设置为 `true` (默认) 开启,设置为 `false` 关闭。 + * `FAKE_STREAMING_INTERVAL`: 设置发送空信息的间隔时间(秒),默认为 `1`。 + +* **注意:** 如果想使用真的流式请求,请**关闭**该功能 + +### ⚡ 并发与缓存 + +* **作用:** 允许您为用户的单次提问同时向 Gemini 发送多个请求,并将额外的成功响应缓存起来,用于后续重新生成回复。 + +* **注意:** 此功能**默认关闭** 。只有当您将并发数设置为 2 或以上时,缓存才会生效。缓存匹配要求提问的上下文与被缓存的问题**完全一致**(包括标点符号)。此外,该模式目前仅支持非流式及假流式传输 + +* **配置与说明:** + * `CONCURRENT_REQUESTS`: 设置每次用户提问时,同时向 Gemini 发送的请求数量。默认为 `1` (即关闭并发和缓存)。 + * `INCREASE_CONCURRENT_ON_FAILURE`: 当所有并发请求都失败时,临时增加多少并发数再次尝试。默认为 `0`。 + * `MAX_CONCURRENT_REQUESTS`: 允许的最大并发请求数。默认为 `3`。 + * `CACHE_EXPIRY_TIME`: 缓存的有效时间(秒),默认 `21600` (6小时)。 + * `MAX_CACHE_ENTRIES`: 最多缓存多少条响应,默认 `500`。 + * `PRECISE_CACHE`: 是否使用用户的全部消息,而不是最后八条来计算缓存键。默认为 `false`。 + + **Q: 新版本增加的并发缓存功能会增加 gemini 配额的使用量吗?** + + **A: 不会**。因为默认情况下该功能是关闭的。只有当你主动将并发数 `CONCURRENT_REQUESTS` 设置为大于 1 的数值时,才会实际发起并发请求,这才会消耗更多配额。 + + **Q: 如何使用并发缓存功能?** + + **A:** 修改环境变量 `CONCURRENT_REQUESTS`,使其等于你想在一次用户提问中同时向 Gemini 发送的请求数量(例如设置为 `3`)。这样设置后,如果一次并发请求中收到了多个成功的响应,除了第一个返回给用户外,其他的就会被缓存起来。 + +### 🎭 伪装信息 + +* **作用:** 在发送给 Gemini 的消息中添加一段随机生成的、无意义的字符串,用于“伪装”请求,可能有助于防止被识别为自动化程序。**默认开启**。 + +* **如何配置:** + * `RANDOM_STRING`: 设置为 `true` (默认) 开启,设置为 `false` 关闭。 + * `RANDOM_STRING_LENGTH`: 设置随机字符串的长度,默认为 `5`。 + +* **注意:** 如果使用非 SillyTavern 的其余客户端 (例如 cherryStudio ),请**关闭**该功能 + +### 🌐 联网模式 + +* **作用:** 让 Gemini 模型能够利用搜索工具进行联网搜索,以回答需要最新信息或超出其知识库范围的问题。 + +* **如何使用:** + 1. 将环境变量 `SEARCH_MODE` (默认为 `false`) 设置为 `true` 来启用此功能。 + 2. 在客户端请求时,选择模型名称带有 `-search` 后缀的模型(例如 `gemini-2.5-pro-exp-search`,具体可用模型请通过 `/v1/models` 接口查询)。 + +* **如何配置:** + * `SEARCH_MODE`: 设置为 `true` 启用,`false` 关闭。 + * `SEARCH_PROMPT`: 当使用联网模式时,附加给模型的提示词,引导它使用搜索工具。默认为 `(使用搜索工具联网搜索,需要在content中结合搜索内容)`。 + diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/app/api/__init__.py b/app/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0fb6ae637fff8f34502511fe02fa2e3402aa92b --- /dev/null +++ b/app/api/__init__.py @@ -0,0 +1,9 @@ +from app.api.routes import router, init_router +from app.api.dashboard import dashboard_router, init_dashboard_router + +__all__ = [ + 'router', + 'init_router', + 'dashboard_router', + 'init_dashboard_router' +] \ No newline at end of file diff --git a/app/api/auth.py b/app/api/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..014793f5c3530f187a0b20d90d4da3371d26f554 --- /dev/null +++ b/app/api/auth.py @@ -0,0 +1,16 @@ +from fastapi import HTTPException, Request +import app.config.settings as settings +# 密码验证依赖 +async def verify_password(request: Request, PASSWORD: str = None): + """验证请求中的Bearer令牌是否与配置的密码匹配""" + if PASSWORD: + auth_header = request.headers.get("Authorization") + if not auth_header or not auth_header.startswith("Bearer "): + raise HTTPException( + status_code=401, detail="Unauthorized: Missing or invalid token") + token = auth_header.split(" ")[1] + if token != PASSWORD: + raise HTTPException( + status_code=401, detail="Unauthorized: Invalid token") + + diff --git a/app/api/dashboard.py b/app/api/dashboard.py new file mode 100644 index 0000000000000000000000000000000000000000..378222bf94d0358ceb774713b19777b7cb03c3a7 --- /dev/null +++ b/app/api/dashboard.py @@ -0,0 +1,544 @@ +from fastapi import APIRouter, HTTPException, Depends +from datetime import datetime, timedelta +import time +import asyncio +import random +import threading +from app.utils import ( + log_manager, + ResponseCacheManager, + ActiveRequestsManager, + clean_expired_stats +) +import app.config.settings as settings +from app.services import GeminiClient +from app.utils.auth import verify_web_password +from app.utils.maintenance import api_call_stats_clean +from app.utils.logging import log, vertex_log_manager +from app.config.persistence import save_settings +from app.utils.stats import api_stats_manager +# 创建路由器 +dashboard_router = APIRouter(prefix="/api", tags=["dashboard"]) + +# 全局变量引用,将在init_dashboard_router中设置 +key_manager = None +response_cache_manager = None +active_requests_manager = None + +# 用于存储API密钥检测的进度信息 +api_key_test_progress = { + "is_running": False, + "completed": 0, + "total": 0, + "valid": 0, + "invalid": 0, + "is_completed": False +} + +def init_dashboard_router( + key_mgr, + cache_mgr, + active_req_mgr +): + """初始化仪表盘路由器""" + global key_manager, response_cache_manager, active_requests_manager + key_manager = key_mgr + response_cache_manager = cache_mgr + active_requests_manager = active_req_mgr + return dashboard_router + +@dashboard_router.get("/dashboard-data") +async def get_dashboard_data(): + """获取仪表盘数据的API端点,用于动态刷新""" + # 先清理过期数据,确保统计数据是最新的 + await api_stats_manager.maybe_cleanup() + await response_cache_manager.clean_expired() # 使用管理器清理缓存 + active_requests_manager.clean_completed() # 使用管理器清理活跃请求 + + # 获取当前统计数据 + now = datetime.now() + + # 使用新的统计系统获取调用数据 + last_24h_calls = api_stats_manager.get_calls_last_24h() + hourly_calls = api_stats_manager.get_calls_last_hour(now) + minute_calls = api_stats_manager.get_calls_last_minute(now) + + # 获取时间序列数据 + time_series_data, tokens_time_series = api_stats_manager.get_time_series_data(30, now) + + # 获取API密钥使用统计 + api_key_stats = api_stats_manager.get_api_key_stats(key_manager.api_keys) + + # 根据ENABLE_VERTEX设置决定返回哪种日志 + if settings.ENABLE_VERTEX: + recent_logs = vertex_log_manager.get_recent_logs(500) # 获取最近500条Vertex日志 + else: + recent_logs = log_manager.get_recent_logs(500) # 获取最近500条普通日志 + + # 获取缓存统计 + total_cache = response_cache_manager.cur_cache_num + + # 获取活跃请求统计 + active_count = len(active_requests_manager.active_requests) + active_done = sum(1 for task in active_requests_manager.active_requests.values() if task.done()) + active_pending = active_count - active_done + + # 返回JSON格式的数据 + return { + "key_count": len(key_manager.api_keys), + "model_count": len(GeminiClient.AVAILABLE_MODELS), + "retry_count": settings.MAX_RETRY_NUM, + "last_24h_calls": last_24h_calls, + "hourly_calls": hourly_calls, + "minute_calls": minute_calls, + "calls_time_series": time_series_data, # 添加API调用时间序列 + "tokens_time_series": tokens_time_series, # 添加Token使用时间序列 + "current_time": datetime.now().strftime('%H:%M:%S'), + "logs": recent_logs, + "api_key_stats": api_key_stats, + # 添加配置信息 + "max_requests_per_minute": settings.MAX_REQUESTS_PER_MINUTE, + "max_requests_per_day_per_ip": settings.MAX_REQUESTS_PER_DAY_PER_IP, + # 添加版本信息 + "local_version": settings.version["local_version"], + "remote_version": settings.version["remote_version"], + "has_update": settings.version["has_update"], + # 添加流式响应配置 + "fake_streaming": settings.FAKE_STREAMING, + "fake_streaming_interval": settings.FAKE_STREAMING_INTERVAL, + # 添加随机字符串配置 + "random_string": settings.RANDOM_STRING, + "random_string_length": settings.RANDOM_STRING_LENGTH, + # 添加联网搜索配置 + "search_mode": settings.search["search_mode"], + "search_prompt": settings.search["search_prompt"], + # 添加缓存信息 + "cache_entries": total_cache, + "cache_expiry_time": settings.CACHE_EXPIRY_TIME, + "max_cache_entries": settings.MAX_CACHE_ENTRIES, + # 添加活跃请求池信息 + "active_count": active_count, + "active_done": active_done, + "active_pending": active_pending, + # 添加并发请求配置 + "concurrent_requests": settings.CONCURRENT_REQUESTS, + "increase_concurrent_on_failure": settings.INCREASE_CONCURRENT_ON_FAILURE, + "max_concurrent_requests": settings.MAX_CONCURRENT_REQUESTS, + # 启用vertex + "enable_vertex": settings.ENABLE_VERTEX, + # 添加Vertex Express配置 + "enable_vertex_express": settings.ENABLE_VERTEX_EXPRESS, + "vertex_express_api_key": bool(settings.VERTEX_EXPRESS_API_KEY), # 只返回是否设置的状态 + # 添加最大重试次数 + "max_retry_num": settings.MAX_RETRY_NUM, + } + +@dashboard_router.post("/reset-stats") +async def reset_stats(password_data: dict): + """ + 重置API调用统计数据 + + Args: + password_data (dict): 包含密码的字典 + + Returns: + dict: 操作结果 + """ + try: + if not isinstance(password_data, dict): + raise HTTPException(status_code=422, detail="请求体格式错误:应为JSON对象") + + password = password_data.get("password") + if not password: + raise HTTPException(status_code=400, detail="缺少密码参数") + + if not isinstance(password, str): + raise HTTPException(status_code=422, detail="密码参数类型错误:应为字符串") + + if not verify_web_password(password): + raise HTTPException(status_code=401, detail="密码错误") + + # 调用重置函数 + await api_stats_manager.reset() + + return {"status": "success", "message": "API调用统计数据已重置"} + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=500, detail=f"重置失败:{str(e)}") + +@dashboard_router.post("/update-config") +async def update_config(config_data: dict): + """ + 更新配置项 + + Args: + config_data (dict): 包含配置项和密码的字典 + + Returns: + dict: 操作结果 + """ + try: + if not isinstance(config_data, dict): + raise HTTPException(status_code=422, detail="请求体格式错误:应为JSON对象") + + password = config_data.get("password") + if not password: + raise HTTPException(status_code=400, detail="缺少密码参数") + + if not isinstance(password, str): + raise HTTPException(status_code=422, detail="密码参数类型错误:应为字符串") + + if not verify_web_password(password): + raise HTTPException(status_code=401, detail="密码错误") + + # 获取要更新的配置项 + config_key = config_data.get("key") + config_value = config_data.get("value") + + if not config_key: + raise HTTPException(status_code=400, detail="缺少配置项键名") + + # 根据配置项类型进行类型转换和验证 + if config_key == "max_requests_per_minute": + try: + value = int(config_value) + if value <= 0: + raise ValueError("每分钟请求限制必须大于0") + settings.MAX_REQUESTS_PER_MINUTE = value + log('info', f"每分钟请求限制已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "max_requests_per_day_per_ip": + try: + value = int(config_value) + if value <= 0: + raise ValueError("每IP每日请求限制必须大于0") + settings.MAX_REQUESTS_PER_DAY_PER_IP = value + log('info', f"每IP每日请求限制已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "fake_streaming": + if not isinstance(config_value, bool): + raise HTTPException(status_code=422, detail="参数类型错误:应为布尔值") + settings.FAKE_STREAMING = config_value + log('info', f"假流式请求已更新为:{config_value}") + + elif config_key == "enable_vertex_express": + if not isinstance(config_value, bool): + raise HTTPException(status_code=422, detail="参数类型错误:应为布尔值") + settings.ENABLE_VERTEX_EXPRESS = config_value + log('info', f"Vertex Express已更新为:{config_value}") + + elif config_key == "vertex_express_api_key": + if not isinstance(config_value, str): + raise HTTPException(status_code=422, detail="参数类型错误:应为字符串") + settings.VERTEX_EXPRESS_API_KEY = config_value + log('info', f"Vertex Express API Key已更新") + + elif config_key == "fake_streaming_interval": + try: + value = float(config_value) + if value <= 0: + raise ValueError("假流式间隔必须大于0") + settings.FAKE_STREAMING_INTERVAL = value + log('info', f"假流式间隔已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "random_string": + if not isinstance(config_value, bool): + raise HTTPException(status_code=422, detail="参数类型错误:应为布尔值") + settings.RANDOM_STRING = config_value + log('info', f"随机字符串已更新为:{config_value}") + elif config_key == "random_string_length": + try: + value = int(config_value) + if value <= 0: + raise ValueError("随机字符串长度必须大于0") + settings.RANDOM_STRING_LENGTH = value + log('info', f"随机字符串长度已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "search_mode": + if not isinstance(config_value, bool): + raise HTTPException(status_code=422, detail="参数类型错误:应为布尔值") + settings.search["search_mode"] = config_value + log('info', f"联网搜索模式已更新为:{config_value}") + + # 在切换search_mode时,重新获取一次可用模型列表 + try: + # 重置密钥栈以确保随机性 + key_manager._reset_key_stack() + # 获取一个随机API密钥 + for key in key_manager.api_keys: + log('info', f"使用API密钥 {key[:8]}... 刷新可用模型列表") + # 使用随机密钥获取可用模型 + all_models = await GeminiClient.list_available_models(key) + GeminiClient.AVAILABLE_MODELS = [model.replace("models/", "") for model in all_models] + if len(GeminiClient.AVAILABLE_MODELS) > 0: + log('info', f"可用模型列表已更新,当前模型数量:{len(GeminiClient.AVAILABLE_MODELS)}") + break + else: + log('warning', f"没有可用的API密钥,无法刷新可用模型列表") + except Exception as e: + log('warning', f"刷新可用模型列表时发生错误: {str(e)}") + + elif config_key == "concurrent_requests": + try: + value = int(config_value) + if value <= 0: + raise ValueError("并发请求数必须大于0") + settings.CONCURRENT_REQUESTS = value + log('info', f"并发请求数已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "increase_concurrent_on_failure": + try: + value = int(config_value) + if value < 0: + raise ValueError("失败时增加的并发数不能为负数") + settings.INCREASE_CONCURRENT_ON_FAILURE = value + log('info', f"失败时增加的并发数已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "max_concurrent_requests": + try: + value = int(config_value) + if value <= 0: + raise ValueError("最大并发请求数必须大于0") + settings.MAX_CONCURRENT_REQUESTS = value + log('info', f"最大并发请求数已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "enable_vertex": + if not isinstance(config_value, bool): + raise HTTPException(status_code=422, detail="参数类型错误:应为布尔值") + settings.ENABLE_VERTEX = config_value + log('info', f"Vertex AI 已更新为:{config_value}") + + elif config_key == "max_retry_num": + try: + value = int(config_value) + if value <= 0: + raise ValueError("最大重试次数必须大于0") + settings.MAX_RETRY_NUM = value + log('info', f"最大重试次数已更新为:{value}") + except ValueError as e: + raise HTTPException(status_code=422, detail=f"参数类型错误:{str(e)}") + + elif config_key == "search_prompt": + if not isinstance(config_value, str): + raise HTTPException(status_code=422, detail="参数类型错误:应为字符串") + settings.search["search_prompt"] = config_value + log('info', f"联网搜索提示已更新为:{config_value}") + + elif config_key == "gemini_api_keys": + if not isinstance(config_value, str): + raise HTTPException(status_code=422, detail="参数类型错误:API密钥应为逗号分隔的字符串") + + # 分割并清理API密钥 + new_keys = [key.strip() for key in config_value.split(',') if key.strip()] + if not new_keys: + raise HTTPException(status_code=400, detail="未提供有效的API密钥") + + # 添加到现有的API密钥字符串中 + current_keys = settings.GEMINI_API_KEYS.split(',') if settings.GEMINI_API_KEYS else [] + current_keys = [key.strip() for key in current_keys if key.strip()] + + # 合并新旧密钥并去重 + all_keys = list(set(current_keys + new_keys)) + settings.GEMINI_API_KEYS = ','.join(all_keys) + + # 计算新添加的密钥数量 + added_key_count = 0 + for key in new_keys: + if key not in key_manager.api_keys: + key_manager.api_keys.append(key) + added_key_count += 1 + + # 重置密钥栈 + key_manager._reset_key_stack() + + # 如果可用模型为空,尝试获取模型列表 + if not GeminiClient.AVAILABLE_MODELS: + try: + # 使用新添加的密钥之一尝试获取可用模型 + for key in new_keys: + log('info', f"使用新添加的API密钥 {key[:8]}... 获取可用模型列表") + all_models = await GeminiClient.list_available_models(key) + GeminiClient.AVAILABLE_MODELS = [model.replace("models/", "") for model in all_models] + if GeminiClient.AVAILABLE_MODELS: + log('info', f"成功获取可用模型列表,共 {len(GeminiClient.AVAILABLE_MODELS)} 个模型") + break + except Exception as e: + log('warning', f"获取可用模型列表时发生错误: {str(e)}") + + log('info', f"已添加 {added_key_count} 个新API密钥,当前共有 {len(key_manager.api_keys)} 个") + + else: + raise HTTPException(status_code=400, detail=f"不支持的配置项:{config_key}") + save_settings() + return {"status": "success", "message": f"配置项 {config_key} 已更新"} + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=500, detail=f"更新失败:{str(e)}") + +@dashboard_router.post("/test-api-keys") +async def test_api_keys(password_data: dict): + """ + 测试所有API密钥的有效性 + + Args: + password_data (dict): 包含密码的字典 + + Returns: + dict: 操作结果 + """ + try: + if not isinstance(password_data, dict): + raise HTTPException(status_code=422, detail="请求体格式错误:应为JSON对象") + + password = password_data.get("password") + if not password: + raise HTTPException(status_code=400, detail="缺少密码参数") + + if not isinstance(password, str): + raise HTTPException(status_code=422, detail="密码参数类型错误:应为字符串") + + if not verify_web_password(password): + raise HTTPException(status_code=401, detail="密码错误") + + # 检查是否已经有测试在运行 + if api_key_test_progress["is_running"]: + raise HTTPException(status_code=409, detail="已有API密钥检测正在进行中") + + # 获取有效密钥列表 + valid_keys = key_manager.api_keys.copy() + + # 启动异步测试 + threading.Thread( + target=start_api_key_test_in_thread, + args=(valid_keys,), + daemon=True + ).start() + + return {"status": "success", "message": "API密钥检测已启动,将同时检测有效密钥和无效密钥"} + except HTTPException: + raise + except Exception as e: + raise HTTPException(status_code=500, detail=f"启动API密钥检测失败:{str(e)}") + +@dashboard_router.get("/test-api-keys/progress") +async def get_test_api_keys_progress(): + """ + 获取API密钥检测进度 + + Returns: + dict: 进度信息 + """ + return api_key_test_progress + +def check_api_key_in_thread(key): + """在线程中检查单个API密钥的有效性""" + loop = asyncio.new_event_loop() + asyncio.set_event_loop(loop) + try: + is_valid = loop.run_until_complete(test_api_key(key)) + if is_valid: + log('info', f"API密钥 {key[:8]}... 有效") + return key, True + else: + log('warning', f"API密钥 {key[:8]}... 无效") + return key, False + finally: + loop.close() + +async def test_api_key(key): + """测试单个API密钥是否有效""" + try: + # 尝试列出可用模型来检查API密钥是否有效 + all_models = await GeminiClient.list_available_models(key) + return len(all_models) > 0 + except Exception as e: + log('error', f"测试API密钥 {key[:8]}... 时出错: {str(e)}") + return False + +def start_api_key_test_in_thread(keys): + """在线程中启动API密钥检测过程""" + # 重置进度信息 + api_key_test_progress.update({ + "is_running": True, + "completed": 0, + "total": 0, # 稍后会更新 + "valid": 0, + "invalid": 0, + "is_completed": False + }) + + try: + # 获取所有需要检测的密钥(包括当前GEMINI_API_KEYS和INVALID_API_KEYS) + current_keys = keys + + # 获取当前无效密钥 + invalid_api_keys = settings.INVALID_API_KEYS.split(',') if settings.INVALID_API_KEYS else [] + invalid_api_keys = [key.strip() for key in invalid_api_keys if key.strip()] + + # 合并所有需要测试的密钥,去重 + all_keys_to_test = list(set(current_keys + invalid_api_keys)) + + # 更新总数 + api_key_test_progress["total"] = len(all_keys_to_test) + + # 创建有效和无效密钥列表 + valid_keys = [] + invalid_keys = [] + + # 检查每个密钥 + for key in all_keys_to_test: + # 检查密钥 + _, is_valid = check_api_key_in_thread(key) + + # 更新进度 + api_key_test_progress["completed"] += 1 + + # 将密钥添加到相应列表 + if is_valid: + valid_keys.append(key) + api_key_test_progress["valid"] += 1 + else: + invalid_keys.append(key) + api_key_test_progress["invalid"] += 1 + + # 更新全局密钥列表 + key_manager.api_keys = valid_keys + + # 更新设置中的有效和无效密钥 + settings.GEMINI_API_KEYS = ','.join(valid_keys) + settings.INVALID_API_KEYS = ','.join(invalid_keys) + + # 更新最大重试次数 + settings.MAX_RETRY_NUM = len(valid_keys) + + # 保存设置 + save_settings() + + # 重置密钥栈 + key_manager._reset_key_stack() + + log('info', f"API密钥检测完成。有效密钥: {len(valid_keys)},无效密钥: {len(invalid_keys)}") + except Exception as e: + log('error', f"API密钥检测过程中发生错误: {str(e)}") + finally: + # 标记检测完成 + api_key_test_progress.update({ + "is_running": False, + "is_completed": True + }) diff --git a/app/api/nonstream_handlers.py b/app/api/nonstream_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..19e111fa0341ffa7a88f16b07bf83758d588a4e3 --- /dev/null +++ b/app/api/nonstream_handlers.py @@ -0,0 +1,210 @@ +import asyncio +from fastapi import HTTPException, Request +from app.models import ChatCompletionRequest +from app.services import GeminiClient +from app.utils import update_api_call_stats +from app.utils.error_handling import handle_gemini_error +from app.utils.logging import log +import app.config.settings as settings +import random +from typing import Literal +from app.utils.response import openAI_from_Gemini, openAI_from_text +from app.utils.stats import get_api_key_usage + + +# 非流式请求处理函数 +async def process_nonstream_request( + chat_request: ChatCompletionRequest, + contents, + system_instruction, + current_api_key: str, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key: str +): + """处理非流式API请求""" + gemini_client = GeminiClient(current_api_key) + # 创建调用 Gemini API 的主任务 + gemini_task = asyncio.create_task( + gemini_client.complete_chat( + chat_request, + contents, + safety_settings_g2 if 'gemini-2.5' in chat_request.model else safety_settings, + system_instruction + ) + ) + # 使用 shield 保护任务不被外部轻易取消 + shielded_gemini_task = asyncio.shield(gemini_task) + + try: + # 等待受保护的 API 调用任务完成 + response_content = await shielded_gemini_task + response_content.set_model(chat_request.model) + + # 检查响应内容是否为空 + if not response_content or not response_content.text: + log('warning', f"API密钥 {current_api_key[:8]}... 返回空响应", + extra={'key': current_api_key[:8], 'request_type': 'non-stream', 'model': chat_request.model}) + return "empty" + + # 缓存响应结果 + await response_cache_manager.store(cache_key, response_content) + # 更新 API 调用统计 + await update_api_call_stats(settings.api_call_stats, endpoint=current_api_key, model=chat_request.model,token=response_content.total_token_count) + + return "success" + + except Exception as e: + # 处理 API 调用过程中可能发生的任何异常 + handle_gemini_error(e, current_api_key) + return "error" + + +# 处理 route 中发起请求的函数 +async def process_request( + chat_request: ChatCompletionRequest, + key_manager, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key: str +): + """处理非流式请求""" + global current_api_key + + # 转换消息格式 + contents, system_instruction = GeminiClient.convert_messages( + GeminiClient, chat_request.messages,model=chat_request.model) + + # --- 在开始处理前检查缓存 --- + cached_response, cache_hit = await response_cache_manager.get_and_remove(cache_key) + if cache_hit: + log('info', f"请求命中缓存 : {cache_key[:8]}...,直接返回缓存结果。", + extra={'request_type': 'non-stream', 'model': chat_request.model, 'cache_operation': 'hit_and_remove'}) + return openAI_from_Gemini(cached_response,stream=False) + + # 设置初始并发数 + current_concurrent = settings.CONCURRENT_REQUESTS + max_retry_num = settings.MAX_RETRY_NUM + + # 获取有效的API密钥 + valid_keys = [] + for _ in range(len(key_manager.api_keys)): + api_key = await key_manager.get_available_key() + if api_key: + # 获取API密钥的调用次数 + usage = await get_api_key_usage(settings.api_call_stats, api_key) + # 如果调用次数小于限制,则添加到有效密钥列表 + if usage < settings.API_KEY_DAILY_LIMIT: + valid_keys.append(api_key) + else: + log('warning', f"API密钥 {api_key[:8]}... 已达到每日调用限制 ({usage}/{settings.API_KEY_DAILY_LIMIT})", + extra={'key': api_key[:8], 'request_type': 'non-stream', 'model': chat_request.model}) + + # 如果没有有效密钥,则随机使用一个密钥 + if not valid_keys: + log('warning', "所有API密钥已达到每日调用限制,将随机使用一个密钥", + extra={'request_type': 'non-stream', 'model': chat_request.model}) + # 重置密钥栈并获取一个密钥 + key_manager._reset_key_stack() + get_key = await key_manager.get_available_key() + valid_keys = [get_key] if get_key else [] + + # 如果可用密钥数量小于并发数,则使用所有可用密钥 + if len(valid_keys) < current_concurrent: + current_concurrent = len(valid_keys) + + # 当前请求次数 + current_try_num = 0 + + # 空响应计数 + empty_response_count = 0 + + # 尝试使用不同API密钥,直到所有密钥都尝试过 + while valid_keys and (current_try_num < max_retry_num) and (empty_response_count < settings.MAX_EMPTY_RESPONSES): + # 获取当前批次的密钥 + batch_num = min(max_retry_num - current_try_num, current_concurrent) + + current_batch = valid_keys[:batch_num] + valid_keys = valid_keys[batch_num:] + + # 更新当前尝试次数 + current_try_num += batch_num + + # 创建并发任务 + tasks = [] + tasks_map = {} + for api_key in current_batch: + # 记录当前尝试的密钥信息 + log('info', f"非流式请求开始,使用密钥: {api_key[:8]}...", + extra={'key': api_key[:8], 'request_type': 'non-stream', 'model': chat_request.model}) + + # 创建任务 + task = asyncio.create_task( + process_nonstream_request( + chat_request, + contents, + system_instruction, + api_key, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key + ) + ) + tasks.append((api_key, task)) + tasks_map[task] = api_key + + # 等待所有任务完成或找到成功响应 + success = False + while tasks and not success: + # 短时间等待任务完成 + done, pending = await asyncio.wait( + [task for _, task in tasks], + return_when=asyncio.FIRST_COMPLETED + ) + # 检查已完成的任务是否成功 + for task in done: + api_key = tasks_map[task] + try: + status = task.result() + # 如果有成功响应内容 + if status == "success" : + success = True + log('info', f"非流式请求成功", + extra={'key': api_key[:8],'request_type': 'non-stream', 'model': chat_request.model}) + cached_response, cache_hit = await response_cache_manager.get_and_remove(cache_key) + return openAI_from_Gemini(cached_response,stream=False) + elif status == "empty": + # 增加空响应计数 + empty_response_count += 1 + log('warning', f"空响应计数: {empty_response_count}/{settings.MAX_EMPTY_RESPONSES}", + extra={'key': api_key[:8], 'request_type': 'non-stream', 'model': chat_request.model}) + + except Exception as e: + handle_gemini_error(e, api_key) + + # 更新任务列表,移除已完成的任务 + tasks = [(k, t) for k, t in tasks if not t.done()] + + # 如果当前批次没有成功响应,并且还有密钥可用,则继续尝试 + if not success and valid_keys: + # 增加并发数,但不超过最大并发数 + current_concurrent = min(current_concurrent + settings.INCREASE_CONCURRENT_ON_FAILURE, settings.MAX_CONCURRENT_REQUESTS) + log('info', f"所有并发请求失败或返回空响应,增加并发数至: {current_concurrent}", + extra={'request_type': 'non-stream', 'model': chat_request.model}) + + # 如果空响应次数达到限制,跳出循环,并返回酒馆正常响应(包含错误信息) + if empty_response_count >= settings.MAX_EMPTY_RESPONSES: + log('warning', f"空响应次数达到限制 ({empty_response_count}/{settings.MAX_EMPTY_RESPONSES}),停止轮询", + extra={'request_type': 'non-stream', 'model': chat_request.model}) + + return openAI_from_text(model=chat_request.model,content="空响应次数达到上限\n请修改输入提示词或开启防截断",finish_reason="stop",stream=False) + + # 如果所有尝试都失败 + log('error', "API key 替换失败,所有API key都已尝试,请重新配置或稍后重试", extra={'request_type': 'switch_key'}) + + return openAI_from_text(model=chat_request.model,content="所有 API 密钥均请求失败\n具体错误请查看轮询日志",finish_reason="stop",stream=False) + + # raise HTTPException(status_code=500, detail=f"API key 替换失败,所有API key都已尝试,请重新配置或稍后重试") diff --git a/app/api/routes.py b/app/api/routes.py new file mode 100644 index 0000000000000000000000000000000000000000..492ff7c5b407edc6300aeb6838c6d65bb98e532f --- /dev/null +++ b/app/api/routes.py @@ -0,0 +1,289 @@ +import json +from fastapi import APIRouter, HTTPException, Request, Depends, status +from fastapi.responses import StreamingResponse +from app.models import ChatCompletionRequest, ChatCompletionResponse, ModelList +from app.services import GeminiClient +from app.utils import protect_from_abuse,generate_cache_key_all,generate_cache_key,openAI_from_text,log +from app.utils.response import openAI_from_Gemini +from .stream_handlers import process_stream_request +from .nonstream_handlers import process_request +from app.models.schemas import ChatCompletionResponse +from app.vertex.vertex import list_models as list_models_vertex +import app.config.settings as settings +import asyncio + +# 导入拆分后的模块 +from .auth import verify_password + +# 创建路由器 +router = APIRouter() + +# 全局变量引用 - 这些将在main.py中初始化并传递给路由 +key_manager = None +response_cache_manager = None +active_requests_manager = None +safety_settings = None +safety_settings_g2 = None +current_api_key = None +FAKE_STREAMING = None +FAKE_STREAMING_INTERVAL = None +PASSWORD = None +MAX_REQUESTS_PER_MINUTE = None +MAX_REQUESTS_PER_DAY_PER_IP = None + +# 初始化路由器的函数 +def init_router( + _key_manager, + _response_cache_manager, + _active_requests_manager, + _safety_settings, + _safety_settings_g2, + _current_api_key, + _fake_streaming, + _fake_streaming_interval, + _password, + _max_requests_per_minute, + _max_requests_per_day_per_ip +): + global key_manager, response_cache_manager, active_requests_manager + global safety_settings, safety_settings_g2, current_api_key + global FAKE_STREAMING, FAKE_STREAMING_INTERVAL + global PASSWORD, MAX_REQUESTS_PER_MINUTE, MAX_REQUESTS_PER_DAY_PER_IP + + key_manager = _key_manager + response_cache_manager = _response_cache_manager + active_requests_manager = _active_requests_manager + safety_settings = _safety_settings + safety_settings_g2 = _safety_settings_g2 + current_api_key = _current_api_key + FAKE_STREAMING = _fake_streaming + FAKE_STREAMING_INTERVAL = _fake_streaming_interval + PASSWORD = _password + MAX_REQUESTS_PER_MINUTE = _max_requests_per_minute + MAX_REQUESTS_PER_DAY_PER_IP = _max_requests_per_day_per_ip + +# 自定义密码验证依赖 +async def custom_verify_password(request: Request): + await verify_password(request, settings.PASSWORD) + +async def verify_user_agent(request: Request): + if not settings.WHITELIST_USER_AGENT: + return + if request.headers.get("User-Agent") not in settings.WHITELIST_USER_AGENT: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Not allowed client") + +async def get_cached(cache_key,is_stream: bool): + # 检查缓存是否存在,如果存在,返回缓存 + cached_response, cache_hit = await response_cache_manager.get_and_remove(cache_key) + + if cache_hit and cached_response: + log('info', f"缓存命中: {cache_key[:8]}...", + extra={'request_type': 'non-stream', 'model': cached_response.model}) + + if is_stream: + chunk = openAI_from_Gemini(cached_response,stream=True) + return StreamingResponse(chunk, media_type="text/event-stream") + else: + return openAI_from_Gemini(cached_response,stream=False) + + return None + +@router.get("/aistudio/models",response_model=ModelList) +async def aistudio_list_models(_ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + if settings.WHITELIST_MODELS: + filtered_models = [model for model in GeminiClient.AVAILABLE_MODELS if model in settings.WHITELIST_MODELS] + else: + filtered_models = [model for model in GeminiClient.AVAILABLE_MODELS if model not in settings.BLOCKED_MODELS] + return ModelList(data=[{"id": model, "object": "model", "created": 1678888888, "owned_by": "organization-owner"} for model in filtered_models]) + +@router.get("/vertex/models",response_model=ModelList) +async def vertex_list_models(_ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + # 使用Vertex AI实现 + from app.vertex.vertex import list_models as vertex_list_models + + # 调用Vertex AI实现 + vertex_response = await vertex_list_models(api_key=current_api_key) + + # 转换为ModelList格式 + return ModelList(data=vertex_response.get("data", [])) + +# API路由 +@router.get("/v1/models",response_model=ModelList) +@router.get("/models",response_model=ModelList) +async def list_models(_ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + if settings.ENABLE_VERTEX: + return await vertex_list_models(_, _2) + return await aistudio_list_models(_, _2) + +@router.post("/aistudio/chat/completions", response_model=ChatCompletionResponse) +async def aistudio_chat_completions(request: ChatCompletionRequest, http_request: Request, + _ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + + global current_api_key + + # 生成缓存键 - 用于匹配请求内容对应缓存 + if settings.PRECISE_CACHE: + cache_key = generate_cache_key_all(request) + else: + cache_key = generate_cache_key(request,8) + + # 请求前基本检查 + await protect_from_abuse( + http_request, + settings.MAX_REQUESTS_PER_MINUTE, + settings.MAX_REQUESTS_PER_DAY_PER_IP) + + if request.model not in GeminiClient.AVAILABLE_MODELS: + log('error', "无效的模型", + extra={'model': request.model, 'status_code': 400}) + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="无效的模型") + + + # 记录请求缓存键信息 + log('info', f"请求缓存键: {cache_key[:8]}...", + extra={'request_type': 'non-stream', 'model': request.model}) + + # 检查缓存是否存在,如果存在,返回缓存 + cached_response = await get_cached(cache_key, is_stream = request.stream) + if cached_response : + return cached_response + + if not settings.PUBLIC_MODE: + # 构建包含缓存键的活跃请求池键 + pool_key = f"{cache_key}" + + # 查找所有使用相同缓存键的活跃任务 + active_task = active_requests_manager.get(pool_key) + if active_task and not active_task.done(): + log('info', f"发现相同请求的进行中任务", + extra={'request_type': 'stream' if request.stream else "non-stream", 'model': request.model}) + + # 等待已有任务完成 + try: + # 设置超时,避免无限等待 + await asyncio.wait_for(active_task, timeout=180) + + # 使用任务结果 + if active_task.done() and not active_task.cancelled(): + + result = active_task.result() + active_requests_manager.remove(pool_key) + if result: + return result + + except (asyncio.TimeoutError, asyncio.CancelledError) as e: + # 任务超时或被取消的情况下,记录日志然后让代码继续执行 + error_type = "超时" if isinstance(e, asyncio.TimeoutError) else "被取消" + log('warning', f"等待已有任务{error_type}: {pool_key}", + extra={'request_type': 'non-stream', 'model': request.model}) + + # 从活跃请求池移除该任务 + if active_task.done() or active_task.cancelled(): + active_requests_manager.remove(pool_key) + log('info', f"已从活跃请求池移除{error_type}任务: {pool_key}", + extra={'request_type': 'non-stream'}) + + + if request.stream: + # 流式请求处理任务 + process_task = asyncio.create_task( + process_stream_request( + chat_request = request, + key_manager=key_manager, + response_cache_manager = response_cache_manager, + safety_settings = safety_settings, + safety_settings_g2 = safety_settings_g2, + cache_key = cache_key + ) + ) + + else: + # 创建非流式请求处理任务 + process_task = asyncio.create_task( + process_request( + chat_request = request, + key_manager = key_manager, + response_cache_manager = response_cache_manager, + safety_settings = safety_settings, + safety_settings_g2 = safety_settings_g2, + cache_key = cache_key + ) + ) + + if not settings.PUBLIC_MODE: + # 将任务添加到活跃请求池 + active_requests_manager.add(pool_key, process_task) + + # 等待任务完成 + try: + response = await process_task + if not settings.PUBLIC_MODE: + active_requests_manager.remove(pool_key) + + return response + except Exception as e: + if not settings.PUBLIC_MODE: + # 如果任务失败,从活跃请求池中移除 + active_requests_manager.remove(pool_key) + + # 检查是否已有缓存的结果(可能是由另一个任务创建的) + cached_response = await get_cached(cache_key, is_stream = request.stream) + if cached_response : + return cached_response + + # 发送错误信息给客户端 + raise HTTPException(status_code=500, detail=f" hajimi 服务器内部处理时发生错误\n具体原因:{e}") + +@router.post("/vertex/chat/completions", response_model=ChatCompletionResponse) +async def vertex_chat_completions(request: ChatCompletionRequest, http_request: Request, + _ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + global current_api_key + + # 使用Vertex AI实现 + from app.vertex.vertex import chat_completions as vertex_chat_completions + from app.vertex.vertex import OpenAIRequest, OpenAIMessage, get_api_key + + # 转换消息格式 + openai_messages = [] + for message in request.messages: + openai_messages.append(OpenAIMessage( + role=message.role, + content=message.content + )) + + # 转换请求格式 + vertex_request = OpenAIRequest( + model=request.model, + messages=openai_messages, + temperature=request.temperature, + max_tokens=request.max_tokens, + top_p=request.top_p, + top_k=request.top_k, + stream=request.stream, + stop=request.stop, + presence_penalty=request.presence_penalty, + frequency_penalty=request.frequency_penalty, + seed=getattr(request, 'seed', None), + logprobs=getattr(request, 'logprobs', None), + response_logprobs=getattr(request, 'response_logprobs', None), + n=request.n + ) + + # 调用Vertex AI实现 + return await vertex_chat_completions(vertex_request, api_key=current_api_key) + +@router.post("/v1/chat/completions", response_model=ChatCompletionResponse) +@router.post("/chat/completions", response_model=ChatCompletionResponse) +async def chat_completions(request: ChatCompletionRequest, http_request: Request, + _ = Depends(custom_verify_password), + _2 = Depends(verify_user_agent)): + """处理API请求的主函数,根据需要处理流式或非流式请求""" + if settings.ENABLE_VERTEX: + return await vertex_chat_completions(request, http_request, _, _2) + return await aistudio_chat_completions(request, http_request, _, _2) diff --git a/app/api/stream_handlers.py b/app/api/stream_handlers.py new file mode 100644 index 0000000000000000000000000000000000000000..d44af6b04862faafa8bddb95410950af14da90a5 --- /dev/null +++ b/app/api/stream_handlers.py @@ -0,0 +1,299 @@ +import asyncio +from fastapi.responses import StreamingResponse +from app.models import ChatCompletionRequest +from app.services import GeminiClient +from app.utils import handle_gemini_error, update_api_call_stats,log,openAI_from_text +from app.utils.response import openAI_from_Gemini +from app.utils.stats import get_api_key_usage +import app.config.settings as settings + +async def stream_response_generator( + chat_request: ChatCompletionRequest, + key_manager, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key: str +): + # 转换消息格式 + contents, system_instruction = GeminiClient.convert_messages( + GeminiClient, chat_request.messages,model=chat_request.model) + + + # 获取有效的API密钥 + valid_keys = [] + for _ in range(len(key_manager.api_keys)): + api_key = await key_manager.get_available_key() + if api_key: + # 获取API密钥的调用次数 + usage = await get_api_key_usage(settings.api_call_stats, api_key) + # 如果调用次数小于限制,则添加到有效密钥列表 + if usage < settings.API_KEY_DAILY_LIMIT: + valid_keys.append(api_key) + else: + log('warning', f"API密钥 {api_key[:8]}... 已达到每日调用限制 ({usage}/{settings.API_KEY_DAILY_LIMIT})", + extra={'key': api_key[:8], 'request_type': 'stream', 'model': chat_request.model}) + + # 如果没有有效密钥,则随机使用一个密钥 + if not valid_keys: + log('warning', "所有API密钥已达到每日调用限制,将随机使用一个密钥", + extra={'request_type': 'stream', 'model': chat_request.model}) + # 重置密钥栈并获取一个密钥 + key_manager._reset_key_stack() + get_key = await key_manager.get_available_key() + valid_keys = [get_key] if get_key else [] + + # 设置初始并发数 + current_concurrent = settings.CONCURRENT_REQUESTS + max_retry_num = settings.MAX_RETRY_NUM + + + # 如果可用密钥数量小于并发数,则使用所有可用密钥 + keys_num = len(valid_keys) + if keys_num < current_concurrent: + current_concurrent = keys_num + + # 当前请求次数 + current_try_num = 0 + + # 空响应计数 + empty_response_count = 0 + + # (假流式) 尝试使用不同API密钥,直到所有密钥都尝试过 + while (valid_keys and settings.FAKE_STREAMING and (current_try_num < min(max_retry_num,keys_num)) ): + + # 获取当前批次的密钥 + batch_num= min(max_retry_num - current_try_num, current_concurrent) + + current_batch = valid_keys[:batch_num] + valid_keys = valid_keys[batch_num:] + + # 更新当前尝试次数 + current_try_num += batch_num + + # 创建并发任务 + tasks = [] + tasks_map = {} + for api_key in current_batch: + # 假流式模式的处理逻辑 + log('info', f"假流式请求开始,使用密钥: {api_key[:8]}...", + extra={'key': api_key[:8], 'request_type': 'fake-stream', 'model': chat_request.model}) + + task = asyncio.create_task( + handle_fake_streaming( + api_key, + chat_request, + contents, + response_cache_manager, + system_instruction, + safety_settings, + safety_settings_g2, + cache_key + ) + ) + + tasks.append((api_key, task)) + tasks_map[task] = api_key + + # 等待所有任务完成或找到成功响应 + success = False + while tasks and not success: + # 等待任务完成 + done, pending = await asyncio.wait( + [task for _, task in tasks], + timeout=settings.FAKE_STREAMING_INTERVAL, + return_when=asyncio.FIRST_COMPLETED + ) + + # 如果没有任务完成,发送保活消息 + if not done : + yield openAI_from_text(model=chat_request.model,content='',stream=True) + continue + + # 检查已完成的任务是否成功 + for task in done: + api_key = tasks_map[task] + if not task.cancelled(): + try: + status = task.result() + # 如果有成功响应内容 + if status == "success" : + success = True + log('info', f"假流式请求成功", + extra={'key': api_key[:8],'request_type': "fake-stream", 'model': chat_request.model}) + cached_response, cache_hit = await response_cache_manager.get_and_remove(cache_key) + if cache_hit and cached_response: + yield openAI_from_Gemini(cached_response,stream=True) + else: + success = False + break + elif status == "empty": + # 增加空响应计数 + empty_response_count += 1 + log('warning', f"空响应计数: {empty_response_count}/{settings.MAX_EMPTY_RESPONSES}", + extra={'key': api_key[:8], 'request_type': 'stream', 'model': chat_request.model}) + + except Exception as e: + error_detail = handle_gemini_error(e, api_key) + log('error', f"请求失败: {error_detail}", + extra={'key': api_key[:8], 'request_type': 'stream', 'model': chat_request.model}) + + # 如果找到成功的响应,跳出循环 + if success: + return + + # 如果空响应次数达到限制,跳出循环 + if empty_response_count >= settings.MAX_EMPTY_RESPONSES: + log('warning', f"空响应次数达到限制 ({empty_response_count}/{settings.MAX_EMPTY_RESPONSES}),停止轮询", + extra={'request_type': 'fake-stream', 'model': chat_request.model}) + yield openAI_from_text(model=chat_request.model,content="空响应次数达到上限\n请修改输入提示词",finish_reason="stop",stream=True) + + return + + # 更新任务列表,移除已完成的任务 + tasks = [(k, t) for k, t in tasks if not t.done()] + + # 如果所有请求都失败,增加并发数并继续尝试 + if not success and valid_keys: + # 增加并发数,但不超过最大并发数 + current_concurrent = min(current_concurrent + settings.INCREASE_CONCURRENT_ON_FAILURE, settings.MAX_CONCURRENT_REQUESTS) + log('info', f"所有假流式请求失败,增加并发数至: {current_concurrent}", + extra={'request_type': 'stream', 'model': chat_request.model}) + + # (真流式) 尝试使用不同API密钥,直到所有密钥都尝试过或达到尝试上限 + while (valid_keys and not settings.FAKE_STREAMING and (current_try_num < min(max_retry_num,keys_num)) ): + # 获取密钥 + api_key = valid_keys[0] + valid_keys = valid_keys[1:] + current_try_num += 1 + + success = False + try: + client = GeminiClient(api_key) + + # 获取流式响应 + stream_generator = client.stream_chat( + chat_request, + contents, + safety_settings_g2 if 'gemini-2.5' in chat_request.model else safety_settings, + system_instruction + ) + token=0 + # 处理流式响应 + async for chunk in stream_generator: + if chunk : + + if chunk.total_token_count: + token = int(chunk.total_token_count) + success = True + data = openAI_from_Gemini(chunk,stream=True) + # log('info', f"流式响应发送数据: {data}") + yield data + + else: + log('warning', f"流式请求返回空响应,空响应计数: {empty_response_count}/{settings.MAX_EMPTY_RESPONSES}", + extra={'key': api_key[:8], 'request_type': 'stream', 'model': chat_request.model}) + # 增加空响应计数 + empty_response_count += 1 + await update_api_call_stats( + settings.api_call_stats, + endpoint=api_key, + model=chat_request.model, + token=token + ) + break + + except Exception as e: + error_detail = handle_gemini_error(e, api_key) + log('error', f"流式响应: API密钥 {api_key[:8]}... 请求失败: {error_detail}", + extra={'key': api_key[:8], 'request_type': 'stream', 'model': chat_request.model}) + return + finally: + # 如果成功获取相应,更新API调用统计 + if success: + await update_api_call_stats( + settings.api_call_stats, + endpoint=api_key, + model=chat_request.model, + token=token + ) + return + + # 如果空响应次数达到限制,跳出循环 + if empty_response_count >= settings.MAX_EMPTY_RESPONSES: + + log('warning', f"空响应次数达到限制 ({empty_response_count}/{settings.MAX_EMPTY_RESPONSES}),停止轮询", + extra={'request_type': 'stream', 'model': chat_request.model}) + + yield openAI_from_text(model=chat_request.model,content="空响应次数达到上限\n请修改输入提示词",finish_reason="stop",stream=True) + + return + + # 所有API密钥都尝试失败的处理 + log('error', "所有 API 密钥均请求失败,请稍后重试", + extra={'key': 'ALL', 'request_type': 'stream', 'model': chat_request.model}) + yield openAI_from_text(model=chat_request.model,content="所有API密钥均请求失败\n具体错误请查看轮询日志",finish_reason="stop") + +# 处理假流式模式 +async def handle_fake_streaming(api_key,chat_request, contents, response_cache_manager,system_instruction, safety_settings, safety_settings_g2, cache_key): + + # 使用非流式请求内容 + gemini_client = GeminiClient(api_key) + + gemini_task = asyncio.create_task( + gemini_client.complete_chat( + chat_request, + contents, + safety_settings_g2 if 'gemini-2.5' in chat_request.model else safety_settings, + system_instruction + ) + ) + gemini_task = asyncio.shield(gemini_task) + + try: + # 获取响应内容 + response_content = await gemini_task + response_content.set_model(chat_request.model) + log('info', f"假流式成功获取响应,进行缓存", + extra={'key': api_key[:8], 'request_type': 'fake-stream', 'model': chat_request.model}) + + # 更新API调用统计 + await update_api_call_stats(settings.api_call_stats, endpoint=api_key, model=chat_request.model,token=response_content.total_token_count) + + # 检查响应内容是否为空 + if not response_content or not response_content.text: + log('warning', f"请求返回空响应", + extra={'key': api_key[:8], 'request_type': 'fake-stream', 'model': chat_request.model}) + return "empty" + + # 缓存 + await response_cache_manager.store(cache_key, response_content) + return "success" + + except Exception as e: + handle_gemini_error(e, api_key) + # log('error', f"假流式模式: API密钥 {api_key[:8]}... 请求失败: {error_detail}", + # extra={'key': api_key[:8], 'request_type': 'fake-stream', 'model': chat_request.model}) + return "error" + + + +# 流式请求处理函数 +async def process_stream_request( + chat_request: ChatCompletionRequest, + key_manager, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key: str +) -> StreamingResponse: + """处理流式API请求""" + + return StreamingResponse(stream_response_generator( + chat_request, + key_manager, + response_cache_manager, + safety_settings, + safety_settings_g2, + cache_key + ), media_type="text/event-stream") diff --git a/app/config/__init__.py b/app/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf06a83ef27779408ac849b0868bc629a06340f --- /dev/null +++ b/app/config/__init__.py @@ -0,0 +1,4 @@ +# 配置模块初始化文件 +import app.config.settings as settings +from app.config.safety import * +from app.config.persistence import save_settings, load_settings \ No newline at end of file diff --git a/app/config/persistence.py b/app/config/persistence.py new file mode 100644 index 0000000000000000000000000000000000000000..7002914e9a665a4765f700a76645a11b418605a8 --- /dev/null +++ b/app/config/persistence.py @@ -0,0 +1,101 @@ +import json +import os +import inspect +import pathlib +from app.config import settings +from app.utils.logging import log + +# 定义不应该被保存或加载的配置项 +EXCLUDED_SETTINGS = [ + "STORAGE_DIR", + "ENABLE_STORAGE", + "BASE_DIR", + "PASSWORD", + "WEB_PASSWORD", + "WHITELIST_MODELS", + "BLOCKED_MODELS", + "DEFAULT_BLOCKED_MODELS", + "PUBLIC_MODE", + "DASHBOARD_URL", + "version", + "GOOGLE_CREDENTIALS_JSON" +] + +def save_settings(): + """ + 将settings中所有的从os.environ.get获取的配置保存到JSON文件中, + 但排除特定的配置项 + """ + if settings.ENABLE_STORAGE: + # 确保存储目录存在 + storage_dir = pathlib.Path(settings.STORAGE_DIR) + storage_dir.mkdir(parents=True, exist_ok=True) + + # 设置JSON文件路径 + settings_file = storage_dir / "settings.json" + + # 获取settings模块中的所有变量 + settings_dict = {} + for name, value in inspect.getmembers(settings): + # 跳过内置和私有变量,以及函数/模块/类,以及排除列表中的配置项 + if (not name.startswith('_') and + not inspect.isfunction(value) and + not inspect.ismodule(value) and + not inspect.isclass(value) and + name not in EXCLUDED_SETTINGS): + + # 尝试将可序列化的值添加到字典中 + try: + json.dumps({name: value}) # 测试是否可序列化 + settings_dict[name] = value + except (TypeError, OverflowError): + # 如果不可序列化,则跳过 + continue + log('info', f"保存设置到JSON文件: {settings_file}") + + # 保存到JSON文件 + with open(settings_file, 'w', encoding='utf-8') as f: + json.dump(settings_dict, f, ensure_ascii=False, indent=4) + + return settings_file + +def load_settings(): + """ + 从JSON文件中加载设置并更新settings模块, + 排除特定的配置项,并合并GEMINI_API_KEYS + """ + if settings.ENABLE_STORAGE: + # 设置JSON文件路径 + storage_dir = pathlib.Path(settings.STORAGE_DIR) + settings_file = storage_dir / "settings.json" + + # 如果文件不存在,则返回 + if not settings_file.exists(): + return False + + # 从JSON文件中加载设置 + try: + with open(settings_file, 'r', encoding='utf-8') as f: + loaded_settings = json.load(f) + + # 保存当前环境变量中的GEMINI_API_KEYS + current_api_keys = settings.GEMINI_API_KEYS.split(',') if settings.GEMINI_API_KEYS else [] + current_api_keys = [key.strip() for key in current_api_keys if key.strip()] + + # 更新settings模块中的变量,但排除特定配置项 + for name, value in loaded_settings.items(): + if hasattr(settings, name) and name not in EXCLUDED_SETTINGS: + # 特殊处理GEMINI_API_KEYS,进行合并去重 + if name == "GEMINI_API_KEYS": + loaded_api_keys = value.split(',') if value else [] + loaded_api_keys = [key.strip() for key in loaded_api_keys if key.strip()] + all_keys = list(set(current_api_keys + loaded_api_keys)) + setattr(settings, name, ','.join(all_keys)) + else: + setattr(settings, name, value) + + log('info', f"加载设置成功") + return True + except Exception as e: + log('error', f"加载设置时出错: {e}") + return False \ No newline at end of file diff --git a/app/config/safety.py b/app/config/safety.py new file mode 100644 index 0000000000000000000000000000000000000000..8cd8f7e49c41499c7b143ee88e8e908a46c4116e --- /dev/null +++ b/app/config/safety.py @@ -0,0 +1,49 @@ +# 安全设置配置 + +# Gemini 1.0 安全设置 +SAFETY_SETTINGS = [ + { + "category": "HARM_CATEGORY_HARASSMENT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_HATE_SPEECH", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "threshold": "BLOCK_NONE" + }, + { + "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + "threshold": "BLOCK_NONE" + }, + { + "category": 'HARM_CATEGORY_CIVIC_INTEGRITY', + "threshold": 'BLOCK_NONE' + } +] + +# Gemini 2.0 安全设置 +SAFETY_SETTINGS_G2 = [ + { + "category": "HARM_CATEGORY_HARASSMENT", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_HATE_SPEECH", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", + "threshold": "OFF" + }, + { + "category": "HARM_CATEGORY_DANGEROUS_CONTENT", + "threshold": "OFF" + }, + { + "category": 'HARM_CATEGORY_CIVIC_INTEGRITY', + "threshold": 'OFF' + } +] \ No newline at end of file diff --git a/app/config/settings.py b/app/config/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..e1689786ce6f33695a731273d151b56fa1039a4f --- /dev/null +++ b/app/config/settings.py @@ -0,0 +1,95 @@ +import os +import pathlib +import logging +from datetime import datetime, timedelta +import asyncio +GEMINI_API_KEYS = os.environ.get("GEMINI_API_KEYS", "") +#失效的API密钥 +INVALID_API_KEYS = os.environ.get("INVALID_API_KEYS", "") +# 基础目录设置 +BASE_DIR = pathlib.Path(__file__).parent.parent +# 存储目录 +STORAGE_DIR = os.environ.get("STORAGE_DIR", "/hajimi/settings/") +ENABLE_STORAGE = os.environ.get("ENABLE_STORAGE", "false").lower() in ["true", "1", "yes"] +# 流式响应配置 +FAKE_STREAMING = os.environ.get("FAKE_STREAMING", "true").lower() in ["true", "1", "yes"] +# 假流式请求的空内容返回间隔(秒) +FAKE_STREAMING_INTERVAL = float(os.environ.get("FAKE_STREAMING_INTERVAL", "1")) + +# 空响应重试次数限制 +MAX_EMPTY_RESPONSES = int(os.environ.get("MAX_EMPTY_RESPONSES", "5")) # 默认最多允许5次空响应 + +#随机字符串 +RANDOM_STRING = os.environ.get("RANDOM_STRING", "true").lower() in ["true", "1", "yes"] +RANDOM_STRING_LENGTH = int(os.environ.get("RANDOM_STRING_LENGTH", "5")) + +# 是否启用Vertex AI +ENABLE_VERTEX = os.environ.get("ENABLE_VERTEX", "false").lower() in ["true", "1", "yes"] +GOOGLE_CREDENTIALS_JSON = os.environ.get("GOOGLE_CREDENTIALS_JSON", "") +ENABLE_VERTEX_EXPRESS = os.environ.get("ENABLE_VERTEX_EXPRESS", "false").lower() in ["true", "1", "yes"] +VERTEX_EXPRESS_API_KEY = os.environ.get("VERTEX_EXPRESS_API_KEY", None) +# 日志配置 +logging.getLogger("uvicorn").disabled = True +logging.getLogger("uvicorn.access").disabled = True + +# 安全配置 +PASSWORD = os.environ.get("PASSWORD", "123").strip('"') +WEB_PASSWORD = os.environ.get("WEB_PASSWORD", PASSWORD).strip('"') +MAX_REQUESTS_PER_MINUTE = int(os.environ.get("MAX_REQUESTS_PER_MINUTE", "30")) +MAX_REQUESTS_PER_DAY_PER_IP = int(os.environ.get("MAX_REQUESTS_PER_DAY_PER_IP", "600")) +RETRY_DELAY = 1 +MAX_RETRY_DELAY = 16 # 网络错误 5xx 重试时的最大等待时间 +MAX_RETRY_NUM = int(os.environ.get("MAX_RETRY_NUM", "15")) # 请求时的最大总轮询 key 数 + +# 并发请求配置 +CONCURRENT_REQUESTS = int(os.environ.get("CONCURRENT_REQUESTS", "1")) # 默认并发请求数 +INCREASE_CONCURRENT_ON_FAILURE = int(os.environ.get("INCREASE_CONCURRENT_ON_FAILURE", "0")) # 失败时增加的并发数 +MAX_CONCURRENT_REQUESTS = int(os.environ.get("MAX_CONCURRENT_REQUESTS", "3")) # 最大并发请求数 + +# API密钥使用限制 +# 默认每个API密钥每24小时可使用次数 +API_KEY_DAILY_LIMIT = int(os.environ.get("API_KEY_DAILY_LIMIT", "100")) + +# 缓存配置 +CACHE_EXPIRY_TIME = int(os.environ.get("CACHE_EXPIRY_TIME", "21600")) # 默认缓存 6 小时 (21600 秒) +MAX_CACHE_ENTRIES = int(os.environ.get("MAX_CACHE_ENTRIES", "500")) # 默认最多缓存500条响应 +PRECISE_CACHE = os.environ.get("PRECISE_CACHE", "false").lower() in ["true", "1", "yes"] #是否取所有消息来算缓存键 + +search={ + "search_mode":os.environ.get("SEARCH_MODE", "false").lower() in ["true", "1", "yes"], + "search_prompt":os.environ.get("SEARCH_PROMPT", "(使用搜索工具联网搜索,需要在content中结合搜索内容)").strip('"') +} + +version={ + "local_version":"0.0.0", + "remote_version":"0.0.0", + "has_update":False +} + +# API调用统计 +# 这个对象保留为空结构以保持向后兼容性 +# 实际统计数据已迁移到 app/utils/stats.py 中的 ApiStatsManager 类 +api_call_stats = { + 'calls': [] # 兼容旧版代码结构 +} + +# 用于保护 api_call_stats 并发访问的锁 +stats_lock = asyncio.Lock() + +# 模型屏蔽列表配置 +# 默认屏蔽的模型列表 +DEFAULT_BLOCKED_MODELS = [] + +# 从环境变量中读取屏蔽模型列表,如果未设置则使用默认列表 +# 环境变量格式应为逗号分隔的模型名称字符串 +BLOCKED_MODELS = os.environ.get("BLOCKED_MODELS", ",".join(DEFAULT_BLOCKED_MODELS)) +# 将字符串转换为列表 +BLOCKED_MODELS = { model.strip() for model in BLOCKED_MODELS.split(",") if model.strip() } +#公益站模式 +PUBLIC_MODE = os.environ.get("PUBLIC_MODE", "false").lower() in ["true", "1", "yes"] +#前端地址 +DASHBOARD_URL = os.environ.get("DASHBOARD_URL", "") +# 白名单模式 +WHITELIST_MODELS = { x.strip() for x in os.environ.get("WHITELIST_MODELS", "").split(",") if x.strip() } +# 白名单User-Agent +WHITELIST_USER_AGENT = { x.strip().lower() for x in os.environ.get("WHITELIST_USER_AGENT", "").split(",") if x.strip() } \ No newline at end of file diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000000000000000000000000000000000000..95ed19d53fd07589e9edc4908a8c17c0701367ea --- /dev/null +++ b/app/main.py @@ -0,0 +1,223 @@ +from fastapi import FastAPI, Request +from fastapi.responses import JSONResponse, HTMLResponse +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates +from app.models import ErrorResponse +from app.services import GeminiClient +from app.utils import ( + APIKeyManager, + test_api_key, + ResponseCacheManager, + ActiveRequestsManager, + check_version, + schedule_cache_cleanup, + handle_exception, + log +) +from app.config.persistence import save_settings, load_settings +from app.api import router, init_router, dashboard_router, init_dashboard_router +from app.vertex.vertex import init_vertex_ai +import app.config.settings as settings +from app.config.safety import SAFETY_SETTINGS, SAFETY_SETTINGS_G2 +import asyncio +import sys +import pathlib +import os +# 设置模板目录 +BASE_DIR = pathlib.Path(__file__).parent +templates = Jinja2Templates(directory=str(BASE_DIR / "templates")) + +app = FastAPI(limit="50M") + +# --------------- 全局实例 --------------- +load_settings() +# 初始化API密钥管理器 +key_manager = APIKeyManager() + +# 创建全局缓存字典,将作为缓存管理器的内部存储 +response_cache = {} + +# 初始化缓存管理器,使用全局字典作为存储 +response_cache_manager = ResponseCacheManager( + expiry_time=settings.CACHE_EXPIRY_TIME, + max_entries=settings.MAX_CACHE_ENTRIES, + cache_dict=response_cache +) + +# 活跃请求池 - 将作为活跃请求管理器的内部存储 +active_requests_pool = {} + +# 初始化活跃请求管理器 +active_requests_manager = ActiveRequestsManager(requests_pool=active_requests_pool) + +SKIP_CHECK_API_KEY = os.environ.get("SKIP_CHECK_API_KEY", "").lower() == "true" + +# --------------- 工具函数 --------------- + +async def check_remaining_keys_async(keys_to_check: list, initial_invalid_keys: list): + """ + 在后台异步检查剩余的 API 密钥。 + """ + local_invalid_keys = [] + found_valid_keys =False + + for key in keys_to_check: + try: + is_valid = await test_api_key(key) + if is_valid: + if key not in key_manager.api_keys: # 避免重复添加 + key_manager.api_keys.append(key) + found_valid_keys = True + log('info', f"API Key {key[:8]}... 有效") + else: + local_invalid_keys.append(key) + log('warning', f" API Key {key[:8]}... 无效") + except Exception as e: + log('warning', f"检查 API Key {key[:8]}... 时出错",extra={'error_message': str(e)}) + local_invalid_keys.append(key) # 出错也视为无效 + + await asyncio.sleep(0.05) # 短暂休眠,避免请求过于密集 + + if found_valid_keys: + key_manager._reset_key_stack() # 如果找到新的有效key,重置栈 + + # 合并所有无效密钥 (初始无效 + 后台检查出的无效) + combined_invalid_keys = list(set(initial_invalid_keys + local_invalid_keys)) + + # 获取当前设置中的无效密钥 + current_invalid_keys_str = settings.INVALID_API_KEYS or "" + current_invalid_keys_set = set(k.strip() for k in current_invalid_keys_str.split(',') if k.strip()) + + # 更新无效密钥集合 + new_invalid_keys_set = current_invalid_keys_set.union(set(combined_invalid_keys)) + + # 只有当无效密钥列表发生变化时才保存 + if new_invalid_keys_set != current_invalid_keys_set: + settings.INVALID_API_KEYS = ','.join(sorted(list(new_invalid_keys_set))) + save_settings() + + log('info', f"密钥检查任务完成。当前总可用密钥数量: {len(key_manager.api_keys)}") + +# 设置全局异常处理 +sys.excepthook = handle_exception + +# --------------- 事件处理 --------------- + +@app.on_event("startup") +async def startup_event(): + log('info', "Starting Gemini API proxy...") + await check_version() + init_vertex_ai() + log('info', "初始化Vertex AI") + schedule_cache_cleanup(response_cache_manager, active_requests_manager) + # 检查版本 + await check_version() + load_settings() + + # 密钥检查 + initial_keys = key_manager.api_keys.copy() + key_manager.api_keys = [] # 清空,等待检查结果 + first_valid_key = None + initial_invalid_keys = [] + keys_to_check_later = [] + + # 阻塞式查找第一个有效密钥 + for index, key in enumerate(initial_keys): + is_valid = await test_api_key(key) + if is_valid: + log('info', f"找到第一个有效密钥: {key[:8]}...") + first_valid_key = key + key_manager.api_keys.append(key) # 添加到管理器 + key_manager._reset_key_stack() + # 将剩余的key放入后台检查列表 + keys_to_check_later = initial_keys[index + 1:] + break # 找到即停止 + else: + log('warning', f"密钥 {key[:8]}... 无效") + initial_invalid_keys.append(key) + + if not first_valid_key: + log('error', "启动时未能找到任何有效 API 密钥!") + keys_to_check_later = [] # 没有有效key,无需后台检查 + else: + # 使用第一个有效密钥加载模型 + try: + all_models = await GeminiClient.list_available_models(first_valid_key) + GeminiClient.AVAILABLE_MODELS = [model.replace("models/", "") for model in all_models] + log('info', f"使用密钥 {first_valid_key[:8]}... 加载可用模型成功") + except Exception as e: + log('warning', f"使用密钥 {first_valid_key[:8]}... 加载可用模型失败",extra={'error_message': str(e)}) + + if not SKIP_CHECK_API_KEY: + # 创建后台任务检查剩余密钥 + if keys_to_check_later: + asyncio.create_task(check_remaining_keys_async(keys_to_check_later, initial_invalid_keys)) + else: + # 如果没有需要后台检查的key,也要处理初始无效key + current_invalid_keys_str = settings.INVALID_API_KEYS or "" + current_invalid_keys_set = set(k.strip() for k in current_invalid_keys_str.split(',') if k.strip()) + new_invalid_keys_set = current_invalid_keys_set.union(set(initial_invalid_keys)) + if new_invalid_keys_set != current_invalid_keys_set: + settings.INVALID_API_KEYS = ','.join(sorted(list(new_invalid_keys_set))) + save_settings() + log('info', f"更新初始无效密钥列表完成,总无效密钥数: {len(new_invalid_keys_set)}") + + else: # 跳过检查 + log('info',"跳过 API 密钥检查") + key_manager.api_keys.extend(keys_to_check_later) + key_manager._reset_key_stack() + + # 初始化路由器 + init_router( + key_manager, + response_cache_manager, + active_requests_manager, + SAFETY_SETTINGS, + SAFETY_SETTINGS_G2, + first_valid_key, + settings.FAKE_STREAMING, + settings.FAKE_STREAMING_INTERVAL, + settings.PASSWORD, + settings.MAX_REQUESTS_PER_MINUTE, + settings.MAX_REQUESTS_PER_DAY_PER_IP + ) + + # 初始化仪表盘路由器 + init_dashboard_router( + key_manager, + response_cache_manager, + active_requests_manager + ) + +# --------------- 异常处理 --------------- + +@app.exception_handler(Exception) +async def global_exception_handler(request: Request, exc: Exception): + from app.utils import translate_error + error_message = translate_error(str(exc)) + extra_log_unhandled_exception = {'status_code': 500, 'error_message': error_message} + log('error', f"Unhandled exception: {error_message}", extra=extra_log_unhandled_exception) + return JSONResponse(status_code=500, content=ErrorResponse(message=str(exc), type="internal_error").dict()) + +# --------------- 路由 --------------- + +app.include_router(router) +app.include_router(dashboard_router) + +# 挂载静态文件目录 +app.mount("/assets", StaticFiles(directory="app/templates/assets"), name="assets") + +# 设置根路由路径 +dashboard_path = f"/{settings.DASHBOARD_URL}" if settings.DASHBOARD_URL else "/" + +@app.get(dashboard_path, response_class=HTMLResponse) +async def root(request: Request): + """ + 根路由 - 返回静态 HTML 文件 + """ + base_url = str(request.base_url).replace("http", "https") + api_url = f"{base_url}v1" if base_url.endswith("/") else f"{base_url}/v1" + # 直接返回 index.html 文件 + return templates.TemplateResponse( + "index.html", {"request": request, "api_url": api_url} + ) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d62b0611f9c301fcaac1c486022a5282ed3ff93b --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1,19 @@ +from app.models.schemas import ( + Message, + ChatCompletionRequest, + Choice, + Usage, + ChatCompletionResponse, + ErrorResponse, + ModelList +) + +__all__ = [ + 'Message', + 'ChatCompletionRequest', + 'Choice', + 'Usage', + 'ChatCompletionResponse', + 'ErrorResponse', + 'ModelList' +] \ No newline at end of file diff --git a/app/models/schemas.py b/app/models/schemas.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc6fb6a128143fe949adf95b0dc1821558dbaf0 --- /dev/null +++ b/app/models/schemas.py @@ -0,0 +1,56 @@ +from typing import List, Dict, Optional, Union, Literal, Any +from pydantic import BaseModel, Field + +class Message(BaseModel): + role: str + content: Union[str, List[Dict[str, Any]], None] = None + tool_call_id: Optional[str] = None # Used when role is 'tool' + +class ChatCompletionRequest(BaseModel): + model: str + messages: List[Message] + temperature: float = 0.7 + top_p: Optional[float] = 1.0 + top_k: Optional[float] = 40.0 + n: int = 1 + stream: bool = False + stop: Optional[Union[str, List[str]]] = None + max_tokens: Optional[int] = None + presence_penalty: Optional[float] = 0.0 + frequency_penalty: Optional[float] = 0.0 + seed: Optional[int] = None + logprobs: Optional[int] = None + response_logprobs: Optional[bool] = None + thinking_budget: Optional[int] = None + reasoning_effort : Optional[str] = None + # 函数调用 + tools: Optional[List[Dict[str, Any]]] = None + tool_choice: Optional[Union[Literal["none", "auto"], Dict[str, Any]]] = "auto" + +class Choice(BaseModel): + index: int + message: Message + finish_reason: Optional[str] = None + +class Usage(BaseModel): + prompt_tokens: int = 0 + completion_tokens: int = 0 + total_tokens: int = 0 + +class ChatCompletionResponse(BaseModel): + id: str + object: Literal["chat.completion"] + created: int + model: str + choices: List[Choice] + usage: Usage = Field(default_factory=Usage) + +class ErrorResponse(BaseModel): + message: str + type: str + param: Optional[str] = None + code: Optional[str] = None + +class ModelList(BaseModel): + object: str = "list" + data: List[Dict] \ No newline at end of file diff --git a/app/services/OpenAI.py b/app/services/OpenAI.py new file mode 100644 index 0000000000000000000000000000000000000000..56d9dc1d11a422a01a86e13982baefec0ddcd554 --- /dev/null +++ b/app/services/OpenAI.py @@ -0,0 +1,108 @@ +import requests +import json +import os +import asyncio +from app.models import ChatCompletionRequest, Message +from dataclasses import dataclass +from typing import Optional, Dict, Any, List +import httpx +import logging +import secrets +import string +from app.utils import format_log_message +import app.config.settings as settings + +from app.utils.logging import log + +def generate_secure_random_string(length): + all_characters = string.ascii_letters + string.digits + secure_random_string = ''.join(secrets.choice(all_characters) for _ in range(length)) + return secure_random_string + +@dataclass +class GeneratedText: + text: str + finish_reason: Optional[str] = None + +class OpenAIClient: + + AVAILABLE_MODELS = [] + EXTRA_MODELS = os.environ.get("EXTRA_MODELS", "").split(",") + + def __init__(self, api_key: str): + self.api_key = api_key + + def filter_data_by_whitelist(data, allowed_keys): + """ + 根据白名单过滤字典。 + Args: + data (dict): 原始的 Python 字典 (代表 JSON 对象)。 + allowed_keys (list or set): 包含允许保留的键名的列表或集合。 + 使用集合 (set) 进行查找通常更快。 + Returns: + dict: 只包含白名单中键的新字典。 + """ + # 使用集合(set)可以提高查找效率,特别是当白名单很大时 + allowed_keys_set = set(allowed_keys) + # 使用字典推导式创建过滤后的新字典 + filtered_data = {key: value for key, value in data.items() if key in allowed_keys_set} + return filtered_data + + # 真流式处理 + async def stream_chat(self, request: ChatCompletionRequest): + whitelist = ["model", "messages", "temperature", "max_tokens","stream","tools","reasoning_effort","top_k","presence_penalty"] + + data = self.filter_data_by_whitelist(request, whitelist) + + + if settings.search["search_mode"] and data.model.endswith("-search"): + log('INFO', "开启联网搜索模式", extra={'key': self.api_key[:8], 'model':request.model}) + data.setdefault("tools", []).append({"google_search": {}}) + + data.model = data.model.removesuffix("-search") + + # 真流式请求处理逻辑 + extra_log = {'key': self.api_key[:8], 'request_type': 'stream', 'model': request.model} + log('INFO', "流式请求开始", extra=extra_log) + + + url = f"https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {self.api_key}" + } + + async with httpx.AsyncClient() as client: + async with client.stream("POST", url, headers=headers, json=data, timeout=600) as response: + buffer = b"" # 用于累积可能不完整的 JSON 数据 + try: + async for line in response.aiter_lines(): + if not line.strip(): # 跳过空行 (SSE 消息分隔符) + continue + if line.startswith("data: "): + line = line[len("data: "):].strip() # 去除 "data: " 前缀 + + # 检查是否是结束标志,如果是,结束循环 + if line == "[DONE]": + break + + buffer += line.encode('utf-8') + try: + # 尝试解析整个缓冲区 + data = json.loads(buffer.decode('utf-8')) + # 解析成功,清空缓冲区 + buffer = b"" + + yield data + + except json.JSONDecodeError: + # JSON 不完整,继续累积到 buffer + continue + except Exception as e: + log('ERROR', f"流式处理期间发生错误", + extra={'key': self.api_key[:8], 'request_type': 'stream', 'model': request.model}) + raise e + except Exception as e: + raise e + finally: + log('info', "流式请求结束") diff --git a/app/services/__init__.py b/app/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..228d10c3633d9fe30a1782aeda4f5d42ce24493c --- /dev/null +++ b/app/services/__init__.py @@ -0,0 +1,9 @@ +from app.services.gemini import GeminiClient, GeminiResponseWrapper, GeneratedText +from app.services.OpenAI import OpenAIClient + +__all__ = [ + 'GeminiClient', + 'OpenAIClient', + 'GeminiResponseWrapper', + 'GeneratedText' +] \ No newline at end of file diff --git a/app/services/gemini.py b/app/services/gemini.py new file mode 100644 index 0000000000000000000000000000000000000000..52f6ab36f9ee93c208aa004f31c7bd0355609905 --- /dev/null +++ b/app/services/gemini.py @@ -0,0 +1,441 @@ +import json +import os +import httpx # 添加 httpx 导入 +from app.models import ChatCompletionRequest +from dataclasses import dataclass +from typing import Optional, Dict, Any, List +import httpx +import secrets +import string +import app.config.settings as settings + +from app.utils.logging import log + +def generate_secure_random_string(length): + all_characters = string.ascii_letters + string.digits + secure_random_string = ''.join(secrets.choice(all_characters) for _ in range(length)) + return secure_random_string + +@dataclass +class GeneratedText: + text: str + finish_reason: Optional[str] = None + + +class GeminiResponseWrapper: + def __init__(self, data: Dict[Any, Any]): + self._data = data + self._text = self._extract_text() + self._finish_reason = self._extract_finish_reason() + self._prompt_token_count = self._extract_prompt_token_count() + self._candidates_token_count = self._extract_candidates_token_count() + self._total_token_count = self._extract_total_token_count() + self._thoughts = self._extract_thoughts() + self._function_call = self._extract_function_call() + self._json_dumps = json.dumps(self._data, indent=4, ensure_ascii=False) + self._model = "gemini" + + def _extract_thoughts(self) -> Optional[str]: + try: + for part in self._data['candidates'][0]['content']['parts']: + if 'thought' in part: + return part['text'] + return "" + except (KeyError, IndexError): + return "" + + def _extract_text(self) -> str: + try: + text="" + for part in self._data['candidates'][0]['content']['parts']: + if 'thought' not in part: + text += part['text'] + return text + except (KeyError, IndexError): + return "" + + def _extract_function_call(self) -> Optional[Dict[str, Any]]: + try: + parts = self._data.get('candidates', [{}])[0].get('content', {}).get('parts', []) + # 使用列表推导式查找所有包含 'functionCall' 的 part,并提取其值 + function_calls = [ + part['functionCall'] + for part in parts + if isinstance(part, dict) and 'functionCall' in part + ] + # 如果列表不为空,则返回列表;否则返回 None + return function_calls if function_calls else None + except (KeyError, IndexError, TypeError): + return None + + def _extract_finish_reason(self) -> Optional[str]: + try: + return self._data['candidates'][0].get('finishReason') + except (KeyError, IndexError): + return None + + def _extract_prompt_token_count(self) -> Optional[int]: + try: + return self._data['usageMetadata'].get('promptTokenCount') + except (KeyError): + return None + + def _extract_candidates_token_count(self) -> Optional[int]: + try: + return self._data['usageMetadata'].get('candidatesTokenCount') + except (KeyError): + return None + + def _extract_total_token_count(self) -> Optional[int]: + try: + return self._data['usageMetadata'].get('totalTokenCount') + except (KeyError): + return None + + def set_model(self,model) -> Optional[str]: + self._model = model + + @property + def text(self) -> str: + return self._text + + @property + def finish_reason(self) -> Optional[str]: + return self._finish_reason + + @property + def prompt_token_count(self) -> Optional[int]: + return self._prompt_token_count + + @property + def candidates_token_count(self) -> Optional[int]: + return self._candidates_token_count + + @property + def total_token_count(self) -> Optional[int]: + return self._total_token_count + + @property + def thoughts(self) -> Optional[str]: + return self._thoughts + + @property + def json_dumps(self) -> str: + return self._json_dumps + + @property + def model(self) -> str: + return self._model + + @property + def function_call(self) -> Optional[Dict[str, Any]]: + return self._function_call + + +class GeminiClient: + + AVAILABLE_MODELS = [] + EXTRA_MODELS = os.environ.get("EXTRA_MODELS", "").split(",") + + def __init__(self, api_key: str): + self.api_key = api_key + + # 请求参数处理 + def _prepare_request_data(self, request: ChatCompletionRequest, contents, safety_settings, system_instruction, model): + + config_params = { + "temperature": request.temperature, + "maxOutputTokens": request.max_tokens, + "topP": request.top_p, + "topK": request.top_k, + "stopSequences": request.stop if isinstance(request.stop, list) else [request.stop] if request.stop is not None else None, + "candidateCount": request.n, + } + if request.thinking_budget: + config_params["thinkingConfig"] = { + "thinkingBudget": request.thinking_budget + } + generationConfig = {k: v for k, v in config_params.items() if v is not None} + + api_version = "v1alpha" if "think" in request.model else "v1beta" + + data = { + "contents": contents, + "generationConfig": generationConfig, + "safetySettings": safety_settings, + } + + # --- 函数调用处理 --- + # 1. 添加 tools (函数声明) + function_declarations = [] + if request.tools: + # 显式提取 Gemini API 所需的字段,避免包含 'id' 等无效字段 + function_declarations = [] + for tool in request.tools: + if tool.get("type") == "function": + func_def = tool.get("function") + if func_def: + # 只包含 Gemini API 接受的字段 + declaration = { + "name": func_def.get("name"), + "description": func_def.get("description"), + } + # 获取 parameters 并移除可能存在的 $schema 字段 + parameters = func_def.get("parameters") + if isinstance(parameters, dict) and "$schema" in parameters: + parameters = parameters.copy() + del parameters["$schema"] + if parameters is not None: + declaration["parameters"] = parameters + + # 移除值为 None 的键,以保持 payload 清洁 + declaration = {k: v for k, v in declaration.items() if v is not None} + if declaration.get("name"): # 确保 name 存在 + function_declarations.append(declaration) + + if function_declarations: + data["tools"] = [{"function_declarations": function_declarations}] + + # 2. 添加 tool_config (基于 tool_choice) + tool_config = None + if request.tool_choice: + choice = request.tool_choice + mode = None + allowed_functions = None + if isinstance(choice, str): + if choice == "none": + mode = "NONE" + elif choice == "auto": + mode = "AUTO" + elif isinstance(choice, dict) and choice.get("type") == "function": + func_name = choice.get("function", {}).get("name") + if func_name: + mode = "ANY" # 'ANY' 模式用于强制调用特定函数 + allowed_functions = [func_name] + + # 如果成功解析出有效的 mode,构建 tool_config + if mode: + config = {"mode": mode} + if allowed_functions: + config["allowed_function_names"] = allowed_functions + tool_config = {"function_calling_config": config} + + # 3. 添加 tool_config 到 data + if tool_config: + data["tool_config"] = tool_config + + # 联网模式 + if settings.search["search_mode"] and model.endswith("-search"): + log('INFO', "开启联网搜索模式", extra={'key': self.api_key[:8], 'model':request.model}) + + data.setdefault("tools", []).append({"google_search": {}}) + + if system_instruction: + data["system_instruction"] = system_instruction + + return api_version, data + + + # 流式请求 + async def stream_chat(self, request: ChatCompletionRequest, contents, safety_settings, system_instruction): + # 真流式请求处理逻辑 + extra_log = {'key': self.api_key[:8], 'request_type': 'stream', 'model': request.model} + log('INFO', "流式请求开始", extra=extra_log) + + api_version, data = self._prepare_request_data(request, contents, safety_settings, system_instruction,request.model) + + model= request.model.removesuffix("-search") + url = f"https://generativelanguage.googleapis.com/{api_version}/models/{model}:streamGenerateContent?key={self.api_key}&alt=sse" + headers = { + "Content-Type": "application/json", + } + + async with httpx.AsyncClient() as client: + async with client.stream("POST", url, headers=headers, json=data, timeout=600) as response: + buffer = b"" # 用于累积可能不完整的 JSON 数据 + try: + async for line in response.aiter_lines(): + if not line.strip(): # 跳过空行 (SSE 消息分隔符) + continue + if line.startswith("data: "): + line = line[len("data: "):].strip() # 去除 "data: " 前缀 + + # 检查是否是结束标志,如果是,结束循环 + if line == "[DONE]": + break + + buffer += line.encode('utf-8') + try: + # 尝试解析整个缓冲区 + data = json.loads(buffer.decode('utf-8')) + # 解析成功,清空缓冲区 + buffer = b"" + + yield GeminiResponseWrapper(data) + + except json.JSONDecodeError: + # JSON 不完整,继续累积到 buffer + continue + except Exception as e: + log('ERROR', f"流式处理期间发生错误", + extra={'key': self.api_key[:8], 'request_type': 'stream', 'model': request.model}) + raise e + except Exception as e: + raise e + finally: + log('info', "流式请求结束") + + # 非流式处理 + async def complete_chat(self, request: ChatCompletionRequest, contents, safety_settings, system_instruction): + + api_version, data = self._prepare_request_data(request, contents, safety_settings, system_instruction,request.model) + model= request.model.removesuffix("-search") + url = f"https://generativelanguage.googleapis.com/{api_version}/models/{model}:generateContent?key={self.api_key}" + headers = { + "Content-Type": "application/json", + } + + try: + async with httpx.AsyncClient() as client: + response = await client.post(url, headers=headers, json=data, timeout=600) + response.raise_for_status() # 检查 HTTP 错误状态 + + return GeminiResponseWrapper(response.json()) + except Exception as e: + raise + + # OpenAI 格式请求转换为 gemini 格式请求 + def convert_messages(self, messages, use_system_prompt=False, model=None): + gemini_history = [] + errors = [] + + system_instruction_text = "" + system_instruction_parts = [] # 用于收集系统指令文本 + + # 处理系统指令 + if use_system_prompt: + # 遍历消息列表,查找开头的连续 system 消息 + for i, message in enumerate(messages): + # 必须是 system 角色且内容是字符串 + if message.role == 'system' and isinstance(message.content, str): + system_instruction_parts.append(message.content) + else: + break # 遇到第一个非 system 或内容非字符串的消息就停止 + + # 将收集到的系统指令合并为一个字符串 + system_instruction_text = "\n".join(system_instruction_parts) + system_instruction = {"parts": [{"text": system_instruction_text}]} if system_instruction_text else None + + # 转换主要消息 + + for i, message in enumerate(messages): + role = message.role + content = message.content + if isinstance(content, str): + + if role == 'tool': + role_to_use = 'function' + tool_call_id = message.tool_call_id + + prefix = "call_" + if tool_call_id.startswith(prefix): + # 假设 tool_call_id = f"call_{function_name}" (response.py中的处理) + function_name = tool_call_id[len(prefix):] + else: + continue + + function_response_part = { + "functionResponse": { + "name": function_name, + "response": {"content": content} + } + } + + gemini_history.append({"role": role_to_use, "parts": [function_response_part]}) + + continue + elif role in ['user', 'system']: + role_to_use = 'user' + elif role == 'assistant': + role_to_use = 'model' + + else: + errors.append(f"Invalid role: {role}") + continue + + # Gemini 的一个重要规则:连续的同角色消息需要合并 + # 如果 gemini_history 已有内容,并且最后一条消息的角色和当前要添加的角色相同 + if gemini_history and gemini_history[-1]['role'] == role_to_use: + gemini_history[-1]['parts'].append({"text": content}) + else: + gemini_history.append({"role": role_to_use, "parts": [{"text": content}]}) + elif isinstance(content, list): + parts = [] + for item in content: + if item.get('type') == 'text': + parts.append({"text": item.get('text')}) + elif item.get('type') == 'image_url': + image_data = item.get('image_url', {}).get('url', '') + if image_data.startswith('data:image/'): + try: + mime_type, base64_data = image_data.split(';')[0].split(':')[1], image_data.split(',')[1] + parts.append({ + "inline_data": { + "mime_type": mime_type, + "data": base64_data + } + }) + except (IndexError, ValueError): + errors.append( + f"Invalid data URI for image: {image_data}") + else: + errors.append( + f"Invalid image URL format for item: {item}") + + if parts: + if role in ['user', 'system']: + role_to_use = 'user' + elif role == 'assistant': + role_to_use = 'model' + else: + errors.append(f"Invalid role: {role}") + continue + + if gemini_history and gemini_history[-1]['role'] == role_to_use: + gemini_history[-1]['parts'].extend(parts) + else: + gemini_history.append( + {"role": role_to_use, "parts": parts}) + if errors: + return errors + + # --- 后处理 --- + + # 注入搜索提示 + if settings.search["search_mode"] and model and model.endswith("-search"): + gemini_history.insert(len(gemini_history)-2,{'role': 'user', 'parts': [{'text':settings.search["search_prompt"]}]}) + + # 注入随机字符串 + if settings.RANDOM_STRING: + gemini_history.insert(1,{'role': 'user', 'parts': [{'text': generate_secure_random_string(settings.RANDOM_STRING_LENGTH)}]}) + gemini_history.insert(len(gemini_history)-1,{'role': 'user', 'parts': [{'text': generate_secure_random_string(settings.RANDOM_STRING_LENGTH)}]}) + log('INFO', "伪装消息成功") + + return gemini_history, system_instruction + + @staticmethod + async def list_available_models(api_key) -> list: + url = "https://generativelanguage.googleapis.com/v1beta/models?key={}".format( + api_key) + async with httpx.AsyncClient() as client: + response = await client.get(url) + response.raise_for_status() + data = response.json() + models = [] + for model in data.get("models", []): + models.append(model["name"]) + if model["name"].startswith("models/gemini-2") and settings.search["search_mode"]: + models.append(model["name"] + "-search") + models.extend(GeminiClient.EXTRA_MODELS) + + return models diff --git a/app/templates/__init__.py b/app/templates/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8ff14b762c088cd92e0c38e30a754ed25f7a151d --- /dev/null +++ b/app/templates/__init__.py @@ -0,0 +1 @@ +# Templates package initialization \ No newline at end of file diff --git a/app/templates/assets/01231aa3833908b1eb1bb38e7e933589.html b/app/templates/assets/01231aa3833908b1eb1bb38e7e933589.html new file mode 100644 index 0000000000000000000000000000000000000000..8db473bfe09d20b61645a59758296f243530bedf --- /dev/null +++ b/app/templates/assets/01231aa3833908b1eb1bb38e7e933589.html @@ -0,0 +1,14 @@ + + +
+ + + +d&&(d=m,v=f+g)}var _=this.getRawIndex(c),S=this.getRawIndex(v);c 0?e:1:e))}var ZW=function(r,t,e,n){for(;eS&&(S=_),S!==v&&(y.width=S,c-=S+f*S,h--)}}),v=(c-u)/(h+(h-1)*f),v=Math.max(v,0);var d=0,p;D(i,function(y,m){y.width||(y.width=v),p=y,d+=y.width*(1+f)}),p&&(d-=p.width*f);var g=-d/2;D(i,function(y,m){e[a][m]=e[a][m]||{bandWidth:o,offset:g,width:y.width},g+=y.width*(1+f)})}),e}function YW(r,t,e){if(r&&t){var n=r[W_(t)];return n}}function aR(r,t){var e=eR(r,t),n=rR(e);D(e,function(a){var i=a.getData(),o=a.coordinateSystem,s=o.getBaseAxis(),l=tR(a),u=n[W_(s)][l],f=u.offset,c=u.width;i.setLayout({bandWidth:u.bandWidth,offset:f,size:c})})}function iR(r){return{seriesType:r,plan:_l(),reset:function(t){if(oR(t)){var e=t.getData(),n=t.coordinateSystem,a=n.getBaseAxis(),i=n.getOtherAxis(a),o=e.getDimensionIndex(e.mapDimension(i.dim)),s=e.getDimensionIndex(e.mapDimension(a.dim)),l=t.get("showBackground",!0),u=e.mapDimension(i.dim),f=e.getCalculationInfo("stackResultDimension"),c=wi(e,u)&&!!e.getCalculationInfo("stackedOnSeries"),h=i.isHorizontal(),v=XW(a,i),d=sR(t),p=t.get("barMinHeight")||0,g=f&&e.getDimensionIndex(f),y=e.getLayout("size"),m=e.getLayout("offset");return{progress:function(_,S){for(var x=_.count,b=d&&Gn(x*3),w=d&&l&&Gn(x*3),C=d&&Gn(x),T=n.master.getRect(),A=h?T.width:T.height,M,I=S.getStore(),L=0;(M=_.next())!=null;){var P=I.get(c?g:o,M),E=I.get(s,M),O=v,z=void 0;c&&(z=+P-I.get(o,M));var N=void 0,B=void 0,H=void 0,Z=void 0;if(h){var Q=n.dataToPoint([P,E]);if(c){var ft=n.dataToPoint([z,E]);O=ft[0]}N=O,B=Q[1]+m,H=Q[0]-O,Z=y,Math.abs(H)t){i?e.push(o(i,l,t)):a&&e.push(o(a,l,0),o(a,l,t));break}else a&&(e.push(o(a,l,0)),a=null),e.push(l),i=l}return e}function O$(r,t,e){var n=r.getVisual("visualMeta");if(!(!n||!n.length||!r.count())&&t.type==="cartesian2d"){for(var a,i,o=n.length-1;o>=0;o--){var s=r.getDimensionInfo(n[o].dimension);if(a=s&&s.coordDim,a==="x"||a==="y"){i=n[o];break}}if(i){var l=t.getAxis(a),u=K(i.stops,function(_){return{coord:l.toGlobalCoord(l.dataToCoord(_.value)),color:_.color}}),f=u.length,c=i.outerColors.slice();f&&u[0].coord>u[f-1].coord&&(u.reverse(),c.reverse());var h=k$(u,a==="x"?e.getWidth():e.getHeight()),v=h.length;if(!v&&f)return u[0].coord<0?c[1]?c[1]:u[f-1].color:c[0]?c[0]:u[0].color;var d=10,p=h[0].coord-d,g=h[v-1].coord+d,y=g-p;if(y<.001)return"transparent";D(h,function(_){_.offset=(_.coord-p)/y}),h.push({offset:v?h[v-1].offset:.5,color:c[1]||"transparent"}),h.unshift({offset:v?h[0].offset:.5,color:c[0]||"transparent"});var m=new $o(0,0,0,0,h,!0);return m[a]=p,m[a+"2"]=g,m}}}function N$(r,t,e){var n=r.get("showAllSymbol"),a=n==="auto";if(!(n&&!a)){var i=e.getAxesByScale("ordinal")[0];if(i&&!(a&&V$(i,t))){var o=t.mapDimension(i.dim),s={};return D(i.getViewLabels(),function(l){var u=i.scale.getRawOrdinalNumber(l.tickValue);s[u]=1}),function(l){return!s.hasOwnProperty(t.get(o,l))}}}}function V$(r,t){var e=r.getExtent(),n=Math.abs(e[1]-e[0])/r.scale.count();isNaN(n)&&(n=0);for(var a=t.count(),i=Math.max(1,Math.round(a/5)),o=0;on)return!1;return!0}function B$(r,t){return isNaN(r)||isNaN(t)}function z$(r){for(var t=r.length/2;t>0&&B$(r[t*2-2],r[t*2-1]);t--);return t-1}function cT(r,t){return[r[t*2],r[t*2+1]]}function F$(r,t,e){for(var n=r.length/2,a=e==="x"?0:1,i,o,s=0,l=-1,u=0;u